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 |
|---|---|---|---|---|---|---|---|---|---|
e2919039a20a255232fefe3b78e173587710baf0 | cla_backend/apps/core/middleware.py | cla_backend/apps/core/middleware.py | from django.http import Http404
from django_statsd.clients import statsd
class GraphiteMiddleware(object):
def process_response(self, request, response):
statsd.incr("response.%s" % response.status_code)
return response
def process_exception(self, request, exception):
if not isinstanc... | class GraphiteMiddleware(object):
def process_response(self, request, response):
return response
| Remove statsd code and resultant redundant code | Remove statsd code and resultant redundant code | Python | mit | ministryofjustice/cla_backend,ministryofjustice/cla_backend,ministryofjustice/cla_backend,ministryofjustice/cla_backend |
6784c455cf93c16237661d6d9fed6af06726a880 | conveyor/processor.py | conveyor/processor.py | from __future__ import absolute_import
from __future__ import division
import collections
from xmlrpc2 import client as xmlrpc2
class BaseProcessor(object):
def __init__(self, index, *args, **kwargs):
super(BaseProcessor, self).__init__(*args, **kwargs)
self.index = index
self.client =... | from __future__ import absolute_import
from __future__ import division
import collections
import slumber
import slumber.exceptions
import xmlrpc2.client
class BaseProcessor(object):
def __init__(self, index, warehouse, *args, **kwargs):
super(BaseProcessor, self).__init__(*args, **kwargs)
warg... | Switch to more obvious imports | Switch to more obvious imports
| Python | bsd-2-clause | crateio/carrier |
1d63f615ac58cc8c548cdd8e359694355e5b1843 | portal/forms.py | portal/forms.py | from django.contrib.auth.models import User
from django import forms
# Create your forms here.
class UserForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput)
class Meta:
model = User
fields = ['username', 'email', 'password']
| from django.contrib.auth.models import User
from django import forms
# Create your forms here.
class BootstrapForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
for visible in self.visible_fields():
visible.field.widget.attrs['class'] = 'form... | Add BootstrapForm to beautify form_template | Add BootstrapForm to beautify form_template
| Python | mit | huangsam/chowist,huangsam/chowist,huangsam/chowist |
6b880f3c783e6a278906b8da2aabea29bb106252 | thinc/neural/_classes/resnet.py | thinc/neural/_classes/resnet.py | from .model import Model
from ...api import layerize
from .affine import Affine
import cytoolz as toolz
def Residual(layer):
def residual_fwd(X, drop=0.):
y, bp_y = layer.begin_update(X, drop=drop)
output = X+y
def residual_bwd(d_output, sgd=None):
return d_output + bp_y(d_out... | from .model import Model
from ...api import layerize
from .affine import Affine
import cytoolz as toolz
class Residual(Model):
def __init__(self, layer):
Model.__init__(self)
self._layers.append(layer)
self.on_data_hooks.append(on_data)
def __call__(self, X):
return X + self.... | Add predict path for Residual | Add predict path for Residual
| Python | mit | spacy-io/thinc,spacy-io/thinc,spacy-io/thinc,explosion/thinc,explosion/thinc,explosion/thinc,explosion/thinc |
105ac0020dbc60fe57da7db75fb82cf872a0834d | crm_switzerland/models/res_partner.py | crm_switzerland/models/res_partner.py | # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2018 Compassion CH (http://www.compassion.ch)
# Releasing children from poverty in Jesus' name
# @author: Emanuel Cino <ecino@compassion.ch>
#
# The licence is in the file __manifest__.py... | # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2018 Compassion CH (http://www.compassion.ch)
# Releasing children from poverty in Jesus' name
# @author: Emanuel Cino <ecino@compassion.ch>
#
# The licence is in the file __manifest__.py... | FIX bug when sending notification to multiple partners | FIX bug when sending notification to multiple partners
| Python | agpl-3.0 | ecino/compassion-switzerland,eicher31/compassion-switzerland,CompassionCH/compassion-switzerland,eicher31/compassion-switzerland,CompassionCH/compassion-switzerland,ecino/compassion-switzerland,eicher31/compassion-switzerland,CompassionCH/compassion-switzerland,ecino/compassion-switzerland |
bb8d2fa458dd565b88db4e2185062f641864e990 | tornado/test/httpserver_test.py | tornado/test/httpserver_test.py | #!/usr/bin/env python
from tornado.testing import AsyncHTTPTestCase, LogTrapTestCase
from tornado.web import Application, RequestHandler
import os
import pycurl
import re
import unittest
import urllib
class HelloWorldRequestHandler(RequestHandler):
def get(self):
self.finish("Hello world")
class SSLTest(... | #!/usr/bin/env python
from tornado.testing import AsyncHTTPTestCase, LogTrapTestCase
from tornado.web import Application, RequestHandler
import os
import pycurl
import re
import unittest
import urllib
try:
import ssl
except ImportError:
ssl = None
class HelloWorldRequestHandler(RequestHandler):
def get(s... | Disable SSL test on python 2.5 | Disable SSL test on python 2.5
| Python | apache-2.0 | bywbilly/tornado,AlphaStaxLLC/tornado,felixonmars/tornado,jarrahwu/tornado,BencoLee/tornado,MjAbuz/tornado,shaohung001/tornado,sunjeammy/tornado,zhuochenKIDD/tornado,VShangxiao/tornado,LTD-Beget/tornado,Snamint/tornado,304471720/tornado,Callwoola/tornado,shashankbassi92/tornado,InverseLina/tornado,Batterfii/tornado,cyr... |
39cc30f2f6c74d3a506c5d1a46cf0ccc6377b80f | pylibscrypt/__init__.py | pylibscrypt/__init__.py |
# First, try loading libscrypt
_done = False
try:
from pylibscrypt import *
except ImportError:
pass
else:
_done = True
# If that didn't work, get the inlined Python version
if not _done:
try:
from pypyscrypt_inline import *
except ImportError:
pass
else:
_done = True
... |
# First, try loading libscrypt
_done = False
try:
from pylibscrypt import *
except ImportError:
pass
else:
_done = True
# If that didn't work, try the scrypt module
if not _done:
try:
from pyscrypt import *
except ImportError:
pass
else:
_done = True
# If that didn't w... | Use pyscrypt.py in package import if libscrypt isn't available | Use pyscrypt.py in package import if libscrypt isn't available
| Python | isc | jvarho/pylibscrypt,jvarho/pylibscrypt |
00aa59468c4dbfde282891f1396e29bd3f28fb62 | gunny/reveille/service.py | gunny/reveille/service.py | from twisted.application import internet
from twisted.application.service import Service
from twisted.internet import reactor
from autobahn.websocket import connectWS
class ControlService(Service):
pass
class PlayerService(Service):
def __init__(self, factory):
self.factory = factory
self.... | from twisted.application.service import Service
from twisted.internet import stdio
from autobahn.websocket import connectWS
class CoxswainService(Service):
def __init__(self, factory):
self.factory = factory
self.conn = None
def startService(self):
#self.factory(ReveilleCommandProto... | Rename classes to reflect intended use. | Rename classes to reflect intended use.
| Python | bsd-2-clause | davidblewett/gunny,davidblewett/gunny |
9938678e05270c06d328aeb466ab827bab232e3a | solar_neighbourhood/prepare_data_add_kinematics.py | solar_neighbourhood/prepare_data_add_kinematics.py | """
Add very large RV errors for stars with no known RVs.
Convert to cartesian.
"""
import numpy as np
import sys
sys.path.insert(0, '..')
from chronostar import tabletool
from astropy.table import Table
datafile = Table.read('../data/ScoCen_box_result.fits')
d = Table.read(datafile)
# Set missing radial velocities ... | """
Add very large RV errors for stars with no known RVs.
Convert to cartesian.
"""
import numpy as np
import sys
sys.path.insert(0, '..')
from chronostar import tabletool
from astropy.table import Table
datafile = '../data/ScoCen_box_result.fits')
d = tabletool.read(datafile)
# Set missing radial velocities (nan) t... | Convert entire table to cartesian | Convert entire table to cartesian
| Python | mit | mikeireland/chronostar,mikeireland/chronostar,mikeireland/chronostar,mikeireland/chronostar |
364d83c8add1fdde679aa2823ae94ad7f264cb48 | raco/relation_key.py | raco/relation_key.py | """Representation of a Myria relation key.
Myria relations are identified by a tuple of user, program, relation_name."""
class RelationKey(object):
def __init__(self, user='public', program='adhoc', relation=None):
assert relation
self.user = user
self.program = program
self.relati... | """Representation of a Myria relation key.
Myria relations are identified by a tuple of user, program, relation_name."""
class RelationKey(object):
def __init__(self, user='public', program='adhoc', relation=None):
assert relation
self.user = user
self.program = program
self.relati... | Add hash function to RelationKey | Add hash function to RelationKey
| Python | bsd-3-clause | uwescience/raco,uwescience/raco,uwescience/raco,uwescience/raco,uwescience/raco |
93a23b3aed48da6953914036ae488c5b3ab891c7 | scikits/audiolab/soundio/alsa.py | scikits/audiolab/soundio/alsa.py | import numpy as np
from _alsa import card_name, card_indexes, asoundlib_version
from _alsa import Device, AlsaException
def play(input, samplerate = 48000):
if input.ndim == 1:
n = input.size
nc = 1
elif input.ndim == 2:
n, nc = input.shape
else:
raise ValueError("Only ndim... | import numpy as np
from _alsa import card_name, card_indexes, asoundlib_version
from _alsa import Device, AlsaException
def play(input, samplerate = 48000):
if input.ndim == 1:
n = input.size
nc = 1
elif input.ndim == 2:
n, nc = input.shape
else:
raise ValueError("Only ndim... | Check input dtype before creating pcm device. | Check input dtype before creating pcm device.
| Python | lgpl-2.1 | cournape/audiolab,cournape/audiolab,cournape/audiolab |
9c650cb3fb37e8c96ef9642af553ce77a28a1587 | problem-static/Intro-Eval_50/admin/eval.py | problem-static/Intro-Eval_50/admin/eval.py | #!/usr/bin/python2.7
import sys
del __builtins__.__dict__['__import__']
del __builtins__.__dict__['reload']
flag = "eval_is_fun"
class UnbufferedStream(object):
def __init__(self, stream):
self.stream = stream
def write(self, data):
self.stream.write(data)
self.stream.flush()
def... | #!/usr/bin/python2.7
import sys
del __builtins__.__dict__['__import__']
del __builtins__.__dict__['reload']
flag = "eval_is_fun"
class UnbufferedStream(object):
def __init__(self, stream):
self.stream = stream
def write(self, data):
self.stream.write(data)
self.stream.flush()
def... | Move welcome message to outside the loop | Move welcome message to outside the loop
| Python | mit | james9909/IntroCTF,james9909/IntroCTF,james9909/IntroCTF,james9909/IntroCTF,james9909/IntroCTF,james9909/IntroCTF |
1bbffc2152ea1c48b47153005beeb2974b682f3c | bot/actions/action.py | bot/actions/action.py | from bot.api.api import Api
from bot.storage import Config, State, Cache
from bot.utils.dictionaryobject import DictionaryObject
class Event(DictionaryObject):
pass
class Update(Event):
def __init__(self, update, is_pending):
super().__init__()
self.update = update
self.is_pending = ... | from bot.api.api import Api
from bot.storage import Config, State, Cache
from bot.utils.dictionaryobject import DictionaryObject
class Event(DictionaryObject):
pass
class Update(Event):
def __init__(self, update, is_pending):
super().__init__()
self.update = update
self.is_pending = ... | Fix for_each incorrectly using lazy map operator | Fix for_each incorrectly using lazy map operator
| Python | agpl-3.0 | alvarogzp/telegram-bot,alvarogzp/telegram-bot |
eb7ff9cec9360af0b5c18915164a54d4755e657b | mistraldashboard/dashboards/mistral/executions/tables.py | mistraldashboard/dashboards/mistral/executions/tables.py | # -*- coding: utf-8 -*-
#
# Copyright 2014 - StackStorm, Inc.
#
# 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 ... | # -*- coding: utf-8 -*-
#
# Copyright 2014 - StackStorm, Inc.
#
# 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 ... | Add Task's output and parameters columns | Add Task's output and parameters columns
Change-Id: I98f57a6a0178bb7258d82f3a165127f060f42f7b
Implements: blueprint mistral-ui
| Python | apache-2.0 | openstack/mistral-dashboard,openstack/mistral-dashboard,openstack/mistral-dashboard |
557cf0bc733c49e973a12bd14fb596af6a7fb5ff | refugeedata/admin.py | refugeedata/admin.py | from django.contrib import admin
from refugeedata import models, forms
class NumberAdmin(admin.ModelAdmin):
list_display = ("number", "short_id", "active")
class BatchAdmin(admin.ModelAdmin):
list_display = ("registration_number_format", "data_file")
def get_form(self, request, obj=None, **kwargs):
... | from django.core.management import call_command
from django.contrib import admin
from refugeedata import models, forms
class NumberAdmin(admin.ModelAdmin):
list_display = ("number", "short_id", "active")
class BatchAdmin(admin.ModelAdmin):
list_display = ("registration_number_format", "data_file")
d... | Call export_card_data on batch save | Call export_card_data on batch save
| Python | mit | ukch/refugeedata,ukch/refugeedata,ukch/refugeedata,ukch/refugeedata |
a4fa3b9866ac9712f029c7cabe64121f80875207 | biobox_cli/main.py | biobox_cli/main.py | """
biobox - A command line interface for running biobox Docker containers
Usage:
biobox <command> <biobox_type> <image> [<args>...]
Options:
-h, --help Show this screen.
-v, --version Show version.
Commands:
run Run a biobox Docker image with input parameters
verify Verify that a D... | """
biobox - A command line interface for running biobox Docker containers
Usage:
biobox <command> <biobox_type> <image> [<args>...]
Options:
-h, --help Show this screen.
-v, --version Show version.
Commands:
run Run a biobox Docker image with input parameters
verify Verify that a D... | Use str methods instead of string module | Use str methods instead of string module
| Python | mit | bioboxes/command-line-interface,pbelmann/command-line-interface,michaelbarton/command-line-interface,michaelbarton/command-line-interface,bioboxes/command-line-interface,pbelmann/command-line-interface |
a6804dd0baefbbd9681edc2f0ba0ec13e84f5cc3 | nimp/utilities/paths.py | nimp/utilities/paths.py | # -*- coding: utf-8 -*-
import os
import os.path
import sys
import fnmatch
import glob
from nimp.utilities.logging import *
from nimp.utilities.system import *
#-------------------------------------------------------------------------------
def split_path(path):
splitted_path = []
while True:
(path, ... | # -*- coding: utf-8 -*-
import os
import os.path
import sys
import fnmatch
import glob
from nimp.utilities.logging import *
from nimp.utilities.system import *
#-------------------------------------------------------------------------------
def split_path(path):
splitted_path = []
while True:
(path, ... | Fix case where path is None in sanitize_path | Fix case where path is None in sanitize_path
| Python | mit | dontnod/nimp |
65c22394fad7929a7de1e78be7569a2895915dc9 | protocols/admin.py | protocols/admin.py | from django.contrib import admin
from .models import Protocol, Topic, Institution
class ProtocolAdmin(admin.ModelAdmin):
list_display = ['number', 'start_time', 'get_topics', 'information', 'majority', 'current_majority', 'institution']
list_display_links = ['number']
list_filter = ['institution__name',... | from django.contrib import admin
from .models import Protocol, Topic, Institution
class ProtocolAdminIndex(admin.ModelAdmin):
list_display = ['number', 'start_time', 'get_topics', 'information', 'majority', 'current_majority', 'institution']
list_display_links = ['number']
list_filter = ['institution__n... | Add Topics index page customization | Add Topics index page customization
| Python | mit | Hackfmi/Diaphanum,Hackfmi/Diaphanum |
22326bdd9265d8ae97055cbcc1f64939dd6bfcda | reviewboard/notifications/templatetags/markdown_email.py | reviewboard/notifications/templatetags/markdown_email.py | from __future__ import unicode_literals
import markdown
from django import template
from django.utils.safestring import mark_safe
from djblets.markdown import markdown_unescape
register = template.Library()
@register.filter
def markdown_email_html(text, is_rich_text):
if not is_rich_text:
return text
... | from __future__ import unicode_literals
import markdown
from django import template
from django.utils.safestring import mark_safe
from djblets.markdown import markdown_unescape
register = template.Library()
@register.filter
def markdown_email_html(text, is_rich_text):
if not is_rich_text:
return text
... | Remove a legacy Markdown extension when generating e-mails. | Remove a legacy Markdown extension when generating e-mails.
The recent updates for using Python-Markdown 3.x removed the
`smart_strong` extension from the main Markdown procssing, but failed to
remove it for the list of extensions used in e-mails. This is a trivial
change that simply removes that entry.
| Python | mit | reviewboard/reviewboard,chipx86/reviewboard,reviewboard/reviewboard,reviewboard/reviewboard,chipx86/reviewboard,reviewboard/reviewboard,chipx86/reviewboard,chipx86/reviewboard |
681cc1dc53851a2d127b4c00fc4e7d9e54bd8fba | cms/envs/devstack_docker.py | cms/envs/devstack_docker.py | """ Overrides for Docker-based devstack. """
from .devstack import * # pylint: disable=wildcard-import, unused-wildcard-import
# Docker does not support the syslog socket at /dev/log. Rely on the console.
LOGGING['handlers']['local'] = LOGGING['handlers']['tracking'] = {
'class': 'logging.NullHandler',
}
LOGGIN... | """ Overrides for Docker-based devstack. """
from .devstack import * # pylint: disable=wildcard-import, unused-wildcard-import
# Docker does not support the syslog socket at /dev/log. Rely on the console.
LOGGING['handlers']['local'] = LOGGING['handlers']['tracking'] = {
'class': 'logging.NullHandler',
}
LOGGIN... | Set LMS_BASE setting for Studio | Set LMS_BASE setting for Studio
This allows previews in LMS to work properly.
ECOM-6634
| Python | agpl-3.0 | jolyonb/edx-platform,ahmedaljazzar/edx-platform,proversity-org/edx-platform,raccoongang/edx-platform,edx/edx-platform,hastexo/edx-platform,fintech-circle/edx-platform,Stanford-Online/edx-platform,eduNEXT/edunext-platform,jolyonb/edx-platform,eduNEXT/edx-platform,ESOedX/edx-platform,a-parhom/edx-platform,prarthitm/edxpl... |
594cd5d490786bbbdcf877d8c155530c36acd2c1 | src/services/TemperatureMonitor/src/temperature.py | src/services/TemperatureMonitor/src/temperature.py | import smbus
class TemperatureSensor:
temp_history = []
last_temp = 0
def __init__(self, address):
self.bus = smbus.SMBus(1)
self.address = address
def get_temp(self):
MSB = self.bus.read_byte_data(self.address, 0)
LSB = self.bus.read_byte_data(self.address, 1)
... | import smbus
class TemperatureSensor:
temp_history = []
last_temp = 0
def __init__(self, address):
self.bus = smbus.SMBus(1)
self.address = address
def get_temp(self):
MSB = self.bus.read_byte_data(self.address, 0)
LSB = self.bus.read_byte_data(self.address, 1)
... | Remove Smoothing From Temp Sensor | Remove Smoothing From Temp Sensor
| Python | mit | IAPark/PITherm |
72d33ea47458cace13dac920ce2a82e55f83caba | statsmodels/stats/tests/test_outliers_influence.py | statsmodels/stats/tests/test_outliers_influence.py | from numpy.testing import assert_almost_equal
from statsmodels.datasets import statecrime, get_rdataset
from statsmodels.regression.linear_model import OLS
from statsmodels.stats.outliers_influence import reset_ramsey
from statsmodels.stats.outliers_influence import variance_inflation_factor
from statsmodels.tools imp... | from numpy.testing import assert_almost_equal
from statsmodels.datasets import statecrime
from statsmodels.regression.linear_model import OLS
from statsmodels.stats.outliers_influence import reset_ramsey
from statsmodels.stats.outliers_influence import variance_inflation_factor
from statsmodels.tools import add_consta... | Add pandas dataframe capability in variance_inflation_factor | ENH: Add pandas dataframe capability in variance_inflation_factor
| Python | bsd-3-clause | bashtage/statsmodels,josef-pkt/statsmodels,josef-pkt/statsmodels,bashtage/statsmodels,bashtage/statsmodels,statsmodels/statsmodels,josef-pkt/statsmodels,josef-pkt/statsmodels,statsmodels/statsmodels,statsmodels/statsmodels,statsmodels/statsmodels,josef-pkt/statsmodels,josef-pkt/statsmodels,statsmodels/statsmodels,basht... |
c820e3ed4d78b975a6bdff54a2ecae26354ae10e | tests/test_itunes.py | tests/test_itunes.py | """
test_itunes.py
Copyright © 2015 Alex Danoff. All Rights Reserved.
2015-08-02
This file tests the functionality provided by the itunes module.
"""
import unittest
from itunes.itunes import parse_value
class ITunesTests(unittest.TestCase):
"""
Test cases for iTunes functionality.
"""
def test_pa... | """
test_itunes.py
Copyright © 2015 Alex Danoff. All Rights Reserved.
2015-08-02
This file tests the functionality provided by the itunes module.
"""
import unittest
from datetime import datetime
from itunes.itunes import parse_value
class ITunesTests(unittest.TestCase):
"""
Test cases for iTunes functiona... | Add `parse_value` test for AppleScript dates | Add `parse_value` test for AppleScript dates
Added a test case to `parse_value` to parse dates returned in
AppleScript responses.
| Python | mit | adanoff/iTunesTUI |
d69b137bd19e0363173b120ff4f68becc6be7b3c | mama_cas/tests/backends.py | mama_cas/tests/backends.py | from django.contrib.auth.backends import ModelBackend
from django.contrib.auth.models import User
class ExceptionBackend(ModelBackend):
"""Raise an exception on authentication for testing purposes."""
def authenticate(self, username=None, password=None):
raise Exception
class CaseInsensitiveBackend(... | from django.contrib.auth.backends import ModelBackend
from mama_cas.compat import get_user_model
class ExceptionBackend(ModelBackend):
"""Raise an exception on authentication for testing purposes."""
def authenticate(self, username=None, password=None):
raise Exception
class CaseInsensitiveBackend(... | Use get_user_model within test backend | Use get_user_model within test backend
| Python | bsd-3-clause | orbitvu/django-mama-cas,harlov/django-mama-cas,forcityplatform/django-mama-cas,jbittel/django-mama-cas,orbitvu/django-mama-cas,forcityplatform/django-mama-cas,jbittel/django-mama-cas,harlov/django-mama-cas |
46077269450f98505308736251b3f08ed3c6827f | scripts/poweron/DRAC.py | scripts/poweron/DRAC.py | import subprocess, sys, os.path
class DRAC_NO_SUPP_PACK(Exception):
"""Base Exception class for all transfer plugin errors."""
def __init__(self, *args):
Exception.__init__(self, *args)
class DRAC_POWERON_FAILED(Exception):
"""Base Exception class for all transfer plugin errors."""
def... | import subprocess, sys, os.path
class DRAC_NO_SUPP_PACK(Exception):
"""Base Exception class for all transfer plugin errors."""
def __init__(self, *args):
Exception.__init__(self, *args)
class DRAC_POWERON_FAILED(Exception):
"""Base Exception class for all transfer plugin errors."""
def... | Change path to the supplemental pack | CA-40618: Change path to the supplemental pack
Signed-off-by: Javier Alvarez-Valle <cf4c8668a0b4c5e013f594a6940d05b3d4d9ddcf@citrix.com>
| Python | lgpl-2.1 | Frezzle/xen-api,vasilenkomike/xen-api,simonjbeaumont/xen-api,euanh/xen-api,cheng-z/xen-api,jjd27/xen-api,vasilenkomike/xen-api,rafalmiel/xen-api,robertbreker/xen-api,koushikcgit/xen-api,huizh/xen-api,agimofcarmen/xen-api,cheng--zhang/xen-api,salvocambria/xen-api,jjd27/xen-api,djs55/xen-api,thomassa/xen-api,huizh/xen-ap... |
1fe22f9750c618ede99f9b0a0d088aa67b7929a1 | stock_available_unreserved/models/quant.py | stock_available_unreserved/models/quant.py | # Copyright 2018 Camptocamp SA
# Copyright 2016-19 ForgeFlow S.L. (https://www.forgeflow.com)
# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html).
from odoo import api, fields, models
class StockQuant(models.Model):
_inherit = "stock.quant"
contains_unreserved = fields.Boolean(
stri... | # Copyright 2018 Camptocamp SA
# Copyright 2016-19 ForgeFlow S.L. (https://www.forgeflow.com)
# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html).
from odoo import api, fields, models
class StockQuant(models.Model):
_inherit = "stock.quant"
contains_unreserved = fields.Boolean(
stri... | Fix compute contains_unreserved on NewId records | [FIX] Fix compute contains_unreserved on NewId records
| Python | agpl-3.0 | OCA/stock-logistics-warehouse,OCA/stock-logistics-warehouse,OCA/stock-logistics-warehouse,OCA/stock-logistics-warehouse |
828b78767c17419513337ca29b5c2dab08995714 | ctypeslib/test/test_dynmodule.py | ctypeslib/test/test_dynmodule.py | # Basic test of dynamic code generation
import unittest
import os, glob
import stdio
from ctypes import POINTER, c_int
class DynModTest(unittest.TestCase):
def tearDown(self):
for fnm in glob.glob(stdio._gen_basename + ".*"):
try:
os.remove(fnm)
except IOError:
... | # Basic test of dynamic code generation
import unittest
import os, glob
import stdio
from ctypes import POINTER, c_int
class DynModTest(unittest.TestCase):
def test_fopen(self):
self.failUnlessEqual(stdio.fopen.restype, POINTER(stdio.FILE))
self.failUnlessEqual(stdio.fopen.argtypes, [stdio.STRING... | Remove now useless TearDown method. | Remove now useless TearDown method.
git-svn-id: ac2c3632cb6543e7ab5fafd132c7fe15057a1882@53797 6015fed2-1504-0410-9fe1-9d1591cc4771
| Python | mit | trolldbois/ctypeslib,luzfcb/ctypeslib,trolldbois/ctypeslib,luzfcb/ctypeslib,luzfcb/ctypeslib,trolldbois/ctypeslib |
23e3197f15d13445defe6ec7cfb4f08484089068 | tests/test_scripts/test_simulate_data.py | tests/test_scripts/test_simulate_data.py | import json
import numpy as np
from click.testing import CliRunner
from fastimgproto.scripts.simulate_data import cli as sim_cli
def test_simulate_data():
runner = CliRunner()
with runner.isolated_filesystem():
output_filename = 'simdata.npz'
result = runner.invoke(sim_cli,
... | import json
import numpy as np
from click.testing import CliRunner
from fastimgproto.scripts.simulate_data import cli as sim_cli
def test_simulate_data():
runner = CliRunner()
with runner.isolated_filesystem():
output_filename = 'simdata.npz'
result = runner.invoke(sim_cli,
... | Use few nsteps for testing sim-script | Use few nsteps for testing sim-script
| Python | apache-2.0 | SKA-ScienceDataProcessor/FastImaging-Python,SKA-ScienceDataProcessor/FastImaging-Python |
5972644fe7d0267849440d8e60509baba6e013a3 | test/test_exception.py | test/test_exception.py | from mock import MagicMock
import pyaem
import unittest
class TestPyAemException(unittest.TestCase):
def test_init(self):
exception = pyaem.PyAemException(123, 'somemessage')
self.assertEqual(exception.code, 123)
self.assertEqual(exception.message, 'somemessage')
if __name__ == '__main__':
unittes... | import pyaem
import unittest
class TestException(unittest.TestCase):
def test_init(self):
exception = pyaem.PyAemException(123, 'somemessage')
self.assertEqual(exception.code, 123)
self.assertEqual(exception.message, 'somemessage')
if __name__ == '__main__':
unittest.main() | Rename class name to be consistent with file name. Remove unused import. | Rename class name to be consistent with file name. Remove unused import.
| Python | mit | Sensis/pyaem,wildone/pyaem |
dfea77df6e6ba27bada1c80da6efab392507736b | forklift/services/satellite.py | forklift/services/satellite.py | #
# Copyright 2014 Infoxchange Australia
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to... | #
# Copyright 2014 Infoxchange Australia
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to... | Fix making threads daemonic on Python 3.2 | Fix making threads daemonic on Python 3.2
| Python | apache-2.0 | infoxchange/docker-forklift,infoxchange/docker-forklift |
d41af20b1bdf5b630962a2e474b5d9c7ed62cd5c | nuxeo-drive-client/nxdrive/gui/resources.py | nuxeo-drive-client/nxdrive/gui/resources.py | """Helper to lookup UI resources from package"""
import re
import os
from nxdrive.logging_config import get_logger
log = get_logger(__name__)
def find_icon(icon_filename):
"""Find the FS path of an icon on various OS binary packages"""
import nxdrive
nxdrive_path = os.path.dirname(nxdrive.__file__)
... | """Helper to lookup UI resources from package"""
import os
from nxdrive.logging_config import get_logger
from nxdrive.utils import find_resource_dir
log = get_logger(__name__)
def find_icon(icon_filename):
"""Find the FS path of an icon in various OS binary packages"""
import nxdrive
nxdrive_path = os.p... | Use generic resource directory finder for icon files | NXP-12694: Use generic resource directory finder for icon files
| Python | lgpl-2.1 | arameshkumar/base-nuxeo-drive,IsaacYangSLA/nuxeo-drive,rsoumyassdi/nuxeo-drive,arameshkumar/nuxeo-drive,ssdi-drive/nuxeo-drive,DirkHoffmann/nuxeo-drive,arameshkumar/nuxeo-drive,arameshkumar/base-nuxeo-drive,DirkHoffmann/nuxeo-drive,loopingz/nuxeo-drive,rsoumyassdi/nuxeo-drive,DirkHoffmann/nuxeo-drive,arameshkumar/nuxeo... |
72dea9616a84cefd8424f965060552c84cfd241d | tests/test_luabject.py | tests/test_luabject.py | try:
import unittest2 as unittest
except ImportError:
import unittest
from village import _luabject
class TestDirect(unittest.TestCase):
def test_new(self):
state = _luabject.new()
# PyCObject isn't available to assertIsInstance, so:
self.assertEqual(type(state).__name__, 'PyCOb... | try:
import unittest2 as unittest
except ImportError:
import unittest
from village import _luabject
class TestDirect(unittest.TestCase):
def test_new(self):
state = _luabject.new()
# PyCObject isn't available to assertIsInstance, so:
self.assertEqual(type(state).__name__, 'PyCOb... | Test unrunnable script exceptions too | Test unrunnable script exceptions too
| Python | mit | markpasc/luabject,markpasc/luabject |
9f20f232a9507f0002adc682a87bb792f6fbdd4e | django_plim/template.py | django_plim/template.py | #!/usr/bin/env python
#-*- coding: UTF-8 -*-
from functools import partial
from django.conf import settings
from plim import preprocessor as plim_preprocessor
from mako.template import Template as MakoTemplate
from mako.lookup import TemplateLookup
lookup = TemplateLookup(directories=settings.TEMPLATE_DIRS)
Templat... | #!/usr/bin/env python
#-*- coding: UTF-8 -*-
from functools import partial
from django.conf import settings
from plim import preprocessor as plim_preprocessor
from mako.template import Template as MakoTemplate
from mako.lookup import TemplateLookup
from django.template.loaders import app_directories
lookup = Templa... | Add example code copied from django doc | Add example code copied from django doc
| Python | mit | imom0/django-plim |
c53824a3427235c814cfe35c5c85fd5e1e312b40 | i3/.config/i3/scripts/lock_screen/lock_screen.py | i3/.config/i3/scripts/lock_screen/lock_screen.py | #!/usr/bin/env python
from subprocess import check_call, CalledProcessError
from tempfile import NamedTemporaryFile
from dpms import DPMS
from mss import mss
from PIL import Image, ImageFilter
GAUSSIAN_BLUR_RADIUS = 5
SCREEN_TIMEOUT = (5, 5, 5) # Standby, Suspend, Off
# Get current DPMS settings
dpms = DPMS()
curr... | #!/usr/bin/env python
from subprocess import check_call, CalledProcessError
from tempfile import NamedTemporaryFile
from dpms import DPMS
from mss import mss
from PIL import Image, ImageFilter
GAUSSIAN_BLUR_RADIUS = 5
SCREEN_TIMEOUT = (5, 5, 5) # Standby, Suspend, Off
# Get current DPMS settings
dpms = DPMS()
curr... | Remove call to GetTimeouts() after SetTimeouts() | i3: Remove call to GetTimeouts() after SetTimeouts()
Fixed in commit 72e984a54049c77208546b8565cece100e87be48 from
m45t3r/python-dpms.
| Python | mit | m45t3r/dotfiles,m45t3r/dotfiles,m45t3r/dotfiles |
55c72a5297244ba51fba5ebc5b71efc3001e0dd4 | otz/__init__.py | otz/__init__.py | from otz.Timestream import CalibrationTimestream, CapturedTimestream
from otz.Calibration import Calibration
| from otz.Timestream import CalibrationTimestream, CapturedTimestream
from otz.Calibration import Calibration
from otz.Beam import Beam, Bead
| Add Beam, Bead to main module | Add Beam, Bead to main module
| Python | unlicense | ghallsimpsons/optical_tweezers |
cd75c139910e8968e5262d0f0f5289119b258f21 | phileo/views.py | phileo/views.py | from django.contrib.auth.decorators import login_required
from django.contrib.contenttypes.models import ContentType
from django.http import HttpResponse
from django.utils import simplejson as json
from django.shortcuts import get_object_or_404, redirect
from django.views.decorators.http import require_POST
from phil... | from django.contrib.auth.decorators import login_required
from django.contrib.contenttypes.models import ContentType
from django.http import HttpResponse
from django.utils import simplejson as json
from django.shortcuts import get_object_or_404, redirect
from django.views.decorators.http import require_POST
from phil... | Remove user from count query to show likes count for all users for obj | Remove user from count query to show likes count for all users for obj
| Python | mit | pinax/phileo,jacobwegner/phileo,rizumu/pinax-likes,rizumu/pinax-likes,jacobwegner/phileo,pinax/pinax-likes,pinax/phileo |
8b0e39eec8a82fd3f5a424ec75678426b2bf523e | cinder/version.py | cinder/version.py | # Copyright 2011 OpenStack Foundation
#
# 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 l... | # Copyright 2011 OpenStack Foundation
#
# 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 l... | Remove runtime dep on python-pbr, python-d2to1 | Remove runtime dep on python-pbr, python-d2to1
Requires RPM spec to fill in REDHATCINDERVERSION.
| Python | apache-2.0 | alex8866/cinder,alex8866/cinder |
9c6739830ea8ccfbe697bc691de001a42f01f9c6 | serial_protocol/test.py | serial_protocol/test.py | import serial
import time
import binascii
import struct
def establishConnection():
# Define Constants
SERIAL_DEVICE = "/dev/ttyACM0"
# Establish Connection
ser = serial.Serial(SERIAL_DEVICE, 9600)
time.sleep(2)
print("Connection Established")
return ser
# Each motor speed is a float from -1.0 to 1.0
d... | import serial
import time
import binascii
import struct
def establishConnection():
# Define Constants
SERIAL_DEVICE = "/dev/ttyACM0"
# Establish Connection
ser = serial.Serial(SERIAL_DEVICE, 9600)
time.sleep(2)
print("Connection Established")
return ser
# Each motor speed is a float from -1.0 to 1.0
d... | Write each byte at a time in protocol | Write each byte at a time in protocol
| Python | mit | zacharylawrence/ENEE408I-Team-9,zacharylawrence/ENEE408I-Team-9,zacharylawrence/ENEE408I-Team-9 |
072bc480cbc489cd89d03405026f152934893b7e | go/routers/keyword/view_definition.py | go/routers/keyword/view_definition.py | from django import forms
from go.router.view_definition import RouterViewDefinitionBase, EditRouterView
class KeywordForm(forms.Form):
keyword = forms.CharField()
target_endpoint = forms.CharField()
class BaseKeywordFormSet(forms.formsets.BaseFormSet):
@staticmethod
def initial_from_config(data):
... | from django import forms
from go.router.view_definition import RouterViewDefinitionBase, EditRouterView
class KeywordForm(forms.Form):
keyword = forms.CharField()
target_endpoint = forms.CharField()
class BaseKeywordFormSet(forms.formsets.BaseFormSet):
@staticmethod
def initial_from_config(data):
... | Revert "Remove unnecessary and broken DELETE check." | Revert "Remove unnecessary and broken DELETE check."
This reverts commit 7906153b4718f34ed31c193a8e80b171e567209c.
Reverting commit accidentally commited straight to develop.
| Python | bsd-3-clause | praekelt/vumi-go,praekelt/vumi-go,praekelt/vumi-go,praekelt/vumi-go |
939998db349c364aa0f5ba4705d4feb2da7104d5 | nn/flags.py | nn/flags.py | import functools
import tensorflow as tf
FLAGS = tf.app.flags.FLAGS
tf.app.flags.DEFINE_string("batch-size", 64, "")
tf.app.flags.DEFINE_float("dropout-prob", 0, "")
tf.app.flags.DEFINE_string("word-file", None, "")
tf.app.flags.DEFINE_integer("num-threads-per-queue", 2, "")
tf.app.flags.DEFINE_integer("queue-capac... | import functools
import tensorflow as tf
FLAGS = tf.app.flags.FLAGS
tf.app.flags.DEFINE_string("batch-size", 64, "")
tf.app.flags.DEFINE_float("dropout-prob", 0, "")
tf.app.flags.DEFINE_string("word-file", None, "")
tf.app.flags.DEFINE_integer("num-threads-per-queue", 2, "")
tf.app.flags.DEFINE_integer("queue-capac... | Fix float type flag definition | Fix float type flag definition
| Python | unlicense | raviqqe/tensorflow-extenteten,raviqqe/tensorflow-extenteten |
10db5e8b893a84e765162535f64e1ede81d48b47 | empty_check.py | empty_check.py | from django.core.exceptions import ValidationError
class EmptyCheck(object):
def __call__(self, value):
if len(value.strip()) == 0:
raise ValidationError("Value cannot be empty")
| from django.core.exceptions import ValidationError
# Usage example in a custom form
# firstname = forms.CharField(validators = [EmptyCheck()])
class EmptyCheck(object):
def __call__(self, value):
if len(value.strip()) == 0:
raise ValidationError("Value cannot be empty")
| Add comment to show usage example | Add comment to show usage example | Python | mit | vishalsodani/django-empty-check-validator |
34812fe2deec64229efd4119640f3c2ddf0ed415 | visualize.py | visualize.py | '''
Create a visual representation of the various DAGs defined
'''
import sys
import requests
import networkx as nx
import matplotlib.pyplot as plt
if __name__ == '__main__':
g = nx.DiGraph()
labels = {
'edges': {},
'nodes': {},
}
nodes = {}
for routeKey, routeMap in requests.ge... | '''
Create a visual representation of the various DAGs defined
'''
import sys
import requests
import networkx as nx
import matplotlib.pyplot as plt
if __name__ == '__main__':
g = nx.DiGraph()
labels = {
'edges': {},
'nodes': {},
}
for routeKey, routeMap in requests.get(sys.argv[1]).j... | Make the sprint layout a bit easier to look at | Make the sprint layout a bit easier to look at
| Python | mit | jacksontj/dnms,jacksontj/dnms |
057510c78f80c3592c562006413049ab1292d0a3 | ipaqe_provision_hosts/backend/base.py | ipaqe_provision_hosts/backend/base.py | # author: Milan Kubik
NOT_IMPLEMENTED_MSG = "You need to override this method in a subclass"
class IDMBackendException(Exception):
pass
class VMsNotCreatedError(IDMBackendException):
pass
class IDMBackendMissingName(IDMBackendException):
pass
class IDMBackendBase(object):
"""IDMBackendBase class... | # author: Milan Kubik
NOT_IMPLEMENTED_MSG = "You need to override this method in a subclass"
from ipaqe_provision_hosts.errors import IPAQEProvisionerError
class VMsNotCreatedError(IPAQEProvisionerError):
pass
class IDMBackendBase(object):
"""IDMBackendBase class
This class represents a contract b... | Replace the exceptions in backend classes | Replace the exceptions in backend classes
| Python | mit | apophys/ipaqe-provision-hosts |
8a43cf58791a665a4fc23bc5d0911af61f7e1fb6 | qipr_approver/approver/views/similar_projects.py | qipr_approver/approver/views/similar_projects.py | from django.shortcuts import redirect
from approver.workflows import project_crud
from approver.decorators import login_required
import approver.utils as utils
from django.core.urlresolvers import reverse
@login_required
def similar_projects(request, project_id=None,from_page=None):
project = project_crud.ge... | from django.shortcuts import redirect
from django.core.urlresolvers import reverse
from django.contrib.auth.decorators import login_required
from approver.workflows import project_crud
import approver.utils as utils
@login_required
def similar_projects(request, project_id=None,from_page=None):
project = project... | Add shib auth to similar projects page | Add shib auth to similar projects page
| Python | apache-2.0 | DevMattM/qipr_approver,DevMattM/qipr_approver,ctsit/qipr_approver,ctsit/qipr_approver,ctsit/qipr_approver,DevMattM/qipr_approver,DevMattM/qipr_approver,PFWhite/qipr_approver,DevMattM/qipr_approver,PFWhite/qipr_approver,ctsit/qipr_approver,PFWhite/qipr_approver,ctsit/qipr_approver,PFWhite/qipr_approver,PFWhite/qipr_appr... |
896b385f983ecf939bdc2ea938b9949fdc3fdbb8 | colorise/color_tools.py | colorise/color_tools.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Functions for converting and comparing colors."""
import colorsys
import math
import operator
def hls_to_rgb(hue, lightness, saturation):
"""Convert HLS (hue, lightness, saturation) values to RGB."""
return tuple(int(math.ceil(c * 255.))
for ... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Functions for converting and comparing colors."""
import colorsys
import math
import operator
def hls_to_rgb(hue, lightness, saturation):
"""Convert HLS (hue, lightness, saturation) values to RGB."""
return tuple(int(math.ceil(c * 255.))
for ... | Remove unused color distance function | Remove unused color distance function
| Python | bsd-3-clause | MisanthropicBit/colorise |
e174a898595664ff291cbf8ccda0f1c404a73575 | control/server.py | control/server.py | import asyncore
import socket
from logging import error, info, warning
from client import Client
class Server(asyncore.dispatcher):
def __init__(self, port, host="localhost"):
asyncore.dispatcher.__init__(self)
self.create_socket()
self.set_reuse_addr()
self.bind((host, port))
... | import asyncore
import socket
from logging import error, info, warning
from client import Client
class Server(asyncore.dispatcher):
def __init__(self, port, connect_fn=None, msg_fn=None, close_fn=None):
asyncore.dispatcher.__init__(self)
self.create_socket()
self.set_reuse_addr()
... | Remove disconnected client from clients list, allow client callbacks to be set in constructor. | Remove disconnected client from clients list, allow client callbacks to be set in constructor.
| Python | mit | zwarren/morse-car-controller,zwarren/morse-car-controller |
91720739af3c7b35e331949cdd64a98023e23799 | parkings/api/public/parking_area.py | parkings/api/public/parking_area.py | from rest_framework import viewsets
from rest_framework_gis.pagination import GeoJsonPagination
from rest_framework_gis.serializers import GeoFeatureModelSerializer, GeometrySerializerMethodField
from parkings.models import ParkingArea
class ParkingAreaSerializer(GeoFeatureModelSerializer):
wgs84_areas = Geometr... | from rest_framework import viewsets
from rest_framework_gis.pagination import GeoJsonPagination
from rest_framework_gis.serializers import GeoFeatureModelSerializer, GeometrySerializerMethodField
from parkings.models import ParkingArea
from ..common import WGS84InBBoxFilter
class ParkingAreaSerializer(GeoFeatureMod... | Add bbox to parking area view set | Add bbox to parking area view set
| Python | mit | tuomas777/parkkihubi |
d52034eddeb510acc367c87c88e4277994157338 | githubsetupircnotifications.py | githubsetupircnotifications.py | """
github-setup-irc-notifications - Configure all repositories in an organization
with irc notifications
"""
import argparse
import getpass
import sys
import github3
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--username')
parser.add_argument('--password')
parser.add_argumen... | """
github-setup-irc-notifications - Configure all repositories in an organization
with irc notifications
"""
import argparse
import getpass
import sys
import github3
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--username')
parser.add_argument('--password')
parser.add_argumen... | Create the hook for each repo | Create the hook for each repo
| Python | mit | kragniz/github-setup-irc-notifications |
ed4c80aa8e9ee628876c3cc96907ca407ee4ff5d | backend/scripts/ddirdenorm.py | backend/scripts/ddirdenorm.py | #!/usr/bin/env python
import rethinkdb as r
import optparse
if __name__ == "__main__":
parser = optparse.OptionParser()
parser.add_option("-p", "--port", dest="port",
help="rethinkdb port", default=30815)
(options, args) = parser.parse_args()
conn = r.connect('localhost', int(op... | #!/usr/bin/env python
import rethinkdb as r
import optparse
if __name__ == "__main__":
parser = optparse.OptionParser()
parser.add_option("-p", "--port", dest="port",
help="rethinkdb port", default=30815)
(options, args) = parser.parse_args()
conn = r.connect('localhost', int(op... | Handle non-existent files in the database. | Handle non-existent files in the database.
| Python | mit | materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org |
e7627ee439e2e4f17466bf124629ae353460a68d | __init__.py | __init__.py | # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2012 OpenERP - Team de Localización Argentina.
# https://launchpad.net/~openerp-l10n-ar-localization
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of t... | # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2012 OpenERP - Team de Localización Argentina.
# https://launchpad.net/~openerp-l10n-ar-localization
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of t... | Change product types are really dangerous!!! | [FIX] Change product types are really dangerous!!! | Python | agpl-3.0 | odoo-l10n-ar/l10n_ar_invoice |
30bd8b9b4d18579cdf9b723f82f35987c1ad9176 | __main__.py | __main__.py | from scanresults import ScanResults
import sys
sr = ScanResults()
sr.add_files(*sys.argv[1:])
sr.train()
out = sr.sentences()
if out is not None:
print(out)
| from scanresults import ScanResults
import sys
from argparse import ArgumentParser
parser = ArgumentParser(description='Generate markov text from a corpus')
parser.add_argument('-t','--train', default=2, type=int, metavar='train_n',
help="The size of the Markov state prefix to train the corpus on")... | Enable command-line args for configuration | Enable command-line args for configuration
| Python | bsd-3-clause | darrenpmeyer/scanresults,darrenpmeyer/scanresults |
5459dfc62e3a0d5b36b6d9405232382c1f8b663a | __init__.py | __init__.py | import sys
import os
sys.path.insert(0, os.path.dirname(__file__))
from . import multiscanner, storage
common = multiscanner.common
multiscan = multiscanner.multiscan
parse_reports = multiscanner.parse_reports
config_init = multiscanner.config_init
| import os
import sys
sys.path.insert(0, os.path.dirname(__file__))
from . import multiscanner
common = multiscanner.common
multiscan = multiscanner.multiscan
parse_reports = multiscanner.parse_reports
config_init = multiscanner.config_init
| Remove unused imports and sort | Remove unused imports and sort
| Python | mpl-2.0 | jmlong1027/multiscanner,jmlong1027/multiscanner,mitre/multiscanner,MITRECND/multiscanner,mitre/multiscanner,MITRECND/multiscanner,mitre/multiscanner,jmlong1027/multiscanner,jmlong1027/multiscanner |
15307ebe2c19c1a3983b0894152ba81fdde34619 | exp/descriptivestats.py | exp/descriptivestats.py | import pandas
import numpy
import matplotlib.pyplot as plt
def univariate_stats():
num_examples = 1000
z = pandas.Series(numpy.random.randn(num_examples))
# Minimum
print(z.min())
# Maximum
print(z.max())
# Mean
print(z.mean())
# Median
print(z.median())
# Variance
pri... | import pandas
import numpy
import matplotlib.pyplot as plt
def univariate_stats():
# Generate 1000 random numbers from a normal distribution
num_examples = 1000
z = pandas.Series(numpy.random.randn(num_examples))
# Minimum
print(z.min())
# Maximum
print(z.max())
# Mean
print(z.mea... | Add comment on dist of first function | Add comment on dist of first function | Python | mit | charanpald/tyre-hug |
3999e9812a766066dcccf6a4d07174144cb9f72d | wurstmineberg.45s.py | wurstmineberg.45s.py | #!/usr/local/bin/python3
import requests
people = requests.get('https://api.wurstmineberg.de/v2/people.json').json()
status = requests.get('https://api.wurstmineberg.de/v2/world/wurstmineberg/status.json').json()
print(len(status['list']))
print('---')
print('Version: {}|color=gray'.format(status['version']))
for w... | #!/usr/local/bin/python3
import requests
people = requests.get('https://api.wurstmineberg.de/v2/people.json').json()
status = requests.get('https://api.wurstmineberg.de/v2/world/wurstmineberg/status.json').json()
print(len(status['list']))
print('---')
print('Version: {ver}|href=http://minecraft.gamepedia.com/{ver}... | Add Minecraft Wiki link to version item | Add Minecraft Wiki link to version item
| Python | mit | wurstmineberg/bitbar-server-status |
5abac5e7cdc1d67ec6ed0996a5b132fae20af530 | compare_text_of_urls.py | compare_text_of_urls.py | #!/usr/bin/env python
from __future__ import print_function
import json
import os
from os.path import join, dirname, abspath
import subprocess
import sys
from get_text_from_url import process_page
def main(argv=None):
if argv is None:
argv = sys.argv
arg = argv[1:]
# Enter two URLs with a spac... | #!/usr/bin/env python
from __future__ import print_function
import json
import os
from os.path import join, dirname, abspath
import subprocess
import sys
from get_text_from_url import process_page
def main(argv=None):
if argv is None:
argv = sys.argv
arg = argv[1:]
# Enter two URLs with a spac... | Use the URLs input in the UI boxes | Use the URLs input in the UI boxes
Parse JSON from two separate URL input boxes, instead of using one input
box and parsing one long string containing both URLs.
| Python | agpl-3.0 | scraperwiki/difference-tool,scraperwiki/difference-tool,scraperwiki/difference-tool,scraperwiki/difference-tool |
c691c256682bec5f9a242ab71ab42d296bbf88a9 | nightreads/posts/admin.py | nightreads/posts/admin.py | from django.contrib import admin
# Register your models here.
| from django.contrib import admin
from .models import Post, Tag
admin.site.register(Post)
admin.site.register(Tag)
| Add `Post`, `Tag` models to Admin | Add `Post`, `Tag` models to Admin
| Python | mit | avinassh/nightreads,avinassh/nightreads |
4fe8a1c1b294f0d75a901d4e8e80f47f5583e44e | pages/lms/info.py | pages/lms/info.py | from e2e_framework.page_object import PageObject
from ..lms import BASE_URL
class InfoPage(PageObject):
"""
Info pages for the main site.
These are basically static pages, so we use one page
object to represent them all.
"""
# Dictionary mapping section names to URL paths
SECTION_PATH = {... | from e2e_framework.page_object import PageObject
from ..lms import BASE_URL
class InfoPage(PageObject):
"""
Info pages for the main site.
These are basically static pages, so we use one page
object to represent them all.
"""
# Dictionary mapping section names to URL paths
SECTION_PATH = {... | Fix for test failure introduced by basic auth changes | Fix for test failure introduced by basic auth changes
| Python | agpl-3.0 | edx/edx-e2e-tests,raeeschachar/edx-e2e-mirror,raeeschachar/edx-e2e-mirror,edx/edx-e2e-tests |
417ab5241c852cdcd072143bc2444f20f2117623 | tests/execution_profiles/capture_profile.py | tests/execution_profiles/capture_profile.py | import cProfile
from pqhelper import capture
def main():
cProfile.run('test_solution(catapult)')
def test_solution(board_string):
print capture.capture(board_string)
skeleton = '''
..*..*..
.gm..mg.
.ms..sm.
.rs..sr.
.ggmmgg.
.rsggsr.
.rsrrsr.
ssgssgss'''
giant_rat = '''
...mm...
..mrym..
.mgyrgm.
mygryg... | import cProfile
from pqhelper import capture
def main():
cProfile.run('test_solution(catapult)')
def test_solution(board_string):
board = capture.Board(board_string)
print capture.capture(board)
skeleton = '''
..*..*..
.gm..mg.
.ms..sm.
.rs..sr.
.ggmmgg.
.rsggsr.
.rsrrsr.
ssgssgss'''
giant_rat = '''
... | Update capture profiler to new spec of providing board instead of string. | Update capture profiler to new spec of providing board instead of string.
| Python | mit | kobejohn/PQHelper |
fb2cfe4759fb98de644932af17a247428b2cc0f5 | api/auth.py | api/auth.py | from django.http import HttpResponseForbidden
from django.contrib.auth.models import AnonymousUser
from api.models import AuthAPIKey
class APIKeyAuthentication(object):
def is_authenticated(self, request):
params = {}
for key,value in request.GET.items():
params[key.lower()] = value
... | from django.http import HttpResponseForbidden
from django.contrib.auth.models import AnonymousUser
from api.models import AuthAPIKey
class APIKeyAuthentication(object):
def is_authenticated(self, request):
params = {}
for key,value in request.GET.items():
params[key.lower()] = value
... | Fix Auth API key check causing error 500s | Fix Auth API key check causing error 500s
| Python | bsd-3-clause | nikdoof/test-auth |
a1d9312e1ac6f66aaf558652d890ac2a6bd67e40 | backend/loader/model/datafile.py | backend/loader/model/datafile.py | from dataitem import DataItem
class DataFile(DataItem):
def __init__(self, name, access, owner):
super(DataFile, self).__init__(name, access, owner, "datafile")
self.checksum = ""
self.size = 0
self.location = ""
self.mediatype = ""
self.conditions = []
self.... | from dataitem import DataItem
class DataFile(DataItem):
def __init__(self, name, access, owner):
super(DataFile, self).__init__(name, access, owner, "datafile")
self.checksum = ""
self.size = 0
self.location = ""
self.mediatype = ""
self.conditions = []
self.... | Add parent so we can track versions. | Add parent so we can track versions.
| Python | mit | materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org |
eaa17491581cbb52242fbe543dd09929f537a8bc | mysettings.py | mysettings.py | from src.markdown.makrdown import jinja_aware_markdown
PREFERRED_URL_SCHEME = 'http'
SERVER_NAME = 'localhost:5000'
FLATPAGES_EXTENSION = '.md'
FLATPAGES_HTML_RENDERER = jinja_aware_markdown
FREEZER_IGNORE_404_NOT_FOUND = True
FLATPAGES_AUTO_RELOAD = True
GITHUB_URL = 'https://github.com/JetBrains/kotlin'
TWITTER_URL ... | from src.markdown.makrdown import jinja_aware_markdown
PREFERRED_URL_SCHEME = 'http'
SERVER_NAME = 'localhost:5000'
FLATPAGES_EXTENSION = '.md'
FLATPAGES_HTML_RENDERER = jinja_aware_markdown
FREEZER_IGNORE_404_NOT_FOUND = True
FLATPAGES_AUTO_RELOAD = True
FREEZER_STATIC_IGNORE = ["*"]
GITHUB_URL = 'https://github.com/... | Add option to ignore static. | Add option to ignore static.
| Python | apache-2.0 | meilalina/kotlin-web-site,meilalina/kotlin-web-site,hltj/kotlin-web-site-cn,hltj/kotlin-web-site-cn,JetBrains/kotlin-web-site,JetBrains/kotlin-web-site,hltj/kotlin-web-site-cn,hltj/kotlin-web-site-cn,JetBrains/kotlin-web-site,JetBrains/kotlin-web-site,meilalina/kotlin-web-site,JetBrains/kotlin-web-site,meilalina/kotlin... |
c90dbc5007b5627b264493c2d16af79cff9c2af0 | joku/checks.py | joku/checks.py | """
Specific checks.
"""
from discord.ext.commands import CheckFailure
def is_owner(ctx):
if not ctx.bot.owner_id == ctx.message.author.id:
raise CheckFailure(message="You are not the owner.")
return True
| """
Specific checks.
"""
from discord.ext.commands import CheckFailure, check
def is_owner(ctx):
if not ctx.bot.owner_id == ctx.message.author.id:
raise CheckFailure(message="You are not the owner.")
return True
def has_permissions(**perms):
def predicate(ctx):
if ctx.bot.owner_id == ctx... | Add better custom has_permission check. | Add better custom has_permission check.
| Python | mit | MJB47/Jokusoramame,MJB47/Jokusoramame,MJB47/Jokusoramame |
abb00ac993154071776488b5dcaef32cc2982f4c | test/functional/master/test_endpoints.py | test/functional/master/test_endpoints.py | import os
import yaml
from test.framework.functional.base_functional_test_case import BaseFunctionalTestCase
from test.functional.job_configs import BASIC_JOB
class TestMasterEndpoints(BaseFunctionalTestCase):
def _start_master_only_and_post_a_new_job(self):
master = self.cluster.start_master()
... | import os
import tempfile
import yaml
from test.framework.functional.base_functional_test_case import BaseFunctionalTestCase
from test.functional.job_configs import BASIC_JOB
class TestMasterEndpoints(BaseFunctionalTestCase):
def setUp(self):
super().setUp()
self._project_dir = tempfile.Tempora... | Fix broken functional tests on windows | Fix broken functional tests on windows
Something must have changed on the Appveyor side since this code
hasn't been touched recently. The issue was that a functional test
was referring to "/tmp" which is not valid on Windows. I'm surprised
this worked on Windows in the first place.
| Python | apache-2.0 | josephharrington/ClusterRunner,box/ClusterRunner,josephharrington/ClusterRunner,nickzuber/ClusterRunner,Medium/ClusterRunner,nickzuber/ClusterRunner,box/ClusterRunner,Medium/ClusterRunner |
59b2d0418c787066c37904816925dad15b0b45cf | scanblog/scanning/admin.py | scanblog/scanning/admin.py | from django.contrib import admin
from scanning.models import PendingScan, Document, DocumentPage, Scan, ScanPage, Transcription
class ScanPageInline(admin.TabularInline):
model = ScanPage
class ScanAdmin(admin.ModelAdmin):
model = Scan
inlines = [ScanPageInline]
admin.site.register(Scan, ScanAdmin)
class... | from django.contrib import admin
from scanning.models import PendingScan, Document, DocumentPage, Scan, ScanPage, Transcription
class ScanPageInline(admin.TabularInline):
model = ScanPage
class ScanAdmin(admin.ModelAdmin):
model = Scan
inlines = [ScanPageInline]
admin.site.register(Scan, ScanAdmin)
class... | Use author display name in document list_filter | Use author display name in document list_filter
| Python | agpl-3.0 | yourcelf/btb,yourcelf/btb,flexpeace/btb,flexpeace/btb,yourcelf/btb,flexpeace/btb,flexpeace/btb,yourcelf/btb,flexpeace/btb,yourcelf/btb |
e4e10ee0ae5a18cfec0e15b7b85986b7f4fc4f9d | feder/institutions/viewsets.py | feder/institutions/viewsets.py | import django_filters
from rest_framework import filters, viewsets
from teryt_tree.rest_framework_ext.viewsets import custom_area_filter
from .models import Institution, Tag
from .serializers import InstitutionSerializer, TagSerializer
class InstitutionFilter(filters.FilterSet):
jst = django_filters.CharFilter(m... | import django_filters
from rest_framework import filters, viewsets
from teryt_tree.rest_framework_ext.viewsets import custom_area_filter
from .models import Institution, Tag
from .serializers import InstitutionSerializer, TagSerializer
class InstitutionFilter(filters.FilterSet):
jst = django_filters.CharFilter(m... | Fix prefetched fields in Institutions in API | Fix prefetched fields in Institutions in API
| Python | mit | watchdogpolska/feder,watchdogpolska/feder,watchdogpolska/feder,watchdogpolska/feder |
671ca30892e3ebeb0a9140f95690853b4b92dc02 | post/views.py | post/views.py | from django.core.urlresolvers import reverse
from django.utils.translation import ugettext as _
from post.models import Post
from jmbo.generic.views import GenericObjectDetail, GenericObjectList
from jmbo.view_modifiers import DefaultViewModifier
class ObjectList(GenericObjectList):
def get_extra_context(self, *... | from django.core.urlresolvers import reverse
from django.utils.translation import ugettext as _
from post.models import Post
from jmbo.generic.views import GenericObjectDetail, GenericObjectList
from jmbo.view_modifiers import DefaultViewModifier
class ObjectList(GenericObjectList):
def get_extra_context(self, *... | Fix reverse since we deprecated post_object_list | Fix reverse since we deprecated post_object_list
| Python | bsd-3-clause | praekelt/jmbo-post,praekelt/jmbo-post |
ee3b712611ed531843134ef4ce94cb45c726c127 | nap/extras/actions.py | nap/extras/actions.py |
from django.http import StreamingHttpResponse
from django.utils.encoding import force_text
from .models import modelserialiser_factory
from .simplecsv import CSV
class ExportCsv(object):
def __init__(self, serialiser=None, label=None, **opts):
self.serialiser = serialiser
self.opts = opts
... |
from django.http import StreamingHttpResponse
from django.utils.encoding import force_text
from .models import modelserialiser_factory
from .simplecsv import CSV
class ExportCsv(object):
def __init__(self, serialiser=None, label=None, **opts):
self.serialiser = serialiser
self.opts = opts
... | Fix filename creation in csv export action | Fix filename creation in csv export action
| Python | bsd-3-clause | limbera/django-nap,MarkusH/django-nap |
63eaf0faf56a70fadbd37f0acac6f5e61c7b19eb | checkdns.py | checkdns.py | # coding=utf8
# 31.220.16.242
# 216.58.222.46
import socket
import time
import webbrowser
def checkdns():
print time.ctime()
retorno = True
try:
ip = socket.gethostbyname('google.com')
print ("O IP do host verificado é: " + ip)
if ip == "216.58.222.46":
... | # coding=utf8
# 31.220.16.242
# 216.58.222.46
import socket
import time
import webbrowser
def checkdns():
print time.ctime()
retorno = True
try:
ip = socket.gethostbyname('google.com')
print ("O IP do host verificado é: " + ip)
if ip == "216.58.22.46":
... | Change sleep function to the end to do repeat everytime | Change sleep function to the end to do repeat everytime
| Python | mit | felipebhz/checkdns |
175bbd2f181d067712d38beeca9df4063654103a | nlppln/frog_to_saf.py | nlppln/frog_to_saf.py | #!/usr/bin/env python
import click
import os
import codecs
import json
from xtas.tasks._frog import parse_frog, frog_to_saf
@click.command()
@click.argument('input_files', nargs=-1, type=click.Path(exists=True))
@click.argument('output_dir', nargs=1, type=click.Path())
def frog2saf(input_files, output_dir):
if n... | #!/usr/bin/env python
import click
import os
import codecs
import json
from xtas.tasks._frog import parse_frog, frog_to_saf
@click.command()
@click.argument('input_files', nargs=-1, type=click.Path(exists=True))
@click.argument('output_dir', nargs=1, type=click.Path())
def frog2saf(input_files, output_dir):
if n... | Update script to remove extension from filename | Update script to remove extension from filename
Before, the script added the extension .json to whatever the file
name was. Now, it removes the last extension and then appends .json.
| Python | apache-2.0 | WhatWorksWhenForWhom/nlppln,WhatWorksWhenForWhom/nlppln,WhatWorksWhenForWhom/nlppln |
aaba085cd2e97c8c23e6724da3313d42d12798f0 | app/grandchallenge/annotations/validators.py | app/grandchallenge/annotations/validators.py | from rest_framework import serializers
from django.conf import settings
def validate_grader_is_current_retina_user(grader, context):
"""
This method checks if the passed grader equals the request.user that is passed in the context.
Only applies to users that are in the retina_graders group.
"""
re... | from rest_framework import serializers
from django.conf import settings
def validate_grader_is_current_retina_user(grader, context):
"""
This method checks if the passed grader equals the request.user that is passed in the context.
Only applies to users that are in the retina_graders group.
"""
re... | Make sure request.user is a user | Make sure request.user is a user
| Python | apache-2.0 | comic/comic-django,comic/comic-django,comic/comic-django,comic/comic-django,comic/comic-django |
ac6ce056e6b05531d81c550ae3e1e1d688ece4a0 | jwt_auth/serializers.py | jwt_auth/serializers.py | from .models import User
from rest_framework import serializers
class UserSerializer(serializers.ModelSerializer):
password = serializers.CharField(max_length=20, min_length=8, trim_whitespace=False, write_only=True)
class Meta:
model = User
fields = ('id', 'nickname', 'username', 'email', 'pa... | from .models import User
from rest_framework import serializers
class UserSerializer(serializers.ModelSerializer):
password = serializers.CharField(max_length=20, min_length=8, trim_whitespace=False, write_only=True)
class Meta:
model = User
fields = ('id', 'nickname', 'username', 'email', 'pa... | Make serializer commet more clear | [docs](jwt_auth): Make serializer commet more clear
| Python | mit | codertx/lightil |
10d0b7c452c8d9d5893cfe612e0beaa738f61628 | easy_pjax/__init__.py | easy_pjax/__init__.py | #-*- coding: utf-8 -*-
"""
Register filter so it is available for use in the `extends` template tag
(The `extends` tag must come first in a template, so regular `load` is not
an option).
"""
from __future__ import absolute_import, division, print_function, unicode_literals
__version__ = "1.2.0"
try:
from djang... | #-*- coding: utf-8 -*-
"""
Register filter so it is available for use in the `extends` template tag
(The `extends` tag must come first in a template, so regular `load` is not
an option).
"""
from __future__ import absolute_import, division, print_function, unicode_literals
__version__ = "1.2.0"
has_add_to_builtins ... | Add to template builtins only if add_to_buitlins is available (Django <= 1.8) | Add to template builtins only if add_to_buitlins is available (Django <= 1.8)
| Python | bsd-3-clause | nigma/django-easy-pjax,nigma/django-easy-pjax,nigma/django-easy-pjax |
b6208c1f9b6f0afca1dff40a66d2c915594b1946 | blaze/io/server/tests/start_simple_server.py | blaze/io/server/tests/start_simple_server.py | """
Starts a Blaze server for tests.
$ start_test_server.py /path/to/catalog_config.yaml <portnumber>
"""
import sys, os
import blaze
from blaze.io.server.app import app
blaze.catalog.load_config(sys.argv[1])
app.run(port=int(sys.argv[2]), use_reloader=False)
| """
Starts a Blaze server for tests.
$ start_test_server.py /path/to/catalog_config.yaml <portnumber>
"""
import sys, os
if os.name == 'nt':
old_excepthook = sys.excepthook
# Exclude this from our autogenerated API docs.
undoc = lambda func: func
@undoc
def gui_excepthook(exctype, value, tb):
... | Add exception hook to help diagnose server test errors in python3 gui mode | Add exception hook to help diagnose server test errors in python3 gui mode
| Python | bsd-3-clause | caseyclements/blaze,dwillmer/blaze,jcrist/blaze,mrocklin/blaze,cowlicks/blaze,ContinuumIO/blaze,jcrist/blaze,xlhtc007/blaze,FrancescAlted/blaze,aterrel/blaze,nkhuyu/blaze,AbhiAgarwal/blaze,markflorisson/blaze-core,nkhuyu/blaze,FrancescAlted/blaze,ChinaQuants/blaze,markflorisson/blaze-core,alexmojaki/blaze,alexmojaki/bl... |
95bde4f783a4d11627d8bc64e24b383e945bdf01 | src/web/tags.py | src/web/tags.py | # -*- coding: utf-8 -*-
# vim: set fileencodings=utf-8
__docformat__ = "reStructuredText"
import json
import datetime
from django.template.base import Library
from django.utils.safestring import mark_safe
register = Library()
#CDN_URL = 'https://cdn.crate.io'
CDN_URL = 'http://localhost:8001'
def media(context, m... | # -*- coding: utf-8 -*-
# vim: set fileencodings=utf-8
__docformat__ = "reStructuredText"
import json
import datetime
from django.template.base import Library
from django.utils.safestring import mark_safe
register = Library()
CDN_URL = 'https://cdn.crate.io'
def media(context, media_url):
"""
Get the path... | Revert local CDN location set by Jodok | Revert local CDN location set by Jodok
| Python | apache-2.0 | crate/crate-web,jomolinare/crate-web,crate/crate-web,crate/crate-web,jomolinare/crate-web,jomolinare/crate-web |
8d8002062a0ecbf3720870d7561670a8c7e98da2 | test/stores/test_auth_tokens_store.py | test/stores/test_auth_tokens_store.py | from test.base import ApiTestCase
from zou.app.stores import auth_tokens_store
class CommandsTestCase(ApiTestCase):
def setUp(self):
super(CommandsTestCase, self).setUp()
self.store = auth_tokens_store
self.store.clear()
def tearDown(self):
self.store.clear()
def test_g... | from test.base import ApiTestCase
from zou.app.stores import auth_tokens_store
class CommandsTestCase(ApiTestCase):
def setUp(self):
super(CommandsTestCase, self).setUp()
self.store = auth_tokens_store
self.store.clear()
def tearDown(self):
self.store.clear()
def test_g... | Fix test for auth tokens store | Fix test for auth tokens store
| Python | agpl-3.0 | cgwire/zou |
7ba77209687ae1bb1344cc09e3539f7e21bfe599 | tests/test_utilities/test_csvstack.py | tests/test_utilities/test_csvstack.py | #!/usr/bin/env python
import sys
import StringIO
import unittest
from csvkit import CSVKitReader
from csvkit.utilities.stack import CSVStack
class TestCSVStack(unittest.TestCase):
def test_explicit_grouping(self):
# stack two CSV files
args = ["--groups", "asd,sdf", "-n", "foo", "examples/dummy.c... | #!/usr/bin/env python
import sys
import StringIO
import unittest
from csvkit import CSVKitReader
from csvkit.utilities.stack import CSVStack
class TestCSVStack(unittest.TestCase):
def test_explicit_grouping(self):
# stack two CSV files
args = ["--groups", "asd,sdf", "-n", "foo", "examples/dummy.c... | Improve test of csvstack --filenames. | Improve test of csvstack --filenames.
| Python | mit | unpingco/csvkit,snuggles08/csvkit,doganmeh/csvkit,aequitas/csvkit,themiurgo/csvkit,bradparks/csvkit__query_join_filter_CSV_cli,matterker/csvkit,archaeogeek/csvkit,metasoarous/csvkit,jpalvarezf/csvkit,kyeoh/csvkit,nriyer/csvkit,gepuro/csvkit,bmispelon/csvkit,KarrieK/csvkit,Tabea-K/csvkit,moradology/csvkit,tlevine/csvkit... |
585317f3a03f55f6487a98446d4a9279f91714d2 | tests/test_vector2_scalar_multiplication.py | tests/test_vector2_scalar_multiplication.py | import pytest # type: ignore
from hypothesis import given
from hypothesis.strategies import floats
from utils import vectors
from ppb_vector import Vector2
@pytest.mark.parametrize("x, y, expected", [
(Vector2(6, 1), 0, Vector2(0, 0)),
(Vector2(6, 1), 2, Vector2(12, 2)),
(Vector2(0, 0), 3, Vector2(0, 0))... | import pytest # type: ignore
from hypothesis import given
from hypothesis.strategies import floats
from utils import vectors
from ppb_vector import Vector2
@pytest.mark.parametrize("x, y, expected", [
(Vector2(6, 1), 0, Vector2(0, 0)),
(Vector2(6, 1), 2, Vector2(12, 2)),
(Vector2(0, 0), 3, Vector2(0, 0))... | Add a test of the linearity of scalar multiplication | Add a test of the linearity of scalar multiplication
| Python | artistic-2.0 | ppb/ppb-vector,ppb/ppb-vector |
aa5259efac8f7fbe8e2afd263198feaaa45fc4c3 | tingbot/platform_specific/__init__.py | tingbot/platform_specific/__init__.py | import platform
def is_tingbot():
"""return True if running as a tingbot. We can update this function to be more smart in future"""
return platform.machine().startswith('armv71')
if platform.system() == 'Darwin':
from osx import fixup_env, create_main_surface, register_button_callback
elif is_tingbot():
... | import platform, os
def is_tingbot():
"""
Return True if running as a tingbot.
"""
# TB_RUN_ON_LCD is an environment variable set by tbprocessd when running tingbot apps.
return 'TB_RUN_ON_LCD' in os.environ
if platform.system() == 'Darwin':
from osx import fixup_env, create_main_surface, regi... | Change test for running on Tingbot | Change test for running on Tingbot
| Python | bsd-2-clause | furbrain/tingbot-python |
16c1ae09e0288036aae87eb4337c24b23b1e6638 | classify.py | classify.py | from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.neighbors import KNeighborsRegressor
from sklearn.ensemble import RandomForestRegressor
from sklearn.pipeline import Pipeline
import numpy as np
import json
import sys
import time
from analyze import Analyzer # for some train data labelling
def m... | from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.ensemble import RandomForestRegressor
from sklearn.pipeline import Pipeline
import numpy as np
import json
import sys
from analyze import Analyzer # for some train data labelling
def main(argv):
group = argv[0] if len(argv) > 0 else "id"
... | Clean up some unused imports and comments | Clean up some unused imports and comments
| Python | mit | timvandermeij/sentiment-analysis,timvandermeij/sentiment-analysis |
3685715cd260f4f5ca392caddf7fb0c01af9ebcc | mzalendo/comments2/feeds.py | mzalendo/comments2/feeds.py | from disqus.wxr_feed import ContribCommentsWxrFeed
# from comments2.models import Comment
from core.models import Person
# http://help.disqus.com/customer/portal/articles/472150-custom-xml-import-format
class CommentWxrFeed(ContribCommentsWxrFeed):
link = "/"
def items(self):
return Person.objects.a... | from disqus.wxr_feed import ContribCommentsWxrFeed
# from comments2.models import Comment
from core.models import Person, Place, Organisation
# http://help.disqus.com/customer/portal/articles/472150-custom-xml-import-format
class CommentWxrFeed(ContribCommentsWxrFeed):
link = "/"
def items(self):
li... | Add in comments for orgs and places too, remove limit | Add in comments for orgs and places too, remove limit
| Python | agpl-3.0 | mysociety/pombola,Hutspace/odekro,ken-muturi/pombola,mysociety/pombola,Hutspace/odekro,patricmutwiri/pombola,geoffkilpin/pombola,patricmutwiri/pombola,mysociety/pombola,ken-muturi/pombola,ken-muturi/pombola,ken-muturi/pombola,mysociety/pombola,mysociety/pombola,patricmutwiri/pombola,geoffkilpin/pombola,geoffkilpin/pomb... |
61cf4e2feb3d8920179e28719822c7fb34ea6550 | 3/ibm_rng.py | 3/ibm_rng.py | def ibm_rng(x1, a, c, m):
x = x1
while True:
x = (a * x + c) % m
yield x / (m-1)
def main():
rng = ibm_rng(1, 65539, 0, 2**31)
while True:
x = next(rng)
print(x)
if __name__ == '__main__':
main()
| def ibm_rng(x1, a=65539, c=0, m=2**31):
x = x1
while True:
x = (a * x + c) % m
yield x / (m-1)
def main():
rng = ibm_rng(1, 65539, 0, 2**31)
while True:
x = next(rng)
print(x)
if __name__ == '__main__':
main()
| Add defaults to the ibm RNG | Add defaults to the ibm RNG
| Python | mit | JelteF/statistics |
db3cee63baf64d00b2d2ac4fcf726f287b6d7af2 | app/proxy_fix.py | app/proxy_fix.py | from werkzeug.middleware.proxy_fix import ProxyFix
class CustomProxyFix(object):
def __init__(self, app, forwarded_proto):
self.app = ProxyFix(app)
self.forwarded_proto = forwarded_proto
def __call__(self, environ, start_response):
environ.update({
"HTTP_X_FORWARDED_PROTO"... | from werkzeug.middleware.proxy_fix import ProxyFix
class CustomProxyFix(object):
def __init__(self, app, forwarded_proto):
self.app = ProxyFix(app, x_for=1, x_proto=1, x_host=1, x_port=0, x_prefix=0)
self.forwarded_proto = forwarded_proto
def __call__(self, environ, start_response):
e... | Update call to proxy fix to use new method signature | Update call to proxy fix to use new method signature
Old method:
```python
ProxyFix(app, num_proxies=1)
```
https://werkzeug.palletsprojects.com/en/0.14.x/contrib/fixers/#werkzeug.contrib.fixers.ProxyFix
This uses forwarded values for `REMOTE_ADDR` and `HTTP_HOST`.
New method:
```python
ProxyFix(app, num_proxies=No... | Python | mit | alphagov/notifications-admin,alphagov/notifications-admin,alphagov/notifications-admin,alphagov/notifications-admin |
34c0c6c73a65da3120aa52600254afc909e9a3bc | pytach/wsgi.py | pytach/wsgi.py | import bottle
from bottle import route, run
from web import web
import config
app = application = bottle.Bottle()
app.merge(web.app)
config.arguments['--verbose'] = True
if __name__ == '__main__':
app.run(host='0.0.0.0', port=8082, debug=True)
| import bottle
import config
from web import web
app = application = bottle.Bottle()
app.merge(web.app)
config.arguments['--verbose'] = True
| Remove unused main and unused imports | Remove unused main and unused imports
| Python | mit | gotling/PyTach,gotling/PyTach,gotling/PyTach |
d86bdec5d7d57fe74cb463e391798bd1e5be87ff | pombola/ghana/urls.py | pombola/ghana/urls.py | from django.conf.urls import patterns, include, url, handler404
from django.views.generic import TemplateView
import django.contrib.auth.views
from .views import data_upload, info_page_upload
urlpatterns = patterns('',
url(r'^intro$', TemplateView.as_view(template_name='intro.html')),
url(r'^data/upload/mps/... | from django.conf.urls import patterns, url, include
from django.views.generic import TemplateView
from .views import data_upload, info_page_upload
urlpatterns = patterns('',
url(r'^intro$', TemplateView.as_view(template_name='intro.html')),
url(r'^data/upload/mps/$', data_upload, name='data_upload'),
url(... | Update Ghana code to match current Pombola | Update Ghana code to match current Pombola
| Python | agpl-3.0 | geoffkilpin/pombola,mysociety/pombola,mysociety/pombola,mysociety/pombola,mysociety/pombola,mysociety/pombola,geoffkilpin/pombola,geoffkilpin/pombola,geoffkilpin/pombola,geoffkilpin/pombola,geoffkilpin/pombola,mysociety/pombola |
5526f8e3dca2f84fce34df5a134bada8479a2f69 | netbox/ipam/models/__init__.py | netbox/ipam/models/__init__.py | from .fhrp import *
from .ip import *
from .services import *
from .vlans import *
from .vrfs import *
__all__ = (
'ASN',
'Aggregate',
'IPAddress',
'IPRange',
'FHRPGroup',
'FHRPGroupAssignment',
'Prefix',
'RIR',
'Role',
'RouteTarget',
'Service',
'ServiceTemplate',
'V... | # Ensure that VRFs are imported before IPs/prefixes so dumpdata & loaddata work correctly
from .fhrp import *
from .vrfs import *
from .ip import *
from .services import *
from .vlans import *
__all__ = (
'ASN',
'Aggregate',
'IPAddress',
'IPRange',
'FHRPGroup',
'FHRPGroupAssignment',
'Prefi... | Fix dumpdata ordering for VRFs | Fix dumpdata ordering for VRFs
| Python | apache-2.0 | digitalocean/netbox,digitalocean/netbox,digitalocean/netbox,digitalocean/netbox |
0782ba56218e825dea5b76cbf030a522932bcfd6 | networkx/classes/ordered.py | networkx/classes/ordered.py | """
OrderedDict variants of the default base classes.
These classes are especially useful for doctests and unit tests.
"""
try:
# Python 2.7+
from collections import OrderedDict
except ImportError:
# Oython 2.6
try:
from ordereddict import OrderedDict
except ImportError:
OrderedDic... | """
OrderedDict variants of the default base classes.
"""
try:
# Python 2.7+
from collections import OrderedDict
except ImportError:
# Oython 2.6
try:
from ordereddict import OrderedDict
except ImportError:
OrderedDict = None
from .graph import Graph
from .multigraph import MultiGr... | Remove unnecessary (and debatable) comment. | Remove unnecessary (and debatable) comment.
| Python | bsd-3-clause | nathania/networkx,dhimmel/networkx,RMKD/networkx,sharifulgeo/networkx,chrisnatali/networkx,goulu/networkx,farhaanbukhsh/networkx,jni/networkx,jakevdp/networkx,ionanrozenfeld/networkx,debsankha/networkx,nathania/networkx,tmilicic/networkx,kernc/networkx,ltiao/networkx,michaelpacer/networkx,bzero/networkx,dhimmel/network... |
4a6060f476aebac163dbac8f9822539596379c0a | welt2000/__init__.py | welt2000/__init__.py | from flask import Flask, request, session
from flask.ext.babel import Babel
from babel.core import negotiate_locale
from welt2000.__about__ import (
__title__, __summary__, __uri__, __version__, __author__, __email__,
__license__,
) # noqa
app = Flask(__name__)
app.secret_key = '1234567890'
babel = Babel(a... | from flask import Flask, request, session, current_app
from flask.ext.babel import Babel
from babel.core import negotiate_locale
from welt2000.__about__ import (
__title__, __summary__, __uri__, __version__, __author__, __email__,
__license__,
) # noqa
app = Flask(__name__)
app.secret_key = '1234567890'
ba... | Use current_app.babel_instance instead of babel | app: Use current_app.babel_instance instead of babel
That way we can use Babel.init_app() later
| Python | mit | Turbo87/welt2000,Turbo87/welt2000 |
4bb8a61cde27575865cdd2b7df5afcb5d6860523 | fmriprep/interfaces/tests/test_reports.py | fmriprep/interfaces/tests/test_reports.py | import pytest
from ..reports import get_world_pedir
@pytest.mark.parametrize("orientation,pe_dir,expected", [
('RAS', 'j', 'Posterior-Anterior'),
('RAS', 'j-', 'Anterior-Posterior'),
('RAS', 'i', 'Left-Right'),
('RAS', 'i-', 'Right-Left'),
('RAS', 'k', 'Inferior-Superior'),
('RAS', 'k-', 'Sup... | import pytest
from ..reports import get_world_pedir
@pytest.mark.parametrize("orientation,pe_dir,expected", [
('RAS', 'j', 'Posterior-Anterior'),
('RAS', 'j-', 'Anterior-Posterior'),
('RAS', 'i', 'Left-Right'),
('RAS', 'i-', 'Right-Left'),
('RAS', 'k', 'Inferior-Superior'),
('RAS', 'k-', 'Sup... | Add weird SLP orientation to get_world_pedir | TEST: Add weird SLP orientation to get_world_pedir
| Python | bsd-3-clause | oesteban/fmriprep,poldracklab/preprocessing-workflow,oesteban/fmriprep,poldracklab/preprocessing-workflow,oesteban/fmriprep |
95ea1d7d6564bcbb2e3b8d2ba254ccd2c1c38436 | mamba/__init__.py | mamba/__init__.py | __version__ = '0.9.2'
def description(message):
pass
def _description(message):
pass
def it(message):
pass
def _it(message):
pass
def context(message):
pass
def _context(message):
pass
def before():
pass
def after():
pass
| __version__ = '0.9.2'
def description(message):
pass
def _description(message):
pass
def fdescription(message):
pass
def it(message):
pass
def _it(message):
pass
def fit(message):
pass
def context(message):
pass
def _context(message):
pass
def fcontext(message):
pas... | Add import for focused stuff | Add import for focused stuff
| Python | mit | nestorsalceda/mamba |
29e491c5505d2068b46eb489044455968e53ab70 | test/400-bay-water.py | test/400-bay-water.py | assert_has_feature(
14, 2623, 6318, 'water',
{ 'kind': 'bay', 'label_placement': 'yes' })
| # osm_id: 43950409 name: San Pablo Bay
assert_has_feature(
14, 2623, 6318, 'water',
{ 'kind': 'bay', 'label_placement': 'yes' })
# osm_id: 360566115 name: Byron strait
assert_has_feature(
14, 15043, 8311, 'water',
{ 'kind': 'strait', 'label_placement': 'yes' })
# osm_id: -1451065 name: Horsens Fjord
a... | Add tests for strait and fjord | Add tests for strait and fjord
| Python | mit | mapzen/vector-datasource,mapzen/vector-datasource,mapzen/vector-datasource |
cdf545cf9385a0490590cd0162141025a1301c09 | track/config.py | track/config.py | import configargparse
DEFAULT_CONFIG_FILES=[
'./track.cfg',
'~/.track.cfg',
]
# Bit of a cheat... not actually an object constructor, just a 'make me an object' method
def ArgParser():
return configargparse.ArgParser(
ignore_unknown_config_file_keys =True,
allow_abbrev ... | import configargparse
DEFAULT_CONFIG_FILES=[
'./track.cfg',
'~/.track.cfg',
]
# Bit of a cheat... not actually an object constructor, just a 'make me an object' method
def ArgParser():
return configargparse.ArgParser(
ignore_unknown_config_file_keys =True,
allow_abbrev ... | Use argparse formatter RawDescriptionHelpFormatter, maybe temporarily | Use argparse formatter RawDescriptionHelpFormatter, maybe temporarily
| Python | mit | bgottula/track,bgottula/track |
148d4c44a9eb63016b469c6bf317a3dbe9ed7918 | permuta/permutations.py | permuta/permutations.py | from .misc import DancingLinks
from .permutation import Permutation
import random
class Permutations(object):
def __init__(self, n):
assert 0 <= n
self.n = n
def __iter__(self):
left = DancingLinks(range(1, self.n+1))
res = []
def gen():
if len(left) == 0:
... | from .misc import DancingLinks
from .permutation import Permutation
import random
class Permutations(object):
"""Class for iterating through all Permutations of length n"""
def __init__(self, n):
"""Returns an object giving all permutations of length n"""
assert 0 <= n
self.n = n
... | Add documentation for Permutations class | Add documentation for Permutations class
| Python | bsd-3-clause | PermutaTriangle/Permuta |
86791effb26c33514bbc6713f67a903e8d9e5295 | scripts/c19.py | scripts/c19.py | from __future__ import print_function
import sys
from pyspark.sql import SparkSession
from pyspark.sql.functions import lit, col, coalesce
if __name__ == "__main__":
if len(sys.argv) != 3:
print("Usage: c19.py <input> <output>", file=sys.stderr)
exit(-1)
spark = SparkSession.builder.appName('... | from __future__ import print_function
import sys
from pyspark.sql import SparkSession
from pyspark.sql.functions import col, struct, max
if __name__ == "__main__":
if len(sys.argv) != 3:
print("Usage: c19.py <input> <output>", file=sys.stderr)
exit(-1)
spark = SparkSession.builder.appName('Se... | Choose a single corpus for a given series,date pair. | Choose a single corpus for a given series,date pair.
| Python | apache-2.0 | ViralTexts/vt-passim,ViralTexts/vt-passim,ViralTexts/vt-passim |
390fa07c191d79290b1ef83c268f38431f68093a | tests/clients/simple.py | tests/clients/simple.py | # -*- coding: utf-8 -*-
from base import jsonrpyc
class MyClass(object):
def one(self):
return 1
def twice(self, n):
return n * 2
def arglen(self, *args, **kwargs):
return len(args) + len(kwargs)
if __name__ == "__main__":
rpc = jsonrpyc.RPC(MyClass())
| # -*- coding: utf-8 -*-
import os
import sys
base = os.path.dirname(os.path.abspath(__file__))
sys.path.append(base)
from base import jsonrpyc
class MyClass(object):
def one(self):
return 1
def twice(self, n):
return n * 2
def arglen(self, *args, **kwargs):
return len(args) ... | Fix import in test client. | Fix import in test client.
| Python | mit | riga/jsonrpyc |
73d0be7a432340b4ecd140ad1cc8792d3f049779 | tests/factories/user.py | tests/factories/user.py | # -*- coding: utf-8 -*-
# Copyright (c) 2016 The Pycroft Authors. See the AUTHORS file.
# This file is part of the Pycroft project and licensed under the terms of
# the Apache License, Version 2.0. See the LICENSE file for details.
import factory
from factory.faker import Faker
from pycroft.model.user import User
from... | # -*- coding: utf-8 -*-
# Copyright (c) 2016 The Pycroft Authors. See the AUTHORS file.
# This file is part of the Pycroft project and licensed under the terms of
# the Apache License, Version 2.0. See the LICENSE file for details.
import factory
from factory.faker import Faker
from pycroft.model.user import User
from... | Use SelfAttribute instead of explicit lambda | Use SelfAttribute instead of explicit lambda
| Python | apache-2.0 | agdsn/pycroft,agdsn/pycroft,agdsn/pycroft,agdsn/pycroft,agdsn/pycroft |
2c37ed091baf12e53885bfa06fdb835bb8de1218 | tests/skipif_markers.py | tests/skipif_markers.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
skipif_markers
--------------
Contains pytest skipif markers to be used in the suite.
"""
import pytest
import os
try:
os.environ[u'TRAVIS']
except KeyError:
travis = False
else:
travis = True
try:
os.environ[u'DISABLE_NETWORK_TESTS']
except KeyErr... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
skipif_markers
--------------
Contains pytest skipif markers to be used in the suite.
"""
import pytest
import os
try:
os.environ[u'TRAVIS']
except KeyError:
travis = False
else:
travis = True
try:
os.environ[u'DISABLE_NETWORK_TESTS']
except KeyErr... | Add Bitbucket to skipif marker reason | Add Bitbucket to skipif marker reason
| Python | bsd-3-clause | pjbull/cookiecutter,atlassian/cookiecutter,sp1rs/cookiecutter,0k/cookiecutter,cichm/cookiecutter,takeflight/cookiecutter,atlassian/cookiecutter,kkujawinski/cookiecutter,foodszhang/cookiecutter,christabor/cookiecutter,ramiroluz/cookiecutter,cguardia/cookiecutter,tylerdave/cookiecutter,benthomasson/cookiecutter,Springerl... |
66eddf04efd46fb3dbeae34c4d82f673a88be70f | tests/test_person.py | tests/test_person.py | from copy import copy
from unittest import TestCase
from address_book import Person
class PersonTestCase(TestCase):
def test_get_groups(self):
pass
def test_add_address(self):
basic_address = ['Russian Federation, Kemerovo region, Kemerovo, Kirova street 23, apt. 42']
person = Pers... | from copy import copy
from unittest import TestCase
from address_book import Person
class PersonTestCase(TestCase):
def test_get_groups(self):
pass
def test_add_address(self):
basic_address = ['Russian Federation, Kemerovo region, Kemerovo, Kirova street 23, apt. 42']
person = Pers... | Test the ability to add phone to the person | Test the ability to add phone to the person
| Python | mit | dizpers/python-address-book-assignment |
3e84dcb7b449db89ca6ce2b91b34a5e8f8428b39 | core/markdown.py | core/markdown.py | from markdown.extensions import nl2br, sane_lists, fenced_code
from pymdownx import magiclink
from mdx_unimoji import UnimojiExtension
import utils.markdown
markdown_extensions = [
magiclink.MagiclinkExtension(),
nl2br.Nl2BrExtension(),
utils.markdown.ExtendedLinkExtension(),
sane_lists.SaneListExtensi... | from markdown.extensions import nl2br, sane_lists, fenced_code
from pymdownx import magiclink
from mdx_unimoji import UnimojiExtension
import utils.markdown
markdown_extensions = [
magiclink.MagiclinkExtension(),
nl2br.Nl2BrExtension(),
utils.markdown.ExtendedLinkExtension(),
sane_lists.SaneListExtensi... | Allow sub- and superscript tags | Allow sub- and superscript tags
| Python | agpl-3.0 | stadtgestalten/stadtgestalten,stadtgestalten/stadtgestalten,stadtgestalten/stadtgestalten |
458d61ffb5161394f8080cea59716b2f9cb492f3 | nbgrader_config.py | nbgrader_config.py | c = get_config()
c.CourseDirectory.db_assignments = [dict(name="1", duedate="2019-12-09 17:00:00 UTC")]
c.CourseDirectory.db_students = [
dict(id="foo", first_name="foo", last_name="foo")
]
c.ClearSolutions.code_stub = {'python': '##### Implement this part of the code #####\nraise NotImplementedError()'}
| c = get_config()
c.CourseDirectory.db_assignments = [dict(name="1", duedate="2019-12-09 17:00:00 UTC")]
c.CourseDirectory.db_students = [
dict(id="foo", first_name="foo", last_name="foo")
]
c.ClearSolutions.code_stub = {'python': '''##### Implement this part of the code #####
raise NotImplementedError("Code not imp... | Add error message for not implemented error | Add error message for not implemented error
| Python | mit | pbutenee/ml-tutorial,pbutenee/ml-tutorial |
7c77a7b14432a85447ff74e7aa017ca56c86e662 | oidc_apis/views.py | oidc_apis/views.py | from django.http import JsonResponse
from django.views.decorators.http import require_http_methods
from oidc_provider.lib.utils.oauth2 import protected_resource_view
from .api_tokens import get_api_tokens_by_access_token
@require_http_methods(['GET', 'POST'])
@protected_resource_view(['openid'])
def get_api_tokens_v... | from django.http import JsonResponse
from django.views.decorators.http import require_http_methods
from oidc_provider.lib.utils.oauth2 import protected_resource_view
from django.views.decorators.csrf import csrf_exempt
from .api_tokens import get_api_tokens_by_access_token
@csrf_exempt
@require_http_methods(['GET', ... | Make api-tokens view exempt from CSRF checks | Make api-tokens view exempt from CSRF checks
| Python | mit | mikkokeskinen/tunnistamo,mikkokeskinen/tunnistamo |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.