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
76df79075d0fdfb310a99f0805ccae253d439ee2
game/player.py
game/player.py
#!/usr/bin/env python from abc import ABCMeta, abstractmethod from game.gameboard import GameBoard class Player(object): __metaclass__ = ABCMeta def __init__(self, color): self._color = color.lower() def color(self): return self._color def is_winner(self, board): if board.gam...
#!/usr/bin/env python from abc import ABCMeta, abstractmethod from game.gameboard import GameBoard class Player(object): __metaclass__ = ABCMeta def __init__(self, color): self._color = color.lower() def color(self): return self._color def is_winner(self, board): return board...
Replace the particular boolean returns with a boolean expression on is_winner
Replace the particular boolean returns with a boolean expression on is_winner
Python
apache-2.0
apojomovsky/cuatro_en_linea,apojomovsky/cuatro_en_linea
425152f3c65b6c58065cde9ccbcebd360289ec8c
files_and_folders.py
files_and_folders.py
import os def files_and_folders(dir_path='.'): files = [] folders = [] for filename in sorted(os.listdir(dir_path)): if os.path.isdir(os.path.join(dir_path, filename)): folders.append(filename) else: files.append(filename) return tuple(files), tuple(folders)
import os # improvement liberally borrowed from: # https://forum.omz-software.com/topic/2784/feature-request-pythonista-built-in-file-picker def files_and_folders(dir_path='.'): '''Return a dict containing a sorted tuple of files and a sorted tuple of folders''' f_and_f = os.listdir(dir_path) folders...
Cut number of lines in half
Cut number of lines in half @The-Penultimate-Defenestrator use of sets is a nice optimization! # improvement liberally borrowed from: # https://forum.omz-software.com/topic/2784/feature-request-pythonista-built-in-file-picker
Python
apache-2.0
cclauss/Ten-lines-or-less
a1fdc8e14377d4fe619550e12ea359e5e9c60f0e
dear_astrid/test/helpers.py
dear_astrid/test/helpers.py
import datetime import os import sys import time from dear_astrid.constants import * from dear_astrid.constants import __all__ as _constants_all from dear_astrid.tzinfo import * from dear_astrid.tzinfo import __all__ as _tzinfo_all __all__ = [ 'dtu', 'u', 'timezone', ] + _constants_all + _tzinfo_all def dtu(*...
import datetime import os import sys import time from dear_astrid.constants import * from dear_astrid.constants import __all__ as _constants_all from dear_astrid.tzinfo import * from dear_astrid.tzinfo import __all__ as _tzinfo_all __all__ = [ 'dtu', 'u', 'timezone', ] + _constants_all + _tzinfo_all def dtu(*...
Simplify py 2/3 unicode string helper
Simplify py 2/3 unicode string helper
Python
mit
rwstauner/dear_astrid,rwstauner/dear_astrid
9c0f06228254a41bd68062feafaf8c8dbaddd06b
marshmallow/base.py
marshmallow/base.py
# -*- coding: utf-8 -*- '''Abstract base classes. These are necessary to avoid circular imports between core.py and fields.py. ''' class FieldABC(object): '''Abstract base class from which all Field classes inherit. ''' parent = None name = None def format(self, value): raise NotImplemen...
# -*- coding: utf-8 -*- '''Abstract base classes. These are necessary to avoid circular imports between core.py and fields.py. ''' import copy class FieldABC(object): '''Abstract base class from which all Field classes inherit. ''' parent = None name = None def format(self, value): raise...
Speed up deep copy of fields
Speed up deep copy of fields
Python
mit
dwieeb/marshmallow,VladimirPal/marshmallow,bartaelterman/marshmallow,mwstobo/marshmallow,maximkulkin/marshmallow,Tim-Erwin/marshmallow,jmcarp/marshmallow,0xDCA/marshmallow,daniloakamine/marshmallow,marshmallow-code/marshmallow,xLegoz/marshmallow,Bachmann1234/marshmallow,jmcarp/marshmallow,0xDCA/marshmallow,etataurov/ma...
50c734268a1380379d8d326a0860b2a9f2fade23
restpose/__init__.py
restpose/__init__.py
# -*- coding: utf-8 - # # This file is part of the restpose python module, released under the MIT # license. See the COPYING file for more information. """Python client for the RestPose search server. """ from .client import Server from .version import dev_release, version_info, __version__ from restkit import Reso...
# -*- coding: utf-8 - # # This file is part of the restpose python module, released under the MIT # license. See the COPYING file for more information. """Python client for the RestPose search server. """ from .client import Server from .errors import RestPoseError, CheckPointExpiredError from .version import dev_re...
Add RestPoseError and CheckPointExpiredError to top-level module symbols
Add RestPoseError and CheckPointExpiredError to top-level module symbols
Python
mit
restpose/restpose-py,restpose/restpose-py
746be2e5557f6626e984a679f1699c6a76fa932e
miner/block_test.py
miner/block_test.py
import unittest from block import Block class TestBlock(unittest.TestCase): class MerkleTreeMock: pass def test_init(self): prev = 0x123123 tree = TestBlock.MerkleTreeMock() time = 0x432432 bits = 0x1a44b9f2 b = Block(prev, tree, time, bits) self.ass...
import unittest from block import Block class TestBlock(unittest.TestCase): class MerkleTreeMock: pass def test_init(self): prev = bytes([123] * 32) tree = TestBlock.MerkleTreeMock() time = 432432 bits = 0x1a44b9f2 b = Block(prev, tree, time, bits) s...
Change block init test to pass bytes for hash
Change block init test to pass bytes for hash
Python
mit
DrPandemic/pickaxe,DrPandemic/pickaxe,DrPandemic/pickaxe,DrPandemic/pickaxe
65695bd7c4c7fcf3449358c0946e4584bb30a8ec
climate_data/migrations/0024_auto_20170623_0308.py
climate_data/migrations/0024_auto_20170623_0308.py
# -*- coding: utf-8 -*- # Generated by Django 1.10.6 on 2017-06-23 03:08 from __future__ import unicode_literals from django.db import migrations # noinspection PyUnusedLocal def add_station_sensor_link_to_reading(apps, schema_editor): # noinspection PyPep8Naming Reading = apps.get_model('climate_data', 'Rea...
# -*- coding: utf-8 -*- # Generated by Django 1.10.6 on 2017-06-23 03:08 from __future__ import unicode_literals from django.db import migrations import sys # noinspection PyUnusedLocal def add_station_sensor_link_to_reading(apps, schema_editor): # noinspection PyPep8Naming Reading = apps.get_model('climate...
Increase page size again in station-sensor link / reading migration, and add a percent indicator. Exclude any readings that have previously been fixed up by the migration.
Increase page size again in station-sensor link / reading migration, and add a percent indicator. Exclude any readings that have previously been fixed up by the migration.
Python
apache-2.0
qubs/data-centre,qubs/climate-data-api,qubs/data-centre,qubs/climate-data-api
5c353a23dfc2378c97fb4888db09e4a505bf8f8f
editorconfig/__init__.py
editorconfig/__init__.py
"""EditorConfig Python Core""" from versiontools import join_version VERSION = (0, 11, 0, "final") __all__ = ['get_properties', 'EditorConfigError', 'exceptions'] __version__ = join_version(VERSION) def get_properties(filename): """Locate and parse EditorConfig files for the given filename""" handler = Ed...
"""EditorConfig Python Core""" from editorconfig.versiontools import join_version VERSION = (0, 11, 0, "final") __all__ = ['get_properties', 'EditorConfigError', 'exceptions'] __version__ = join_version(VERSION) def get_properties(filename): """Locate and parse EditorConfig files for the given filename""" ...
Fix import style for Python3
Fix import style for Python3
Python
bsd-2-clause
johnfraney/editorconfig-vim,johnfraney/editorconfig-vim,johnfraney/editorconfig-vim,benjifisher/editorconfig-vim,VictorBjelkholm/editorconfig-vim,benjifisher/editorconfig-vim,benjifisher/editorconfig-vim,pocke/editorconfig-vim,VictorBjelkholm/editorconfig-vim,pocke/editorconfig-vim,VictorBjelkholm/editorconfig-vim,pock...
f6b7a4ec8aa72acfd93e7f85199b251e91ca4465
cherrypy/test/test_refleaks.py
cherrypy/test/test_refleaks.py
"""Tests for refleaks.""" from cherrypy._cpcompat import HTTPConnection, HTTPSConnection, ntob import threading import cherrypy data = object() from cherrypy.test import helper class ReferenceTests(helper.CPWebCase): @staticmethod def setup_server(): class Root: @cherrypy.expose ...
"""Tests for refleaks.""" import itertools from cherrypy._cpcompat import HTTPConnection, HTTPSConnection, ntob import threading import cherrypy data = object() from cherrypy.test import helper class ReferenceTests(helper.CPWebCase): @staticmethod def setup_server(): class Root: ...
Use a simple counter rather than appending booleans to a list and counting them.
Use a simple counter rather than appending booleans to a list and counting them.
Python
bsd-3-clause
cherrypy/cheroot,Safihre/cherrypy,cherrypy/cherrypy,cherrypy/cherrypy,Safihre/cherrypy
a5b3dd62e58dc23c03b7876ee99b757022413e94
billjobs/urls.py
billjobs/urls.py
from django.conf.urls import url, include from rest_framework.authtoken.views import obtain_auth_token from . import views urlpatterns = [ url(r'^generate_pdf/(?P<bill_id>\d+)$', views.generate_pdf, name='generate-pdf'), url(r'^user/$', views.UserAdmin.as_view(), name='user'), url(r'^user/(?P<pk>[0...
from django.conf.urls import url, include from rest_framework.authtoken.views import obtain_auth_token from . import views api_patterns = [ url(r'^auth/', include('rest_framework.urls', namespace='rest_framework')), url(r'^token-auth/', obtain_auth_token, name='api-token-auth'), url...
Move api auth url to api_patterns
Move api auth url to api_patterns
Python
mit
ioO/billjobs
71798ca99fe7245a578ea1d6ba367e485d9ad5f8
mvp/renderlayers.py
mvp/renderlayers.py
# -*- coding: utf-8 -*- from contextlib import contextmanager import maya.app.renderSetup.model.renderSetup as renderSetup from maya import cmds @contextmanager def enabled_render_layers(): old_layer = cmds.editRenderLayerGlobals(query=True, currentRenderLayer=True) try: rs = renderSetup.instance() ...
# -*- coding: utf-8 -*- from contextlib import contextmanager import maya.app.renderSetup.model.renderSetup as renderSetup from maya import cmds @contextmanager def enabled_render_layers(): old_layer = cmds.editRenderLayerGlobals( query=True, currentRenderLayer=True, ) try: rs = r...
Fix defaultRenderLayer was not included when blasting all layers.
Fix defaultRenderLayer was not included when blasting all layers.
Python
mit
danbradham/mvp
56528264cdc76dc1b00804b7f67908d3bb1b1b0e
flask_appconfig/docker.py
flask_appconfig/docker.py
#!/usr/bin/env python import os from six.moves.urllib_parse import urlparse def from_docker_envvars(config): # linked postgres database (link name 'pg' or 'postgres') if 'PG_PORT' in os.environ: pg_url = urlparse(os.environ['PG_PORT']) if not pg_url.scheme == 'tcp': raise ValueEr...
#!/usr/bin/env python import os from six.moves.urllib_parse import urlparse def from_docker_envvars(config): # linked postgres database (link name 'pg' or 'postgres') if 'PG_PORT' in os.environ: pg_url = urlparse(os.environ['PG_PORT']) if not pg_url.scheme == 'tcp': raise ValueEr...
Use correct database name instead of None when not supplied.
Use correct database name instead of None when not supplied.
Python
mit
mbr/flask-appconfig
07e7f5023958538933802f78c7bdd5d61f04a825
flocker/restapi/__init__.py
flocker/restapi/__init__.py
# Copyright Hybrid Logic Ltd. See LICENSE file for details. """ Infrastructure for publishing a REST HTTP API. """ from ._infrastructure import structured __all__ = ["structured"]
# Copyright Hybrid Logic Ltd. See LICENSE file for details. """ Infrastructure for publishing a REST HTTP API. """ from ._infrastructure import ( structured, EndpointResponse, userDocumentation, ) __all__ = ["structured", "EndpointResponse", "userDocumentation"]
Address review comment: Make more APIs public.
Address review comment: Make more APIs public.
Python
apache-2.0
moypray/flocker,adamtheturtle/flocker,Azulinho/flocker,agonzalezro/flocker,1d4Nf6/flocker,1d4Nf6/flocker,runcom/flocker,1d4Nf6/flocker,moypray/flocker,lukemarsden/flocker,LaynePeng/flocker,jml/flocker,moypray/flocker,adamtheturtle/flocker,lukemarsden/flocker,wallnerryan/flocker-profiles,mbrukman/flocker,jml/flocker,And...
b016fad5d55993b064a1c4d15fd281f439045491
gateway/camera/device.py
gateway/camera/device.py
from gateway import net class CameraDevice(object): def __init__(self, stream, address): self.resolution = None self.framerate = None self.__stream = stream self.__address = address def send(self, opcode, body=None): packet = net.encode_packet(opcode, body) yie...
from tornado import gen from gateway import net class CameraDevice(object): def __init__(self, stream, address): self.resolution = None self.framerate = None self.__stream = stream self.__address = address @gen.coroutine def send(self, opcode, body=None): packet =...
Fix CameraDevice's send method is not called
Fix CameraDevice's send method is not called Add send method @gen.coroutine decorator
Python
mit
walkover/auto-tracking-cctv-gateway
9f0c05eb9926dc5a9be6eb65bd71f7f1218e24e1
grano/logic/validation.py
grano/logic/validation.py
import re import colander from colander import Invalid from grano.logic.references import ProjectRef from grano.core import db from grano.model import Schema, Attribute FORBIDDEN = ['project', 'source', 'target', 'id', 'created_at', 'updated_at', 'author', 'author_id'] database_forbidden = colander.Function(lambda v...
import colander from colander import Invalid class All(object): """ Composite validator which succeeds if none of its subvalidators raises an :class:`colander.Invalid` exception""" def __init__(self, *validators): self.validators = validators def __call__(self, node, value): for valid...
Fix handling of All() exceptions.
Fix handling of All() exceptions.
Python
mit
4bic/grano,CodeForAfrica/grano,4bic-attic/grano,granoproject/grano
5ed5855efe09c92efbf93dab5eb0b37325072381
opps/api/__init__.py
opps/api/__init__.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from django.http import HttpResponse from django.contrib.auth import authenticate from piston.handler import BaseHandler as Handler from opps.api.models import ApiKey class BaseHandler(Handler): def read(self, request): base = self.model.objects if ...
#!/usr/bin/env python # -*- coding: utf-8 -*- from django.http import HttpResponse from django.contrib.auth import authenticate from piston.handler import BaseHandler as Handler from opps.api.models import ApiKey class BaseHandler(Handler): def read(self, request): base = self.model.objects if ...
Fix method get on ApiKeyAuthentication
Fix method get on ApiKeyAuthentication
Python
mit
jeanmask/opps,opps/opps,YACOWS/opps,opps/opps,opps/opps,jeanmask/opps,williamroot/opps,williamroot/opps,YACOWS/opps,jeanmask/opps,williamroot/opps,opps/opps,YACOWS/opps,williamroot/opps,YACOWS/opps,jeanmask/opps
66c0b220188499a5871ee1fbe5b79f0a57db4ec9
feder/tasks/filters.py
feder/tasks/filters.py
# -*- coding: utf-8 -*- from atom.filters import CrispyFilterMixin, AutocompleteChoiceFilter from django.utils.translation import ugettext_lazy as _ import django_filters from .models import Task class TaskFilter(CrispyFilterMixin, django_filters.FilterSet): case = AutocompleteChoiceFilter('CaseAutocomplete') ...
# -*- coding: utf-8 -*- from atom.filters import CrispyFilterMixin, AutocompleteChoiceFilter from django.utils.translation import ugettext_lazy as _ import django_filters from .models import Task class TaskFilter(CrispyFilterMixin, django_filters.FilterSet): case = AutocompleteChoiceFilter('CaseAutocomplete') ...
Add is_done filter for task
Add is_done filter for task
Python
mit
watchdogpolska/feder,watchdogpolska/feder,watchdogpolska/feder,watchdogpolska/feder
c55a42737a99104734a79e946304849258bfa44b
aplib/__init__.py
aplib/__init__.py
# Copyright (c) 2002-2011 IronPort Systems and Cisco Systems # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, mo...
# Copyright (c) 2002-2011 IronPort Systems and Cisco Systems # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, mo...
Allow aplib to be imported when coro is not installed.
Allow aplib to be imported when coro is not installed.
Python
mit
ironport/aplib,ironport/aplib
f4701ac73f884ef28e62bb35adc81330ce512171
goto_last_edit.py
goto_last_edit.py
import sublime_plugin # the last edited Region, keyed to View.id _last_edits = {} class RecordLastEdit(sublime_plugin.EventListener): def on_modified(self, view): _last_edits[view.id()] = view.sel()[0] class GotoLastEdit(sublime_plugin.TextCommand): def run(self, edit): last_edit = _last...
import sublime, sublime_plugin LAST_EDITS_SETTING = 'last_edits' class RecordLastEdit(sublime_plugin.EventListener): def on_modified(self, view): last_edits = view.settings().get(LAST_EDITS_SETTING, {}) edit_position = view.sel()[0] last_edits[str(view.id())] = {'a': edit_position.a, '...
Return to original if cursor is already at least edit
Return to original if cursor is already at least edit
Python
mit
abrookins/GotoLastEdit
ebb0236d7c68883de7a4202df23e74becd943f29
hooks/pre_gen_project.py
hooks/pre_gen_project.py
project_slug = '{{ cookiecutter.project_slug }}' print('pre gen') if hasattr(project_slug, 'isidentifier'): assert project_slug.isidentifier(), 'Project slug should be valid Python identifier!'
project_slug = '{{ cookiecutter.project_slug }}' if hasattr(project_slug, 'isidentifier'): assert project_slug.isidentifier(), 'Project slug should be valid Python identifier!'
Fix a typo in the pre-generation hooks
Fix a typo in the pre-generation hooks
Python
bsd-3-clause
valerymelou/cookiecutter-django-gulp,valerymelou/cookiecutter-django-gulp,valerymelou/cookiecutter-django-gulp
5748265d5102ee69e928d65ff3d40779af120dac
count-inversions/count_inversions.py
count-inversions/count_inversions.py
from random import randint import sys def sort_and_count(arr): n = len(arr) if n == 1: return 0 else: first_half = arr[:n/2] second_half = arr[n/2:] return merge_and_count_split(sort_and_count(first_half), sort_and_count(second_half)) def merge_and_count_split(arr1, arr2): return 0 def main(arr_len): ...
from random import randint import sys def sort_and_count(arr): n = len(arr) if n == 1: return arr else: first_half = arr[:n/2] second_half = arr[n/2:] return merge_and_count_split(sort_and_count(first_half), sort_and_count(second_half)) def merge_and_count_split(arr1, arr2): i, j = 0, 0 result = [] ...
Implement merge component of merge_and_count_split
Implement merge component of merge_and_count_split The merging part of merge_and_count_split was is taken right out of merge-sort. A test revealed a mistake in merge_and_sort where 0 was returned instead of the array when the array has one element, so that was fixed.
Python
mit
timpel/stanford-algs,timpel/stanford-algs
2f26197d10a1c7cfc010074576c7e1a2c2a31e78
data_structures/bitorrent/torrent.py
data_structures/bitorrent/torrent.py
import hashlib import urllib import bencode class Torrent(object): def __init__(self, path): self.encoded = self._get_meta(path) self.decoded = bencode.bdecode(self.encoded) def _get_meta(self, path): with open(path) as f: return f.read() @property def hash(self): info_hash = hashlib...
import hashlib import urllib import bencode class Torrent(object): def __init__(self, path): self.encoded = self._get_meta(path) self.decoded = bencode.bdecode(self.encoded) def _get_meta(self, path): with open(path) as f: return f.read() def __getitem__(self, item): return self.decode...
Use __getitem__ to improve readbility
Use __getitem__ to improve readbility
Python
apache-2.0
vtemian/university_projects,vtemian/university_projects,vtemian/university_projects
9caa0aa6c8fddc8a21997cf4df88d407b1598412
keras_cv/__init__.py
keras_cv/__init__.py
# Copyright 2022 The KerasCV 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in ...
# Copyright 2022 The KerasCV 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in ...
Add export for models module
Add export for models module
Python
apache-2.0
keras-team/keras-cv,keras-team/keras-cv,keras-team/keras-cv
e7a8c76c1f8f07866a4b7ea55870dacb5c76ef90
face/tests/model_tests.py
face/tests/model_tests.py
from django.test import TestCase from functional_tests.factory import FaceFactory class Facetest(TestCase): def setUp(self): self.face = FaceFactory(title='Lokesh') def test_title_to_share_returns_meet_Lokesh__farmer_from_sivaganga_tamil_nadu(self): self.assertEqual(self.face.title_to_share,'...
from django.test import TestCase from functional_tests.factory import FaceFactory class Facetest(TestCase): def setUp(self): self.face = FaceFactory(title='Lokesh') def test_title_to_share_returns_meet_Lokesh__farmer_from_sivaganga_tamil_nadu(self): self.assertEqual(self.face.title_to_share,'...
Fix unit test for seo faces url
Fix unit test for seo faces url
Python
bsd-3-clause
PARINetwork/pari,PARINetwork/pari,PARINetwork/pari,PARINetwork/pari
8df691acaebffc343dac4535a64f8a809607558a
Demo/sgi/cd/cdaiff.py
Demo/sgi/cd/cdaiff.py
import sys import readcd import aiff import AL import CD Error = 'cdaiff.Error' def writeaudio(a, type, data): a.writesampsraw(data) def main(): if len(sys.argv) > 1: a = aiff.Aiff().init(sys.argv[1], 'w') else: a = aiff.Aiff().init('@', 'w') a.sampwidth = AL.SAMPLE_16 a.nchannels = AL.STEREO a.samprate = ...
import sys import readcd import aifc import AL import CD Error = 'cdaiff.Error' def writeaudio(a, type, data): a.writeframesraw(data) def main(): if len(sys.argv) > 1: a = aifc.open(sys.argv[1], 'w') else: a = aifc.open('@', 'w') a.setsampwidth(AL.SAMPLE_16) a.setnchannels(AL.STEREO) a.setframerate(AL.RATE...
Use module aifc instead of module aiff.
Use module aifc instead of module aiff.
Python
mit
sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator
b097675e5906f7b0e9c050110fea58e40491814b
music/api.py
music/api.py
from django.conf.urls.defaults import url from tastypie.resources import ModelResource from jmbo.api import ModelBaseResource from music.models import Track class TrackResource(ModelBaseResource): class Meta: queryset = Track.permitted.all() resource_name = 'track' ordering = ['last_pla...
from django.conf.urls.defaults import url from tastypie.resources import ModelResource from tastypie.constants import ALL from jmbo.api import ModelBaseResource from music.models import Track class TrackResource(ModelBaseResource): class Meta: queryset = Track.permitted.all() resource_name = 't...
Allow filtering and ordering on API
Allow filtering and ordering on API
Python
bsd-3-clause
praekelt/jmbo-music,praekelt/jmbo-music
61bfc62937176b580b8b6ae12a90c5b76b00d50d
libcloud/__init__.py
libcloud/__init__.py
# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # libcloud.org licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not...
# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # libcloud.org licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not...
Add version string to libcloud
Add version string to libcloud git-svn-id: 353d90d4d8d13dcb4e0402680a9155a727f61a5a@895867 13f79535-47bb-0310-9956-ffa450edef68
Python
apache-2.0
Kami/libcloud,jimbobhickville/libcloud,ClusterHQ/libcloud,apache/libcloud,DimensionDataCBUSydney/libcloud,curoverse/libcloud,smaffulli/libcloud,schaubl/libcloud,techhat/libcloud,DimensionDataCBUSydney/libcloud,cryptickp/libcloud,cloudControl/libcloud,supertom/libcloud,ZuluPro/libcloud,Verizon/libcloud,t-tran/libcloud,S...
372ff487c068da2b31cd25e550e8dcd7bd12d17d
openprocurement/tender/esco/adapters.py
openprocurement/tender/esco/adapters.py
# -*- coding: utf-8 -*- from openprocurement.tender.openeu.adapters import TenderAboveThresholdEUConfigurator from openprocurement.tender.esco.models import Tender class TenderESCOConfigurator(TenderAboveThresholdEUConfigurator): """ ESCO Tender configuration adapter """ name = "esco Tender configurator" ...
# -*- coding: utf-8 -*- from openprocurement.tender.openeu.adapters import TenderAboveThresholdEUConfigurator from openprocurement.tender.esco.models import Tender class TenderESCOConfigurator(TenderAboveThresholdEUConfigurator): """ ESCO Tender configuration adapter """ name = "esco Tender configurator" ...
Add awarding criteria field to configurator
Add awarding criteria field to configurator
Python
apache-2.0
openprocurement/openprocurement.tender.esco
50f577e63fe58531447dc0bc2eed80859d3aa1ad
ibmcnx/doc/DataSources.py
ibmcnx/doc/DataSources.py
###### # Check ExId (GUID) by Email through JDBC # # Author: Christoph Stoettner # Mail: christoph.stoettner@stoeps.de # Documentation: http://scripting101.stoeps.de # # Version: 2.0 # Date: 2014-06-04 # # License: Apache 2.0 # # Check ExId of a User in all Connections Appli...
###### # Check ExId (GUID) by Email through JDBC # # Author: Christoph Stoettner # Mail: christoph.stoettner@stoeps.de # Documentation: http://scripting101.stoeps.de # # Version: 2.0 # Date: 2014-06-04 # # License: Apache 2.0 # # Check ExId of a User in all Connections Appli...
Create script to save documentation to a file
4: Create script to save documentation to a file Task-Url: http://github.com/stoeps13/ibmcnx2/issues/issue/4
Python
apache-2.0
stoeps13/ibmcnx2,stoeps13/ibmcnx2
6d25dcdb5eaca6d0d0404b4104017a18076174f8
mass/utils.py
mass/utils.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Helper functions. """ # built-in modules import json # local modules from mass.input_handler import InputHandler from mass.scheduler.swf import config def submit(job, protocol=None, priority=1): """Submit mass job to SWF with specific priority. """ impo...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Helper functions. """ # built-in modules import json # local modules from mass.exception import UnsupportedScheduler from mass.input_handler import InputHandler from mass.scheduler.swf import config def submit(job, protocol=None, priority=1, scheduler='swf'): "...
Raise UnsupportedScheduler if specific scheduler for submit is not supported (Now just swf is supported).
Raise UnsupportedScheduler if specific scheduler for submit is not supported (Now just swf is supported).
Python
apache-2.0
KKBOX/mass,badboy99tw/mass,KKBOX/mass,badboy99tw/mass,badboy99tw/mass,KKBOX/mass
adb265a57baed6a94f83ba13f88342313ad78566
tests/adapter.py
tests/adapter.py
"""adapter Mock storage adapter class for unit tests """ class MockStorageAdapter: """Mock storage adapter class. Will be patched for testing purposes """ def store_entry(self, entry): """Mock store_entry""" pass def store_response(self, response): """Mock store_response"...
"""adapter Mock storage adapter class for unit tests """ class MockStorageAdapter: """Mock storage adapter class. Will be patched for testing purposes """ def store_entry(self, entry: dict): """Mock store_entry""" pass def store_response(self, response: dict): """Mock sto...
Add type annotations to MockStorageAdapter methods
Add type annotations to MockStorageAdapter methods
Python
mit
tjmcginnis/tmj
32126085f361489bb5c9c18972479b0c313c7d10
bash_runner/tasks.py
bash_runner/tasks.py
""" Cloudify plugin for running a simple bash script. Operations: start: Run a script """ from celery import task from cosmo.events import send_event as send_riemann_event from cloudify.utils import get_local_ip get_ip = get_local_ip send_event = send_riemann_event @task def start(__cloudify_id, port=8080, **...
""" Cloudify plugin for running a simple bash script. Operations: start: Run a script """ from celery import task from cosmo.events import send_event as send_riemann_event from cloudify.utils import get_local_ip get_ip = get_local_ip send_event = send_riemann_event @task def start(__cloudify_id, port=8080, **...
Send the output to a tmp file
Send the output to a tmp file
Python
apache-2.0
rantav/cosmo-plugin-bash-runner
637651e572d9bcd4049ad5351f7fde1869c6823a
onadata/libs/authentication.py
onadata/libs/authentication.py
from django.utils.translation import ugettext as _ from django_digest import HttpDigestAuthenticator from rest_framework.authentication import ( BaseAuthentication, get_authorization_header, BasicAuthentication) from rest_framework.exceptions import AuthenticationFailed class DigestAuthentication(BaseAuthenti...
from django.conf import settings from django.utils.translation import ugettext as _ from django_digest import HttpDigestAuthenticator from rest_framework.authentication import ( BaseAuthentication, get_authorization_header, BasicAuthentication) from rest_framework.exceptions import AuthenticationFailed class ...
Allow HTTP auth during tests
Allow HTTP auth during tests
Python
bsd-2-clause
kobotoolbox/kobocat,kobotoolbox/kobocat,kobotoolbox/kobocat,kobotoolbox/kobocat
c5096a3370ad9b4fff428580e1b3c0c7de1399ce
scripts/set_ports.py
scripts/set_ports.py
#!/usr/bin/env python -B from optparse import OptionParser import inspect import json import os def get_port_mappings(container): script_dir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) container_id = os.popen('cat %s/../containers/%s/host.id' % (script_dir, container)).read().strip...
#!/usr/bin/env python -B from optparse import OptionParser import inspect import json import os container_id=None def get_port_mappings(container): global container_id script_dir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) container_id = os.popen('cat %s/../containers/%s/host.id'...
Set container_id and ext_ip container serf tags.
Set container_id and ext_ip container serf tags.
Python
apache-2.0
johanatan/datt-metadatt,johanatan/datt-metadatt,dattlabs/datt-metadatt,johanatan/datt-metadatt,johanatan/datt-metadatt,dattlabs/datt-metadatt,dattlabs/datt-metadatt,dattlabs/datt-metadatt
aedabe987e6ce93d61ed7707f0ebdc874b60fa1b
libtmux/__about__.py
libtmux/__about__.py
__title__ = 'libtmux' __package_name__ = 'libtmux' __version__ = '0.8.1' __description__ = 'scripting library / orm for tmux' __email__ = 'tony@git-pull.com' __author__ = 'Tony Narlock' __github__ = 'https://github.com/tmux-python/libtmux' __pypi__ = 'https://pypi.org/project/libtmux/' __license__ = 'MIT' __copyright__...
__title__ = 'libtmux' __package_name__ = 'libtmux' __version__ = '0.8.1' __description__ = 'scripting library / orm for tmux' __email__ = 'tony@git-pull.com' __author__ = 'Tony Narlock' __github__ = 'https://github.com/tmux-python/libtmux' __docs__ = 'https://libtmux.git-pull.com' __tracker__ = 'https://github.com/tmux...
Add docs and issue tracker to metadata
Add docs and issue tracker to metadata
Python
bsd-3-clause
tony/libtmux
2de494810b73dd69c6b4bb87e87007291309d573
lightstep/util.py
lightstep/util.py
""" Utility functions """ import random import time from . import constants def _service_url_from_hostport(secure, host, port): """ Create an appropriate service URL given the parameters. `secure` should be a bool. """ if secure: protocol = 'https://' else: protocol = 'http://'...
""" Utility functions """ import random import time from . import constants def _service_url_from_hostport(secure, host, port): """ Create an appropriate service URL given the parameters. `secure` should be a bool. """ if secure: protocol = 'https://' else: protocol = 'http://'...
Fix _time_to_micros bug. It was calling time.time() when it should use its own argument.
Fix _time_to_micros bug. It was calling time.time() when it should use its own argument.
Python
mit
lightstephq/lightstep-tracer-python
7278f68b18f8cee3f9a78e1265df0994a23254bc
mamba/__init__.py
mamba/__init__.py
from mamba.loader import describe, context from mamba.hooks import before, after from mamba.decorators import skip __all__ = [describe, context, before, after, skip]
from mamba.loader import describe, context from mamba.hooks import before, after from mamba.decorators import skip __all__ = ['describe', 'context', 'before', 'after', 'skip']
Fix the import all mamba error
Fix the import all mamba error
Python
mit
nestorsalceda/mamba,markng/mamba,alejandrodob/mamba,dex4er/mamba,angelsanz/mamba,jaimegildesagredo/mamba,eferro/mamba
ec8d7181be646498717b8efa97dd6770d61f067a
test/viz/test_pca.py
test/viz/test_pca.py
def test_pca(): from sequana.viz.pca import PCA from sequana import sequana_data import pandas as pd data = sequana_data("test_pca.csv") df = pd.read_csv(data) df = df.set_index("Id") p = PCA(df, colors={ "A1": 'r', "A2": 'r', 'A3': 'r', "B1": 'b', "B2": 'b', 'B3': 'b'}) ...
import pytest @pytest.mark.timeout(10) def test_pca(): from sequana.viz.pca import PCA from sequana import sequana_data import pandas as pd data = sequana_data("test_pca.csv") df = pd.read_csv(data) df = df.set_index("Id") p = PCA(df, colors={ "A1": 'r', "A2": 'r', 'A3': 'r', ...
Set timeout on pca test
Set timeout on pca test
Python
bsd-3-clause
sequana/sequana,sequana/sequana,sequana/sequana,sequana/sequana,sequana/sequana
a7ece0bd59b63455d26efbc927df7dc5607ce55b
tests/test_player.py
tests/test_player.py
import unittest from pypoker import Player from pypoker import Table class PlayerTestCase(unittest.TestCase): ''' Tests for the Player class ''' def setUp(self): self.player = Player('usman', 1000, None) def test_player_initialization(self): self.assertEqual([self.player.player_name,...
import unittest from pypoker import Player from pypoker import Table class PlayerTestCase(unittest.TestCase): ''' Tests for the Player class ''' def setUp(self): self.player = Player('usman', 1000, None) self.table = Table(50,100,2,10,100,1000) self.table.add_player('bob',1000)...
Add unit tests for functions call and check and fold for module player
Add unit tests for functions call and check and fold for module player
Python
mit
ueg1990/pypoker
7bed531fcbc63de25572a6b02fb8b19bd066fa50
test_pearhash.py
test_pearhash.py
import unittest from pearhash import PearsonHasher class TestPearsonHasher(unittest.TestCase): def test_table_is_a_permutation_of_range_256(self): hasher = PearsonHasher(2) self.assertEqual(set(hasher.table), set(range(256)))
import unittest from pearhash import PearsonHasher class TestPearsonHasher(unittest.TestCase): def test_table_is_a_permutation_of_range_256(self): hasher = PearsonHasher(2) self.assertEqual(set(hasher.table), set(range(256))) def test_two_bytes(self): hasher = PearsonHasher(2) self.assertEqual(hasher.ha...
Add a few trivial tests
Add a few trivial tests
Python
mit
ze-phyr-us/pearhash
44de3c76421a2ed4917ac7f2c6798dec631650a8
spacy/tests/regression/test_issue834.py
spacy/tests/regression/test_issue834.py
# coding: utf-8 from __future__ import unicode_literals from io import StringIO import pytest word2vec_str = """, -0.046107 -0.035951 -0.560418 de -0.648927 -0.400976 -0.527124 . 0.113685 0.439990 -0.634510   -1.499184 -0.184280 -0.598371""" @pytest.mark.xfail def test_issue834(en_vocab): f = StringIO(word2vec_...
# coding: utf-8 from __future__ import unicode_literals word2vec_str = """, -0.046107 -0.035951 -0.560418 de -0.648927 -0.400976 -0.527124 . 0.113685 0.439990 -0.634510 \u00A0 -1.499184 -0.184280 -0.598371""" def test_issue834(en_vocab, text_file): """Test that no-break space (U+00A0) is detected as space by th...
Reformat test and use text_file fixture
Reformat test and use text_file fixture
Python
mit
spacy-io/spaCy,raphael0202/spaCy,explosion/spaCy,explosion/spaCy,oroszgy/spaCy.hu,honnibal/spaCy,banglakit/spaCy,spacy-io/spaCy,explosion/spaCy,aikramer2/spaCy,banglakit/spaCy,oroszgy/spaCy.hu,honnibal/spaCy,raphael0202/spaCy,Gregory-Howard/spaCy,banglakit/spaCy,aikramer2/spaCy,recognai/spaCy,spacy-io/spaCy,Gregory-How...
cdbb9e8bcffc4c5ba47791b81782df4a07273b6b
Lib/test/test_file.py
Lib/test/test_file.py
from test_support import TESTFN from UserList import UserList # verify writelines with instance sequence l = UserList(['1', '2']) f = open(TESTFN, 'wb') f.writelines(l) f.close() f = open(TESTFN, 'rb') buf = f.read() f.close() assert buf == '12' # verify writelines with integers f = open(TESTFN, 'wb') try: f.writ...
import os from test_support import TESTFN from UserList import UserList # verify writelines with instance sequence l = UserList(['1', '2']) f = open(TESTFN, 'wb') f.writelines(l) f.close() f = open(TESTFN, 'rb') buf = f.read() f.close() assert buf == '12' # verify writelines with integers f = open(TESTFN, 'wb') try:...
Clean up the temporary file when done with it.
Clean up the temporary file when done with it.
Python
mit
sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator
f89f24c22d2dd3c1bab59083397501238e2d0ba9
sputnik/core.py
sputnik/core.py
import requests import simplejson as json def getbaseurl(service='search', version='1', method='track', format='json'): """Returns the base URL for a Spotify Web API query""" baseurl = "http://ws.spotify.com/{0}/{1}/{2}.{3}" return baseurl.format(service, version, method, format) def sea...
import requests try: import simplejson as json except ImportError: import json def getbaseurl(service='search', version='1', method='track', format='json'): """Returns the base URL for a Spotify Web API query""" baseurl = "http://ws.spotify.com/{0}/{1}/{2}.{3}" return baseurl.forma...
Add json module as fallback for simplejson
Add json module as fallback for simplejson
Python
mit
iconpin/sputnik-python
2ba8beb54b6de9fbe68501fa71a878da1426e6cd
tests/conftest.py
tests/conftest.py
import os import pytest from mothership import create_app, settings from mothership import db as _db @pytest.fixture(scope='session') def app(request): app = create_app('mothership.settings.TestConfig') # Establish an application context before running the tests. ctx = app.app_context() ctx.push() ...
import os, sys import pytest """ So PYTHONPATH enviroment variable doesn't have to be set for pytest to find mothership module. """ curdir = os.path.dirname(os.path.realpath(__file__)) sys.path.insert(0, os.path.join(curdir,'..')) from mothership import create_app, settings from mothership import db as _db...
Allow tests to find mothership module
Allow tests to find mothership module
Python
mit
afl-mothership/afl-mothership,afl-mothership/afl-mothership,afl-mothership/afl-mothership,afl-mothership/afl-mothership
40ae333ab81ae1f4d93f3937306ddd12718b59a8
virtool/processes.py
virtool/processes.py
import virtool.db.processes FIRST_STEPS = { "delete_reference": "delete_indexes", "clone_reference": "copy_otus", "import_reference": "load_file", "remote_reference": "download", "update_remote_reference": "download", "update_software": "", "install_hmms": "" } class ProgressTracker: ...
import virtool.db.processes FIRST_STEPS = { "delete_reference": "delete_indexes", "clone_reference": "copy_otus", "import_reference": "load_file", "remote_reference": "download", "update_remote_reference": "download", "update_software": "download", "install_hmms": "download" } class Progr...
Make download first step for install_software process type
Make download first step for install_software process type
Python
mit
virtool/virtool,igboyes/virtool,virtool/virtool,igboyes/virtool
6ae84a6e098275cdaac8598695c97403dcb2092e
volttron/__init__.py
volttron/__init__.py
''' Copyright (c) 2013, Battelle Memorial Institute All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions ...
# This is a namespace package; do not add anything else to this file. from pkgutil import extend_path __path__ = extend_path(__path__, __name__)
Make volttron a namespace package.
Make volttron a namespace package.
Python
bsd-2-clause
schandrika/volttron,schandrika/volttron,schandrika/volttron,schandrika/volttron
7c12d7f8e5fcd4cc328e109e0bdde9e62b4706f7
parse_tweets.py
parse_tweets.py
# Requires pandas and matplotlib to be installed, e.g. # # `sudo apt-get install pandas-python` import json import re import pandas as pd import matplotlib.pyplot as plt tweets_data_path = './twitter_data.txt' tweets_data = [] tweets_file = open(tweets_data_path, "r") for line in tweets_file: try: t...
# Requires pandas and matplotlib to be installed, e.g. # # `sudo apt-get install pandas-python` import json import re import pandas as pd import matplotlib.pyplot as plt import sys tweets_data_path = './twitter_data.txt' tweets_data = [] tweets_file = open(tweets_data_path, "r") for line in tweets_file: try...
Add next part of parser, and fix errors in earlier part arising from incomplete data items
Add next part of parser, and fix errors in earlier part arising from incomplete data items
Python
mit
0x7df/twitter2pocket
9cfdb35fb1f645eda99d28085b093ee36dd14625
processors/closure_compiler.py
processors/closure_compiler.py
from collections import OrderedDict import os import StringIO from django.conf import settings from django.utils.encoding import smart_str from ..base import Processor from django.core.exceptions import ImproperlyConfigured class ClosureCompiler(Processor): def modify_expected_output_filenames(self, filenames): ...
from collections import OrderedDict import os import StringIO from django.conf import settings from django.utils.encoding import smart_str from ..base import Processor from django.core.exceptions import ImproperlyConfigured class ClosureCompiler(Processor): def modify_expected_output_filenames(self, filenames): ...
Use the ECMASCRIPT5_STRICT flag otherwise AngularJS dies
Use the ECMASCRIPT5_STRICT flag otherwise AngularJS dies
Python
bsd-2-clause
potatolondon/assetpipe
84342312ab663b1d7c9a9ac5e09811c2ed636fb4
site_scons/utils.py
site_scons/utils.py
import os import os.path from os.path import join as pjoin def download_file(source, target): return 'wget %s -O %s' % (source, target) def get_file_list(base_path, include_list = None, exclude_list = None): if not isinstance(include_list, (list, tuple)): include_list = [ include_list ] if not exclude_list...
import os import os.path import hashlib from os.path import join as pjoin def download_file(source, target): return 'wget %s -O %s' % (source, target) def get_file_list(base_path, include_list = None, exclude_list = None): if not isinstance(include_list, (list, tuple)): include_list = [ include_list ] if n...
Add some more utility functions.
Add some more utility functions.
Python
apache-2.0
cloudkick/cast,cloudkick/cast,cloudkick/cast,cloudkick/cast
38d2aceecf485e59af4e66be711d7d0f12086c06
twinsies/clock.py
twinsies/clock.py
from apscheduler.schedulers.blocking import BlockingScheduler from twinsies.twitter import (random_trend_query, fetch_tweets, dig_for_twins, update_status) from memory_profiler import profile sched = BlockingScheduler() @sched.scheduled_job('interval', minutes=16) @profile def twinsy_finder(fetch_size=10000): ...
from apscheduler.schedulers.blocking import BlockingScheduler from twinsies.twitter import (random_trend_query, fetch_tweets, dig_for_twins, update_status) from memory_profiler import profile sched = BlockingScheduler() @sched.scheduled_job('interval', minutes=16) @profile def twinsy_finder(fetch_size=10000): ...
Remove del fetched_tweets (now a generator)
Remove del fetched_tweets (now a generator)
Python
mit
kkwteh/twinyewest
caa96562fb65dfdedc37f6efc463701e8b22d410
zipview/views.py
zipview/views.py
import zipfile from django.views.generic import View from django.http import HttpResponse from django.core.files.base import ContentFile from django.utils.six import b class BaseZipView(View): """A base view to zip and stream several files.""" http_method_names = ['get'] zipfile_name = 'download.zip' ...
import zipfile from django.views.generic import View from django.http import HttpResponse from django.core.files.base import ContentFile class BaseZipView(View): """A base view to zip and stream several files.""" http_method_names = ['get'] zipfile_name = 'download.zip' def get_files(self): ...
Remove obsolete python2 unicode helpers
Remove obsolete python2 unicode helpers
Python
mit
thibault/django-zipview
fd819ff0ff1a7d73dd58f152d2c4be8aea18e2d3
rebulk/processors.py
rebulk/processors.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Processor functions """ def conflict_prefer_longer(matches): """ Remove shorter matches if they conflicts with longer ones :param matches: :type matches: rebulk.match.Matches :param context: :type context: :return: :rtype: list[rebulk....
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Processor functions """ def conflict_prefer_longer(matches): """ Remove shorter matches if they conflicts with longer ones :param matches: :type matches: rebulk.match.Matches :param context: :type context: :return: :rtype: list[rebulk....
Fix issue when a private match is found multiple times
Fix issue when a private match is found multiple times
Python
mit
Toilal/rebulk
7366e84afdc93b68278b64bc9ddfac08901cb032
python/peacock/tests/postprocessor_tab/gold/TestPostprocessorPluginManager_test_script.py
python/peacock/tests/postprocessor_tab/gold/TestPostprocessorPluginManager_test_script.py
#* This file is part of the MOOSE framework #* https://www.mooseframework.org #* #* All rights reserved, see COPYRIGHT for full restrictions #* https://github.com/idaholab/moose/blob/master/COPYRIGHT #* #* Licensed under LGPL 2.1, please see LICENSE for details #* https://www.gnu.org/licenses/lgpl-2.1.html """ python ...
""" python TestPostprocessorPluginManager_test_script.py """ import matplotlib.pyplot as plt import mooseutils # Create Figure and Axes figure = plt.figure(facecolor='white') axes0 = figure.add_subplot(111) axes1 = axes0.twinx() # Read Postprocessor Data data = mooseutils.PostprocessorReader('../input/white_elephant_...
Remove header from gold script file
Remove header from gold script file
Python
lgpl-2.1
milljm/moose,YaqiWang/moose,nuclear-wizard/moose,bwspenc/moose,sapitts/moose,idaholab/moose,idaholab/moose,jessecarterMOOSE/moose,permcody/moose,nuclear-wizard/moose,milljm/moose,lindsayad/moose,laagesen/moose,idaholab/moose,andrsd/moose,milljm/moose,SudiptaBiswas/moose,dschwen/moose,permcody/moose,lindsayad/moose,sapi...
ae5b93c4e12f732a8c56de80b39f227c90ef4809
polls/models.py
polls/models.py
from django.db import models class Question(models.Model): question_text = models.CharField(max_length=140) published_at = models.DateTimeField(auto_now_add=True) class Meta: get_latest_by = 'published_at' def __str__(self): return self.question_text class Choice(models.Model): ...
from django.db import models class Question(models.Model): question_text = models.CharField(max_length=140) published_at = models.DateTimeField(auto_now_add=True) class Meta: get_latest_by = 'published_at' ordering = ('-published_at',) def __str__(self): return self.question_...
Order questions by published date
Order questions by published date Closes #23
Python
mit
apiaryio/polls-api
10e3c7b8dbc4befa2533de1a07f1f7827b961f81
rejected/__init__.py
rejected/__init__.py
""" Rejected is a Python RabbitMQ Consumer Framework and Controller Daemon """ import logging # Add NullHandler to prevent logging warnings logging.getLogger(__name__).addHandler(logging.NullHandler()) from rejected.consumer import ( Consumer, ConsumerException, MessageException, ProcessingException,...
""" Rejected is a Python RabbitMQ Consumer Framework and Controller Daemon """ import logging # Add NullHandler to prevent logging warnings logging.getLogger(__name__).addHandler(logging.NullHandler()) from rejected.consumer import ( # noqa: E402 Consumer, ConsumerException, MessageException, Proces...
Fix noqa location, bump version
Fix noqa location, bump version
Python
bsd-3-clause
gmr/rejected,gmr/rejected
c9491f47e1fc98e0a6aadf9bf379f21112768332
platformio/builder/scripts/windows_x86.py
platformio/builder/scripts/windows_x86.py
# Copyright (C) Ivan Kravets <me@ikravets.com> # See LICENSE for details. """ Builder for Windows x86 """ from SCons.Script import AlwaysBuild, Default, DefaultEnvironment from platformio.util import get_systype env = DefaultEnvironment() env.Replace( SIZEPRINTCMD="size $SOURCES", PROGSUFFIX=".exe" ) ...
# Copyright (C) Ivan Kravets <me@ikravets.com> # See LICENSE for details. """ Builder for Windows x86 """ from SCons.Script import AlwaysBuild, Default, DefaultEnvironment from platformio.util import get_systype env = DefaultEnvironment() env.Replace( AR="$_MINGWPREFIX-ar", AS="$_MINGWPREFIX-as", ...
Add support for mingw-linux toolchains
Add support for mingw-linux toolchains
Python
apache-2.0
ZachMassia/platformio,platformio/platformio-core,mseroczynski/platformio,eiginn/platformio,valeros/platformio,mcanthony/platformio,platformio/platformio,dkuku/platformio,platformio/platformio-core,atyenoria/platformio,mplewis/platformio
a17933c7806634391137244e2c17327898187146
djstripe/__init__.py
djstripe/__init__.py
""" .. module:: djstripe. :synopsis: dj-stripe - Django + Stripe Made Easy """ from __future__ import absolute_import, division, print_function, unicode_literals import pkg_resources from . import checks # noqa: Register the checks __version__ = pkg_resources.require("dj-stripe")[0].version
""" .. module:: djstripe. :synopsis: dj-stripe - Django + Stripe Made Easy """ from __future__ import absolute_import, division, print_function, unicode_literals import pkg_resources import stripe from . import checks # noqa: Register the checks __version__ = pkg_resources.require("dj-stripe")[0].version # Se...
Set dj-stripe as stripe app info
Set dj-stripe as stripe app info https://stripe.com/docs/building-plugins#setappinfo
Python
mit
pydanny/dj-stripe,pydanny/dj-stripe,jleclanche/dj-stripe,dj-stripe/dj-stripe,kavdev/dj-stripe,jleclanche/dj-stripe,dj-stripe/dj-stripe,kavdev/dj-stripe
26d2e13945f4780ff74dfe99695be7045fb9ed39
piper/prop.py
piper/prop.py
import facter from collections import MutableMapping from piper.abc import DynamicItem class PropBase(DynamicItem): def __init__(self): super(PropBase, self).__init__(None) self._props = None @property def properties(self): """ Collect system properties and return a dicti...
import facter from collections import MutableMapping from piper.abc import DynamicItem class PropBase(DynamicItem): def __init__(self): super(PropBase, self).__init__(None) self._props = None @property def properties(self): """ Collect system properties and return a dicti...
Add PropBase.flatten() support for flattening lists
Add PropBase.flatten() support for flattening lists
Python
mit
thiderman/piper
6c7ca64fbd93ab52dfc1ba792fd314395483d651
piazza_api/piazza.py
piazza_api/piazza.py
class Piazza(object): """Unofficial Client for Piazza's Internal API""" def __init__(self): pass
from .rpc import PiazzaRPC class Piazza(object): """Unofficial Client for Piazza's Internal API""" def __init__(self): self._rpc_api = None def user_login(self, email=None, password=None): """Login with email, password and get back a session cookie :type email: str :para...
Add login methods to Piazza
feat(user): Add login methods to Piazza
Python
mit
hfaran/piazza-api,kwangkim/piazza-api
a2ee6106a6c98dae102cf14902c6b82f480e6cbe
python/main.py
python/main.py
import sys from enum import Enum class Furniture(Enum): bed = 1 couce = 2 desk = 3 chair = 4 tv = 5 table = 6 rug = 7 shelf = 8 f = open(sys.argv[1], 'r') print(f.read())
import sys from enum import Enum from furniture import * #class Furniture(Enum): # bed = 1 # couce = 2 # desk = 3 # chair = 4 # tv = 5 # table = 6 # rug = 7 # shelf = 8 f = open(sys.argv[1], 'r') print(f.read()) placeDesksAndChairs() placeCouchesTablesAndTv() placeBeds() placeShelves() place...
Add calls to furniture placement functions
Add calls to furniture placement functions
Python
apache-2.0
TheZoq2/VRHack,TheZoq2/VRHack,TheZoq2/VRHack,TheZoq2/VRHack
c7ed3e2a39c7de1120a33cd0253d9ac3bd9e7984
redcliff/cli.py
redcliff/cli.py
from sys import exit import argparse from .commands import dispatch from .config import get_config from .utils import merge def main(): parser = argparse.ArgumentParser() parser.add_argument('-u', '--base-url') parser.add_argument('-k', '--api-key') parser.add_argument('-C', '--config-file') par...
from sys import exit import argparse from .commands import dispatch, choices from .config import get_config from .utils import merge def main(): parser = argparse.ArgumentParser() parser.add_argument('-u', '--base-url', metavar='https://redmine.example.com', h...
Update main arguments parser config
Update main arguments parser config
Python
mit
dmedvinsky/redcliff
02ca88129430044f4202991358939d87f8c6da0b
simple-cipher/simple_cipher.py
simple-cipher/simple_cipher.py
import math import secrets from string import ascii_lowercase class Cipher(object): def __init__(self, key=None): if not key: key = self._random_key() if not key.isalpha() or not key.islower(): raise ValueError("Key must consist only of lowercase letters") self.key ...
import math import secrets from string import ascii_lowercase class Cipher(object): def __init__(self, key=None): if not key: key = self._random_key() if not key.isalpha() or not key.islower(): raise ValueError("Key must consist only of lowercase letters") self.key ...
Refactor to reuse the encode method for decoding
Refactor to reuse the encode method for decoding
Python
agpl-3.0
CubicComet/exercism-python-solutions
3a86ea268b7cb9f00968e7dcb228d6821dafda99
simple-cipher/simple_cipher.py
simple-cipher/simple_cipher.py
import math import secrets from string import ascii_lowercase class Cipher(object): def __init__(self, key=None): if not key: key = self._random_key() if not key.isalpha() or not key.islower(): raise ValueError("Key must consist only of lowercase letters") self.key ...
import math import secrets from string import ascii_lowercase class Cipher(object): def __init__(self, key=None): if not key: key = self._random_key() if not key.isalpha() or not key.islower(): raise ValueError("Key must consist only of lowercase letters") self.key ...
Refactor to reuse the encode method for decoding
Refactor to reuse the encode method for decoding
Python
agpl-3.0
CubicComet/exercism-python-solutions
16c9563a75792aba7ccc0d979f579d64dc0140c1
common_rg_bar.py
common_rg_bar.py
#!/usr/bin/env python3 ''' Given: 1. status code: (0 - OK, other value - BAD) 2. terminal window width shows red/green bar to visualize return code of previous command ''' import sys def main(): if len(sys.argv) >= 2: code = sys.argv[1] if code == 'x': col_char = '3' cols...
#!/usr/bin/env python3 ''' Given: 1. status code: (0 - OK, other value - BAD) 2. terminal window width 3. (optional) Text to display (without color) shows red/green bar to visualize return code of previous command ''' import sys def main(): if len(sys.argv) >= 2: code = sys.argv[1] if code == 'x...
Add optional text to display
Add optional text to display
Python
mit
kwadrat/rgb_tdd
ff391fc302b6d4e9fab0653522fa2fe47d8e8faa
beavy_modules/url_extractor/lib.py
beavy_modules/url_extractor/lib.py
import lassie from pyembed.core import PyEmbed from beavy.app import cache pyembed = PyEmbed() @cache.memoize() def extract_info(url): return lassie.fetch(url) @cache.memoize() def extract_oembed(url, **kwargs): return pyembed.embed('http://www.youtube.com/watch?v=_PEdPBEpQfY', **kwargs)
from pyembed.core import PyEmbed from beavy.app import cache from lassie import Lassie import re # lassie by default isn't extensive enough for us # configure it so that it is. from lassie.filters import FILTER_MAPS FILTER_MAPS['meta']['open_graph']['map'].update({ # general "og:type": "type", "og:site...
Configure Lassie for more information
Configure Lassie for more information
Python
mpl-2.0
beavyHQ/beavy,beavyHQ/beavy,beavyHQ/beavy,beavyHQ/beavy
c58b2dd49ad5c73d49b496025d13116da30b3b9a
examples/qm7_long.py
examples/qm7_long.py
import numpy from sklearn.linear_model import Ridge from sklearn.kernel_ridge import KernelRidge from sklearn.metrics import mean_absolute_error as MAE from molml.features import EncodedBond, Connectivity from utils import load_qm7 if __name__ == "__main__": # This is just boiler plate code to load the data ...
from sklearn.linear_model import Ridge from sklearn.kernel_ridge import KernelRidge from sklearn.metrics import mean_absolute_error as MAE from molml.features import EncodedBond, Connectivity, MultiFeature from utils import load_qm7 if __name__ == "__main__": # This is just boiler plate code to load the data ...
Change qm7 example to use MultiFeature
Change qm7 example to use MultiFeature
Python
mit
crcollins/molml
67c444fb3603c234916b790d3dded3625f0512e5
pivot/test/test_utils.py
pivot/test/test_utils.py
""" Tests utility scripts """ import os from django.test import TestCase, RequestFactory from django.test.utils import override_settings import pivot from pivot.utils import get_latest_term TEST_CSV_PATH = os.path.join(os.path.dirname(pivot.__file__), 'test', ...
""" Tests utility scripts """ import os from django.test import TestCase, RequestFactory from django.test.utils import override_settings import pivot from pivot.utils import get_latest_term TEST_CSV_PATH = os.path.join(os.path.dirname(pivot.__file__), 'test', ...
Rename test to something more descriptive.
Rename test to something more descriptive.
Python
apache-2.0
uw-it-aca/pivot,uw-it-aca/pivot,uw-it-aca/pivot,uw-it-aca/pivot,uw-it-aca/pivot
f7c03daa9ce803ec10e1c7cd9319840045f47663
ddsc_core/management/commands/export_pi_xml.py
ddsc_core/management/commands/export_pi_xml.py
import sys from django.core.management.base import BaseCommand import pandas as pd from tslib.readers import PiXmlReader from tslib.writers import PiXmlWriter from ddsc_core.models import Timeseries class Command(BaseCommand): args = "<pi.xml>" help = "help" def handle(self, *args, **options): ...
from optparse import make_option from django.core.management.base import BaseCommand import pandas as pd from tslib.readers import PiXmlReader from tslib.writers import PiXmlWriter from ddsc_core.models import Timeseries class Command(BaseCommand): args = "<pi.xml>" help = ( "Create pi.xml from a t...
Improve management command for exporting pi-xml
Improve management command for exporting pi-xml
Python
mit
ddsc/ddsc-core,ddsc/ddsc-core
afb398094e207fdd338a492dbbe9fca3f041e2c7
tests/test_postgres_processor.py
tests/test_postgres_processor.py
import pytest import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "api.api.settings") from . import utils from scrapi.linter.document import NormalizedDocument, RawDocument from scrapi.processing.postgres import PostgresProcessor, Document test_db = PostgresProcessor() NORMALIZED = NormalizedDocument(utils.RE...
import pytest import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "api.api.settings") from django.test import TestCase from scrapi.processing.postgres import PostgresProcessor, Document from . import utils from scrapi.linter.document import RawDocument test_db = PostgresProcessor() # NORMALIZED = NormalizedD...
Make this test a django test case
Make this test a django test case
Python
apache-2.0
erinspace/scrapi,CenterForOpenScience/scrapi,CenterForOpenScience/scrapi,erinspace/scrapi,felliott/scrapi,mehanig/scrapi,fabianvf/scrapi,fabianvf/scrapi,felliott/scrapi,mehanig/scrapi
5d59f800da9fb737cd87d47301793f750ca1cbdd
pysnow/exceptions.py
pysnow/exceptions.py
# -*- coding: utf-8 -*- class PysnowException(Exception): pass class InvalidUsage(PysnowException): pass class ResponseError(PysnowException): message = "<empty>" detail = "<empty>" def __init__(self, error): if "message" in error: self.message = error["message"] or self.m...
# -*- coding: utf-8 -*- class PysnowException(Exception): pass class InvalidUsage(PysnowException): pass class UnexpectedResponseFormat(PysnowException): pass class ResponseError(PysnowException): message = "<empty>" detail = "<empty>" def __init__(self, error): if "message" in ...
Add missing UnexpectedResponseFormat for backward compatability
Add missing UnexpectedResponseFormat for backward compatability Signed-off-by: Abhijeet Kasurde <6334fd0c217b1f2a15926284df229acde5b4fc3a@redhat.com>
Python
mit
rbw0/pysnow
6e32cfd9b2640b4f119a3a8e4138c883fd4bcef0
_tests/test_scikit_ci_addons.py
_tests/test_scikit_ci_addons.py
import ci_addons import os import pytest import subprocess from . import captured_lines def test_home(): expected_home = os.path.abspath(os.path.dirname(__file__) + '/..') assert ci_addons.home() == expected_home @pytest.mark.parametrize("addon", ['anyci/noop', 'anyci/noop.py']) def test_path(addon): ...
import ci_addons import os import pytest import subprocess from . import captured_lines def test_home(): expected_home = os.path.abspath(os.path.dirname(__file__) + '/..') assert ci_addons.home() == expected_home @pytest.mark.parametrize("addon", ['anyci/noop', 'anyci/noop.py']) def test_path(addon): ...
Fix failing tests on appveyor
ci: Fix failing tests on appveyor
Python
apache-2.0
scikit-build/scikit-ci-addons,scikit-build/scikit-ci-addons
43ab1500719665b44e3b4eca4def9002711c2ee8
githublist/parser.py
githublist/parser.py
import requests import collections API_URL = 'https://api.github.com/users/{}/repos' def main(user): return parse(request(user)) def request(user): return requests.get(url=API_URL.format(user)) def parse(response): repos = response.json() data = [] if repos is None: return None fo...
import requests import collections API_URL = 'https://api.github.com/users/{}/repos?per_page=100' def main(user): return parse(request(user)) def request(user): return requests.get(url=API_URL.format(user)) def parse(response): repos = response.json() data = [] if repos is None: retur...
Update api url for recent 100 instead of default 30
Update api url for recent 100 instead of default 30
Python
mit
kshvmdn/github-list,kshvmdn/github-list,kshvmdn/github-list
fdf0daefac50de71a8c4f80a9ef877669ebea48b
byceps/services/tourney/transfer/models.py
byceps/services/tourney/transfer/models.py
""" byceps.services.tourney.transfer.models ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2019 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from typing import NewType from uuid import UUID from attr import attrs TourneyCategoryID = NewType('TourneyCategoryID', UUID) Tourne...
""" byceps.services.tourney.transfer.models ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2019 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from dataclasses import dataclass from typing import NewType from uuid import UUID TourneyCategoryID = NewType('TourneyCategoryID', UUID...
Change tourney match transfer model from `attrs` to `dataclass`
Change tourney match transfer model from `attrs` to `dataclass`
Python
bsd-3-clause
homeworkprod/byceps,homeworkprod/byceps,m-ober/byceps,homeworkprod/byceps,m-ober/byceps,m-ober/byceps
50519406ac64766874ce9edf5cea69233461ffb2
tests/test_config.py
tests/test_config.py
# -*- coding: utf-8 -*- import pytest import uuid from s3keyring.s3 import S3Keyring @pytest.fixture def config(scope='module'): return S3Keyring(profile_name='test').config @pytest.yield_fixture def dummyparam(config, scope='module'): yield 'dummyparam' config.config.remove_option('default', 'dummypa...
# -*- coding: utf-8 -*- import pytest import uuid import tempfile import os from s3keyring.s3 import S3Keyring @pytest.fixture def config(scope='module'): return S3Keyring(profile_name='test').config @pytest.yield_fixture def dummyparam(config, scope='module'): yield 'dummyparam' config.config.remove_...
Test custom configuration file feature
Test custom configuration file feature
Python
mit
InnovativeTravel/s3-keyring
025927fa19bb96095a2ea1c53524945f1f9590ce
spur/results.py
spur/results.py
def result(return_code, output, stderr_output, allow_error=False): if allow_error or return_code == 0: return ExecutionResult(return_code, output, stderr_output) else: raise RunProcessError(return_code, output, stderr_output) class RunProcessError(RuntimeError): def __init__(self, return_c...
def result(return_code, output, stderr_output, allow_error=False): result = ExecutionResult(return_code, output, stderr_output) if allow_error or return_code == 0: return result else: raise result.to_error() class RunProcessError(RuntimeError): def __init__(self, return_code, output, s...
Move logic for creating RunProcessError to ExecutionResult.to_error
Move logic for creating RunProcessError to ExecutionResult.to_error
Python
bsd-2-clause
mwilliamson/spur.py
936db17eed36284917395a6a8272351dabbc8168
numpy/_array_api/_dtypes.py
numpy/_array_api/_dtypes.py
from .. import int8, int16, int32, int64, uint8, uint16, uint32, uint64, float32, float64 # Note: This name is changed from .. import bool_ as bool _all_dtypes = [int8, int16, int32, int64, uint8, uint16, uint32, uint64, float32, float64, bool] _boolean_dtypes = [bool] _floating_dtypes = [float32, float...
import numpy as np # Note: we use dtype objects instead of dtype classes. The spec does not # require any behavior on dtypes other than equality. int8 = np.dtype('int8') int16 = np.dtype('int16') int32 = np.dtype('int32') int64 = np.dtype('int64') uint8 = np.dtype('uint8') uint16 = np.dtype('uint16') uint32 = np.dtype...
Use dtype objects instead of classes in the array API
Use dtype objects instead of classes in the array API The array API does not require any methods or behaviors on dtype objects, other than that they be literals that can be compared for equality and passed to dtype keywords in functions. Since dtype objects are already used by the dtype attribute of ndarray, this make...
Python
mit
cupy/cupy,cupy/cupy,cupy/cupy,cupy/cupy
ffd4c52155acd7d04939e766ebe63171b580a2fa
src/__init__.py
src/__init__.py
import os import logging from kaa.base import ipc from client import * from server import * __all__ = [ 'connect' ] # connected client object _client = None def connect(epgdb, logfile='/tmp/kaa-epg.log', loglevel=logging.INFO): """ """ global _client # get server filename server = os.path.join(...
import os import logging from socket import gethostbyname, gethostname from kaa.base import ipc from client import * from server import * __all__ = [ 'connect', 'DEFAULT_EPG_PORT', 'GuideClient', 'GuideServer' ] # connected client object _client = None def connect(epgdb, address='127.0.0.1', logfile='/tmp/kaa-epg.l...
Add the ability to use inet socket as well.
Add the ability to use inet socket as well. git-svn-id: ffaf500d3baede20d2f41eac1d275ef07405e077@1236 a8f5125c-1e01-0410-8897-facf34644b8e
Python
lgpl-2.1
freevo/kaa-epg
9d960bfa74a09382839f9b671004bebaffe46611
reui/Screen.py
reui/Screen.py
""" A screen object contains a collection of boxes to be displayed on a physical display device. """ from pydispatch import dispatcher from reui import SGL_BOX_UPDATE from gaugette import bitmap class Screen: _boxes = [] _boxMap = {} _bitmap = None def __init__(self, width, height, display): ...
""" A screen object contains a collection of boxes to be displayed on a physical display device. """ from pydispatch import dispatcher from reui import SGL_BOX_UPDATE from gaugette import bitmap class Screen: _boxes = [] _boxMap = {} _bitmap = None def __init__(self, width, height, display): ...
Support for Box direct drawing to screen bitmap
Support for Box direct drawing to screen bitmap
Python
mit
mharriger/reui
0cf0f3de5879795fcd01b8d88bf11efb3362f530
script/echo.py
script/echo.py
#!/usr/bin/env python3 # -*- coding: ascii -*- # A small example bot for Instant. import sys import instabot NICKNAME = 'Echo' def post_cb(self, msg, meta): if msg['text'].startswith('!echo '): return msg['text'][6:] def main(): b = instabot.CmdlineBotBuilder(defnick=NICKNAME) b.make_parser(sy...
#!/usr/bin/env python3 # -*- coding: ascii -*- # A small example bot for Instant. import sys import instabot NICKNAME = 'Echo' def post_cb(self, msg, meta): if msg['text'].startswith('!echo '): return msg['text'][6:] def main(): b = instabot.CmdlineBotBuilder(defnick=NICKNAME) b.make_parser(sy...
Make example bot use keepalive
[Instabot] Make example bot use keepalive
Python
mit
CylonicRaider/Instant,CylonicRaider/Instant,CylonicRaider/Instant,CylonicRaider/Instant,CylonicRaider/Instant
d90d35063f1a79916c20d32d3634842dd59798f1
api/tests/conftest.py
api/tests/conftest.py
import pytest @pytest.fixture(scope='module') def app(): from api import app return app
import pytest @pytest.fixture(scope='module') def app(): from api import app, db app.config['TESTING'] = True db.create_all() return app
Fix default fixture to initialize database
Fix default fixture to initialize database
Python
mit
Demotivated/loadstone
6decf1f48e56832b1d15d3fc26d92f9813d13353
coop_cms/moves.py
coop_cms/moves.py
# -*- coding: utf-8 -*- """ coop_cms manage compatibilty with django and python versions """ import sys from django import VERSION if sys.version_info[0] < 3: # Python 2 from HTMLParser import HTMLParser from StringIO import StringIO else: # Python 3 from html.parser import HTMLParser from i...
# -*- coding: utf-8 -*- """ coop_cms manage compatibilty with django and python versions """ import sys from django import VERSION if sys.version_info[0] < 3: # Python 2 from StringIO import StringIO from HTMLParser import HTMLParser else: # Python 3 from io import BytesIO as StringIO ...
Fix HTMLParser compatibility in Python 3
Fix HTMLParser compatibility in Python 3
Python
bsd-3-clause
ljean/coop_cms,ljean/coop_cms,ljean/coop_cms
9931bd1d5459a983717fb502826f3cca87225b96
src/qrl/services/grpcHelper.py
src/qrl/services/grpcHelper.py
# coding=utf-8 # Distributed under the MIT software license, see the accompanying # file LICENSE or http://www.opensource.org/licenses/mit-license.php. from grpc import StatusCode from qrl.core.misc import logger class GrpcExceptionWrapper(object): def __init__(self, response_type, state_code=StatusCode.UNKNOWN):...
# coding=utf-8 # Distributed under the MIT software license, see the accompanying # file LICENSE or http://www.opensource.org/licenses/mit-license.php. from grpc import StatusCode from qrl.core.misc import logger class GrpcExceptionWrapper(object): def __init__(self, response_type, state_code=StatusCode.UNKNOWN):...
Set code to Invalid argument for ValueErrors
Set code to Invalid argument for ValueErrors
Python
mit
jleni/QRL,cyyber/QRL,jleni/QRL,cyyber/QRL,theQRL/QRL,randomshinichi/QRL,theQRL/QRL,randomshinichi/QRL
ce1fb05e825e9be7589fd12ab798cae760b605e6
sheldon/bot.py
sheldon/bot.py
# -*- coding: utf-8 -*- """ @author: Seva Zhidkov @contact: zhidkovseva@gmail.com @license: The MIT license Copyright (C) 2015 """ from sheldon.exceptions import * from sheldon.manager import * from sheldon.config import * from sheldon.adapter import * from sheldon.storage import * class Sheldon: """ Main ...
# -*- coding: utf-8 -*- """ @author: Seva Zhidkov @contact: zhidkovseva@gmail.com @license: The MIT license Copyright (C) 2015 """ from sheldon.exceptions import * from sheldon.manager import * from sheldon.config import * from sheldon.adapter import * from sheldon.storage import * class Sheldon: """ Main ...
Add basic load config function
Add basic load config function
Python
mit
lises/sheldon
0f114a144268bb611ff00db9917756a8c02f84b9
project/api/signals.py
project/api/signals.py
# Django # Third-Party from django.db.models.signals import pre_delete from django.db.models.signals import pre_save from django.dispatch import receiver from django.conf import settings # Local from .models import User from .tasks import delete_account @receiver(pre_delete, sender=User) def user_pre_delete(sender, ...
# Django # Third-Party from django.db.models.signals import pre_delete from django.db.models.signals import pre_save from django.dispatch import receiver from django.conf import settings # Local from .models import User from .tasks import activate_user from .tasks import delete_account @receiver(pre_delete, sender=U...
Connect person to user account
Connect person to user account
Python
bsd-2-clause
barberscore/barberscore-api,dbinetti/barberscore-django,barberscore/barberscore-api,barberscore/barberscore-api,dbinetti/barberscore-django,dbinetti/barberscore,dbinetti/barberscore,barberscore/barberscore-api
9568efceab48f87ed8302ec4f9bad4b15aac4c5a
tests/test_action.py
tests/test_action.py
import smtplib import unittest from unittest import mock from action import PrintAction, EmailAction @mock.patch("builtins.print") class PrintActionTest(unittest.TestCase): def test_executing_action_prints_message(self, mock_print): action = PrintAction() action.execute("GOOG > $10") mock...
import smtplib import unittest from unittest import mock from action import PrintAction, EmailAction @mock.patch("builtins.print") class PrintActionTest(unittest.TestCase): def test_executing_action_prints_message(self, mock_print): action = PrintAction() action.execute("GOOG > $10") mock...
Add test to check if connection is closed after email is sent.
Add test to check if connection is closed after email is sent.
Python
mit
bsmukasa/stock_alerter
5bc4aa60be988abc98ba76ca4b790b259d75af37
capstone/rl/policies/egreedy.py
capstone/rl/policies/egreedy.py
import random from .greedy import Greedy from .random_policy import RandomPolicy from ..policy import Policy from ...utils import check_random_state class EGreedy(Policy): def __init__(self, e, random_state=None): self.e = e self.greedy = Greedy() self.rand = RandomPolicy() self.r...
from .greedy import Greedy from .random_policy import RandomPolicy from ..policy import Policy from ...utils import check_random_state class EGreedy(Policy): def __init__(self, e, random_state=None): self.e = e self.greedy = Greedy() self.rand = RandomPolicy() self.random_state = ...
Fix EGreedy policy call order
Fix EGreedy policy call order
Python
mit
davidrobles/mlnd-capstone-code
30dbda17bfa3b52dc2aace6eba6b8c1e4b3f7542
robot-name/robot_name.py
robot-name/robot_name.py
# File: robot_name.py # Purpose: Write a program that manages robot factory settings. # Programmer: Amal Shehu # Course: Exercism # Date: Friday 30 September 2016, 03:00 PM import string import random class Robot(): """Robot facory settings""" def __init__(self): self.name = "...
# File: robot_name.py # Purpose: Write a program that manages robot factory settings. # Programmer: Amal Shehu # Course: Exercism # Date: Friday 30 September 2016, 03:00 PM import string import random class Robot(): """Robot facory settings""" def __init__(self): self.name = "...
Add methord to generate unique robot name
Add methord to generate unique robot name
Python
mit
amalshehu/exercism-python
3134af98d2fcf88752170d628400a7e863d4c959
was/artists/views.py
was/artists/views.py
from django.shortcuts import render, get_object_or_404 from django.views.generic.edit import CreateView, UpdateView from .form import CreateArtistForm, UpdateArtistForm, Artists from django.contrib.auth.forms import AuthenticationForm from django.contrib.auth import login, logout from django.http import HttpResponseRed...
from django.shortcuts import render, get_object_or_404 from django.views.generic.edit import CreateView, UpdateView from .form import CreateArtistForm, UpdateArtistForm, Artists, User from django.contrib.auth.forms import AuthenticationForm from django.contrib.auth import login, logout from django.http import HttpRespo...
Create update view (extends UpdateView generic view). Define get_initail in order to pre populate two custom fields username and email which are not in the original Artists model.
Create update view (extends UpdateView generic view). Define get_initail in order to pre populate two custom fields username and email which are not in the original Artists model.
Python
mit
KeserOner/where-artists-share,KeserOner/where-artists-share
533d1462949ab451674d91dd7730957cb2252dde
susumutakuan.py
susumutakuan.py
import discord import asyncio import os import signal import sys from subprocess import run #Set up Client State CLIENT_TOKEN=os.environ['TOKEN'] #Create Discord client client = discord.Client() #Handle shutdown gracefully def sigterm_handler(signum, frame): print('Logging out...', flush=True) raise Keyboar...
import discord import asyncio import os import signal import sys from subprocess import run #Set up Client State CLIENT_TOKEN=os.environ['TOKEN'] #Create Discord client client = discord.Client() #Handle shutdown gracefully def sigterm_handler(signum, frame): print('Logging out...', flush=True) raise Keyboar...
Add universal_newlines paramter to run call
Add universal_newlines paramter to run call
Python
mit
gryffon/SusumuTakuan,gryffon/SusumuTakuan
1d14d28d68278330855e585a859484019d8c3e43
cacivicdata/manage.py
cacivicdata/manage.py
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings") sys.path.append(os.path.dirname(os.path.dirname(__file__))) from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "cacivicdata.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
Change back to django default
Change back to django default
Python
mit
california-civic-data-coalition/django-calaccess-downloads-website,california-civic-data-coalition/django-calaccess-downloads-website,california-civic-data-coalition/django-calaccess-downloads-website
5632daecf9c5f271eeba0f9948d88f44d6a070d0
irclogview/models.py
irclogview/models.py
from django.db import models from picklefield.fields import PickledObjectField class Channel(models.Model): name = models.SlugField(max_length=50, unique=True) updated = models.DateTimeField(auto_now=True) def __unicode__(self): return u'#%s' % self.name class Log(models.Model): channel = mo...
from django.db import models from picklefield.fields import PickledObjectField from . import utils class Channel(models.Model): name = models.SlugField(max_length=50, unique=True) updated = models.DateTimeField(auto_now=True) def __unicode__(self): return u'#%s' % self.name class Log(models.Mod...
Add function to get content in list of dicts format
Add function to get content in list of dicts format
Python
agpl-3.0
BlankOn/irclogview,fajran/irclogview,fajran/irclogview,BlankOn/irclogview
4228082c9c94b3e17e6b00fc1e380841d5389dc5
crawler/models.py
crawler/models.py
from django.db import models # Create your models here. class Data_Ingredient(models.Model): """"Class used to Store Ingredients of the recipes found in the crawling process""" Ingredient = models.CharField(max_length=1000) Recipe = models.CharField(max_length=500) Group = models.CharField(max_len...
from django.db import models class Data_Ingredient(models.Model): """"Class used to Store Ingredients of the recipes found in the crawling process""" Ingredient = models.CharField(max_length=1000) Recipe = models.CharField(max_length=500) Group = models.CharField(max_length=500, default='Ingredientes...
Remove not needed comment line
Remove not needed comment line
Python
mit
lucasgr7/silverplate,lucasgr7/silverplate,lucasgr7/silverplate
22b6785695967a43ab9d187db60c201c3dc4a8e1
peerinst/admin.py
peerinst/admin.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.contrib import admin from django.utils.translation import ugettext_lazy as _ from . import models @admin.register(models.Question) class QuestionAdmin(admin.ModelAdmin): fieldsets = [ (None, {'fields': ['title']}), (_('Mai...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.contrib import admin from django.utils.translation import ugettext_lazy as _ from . import models @admin.register(models.Question) class QuestionAdmin(admin.ModelAdmin): fieldsets = [ (None, {'fields': ['title']}), (_('Mai...
Use radio buttons for the style and number of answers.
Use radio buttons for the style and number of answers.
Python
agpl-3.0
open-craft/dalite-ng,open-craft/dalite-ng,open-craft/dalite-ng
0f53ec6ddeb236bee78794e8d1ed156ad182bc07
projects/forms.py
projects/forms.py
from django import forms from .models import Project class ProjectForm(forms.ModelForm): def __init__(self, *args, **kwargs): self.user = kwargs.pop('user') super(ProjectForm, self).__init__(*args, **kwargs) def save(self, *args, **kwargs): instance = super(ProjectForm, self).save(co...
from django import forms from .models import Project class ProjectForm(forms.ModelForm): def __init__(self, *args, **kwargs): self.user = kwargs.pop('user') super(ProjectForm, self).__init__(*args, **kwargs) def save(self, *args, **kwargs): instance = super(ProjectForm, self).save(co...
Add status to project form
Add status to project form
Python
mit
Hackfmi/Diaphanum,Hackfmi/Diaphanum
84e9532487615f684abbed17d6821ae7bc84c9be
virtualfish/loader/__init__.py
virtualfish/loader/__init__.py
from __future__ import print_function import os import sys import pkg_resources def load(plugins=()): try: version = pkg_resources.get_distribution("virtualfish").version commands = ["set -g VIRTUALFISH_VERSION {}".format(version)] except pkg_resources.DistributionNotFound: commands = ...
from __future__ import print_function import os import sys import pkg_resources def load(plugins=(), full_install=True): try: version = pkg_resources.get_distribution("virtualfish").version commands = ["set -g VIRTUALFISH_VERSION {}".format(version)] except pkg_resources.DistributionNotFound: ...
Add kwarg to load function to distinguish from full install
Add kwarg to load function to distinguish from full install The load function is used for a full install and thus always adds general configuration lines to the loader file, but we don't want that for plugin installation.
Python
mit
adambrenecki/virtualfish,adambrenecki/virtualfish
0db1575341ae37644f2ce43c0a89e4baf83f8d87
filebrowser/urls.py
filebrowser/urls.py
from django.conf.urls.defaults import * from django.views.generic.simple import redirect_to urlpatterns = patterns('', # filebrowser urls url(r'^browse/$', redirect_to, {'url': '/admin/business/photo/?_popup=1', 'permanent': True}, name="fb_browse"), url(r'^mkdir/', 'filebrowser.views.mkdir', name="fb...
from django.conf.urls.defaults import * from django.views.generic.simple import redirect_to urlpatterns = patterns('', # filebrowser urls url(r'^browse/$', 'filebrowser.views.browse', name="fb_browse"), url(r'^mkdir/', 'filebrowser.views.mkdir', name="fb_mkdir"), url(r'^upload/', 'filebrowser.view...
Remove redirect again, it's somehow causing the JS issue and it won't work for other media types
Remove redirect again, it's somehow causing the JS issue and it won't work for other media types
Python
bsd-3-clause
django-wodnas/django-filebrowser-no-grappelli,django-wodnas/django-filebrowser-no-grappelli,sandow-digital/django-filebrowser-no-grappelli-sandow,sandow-digital/django-filebrowser-no-grappelli-sandow,sandow-digital/django-filebrowser-no-grappelli-sandow,django-wodnas/django-filebrowser-no-grappelli
353098b81b0e281d5d78e820dd91c3f360d6e585
ibmcnx/test/test.py
ibmcnx/test/test.py
import loadFunction.py loadFilesService() FilesPolicyService.browse( "title", "true", 1, 25 )
import ibmcnx.test.loadFunction loadFilesService() FilesPolicyService.browse( "title", "true", 1, 25 )
Customize scripts to work with menu
Customize scripts to work with menu
Python
apache-2.0
stoeps13/ibmcnx2,stoeps13/ibmcnx2
e1721a515520a85fbbfae112eb63f877de33e7c9
caffe2/python/test_util.py
caffe2/python/test_util.py
## @package test_util # Module caffe2.python.test_util from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np from caffe2.python import workspace import unittest def rand_array(*dims): # np.random.ran...
## @package test_util # Module caffe2.python.test_util from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np from caffe2.python import core, workspace import unittest def rand_array(*dims): # np.rand...
Clear the operator default engines before running operator tests
Clear the operator default engines before running operator tests Reviewed By: akyrola Differential Revision: D5729024 fbshipit-source-id: f2850d5cf53537b22298b39a07f64dfcc2753c75
Python
apache-2.0
sf-wind/caffe2,xzturn/caffe2,pietern/caffe2,davinwang/caffe2,pietern/caffe2,davinwang/caffe2,sf-wind/caffe2,Yangqing/caffe2,sf-wind/caffe2,Yangqing/caffe2,davinwang/caffe2,xzturn/caffe2,sf-wind/caffe2,sf-wind/caffe2,xzturn/caffe2,pietern/caffe2,pietern/caffe2,xzturn/caffe2,Yangqing/caffe2,Yangqing/caffe2,caffe2/caffe2,...
7ec5786efbdb20b9cbcdf0b4f1b583a7e07e0644
comrade/core/tests.py
comrade/core/tests.py
from nose.tools import ok_, eq_ import unittest import models class SimpleModel(models.ComradeBaseModel): def __unicode__(self): return u'This is a unicode string' class TestBaseModel(unittest.TestCase): def setUp(self): super(TestBaseModel, self).setUp() self.obj = SimpleModel() ...
from nose.tools import ok_, eq_ import unittest import models def check_direct_to_template(prefix, pattern): from django import test from django.core.urlresolvers import reverse client = test.Client() response = client.get(reverse(prefix + ':' + pattern.name)) template_name = pattern.default_args[...
Add test helper method for checking direct_to_template views.
Add test helper method for checking direct_to_template views.
Python
mit
bueda/django-comrade
4f3cfe6e990c932d7f86dbd0cf8ae762407278b0
nucleus/base/urls.py
nucleus/base/urls.py
from django.conf.urls import url from nucleus.base import views urlpatterns = ( url(r'^/?$', views.home, name='base.home'), )
from django.conf.urls import url from django.views.generic import RedirectView urlpatterns = ( url(r'^/?$', RedirectView.as_view(url='/rna/', permanent=True), name='base.home'), )
Change root URL to redirect to /rna/
Change root URL to redirect to /rna/
Python
mpl-2.0
mozilla/nucleus,mozilla/nucleus,mozilla/nucleus,mozilla/nucleus