commit stringlengths 40 40 | subject stringlengths 4 1.73k | repos stringlengths 5 127k | old_file stringlengths 2 751 | new_file stringlengths 2 751 | new_contents stringlengths 1 8.98k | old_contents stringlengths 0 6.59k | license stringclasses 13
values | lang stringclasses 23
values |
|---|---|---|---|---|---|---|---|---|
7205500a464e35e1f7a9250845cfd11dade677c0 | use automatic loader and verbose logging | undertherain/vsmlib | test/test_analogies.py | test/test_analogies.py | import logging
import unittest
import vsmlib
import vsmlib.benchmarks
import vsmlib.benchmarks.analogy
logging.basicConfig(level=logging.DEBUG)
class Tests(unittest.TestCase):
def test_analogies(self):
path_model = "./test/data/embeddings/text/plain"
model = vsmlib.model.load_from_dir(path_model... | import vsmlib
import vsmlib.benchmarks
import vsmlib.benchmarks.analogy
import unittest
class Tests(unittest.TestCase):
def test_analogies(self):
model = vsmlib.model.ModelDense()
path_model = "./test/data/embeddings/text/plain/emb.txt"
model.load_from_text(path_model)
vsmlib.ben... | apache-2.0 | Python |
e1e120cd22e30dd89f2ea8683120307437b7f09c | Use urlparse for parsing urls. | fmarczin/simplekv,mbr/simplekv,mbr/simplekv,karteek/simplekv,karteek/simplekv,fmarczin/simplekv | test/test_filestore.py | test/test_filestore.py | #!/usr/bin/env python
# coding=utf8
import os
import shutil
import sys
import tempfile
from urlparse import urlparse
if sys.version_info < (2, 7):
import unittest2 as unittest
else:
import unittest
from . import SimpleUrlKVTest
from simplekv.fs import FilesystemStore, WebFilesystemStore
from mock import Moc... | #!/usr/bin/env python
# coding=utf8
import os
import shutil
import sys
import tempfile
if sys.version_info < (2, 7):
import unittest2 as unittest
else:
import unittest
from . import SimpleUrlKVTest
from simplekv.fs import FilesystemStore, WebFilesystemStore
from mock import Mock
class TestFileStore(unitte... | mit | Python |
4dfd76bee930015a00fb07b5eab6644f9f0d7a96 | Fix typo | NSLS-II/filestore,tacaswell/filestore,ericdill/databroker,ericdill/databroker | filestore/utils.py | filestore/utils.py | from __future__ import absolute_import
import six
import os
import uuid
from pymongo import MongoClient
if six.PY2:
# http://stackoverflow.com/a/5032238/380231
def _make_sure_path_exists(path):
import errno
try:
os.makedirs(path)
except OSError as exception:
if ... | from __future__ import absolute_import
import six
import os
import uuid
from pymongo import MongoClient
if six.PY2:
# http://stackoverflow.com/a/5032238/380231
def _make_sure_path_exists(path):
import errno
try:
os.makedirs(path)
except OSError as exception:
if ... | bsd-3-clause | Python |
3a162a6f50ce63c60cb2f5c48d0c1ac17a36719a | bump version to 2.0.1 | mrsan22/Angular-Flask-Docker-Skeleton,mrsan22/Angular-Flask-Docker-Skeleton,mrsan22/Angular-Flask-Docker-Skeleton,mrsan22/Angular-Flask-Docker-Skeleton,mrsan22/Angular-Flask-Docker-Skeleton | server/settings.py | server/settings.py | # -*- coding: utf-8 -*-
"""
file: settings.py
notes: Configure Settings for application
"""
import os
class Config(object):
""" Common config options """
APPNAME = 'Angular_Flask_Docker_Skeleton'
SUPPORT_EMAIL = 'mr.san.kumar@gmail.com'
VERSION = '2.0.1'
APPID = 'fl_angular_docker'
SE... | # -*- coding: utf-8 -*-
"""
file: settings.py
notes: Configure Settings for application
"""
import os
class Config(object):
""" Common config options """
APPNAME = 'Angular_Flask_Docker_Skeleton'
SUPPORT_EMAIL = 'mr.san.kumar@gmail.com'
VERSION = '2.0.0'
APPID = 'fl_angular_docker'
SE... | mit | Python |
dbc54912c52b847a48392739585b111c8c6a671d | revert default scan interval | cloud4rpi/cloud4rpi | settings_vendor.py | settings_vendor.py | # System
scanInterval = 5
# Server parameters
baseApiUrl = 'http://stage.cloud4rpi.io:3000/api'
| # System
scanInterval = 60
# Server parameters
baseApiUrl = 'http://stage.cloud4rpi.io:3000/api'
| mit | Python |
57a2f21273877c2d6b4a2819c417a22b9ffcbb57 | Add grep to query | dogoncouch/siemstress | siemquery/query.py | siemquery/query.py | #!/usr/bin/env python
#_MIT License
#_
#_Copyright (c) 2017 Dan Persons (dpersonsdev@gmail.com)
#_
#_Permission is hereby granted, free of charge, to any person obtaining a copy
#_of this software and associated documentation files (the "Software"), to deal
#_in the Software without restriction, including without limi... | #!/usr/bin/env python
#_MIT License
#_
#_Copyright (c) 2017 Dan Persons (dpersonsdev@gmail.com)
#_
#_Permission is hereby granted, free of charge, to any person obtaining a copy
#_of this software and associated documentation files (the "Software"), to deal
#_in the Software without restriction, including without limi... | mit | Python |
d85bebdc65b731f05a2f9246ecf14d50a7718899 | correct a return type of anyconfig.schema.default.is_valid | ssato/python-anyconfig,ssato/python-anyconfig | src/anyconfig/schema/default.py | src/anyconfig/schema/default.py | #
# Copyright (C) 2015 - 2021 Satoru SATOH <satoru.satoh@gmail.com>
# SPDX-License-Identifier: MIT
#
# pylint: disable=unused-argument
"""Default (dummy) implementation.
"""
import typing
from .common import (
DataT, ResultT, MaybeDataT
)
def validate(data: DataT, schema: DataT, ac_schema_safe: bool = True,
... | #
# Copyright (C) 2015 - 2021 Satoru SATOH <satoru.satoh@gmail.com>
# SPDX-License-Identifier: MIT
#
# pylint: disable=unused-argument
"""Default (dummy) implementation.
"""
import typing
from .common import (
DataT, ResultT, MaybeDataT
)
def validate(data: DataT, schema: DataT, ac_schema_safe: bool = True,
... | mit | Python |
cd1907366375ea192b908d4063784413148e096b | fix reciprocity test | dialounke/pylayers,pylayers/pylayers,pylayers/pylayers,dialounke/pylayers | pylayers/antprop/tests/test_reciprocity2.py | pylayers/antprop/tests/test_reciprocity2.py | #-*- coding:Utf-8 -*-
from pylayers.simul.link import *
import numpy as np
import matplotlib.pyplot as plt
import time
print "======================="
print " start test_reciprocity.py "
print "======================="
DL=DLink(L='defstr.ini')
DL.a=np.array([759,1114,1.0])
DL.b=np.array([767,1114,1.5])
DL.fGHz=np.ar... | #-*- coding:Utf-8 -*-
from pylayers.simul.link import *
import numpy as np
import matplotlib.pyplot as plt
import time
print "======================="
print " start test_reciprocity.py "
print "======================="
DL=DLink(L='defstr.ini')
DL.a=np.array([759,1114,1.0])
DL.b=np.array([767,1114,1.5])
DL.fGHz=np.ar... | mit | Python |
042e368e61e67daee39d62f3c17f238f3d6701ef | mark todo | DennyZhang/devops_public,DennyZhang/devops_public,DennyZhang/devops_public,DennyZhang/devops_public | python/git_pull_codedir/git_pull_codedir.py | python/git_pull_codedir/git_pull_codedir.py | # -*- coding: utf-8 -*-
#!/usr/bin/python
##-------------------------------------------------------------------
## @copyright 2017 DennyZhang.com
## Licensed under MIT
## https://raw.githubusercontent.com/DennyZhang/devops_public/master/LICENSE
##
## File : git_pull_codedir.py
## Author : Denny <denny@dennyzhang.com>... | # -*- coding: utf-8 -*-
#!/usr/bin/python
##-------------------------------------------------------------------
## @copyright 2017 DennyZhang.com
## Licensed under MIT
## https://raw.githubusercontent.com/DennyZhang/devops_public/master/LICENSE
##
## File : git_pull_codedir.py
## Author : Denny <denny@dennyzhang.com>... | mit | Python |
57030f6d5cc5f9586be4f10fd0cb66bfbc7c037b | fix problem with tempfile handling | itsdavidbaxter/Tools,itsdavidbaxter/Tools,itsdavidbaxter/Tools,itsdavidbaxter/Tools,itsdavidbaxter/Tools,itsdavidbaxter/Tools,itsdavidbaxter/Tools,itsdavidbaxter/Tools | webapps/py/cswaSMBclient.py | webapps/py/cswaSMBclient.py | import tempfile
from smb.SMBConnection import SMBConnection
import codecs, csv, os
def uploadCmdrWatch(barcodeFile, dataType, data, config):
try:
barcodeFh = codecs.open('/tmp/%s' % barcodeFile, 'w', 'utf-8-sig')
csvlogfh = csv.writer(barcodeFh, delimiter=",", quoting=csv.QUOTE_ALL)
if da... | import tempfile
from smb.SMBConnection import SMBConnection
from cswaUtils import getConfig
import codecs, csv, os
def uploadCmdrWatch(barcodeFile, dataType, data, config):
try:
# we open and close (and retain) a temporary file
# we do this because we need to set the BOM for this Window files
... | apache-2.0 | Python |
28aa4e8b537d4dd683e755e891c81ecdcc0fa54d | Simplify LazyAttribute class. | MadeInHaus/django-social,MadeInHaus/django-social,MadeInHaus/django-social,MadeInHaus/django-social | social/settings.py | social/settings.py | from .models import TwitterSetting, FacebookSetting, InstagramSetting, RSSSetting
__all__ = (
'SOCIAL_TWITTER_AUTO_APPROVE',
'SOCIAL_TWITTER_INTERVAL',
'SOCIAL_TWITTER_CONSUMER_KEY',
'SOCIAL_TWITTER_CONSUMER_SECRET',
'SOCIAL_FACEBOOK_AUTO_APPROVE',
'SOCIAL_FACEBOOK_INTERVAL',
'SOCIAL_FACEB... | from .models import TwitterSetting, FacebookSetting, InstagramSetting, RSSSetting
__all__ = (
'SOCIAL_TWITTER_AUTO_APPROVE',
'SOCIAL_TWITTER_INTERVAL',
'SOCIAL_TWITTER_CONSUMER_KEY',
'SOCIAL_TWITTER_CONSUMER_SECRET',
'SOCIAL_FACEBOOK_AUTO_APPROVE',
'SOCIAL_FACEBOOK_INTERVAL',
'SOCIAL_FACEB... | mit | Python |
b5454286a2cfce07f4971b7bc56dd131402f8fe3 | Fix pylint error after iati.core -> iati | IATI/iati.core,IATI/iati.core | iati/__init__.py | iati/__init__.py | """A top-level namespace package for IATI."""
from .codelists import Code, Codelist # noqa: F401
from .data import Dataset # noqa: F401
from .rulesets import Rule, Ruleset # noqa: F401
from .rulesets import RuleAtLeastOne, RuleDateOrder, RuleDependent, RuleNoMoreThanOne, RuleRegexMatches, RuleRegexNoMatches, RuleSta... | """A top-level namespace package for IATI."""
__import__('pkg_resources').declare_namespace(__name__)
from .codelists import Code, Codelist # noqa: F401
from .data import Dataset # noqa: F401
from .rulesets import Rule, Ruleset # noqa: F401
from .rulesets import RuleAtLeastOne, RuleDateOrder, RuleDependent, RuleNoM... | mit | Python |
529a4290082b14912f8cf725401513106e306bee | Make image filter optional in create image | agnethesoraa/placepuppy,agnethesoraa/placepuppy | image_helpers.py | image_helpers.py | from PIL import Image
import StringIO
import random
import os
from cache import cache
def create_image(width, height, image_filter=None):
stringfile = StringIO.StringIO()
im = Image.open(choose_image(width, height))
resize(im, width, height)
im = crop_image(im, width, height)
if image_filter:
... | from PIL import Image
import StringIO
import random
import os
from cache import cache
def create_image(width, height, image_filter):
stringfile = StringIO.StringIO()
im = Image.open(choose_image(width, height))
resize(im, width, height)
im = crop_image(im, width, height)
if image_filter:
... | mit | Python |
5658b41d1011a1fa9da2e5ee0326e963ea52e782 | Fix migration referencing validator | fin/froide,stefanw/froide,stefanw/froide,fin/froide,fin/froide,stefanw/froide,fin/froide,stefanw/froide,stefanw/froide | froide/account/migrations/0012_application.py | froide/account/migrations/0012_application.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2017-11-10 14:28
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import oauth2_provider.generators
import oauth2_provider.validators
class Migration(migrations.Mi... | # -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2017-11-10 14:28
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import oauth2_provider.generators
import oauth2_provider.validators
class Migration(migrations.Mi... | mit | Python |
e90e00b246c8a6d9b5e26c77db259f51164eaad6 | Remove log | speed-of-light/pyslider | lib/exp/tools/emailer.py | lib/exp/tools/emailer.py | import smtplib
import email
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
# see also: https://pypi.python.org/pypi/mailer/ ##
class Emailer(object):
def __init__(self, uname='', upass=''):
"""
Usage:
with Emailer(uname='xxx', upass='yyy') as mailer:
... | import smtplib
import email
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
# see also: https://pypi.python.org/pypi/mailer/ ##
class Emailer(object):
def __init__(self, uname='', upass=''):
"""
Usage:
with Emailer(uname='xxx', upass='yyy') as mailer:
... | agpl-3.0 | Python |
08a2220bdacb3e49050a7c223e5c1d8109ae434f | Disable the effect of %%bohrium if bohrium cannot be imported. | bh107/bohrium,madsbk/bohrium,madsbk/bohrium,bh107/bohrium,bh107/bohrium,bh107/bohrium,madsbk/bohrium,madsbk/bohrium | ipython-magic.py | ipython-magic.py | ####################################
# This file was created by Bohrium.
# It allows you to run NumPy code (cells) as Bohrium, by using the magic command
# `%%bohrium` in your cells, e.g.:
#
# %%bohrium
# print(numpy)
# print(numpy.arange(10))
####################################
from IPython.core.magic import... | ####################################
# This file was created by Bohrium.
# It allows you to run NumPy code (cells) as Bohrium, by using the magic command
# `%%bohrium` in your cells, e.g.:
#
# %%bohrium
# print(numpy)
# print(numpy.arange(10))
####################################
from IPython.core.magic import... | apache-2.0 | Python |
c2fb467626d586bfb5ddef60fd4d1447515ad161 | Add function for plotting feature importances | freedomofpress/fingerprint-securedrop,freedomofpress/FingerprintSecureDrop,freedomofpress/fingerprint-securedrop,freedomofpress/fingerprint-securedrop,freedomofpress/FingerprintSecureDrop | fpsd/evaluation.py | fpsd/evaluation.py | def get_feature_importances(model):
try:
return model.feature_importances_
except:
pass
try:
# Must be 1D for feature importance plot
if len(model.coef_) <= 1:
return model.coef_[0]
else:
return model.coef_
except:
pass
return ... | def get_feature_importances(model):
try:
return model.feature_importances_
except:
pass
try:
# Must be 1D for feature importance plot
if len(model.coef_) <= 1:
return model.coef_[0]
else:
return model.coef_
except:
pass
return ... | agpl-3.0 | Python |
1f373c745e579a73e6db06e47f21572056e223a1 | Fix DistributionNotFound error | DasIch/pyalysis,DasIch/pyalysis | pyalysis/__init__.py | pyalysis/__init__.py | # coding: utf-8
"""
pyalysis
~~~~~~~~
:copyright: 2014 by Daniel Neuhäuser and Contributors
:license: BSD, see LICENSE.rst
"""
import pkg_resources
try:
__version__ = pkg_resources.get_distribution('Pyalysis').version
__version_info__ = tuple(map(int, __version__.split('-')[0].split('.')))
ex... | # coding: utf-8
"""
pyalysis
~~~~~~~~
:copyright: 2014 by Daniel Neuhäuser and Contributors
:license: BSD, see LICENSE.rst
"""
import pkg_resources
__version__ = pkg_resources.get_distribution('Pyalysis').version
__version_info__ = tuple(map(int, __version__.split('-')[0].split('.')))
| bsd-3-clause | Python |
773e169595827527c7a95d5b098b522473d42b99 | Bump version to 1.10.8 | laughingman7743/PyAthena | pyathena/__init__.py | pyathena/__init__.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
import datetime
from pyathena.error import * # noqa
try:
from multiprocessing import cpu_count
except ImportError:
def cpu_count():
return None
__version__ = "1.10.8"
# Globals https://www.python.org/dev/peps/pep-02... | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
import datetime
from pyathena.error import * # noqa
try:
from multiprocessing import cpu_count
except ImportError:
def cpu_count():
return None
__version__ = "1.10.7"
# Globals https://www.python.org/dev/peps/pep-02... | mit | Python |
2ea1f7fecf143bfc4d1b71cc91fa01849c467769 | Bump version number | terceiro/squad,terceiro/squad,terceiro/squad,terceiro/squad | squad/version.py | squad/version.py | __version__ = '0.4.0'
| __version__ = '0.3.4'
| agpl-3.0 | Python |
961a008eee6916e048d1f0e7d6d77b05bb123b05 | Update Breast-cancer experiment. | lucasdavid/Manifold-Learning,lucasdavid/Manifold-Learning | experiments/diverse/5.2.6.breast_cancer.py | experiments/diverse/5.2.6.breast_cancer.py | import numpy as np
from experiments.base import LearningExperiment, ReductionExperiment
from manifold.infrastructure import Retriever
class BreastCancerExperiment(LearningExperiment, ReductionExperiment):
title = '5.2.6 Breast-cancer Isomap Experiment'
plotting = True
reduction_method = 'isomap'
def... | import numpy as np
from experiments.base import LearningExperiment, ReductionExperiment
from manifold.infrastructure import Retriever
class BreastCancerExperiment(LearningExperiment, ReductionExperiment):
title = '5.2.6 Breast-cancer Isomap Experiment'
plotting = True
reduction_method = 'isomap'
def... | mit | Python |
dc67f4c03caefb671bd91c4932dbd984b949f7d9 | Add startup message to tornado example app | 1stvamp/marked | examples/web/app.py | examples/web/app.py | from __future__ import print_function
from sys import stdout
from tornado.ioloop import IOLoop
from tornado.httpclient import AsyncHTTPClient
from tornado.web import asynchronous, RequestHandler, Application
from marked import markup_to_markdown
class MainHandler(RequestHandler):
def prepare(self):
self... | from tornado.ioloop import IOLoop
from tornado.httpclient import AsyncHTTPClient
from tornado.web import asynchronous, RequestHandler, Application
from marked import markup_to_markdown
class MainHandler(RequestHandler):
def prepare(self):
self.set_header('Content-Type', 'text/markdown; charset="utf-8"')
... | bsd-3-clause | Python |
c398eab1d419b4a447662f0dd02a9f2aaa66e244 | change spec of pyprika.load | OEP/pyprika | pyprika/__init__.py | pyprika/__init__.py | """
A Python package for recipe parsing and management.
"""
__version__ = '1.0.0'
__author__ = 'Paul Kilgo'
import yaml
import sys
from cStringIO import StringIO
from .exceptions import LoadError, ParseError
from .ingredient import Ingredient
from .quantity import Quantity
from .recipe import Recipe
def load(fp):
... | """
A Python package for recipe parsing and management.
"""
__version__ = '1.0.0'
__author__ = 'Paul Kilgo'
import yaml
import sys
from cStringIO import StringIO
from .exceptions import LoadError, ParseError
from .ingredient import Ingredient
from .quantity import Quantity
from .recipe import Recipe
def _loadfp(fp):... | mit | Python |
bbdf282e0ffd2db94be1204ee29f798eac8f3608 | Use mdp nfeature function in chainwalk. | stober/gridworld | src/chainwalk.py | src/chainwalk.py | #! /usr/bin/env python
"""
Author: Jeremy M. Stober
Program: CHAINWALK.PY
Date: Monday, January 11 2010
Description: Chainwalk from LSPI paper (2003).
"""
import os, sys, getopt, pdb, string
import random as pr
import numpy as np
import scipy as sp
import scipy.io as sio
from markovdp import MDP
class Chainwalk( MDP... | #! /usr/bin/env python
"""
Author: Jeremy M. Stober
Program: CHAINWALK.PY
Date: Monday, January 11 2010
Description: Chainwalk from LSPI paper (2003).
"""
import os, sys, getopt, pdb, string
import random as pr
import numpy as np
import scipy as sp
import scipy.io as sio
from markovdp import MDP
class Chainwalk( MDP... | bsd-2-clause | Python |
02a931fd738720fb57e57c97dba4113b943f41c6 | Bump to 3.1.2 dev. | reviewboard/rbtools,reviewboard/rbtools,reviewboard/rbtools | rbtools/__init__.py | rbtools/__init__.py | #
# __init__.py -- Basic version and package information
#
# Copyright (c) 2007-2009 Christian Hammond
# Copyright (c) 2007-2009 David Trowbridge
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the So... | #
# __init__.py -- Basic version and package information
#
# Copyright (c) 2007-2009 Christian Hammond
# Copyright (c) 2007-2009 David Trowbridge
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the So... | mit | Python |
6ebc5c21b32eb4446226f7adb86e8e5a32e8fd62 | change random to randum | Flamacue/foambot | src/cogs/foam.py | src/cogs/foam.py | import random
import os
from discord.ext import commands
SAMPLES_DIR = os.path.abspath("./../samples")
class Foam:
"""Foam related commands"""
def __init__(self, bot):
self.bot = bot
async def play_sound_clip(self, ctx, category):
vc = ctx.message.author.voice_channel
tc = ctx.m... | import random
import os
from discord.ext import commands
SAMPLES_DIR = os.path.abspath("./../samples")
class Foam:
"""Foam related commands"""
def __init__(self, bot):
self.bot = bot
async def play_sound_clip(self, ctx, category):
vc = ctx.message.author.voice_channel
tc = ctx.m... | apache-2.0 | Python |
1179386a98bd0219b4d619c6d4edf8c4df62a67c | Add pipiline. | geekan/scrapy-general-spider,geekan/scrapy-general-spider | general_spider/general_spider/pipelines.py | general_spider/general_spider/pipelines.py | # Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html
import redis
from scrapy import signals
import json
import codecs
from collections import OrderedDict
class TXTWithEncodingPipeline(object):
... | # Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html
import redis
from scrapy import signals
import json
import codecs
from collections import OrderedDict
class TXTWithEncodingPipeline(object):
... | apache-2.0 | Python |
46aaeb2c68ba65a69661a788ccaf7317aa64a633 | Add a redirect view that handles the old "new feedback" and "delivery receipt" URLs. | devilry/devilry-django,devilry/devilry-django,devilry/devilry-django,devilry/devilry-django | src/devilry_settings/default_urls.py | src/devilry_settings/default_urls.py | from django.conf.urls import include
from django.conf.urls import url
from django.contrib import admin
from django.core.urlresolvers import reverse
from django.http import HttpResponseBadRequest, HttpResponsePermanentRedirect
from devilry_frontpage.views import frontpage
admin.autodiscover()
def redirecto_to_show_de... | from django.conf.urls import include
from django.conf.urls import url
from django.contrib import admin
from devilry_frontpage.views import frontpage
admin.autodiscover()
devilry_urls = (
(r'^markup/', include('devilry.apps.markup.urls')),
(r'^jsfiledownload/', include('devilry.apps.jsfiledownload.urls')),
... | bsd-3-clause | Python |
e55630a73da0fe314861cb18bd07bd7d7a4bcc59 | Improve status bar message | jamesfzhang/rdio | rdio.py | rdio.py | '''
Rdio - Sublime Text Plugin
Provides a convenient way to pause, play, go to next/previous track,
and get current track information in the Rdio Mac application.
'''
import sublime
import sublime_plugin
import subprocess
class Rdio():
commands = {
'play': 'play',
'pause': 'pause',
'next': 'next trac... | '''
Rdio - Sublime Text Plugin
Provides a convenient way to pause, play, go to next/previous track,
and get current track information in the Rdio Mac application.
'''
import sublime
import sublime_plugin
import subprocess
class Rdio():
commands = {
'play': 'play',
'pause': 'pause',
'next': 'next trac... | mit | Python |
8bef9eae2b88eee0015ef4c3b77e8e77548bbf20 | clean whitespace | develersrl/rooms,develersrl/rooms,develersrl/rooms,develersrl/rooms,develersrl/rooms,develersrl/rooms,develersrl/rooms | trunk/editor/engine.py | trunk/editor/engine.py | #!/usr/bin/env python
import os
from shutil import rmtree
from os import mkdir
from subprocess import Popen
from os.path import split
from shutil import copy
import tempfile
from utils import g_ptransform
from savefilerooms import saveFileRooms
from structdata import g_project
def startEngine(engine):
"""
... | #!/usr/bin/env python
import os
from shutil import rmtree
from os import mkdir
from subprocess import Popen
from os.path import split
from shutil import copy
import tempfile
from utils import g_ptransform
from savefilerooms import saveFileRooms
from structdata import g_project
def startEngine(engine):
"""
... | mit | Python |
11529d7ad4d428bdd9f5a58adc1085a665d4f222 | Load the external interface on package import | bryanwweber/UConnRCMPy | uconnrcmpy/__init__.py | uconnrcmpy/__init__.py | from .ignitiondelayexp import ExperimentalIgnitionDelay
from .compare_to_sim import compare_to_sim
from .volume_trace import VolumeTraceBuilder
from .nonreactive import NonReactiveExperiments
__all__ = [
'ExperimentalIgnitionDelay',
'compare_to_sim',
'VolumeTraceBuilder',
'NonReactiveExperiments',
]
| bsd-3-clause | Python | |
070461032f3a22deab4879c8503d89b361d6366c | add max equality solution | timotheus/python-patterns | exercise/max_equality.py | exercise/max_equality.py | """
Maximum equality
================
Your colleague Beta Rabbit, top notch spy and saboteur, has been working tirelessly to discover a way to break into Professor Boolean's lab and rescue the rabbits being held inside. He has just excitedly informed you of a breakthrough - a secret bridge that leads over a moat (like... |
def assertEqual(a, b, label):
try:
assert(a == b)
print "%s == %s: %s" % (a, b, label)
except:
print("%s != %s: %s" % (a, b, label))
def moveUp(x, car):
try:
x[car+1] -= 1
x[car] += 1
except IndexError:
pass
def moveBack(x, car):
try:
x[ca... | unlicense | Python |
f718ad017131f295becc28386011e2e8c1070191 | reduce nesting | datasciencebr/serenata-de-amor,datasciencebr/serenata-de-amor | jarbas/celery.py | jarbas/celery.py | import logging
import os
from celery import Celery
from celery.schedules import crontab
from django.conf import settings
logger = logging.getLogger('celery')
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'jarbas.settings')
app = Celery('jarbas')
app.config_from_object('django.conf:settings', namespace='CELERY')
a... | import logging
import os
from celery import Celery
from celery.schedules import crontab
from django.conf import settings
logger = logging.getLogger('celery')
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'jarbas.settings')
app = Celery('jarbas')
app.config_from_object('django.conf:settings', namespace='CELERY')
a... | mit | Python |
cf76cd39320497e78dc23faffdf76112bec44612 | reformat code | mozman/ezdxf,mozman/ezdxf,mozman/ezdxf,mozman/ezdxf,mozman/ezdxf | src/ezdxf/lldxf/hdrvars.py | src/ezdxf/lldxf/hdrvars.py | # Purpose: header variables factory
# Copyright (c) 2010-2021, Manfred Moitzi
# License: MIT License
from typing import Sequence, Union
from .types import DXFVertex, DXFTag, cast_tag_value
def SingleValue(value: Union[str, float], code: int = 1) -> DXFTag:
return DXFTag(code, cast_tag_value(code, value))
def Po... | # Purpose: header variables factory
# Created: 20.11.2010
# Copyright (c) 2010-2018, Manfred Moitzi
# License: MIT License
from typing import Sequence, Union
from .types import DXFVertex, DXFTag, cast_tag_value
def SingleValue(value: Union[str, float], code: int = 1) -> DXFTag:
return DXFTag(code, cast_tag_value(... | mit | Python |
5e6f23fbefa7bad8b7c06ef310f3d875179d50e5 | Add disk.inodeusage and fix disk.usage logic | saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt | salt/modules/disk.py | salt/modules/disk.py | '''
Module for gathering disk information
'''
def usage():
'''
Return usage information for volumes mounted on this minion
CLI Example::
salt '*' disk.usage
'''
cmd = 'df -P'
ret = {}
out = __salt__['cmd.run'](cmd).split('\n')
for line in out:
if not line.count(' '):
... | '''
Module for gathering disk information
'''
def usage():
'''
Return usage information for volumes mounted on this minion
CLI Example::
salt '*' disk.usage
'''
cmd = 'df -P'
ret = {}
out = __salt__['cmd.run'](cmd).split('\n')
for line in out:
if not line.count(' '):
... | apache-2.0 | Python |
3c28d13136f55c22afa8a07fbf68d4f05923a9d5 | add doc string | saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt | salt/runners/test.py | salt/runners/test.py | # -*- coding: utf-8 -*-
'''
This runner is used only for test purposes and servers no production purpose
'''
from __future__ import absolute_import
from __future__ import print_function
# Import python libs
import time
import salt.ext.six as six
from salt.ext.six.moves import range
def arg(*args, **kwargs):
'''
... | # -*- coding: utf-8 -*-
'''
This runner is used only for test purposes and servers no production purpose
'''
from __future__ import absolute_import
from __future__ import print_function
# Import python libs
import time
import salt.ext.six as six
from salt.ext.six.moves import range
def arg(*args, **kwargs):
'''
... | apache-2.0 | Python |
5143aa0347bf5e6db1be1e0301429402d0435ebc | Update KC CTS | KhronosGroup/VK-GL-CTS,KhronosGroup/VK-GL-CTS,KhronosGroup/Vulkan-CTS,KhronosGroup/Vulkan-CTS,KhronosGroup/Vulkan-CTS,KhronosGroup/VK-GL-CTS,KhronosGroup/Vulkan-CTS,KhronosGroup/VK-GL-CTS,KhronosGroup/VK-GL-CTS,KhronosGroup/VK-GL-CTS,KhronosGroup/Vulkan-CTS,KhronosGroup/Vulkan-CTS | external/fetch_kc_cts.py | external/fetch_kc_cts.py | # -*- coding: utf-8 -*-
#-------------------------------------------------------------------------
# Khronos OpenGL CTS
# ------------------
#
# Copyright (c) 2016 The Khronos Group Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the Licens... | # -*- coding: utf-8 -*-
#-------------------------------------------------------------------------
# Khronos OpenGL CTS
# ------------------
#
# Copyright (c) 2016 The Khronos Group Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the Licens... | apache-2.0 | Python |
41649ad92eaf595d675dbb86345ceb88451d2c0a | add django project helper class | MyBook/fabric-utils,Eksmo/fabric-utils | fabric_utils/projects.py | fabric_utils/projects.py | # coding: utf-8
import os
from contextlib import contextmanager
from fabric.api import cd, sudo, settings
from .helpers import virtualenv
class PythonProject(object):
python_bin = 'python'
src = None
env = None
user = None
def __init__(self, *args, **kwargs):
pass
@property
def... | # coding: utf-8
import os
from contextlib import contextmanager
from fabric.api import cd
from .helpers import virtualenv
class PythonProject(object):
python_bin = 'python'
src = None
env = None
def __init__(self, *args, **kwargs):
pass
@property
def env_bin(self):
if not s... | bsd-3-clause | Python |
0a8800ee371f77beb1c9b456ef3026421cfb3e52 | include hostname to buildinfo | tsadm/desktop,tsadm/desktop,tsadm/desktop,tsadm/desktop | lib/tsdesktop/version.py | lib/tsdesktop/version.py | import time
import json
from os import path
from getpass import getuser
from platform import uname
VERSION = (16, 6, 0)
APPNAME = 'tsdesktop'
buildinfo = {
'TIME': None,
}
binfoFile = path.join(path.dirname(__file__), 'buildinfo.json')
def writeBuildInfo():
global buildinfo
buildinfo['TIME'] = time.time(... | import time
import json
from os import path
VERSION = (16, 6, 0)
APPNAME = 'tsdesktop'
buildinfo = {
'TIME': None,
}
binfoFile = path.join(path.dirname(__file__), 'buildinfo.json')
def writeBuildInfo():
global buildinfo
from getpass import getuser
buildinfo['TIME'] = time.time()
buildinfo['AUTHOR... | bsd-3-clause | Python |
0f586939be6cf40a1808f3ebc49dbd1bc67152ee | Use unicode, not str, in pretty output. | probcomp/bayeslite,probcomp/bayeslite | shell/src/pretty.py | shell/src/pretty.py | # -*- coding: utf-8 -*-
# Copyright (c) 2010-2014, MIT Probabilistic Computing Project
#
# 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/LICENS... | # -*- coding: utf-8 -*-
# Copyright (c) 2010-2014, MIT Probabilistic Computing Project
#
# 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/LICENS... | apache-2.0 | Python |
96820c1d3d7eccce4a80fc2447486d53ac37421c | add **TODO** due to #14 by @tudoanh | danleyb2/Instagram-API | InstagramAPI/src/http/Response/TimelineFeedResponse.py | InstagramAPI/src/http/Response/TimelineFeedResponse.py | from InstagramAPI.src.http.Response.Objects.FeedAysf import FeedAysf
from InstagramAPI.src.http.Response.Objects.Item import Item
from InstagramAPI.src.http.Response.Objects._Message import _Message
from Response import Response
class TimelineFeedResponse(Response):
def __init__(self, response):
self.num... | from InstagramAPI.src.http.Response.Objects.FeedAysf import FeedAysf
from InstagramAPI.src.http.Response.Objects.Item import Item
from InstagramAPI.src.http.Response.Objects._Message import _Message
from Response import Response
class TimelineFeedResponse(Response):
def __init__(self, response):
self.num... | mit | Python |
2e14019bc45e9d0c7f0f85bcaad984a040876b1b | Bump the version | sulami/feed2maildir | feed2maildir/__init__.py | feed2maildir/__init__.py | VERSION = '0.3.8'
| VERSION = '0.3.7'
| isc | Python |
8c52c1065c01cc9de74dcb7839cff6e3b895b9fb | Make background of scan-pixels.py transparent | milkey-mouse/BamboozLED,milkey-mouse/BamboozLED | scan-pixels.py | scan-pixels.py | #!/usr/bin/python3
from itertools import chain
import time
import opc
client = opc.Client("localhost:7891")
if client.can_connect():
for i in chain(range(5), range(3, -1, -1)):
arr = [(0, 0, 0, 0)] * 5
arr[i] = (255, 255, 255, 255)
client.put_pixels(arr, channel=1)
time.sleep(0.25)... | #!/usr/bin/python3
from itertools import chain
import time
import opc
client = opc.Client("localhost:7891")
if client.can_connect():
for i in chain(range(5), range(3, -1, -1)):
arr = [(0, 0, 0, 255)] * 5
arr[i] = (255, 255, 255, 255)
client.put_pixels(arr, channel=1)
time.sleep(0.2... | mit | Python |
b5bc2ca2dbaf497af4368f6653ebe2d38bd02f49 | make overlays in meta.screenshots.export optional | michaelcontento/monkey-shovel | screenshots.py | screenshots.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, division, with_statement
from PIL import Image, ImageFile
from shovel import task
from meta.utils import path_meta, path_generated, depends
ImageFile.MAXBLOCK = 2**20
def save(image, filename):
image.save(filename, "JPEG", quality=98, optimize=Tru... | # -*- coding: utf-8 -*-
from __future__ import absolute_import, division, with_statement
from PIL import Image, ImageFile
from shovel import task
from meta.utils import path_meta, path_generated, depends
ImageFile.MAXBLOCK = 2**20
def save(image, filename):
image.save(filename, "JPEG", quality=98, optimize=Tru... | apache-2.0 | Python |
e46c5ad6870af05ffa58576d7c2cf061231a4f46 | Make PEP-8 happy. | willrogers/pml,willrogers/pml,razvanvasile/RML | rml/element.py | rml/element.py | ''' Representation of an element
@param element_type: type of the element
@param length: length of the element
'''
import pkg_resources
from rml.exceptions import ConfigException
from cothread.catools import caget
class Element(object):
def __init__(self, element_type, length, **kwargs):
self.element_typ... | ''' Representation of an element
@param element_type: type of the element
@param length: length of the element
'''
import pkg_resources
from rml.exceptions import ConfigException
from cothread.catools import caget
class Element(object):
def __init__(self, element_type, length, **kwargs):
self.element_type... | apache-2.0 | Python |
1ac105b7efa3ae4c531fdcc8a626ab47d86e0192 | Write parameterized test for gen schema read function. | becketta/ctip | tests/test_gen_schema_reading_and_writing.py | tests/test_gen_schema_reading_and_writing.py | # -*- coding: utf-8 -*-
"""
Test parsing genfiles and writing GenSchema to genfiles.
Created on Sun Jul 10 19:54:47 2016
@author: Aaron Beckett
"""
import pytest
import json
from ctip import GenSchema
def gather_test_files():
"""Search the tests/resources directory for pairs of gen and config files."""
... | # -*- coding: utf-8 -*-
"""
Test parsing genfiles and writing GenSchema to genfiles.
Created on Sun Jul 10 19:54:47 2016
@author: Aaron Beckett
"""
import pytest
from ctip import GenSchema
def gather_test_files():
"""Search the tests/resources directory for pairs of gen and config files."""
pass
@pytes... | mit | Python |
528dfaaa2a860229f11fe28c3d67270f0f49a107 | Clean up test | balloob/github3.py,itsmemattchung/github3.py,icio/github3.py,ueg1990/github3.py,agamdua/github3.py,wbrefvem/github3.py,christophelec/github3.py,krxsky/github3.py,h4ck3rm1k3/github3.py,jim-minter/github3.py,sigmavirus24/github3.py,degustaf/github3.py | tests/test_issue_authorize_optional_scope.py | tests/test_issue_authorize_optional_scope.py | import github3
from tests.utils import BaseCase
"""
http://github3py.readthedocs.org/en/0.7.0/github.html#github3.github.GitHub
says scopes are required to create an authorization.
http://developer.github.com/v3/oauth/#create-a-new-authorization (at time of
writing - 2013-09-06) disagrees
"""
class TestOptionalScop... | import github3
from mock import patch, Mock
from tests.utils import (expect, BaseCase, load)
"""
http://github3py.readthedocs.org/en/0.7.0/github.html#github3.github.GitHub.authorize says scopes are required.
http://developer.github.com/v3/oauth/#create-a-new-authorization (at time of writing - 2013-09-06) disagrees
... | bsd-3-clause | Python |
6ceb07f21b5ca2bea239b14e26681fb732e88874 | Remove unused private field | srittau/rouver | rouver/util.py | rouver/util.py | from urllib.parse import quote, urljoin
from werkzeug import Request
def absolute_url(request: Request, path: str) -> str:
"""
Construct an absolute URL, using the request URL as base.
Non-printable and non-ASCII characters in the path are encoded,
but other characters, most notably slashes and perc... | import re
from urllib.parse import quote, urljoin
from werkzeug import Request
_url_scheme_re = re.compile(r"^[a-zA-Z][a-zA-Z0-9.+-]*:")
def absolute_url(request: Request, path: str) -> str:
"""
Construct an absolute URL, using the request URL as base.
Non-printable and non-ASCII characters in the path... | mit | Python |
03b81661c0ced9724ea3a75f17a1a993b7906ef0 | Fix send_newsletter command. It must use optparse in place of argparse | ljean/coop_cms,ljean/coop_cms,ljean/coop_cms | coop_cms/management/commands/send_newsletter.py | coop_cms/management/commands/send_newsletter.py | # -*- coding: utf-8 -*-
"""send newsletter"""
from __future__ import unicode_literals, print_function
from datetime import datetime
from django.core.management.base import BaseCommand
from coop_cms.utils import send_newsletter
from coop_cms.models import NewsletterSending
class Command(BaseCommand):
"""send n... | # -*- coding: utf-8 -*-
"""send newsletter"""
from __future__ import unicode_literals, print_function
from datetime import datetime
from django.core.management.base import BaseCommand
from coop_cms.utils import send_newsletter
from coop_cms.models import NewsletterSending
class Command(BaseCommand):
"""send n... | bsd-3-clause | Python |
d56301f67ec757e67047e9640ec607bff7a36d75 | switch to 'removesuffix' instead of 'rstrip' | dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq | corehq/ex-submodules/dimagi/utils/couch/undo.py | corehq/ex-submodules/dimagi/utils/couch/undo.py | from datetime import datetime
from dimagi.ext.couchdbkit import *
DELETED_SUFFIX = '-Deleted'
class DeleteRecord(Document):
base_doc = 'DeleteRecord'
domain = StringProperty()
datetime = DateTimeProperty()
class DeleteDocRecord(DeleteRecord):
doc_id = StringProperty()
def undo(self):
d... | from datetime import datetime
from dimagi.ext.couchdbkit import *
DELETED_SUFFIX = '-Deleted'
class DeleteRecord(Document):
base_doc = 'DeleteRecord'
domain = StringProperty()
datetime = DateTimeProperty()
class DeleteDocRecord(DeleteRecord):
doc_id = StringProperty()
def undo(self):
d... | bsd-3-clause | Python |
c170039187230f6afabf5aef7ab67c620c1f1547 | Bump up version | rehandalal/flask-funnel | flask_funnel/_version.py | flask_funnel/_version.py | # See http://www.python.org/dev/peps/pep-0386/
# Examples:
# * 1.0.dev
# * 1.0a2
# * 1.0b2
# * 1.0
__version__ = '0.1.6'
__releasedate__ = ''
| # See http://www.python.org/dev/peps/pep-0386/
# Examples:
# * 1.0.dev
# * 1.0a2
# * 1.0b2
# * 1.0
__version__ = '0.1.5'
__releasedate__ = ''
| bsd-3-clause | Python |
b236b609cc50cea920317b4f995705b3b47bf01a | Bump version to 0.2.4 | MichaelAquilina/s3backup,MichaelAquilina/s3backup | s4/__init__.py | s4/__init__.py | VERSION = '0.2.4'
| VERSION = '0.2.3'
| mit | Python |
987508d4ed62b31d1d89bc64de983f8a3a5e43d6 | Create function and documentation for creating a line chart | alexmilesyounger/ds_basics | s5v1.py | s5v1.py | from s4v3 import *
from matplotlib.pyplot as plt # import matplotlib's pyplot and assign it to a variable name. I didn't know you could do this, but it's pretty cool for unweildly and long library names or function. However, it's probably not great for universal readability since I'm changing a well known name into a ... | mit | Python | |
8422878593a0d8ca4bc440c338a4d92108507065 | make update_version.py also update auto generated documentation | archos-sa/libtorrent-avp,archos-sa/libtorrent-avp,archos-sa/libtorrent-avp,archos-sa/libtorrent-avp,archos-sa/libtorrent-avp,archos-sa/libtorrent-avp | set_version.py | set_version.py | #! /usr/bin/env python
import os
import sys
import glob
version = (int(sys.argv[1]), int(sys.argv[2]), int(sys.argv[3]), int(sys.argv[4]))
def substitute_file(name):
subst = ''
f = open(name)
for l in f:
if '#define LIBTORRENT_VERSION_MAJOR' in l and name.endswith('.hpp'):
l = '#define LIBTORRENT_VERSION_MAJO... | #! /usr/bin/env python
import os
import sys
import glob
version = (int(sys.argv[1]), int(sys.argv[2]), int(sys.argv[3]), int(sys.argv[4]))
def substitute_file(name):
subst = ''
f = open(name)
for l in f:
if '#define LIBTORRENT_VERSION_MAJOR' in l and name.endswith('.hpp'):
l = '#define LIBTORRENT_VERSION_MAJO... | bsd-3-clause | Python |
647f82bdb3bddcc066d8f38928ad4b22160f84ec | Add comment | ga4gh/ga4gh-common | ga4gh/common/__init__.py | ga4gh/common/__init__.py | """
Common utilities for GA4GH software
"""
# Don't include future imports here; we don't want to export them as
# part of the package
__version__ = "undefined"
try:
from . import _version
__version__ = _version.version
except ImportError:
pass
| """
Common utilities for GA4GH software
"""
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
__version__ = "undefined"
try:
from . import _version
__version__ = _version.version
except ImportError:
pass
| apache-2.0 | Python |
56cc448b7347ab47126c41c9961e17f26aabc128 | Correct manage league url | skill-huddle/skill-huddle,skill-huddle/skill-huddle | sh_app/urls.py | sh_app/urls.py | from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^about/$', views.about, name='about'),
url(r'^register/$', views.register, name='register'),
url(r'^login/$', views.user_login, name='login'),
url(r'^logout/$', views.user_logout, name... | from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^about/$', views.about, name='about'),
url(r'^register/$', views.register, name='register'),
url(r'^login/$', views.user_login, name='login'),
url(r'^logout/$', views.user_logout, name... | mit | Python |
b17655138b6ec3f9915a57c2e7279f95725ff6e0 | Clean up shovel test.quick | python-astrodynamics/spacetrack | shovel/test.py | shovel/test.py | # coding: utf-8
from __future__ import absolute_import, division, print_function
from collections import OrderedDict
from plumbum import FG, TF, local
from plumbum.cmd import doc8, flake8, sphinx_build
from shovel import task
pytest = local['py.test']
@task
def quick():
passed = OrderedDict()
passed['test... | # coding: utf-8
from __future__ import absolute_import, division, print_function
import subprocess
from collections import OrderedDict
from plumbum import local, FG
from shovel import task
pytest = local['py.test']
@task
def quick():
failed = OrderedDict.fromkeys(
['test', 'docs', 'spelling', 'doc8', '... | mit | Python |
78d520b88e13a35ac20a0eeea1385f35b17383d2 | Switch to more optimal non-generator solution | CubicComet/exercism-python-solutions | sieve/sieve.py | sieve/sieve.py | def sieve(n):
if n < 2:
return []
not_prime = set()
prime = [2]
for i in range(3, n+1, 2):
if i not in not_prime:
prime.append(i)
not_prime.update(range(i*i, n, i))
return prime
| def sieve(n):
return list(primes(n))
def primes(n):
if n < 2:
raise StopIteration
yield 2
not_prime = set()
for i in range(3, n+1, 2):
if i not in not_prime:
yield i
not_prime.update(range(i*i, n, i))
| agpl-3.0 | Python |
7e371ddcfcc7fdcdea190f76209be66c6b8831cb | Add contextual data to admin site | alykhank/Tunezout,alykhank/Tunezout | songs/admin.py | songs/admin.py | from django.contrib import admin
from songs.models import Genre, Song
class SongInline(admin.TabularInline):
model = Song
class GenreAdmin(admin.ModelAdmin):
inlines = [SongInline]
class SongAdmin(admin.ModelAdmin):
list_display = ('title', 'artist', 'year', 'genre', 'up', 'down', 'score')
admin.site.register(Ge... | from django.contrib import admin
from songs.models import Genre, Song
admin.site.register(Genre)
admin.site.register(Song)
| mit | Python |
3e0aa8305835362286f87681e8b0be625de252a9 | comment functions | rnagle/pycar | project1/extra_credit_state_banks_complete.py | project1/extra_credit_state_banks_complete.py | # Import built-in python modules we'll want to access csv files and import us module
# if you get an error run: pip install us or sudo pip install us
# Else contact @aboutaaron, @malev, @ryannagle
import csv
import us
def break_apart_states_into_files():
# We're going to download a csv file...
# What should we... | # Import built-in python modules we'll want to access csv files and import us module
# if you get an error run: pip install us or sudo pip install us
# Else contact @aboutaaron, @malev, @ryannagle
import csv
import us
def break_apart_states_into_files():
# We're going to download a csv file...
# What should we... | mit | Python |
59032cc1d0b06e0e8b688ecf568557de0cc7caf0 | Update solution.py | lilsweetcaligula/Online-Judges,lilsweetcaligula/Online-Judges,lilsweetcaligula/Online-Judges | leetcode/easy/single_number/py/solution.py | leetcode/easy/single_number/py/solution.py | #
# The functional approach we could use to locate the single number is
# to group the numbers by value and return the group with only a single
# number in it.
#
# The caveat to the groupping approach is we need a sorted array for
# best performance - O(n log n). Hence: itertools.groupby(sorted(nums))
#
# A more costl... | class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
import itertools
for num, group in itertools.groupby(sorted(nums)):
count = len(tuple(group))
if count == 1:
r... | mit | Python |
038fd9e8d38013a876dee16087beca9ea1eddf61 | add django_get_or_create on expert_category_factory | masschallenge/django-accelerator,masschallenge/django-accelerator | accelerator/tests/factories/expert_category_factory.py | accelerator/tests/factories/expert_category_factory.py | # MIT License
# Copyright (c) 2017 MassChallenge, Inc.
from __future__ import unicode_literals
import swapper
from factory import (
DjangoModelFactory,
Iterator,
)
from accelerator.apps import AcceleratorConfig
from accelerator.models import VALID_EXPERT_CATEGORIES
# The import of VALID_EXPERT_CATEGORIES is ... | # MIT License
# Copyright (c) 2017 MassChallenge, Inc.
from __future__ import unicode_literals
import swapper
from factory import (
DjangoModelFactory,
Iterator,
)
from accelerator.apps import AcceleratorConfig
from accelerator.models import VALID_EXPERT_CATEGORIES
# The import of VALID_EXPERT_CATEGORIES is ... | mit | Python |
0a49e485a8977e91af2cfa694827b32c774910c7 | Synchronize style | mattsmart/biomodels,mattsmart/biomodels,mattsmart/biomodels | agent_based_models/abm_conjugation_simple/plot_grid.py | agent_based_models/abm_conjugation_simple/plot_grid.py | import matplotlib.patches as mpatches
import matplotlib.pyplot as plt
"""
COMMENTS:
-radius seems to extend 85% of r, to intersect middle of line seg
-eg. radius 10 means hex takes up almost 20 x slots
-JAMES: will try circles
INPUT:
1) n
2) list of lists, of size n x n, containing labels (corres... | import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
"""
COMMENTS:
-radius seems to extend 85% of r, to intersect middle of line seg
-eg. radius 10 means hex takes up almost 20 x slots
-JAMES: will try circles
INPUT:
1) n
2) list of lists, of size n x n, containing labels (corres... | mit | Python |
9cb249fc2f7bc1043d50f7d9424026a3a68e4f2a | Add test we don't handle for `py/request-without-cert-validation` | github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql | python/ql/test/query-tests/Security/CWE-295-RequestWithoutValidation/make_request.py | python/ql/test/query-tests/Security/CWE-295-RequestWithoutValidation/make_request.py | import requests
#Simple cases
requests.get('https://semmle.com', verify=True) # GOOD
requests.get('https://semmle.com', verify=False) # BAD
requests.post('https://semmle.com', verify=True) # GOOD
requests.post('https://semmle.com', verify=False) # BAD
# Simple flow
put = requests.put
put('https://semmle.com', verify=... | import requests
#Simple cases
requests.get('https://semmle.com', verify=True) # GOOD
requests.get('https://semmle.com', verify=False) # BAD
requests.post('https://semmle.com', verify=True) # GOOD
requests.post('https://semmle.com', verify=False) # BAD
# Simple flow
put = requests.put
put('https://semmle.com', verify=... | mit | Python |
55f8bce3a4d1232f2b7ffbdfa2c1cf741686a33f | Make reverse migration for lot_type run | jackbravo/condorest-django,jackbravo/condorest-django,jackbravo/condorest-django | lots/migrations/0002_auto_20170717_2115.py | lots/migrations/0002_auto_20170717_2115.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.3 on 2017-07-18 02:15
from __future__ import unicode_literals
from django.db import models, migrations, connection
from lots.models import LotType, Lot
from revenue.models import Fee, Receipt
def load_data(apps, schema_editor):
LotType = apps.get_model("lots", ... | # -*- coding: utf-8 -*-
# Generated by Django 1.11.3 on 2017-07-18 02:15
from __future__ import unicode_literals
from django.db import models, migrations
from lots.models import LotType, Lot
from revenue.models import Fee, Receipt
def load_data(apps, schema_editor):
LotType = apps.get_model("lots", "LotType")
... | mpl-2.0 | Python |
9ffe8a195af0a2504728e4764d093152959474e8 | Fix MTO configurator not filled | Eficent/odoomrp-wip,oihane/odoomrp-wip,odoomrp/odoomrp-wip,jobiols/odoomrp-wip,esthermm/odoomrp-wip,esthermm/odoomrp-wip,Eficent/odoomrp-wip,jobiols/odoomrp-wip,Daniel-CA/odoomrp-wip-public,diagramsoftware/odoomrp-wip,diagramsoftware/odoomrp-wip,sergiocorato/odoomrp-wip,sergiocorato/odoomrp-wip,factorlibre/odoomrp-wip,... | mrp_product_variants/models/procurement.py | mrp_product_variants/models/procurement.py | # -*- coding: utf-8 -*-
# © 2015 Oihane Crucelaegui - AvanzOSC
# © 2016 Pedro M. Baeza <pedro.baeza@tecnativa.com>
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
from openerp import api, models
class ProcurementOrder(models.Model):
_inherit = 'procurement.order'
@api.model
def _prepare... | # -*- coding: utf-8 -*-
# © 2015 Oihane Crucelaegui - AvanzOSC
# © 2016 Pedro M. Baeza <pedro.baeza@tecnativa.com>
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
from openerp import api, models
class ProcurementOrder(models.Model):
_inherit = 'procurement.order'
@api.model
def _prepare... | agpl-3.0 | Python |
9bf031a73141ec1966e2929825660eab7ba05e10 | Rewrite examples/asyncs/dummy_server.py under new apps framework | clchiou/garage,clchiou/garage,clchiou/garage,clchiou/garage | py/garage/examples/asyncs/dummy_server.py | py/garage/examples/asyncs/dummy_server.py | """A server that does nothing."""
import logging
import curio
from garage import apps
from garage import parts
from garage.partdefs.asyncs import servers
LOG = logging.getLogger(__name__)
@parts.register_maker
async def dummy_server() -> servers.PARTS.server:
try:
duration = 10
LOG.info('slee... | """A server that does nothing."""
import logging
import curio
from garage import cli
from garage import components
from garage.startups.asyncs.servers import ServerContainerComponent
LOG = logging.getLogger(__name__)
class ServerComponent(components.Component):
provide = ServerContainerComponent.require.mak... | mit | Python |
eba69f1edefea197d8a083997f5f1d61ebf27c93 | Change how devices with no start_events are started | missionpinball/mpf,missionpinball/mpf | mpf/core/mode_device.py | mpf/core/mode_device.py | """Contains a class to implement mode devices."""
import abc
from mpf.core.device import Device
from mpf.core.mode import Mode
from mpf.core.player import Player
class ModeDevice(Device, metaclass=abc.ABCMeta):
"""A device in a mode."""
def __init__(self, machine, name):
"""Initialise mode device."... | """Contains a class to implement mode devices."""
import abc
from mpf.core.device import Device
from mpf.core.mode import Mode
from mpf.core.player import Player
class ModeDevice(Device, metaclass=abc.ABCMeta):
"""A device in a mode."""
def __init__(self, machine, name):
"""Initialise mode device."... | mit | Python |
0e167443fad746907c42ea91a8bade580f0e545a | Bump version. | racker/python-service-registry-cli,racker/python-service-registry-cli | service_registry_cli/__init__.py | service_registry_cli/__init__.py | # Copyright 2012 Rackspace
#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the... | # Copyright 2012 Rackspace
#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the... | apache-2.0 | Python |
42ac7f8c3fa178a488ed081c959f6f586678d77c | update test | dubirajara/django_my_ideas_wall,dubirajara/django_my_ideas_wall,dubirajara/django_my_ideas_wall,dubirajara/django_my_ideas_wall | myideas/core/tests/test_models.py | myideas/core/tests/test_models.py | from django.test import TestCase
from django.shortcuts import resolve_url as r
from django.contrib.auth import get_user_model
from django.utils.text import slugify
from myideas.core.models import Ideas
class IdeasModelTest(TestCase):
def setUp(self):
user = get_user_model().objects.create(username='admin... | from django.test import TestCase
from django.shortcuts import resolve_url as r
from django.contrib.auth import get_user_model
from myideas.core.models import Ideas
class IdeasModelTest(TestCase):
def setUp(self):
user = get_user_model().objects.create(username='adminapp')
self.idea = Ideas.object... | agpl-3.0 | Python |
8f3509593548f1064344c1712bb97687749efe8a | Update SetAndHandleEmpty.py | VirusTotal/content,demisto/content,demisto/content,demisto/content,VirusTotal/content,demisto/content,VirusTotal/content,VirusTotal/content | Scripts/SetAndHandleEmpty/SetAndHandleEmpty.py | Scripts/SetAndHandleEmpty/SetAndHandleEmpty.py | import demistomock as demisto
from CommonServerPython import *
def main():
args = demisto.args()
value = args.get('value')
if value:
human_readable = 'Key ' + args.get('key') + ' set'
context_entry = {args.get('key'): value}
else:
context_entry = {}
human_readable = 'va... | import demistomock as demisto
from CommonServerPython import *
def main():
args = demisto.args()
value = args.get('value')
if value:
human_readable = 'Key ' + args.get('key') + ' set'
context_entry = {args.get('key'): value}
else:
context_entry = {}
human_readable = 'va... | mit | Python |
2e43cdafdaf8fa12b3819557f0f36db8ec19ac0b | add alt_ignore_filename test | robphoenix/diffios,bordeltabernacle/diffios | tests/test_DiffiosFile.py | tests/test_DiffiosFile.py | import os
import sys
sys.path.append(os.path.abspath("../diffios"))
from diffios import DiffiosFile
from blocks import candidate_blocks, case_blocks
configs_dir = os.path.abspath("./configs/")
configs = sorted(os.path.join(configs_dir, f) for f in os.listdir(configs_dir))
dfs = [DiffiosFile(config) for config in con... | import os
import sys
sys.path.append(os.path.abspath("../diffios"))
from diffios import DiffiosFile
from blocks import candidate_blocks, case_blocks
configs_dir = os.path.abspath("./configs/")
configs = sorted(os.path.join(configs_dir, f) for f in os.listdir(configs_dir))
dfs = [DiffiosFile(config) for config in con... | mit | Python |
b9979a196c79ab1a2994210ccaae298d6462ce5d | Remove extra newline | murrown/cyder,murrown/cyder,murrown/cyder,akeym/cyder,akeym/cyder,OSU-Net/cyder,drkitty/cyder,OSU-Net/cyder,drkitty/cyder,drkitty/cyder,OSU-Net/cyder,drkitty/cyder,akeym/cyder,OSU-Net/cyder,akeym/cyder,murrown/cyder | cyder/cydns/soa/forms.py | cyder/cydns/soa/forms.py | from django.forms import ModelForm
from cyder.base.mixins import UsabilityFormMixin
from cyder.base.eav.forms import get_eav_form
from cyder.cydns.soa.models import SOA, SOAAV
class SOAForm(ModelForm, UsabilityFormMixin):
class Meta:
model = SOA
fields = ('root_domain', 'primary', 'contact', 'expi... | from django.forms import ModelForm
from cyder.base.mixins import UsabilityFormMixin
from cyder.base.eav.forms import get_eav_form
from cyder.cydns.soa.models import SOA, SOAAV
class SOAForm(ModelForm, UsabilityFormMixin):
class Meta:
model = SOA
fields = ('root_domain', 'primary', 'contact', 'expi... | bsd-3-clause | Python |
74cde77bfca8ecb237594f432607bb8b36363a87 | Remove deprecation warning test | pytest-dev/pluggy,pytest-dev/pluggy,RonnyPfannschmidt/pluggy,RonnyPfannschmidt/pluggy,hpk42/pluggy | testing/test_deprecations.py | testing/test_deprecations.py | """
Deprecation warnings testing roundup.
"""
import pytest
from pluggy.callers import _Result
from pluggy import PluginManager, HookimplMarker, HookspecMarker
hookspec = HookspecMarker("example")
hookimpl = HookimplMarker("example")
def test_result_deprecated():
r = _Result(10, None)
with pytest.deprecated_... | """
Deprecation warnings testing roundup.
"""
import pytest
from pluggy.callers import _Result
from pluggy import PluginManager, HookimplMarker, HookspecMarker
hookspec = HookspecMarker("example")
hookimpl = HookimplMarker("example")
def test_result_deprecated():
r = _Result(10, None)
with pytest.deprecated_... | mit | Python |
1ff1e785c2ed66ba6f4ec410ffd77c746524d656 | Bump version to 0.6.4 | josiah-wolf-oberholtzer/uqbar | uqbar/_version.py | uqbar/_version.py | __version_info__ = (0, 6, 4)
__version__ = ".".join(str(x) for x in __version_info__)
| __version_info__ = (0, 6, 3)
__version__ = ".".join(str(x) for x in __version_info__)
| mit | Python |
bec716d1135112fe0de5c634b1998fdf9ca9d0ad | Correct reference to client instance | armstrong/armstrong.esi | armstrong/esi/middleware.py | armstrong/esi/middleware.py | from django.core import urlresolvers
from django.core.cache import cache
from django.http import HttpResponse
import re
from . import http_client
def replace_esi_tags(request, content, url_data):
for url, (view, args, kwargs) in url_data.items():
esi_tag = '<esi:include src="%s" />' % url
client ... | from django.core import urlresolvers
from django.core.cache import cache
from django.http import HttpResponse
import re
from . import http_client
def replace_esi_tags(request, content, url_data):
for url, (view, args, kwargs) in url_data.items():
esi_tag = '<esi:include src="%s" />' % url
client ... | bsd-3-clause | Python |
e905334869af72025592de586b81650cb3468b8a | Declare queues when broker is instantiated | imankulov/sentry,BuildingLink/sentry,zenefits/sentry,korealerts1/sentry,kevinastone/sentry,fotinakis/sentry,fuziontech/sentry,ngonzalvez/sentry,mvaled/sentry,Kronuz/django-sentry,ngonzalvez/sentry,looker/sentry,felixbuenemann/sentry,ngonzalvez/sentry,nicholasserra/sentry,camilonova/sentry,jokey2k/sentry,llonchj/sentry,... | sentry/queue/client.py | sentry/queue/client.py | """
sentry.queue.client
~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from kombu import BrokerConnection
from kombu.common import maybe_declare
from kombu.pools import producers
from sentry.conf import settings
from sentry.q... | """
sentry.queue.client
~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from kombu import BrokerConnection
from kombu.common import maybe_declare
from kombu.pools import producers
from sentry.conf import settings
from sentry.q... | bsd-3-clause | Python |
7fb3397603440e8bed83dccd238c4599f21037dc | Fix hasher | aipescience/django-daiquiri,aipescience/django-daiquiri,aipescience/django-daiquiri | daiquiri/core/hashers.py | daiquiri/core/hashers.py | # inspired by https://djangosnippets.org/snippets/10572/
from collections import OrderedDict
from django.contrib.auth.hashers import CryptPasswordHasher, mask_hash
from django.utils.encoding import force_str
from django.utils.crypto import get_random_string, constant_time_compare
from django.utils.translation import u... | # inspired by https://djangosnippets.org/snippets/10572/
from collections import OrderedDict
from django.contrib.auth.hashers import CryptPasswordHasher, mask_hash
from django.utils.encoding import force_str
from django.utils.crypto import get_random_string, constant_time_compare
from django.utils.translation import u... | apache-2.0 | Python |
09865cc9f4d1558b86427669b9caa73c2c6bcae0 | Add some (trivial) models for bug search | onceuponatimeforever/oh-mainline,waseem18/oh-mainline,heeraj123/oh-mainline,ehashman/oh-mainline,heeraj123/oh-mainline,Changaco/oh-mainline,mzdaniel/oh-mainline,campbe13/openhatch,mzdaniel/oh-mainline,moijes12/oh-mainline,eeshangarg/oh-mainline,eeshangarg/oh-mainline,ehashman/oh-mainline,heeraj123/oh-mainline,vipul-sha... | mysite/search/models.py | mysite/search/models.py | from django.db import models
# Create your models here.
class Project(models.Model):
name = models.CharField(max_length=200)
language = models.CharField(max_length=200)
class Bug(models.Model):
project = models.ForeignKey(Project)
title = models.CharField(max_length=200)
description = models.TextF... | from django.db import models
# Create your models here.
| agpl-3.0 | Python |
35f7e69e8870fe2cac87fe1d2e31492ddf283972 | Fix bug. | bonprosoft/labcap,bonprosoft/labcap,bonprosoft/labcap | server/slack_notify.py | server/slack_notify.py | # -*- coding: utf-8 -*-
import json
import requests
import datetime
url = "https://hooks.slack.com/services/"
USERNAME = "yurei"
CHANNEL = "#room"
def create_timespan_string(timespan):
return "%d日%d時間%d分" % (timespan.days, timespan.seconds / (60 * 60), timespan.seconds % (60 * 60) / 60)
def notify_active(userna... | # -*- coding: utf-8 -*-
import json
import requests
import datetime
url = "https://hooks.slack.com/services/"
USERNAME = "yurei"
CHANNEL = "#room"
def create_timespan_string(timespan):
return "%d日%d時間%d分" % (timespan.days, timespan.seconds / (60 * 60), timespan.seconds % (60 * 60) / 60)
def notify_active(userna... | mit | Python |
45fc612fdc5a354dbf0bacccd345b1aebcc73e59 | Revert "Fix openweather unit tests" | rnyberg/pyfibot,EArmour/pyfibot,aapa/pyfibot,aapa/pyfibot,lepinkainen/pyfibot,rnyberg/pyfibot,lepinkainen/pyfibot,huqa/pyfibot,huqa/pyfibot,EArmour/pyfibot | tests/test_openweather.py | tests/test_openweather.py | # -*- coding: utf-8 -*-
import bot_mock
from pyfibot.modules import module_openweather
from utils import check_re
bot = bot_mock.BotMock()
def test_weather():
regex = u'Lappeenranta, FI: Temperature: \d+.\d\xb0C, feels like: \d+.\d\xb0C, wind: \d+.\d m/s, humidity: \d+%, pressure: \d+ hPa, cloudiness: \d+%'
... | # -*- coding: utf-8 -*-
import bot_mock
from pyfibot.modules import module_openweather
from utils import check_re
bot = bot_mock.BotMock()
def test_weather():
regex = u'Lappeenranta, FI: Temperature: \d+.\d\xb0C, feels like: \d+.\d\xb0C, wind: \d+.\d m/s, humidity: \d+%, pressure: \d+ hPa, cloudiness: \d+%'
... | bsd-3-clause | Python |
ef3271455ee4ae24ceca44029320bf6c0dfec047 | Fix outdated test | brandonPurvis/osf.io,monikagrabowska/osf.io,mluo613/osf.io,bdyetton/prettychart,wearpants/osf.io,caseyrygt/osf.io,ckc6cz/osf.io,njantrania/osf.io,doublebits/osf.io,pattisdr/osf.io,kch8qx/osf.io,reinaH/osf.io,njantrania/osf.io,felliott/osf.io,hmoco/osf.io,asanfilippo7/osf.io,chennan47/osf.io,TomHeatwole/osf.io,billyhunt... | tests/test_permissions.py | tests/test_permissions.py | # -*- coding: utf-8 -*-
"""Tests for the permissions module."""
import unittest
from nose.tools import * # PEP8 asserts
from website.util import permissions
def test_expand_permissions():
result = permissions.expand_permissions('admin')
assert_equal(result, ['read', 'write', 'admin'])
result2 = permiss... | # -*- coding: utf-8 -*-
"""Tests for the permissions module."""
import unittest
from nose.tools import * # PEP8 asserts
from website.util import permissions
def test_expand_permissions():
result = permissions.expand_permissions('admin')
assert_equal(result, ['read', 'write', 'admin'])
result2 = permiss... | apache-2.0 | Python |
28a98e8ac16a7d7b1a183efd526db4e89e26a9a5 | Fix basic_tagger example | explosion/thinc,spacy-io/thinc,explosion/thinc,spacy-io/thinc,explosion/thinc,explosion/thinc,spacy-io/thinc | examples/basic_tagger.py | examples/basic_tagger.py | from __future__ import print_function
from thinc.neural._classes.hash_embed import HashEmbed
from thinc.neural.vec2vec import Model, ReLu, Softmax
from thinc.api import layerize, chain, with_flatten
from thinc.extra.datasets import ancora_pos_tags
from thinc.neural.util import to_categorical
import plac
try:
im... | from __future__ import print_function
from thinc.neural._classes.hash_embed import HashEmbed
from thinc.neural.vec2vec import Model, ReLu, Softmax
from thinc.api import layerize, chain, with_flatten
from thinc.extra.datasets import ancora_pos_tags
from thinc.neural.util import to_categorical
import plac
try:
im... | mit | Python |
bbac4059628d626c90eceb9f04866b0296f810b7 | Make UploadGMResults include builder_name in upload path BUG=806 Review URL: https://codereview.appspot.com/6500090 | google/skia-buildbot,Tiger66639/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,google/skia-buildbot,google/skia-buildbot,google/skia-buildbot,Tiger66639/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,Ti... | slave/skia_slave_scripts/upload_gm_results.py | slave/skia_slave_scripts/upload_gm_results.py | #!/usr/bin/env python
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
""" Upload actual GM results to the skia-autogen SVN repository to aid in
rebaselining. """
from build_step import BuildStep
from ... | #!/usr/bin/env python
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
""" Upload actual GM results to the skia-autogen SVN repository to aid in
rebaselining. """
from build_step import BuildStep
from ... | bsd-3-clause | Python |
22faee82e1f070532c0dfe5777136e842233a1f0 | Fix % only showing 0 or 100%, everything between goes to 0%. | artefactual/archivematica-history,artefactual/archivematica-history,artefactual/archivematica-history,artefactual/archivematica-history | src/dashboard/src/main/templatetags/percentage.py | src/dashboard/src/main/templatetags/percentage.py | from django.template import Node, Library
register = Library()
@register.filter('percentage')
def percentage(value, total):
try:
percentage = float(value) / float(total) * 100
except ZeroDivisionError:
percentage = 0
return '<abbr title="%s/%s">%s%%</abbr>' % (value, total, percentage)
| from django.template import Node, Library
register = Library()
@register.filter('percentage')
def percentage(value, total):
try:
percentage = int(value) / int(total) * 100
except ZeroDivisionError:
percentage = 0
return '<abbr title="%s/%s">%s%%</abbr>' % (value, total, percentage)
| agpl-3.0 | Python |
7587e85bdedaca8e0d9244e50f9a26aeae7e67cf | add some logging | alexcormier/dotbot-rust | rust.py | rust.py | import dotbot
class Rust(dotbot.Plugin):
def __init__(self, context):
self._directives = {
"rust": self._handle_rust,
"cargo": self._handle_cargo
}
def can_handle(self, directive):
return directive in self._directives
def handle(self, directive, data):
... | import dotbot
class Rust(dotbot.Plugin):
def __init__(self, context):
self._directives = {
"rust": self._handle_rust,
"cargo": self._handle_cargo
}
def can_handle(self, directive):
return directive in self._directives
def handle(self, directive, data):
... | isc | Python |
7fc4e6b4afb3abbc2a7611e7fcdd2ab8af4c1699 | Fix PEP 8 issue. | thaim/ansible,thaim/ansible | lib/ansible/utils/helpers.py | lib/ansible/utils/helpers.py | # (c) 2016, Ansible by Red Hat <info@ansible.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later v... | # (c) 2016, Ansible by Red Hat <info@ansible.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later v... | mit | Python |
8b115a3d6a3ecdd7fc6945bbce20680dc1cca119 | Add a second Python solution for problem 10 | mdsrosa/project_euler,mdsrosa/project_euler,mdsrosa/project_euler,mdsrosa/project_euler,mdsrosa/project_euler,mdsrosa/project_euler,mdsrosa/project_euler,mdsrosa/project_euler | solutions/problem_10/solution.py | solutions/problem_10/solution.py | import sys
import os
sys.path.append(os.path.abspath(os.path.dirname('./utils/python')))
from python.utils import timeit, is_prime
LIMIT = 2000000
@timeit
def solution():
total_sum = 0
for n in xrange(2, LIMIT):
if is_prime(n):
total_sum += n
return total_sum
@timeit
def solution2():
... | import sys
import os
sys.path.append(os.path.abspath(os.path.dirname('./utils/python')))
from python.utils import timeit, is_prime
@timeit
def solution():
LIMIT = 2000000
total_sum = 0
for n in xrange(2, LIMIT):
if is_prime(n):
total_sum += n
return total_sum
solution()
| mit | Python |
7f9a086f32a949b52fc3876e3d07869b1670e62b | Bump version number | nabla-c0d3/nassl,nabla-c0d3/nassl,nabla-c0d3/nassl | nassl/__init__.py | nassl/__init__.py | # -*- coding: utf-8 -*-
__author__ = 'Alban Diquet'
__version__ = '1.1.2'
| # -*- coding: utf-8 -*-
__author__ = 'Alban Diquet'
__version__ = '1.1.1'
| agpl-3.0 | Python |
0e121fa91a58f66ee6e312c061d9a7815bbf0252 | add pluralization to fix broken extraction | bqbn/addons-server,Hitechverma/zamboni,ddurst/zamboni,kumar303/olympia,Witia1/olympia,anaran/olympia,SuriyaaKudoIsc/olympia,crdoconnor/olympia,harikishen/addons-server,Prashant-Surya/addons-server,jamesthechamp/zamboni,luckylavish/zamboni,mstriemer/addons-server,koehlermichael/olympia,lavish205/olympia,Jobava/zamboni,a... | mkt/reviewers/helpers.py | mkt/reviewers/helpers.py | from jingo import register
import jinja2
from tower import ugettext as _, ugettext_lazy as _lazy, ungettext as ngettext
import amo
from amo.helpers import impala_breadcrumbs
from amo.urlresolvers import reverse
from mkt.developers.helpers import mkt_page_title
from .views import queue_counts
@register.function
@jin... | from jingo import register
import jinja2
from tower import ugettext as _, ugettext_lazy as _lazy
import amo
from amo.helpers import impala_breadcrumbs
from amo.urlresolvers import reverse
from mkt.developers.helpers import mkt_page_title
from .views import queue_counts
@register.function
@jinja2.contextfunction
def... | bsd-3-clause | Python |
a3d0c85391b48baadcdad73dc2308c97c90028ce | Add an example with Subadres. Refs #34. | OnroerendErfgoed/crabpy | examples/crab_gateway.py | examples/crab_gateway.py | # -*- coding: utf-8 -*-
'''
This script demonstrates using the crab gateway to walk the entire
address tree (street and number) of a `gemeente`.
'''
from crabpy.client import crab_request, crab_factory
from crabpy.gateway.crab import CrabGateway
g = CrabGateway(crab_factory())
gemeente = g.get_gemeente_by_id(1)
pri... | # -*- coding: utf-8 -*-
'''
This script demonstrates using the crab gateway to walk the entire
address tree (street and number) of a `gemeente`.
'''
from crabpy.client import crab_request, crab_factory
from crabpy.gateway.crab import CrabGateway
g = CrabGateway(crab_factory())
gemeente = g.get_gemeente_by_id(1)
pri... | mit | Python |
52a0de9f04fc5f4d6ba4c6eadc9b972849427a54 | Add additional tests | CheriPai/TestAnalyzer,CheriPai/TestAnalyzer,CheriPai/TestAnalyzer | tests/test_pythonanalyzer.py | tests/test_pythonanalyzer.py | from pythonanalyzer import PythonAnalyzer
from unittest import TestCase
class TestPythonAnalyzer(TestCase):
def setUp(self):
self.analyzer = PythonAnalyzer()
def test_get_class_count_basic(self):
assert self.analyzer.get_class_count("class test:") == 1
def test_get_class_count_inherit(se... | from pythonanalyzer import PythonAnalyzer
from unittest import TestCase
class TestPythonAnalyzer(TestCase):
def setUp(self):
self.analyzer = PythonAnalyzer()
def test_get_class_count_basic(self):
assert self.analyzer.get_class_count("class test:") == 1
def test_get_class_count_none(self)... | mpl-2.0 | Python |
ba566ae5975825ffc96a9b4140fe49aecaad3654 | Test case functions | renalreg/radar,renalreg/radar,renalreg/radar,renalreg/radar | tests/test_transform_keys.py | tests/test_transform_keys.py | from radar.utils import (
snake_case,
camel_case,
snake_case_keys,
camel_case_keys
)
def test_snake_case():
return snake_case('fooBar') == 'foo_bar'
def test_camel_case():
return snake_case('foo_bar') == 'fooBar'
def test_snake_case_keys():
assert snake_case_keys({
'fooBar': [
... | from radar.utils import snake_case_keys, camel_case_keys
def test_snake_case_keys():
assert snake_case_keys({
'fooBar': [
{
'fooBar': 'helloWorld'
}
]
}) == {
'foo_bar': [
{
'foo_bar': 'helloWorld'
}
... | agpl-3.0 | Python |
2b1539824dade7fe69011c6fd72280e41c5123ee | Fix tile interface | consbio/seedsource,consbio/seedsource,consbio/seedsource | source/interfaces/tiles/views.py | source/interfaces/tiles/views.py | import mercantile
from clover.geometry.bbox import BBox
from clover.utilities.color import Color
from ncdjango.config import RenderConfiguration, ImageConfiguration
from ncdjango.views import GetImageViewBase
from pyproj import Proj
TILE_SIZE = (256, 256)
TRANSPARENT_BACKGROUND_COLOR = Color(255, 255, 255, 0)
class ... | import mercantile
from clover.geometry.bbox import BBox
from ncdjango.config import RenderConfiguration
from ncdjango.views import GetImageViewBase
from pyproj import Proj
TILE_SIZE = (256, 256)
class GetImageView(GetImageViewBase):
def get_service_name(self, request, *args, **kwargs):
return kwargs['ser... | bsd-3-clause | Python |
9382f8f79c1bc0363b430fd736e1495bf44f9888 | remove unused import | onelab-eu/sfa,onelab-eu/sfa,yippeecw/sfa,onelab-eu/sfa,yippeecw/sfa,yippeecw/sfa | sfa/storage/alchemy.py | sfa/storage/alchemy.py | from types import StringTypes
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy import Column, Integer, String
from sqlalchemy import ForeignKey
from sfa.util.sfalogging import logger
# this module is designed to be loaded when the configured db server is reachable
# OTOH ... | from types import StringTypes
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy import Column, Integer, String
from sqlalchemy.orm import relationship, backref
from sqlalchemy import ForeignKey
from sfa.util.sfalogging import logger
# this module is designed to be loaded w... | mit | Python |
950ac9130bafe1fced578bf61d746b047830bfa0 | Remove "validation" from RejectionException docstring | caleb531/automata | automata/base/exceptions.py | automata/base/exceptions.py | #!/usr/bin/env python3
"""Exception classes shared by all automata."""
class AutomatonException(Exception):
"""The base class for all automaton-related errors."""
pass
class InvalidStateError(AutomatonException):
"""A state is not a valid state for this automaton."""
pass
class InvalidSymbolErro... | #!/usr/bin/env python3
"""Exception classes shared by all automata."""
class AutomatonException(Exception):
"""The base class for all automaton-related errors."""
pass
class InvalidStateError(AutomatonException):
"""A state is not a valid state for this automaton."""
pass
class InvalidSymbolErro... | mit | Python |
afbb3f276163e2f6f0049600591d82cd0c1e2ada | fix wrong page bug in wospicker. | Impactstory/total-impact-webapp,Impactstory/total-impact-webapp,total-impact/total-impact-webapp,total-impact/total-impact-webapp,total-impact/total-impact-webapp,Impactstory/total-impact-webapp,total-impact/total-impact-webapp,Impactstory/total-impact-webapp | totalimpactwebapp/util.py | totalimpactwebapp/util.py | from functools import wraps
from flask import request, current_app
import random, math
# a slow decorator for tests, so can exclude them when necessary
# put @slow on its own line above a slow test method
# to exclude slow tests, run like this: nosetests -A "not slow"
def slow(f):
f.slow = True
return f
# de... | from functools import wraps
from flask import request, current_app
import random, math
# a slow decorator for tests, so can exclude them when necessary
# put @slow on its own line above a slow test method
# to exclude slow tests, run like this: nosetests -A "not slow"
def slow(f):
f.slow = True
return f
# de... | mit | Python |
b50b593f5fc6345274993cd1e8e52b420c59e83a | set abstract base class to false by default. | sassoftware/conary,sassoftware/conary,sassoftware/conary,sassoftware/conary,sassoftware/conary | conary/build/inforecipe.py | conary/build/inforecipe.py | #
# Copyright (c) 2005-2008 rPath, Inc.
#
# This program is distributed under the terms of the Common Public License,
# version 1.0. A copy of this license should have been distributed with this
# source file in a file called LICENSE. If it is not present, the license
# is always available at http://www.rpath.com/perma... | #
# Copyright (c) 2005-2008 rPath, Inc.
#
# This program is distributed under the terms of the Common Public License,
# version 1.0. A copy of this license should have been distributed with this
# source file in a file called LICENSE. If it is not present, the license
# is always available at http://www.rpath.com/perma... | apache-2.0 | Python |
ef27811d9194de7d9bc712ac9c13990c97a08da8 | Check for response is not None rather than bool(response) | rapidpro/tracpro,xkmato/tracpro,rapidpro/tracpro,xkmato/tracpro,xkmato/tracpro,xkmato/tracpro,rapidpro/tracpro | tracpro/orgs_ext/utils.py | tracpro/orgs_ext/utils.py | import logging
from requests import HTTPError
from temba_client.base import TembaAPIError
logger = logging.getLogger(__name__)
class OrgConfigField(object):
"""
Allows setting and retrieving of a config field as if it were a normal
class attribute.
The result of the initial retrieval is cached on... | import logging
from requests import HTTPError
from temba_client.base import TembaAPIError
logger = logging.getLogger(__name__)
class OrgConfigField(object):
"""
Allows setting and retrieving of a config field as if it were a normal
class attribute.
The result of the initial retrieval is cached on... | bsd-3-clause | Python |
4194ba2b25c2e8a6464dc2e0d711756836913384 | change pmid to pubmed | biothings/biothings_explorer,biothings/biothings_explorer | biothings_explorer/api_preprocess/semmed.py | biothings_explorer/api_preprocess/semmed.py | def restructure_semmed_response(json_doc, output_types):
"""Restructure the JSON output from semmed API.
:param: json_doc: the API response from semmed API
"""
if not isinstance(json_doc, list):
return json_doc
new_res = []
for _res in json_doc:
if not isinstance(_res, dict):
... | def restructure_semmed_response(json_doc, output_types):
"""Restructure the JSON output from semmed API.
:param: json_doc: the API response from semmed API
"""
if not isinstance(json_doc, list):
return json_doc
new_res = []
for _res in json_doc:
if not isinstance(_res, dict):
... | apache-2.0 | Python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.