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
6bb7ba60f217f8a6dd470d084a664cbf65274681
software/src/services/open_rocket_simulations.py
software/src/services/open_rocket_simulations.py
import os JAR_FILE = "/openrocket.jar" os.environ['CLASSPATH'] = os.getcwd() + JAR_FILE from jnius import autoclass class OpenRocketSimulations: ENTRY_CLASS = 'TeamRocket' ROCKET_FILE = 'teamrocket.ork' def __init__(self): TeamRocket = autoclass(self.ENTRY_CLASS) self.simulation_file = Tea...
import os from jnius import autoclass JAR_FILE = "/openrocket.jar" os.environ['CLASSPATH'] = os.getcwd() + JAR_FILE class OpenRocketSimulations: ENTRY_CLASS = 'TeamRocket' ROCKET_FILE = 'teamrocket.ork' def __init__(self): TeamRocket = autoclass(self.ENTRY_CLASS) self.simulation_file = Te...
Move specificication of classpath below imports
Move specificication of classpath below imports
Python
mit
team-rocket-vuw/base-station,team-rocket-vuw/base-station,team-rocket-vuw/base-station,team-rocket-vuw/base-station
8a36070c76d1552e2d2e61c1e5c47202cc28b329
basket/news/backends/common.py
basket/news/backends/common.py
from functools import wraps from time import time from django_statsd.clients import statsd class UnauthorizedException(Exception): """Failure to log into the email server.""" pass class NewsletterException(Exception): """Error when trying to talk to the the email server.""" def __init__(self, msg=...
from functools import wraps from time import time from django_statsd.clients import statsd class UnauthorizedException(Exception): """Failure to log into the email server.""" pass class NewsletterException(Exception): """Error when trying to talk to the the email server.""" def __init__(self, msg=...
Refactor the timing decorator to be less confusing
Refactor the timing decorator to be less confusing Also means that we don't have to ignore a flake8 error.
Python
mpl-2.0
glogiotatidis/basket,glogiotatidis/basket,glogiotatidis/basket
775cd06b3e99cef9c777a907fc69c5c20380bb75
raspicam/camera.py
raspicam/camera.py
import logging # import picamera # import picamera.array from abc import ABCMeta, abstractmethod import cv2 LOG = logging.getLogger(__name__) class Camera(metaclass=ABCMeta): @abstractmethod def frame_generator(self): raise NotImplementedError('Not yet implemented') class USBCam(Camera): def...
import logging # import picamera # import picamera.array from abc import ABCMeta, abstractmethod import cv2 LOG = logging.getLogger(__name__) class Camera(metaclass=ABCMeta): @abstractmethod def frame_generator(self): raise NotImplementedError('Not yet implemented') class USBCam(Camera): def...
Allow the USB index to be modified
Allow the USB index to be modified
Python
mit
exhuma/raspicam,exhuma/raspicam,exhuma/raspicam
c2562a8cb2e3d5d3f68604c32d4db7e62422e7a5
pathvalidate/_symbol.py
pathvalidate/_symbol.py
# encoding: utf-8 """ .. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com> """ from __future__ import absolute_import, unicode_literals import re from ._common import _preprocess, ascii_symbol_list, is_not_null_string, unprintable_ascii_char_list from .error import InvalidCharError __RE_SYMBOL = re.com...
# encoding: utf-8 """ .. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com> """ from __future__ import absolute_import, unicode_literals import re from ._common import _preprocess, ascii_symbol_list, unprintable_ascii_char_list from .error import InvalidCharError __RE_SYMBOL = re.compile( "[{}]".for...
Remove an import that no longer used
Remove an import that no longer used
Python
mit
thombashi/pathvalidate
0e8a5e56c53fed0834982a50b96be0a587a18fcb
pebble_tool/__init__.py
pebble_tool/__init__.py
from __future__ import absolute_import, print_function __author__ = 'katharine' import argparse import logging import sys from .commands.base import register_children from .commands import repl, install, screenshot, logs, account, timeline from .commands.sdk import build, emulator, create, convert from .exceptions im...
from __future__ import absolute_import, print_function __author__ = 'katharine' import argparse import logging import sys from .commands.base import register_children from .commands.sdk import build, create from .commands import install, logs, screenshot, timeline, account, repl from .commands.sdk import convert, emu...
Change the order of the subcommands.
Change the order of the subcommands.
Python
mit
gregoiresage/pebble-tool,pebble/pebble-tool,pebble/pebble-tool,pebble/pebble-tool,gregoiresage/pebble-tool,gregoiresage/pebble-tool,pebble/pebble-tool,gregoiresage/pebble-tool
7f3c086a953f91ec7f351c56a4f07f38dc0b9eb3
exampleCourse/elements/course_element/course_element.py
exampleCourse/elements/course_element/course_element.py
import random import chevron def get_dependencies(element_html, element_index, data): return { 'styles': ['course_element.css'], 'scripts': ['course_element.js'] } def render(element_html, element_index, data): html_params = { 'number': random.random() } with open('course_element.musta...
import random import chevron def render(element_html, element_index, data): html_params = { 'number': random.random() } with open('course_element.mustache','r') as f: return chevron.render(f, html_params).strip()
Remove unneeded get_dependencies from course element
Remove unneeded get_dependencies from course element
Python
agpl-3.0
parasgithub/PrairieLearn,rbessick5/PrairieLearn,tbretl/PrairieLearn,parasgithub/PrairieLearn,jakebailey/PrairieLearn,parasgithub/PrairieLearn,tbretl/PrairieLearn,rbessick5/PrairieLearn,jakebailey/PrairieLearn,jakebailey/PrairieLearn,rbessick5/PrairieLearn,mwest1066/PrairieLearn,mwest1066/PrairieLearn,parasgithub/Prairi...
cebfd01451a2d78217bffd171ab3bcccbabf895f
zerodb/collective/indexing/indexer.py
zerodb/collective/indexing/indexer.py
from zope.interface import implements #from Products.Archetypes.CatalogMultiplex import CatalogMultiplex #from Products.CMFCore.CMFCatalogAware import CMFCatalogAware from zerodb.collective.indexing.interfaces import IIndexQueueProcessor # container to hold references to the original and "monkeyed" indexing methods #...
from zope.interface import implements from zerodb.collective.indexing.interfaces import IIndexQueueProcessor class IPortalCatalogQueueProcessor(IIndexQueueProcessor): """ an index queue processor for the standard portal catalog via the `CatalogMultiplex` and `CMFCatalogAware` mixin classes """ class Por...
Remove unused code for monkeyed methods
Remove unused code for monkeyed methods
Python
agpl-3.0
zero-db/zerodb,zerodb/zerodb,zero-db/zerodb,zerodb/zerodb
7f8e5913f493582608712244cbfff0bf8d658c51
chainerrl/misc/batch_states.py
chainerrl/misc/batch_states.py
import chainer def batch_states(states, xp, phi): """The default method for making batch of observations. Args: states (list): list of observations from an environment. xp (module): numpy or cupy phi (callable): Feature extractor applied to observations Return: the object...
import chainer def batch_states(states, xp, phi): """The default method for making batch of observations. Args: states (list): list of observations from an environment. xp (module): numpy or cupy phi (callable): Feature extractor applied to observations Return: the object...
Fix error of chainer v3 on chainer.cuda.cupy
Fix error of chainer v3 on chainer.cuda.cupy
Python
mit
toslunar/chainerrl,toslunar/chainerrl
46aaaf4f2323ec25e87f88ed80435288a31d5b13
armstrong/apps/series/admin.py
armstrong/apps/series/admin.py
from django.contrib import admin from django.contrib.contenttypes import generic from . import models class SeriesNodeInline(generic.GenericTabularInline): model = models.SeriesNode class SeriesAdmin(admin.ModelAdmin): model = models.Series inlines = [ SeriesNodeInline, ] prepopulated...
from django.contrib import admin from . import models class SeriesAdmin(admin.ModelAdmin): model = models.Series prepopulated_fields = { 'slug': ('title', ), } admin.site.register(models.Series, SeriesAdmin)
Remove all of the SeriesNode inline stuff (doesn't work yet)
Remove all of the SeriesNode inline stuff (doesn't work yet)
Python
apache-2.0
armstrong/armstrong.apps.series,armstrong/armstrong.apps.series
509cbe502cf9a6fd6c0f86469656c01edd4eddf1
pygments/styles/igor.py
pygments/styles/igor.py
from pygments.style import Style from pygments.token import Keyword, Name, Comment, String, Error, \ Number, Operator, Generic class IgorStyle(Style): default_style = "" styles = { Comment: 'italic #FF0000', Keyword: '#0000FF', Name.Function: ...
from pygments.style import Style from pygments.token import Keyword, Name, Comment, String, Error, \ Number, Operator, Generic class IgorStyle(Style): """ Pygments version of the official colors for Igor Pro procedures. """ default_style = "" styles = { Comment: 'italic ...
Add class comment and a custom color for the decorator
Add class comment and a custom color for the decorator
Python
bsd-2-clause
aswinpj/Pygments,aswinpj/Pygments,aswinpj/Pygments,aswinpj/Pygments,aswinpj/Pygments,aswinpj/Pygments,aswinpj/Pygments,aswinpj/Pygments,aswinpj/Pygments,aswinpj/Pygments,aswinpj/Pygments,aswinpj/Pygments,aswinpj/Pygments,aswinpj/Pygments,aswinpj/Pygments,aswinpj/Pygments,aswinpj/Pygments,aswinpj/Pygments,aswinpj/Pygmen...
f5e547ed6ef642406e771a62796d738649c31a0f
python/FlatFileTable.py
python/FlatFileTable.py
#!/usr/bin/env python import sys, itertools def record_generator(filename, sep="\t", skip_n_lines=0): """Given a file with field headers on the first line and records on subsequent lines, generates a dictionary for each line keyed by the header fields""" fin = open(filename) for i in range(skip_n_lines):...
#!/usr/bin/env python import sys, itertools def record_generator(filename, sep="\t", skip_n_lines=0, skip_until_regex_line=""): """Given a file with field headers on the first line and records on subsequent lines, generates a dictionary for each line keyed by the header fields""" fin = open(filename) if ...
Add ability for flat file table parsing module to skip ahead to first occurence of a regular expression (use case: consistently parsing DepthOfCoverage output for histogram section of file across file format changes)
Add ability for flat file table parsing module to skip ahead to first occurence of a regular expression (use case: consistently parsing DepthOfCoverage output for histogram section of file across file format changes) git-svn-id: 4561c0a8f080806b19201efb9525134c00b76d40@2377 348d0f76-0448-11de-a6fe-93d51630548a
Python
mit
iontorrent/Torrent-Variant-Caller-stable,iontorrent/Torrent-Variant-Caller-stable,iontorrent/Torrent-Variant-Caller-stable,iontorrent/Torrent-Variant-Caller-stable,iontorrent/Torrent-Variant-Caller-stable,iontorrent/Torrent-Variant-Caller-stable,iontorrent/Torrent-Variant-Caller-stable,iontorrent/Torrent-Variant-Caller...
20079bf375149bb0e8646a2d81dd800028f49faa
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 render...
Add more comments in capturist dashboard view
Add more comments in capturist dashboard view
Python
mit
erikiado/jp2_online,erikiado/jp2_online,erikiado/jp2_online
7e59dc64a8aad61016c0b3f05b467bc4a3e02f57
deploy/generate_production_ini.py
deploy/generate_production_ini.py
""" Based on environment variables make a config file (production.ini) for our encoded application. """ import os from dcicutils.deployment_utils import Deployer class FourfrontDeployer(Deployer): _MY_DIR = os.path.dirname(__file__) TEMPLATE_DIR = os.path.join(_MY_DIR, "ini_files") PYPROJECT_FILE_NAME = ...
""" Based on environment variables make a config file (production.ini) for our encoded application. """ import os from dcicutils.deployment_utils import BasicLegacyFourfrontIniFileManager class FourfrontDeployer(BasicLegacyFourfrontIniFileManager): _MY_DIR = os.path.dirname(__file__) TEMPLATE_DIR = os.path.j...
Adjust deployer to use new class name for ini file management.
Adjust deployer to use new class name for ini file management.
Python
mit
4dn-dcic/fourfront,4dn-dcic/fourfront,4dn-dcic/fourfront,4dn-dcic/fourfront
e19357bb91bf3ae794dc239340c68b82d569698d
bmi_ilamb/config.py
bmi_ilamb/config.py
"""Reads and parses a configuration file for the ILAMB BMI.""" from os.path import join import yaml ilamb_root_key = 'ilamb_root' model_root_key = 'model_root' class Configuration(object): def __init__(self): self._config = {} def load(self, filename): with open(filename, 'r') as fp: ...
"""Reads and parses a configuration file for the ILAMB BMI.""" from os.path import join import yaml ilamb_root_key = 'ilamb_root' model_root_key = 'model_root' models_key = 'models' class Configuration(object): def __init__(self): self._config = {} def load(self, filename): with open(file...
Add ability to pass 'models' argument to ilamb-run
Add ability to pass 'models' argument to ilamb-run This is needed to benchmark individual models instead of all the models under the directory specified by `model_root`.
Python
mit
permamodel/bmi-ilamb
14b8bbf0cade0c31d521e42c6c4c9b57bafaa12a
src/amber/hokuyo/hokuyo.py
src/amber/hokuyo/hokuyo.py
import logging.config import sys import os import time import serial from amber.hokuyo.hokuyo_common import HokuyoController from amber.tools import serial_port, config __author__ = 'paoolo' LOGGER_NAME = 'AmberPipes' pwd = os.path.dirname(os.path.abspath(__file__)) config.add_config_ini('%s/hokuyo.ini' % pwd) log...
import logging.config import sys import os import serial from amber.hokuyo.hokuyo_common import HokuyoController from amber.tools import serial_port, config __author__ = 'paoolo' LOGGER_NAME = 'AmberPipes' pwd = os.path.dirname(os.path.abspath(__file__)) config.add_config_ini('%s/hokuyo.ini' % pwd) logging.config....
Remove auto start in loop with "while True".
Remove auto start in loop with "while True".
Python
mit
showmen15/testEEE,showmen15/testEEE
7021aabe068f546adb10b8f741656c423cb7eb5a
sale_order_mass_confirm/wizard/sale_order_confirm.py
sale_order_mass_confirm/wizard/sale_order_confirm.py
# -*- coding: utf-8 -*- # Copyright 2016 Onestein (<http://www.onestein.eu>) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import api, models class SaleOrderConfirmWizard(models.TransientModel): _name = "sale.order.confirm.wizard" _description = "Wizard - Sale Order Confirm" ...
# -*- coding: utf-8 -*- # Copyright 2016 Onestein (<http://www.onestein.eu>) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import models, api class SaleOrderConfirmWizard(models.TransientModel): _name = "sale.order.confirm.wizard" _description = "Wizard - Sale Order Confirm" ...
Make sure only Sales Order with state in 'draft' or 'sent' is confirmed (state 'canceled' will not be confirmed)
Make sure only Sales Order with state in 'draft' or 'sent' is confirmed (state 'canceled' will not be confirmed)
Python
agpl-3.0
VitalPet/addons-onestein,VitalPet/addons-onestein,VitalPet/addons-onestein
027fa84469e17ec4b8948de095388ec94ea40941
api/identifiers/serializers.py
api/identifiers/serializers.py
from rest_framework import serializers as ser from api.base.serializers import JSONAPISerializer, LinksField, RelationshipField class IdentifierSerializer(JSONAPISerializer): category = ser.CharField(read_only=True) identifier = LinksField({ 'self': 'get_identifiers' }) referent = Relations...
from rest_framework import serializers as ser from api.base.serializers import JSONAPISerializer, LinksField, RelationshipField class IdentifierSerializer(JSONAPISerializer): category = ser.CharField(read_only=True) identifier = LinksField({ 'self': 'get_identifiers' }) referent = Relations...
Add get_absolute_url method to serializer
Add get_absolute_url method to serializer
Python
apache-2.0
abought/osf.io,mfraezz/osf.io,leb2dg/osf.io,cwisecarver/osf.io,DanielSBrown/osf.io,rdhyee/osf.io,CenterForOpenScience/osf.io,mluke93/osf.io,saradbowman/osf.io,cwisecarver/osf.io,aaxelb/osf.io,felliott/osf.io,CenterForOpenScience/osf.io,kwierman/osf.io,brianjgeiger/osf.io,wearpants/osf.io,samchrisinger/osf.io,chennan47/...
47d612aeab78e8d3ceeee8a4769485356194ab81
lib/custom_data/character_loader_new.py
lib/custom_data/character_loader_new.py
"""This module loads character data from XML files and stores them in CharacterData objects that can be read by the game engine. Attributes: CHARACTER_LIST_PATH (String): The filepath for the text file which lists the paths to all of the characters' XML files. Each path is separated by a new-line. ...
"""This module loads character data from XML files and stores them in CharacterData objects that can be read by the game engine. Attributes: CHARACTER_LIST_PATH (String): The filepath for the text file which lists the paths to all of the characters' XML files. Each path is separated by a new-line. ...
Add constant for Character Schema file path
Add constant for Character Schema file path
Python
unlicense
MarquisLP/Sidewalk-Champion
84acc00a3f6d09b4212b6728667af583b45e5a99
km_api/know_me/tests/serializers/test_profile_list_serializer.py
km_api/know_me/tests/serializers/test_profile_list_serializer.py
from know_me import serializers def test_serialize(profile_factory): """ Test serializing a profile. """ profile = profile_factory() serializer = serializers.ProfileListSerializer(profile) expected = { 'id': profile.id, 'name': profile.name, 'quote': profile.quote, ...
from know_me import serializers def test_create(user_factory): """ Saving a serializer containing valid data should create a new profile. """ user = user_factory() data = { 'name': 'John', 'quote': "Hi, I'm John", 'welcome_message': 'This is my profile.', } ser...
Add test for creating profile from serializer.
Add test for creating profile from serializer.
Python
apache-2.0
knowmetools/km-api,knowmetools/km-api,knowmetools/km-api,knowmetools/km-api
8c1b7f8a5a7403e464938aa0aa6876557ec6a2b3
daphne/server.py
daphne/server.py
import time from twisted.internet import reactor from .http_protocol import HTTPFactory class Server(object): def __init__(self, channel_layer, host="127.0.0.1", port=8000): self.channel_layer = channel_layer self.host = host self.port = port def run(self): self.factory = HT...
import time from twisted.internet import reactor from .http_protocol import HTTPFactory class Server(object): def __init__(self, channel_layer, host="127.0.0.1", port=8000, signal_handlers=True): self.channel_layer = channel_layer self.host = host self.port = port self.signal_han...
Allow signal handlers to be disabled to run in subthread
Allow signal handlers to be disabled to run in subthread
Python
bsd-3-clause
django/daphne,maikhoepfel/daphne
ea7919f5e8de2d045df91fdda892757613ef3211
qregexeditor/api/quick_ref.py
qregexeditor/api/quick_ref.py
""" Contains the quick reference widget """ import re from pyqode.qt import QtWidgets from .forms import quick_ref_ui class QuickRefWidget(QtWidgets.QWidget): def __init__(self, parent=None): super(QuickRefWidget, self).__init__(parent) self.ui = quick_ref_ui.Ui_Form() self.ui.setupUi(self)...
""" Contains the quick reference widget """ import re from pyqode.qt import QtCore, QtWidgets from .forms import quick_ref_ui class QuickRefWidget(QtWidgets.QWidget): def __init__(self, parent=None): super(QuickRefWidget, self).__init__(parent) self.ui = quick_ref_ui.Ui_Form() self.ui.setup...
Add zoom in/out action to the text edit context menu
Add zoom in/out action to the text edit context menu Fix #5
Python
mit
ColinDuquesnoy/QRegexEditor
65b4c081c3a66ccd373062f8e7c1d63295c8d8d1
cache_relation/app_settings.py
cache_relation/app_settings.py
# Default cache duration CACHE_RELATION_DEFAULT_DURATION = 60 * 60 * 24 * 3
from django.conf import settings # Default cache timeout CACHE_RELATION_DEFAULT_DURATION = getattr( settings, 'CACHE_RELATION_DEFAULT_DURATION', 60 * 60 * 24 * 3, )
Allow global settings to override.
Allow global settings to override. Signed-off-by: Chris Lamb <711c73f64afdce07b7e38039a96d2224209e9a6c@playfire.com>
Python
bsd-3-clause
thread/django-sensible-caching,playfire/django-cache-toolbox,lamby/django-sensible-caching,lamby/django-cache-toolbox
3f9e0d0b013a2b652aefdacc6c1b54e26af48b16
cmain.py
cmain.py
# # This program provides a simple command line to query population statistics. # Author: Tay Joc Cing # Date: 20 Mar 2015 # import sys import os from country import Country from datamanager import DataManager from dispatcher import CommandDispatcher from constants import * sys.path.append(os.getcwd() + "/classes") ...
# # This program provides a simple command line to query population statistics. # Author: Tay Joc Cing # Date: 20 Mar 2015 # import sys import os sys.path.append(os.getcwd() + "/classes") from country import Country from datamanager import DataManager from dispatcher import CommandDispatcher from constants import * ...
Store current working directory before import
Store current working directory before import
Python
mit
joccing/geoguru,joccing/geoguru
f33bdb8313180fd3f2eae3d8b30783755c7d33ec
euler/solutions/solution_14.py
euler/solutions/solution_14.py
"""Longest Collatz sequence The following iterative sequence is defined for the set of positive integers: n -> n/2 (n is even) n -> 3n + 1 (n is odd) Using the rule above and starting with 13, we generate the following sequence: 13 -> 40 -> 20 -> 10 -> 5 -> 16 -> 8 -> 4 -> 2 -> 1 It can be seen that this sequence ...
"""Longest Collatz sequence The following iterative sequence is defined for the set of positive integers: n -> n/2 (n is even) n -> 3n + 1 (n is odd) Using the rule above and starting with 13, we generate the following sequence: 13 -> 40 -> 20 -> 10 -> 5 -> 16 -> 8 -> 4 -> 2 -> 1 It can be seen that this sequence ...
Add solution for problem 14
Add solution for problem 14 Longest Collatz sequence
Python
mit
rlucioni/project-euler
ef5d3c61acdb7538b4338351b8902802142e03a5
tests/bindings/python/scoring/test-scoring_result.py
tests/bindings/python/scoring/test-scoring_result.py
#!@PYTHON_EXECUTABLE@ #ckwg +5 # Copyright 2011 by Kitware, Inc. All Rights Reserved. Please refer to # KITWARE_LICENSE.TXT for licensing information, or contact General Counsel, # Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065. def test_import(): try: import vistk.pipeline_util.bake except...
#!@PYTHON_EXECUTABLE@ #ckwg +5 # Copyright 2011 by Kitware, Inc. All Rights Reserved. Please refer to # KITWARE_LICENSE.TXT for licensing information, or contact General Counsel, # Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065. def test_import(): try: import vistk.pipeline_util.bake except...
Update Python tests for scoring_result
Update Python tests for scoring_result
Python
bsd-3-clause
linus-sherrill/sprokit,mathstuf/sprokit,Kitware/sprokit,linus-sherrill/sprokit,linus-sherrill/sprokit,linus-sherrill/sprokit,mathstuf/sprokit,Kitware/sprokit,Kitware/sprokit,Kitware/sprokit,mathstuf/sprokit,mathstuf/sprokit
498ab0c125180ba89987e797d0094adc02019a8f
numba/exttypes/utils.py
numba/exttypes/utils.py
"Simple utilities related to extension types" #------------------------------------------------------------------------ # Read state from extension types #------------------------------------------------------------------------ def get_attributes_type(py_class): "Return the attribute struct type of the numba exte...
"Simple utilities related to extension types" #------------------------------------------------------------------------ # Read state from extension types #------------------------------------------------------------------------ def get_attributes_type(py_class): "Return the attribute struct type of the numba exte...
Add utility to iterate over numba base classes
Add utility to iterate over numba base classes
Python
bsd-2-clause
jriehl/numba,cpcloud/numba,stuartarchibald/numba,numba/numba,GaZ3ll3/numba,pombredanne/numba,ssarangi/numba,ssarangi/numba,gdementen/numba,gmarkall/numba,pitrou/numba,shiquanwang/numba,numba/numba,seibert/numba,pitrou/numba,sklam/numba,shiquanwang/numba,IntelLabs/numba,seibert/numba,gdementen/numba,stuartarchibald/numb...
096b9783dc5b8cb0f2a20e9d3d57d3897d36b1ff
charat2/views/guides.py
charat2/views/guides.py
import requests def user_guide(): r = requests.get("http://drweeaboo.net/msparp/userguide/duplicateguide.html") return r.text, r.status_code
import requests def user_guide(): r = requests.get("http://drweeaboo.net/msparp/userguide/duplicateguide.html") r.encoding = r.apparent_encoding return r.text, r.status_code
Set response encoding based on apparent_encoding.
Set response encoding based on apparent_encoding. Headers from drweeaboo.net incorrectly tell us ISO-8859-1.
Python
agpl-3.0
MSPARP/newparp,MSPARP/newparp,MSPARP/newparp
c6d1a929f747a76155cce73e8c1a1358cf226f0e
constellation_forms/__init__.py
constellation_forms/__init__.py
""" This module implements a forms system for creating, filling out, and reviewing forms within an organization. This module depends on the Constellation-Base package to function correctly. Constellation Forms implements a fairly standard forms system. The core features include: * Click-to-Build form builder * Form...
""" This module implements a forms system for creating, filling out, and reviewing forms within an organization. This module depends on the Constellation-Base package to function correctly. Constellation Forms implements a fairly standard forms system. The core features include: * Click-to-Build form builder * Form...
Update front page of the documentation
Update front page of the documentation
Python
isc
ConstellationApps/Forms,ConstellationApps/Forms,ConstellationApps/Forms
25724a77c19828d52cba2b6e682c67f67013590e
django_counter_field/fields.py
django_counter_field/fields.py
from django.db import models class CounterField(models.IntegerField): def __init__(self, *args, **kwargs): kwargs['default'] = kwargs.get('default', 0) super(CounterField, self).__init__(*args, **kwargs) try: from south.modelsinspector import add_introspection_rules except ImportError: pa...
from django.db import models class CounterField(models.IntegerField): """ CounterField wraps the standard django IntegerField. It exists primarily to allow for easy validation of counter fields. The default value of a counter field is 0. """ def __init__(self, *args, **kwargs): kwargs['def...
Fix bug in introspection rule
Fix bug in introspection rule
Python
mit
kajic/django-counter-field
afc94c1a1ebf14dbb393234233055915132a9fb8
django_ethereum_events/apps.py
django_ethereum_events/apps.py
from django.apps import AppConfig from django.conf import settings class EthereumEventsConfig(AppConfig): name = 'django_ethereum_events' def ready(self): super(EthereumEventsConfig, self).ready() app.config_from_object('django.conf:settings') app.autodiscover_tasks(lambda: settings.I...
from django.apps import AppConfig from django.conf import settings class EthereumEventsConfig(AppConfig): name = 'django_ethereum_events'
Fix for the previous commit (Celery app removal)
Fix for the previous commit (Celery app removal) Haven't paid enough attention and missed what ready method does. Removed the code. Libraries shouldn't do this - it's main project responsibility.
Python
mit
artemistomaras/django-ethereum-events,artemistomaras/django-ethereum-events
36fb88bf5f60a656defaafc7626c373e59a70e05
tests/util.py
tests/util.py
#!/usr/bin/env python from __future__ import absolute_import from __future__ import unicode_literals import codecs import contextlib import functools import os class Env(object): def __init__(self): self.user = os.getenv('AWS_ACCESS_KEY_ID', None) assert self.user, \ 'Required environ...
#!/usr/bin/env python from __future__ import absolute_import from __future__ import unicode_literals import codecs import contextlib import functools import os class Env(object): def __init__(self): # self.user = os.getenv('AWS_ACCESS_KEY_ID', None) # assert self.user, \ # 'Required e...
Comment out assertion of environment variables(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY). When test fail, all environment variables appear in the error log in some case. Use credential file(~/.aws/credential) configuration for testing.
Comment out assertion of environment variables(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY). When test fail, all environment variables appear in the error log in some case. Use credential file(~/.aws/credential) configuration for testing.
Python
mit
laughingman7743/PyAthenaJDBC,laughingman7743/PyAthenaJDBC
6e80afd8f4317101a94f0d0114901da736f9912d
infect/infect.py
infect/infect.py
#!/usr/bin/env python # coding: utf-8 import sys import os # import argparse class Infect(object): class Codes: symlink = { 'success': 0, 'target_not_found': 1, 'destination_already_linked': 2, 'destination_exists': 3, } def __init__(self): ...
#!/usr/bin/env python # coding: utf-8 import sys import os # import argparse class Infect(object): class Codes: symlink = { 'success': 0, 'target_not_found': 1, 'destination_already_linked': 2, 'destination_exists': 3, } def __init__(self): ...
Add pragma: nocover to non-implemented methods
Add pragma: nocover to non-implemented methods
Python
mit
thiderman/infect
186567fdc127e5c08131ebbf49b76a7f7430de6a
pathvalidate/_common.py
pathvalidate/_common.py
# encoding: utf-8 """ .. codeauthor:: Tsuyoshi Hombashi <gogogo.vm@gmail.com> """ from __future__ import absolute_import from __future__ import unicode_literals import dataproperty from ._error import NullNameError def _validate_null_string(text): if dataproperty.is_empty_string(text): raise NullNameE...
# encoding: utf-8 """ .. codeauthor:: Tsuyoshi Hombashi <gogogo.vm@gmail.com> """ from __future__ import absolute_import from __future__ import unicode_literals import dataproperty from ._error import NullNameError def _validate_null_string(text, error_msg="null name"): if dataproperty.is_empty_string(text): ...
Change to modifiable error message
Change to modifiable error message
Python
mit
thombashi/pathvalidate
37ad455bdabd7a93254f17c1838e526bd6d77c66
example/people.py
example/people.py
from pupa.scrape import Scraper from pupa.models import Person, Organization class PersonScraper(Scraper): def get_people(self): # committee tech = Organization('Technology', classification='committee') tech.add_post('Chairman', 'chairman') yield tech # subcommittee ...
from pupa.scrape import Scraper from pupa.models import Person, Organization class PersonScraper(Scraper): def get_people(self): # committee tech = Organization('Technology', classification='committee') tech.add_post('Chairman', 'chairman') tech.add_source('https://example.com') ...
Add sources to example scrape.
Add sources to example scrape.
Python
bsd-3-clause
influence-usa/pupa,mileswwatkins/pupa,mileswwatkins/pupa,opencivicdata/pupa,rshorey/pupa,influence-usa/pupa,datamade/pupa,datamade/pupa,opencivicdata/pupa,rshorey/pupa
e7afc1ccf85baf54772493288074122bb1042f93
lcd_ticker.py
lcd_ticker.py
#!/usr/bin/env python """Display stock quotes on LCD""" from ystockquote import get_price, get_change from lcd import lcd_string, tn symbols = ['AAPL', 'MSFT', 'F', 'T', 'KO', 'GOOG', 'SYK', 'DIS', 'GM', 'GE', 'BAC', 'IBM', 'C', 'AMZN', 'AET', 'DOW', 'INTC', 'PFE', 'MRK', 'RTN'] while(True): for s in...
#!/usr/bin/env python """Display stock quotes on LCD""" import ystockquote as y from lcd import lcd_string, tn symbols = ['AAPL', 'MSFT', 'F', 'T', 'KO', 'GOOG', 'SYK', 'DIS', 'GM', 'GE', 'BAC', 'IBM', 'C', 'AMZN', 'AET', 'DOW', 'INTC', 'PFE', 'MRK', 'RTN'] def compact_quote(symbol): symbo...
Move compact_quote() to main LCD ticker file.
Move compact_quote() to main LCD ticker file.
Python
mit
zimolzak/Raspberry-Pi-newbie,zimolzak/Raspberry-Pi-newbie,zimolzak/Raspberry-Pi-newbie,zimolzak/Raspberry-Pi-newbie,zimolzak/Raspberry-Pi-newbie
480e51fc6b09cc47105b4615c0ff9047b39a9067
eva_cttv_pipeline/trait_mapping/utils.py
eva_cttv_pipeline/trait_mapping/utils.py
import logging logger = logging.getLogger(__package__) def request_retry_helper(function, retry_count: int, url: str): """ Given a function make a number of attempts to call function for it to successfully return a non-None value, subsequently returning this value. Makes the number of tries specified in ...
import logging logger = logging.getLogger(__package__) def request_retry_helper(function, retry_count: int, url: str): """ Given a function make a number of attempts to call function for it to successfully return a non-None value, subsequently returning this value. Makes the number of tries specified in ...
Modify the URL helper to not rely on None values
Modify the URL helper to not rely on None values
Python
apache-2.0
EBIvariation/eva-cttv-pipeline
771f0056495f959a88406473debbbcf9712dc14a
web/impact/impact/tests/test_method_override_middleware.py
web/impact/impact/tests/test_method_override_middleware.py
# MIT License # Copyright (c) 2017 MassChallenge, Inc. from django.urls import reverse from impact.middleware.method_override_middleware import METHOD_OVERRIDE_HEADER from impact.tests.api_test_case import APITestCase from impact.tests.contexts import UserContext class TestMethodOverrideMiddleware(APITestCase): ...
# MIT License # Copyright (c) 2017 MassChallenge, Inc. from django.urls import reverse from impact.middleware.method_override_middleware import METHOD_OVERRIDE_HEADER from impact.tests.api_test_case import APITestCase from impact.tests.contexts import UserContext class TestMethodOverrideMiddleware(APITestCase): ...
Rename Test And Add Test For GET
[AC-4959] Rename Test And Add Test For GET
Python
mit
masschallenge/impact-api,masschallenge/impact-api,masschallenge/impact-api,masschallenge/impact-api
ee3aa59ef8a398d4d6beddece92f46758e6b6393
django_evolution/compat/apps.py
django_evolution/compat/apps.py
try: from django.apps.registry import apps # Django >= 1.7 get_apps = apps.get_apps cache = None except ImportError: from django.db.models.loading import cache # Django < 1.7 get_apps = cache.get_apps apps = None def get_app(app_label, emptyOK=False): """Return the app with the g...
try: from django.apps.registry import apps # Django >= 1.7 get_apps = apps.get_apps cache = None except ImportError: from django.db.models.loading import cache # Django < 1.7 get_apps = cache.get_apps apps = None def get_app(app_label, emptyOK=False): """Return the app with the g...
Fix the app compatibility for real.
Fix the app compatibility for real. The previous change was still wrong. This is what I meant to do in the first place.
Python
bsd-3-clause
beanbaginc/django-evolution
7ef43157bfe8e095a816599e4b8e744a62042c47
module_auto_update/migrations/10.0.2.0.0/pre-migrate.py
module_auto_update/migrations/10.0.2.0.0/pre-migrate.py
# -*- coding: utf-8 -*- # Copyright 2018 Tecnativa - Jairo Llopis # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl). import logging from psycopg2 import IntegrityError from odoo.addons.module_auto_update.models.module_deprecated import \ PARAM_DEPRECATED _logger = logging.getLogger(__name__) def mi...
# -*- coding: utf-8 -*- # Copyright 2018 Tecnativa - Jairo Llopis # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl). import logging from psycopg2 import IntegrityError from odoo.addons.module_auto_update.models.module_deprecated import \ PARAM_DEPRECATED _logger = logging.getLogger(__name__) def mi...
Rollback cursor if param exists
[FIX] module_auto_update: Rollback cursor if param exists Without this patch, when upgrading after you have stored the deprecated features parameter, the cursor became broken and no more migrations could happen. You got this error: Traceback (most recent call last): File "/usr/local/bin/odoo", line 6, in <mod...
Python
agpl-3.0
OCA/server-tools,OCA/server-tools,OCA/server-tools,YannickB/server-tools,YannickB/server-tools,YannickB/server-tools
9d2ff18544950e129f5b363af4fa042b067e6830
dashboards/help/guides/urls.py
dashboards/help/guides/urls.py
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # 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...
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # 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...
Fix patterns for Django > 1.10
Fix patterns for Django > 1.10 Pike requires Django 1.11 so fix the template pattern import which was not compatible with that version. This fixes: File "/srv/www/openstack-dashboard/openstack_dashboard/dashboards/help/guides/\ urls.py", line 15, in <module> from django.conf.urls import patterns, url ImportError:...
Python
apache-2.0
SUSE-Cloud/horizon-suse-theme,SUSE-Cloud/horizon-suse-theme
32f2180a2ebe4162d9d9c3058ba9b478a8809ca8
djlotrek/context_processors.py
djlotrek/context_processors.py
from django.conf import settings as django_settings try: from django.core.urlresolvers import reverse, resolve except ImportError: from django.urls import reverse, resolve from django.utils.translation import activate, get_language from urllib.parse import urljoin from .request_utils import get_host_url def ...
from django.conf import settings as django_settings try: from django.core.urlresolvers import reverse, resolve except ImportError: from django.urls import reverse, resolve from django.utils.translation import activate, get_language from urllib.parse import urljoin from .request_utils import get_host_url def ...
Store cur_language in alternate before everything
Store cur_language in alternate before everything
Python
mit
lotrekagency/djlotrek,lotrekagency/djlotrek
db987f6f54dd04dd292237ff534e035605427239
extract/extract-meeting-log/src/eml.py
extract/extract-meeting-log/src/eml.py
#!/usr/bin/python import argparse import datetime import string ############ ### MAIN ### ############ parser = argparse.ArgumentParser(formatter_class = argparse.RawTextHelpFormatter) parser.add_argument( '--date', help = "Date in the format <y>-<m>-<d> for which to produce log. For example, 2014-09-09. I...
#!/usr/bin/python import argparse import datetime import string ############ ### MAIN ### ############ parser = argparse.ArgumentParser(formatter_class = argparse.RawTextHelpFormatter) parser.add_argument( '--date', help = "Date in the format <y>-<m>-<d> for which to produce log. For example, 2014-09-09. I...
Print out number of lines found for chatlog
Print out number of lines found for chatlog
Python
apache-2.0
justincc/viewer-tools
37903904cd0b1a8c4a04811b4a10a16606f9d7b0
doc/jsdoc_conf.py
doc/jsdoc_conf.py
# -*- coding: utf-8 -*- # from __future__ import unicode_literals from common_conf import * SITEURL = ".." TEMPLATE = "doc/theme/templates/jsdoc.html" TITLE = "NuvolaKit 3.0 JavaScript API Reference"
# -*- coding: utf-8 -*- # from __future__ import unicode_literals from common_conf import * SITEURL = ".." TEMPLATE = "doc/theme/templates/jsdoc.html" TITLE = "NuvolaKit 3.0 JavaScript API Reference" INTERLINKS = { "doc": "../", "tiliado": TILIADOWEB, }
Add interlinks urls for doc and tiliado
Add interlinks urls for doc and tiliado Signed-off-by: Jiří Janoušek <2a48236b6dcae98c8c0e90f4673742773ee17d91@gmail.com>
Python
bsd-2-clause
tiliado/nuvolaruntime,tiliado/nuvolaruntime,tiliado/nuvolaruntime,tiliado/nuvolaruntime
d69ced31c6dd174b1149f97a08de0ec5e8805d13
env_modifiers.py
env_modifiers.py
def make_rendered(env, *render_args, **render_kwargs): base_step = env._step def _step(action): env.render(*render_args, **render_kwargs) return base_step(action) env._step = _step def make_timestep_limited(env, timestep_limit): t = 1 old__step = env._step old__reset = env._r...
def make_rendered(env, *render_args, **render_kwargs): base_step = env._step def _step(action): ret = base_step(action) env.render(*render_args, **render_kwargs) return ret env._step = _step def make_timestep_limited(env, timestep_limit): t = 1 old__step = env._step o...
Call _render before _step to support BipedalWalker
Call _render before _step to support BipedalWalker
Python
mit
toslunar/chainerrl,toslunar/chainerrl
4c33e921d8ad6d1a69b0d198e8ea71b64339973a
us_ignite/common/tests/context_processors_tests.py
us_ignite/common/tests/context_processors_tests.py
from nose.tools import eq_ from django.test import TestCase from us_ignite.common.tests import utils from us_ignite.common import context_processors class TestSettingsAvailableContextProcessor(TestCase): def test_settings_are_available(self): request = utils.get_request('get', '/') context = co...
from nose.tools import eq_ from django.test import TestCase from us_ignite.common.tests import utils from us_ignite.common import context_processors class TestSettingsAvailableContextProcessor(TestCase): def test_settings_are_available(self): request = utils.get_request('get', '/') context = co...
Update common context processors tests.
Update common context processors tests.
Python
bsd-3-clause
us-ignite/us_ignite,us-ignite/us_ignite,us-ignite/us_ignite,us-ignite/us_ignite,us-ignite/us_ignite
aaaaad4ea3109406268471b6605eb6078848db0d
falcom/api/uri/fake_mapping.py
falcom/api/uri/fake_mapping.py
# Copyright (c) 2017 The Regents of the University of Michigan. # All Rights Reserved. Licensed according to the terms of the Revised # BSD License. See LICENSE.txt for details. class FakeMappingThatRecordsAccessions: def __init__ (self): self.__set = set() def __getitem__ (self, key): self._...
# Copyright (c) 2017 The Regents of the University of Michigan. # All Rights Reserved. Licensed according to the terms of the Revised # BSD License. See LICENSE.txt for details. class FakeMappingThatRecordsAccessions: def __init__ (self): self.__set = set() def __getitem__ (self, key): self._...
Write function for getting expected args
Write function for getting expected args
Python
bsd-3-clause
mlibrary/image-conversion-and-validation,mlibrary/image-conversion-and-validation
1aaced816ea206a85c0a3cf99915f09af2517e14
parliament/core/search_indexes.py
parliament/core/search_indexes.py
from haystack import site from haystack import indexes from parliament.core.models import Politician from parliament.search.utils import SearchIndex class PolIndex(SearchIndex): text = indexes.CharField(document=True, use_template=True) boosted = indexes.CharField(use_template=True, stored=False) politici...
from haystack import site from haystack import indexes from parliament.core.models import Politician from parliament.search.utils import SearchIndex class PolIndex(SearchIndex): text = indexes.CharField(document=True, use_template=True) boosted = indexes.CharField(use_template=True, stored=False) politici...
Add party/province to politician search index
Add party/province to politician search index
Python
agpl-3.0
litui/openparliament,rhymeswithcycle/openparliament,twhyte/openparliament,rhymeswithcycle/openparliament,litui/openparliament,twhyte/openparliament,litui/openparliament,twhyte/openparliament,rhymeswithcycle/openparliament
7b5ffcef89fe12576885bf4d29651829a5ed6249
gala/__init__.py
gala/__init__.py
""" Gala === Gala is a Python package for nD image segmentation. """ __author__ = 'Juan Nunez-Iglesias <juan.n@unimelb.edu.au>, '+\ 'Ryan Kennedy <kenry@cis.upenn.edu>' del sys, logging __all__ = ['agglo', 'morpho', 'evaluate', 'viz', 'imio', 'classify', 'stack_np', 'app_logger', 'option_manage...
""" Gala === Gala is a Python package for nD image segmentation. """ __author__ = 'Juan Nunez-Iglesias <juan.n@unimelb.edu.au>, '+\ 'Ryan Kennedy <kenry@cis.upenn.edu>' __all__ = ['agglo', 'morpho', 'evaluate', 'viz', 'imio', 'classify', 'stack_np', 'app_logger', 'option_manager', 'features', '...
Remove no longer valid del sys statement
Remove no longer valid del sys statement
Python
bsd-3-clause
jni/gala,janelia-flyem/gala
4564bb9c2f964d46cefb4bb805ac205b8abc9c03
unittests/ufxtract_setup.py
unittests/ufxtract_setup.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from hcalendar import hCalendar import unittest try: import urllib.request as urllib2 except: import urllib2 class...
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from hcalendar import hCalendar import unittest try: import urllib.request as urllib2 except: import urllib2 class...
Change User-agent header during unittests
Change User-agent header during unittests
Python
mit
mback2k/python-hcalendar
451d7d1186fbf7e247707ff8a02efb76d69b110d
sale_payment_method_automatic_workflow/__openerp__.py
sale_payment_method_automatic_workflow/__openerp__.py
# -*- coding: utf-8 -*- ############################################################################## # # Author: Guewen Baconnier # Copyright 2015 Camptocamp SA # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # pu...
# -*- coding: utf-8 -*- ############################################################################## # # Author: Guewen Baconnier # Copyright 2015 Camptocamp SA # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # pu...
Correct author list, add OCA
Correct author list, add OCA
Python
agpl-3.0
Eficent/sale-workflow,jabibi/sale-workflow,akretion/sale-workflow,brain-tec/sale-workflow,thomaspaulb/sale-workflow,Endika/sale-workflow,ddico/sale-workflow,akretion/sale-workflow,BT-cserra/sale-workflow,acsone/sale-workflow,Antiun/sale-workflow,factorlibre/sale-workflow,open-synergy/sale-workflow,diagramsoftware/sale-...
6fe06b2a2b504c28bc35ef2f429d72dc8082efca
cmsplugin_zinnia/placeholder.py
cmsplugin_zinnia/placeholder.py
"""Placeholder model for Zinnia""" import inspect from cms.models.fields import PlaceholderField from cms.plugin_rendering import render_placeholder from zinnia.models.entry import EntryAbstractClass class EntryPlaceholder(EntryAbstractClass): """Entry with a Placeholder to edit content""" content_placehol...
"""Placeholder model for Zinnia""" import inspect from cms.models.fields import PlaceholderField from cms.plugin_rendering import render_placeholder from zinnia.models_bases.entry import AbstractEntry class EntryPlaceholder(AbstractEntry): """Entry with a Placeholder to edit content""" content_placeholder ...
Use AbstractEntry instead of EntryAbstractClass
Use AbstractEntry instead of EntryAbstractClass
Python
bsd-3-clause
bittner/cmsplugin-zinnia,django-blog-zinnia/cmsplugin-zinnia,bittner/cmsplugin-zinnia,django-blog-zinnia/cmsplugin-zinnia,bittner/cmsplugin-zinnia,django-blog-zinnia/cmsplugin-zinnia
cdefa6cb4a91cbbac5d2680fe2e116a2a4ebb86b
recipe_scrapers/allrecipes.py
recipe_scrapers/allrecipes.py
from ._abstract import AbstractScraper class AllRecipes(AbstractScraper): @classmethod def host(cls): return "allrecipes.com" def author(self): # NB: In the schema.org 'Recipe' type, the 'author' property is a # single-value type, not an ItemList. # allrecipes.com seems to...
from ._abstract import AbstractScraper class AllRecipes(AbstractScraper): @classmethod def host(cls): return "allrecipes.com" def author(self): # NB: In the schema.org 'Recipe' type, the 'author' property is a # single-value type, not an ItemList. # allrecipes.com seems to...
Use 'isinstance' in preference to 'type' method
Use 'isinstance' in preference to 'type' method
Python
mit
hhursev/recipe-scraper
12acfff456e1a696d1117b20b8843c6789ee38bb
wake/views.py
wake/views.py
from been.couch import CouchStore from flask import render_template, abort from wake import app store = CouchStore().load() @app.route('/') def wake(): return render_template('stream.html', events=store.collapsed_events()) @app.route('/<slug>') def by_slug(slug): events = list(store.events_by_slug(slug)) ...
from been.couch import CouchStore from flask import render_template, abort, request, url_for from urlparse import urljoin from werkzeug.contrib.atom import AtomFeed from datetime import datetime from wake import app store = CouchStore().load() @app.route('/') def wake(): return render_template('stream.html', even...
Add Atom feed for events that have 'syndicate' set in their source config.
Add Atom feed for events that have 'syndicate' set in their source config.
Python
bsd-3-clause
chromakode/wake
5216f5c590f4b12d5e7d790a1206783edd5b581d
web/models.py
web/models.py
from django.db import models # Create your models here. class Subscriber(models.Model): email = models.EmailField() valid = models.BooleanField(default=True) class Repo(models.Model): name = models.CharField(max_length=256) owner = models.CharField(max_length=256) class Idea(models.Model): subscr...
from django.db import models # Create your models here. class Subscriber(models.Model): email = models.EmailField() valid = models.BooleanField(default=True) class Repo(models.Model): name = models.CharField(max_length=256) owner = models.CharField(max_length=256) def full_repository_name(self): ...
Add a full_repository_name method on Repo model
Add a full_repository_name method on Repo model
Python
apache-2.0
Jucyio/Jucy,Jucyio/Jucy,Jucyio/Jucy
9ad0a652e83659cc442b99d6082d4b07204eca4e
apps/mc/settings.py
apps/mc/settings.py
PROPERTIES = { # common.Property.name_id 'air_temperature': { # dictionary of observation providers of given property # mandatory, at least one provider must be specified 'observation_providers': { # path to Django model # the model must be subclass of common.A...
PROPERTIES = { # common.Property.name_id 'air_temperature': { # dictionary of observation providers of given property # mandatory, at least one provider must be specified 'observation_providers': { # path to Django model # the model must be subclass of common.A...
Move process filter to observation_provider
Move process filter to observation_provider See https://github.com/gis4dis/poster/wiki/Server-configuration/d9e22000c5e923adcb8ec7cee72b62d082799516
Python
bsd-3-clause
gis4dis/poster,gis4dis/poster,gis4dis/poster
8a28ae1c319f80e56146f1a5029222cb144d4650
mempoke.py
mempoke.py
import gdb import struct class DeviceMemory: def __init__(self): self.inferior = gdb.selected_inferior() def __del__(self): del self.inferior def read(self, address): return struct.unpack('I', self.inferior.read_memory(address, 4))[0] def write(self, address, value): ...
import gdb import struct class DeviceMemory: def __init__(self): self.inferior = gdb.selected_inferior() def __del__(self): del self.inferior def read(self, address): return struct.unpack('I', self.inferior.read_memory(address, 4))[0] def write(self, address, value): ...
Add mechanism for defining registers in memory mapped peripherals of MCU
Add mechanism for defining registers in memory mapped peripherals of MCU
Python
mit
fmfi-svt-deadlock/hw-testing,fmfi-svt-deadlock/hw-testing
5d4bcaaef6b2d571ff6929beaffcbe2f320d74ad
migrate.py
migrate.py
from api import db, migration import os migration.create_schema_version() migrations = migration.get_filenames("migrations") versions = [f.split('__')[0] for f in migrations] applied = migration.get_schema_version() print migrations print applied if migration.verify_applied_migrations(versions, applie...
from api import db, migration from os import getcwd from os.path import join migration.create_schema_version() migrations = migration.get_filenames(join(getcwd(), 'migrations')) versions = [f.split('__')[0] for f in migrations] applied = migration.get_schema_version() print migrations print applied ...
Refactor relative path to absolute for more reliability
Refactor relative path to absolute for more reliability
Python
mit
diogolundberg/db-migration
f6d9f03f487afb9d413120b6af603fd184925fac
src/oscar/templatetags/currency_filters.py
src/oscar/templatetags/currency_filters.py
from decimal import Decimal as D from decimal import InvalidOperation from babel.numbers import format_currency from django import template from django.conf import settings from django.utils.translation import get_language, to_locale register = template.Library() @register.filter(name='currency') def currency(value...
from decimal import Decimal as D from decimal import InvalidOperation from babel.numbers import format_currency from django import template from django.conf import settings from django.utils.translation import get_language, to_locale register = template.Library() @register.filter(name='currency') def currency(value...
Update reference to babel documentation
Update reference to babel documentation Babel changed it's link to their documents.
Python
bsd-3-clause
john-parton/django-oscar,okfish/django-oscar,django-oscar/django-oscar,anentropic/django-oscar,sonofatailor/django-oscar,django-oscar/django-oscar,michaelkuty/django-oscar,sasha0/django-oscar,solarissmoke/django-oscar,django-oscar/django-oscar,john-parton/django-oscar,solarissmoke/django-oscar,okfish/django-oscar,sasha...
c9974e13b27e84f0dd49d8a401e281b042fc2d0f
tests/TestLedger.py
tests/TestLedger.py
import Ledger from Transaction import Transaction import unittest class TestLedger(unittest.TestCase) : def setUp(self) : self.test_object = Ledger.Ledger() def tearDown(self) : pass def test_not_None(self) : self.assertIsNotNone(self.test_object) def test_add_transaction(s...
import Ledger from Transaction import Transaction import unittest class TestLedger(unittest.TestCase) : def setUp(self) : self.test_object = Ledger.Ledger() def tearDown(self) : pass def test_not_None(self) : self.assertIsNotNone(self.test_object) def test_add_transaction(s...
Add test to smoke out contains problem in Ledger
Add test to smoke out contains problem in Ledger
Python
apache-2.0
mattdeckard/wherewithal
ba49a9b3344f30f5bd3ea05144546e6a8a763ef0
tests/test_cli/test_config.py
tests/test_cli/test_config.py
# -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function from mock import patch from tests.test_cli.utils import BaseCommandTestCase from polyaxon_cli.cli.config import config class TestConfigManager(BaseCommandTestCase): @patch('polyaxon_cli.managers.config.GlobalConfigManager.g...
# -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function from mock import patch from tests.test_cli.utils import BaseCommandTestCase from polyaxon_cli.cli.config import config class TestConfigManager(BaseCommandTestCase): @patch('polyaxon_cli.managers.config.GlobalConfigManager.i...
Add more tests for config list
Add more tests for config list
Python
apache-2.0
polyaxon/polyaxon,polyaxon/polyaxon,polyaxon/polyaxon
f17d9c3b45758c02f1f67cbec6709e42149369f5
packs/asserts/actions/object_equals.py
packs/asserts/actions/object_equals.py
import pprint import sys from st2actions.runners.pythonrunner import Action __all__ = [ 'AssertObjectEquals' ] class AssertObjectEquals(Action): def run(self, object, expected): ret = cmp(object, expected) if ret == 0: sys.stdout.write('EQUAL.') else: pprint....
import pprint import sys from st2actions.runners.pythonrunner import Action __all__ = [ 'AssertObjectEquals' ] def cmp(x, y): return (x > y) - (x < y) class AssertObjectEquals(Action): def run(self, object, expected): ret = cmp(object, expected) if ret == 0: sys.stdout.wri...
Make action python 3 compatible
Make action python 3 compatible
Python
apache-2.0
StackStorm/st2tests,StackStorm/st2tests,StackStorm/st2tests
ea80d2d6b079ea2053f5bc25f1a8db2d21437093
tests/test_rules.py
tests/test_rules.py
# -*- coding: utf-8 -*- import pytest from repocket.rules import compile_rules, Rule from repocket.main import PocketItem def test_single_rule(): item1 = PocketItem(1, 'http://google.com', [], 'Google') item2 = PocketItem(1, 'http://github.com', [], 'Github') rule = Rule('.*google\.com', ['google']) ...
# -*- coding: utf-8 -*- import pytest from repocket.rules import compile_rules, Rule from repocket.main import PocketItem def test_single_rule(): item1 = PocketItem(1, 'http://google.com', [], 'Google') item2 = PocketItem(2, 'http://github.com', [], 'Github') rule = Rule('.*google\.com', ['google']) ...
Test for dynamic tag creation.
Test for dynamic tag creation.
Python
mit
lensvol/repocket
cc0f33a51f3b13cec191a7a97d20af95082e38db
tests/test_utils.py
tests/test_utils.py
"""Tests for the Texcavator utility functions""" import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "texcavator.settings")
"""Tests for the Texcavator utility functions""" import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "texcavator.settings") from nose.tools import assert_equals from testfixtures import compare import texcavator.utils as utils def test_json_error_message(): response = utils.json_error_message('test') ...
Add test for utility function json_error_message()
Add test for utility function json_error_message()
Python
apache-2.0
UUDigitalHumanitieslab/texcavator,msassmann/texcavator,msassmann/texcavator,msassmann/texcavator,UUDigitalHumanitieslab/texcavator,UUDigitalHumanitieslab/texcavator,msassmann/texcavator
e7b99f9993fa74377a72cac5295ffe6cb6b1d717
moves/tests.py
moves/tests.py
from django.test import TestCase # Create your tests here.
import pdb from django.test import TestCase from .models import Move # Create your tests here. class IndexTests(TestCase): def test_user_uuid_is_set_if_not_set(self): self.client.get('/') self.assertTrue(self.client.session.get('user_uuid'))
Create IndexTests class. Implement uuid test.
Create IndexTests class. Implement uuid test.
Python
mit
bnjmnhndrsn/lunchmove,bnjmnhndrsn/lunchmove,bnjmnhndrsn/lunchmove,Nestio/lunchmove,bnjmnhndrsn/lunchmove,Nestio/lunchmove,Nestio/lunchmove,Nestio/lunchmove
82a00e48492f2d787c980c434d58e249c210818e
ffmpeg/_probe.py
ffmpeg/_probe.py
import json import subprocess from ._run import Error from ._utils import convert_kwargs_to_cmd_line_args def probe(filename, cmd='ffprobe', **kwargs): """Run ffprobe on the specified file and return a JSON representation of the output. Raises: :class:`ffmpeg.Error`: if ffprobe returns a non-zero exi...
import json import subprocess from ._run import Error from ._utils import convert_kwargs_to_cmd_line_args def probe(filename, cmd='ffprobe', timeout=None, **kwargs): """Run ffprobe on the specified file and return a JSON representation of the output. Raises: :class:`ffmpeg.Error`: if ffprobe returns ...
Add optional timeout argument to probe
Add optional timeout argument to probe Popen.communicate() supports a timeout argument which is useful in case there is a risk that the probe hangs.
Python
apache-2.0
kkroening/ffmpeg-python
bc852b937e655ec7cf084df4185d66954d8128e0
tests/test_conditionals.py
tests/test_conditionals.py
import pytest from thinglang.runner import run def test_simple_conditionals(): assert run(""" thing Program does start if "dog" eq "dog" Output.write("dog is dog") if "dog" eq "cat" Output.write("dog is cat") """).output == """dog is dog""".strip() def test_uncon...
import pytest from thinglang.runner import run def test_simple_conditionals(): assert run(""" thing Program does start if "dog" eq "dog" Output.write("dog is dog") if "dog" eq "cat" Output.write("dog is cat") """).output == """dog is dog""".strip() def test_unc...
Add test for conditional elses
Add test for conditional elses
Python
mit
ytanay/thinglang,ytanay/thinglang,ytanay/thinglang,ytanay/thinglang
6e9059f24e75b37333af017f8facdb3426144ecf
conf/jupyter_notebook_config.py
conf/jupyter_notebook_config.py
import os c.NotebookApp.ip = '*' c.NotebookApp.allow_remote_access = True c.MultiKernelManager.kernel_manager_class = 'lc_wrapper.LCWrapperKernelManager' c.KernelManager.shutdown_wait_time = 10.0 c.FileContentsManager.delete_to_trash = False c.NotebookApp.quit_button = False c.NotebookApp.kernel_spec_manager_class = 'l...
import os c.NotebookApp.ip = '*' c.NotebookApp.allow_remote_access = True c.MultiKernelManager.kernel_manager_class = 'lc_wrapper.LCWrapperKernelManager' c.KernelManager.shutdown_wait_time = 10.0 c.FileContentsManager.delete_to_trash = False c.NotebookApp.quit_button = False c.NotebookApp.kernel_spec_manager_class = 'l...
Remove SIDESTICKIES_SCRAPBOX_COOKIE_CONNECT_SID from os.environ after reading
Remove SIDESTICKIES_SCRAPBOX_COOKIE_CONNECT_SID from os.environ after reading
Python
bsd-3-clause
NII-cloud-operation/Jupyter-LC_docker,NII-cloud-operation/Jupyter-LC_docker
b256b3406139be3affc4ff4c376acd53baa96297
crawler/crawler/middlewares/crawledURLCheck.py
crawler/crawler/middlewares/crawledURLCheck.py
# -*- coding: utf-8 -*- """ Checks if the given URL was already processed """ import logging from scrapy.exceptions import IgnoreRequest from sqlalchemy.orm import sessionmaker from sqlalchemy import create_engine from ..settings import DATABASE_URL from ..models import Advertisement class CrawledURLCheck(object):...
# -*- coding: utf-8 -*- """ Checks if the given URL was already processed """ import logging from datetime import date from scrapy.exceptions import IgnoreRequest from sqlalchemy.orm import sessionmaker from sqlalchemy import create_engine from ..settings import DATABASE_URL from ..models import Advertisement clas...
Update last seen if we found url in our database
Update last seen if we found url in our database
Python
mit
bhzunami/Immo,bhzunami/Immo,bhzunami/Immo
6fc6cc1a9d2d67b485c1d9ba492cc02ca864d45f
nipype/interfaces/brainsuite/__init__.py
nipype/interfaces/brainsuite/__init__.py
from .brainsuite import (Bse, Bfc, Pvc, Cerebro, Cortex, Scrubmask, Tca, Dewisp, Dfs, Pialmesh, Skullfinder, Hemisplit)
from .brainsuite import (Bse, Bfc, Pvc, Cerebro, Cortex, Scrubmask, Tca, Dewisp, Dfs, Pialmesh, Skullfinder, Hemisplit, SVReg, BDP)
Add SVReg and BDP to import
Add SVReg and BDP to import
Python
bsd-3-clause
mick-d/nipype,carolFrohlich/nipype,mick-d/nipype,mick-d/nipype,mick-d/nipype,carolFrohlich/nipype,carolFrohlich/nipype,carolFrohlich/nipype
f4383f964643c7fa1c4de050feaf7d134e34d814
example/people.py
example/people.py
from pupa.scrape import Scraper from pupa.scrape.helpers import Legislator, Organization class PersonScraper(Scraper): def get_people(self): # committee tech = Organization('Technology', classification='committee') tech.add_post('Chairman', 'chairman') tech.add_source('https://exa...
from pupa.scrape import Scraper from pupa.scrape.helpers import Legislator, Organization class PersonScraper(Scraper): def get_people(self): # committee tech = Organization('Technology', classification='committee') tech.add_post('Chairman', 'chairman') tech.add_source('https://exa...
Make it so that the example runs without error
Make it so that the example runs without error
Python
bsd-3-clause
datamade/pupa,influence-usa/pupa,rshorey/pupa,datamade/pupa,opencivicdata/pupa,rshorey/pupa,mileswwatkins/pupa,mileswwatkins/pupa,opencivicdata/pupa,influence-usa/pupa
1ec1fff2539ef0223fa18a2049a35a1c81afe8f7
inonemonth/challenges/templatetags/challenges_extras.py
inonemonth/challenges/templatetags/challenges_extras.py
from django.template import Library register = Library() @register.filter def get_representation_for_user(role, user_role): if user_role.type == "juror": if role.type == "clencher": return "{0} ({1})".format(role.type.capitalize(), role.user.email) elif role.type == "juror": ...
from django.template import Library register = Library() @register.filter def get_representation_for_user(role, user_role): cap_role_type = role.type.capitalize() juror_representation_number = role.challenge.get_juror_representation_number(role) if user_role.type == "juror": if role.type == "clenc...
Increase abstractness for remaining test methods
Increase abstractness for remaining test methods
Python
mit
robrechtdr/inonemonth,robrechtdr/inonemonth,robrechtdr/inonemonth,robrechtdr/inonemonth
f353ee5d2e2cf5fd4ee86776fc7e5ee6cb8a3238
sierra_adapter/build_windows.py
sierra_adapter/build_windows.py
#!/usr/bin/env python # -*- encoding: utf-8 -*- """ Usage: build_windows.py --start=<START> --end=<END> [--interval=<INTERVAL>] --resource=<RESOURCE> build_windows.py -h | --help """ import datetime as dt import json import boto3 import docopt import maya args = docopt.docopt(__doc__) start = maya.parse(args...
#!/usr/bin/env python # -*- encoding: utf-8 -*- """ Usage: build_windows.py --start=<START> --end=<END> [--interval=<INTERVAL>] --resource=<RESOURCE> build_windows.py -h | --help """ import datetime as dt import json import math import boto3 import docopt import maya import tqdm args = docopt.docopt(__doc__) ...
Print a progress meter when pushing windows
Print a progress meter when pushing windows
Python
mit
wellcometrust/platform-api,wellcometrust/platform-api,wellcometrust/platform-api,wellcometrust/platform-api
ed5be5a3c2d2f75812b800b09aa94b0702c38fc7
publishconf.py
publishconf.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # from __future__ import unicode_literals # This file is only used if you use `make publish` or # explicitly specify it as your config file. import os import sys sys.path.append(os.curdir) from pelicanconf import * SITEURL = 'http://blog.uname.gr' RELATIVE_URLS = False ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # from __future__ import unicode_literals # This file is only used if you use `make publish` or # explicitly specify it as your config file. import os import sys sys.path.append(os.curdir) from pelicanconf import * SITEURL = 'http://blog.uname.gr' RELATIVE_URLS = False ...
Add google analytics tracking id
Add google analytics tracking id Just so I can get an idea of who/what is looking at this blog
Python
mit
akosiaris/akosiaris.github.io,akosiaris/akosiaris.github.io
c81670e3ab8b5dcedc37def3a10803dde9b7c8b1
devicehive/transports/base_transport.py
devicehive/transports/base_transport.py
class BaseTransport(object): """Base transport class.""" def __init__(self, name, data_format_class, data_format_options, handler_class, handler_options): self.name = name self._data_format = data_format_class(**data_format_options) self._data_type = self._data_format.d...
class BaseTransport(object): """Base transport class.""" def __init__(self, name, data_format_class, data_format_options, handler_class, handler_options): self.name = name self._data_format = data_format_class(**data_format_options) self._data_type = self._data_format.d...
Remove action from required params
Remove action from required params
Python
apache-2.0
devicehive/devicehive-python
151e94d2d0208ac1984da105c6c7966b2a76c697
pymodels/TS_V04_01/__init__.py
pymodels/TS_V04_01/__init__.py
from .lattice import default_optics_mode from .lattice import energy from .accelerator import default_vchamber_on from .accelerator import default_radiation_on from .accelerator import accelerator_data from .accelerator import create_accelerator from .families import get_family_data from .families import family_mapp...
from .lattice import default_optics_mode from .lattice import energy from .accelerator import default_vchamber_on from .accelerator import default_radiation_on from .accelerator import accelerator_data from .accelerator import create_accelerator from .families import get_family_data from .families import family_mapp...
Add control system data to init.
TS.ENH: Add control system data to init.
Python
mit
lnls-fac/sirius
71695f6cb8f939de924c29ef5ba2d69326608fa1
hkijwt/models.py
hkijwt/models.py
from django.db import models from django.conf import settings class AppToAppPermission(models.Model): requester = models.ForeignKey(settings.OAUTH2_PROVIDER_APPLICATION_MODEL, db_index=True, related_name='+') target = models.ForeignKey(settings.OAUTH2_PROVIDER_APPLICATION_MOD...
from django.db import models from django.conf import settings class AppToAppPermission(models.Model): requester = models.ForeignKey(settings.OAUTH2_PROVIDER_APPLICATION_MODEL, db_index=True, related_name='+') target = models.ForeignKey(settings.OAUTH2_PROVIDER_APPLICATION_MOD...
Add __str__ method to AppToAppPermission
Add __str__ method to AppToAppPermission
Python
mit
mikkokeskinen/tunnistamo,mikkokeskinen/tunnistamo
4379d143cfb5bb4c49febd881d7691aed7039210
judge/sandbox.py
judge/sandbox.py
import asyncio class Sandbox: def __init__(self): self._process = None async def start(self): if self._process is not None: raise ValueError("The sandbox has started") self._process = await asyncio.create_subprocess_exec( "sandbox", stdin = as...
import asyncio class Sandbox: def __init__(self): self._process = None async def start(self): if self._process is not None: raise ValueError("The sandbox has started") self._process = await asyncio.create_subprocess_exec( "sandbox", stdin = as...
Implement read of Python wrapper
Implement read of Python wrapper
Python
agpl-3.0
johnchen902/toyoj,johnchen902/toyoj,johnchen902/toyoj,johnchen902/toyoj,johnchen902/toyoj,johnchen902/toyoj
22558f86de3b76b3a9262ee5df3f8802b4c38f88
pylib/gfxprim/loaders/_extend_context.py
pylib/gfxprim/loaders/_extend_context.py
from ..utils import extend, add_swig_getmethod, add_swig_setmethod from . import loaders_c def extend_context(_context): """ Extends _context class with loader module methods for calling convenience. Called once on loaders module inicialization. """ @extend(_context, name='load') @staticmethod def Load(...
from ..utils import extend, add_swig_getmethod, add_swig_setmethod from . import loaders_c def extend_context(_context): """ Extends _context class with loader module methods for calling convenience. Called once on loaders module inicialization. """ @extend(_context, name='load') @staticmethod def Load(...
Fix the loaders extend context after API change.
pywrap: Fix the loaders extend context after API change.
Python
lgpl-2.1
gfxprim/gfxprim,gfxprim/gfxprim,gfxprim/gfxprim,gfxprim/gfxprim,gfxprim/gfxprim
6f6f6e183b574f8505b53ddb7651c8766992b953
pywikibot/families/lingualibre_family.py
pywikibot/families/lingualibre_family.py
"""Family module for Lingua Libre.""" # # (C) Pywikibot team, 2021 # # Distributed under the terms of the MIT license. # from pywikibot import family # The Lingua Libre family class Family(family.WikimediaFamily): """Family class for Lingua Libre. *New in version 6.5.* """ name = 'lingualibre' ...
"""Family module for Lingua Libre.""" # # (C) Pywikibot team, 2021 # # Distributed under the terms of the MIT license. # from pywikibot import family # The Lingua Libre family class Family(family.WikimediaFamily): """Family class for Lingua Libre. *New in version 6.5.* """ name = 'lingualibre' ...
Allow to request for item on Lingua Libre
Allow to request for item on Lingua Libre Bug: T286303 Change-Id: Ic0d8824d1bf326f2182fbb64d0cc2ed77f82fd4c
Python
mit
wikimedia/pywikibot-core,wikimedia/pywikibot-core
4fb253043d9b4841893bd8fd39bf27efee64c844
src/ice/runners/command_line_runner.py
src/ice/runners/command_line_runner.py
""" command_line_runner.py Created by Scott on 2014-08-14. Copyright (c) 2014 Scott Rice. All rights reserved. """ from ice_engine import IceEngine class CommandLineRunner(object): def run(self, argv): # TODO: Configure IceEngine based on the contents of argv engine = IceEngine() engine.run() # K...
""" command_line_runner.py Created by Scott on 2014-08-14. Copyright (c) 2014 Scott Rice. All rights reserved. """ import argparse from ice_engine import IceEngine class CommandLineRunner(object): def get_command_line_args(self, argv): parser = argparse.ArgumentParser() parser.add_argument('-c', '--conf...
Allow passing in config/consoles/emulators.txt locations from command line
Allow passing in config/consoles/emulators.txt locations from command line Summary: This will be really useful for Integration tests, along with whenever we get the desktop app running (since it will communicate with Ice via the command line) Test Plan: Run `src/ice.py --config=/Path/to/different/config`, where the d...
Python
mit
scottrice/Ice
7104882ffcd35c24d8df5b9aa909e9bc9619cba7
eli5/__init__.py
eli5/__init__.py
# -*- coding: utf-8 -*- from __future__ import absolute_import __version__ = '0.4.1' from .formatters import format_as_html, format_html_styles, format_as_text from .explain import explain_weights, explain_prediction from .sklearn import explain_weights_sklearn, explain_prediction_sklearn try: from .ipython imp...
# -*- coding: utf-8 -*- from __future__ import absolute_import __version__ = '0.4.1' from .formatters import format_as_html, format_html_styles, format_as_text from .explain import explain_weights, explain_prediction from .sklearn import explain_weights_sklearn, explain_prediction_sklearn try: from .ipython imp...
Handle improperly installed xgboost. Fixes GH-162.
Handle improperly installed xgboost. Fixes GH-162.
Python
mit
TeamHG-Memex/eli5,TeamHG-Memex/eli5,TeamHG-Memex/eli5
c4e4181617979247c5a891d8027077297d0a04da
modoboa_admin/management/commands/export_identities.py
modoboa_admin/management/commands/export_identities.py
import sys import csv from optparse import make_option from django.core.management.base import BaseCommand from modoboa.core import load_core_settings from modoboa.core.models import User from modoboa.core.extensions import exts_pool from modoboa.core.management.commands import CloseConnectionMixin from ...models imp...
import sys import csv from optparse import make_option from django.core.management.base import BaseCommand from modoboa.core import load_core_settings from modoboa.core.models import User from modoboa.core.extensions import exts_pool from modoboa.core.management.commands import CloseConnectionMixin from ...models imp...
Improve the speed of csv export file generation
Improve the speed of csv export file generation
Python
mit
bearstech/modoboa-admin,bearstech/modoboa-admin,bearstech/modoboa-admin
e72a71c045457bb459be4b7ea7e66e7438abdc95
terraform/templates/sch_log_parser.py
terraform/templates/sch_log_parser.py
import time from datetime import datetime def my_log_parser(logger, line): if line.count(',') >= 6: date, report_type, group_id, job_id, event, package, rest = line.split(',',6) if report_type == 'J' and event != 'Pending': date = datetime.strptime(date, "%Y-%m-%d %H:%M:%S") date = tim...
import time from datetime import datetime def my_log_parser(logger, line): if line.count(',') >= 6: date, report_type, group_id, job_id, event, package, rest = line.split(',',6) if report_type == 'J' and event != 'Pending': date = datetime.strptime(date, "%Y-%m-%d %H:%M:%S") ...
Fix dashboard script parsing failure
Fix dashboard script parsing failure Signed-off-by: Salim Alam <18ae4dd1e3db1d49a738226169e3b099325c79a0@chef.io>
Python
apache-2.0
habitat-sh/habitat,rsertelon/habitat,rsertelon/habitat,habitat-sh/habitat,rsertelon/habitat,rsertelon/habitat,habitat-sh/habitat,nathenharvey/habitat,nathenharvey/habitat,rsertelon/habitat,habitat-sh/habitat,habitat-sh/habitat,habitat-sh/habitat,georgemarshall/habitat,georgemarshall/habitat,nathenharvey/habitat,georgem...
9c75733c445900f579f3db4b98e7c8b71f084678
oscar_sagepay/dashboard/app.py
oscar_sagepay/dashboard/app.py
from django.conf.urls import patterns, url from django.contrib.admin.views.decorators import staff_member_required from oscar.core.application import Application from oscar.apps.dashboard.nav import register, Node from . import views node = Node('Datacash', 'sagepay-transaction-list') register(node, 100) class Sag...
from django.conf.urls import patterns, url from django.contrib.admin.views.decorators import staff_member_required from oscar.core.application import Application from . import views try: from oscar.apps.dashboard.nav import register, Node except ImportError: pass else: # Old way of registering Dashboard n...
Handle Oscar 0.4 dashboard navigation gracefully
Handle Oscar 0.4 dashboard navigation gracefully
Python
bsd-3-clause
django-oscar/django-oscar-sagepay-direct
454329c3cb6434dcdd2b4d89f127a87da8ee23ef
example/example_spin.py
example/example_spin.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import, print_function import sys import time from pyspin import spin def show(name, frames): s = spin.Spinner(frames) print(name) for i in range(50): time.sleep(0.1) print("\r{0}".format(s.next()), end="") ...
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import, print_function import sys import time from pyspin import spin def show(name, frames): s = spin.Spinner(frames) print(name) for i in range(50): print(u"\r{0}".format(s.next()), end="") sys.stdout.flush(...
Fix unicode issue in example code for python2.x
Fix unicode issue in example code for python2.x
Python
mit
lord63/py-spin
1af2795907b3a686d9bce4bdc94b89f3678dd1af
corehq/apps/sms/migrations/0049_auto_enable_turnio_ff.py
corehq/apps/sms/migrations/0049_auto_enable_turnio_ff.py
# Generated by Django 2.2.24 on 2021-06-10 09:13 from django.db import migrations from corehq.messaging.smsbackends.turn.models import SQLTurnWhatsAppBackend from corehq.toggles import TURN_IO_BACKEND, NAMESPACE_DOMAIN def auto_enable_turnio_ff_for_certain_domains(apps, schema_editor): for backend in SQLTurnWhat...
# Generated by Django 2.2.24 on 2021-06-10 09:13 from django.db import migrations from corehq.toggles import TURN_IO_BACKEND, NAMESPACE_DOMAIN def auto_enable_turnio_ff_for_certain_domains(apps, schema_editor): SQLTurnWhatsAppBackend = apps.get_model('sms', 'SQLTurnWhatsAppBackend') for backend in SQLTurnWh...
Use historical model in migration, not directly imported model
Use historical model in migration, not directly imported model
Python
bsd-3-clause
dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq
e560ea4a419e1e61d776245b99ffa0e60b4d0e22
InvenTree/stock/forms.py
InvenTree/stock/forms.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django import forms from InvenTree.forms import HelperForm from .models import StockLocation, StockItem class EditStockLocationForm(HelperForm): class Meta: model = StockLocation fields = [ 'name', 'par...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django import forms from InvenTree.forms import HelperForm from .models import StockLocation, StockItem class EditStockLocationForm(HelperForm): class Meta: model = StockLocation fields = [ 'name', 'par...
Update edit form for StockItem
Update edit form for StockItem - Disallow direct quantity editing (must perform stocktake) - Add notes field to allow editing
Python
mit
SchrodingersGat/InvenTree,inventree/InvenTree,SchrodingersGat/InvenTree,inventree/InvenTree,SchrodingersGat/InvenTree,inventree/InvenTree,inventree/InvenTree,SchrodingersGat/InvenTree
f2b4e4758ae60526e8bb5c57e9c45b0a1901fa14
wagtail/wagtailforms/edit_handlers.py
wagtail/wagtailforms/edit_handlers.py
from __future__ import absolute_import, unicode_literals from django.template.loader import render_to_string from django.utils.safestring import mark_safe from django.utils.translation import ugettext as _ from wagtail.wagtailadmin.edit_handlers import EditHandler class BaseFormSubmissionsPanel(EditHandler): te...
from __future__ import absolute_import, unicode_literals from django.template.loader import render_to_string from django.utils.safestring import mark_safe from django.utils.translation import ugettext as _ from wagtail.wagtailadmin.edit_handlers import EditHandler class BaseFormSubmissionsPanel(EditHandler): te...
Use verbose name for FormSubmissionsPanel heading
Use verbose name for FormSubmissionsPanel heading
Python
bsd-3-clause
rsalmaso/wagtail,takeflight/wagtail,torchbox/wagtail,rsalmaso/wagtail,FlipperPA/wagtail,zerolab/wagtail,jnns/wagtail,nimasmi/wagtail,kaedroho/wagtail,thenewguy/wagtail,zerolab/wagtail,mikedingjan/wagtail,nimasmi/wagtail,wagtail/wagtail,thenewguy/wagtail,nutztherookie/wagtail,takeflight/wagtail,chrxr/wagtail,jnns/wagtai...
8026b5f309264d4e72c3bc503601468cf1cdfcdd
src/nodeconductor_assembly_waldur/packages/filters.py
src/nodeconductor_assembly_waldur/packages/filters.py
import django_filters from nodeconductor.core.filters import UUIDFilter from . import models class PackageTemplateFilter(django_filters.FilterSet): name = django_filters.CharFilter(lookup_type='icontains') settings_uuid = UUIDFilter(name='service_settings__uuid') class Meta(object): model = mod...
import django_filters from nodeconductor.core.filters import UUIDFilter from . import models class PackageTemplateFilter(django_filters.FilterSet): name = django_filters.CharFilter(lookup_type='icontains') settings_uuid = UUIDFilter(name='service_settings__uuid') class Meta(object): model = mod...
Enable filtering OpenStack package by customer and project (WAL-49)
Enable filtering OpenStack package by customer and project (WAL-49)
Python
mit
opennode/waldur-mastermind,opennode/waldur-mastermind,opennode/waldur-mastermind,opennode/nodeconductor-assembly-waldur,opennode/waldur-mastermind,opennode/nodeconductor-assembly-waldur,opennode/nodeconductor-assembly-waldur
79614ed2cf4936358a2f7beca703210720883df2
netbox/netbox/graphql/types.py
netbox/netbox/graphql/types.py
import graphene from graphene.types.generic import GenericScalar from graphene_django import DjangoObjectType __all__ = ( 'BaseObjectType', 'ObjectType', 'TaggedObjectType', ) class BaseObjectType(DjangoObjectType): """ Base GraphQL object type for all NetBox objects """ class Meta: ...
import graphene from django.contrib.contenttypes.models import ContentType from graphene.types.generic import GenericScalar from graphene_django import DjangoObjectType __all__ = ( 'BaseObjectType', 'ObjectType', 'TaggedObjectType', ) # # Base types # class BaseObjectType(DjangoObjectType): """ ...
Add GraphQL type for ContentType
Add GraphQL type for ContentType
Python
apache-2.0
digitalocean/netbox,digitalocean/netbox,digitalocean/netbox,digitalocean/netbox
b55812bd94b20a31ba2f9a64eedbcbb811dc4257
camkes/internal/dictutils.py
camkes/internal/dictutils.py
# # Copyright 2014, NICTA # # This software may be distributed and modified according to the terms of # the BSD 2-Clause license. Note that NO WARRANTY is provided. # See "LICENSE_BSD2.txt" for details. # # @TAG(NICTA_BSD) # '''Various helpers for doing advanced things with dictionaries.''' def get_fields(s): '''...
# # Copyright 2014, NICTA # # This software may be distributed and modified according to the terms of # the BSD 2-Clause license. Note that NO WARRANTY is provided. # See "LICENSE_BSD2.txt" for details. # # @TAG(NICTA_BSD) # '''Various helpers for doing advanced things with dictionaries.''' import re def get_fields(...
Support non-string formats in `get_fields`.
Support non-string formats in `get_fields`. This commit rewrites the `get_fields` function to be simpler and more general. The previous implementation relied on ad hoc dict mocking and only supported format strings involving string-valued formats ('%(name)s'). From this commit other formats (e.g. '%(name)04d') are sup...
Python
bsd-2-clause
smaccm/camkes-tool,smaccm/camkes-tool,smaccm/camkes-tool,smaccm/camkes-tool
d852356e932a5112308a8c65c1ff6f14019a6835
factory/tools/cat_StarterLog.py
factory/tools/cat_StarterLog.py
#!/bin/env python # # cat_StarterLog.py # # Print out the StarterLog for a glidein output file # # Usage: cat_StarterLog.py logname # import os.path import sys STARTUP_DIR=sys.path[0] sys.path.append(os.path.join(STARTUP_DIR,"lib")) import gWftLogParser USAGE="Usage: cat_StarterLog.py <logname>" def main(): try:...
#!/bin/env python # # cat_StarterLog.py # # Print out the StarterLog for a glidein output file # # Usage: cat_StarterLog.py logname # import os.path import sys STARTUP_DIR=sys.path[0] sys.path.append(os.path.join(STARTUP_DIR,"lib")) import gWftLogParser USAGE="Usage: cat_StarterLog.py [-monitor] <logname>" def main(...
Add support for monitor starterlog
Add support for monitor starterlog
Python
bsd-3-clause
holzman/glideinwms-old,holzman/glideinwms-old,bbockelm/glideinWMS,bbockelm/glideinWMS,bbockelm/glideinWMS,holzman/glideinwms-old,bbockelm/glideinWMS
def129e32bf731351253e210b53c44cf8c57c302
planetstack/openstack_observer/steps/sync_images.py
planetstack/openstack_observer/steps/sync_images.py
import os import base64 from django.db.models import F, Q from xos.config import Config from observer.openstacksyncstep import OpenStackSyncStep from core.models.image import Image class SyncImages(OpenStackSyncStep): provides=[Image] requested_interval=0 observes=Image def fetch_pending(self, deleted...
import os import base64 from django.db.models import F, Q from xos.config import Config from observer.openstacksyncstep import OpenStackSyncStep from core.models.image import Image class SyncImages(OpenStackSyncStep): provides=[Image] requested_interval=0 observes=Image def fetch_pending(self, deleted...
Check the existence of the images_path
Check the existence of the images_path ERROR:planetstack.log:[Errno 2] No such file or directory: '/opt/xos/images' BEG TRACEBACK Traceback (most recent call last): File "/opt/xos/observer/event_loop.py", line 349, in sync failed_objects = sync_step(failed=list(self.failed_step_objects), deletion=deletion) Fil...
Python
apache-2.0
wathsalav/xos,wathsalav/xos,wathsalav/xos,wathsalav/xos
5968e99eb8e040686d345c6d77c71bb5975e5f29
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 = Cipher._random_key() if not key.isalpha() or not key.islower(): raise ValueError("Key must consist only of lowercase letters") self.ke...
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 ...
Use super() and self within the Cipher and Caesar classes
Use super() and self within the Cipher and Caesar classes
Python
agpl-3.0
CubicComet/exercism-python-solutions
6cae50cd400fec3a99f72fd9b60cf3a2cce0db24
skimage/morphology/__init__.py
skimage/morphology/__init__.py
from .binary import (binary_erosion, binary_dilation, binary_opening, binary_closing) from .grey import * from .selem import * from .ccomp import label from .watershed import watershed, is_local_maximum from ._skeletonize import skeletonize, medial_axis from .convex_hull import convex_hull_image fr...
from .binary import (binary_erosion, binary_dilation, binary_opening, binary_closing) from .grey import (erosion, dilation, opening, closing, white_tophat, black_tophat, greyscale_erode, greyscale_dilate, greyscale_open, greyscale_close, greyscale_white_top_hat...
Add __all__ to morphology package
Add __all__ to morphology package
Python
bsd-3-clause
michaelaye/scikit-image,vighneshbirodkar/scikit-image,paalge/scikit-image,blink1073/scikit-image,oew1v07/scikit-image,SamHames/scikit-image,chintak/scikit-image,vighneshbirodkar/scikit-image,oew1v07/scikit-image,chriscrosscutler/scikit-image,rjeli/scikit-image,michaelpacer/scikit-image,michaelpacer/scikit-image,michael...
052228bb3ba3c8ec13452f5a8328ed77c30e565d
images/hub/canvasauthenticator/canvasauthenticator/__init__.py
images/hub/canvasauthenticator/canvasauthenticator/__init__.py
from traitlets import List, Unicode from oauthenticator.generic import GenericOAuthenticator from tornado import gen canvas_site = 'https://ucberkeley.test.instructure.com/' class CanvasAuthenticator(GenericOAuthenticator): allowed_email_domains = List( [], config=True, help=""" L...
from traitlets import List, Unicode from oauthenticator.generic import GenericOAuthenticator from tornado import gen canvas_site = 'https://ucberkeley.test.instructure.com/' class CanvasAuthenticator(GenericOAuthenticator): allowed_email_domains = List( [], config=True, help=""" L...
Normalize usernames properly to prevent clashes from guest accounts
Normalize usernames properly to prevent clashes from guest accounts Guest accounts can have non berkeley.edu emails, and might get access to a berkeley.edu user's home directory. This will prevent that.
Python
bsd-3-clause
ryanlovett/datahub,berkeley-dsep-infra/datahub,ryanlovett/datahub,ryanlovett/datahub,berkeley-dsep-infra/datahub,berkeley-dsep-infra/datahub
c3aad1ab31b84cce97555c56ec44986addca5ee8
create_schemas_and_tables.py
create_schemas_and_tables.py
#! /usr/bin/env python3 import os import subprocess ODIE_DIR = os.path.dirname(__file__) subprocess.call([os.path.join(ODIE_DIR, 'create_garfield_models.py')]) subprocess.call([os.path.join(ODIE_DIR, 'create_fsmi_models.py')])
#! /usr/bin/env python3 import os import subprocess ODIE_DIR = os.path.dirname(__file__) # due to Flask-SQLA only using a single MetaData object even when handling multiple # databases, we can't create let it create all our models at once (otherwise it # tries to create Enums in all databases, which will fail due to...
Add comment explaining unconventional model creation
Add comment explaining unconventional model creation
Python
mit
fjalir/odie-server,Kha/odie-server,Kha/odie-server,fjalir/odie-server,fjalir/odie-server,Kha/odie-server,fsmi/odie-server,fsmi/odie-server,fsmi/odie-server
3934ed699cdb0b472c09ad238ee4284b0050869c
prime-factors/prime_factors.py
prime-factors/prime_factors.py
def prime_factors(n): factors = [] factor = 2 while n != 1: while n % factor == 0: factors += [factor] n //= factor factor += 1 return factors
def prime_factors(n): factors = [] while n % 2 == 0: factors += [2] n //= 2 factor = 3 while n != 1: while n % factor == 0: factors += [factor] n //= factor factor += 2 return factors
Make solution more efficient by only testing odd numbers
Make solution more efficient by only testing odd numbers
Python
agpl-3.0
CubicComet/exercism-python-solutions
3beffa750d68c2104b740193f0386be464829a1a
libpb/__init__.py
libpb/__init__.py
"""FreeBSD port building infrastructure.""" from __future__ import absolute_import from . import event def stop(kill=False, kill_clean=False): """Stop building ports and cleanup.""" from os import killpg from signal import SIGTERM, SIGKILL from .builder import builders from .env import cpus, flags from ....
"""FreeBSD port building infrastructure.""" from __future__ import absolute_import from . import event def stop(kill=False, kill_clean=False): """Stop building ports and cleanup.""" from os import killpg from signal import SIGTERM, SIGKILL from .builder import builders from .env import cpus, flags from ....
Use SystemExit, not exit() to initiate a shutdown.
Use SystemExit, not exit() to initiate a shutdown. exit() has unintented side affects, such as closing stdin, that are undesired as stdin is assumed to be writable while libpb/event/run unwinds (i.e. Top monitor).
Python
bsd-2-clause
DragonSA/portbuilder,DragonSA/portbuilder
aa84c6dccbff76a4e3b081dfb334b64bb3e6664f
test/functional/rpc_deprecated.py
test/functional/rpc_deprecated.py
#!/usr/bin/env python3 # Copyright (c) 2017 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test deprecation of RPC calls.""" from test_framework.test_framework import BitcoinTestFramework from test_f...
#!/usr/bin/env python3 # Copyright (c) 2017 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test deprecation of RPC calls.""" from test_framework.test_framework import BitcoinTestFramework class Depr...
Remove test for deprecated createmultsig option
[tests] Remove test for deprecated createmultsig option
Python
mit
DigitalPandacoin/pandacoin,peercoin/peercoin,DigitalPandacoin/pandacoin,peercoin/peercoin,DigitalPandacoin/pandacoin,DigitalPandacoin/pandacoin,peercoin/peercoin,peercoin/peercoin,DigitalPandacoin/pandacoin,peercoin/peercoin,peercoin/peercoin,DigitalPandacoin/pandacoin