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
bc593f1716a8e36e65cf75a58e524e77d38d5d9c
notation/statistics.py
notation/statistics.py
# encoding: utf-8 # included for ease of use with Python 2 (which has no statistics package) def mean(values): return float(sum(values)) / len(values) def median(values): middle = (len(values) - 1) // 2 if len(values) % 2: return values[middle] else: return mean(values[middle:middle ...
# encoding: utf-8 # included for ease of use with Python 2 (which has no statistics package) def mean(values): return float(sum(values)) / len(values) def quantile(p): def bound_quantile(values): ix = int(len(values) * p) if len(values) % 2: return values[ix] elif ix < 1...
Add a rudimentary quantile factory function.
Add a rudimentary quantile factory function.
Python
isc
debrouwere/python-ballpark
54c856e987bf570c7bcb8c449726a5d2895c0241
octopus/__init__.py
octopus/__init__.py
__version__ = "trunk" def run (runnable, logging = True): from twisted.internet import reactor if reactor.running: return runnable.run() else: def _complete (result): reactor.stop() def _run (): runnable.run().addBoth(_complete) if logging: import sys from twisted.python import log log.s...
__version__ = "trunk" def run (runnable, logging = True): from twisted.internet import reactor if reactor.running: return runnable.run() else: if logging: import sys from twisted.python import log log.startLogging(sys.stdout) runnable.on("log", log.msg) def _complete (result): reactor.stop...
Fix octopus.run for new events model.
Fix octopus.run for new events model.
Python
mit
richardingham/octopus,richardingham/octopus,richardingham/octopus,richardingham/octopus
fa98f32ce9c2d4e7dff8281bf5e6f154b82599d6
gargoyle/__init__.py
gargoyle/__init__.py
""" gargoyle ~~~~~~~~ :copyright: (c) 2010 DISQUS. :license: Apache License 2.0, see LICENSE for more details. """ __all__ = ('gargoyle', 'ConditionSet', 'autodiscover', 'VERSION') try: VERSION = __import__('pkg_resources') \ .get_distribution('gargoyle').version except Exception, e: VERSION = 'unkno...
""" gargoyle ~~~~~~~~ :copyright: (c) 2010 DISQUS. :license: Apache License 2.0, see LICENSE for more details. """ __all__ = ('gargoyle', 'ConditionSet', 'autodiscover', 'VERSION') try: VERSION = __import__('pkg_resources') \ .get_distribution('gargoyle').version except Exception, e: VERSION = 'unkno...
Use python import lib (django import lib will be removed in 1.9).
Use python import lib (django import lib will be removed in 1.9).
Python
apache-2.0
brilliant-org/gargoyle,brilliant-org/gargoyle,brilliant-org/gargoyle
3443c7164e490e0607fff599c497a4fc054f3c48
oslo_cache/_i18n.py
oslo_cache/_i18n.py
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # d...
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # d...
Update i18n domain to correct project name
Update i18n domain to correct project name The current oslo_i18n domain name is listed as oslo.versionedobjects Change-Id: I493b66efbd83fb7704fe927866a24b765feb1576
Python
apache-2.0
citrix-openstack-build/oslo.cache,openstack/oslo.cache,openstack/oslo.cache
ec235e290b4428dec2db03a19d678eba52f02fb5
keyring/getpassbackend.py
keyring/getpassbackend.py
"""Specific support for getpass.""" import os import getpass from keyring.core import get_password as original_get_password def get_password(prompt='Password: ', stream=None, service_name='Python', username=None): if username is None: username = getpass.getuser() retu...
"""Specific support for getpass.""" import os import getpass import keyring.core def get_password(prompt='Password: ', stream=None, service_name='Python', username=None): if username is None: username = getpass.getuser() return keyring.core.get_password(service_name, ...
Use module namespaces to distinguish names instead of 'original_' prefix
Use module namespaces to distinguish names instead of 'original_' prefix
Python
mit
jaraco/keyring
4a711a2709ec5d8a8e04bb0f735fcfaa319cffdf
designate/objects/validation_error.py
designate/objects/validation_error.py
# Copyright 2014 Hewlett-Packard Development Company, L.P. # # 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 requir...
# Copyright 2014 Hewlett-Packard Development Company, L.P. # # 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 requir...
Fix the displayed error message in V2 API
Fix the displayed error message in V2 API Change-Id: I07c3f1ed79fa507dbe9b76eb8f5964475516754c
Python
apache-2.0
tonyli71/designate,openstack/designate,ionrock/designate,ionrock/designate,ramsateesh/designate,grahamhayes/designate,cneill/designate-testing,muraliselva10/designate,muraliselva10/designate,cneill/designate-testing,openstack/designate,tonyli71/designate,muraliselva10/designate,grahamhayes/designate,ionrock/designate,t...
6fc2e75426eb34755bf6dbedbd21a4345d9c5738
plugins/websites.py
plugins/websites.py
import re from smartbot import utils class Plugin: def on_message(self, bot, msg, reply): match = re.findall(r"(https?://[^\s]+)", msg["message"], re.IGNORECASE) for i, url in enumerate(match): title = utils.web.get_title(url) if title: reply("[{0}]: {1}".f...
import io import re import unittest from smartbot import utils class Plugin: def on_message(self, bot, msg, reply): match = re.findall(r"(https?://[^\s]+)", msg["message"], re.IGNORECASE) for i, url in enumerate(match): title = utils.web.get_title(url) if title: ...
Add tests for website plugin
Add tests for website plugin
Python
mit
Muzer/smartbot,Cyanogenoid/smartbot,thomasleese/smartbot-old,tomleese/smartbot
8852955632b0ef0250ebbe21b5bdefdecdf30e8a
tests/test_dem.py
tests/test_dem.py
import unittest import numpy as np class CalculationMethodsTestCase(unittest.TestCase): def setUp(self): self.dem = DEMGrid() def test_calculate_slope(self): sx, sy = self.dem._calculate_slope() def test_calculate_laplacian(self): del2z = self.dem._calculate_lapalacian() ...
import unittest import numpy as np class CalculationMethodsTestCase(unittest.TestCase): def setUp(self): self.dem = DEMGrid() def test_calculate_slope(self): sx, sy = self.dem._calculate_slope() def test_calculate_laplacian(self): del2z = self.dem._calculate_lapalacian() ...
Remove redundant case from padding test
Remove redundant case from padding test
Python
mit
stgl/scarplet,rmsare/scarplet
d9938a50429db16ce60d905bca9844073fe2b0fa
this_app/forms.py
this_app/forms.py
from flask_wtf import FlaskForm from wtforms import StringField, PasswordField from wtforms.validators import Required, Length, Email class SignupForm(FlaskForm): """Render and validate the signup form""" email = StringField("Email", validators=[Required(), Email(), Length(1, 32)]) username = StringField(...
from flask_wtf import FlaskForm from wtforms import StringField, PasswordField, BooleanField from wtforms.validators import DataRequired, Length, Email class SignupForm(FlaskForm): """Render and validate the signup form""" email = StringField("Email", validators=[DataRequired(), Email(message="Invalid email f...
Use DataRequired to validate form
Use DataRequired to validate form
Python
mit
borenho/flask-bucketlist,borenho/flask-bucketlist
5f2ab0dcaec5a7826ff0652e7c052971083a8398
openid/test/datadriven.py
openid/test/datadriven.py
import unittest class DataDrivenTestCase(unittest.TestCase): cases = [] @classmethod def generateCases(cls): return cls.cases @classmethod def loadTests(cls): tests = [] for case in cls.generateCases(): if isinstance(case, tuple): test = cls(*c...
import unittest class DataDrivenTestCase(unittest.TestCase): cases = [] @classmethod def generateCases(cls): return cls.cases @classmethod def loadTests(cls): tests = [] for case in cls.generateCases(): if isinstance(case, tuple): test = cls(*c...
Replace ad-hoc pain with builtin methods
Replace ad-hoc pain with builtin methods
Python
apache-2.0
moreati/python3-openid,isagalaev/sm-openid,moreati/python3-openid,moreati/python3-openid,necaris/python3-openid,misli/python3-openid,necaris/python3-openid,misli/python3-openid,misli/python3-openid
89d8ee0b91c9fd579dcf965e9e07f18954625c72
xero/api.py
xero/api.py
from .manager import Manager class Xero(object): """An ORM-like interface to the Xero API""" OBJECT_LIST = (u'Contacts', u'Accounts', u'CreditNotes', u'Currencies', u'Invoices', u'Items', u'Organisation', u'Payments', u'TaxRates', u'TrackingCategories') def __init__...
from .manager import Manager class Xero(object): """An ORM-like interface to the Xero API""" OBJECT_LIST = (u'Contacts', u'Accounts', u'CreditNotes', u'Currencies', u'Invoices', u'Items', u'Organisation', u'Payments', u'TaxRates', u'TrackingCategories', u'ManualJournals'...
Add support for manual journals
Add support for manual journals
Python
bsd-3-clause
wegotpop/pyxero,jarekwg/pyxero,jaymcconnell/pyxero,opendesk/pyxero,thisismyrobot/pyxero,freakboy3742/pyxero,MJMortimer/pyxero,unomena/pyxero,schinckel/pyxero,unomena/pyxeropos,jacobg/pyxero,direvus/pyxero
fb9591c4a2801bfe5f5380c3e33aa44a25db3591
customforms/models.py
customforms/models.py
#!/usr/bin/python # -*- coding: utf-8 -*- from django.utils.translation import ugettext as _ from django.db import models class Form(models.Model): title = models.CharField(_("Title"), max_length=255) def __unicode__(self): return u'%s' % self.title class Meta: ordering = ('title', ) ...
#!/usr/bin/python # -*- coding: utf-8 -*- from django.core.urlresolvers import reverse from django.utils.translation import ugettext as _ from django.db import models class Form(models.Model): title = models.CharField(_("Title"), max_length=255) def __unicode__(self): return u'%s' % self.title ...
Add absolute URLs to form and question admin
Add absolute URLs to form and question admin
Python
apache-2.0
cschwede/django-customforms
d6ff777c7fb3f645c021da1319bb5d78d13aa9db
meshnet/interface.py
meshnet/interface.py
import serial import struct from siphashc import siphash def _hash(key: str, sender: int, receiver: int, msg_type: int, data: bytes): packed_data = struct.pack(">h>hBs", sender, receiver, msg_type, data) return struct.pack("Q", siphash(key, packed_data)) class SerialMessage(object): def __init__(self): ...
import serial import struct from siphashc import siphash def _hash(key: bytes, sender: int, receiver: int, msg_type: int, data: bytes): packed_data = struct.pack(">hhB", sender, receiver, msg_type) + data return struct.pack(">Q", siphash(key, packed_data)) class SerialMessage(object): def __init__(self)...
Fix python siphashing to match c implementation
Fix python siphashing to match c implementation Signed-off-by: Jan Losinski <577c4104c61edf9f052c616c0c23e67bef4a9955@wh2.tu-dresden.de>
Python
bsd-3-clause
janLo/automation_mesh,janLo/automation_mesh,janLo/automation_mesh
b2bab786c4af3dcca7d35b1e6ecff8699e542ec4
pytest_girder/pytest_girder/plugin.py
pytest_girder/pytest_girder/plugin.py
from .fixtures import * # noqa def pytest_addoption(parser): group = parser.getgroup('girder') group.addoption('--mock-db', action='store_true', default=False, help='Whether or not to mock the database using mongomock.') group.addoption('--mongo-uri', action='store', default='mongodb:...
import os from .fixtures import * # noqa def pytest_configure(config): """ Create the necessary directories for coverage. This is necessary because neither coverage nor pytest-cov have support for making the data_file directory before running. """ covPlugin = config.pluginmanager.get_plugin('_cov...
Add a pytest hook for creating the coverage data_file directory
Add a pytest hook for creating the coverage data_file directory
Python
apache-2.0
jbeezley/girder,jbeezley/girder,girder/girder,kotfic/girder,jbeezley/girder,data-exp-lab/girder,Xarthisius/girder,data-exp-lab/girder,girder/girder,RafaelPalomar/girder,jbeezley/girder,girder/girder,kotfic/girder,manthey/girder,kotfic/girder,girder/girder,RafaelPalomar/girder,Xarthisius/girder,RafaelPalomar/girder,Xart...
b1e6f3eacccb5e575ac47b6a40809f4671510672
rest_flex_fields/utils.py
rest_flex_fields/utils.py
try: # Python 3 from collections.abc import Iterable string_types = (str,) except ImportError: # Python 2 from collections import Iterable string_types = (str, unicode) def is_expanded(request, key): """ Examines request object to return boolean of whether passed field is expanded....
from collections.abc import Iterable def is_expanded(request, key): """ Examines request object to return boolean of whether passed field is expanded. """ expand = request.query_params.get("expand", "") expand_fields = [] for e in expand.split(","): expand_fields.extend([e for e i...
Drop Python 2 support in split_level utility function
Drop Python 2 support in split_level utility function
Python
mit
rsinger86/drf-flex-fields
494f14a69d08e9bfd556fccc6b4e2319db129a38
books/models.py
books/models.py
from django.contrib.auth.models import User from django.db import models from django.db.models import fields class Receipt(models.Model): title = fields.CharField(max_length=255) price = fields.DecimalField(max_digits=10, decimal_places=2) user = models.ForeignKey(User) def __str__(self): ret...
from django.contrib.auth.models import User from django.db import models from django.db.models import fields from django.utils import timezone class Receipt(models.Model): title = fields.CharField(max_length=255) price = fields.DecimalField(max_digits=10, decimal_places=2) created = fields.DateTimeField(a...
Add created and modified fields to Receipt
Add created and modified fields to Receipt
Python
mit
trimailov/finance,trimailov/finance,trimailov/finance
b1547647deec6c1edf54c497fa4ed20235ea6902
pymodels/middlelayer/devices/__init__.py
pymodels/middlelayer/devices/__init__.py
from .dcct import DCCT from .li_llrf import LiLLRF from .rf import RF from .sofb import SOFB from .kicker import Kicker from .septum import Septum from .screen import Screen from .bpm import BPM from .ict import ICT from .ict import TranspEff from .egun import HVPS from .egun import Filament
from .dcct import DCCT from .li_llrf import LiLLRF from .rf import RF from .sofb import SOFB from .kicker import Kicker from .septum import Septum from .screen import Screen from .bpm import BPM from .ict import ICT from .ict import TranspEff from .egun import Bias from .egun import Filament from .egun import HVPS
Add missing egun.bias in init
ENH: Add missing egun.bias in init
Python
mit
lnls-fac/sirius
5856e4daaf141e5bf9cdef438378a3757297f9c0
recipe_scrapers/wholefoods.py
recipe_scrapers/wholefoods.py
from ._abstract import AbstractScraper class WholeFoods(AbstractScraper): @classmethod def host(self, domain="com"): return f"www.wholefoodsmarket.{domain}"
from ._abstract import AbstractScraper class WholeFoods(AbstractScraper): @classmethod def host(self, domain="com"): return f"www.wholefoodsmarket.{domain}" def title(self): return self.schema.title() def total_time(self): return self.schema.total_time() def yields(self)...
Add wrapper methods for clarity.
Add wrapper methods for clarity.
Python
mit
hhursev/recipe-scraper
5f42f76ffd11e82d51a334b91d64723388ca4a0d
newswall/providers/feed.py
newswall/providers/feed.py
from datetime import datetime import feedparser import time from newswall.providers.base import ProviderBase class Provider(ProviderBase): def update(self): feed = feedparser.parse(self.config['source']) for entry in feed['entries']: self.create_story(entry.link, titl...
""" RSS Feed Provider ================= Required configuration keys:: { "provider": "newswall.providers.feed", "source": "http://twitter.com/statuses/user_timeline/feinheit.rss" } """ from datetime import datetime import feedparser import time from newswall.providers.base import ProviderBase class ...
Add RSS Feed Provider docs
Add RSS Feed Provider docs
Python
bsd-3-clause
michaelkuty/django-newswall,registerguard/django-newswall,matthiask/django-newswall,HerraLampila/django-newswall,registerguard/django-newswall,HerraLampila/django-newswall,michaelkuty/django-newswall,matthiask/django-newswall
931e2d1e8ba3fd6b129a6d74e3a1ad9984c1938a
benchmarks/benchmarks/bench_random.py
benchmarks/benchmarks/bench_random.py
from __future__ import absolute_import, division, print_function from .common import Benchmark import numpy as np class Random(Benchmark): params = ['normal', 'uniform', 'weibull 1', 'binomial 10 0.5', 'poisson 10'] def setup(self, name): items = name.split() name = items.pop(...
from __future__ import absolute_import, division, print_function from .common import Benchmark import numpy as np from numpy.lib import NumpyVersion class Random(Benchmark): params = ['normal', 'uniform', 'weibull 1', 'binomial 10 0.5', 'poisson 10'] def setup(self, name): items = nam...
Add benchmark tests for numpy.random.randint.
ENH: Add benchmark tests for numpy.random.randint. This add benchmarks randint. There is one set of benchmarks for the default dtype, 'l', that can be tracked back, and another set for the new dtypes 'bool', 'uint8', 'uint16', 'uint32', and 'uint64'.
Python
bsd-3-clause
shoyer/numpy,Dapid/numpy,jakirkham/numpy,WarrenWeckesser/numpy,chatcannon/numpy,WarrenWeckesser/numpy,b-carter/numpy,anntzer/numpy,ssanderson/numpy,simongibbons/numpy,nbeaver/numpy,SiccarPoint/numpy,numpy/numpy,Eric89GXL/numpy,kiwifb/numpy,seberg/numpy,rgommers/numpy,ESSS/numpy,shoyer/numpy,anntzer/numpy,utke1/numpy,dw...
ca8e15d50b816c29fc2a0df27d0266826e38b5b8
cellcounter/statistics/serializers.py
cellcounter/statistics/serializers.py
from rest_framework.serializers import ModelSerializer from .models import CountInstance class CountInstanceSerializer(ModelSerializer): class Meta: model = CountInstance
from rest_framework.serializers import ModelSerializer from .models import CountInstance class CountInstanceSerializer(ModelSerializer): class Meta: model = CountInstance fields = ('count_total',)
Update serializer to deal with new model
Update serializer to deal with new model
Python
mit
cellcounter/cellcounter,haematologic/cellcounter,cellcounter/cellcounter,cellcounter/cellcounter,haematologic/cellcounter,haematologic/cellcounter,cellcounter/cellcounter
3245946ff25889149dc60cf6b1364bd09c953809
faas/puzzleboard-pop/puzzleboard_pop.py
faas/puzzleboard-pop/puzzleboard_pop.py
import json from datetime import datetime import requests from .model.puzzleboard import pop_puzzleboard class HuntwordsPuzzleBoardPopCommand(object): '''Command class that processes puzzleboard-pop message''' def run(self, jreq): '''Command that processes puzzleboard-pop message''' req = ...
import json from datetime import datetime import requests from .model.puzzleboard import pop_puzzleboard class HuntwordsPuzzleBoardPopCommand(object): '''Command class that processes puzzleboard-pop message''' def run(self, jreq): '''Command that processes puzzleboard-pop message''' req = ...
Change url from relative to internal service endpoint
Change url from relative to internal service endpoint
Python
mit
klmcwhirter/huntwords,klmcwhirter/huntwords,klmcwhirter/huntwords,klmcwhirter/huntwords
608dc0db688be1dabe3c6ba7647807f6697fcefe
tools/misc/python/test-data-in-out.py
tools/misc/python/test-data-in-out.py
# TOOL test-data-in-out.py: "Test data input and output in Python" (Data input output test.) # INPUT input TYPE GENERIC # OUTPUT output # OUTPUT OPTIONAL missing_output.txt import shutil shutil.copyfile('input', 'output')
# TOOL test-data-in-out.py: "Test data input and output in Python" (Data input output test.) # INPUT input TYPE GENERIC # OUTPUT output # OUTPUT OPTIONAL missing_output.txt # IMAGE chipster-tools-python import shutil shutil.copyfile('input', 'output')
Test image definition in SADL
Test image definition in SADL
Python
mit
chipster/chipster-tools,chipster/chipster-tools,chipster/chipster-tools,chipster/chipster-tools
5548e32a32bd1cd5951ce50e74c0fad944a1cf04
ideascube/conf/idb_col_llavedelsaber.py
ideascube/conf/idb_col_llavedelsaber.py
"""Configuration for Llave Del Saber, Colombia""" from .idb import * # noqa from django.utils.translation import ugettext_lazy as _ LANGUAGE_CODE = 'es' DOMAIN = 'bibliotecamovil.lan' ALLOWED_HOSTS = ['.bibliotecamovil.lan', 'localhost'] USER_FORM_FIELDS = USER_FORM_FIELDS + ( (_('Personal informations'), ['...
"""Configuration for Llave Del Saber, Colombia""" from .idb import * # noqa from django.utils.translation import ugettext_lazy as _ LANGUAGE_CODE = 'es' DOMAIN = 'bibliotecamovil.lan' ALLOWED_HOSTS = ['.bibliotecamovil.lan', 'localhost'] USER_FORM_FIELDS = USER_FORM_FIELDS + ( (_('Personal informations'), ['...
Stop using the extra field for Colombia
Stop using the extra field for Colombia After discussion, this is not something we will have in Ideascube. Fixes #609
Python
agpl-3.0
ideascube/ideascube,ideascube/ideascube,ideascube/ideascube,ideascube/ideascube
c1b433e5ed4c06b956b4d27f6da4e8b1dab54aaf
services/cloudwatch/sample.py
services/cloudwatch/sample.py
''' =================================== Boto 3 - CloudWatch Service Example =================================== This application implements the CloudWatch service that lets you gets information from Amazon Cloud Watch. See the README for more details. ''' import boto3 ''' Define your AWS credentials: ''' AWS_ACCESS_KE...
''' =================================== Boto 3 - CloudWatch Service Example =================================== This application implements the CloudWatch service that lets you gets information from Amazon Cloud Watch. See the README for more details. ''' import boto3 ''' Define your AWS credentials: ''' AWS_ACCESS_KE...
Fix issue in cloudwacth service credentials
Fix issue in cloudwacth service credentials
Python
mit
rolandovillca/aws_samples_boto3_sdk
a05a05f24c29dcf039e02b55c18c476dc69757df
shell_manager/problem_repo.py
shell_manager/problem_repo.py
""" Problem repository management for the shell manager. """ import spur, gzip from shutil import copy2 from os.path import join def local_update(repo_path, deb_paths=[]): """ Updates a local deb repository by copying debs and running scanpackages. Args: repo_path: the path to the local reposito...
""" Problem repository management for the shell manager. """ import spur, gzip from shutil import copy2 from os.path import join def update_repo(args): """ Main entrypoint for repo update operations. """ if args.repo_type == "local": local_update(args.repository, args.package_paths) else...
Update repo entrypoint and remote_update stub.
Update repo entrypoint and remote_update stub.
Python
mit
RitwikGupta/picoCTF-shell-manager,cganas/picoCTF-shell-manager,RitwikGupta/picoCTF-shell-manager,cganas/picoCTF-shell-manager,picoCTF/picoCTF-shell-manager,cganas/picoCTF-shell-manager,cganas/picoCTF-shell-manager,RitwikGupta/picoCTF-shell-manager,picoCTF/picoCTF-shell-manager,picoCTF/picoCTF-shell-manager,picoCTF/pico...
6f7dba3beccca655b84879ccd0f3071d15536b2f
test/utils.py
test/utils.py
# coding: utf-8 import string import random def generate_string(str_len=6, src=string.ascii_lowercase): return "".join(random.choice(src) for x in xrange(str_len)) def lorem_ipsum(): words_count = random.randint(20, 50) lorem = list([]) for i in xrange(words_count): word_length = random.randin...
# coding: utf-8 import string import random def generate_string(str_len=6, src=string.ascii_lowercase): return "".join(random.choice(src) for x in xrange(str_len)) def lorem_ipsum(words_count=30): lorem = list([]) for i in xrange(words_count): word_length = random.randint(4, 8) lorem.app...
Add word_count parameter for lorem_ipsum generator
Add word_count parameter for lorem_ipsum generator
Python
mit
sarutobi/Rynda,sarutobi/flowofkindness,sarutobi/ritmserdtsa,sarutobi/ritmserdtsa,sarutobi/flowofkindness,sarutobi/Rynda,sarutobi/ritmserdtsa,sarutobi/ritmserdtsa,sarutobi/Rynda,sarutobi/flowofkindness,sarutobi/flowofkindness,sarutobi/Rynda
d80f7a89b5bc23802ad5ec9bb8cc6ad523976718
test_gitnl.py
test_gitnl.py
from __future__ import print_function, division, absolute_import import unittest import gitnl class GitnlTestCase(unittest.TestCase): """Tests from 'gitnl.py'.""" def test_push_remotename_branchfrom(self): desired = 'push remotename branchfrom' actual = gitnl.parse_to_git('push my branch bra...
from __future__ import print_function, division, absolute_import import unittest import gitnl class GitnlTestCase(unittest.TestCase): """Tests from 'gitnl.py'.""" def test_push_remotename_branchfrom(self): desired = 'push remotename branchfrom' actual = gitnl.parse_to_git('push my branch bra...
Add rename branch locally test
Add rename branch locally test
Python
mit
eteq/gitnl,eteq/gitnl
fb213097e838ddfa40d9f71f1705d7af661cfbdf
tests/unit.py
tests/unit.py
# -*- coding: latin-1 -*- import unittest from github2.issues import Issue from github2.client import Github class ReprTests(unittest.TestCase): """__repr__ must return strings, not unicode objects.""" def test_issue(self): """Issues can have non-ASCII characters in the title.""" i = Issue(t...
# -*- coding: latin-1 -*- import unittest from github2.issues import Issue from github2.client import Github class ReprTests(unittest.TestCase): """__repr__ must return strings, not unicode objects.""" def test_issue(self): """Issues can have non-ASCII characters in the title.""" i = Issue(t...
Allow tests to be run with Python <2.6.
Allow tests to be run with Python <2.6.
Python
bsd-3-clause
ask/python-github2
4be7f694220ee969683f07b982f8fcbe61971a04
hairball/plugins/duplicate.py
hairball/plugins/duplicate.py
"""This module provides plugins for basic duplicate code detection.""" from hairball.plugins import HairballPlugin class DuplicateScripts(HairballPlugin): """Plugin that keeps track of which scripts have been used more than once whithin a project.""" def __init__(self): super(DuplicateScripts, ...
"""This module provides plugins for basic duplicate code detection.""" from hairball.plugins import HairballPlugin class DuplicateScripts(HairballPlugin): """Plugin that keeps track of which scripts have been used more than once whithin a project.""" def __init__(self): super(DuplicateScripts, ...
Add comment to explain the length of the scripts taken into account in DuplicateScripts
Add comment to explain the length of the scripts taken into account in DuplicateScripts
Python
bsd-2-clause
ucsb-cs-education/hairball,jemole/hairball,thsunmy/hairball,jemole/hairball,ucsb-cs-education/hairball,thsunmy/hairball
15996286496d913c25290362ba2dba2d349bd5f6
imageManagerUtils/settings.py
imageManagerUtils/settings.py
# Copyright (c) 2017, MIT Licensed, Medicine Yeh # This file helps to read settings from bash script into os.environ import os import sys import subprocess # This path is the location of the caller script MAIN_SCRIPT_PATH = os.path.dirname(os.path.abspath(sys.argv[0])) # Set up the path to settings.sh settings_path ...
# Copyright (c) 2017, MIT Licensed, Medicine Yeh # This file helps to read settings from bash script into os.environ import os import sys import subprocess # This path is the location of the caller script MAIN_SCRIPT_PATH = os.path.dirname(os.path.abspath(sys.argv[0])) # Set up the path to settings.sh settings_path ...
Fix bug of invoking /bin/sh on several OSs
Fix bug of invoking /bin/sh on several OSs
Python
mit
snippits/qemu_image,snippits/qemu_image,snippits/qemu_image
c027e671d1a47d485755b748f2dffc202c704ff8
goodreadsapi.py
goodreadsapi.py
#!/usr/bin/env python import re from xml.parsers.expat import ExpatError import requests import xmltodict from settings import goodreads_api_key def get_goodreads_ids(comment_msg): # receives goodreads url # returns the id using regex regex = r'goodreads.com/book/show/(\d+)' return set(re.findall(r...
#!/usr/bin/env python import re from xml.parsers.expat import ExpatError import requests import xmltodict from settings import goodreads_api_key def get_goodreads_ids(comment_msg): # receives goodreads url # returns the id using regex regex = r'goodreads.com/book/show/(\d+)' return set(re.findall(r...
Update goodreads API to `show original_publication_year`
Update goodreads API to `show original_publication_year`
Python
mit
avinassh/Reddit-GoodReads-Bot
59b015bb3e45497b7ec86bf1799e8442a30b65da
py/PMUtil.py
py/PMUtil.py
# PMUtil.py # Phenotype microarray utility functions # # Author: Daniel A Cuevas # Created on 27 Jan. 2015 # Updated on 27 Jan. 2015 from __future__ import absolute_import, division, print_function import sys import time import datetime def timeStamp(): '''Return time stamp''' t = time.time() fmt = '[%Y-...
# PMUtil.py # Phenotype microarray utility functions # # Author: Daniel A Cuevas # Created on 27 Jan 2015 # Updated on 20 Aug 2015 from __future__ import absolute_import, division, print_function import sys import time import datetime def timeStamp(): '''Return time stamp''' t = time.time() fmt = '[%Y-%m...
Exit method. - (New) Added exit method.
Exit method. - (New) Added exit method.
Python
mit
dacuevas/PMAnalyzer,dacuevas/PMAnalyzer,dacuevas/PMAnalyzer,dacuevas/PMAnalyzer
a8976ff1c3bdc177ca72becf48c4278f963d2627
gtr/__init__.py
gtr/__init__.py
__all__ = [ "gtr.services.funds.Funds", "gtr.services.organisations.Organisations", "gtr.services.persons.Persons", "gtr.services.projects.Projects" ] __version__ = "0.1.0" from gtr.services.base import _Service from gtr.services.funds import Funds from gtr.services.organisations import Organisations f...
__all__ = [ "gtr.services.funds.Funds", "gtr.services.organisations.Organisations", "gtr.services.persons.Persons", "gtr.services.projects.Projects", "gtr.services.publications.Publications" ] __version__ = "0.1.0" from gtr.services.base import _Service from gtr.services.funds import Funds from gtr...
Add Publications class to initialisation
Add Publications class to initialisation
Python
apache-2.0
nestauk/gtr
63a26cbf76a3d0135f5b67dd10cc7f383ffa7ebf
helusers/jwt.py
helusers/jwt.py
from django.conf import settings from rest_framework_jwt.authentication import JSONWebTokenAuthentication from rest_framework_jwt.settings import api_settings from .user_utils import get_or_create_user def patch_jwt_settings(): """Patch rest_framework_jwt authentication settings from allauth""" defaults = ap...
from django.conf import settings from rest_framework import exceptions from rest_framework_jwt.authentication import JSONWebTokenAuthentication from rest_framework_jwt.settings import api_settings from .user_utils import get_or_create_user def patch_jwt_settings(): """Patch rest_framework_jwt authentication sett...
Change authenticate_credentials method to raise an exception if the account is disabled
Change authenticate_credentials method to raise an exception if the account is disabled
Python
bsd-2-clause
City-of-Helsinki/django-helusers,City-of-Helsinki/django-helusers
764f8d9d7818076555cde5fcad29f3052b523771
company/autocomplete_light_registry.py
company/autocomplete_light_registry.py
import autocomplete_light from .models import Company class CompanyAutocomplete(autocomplete_light.AutocompleteModelBase): search_fields = ['^name'] model = Company autocomplete_light.register(CompanyAutocomplete)
import autocomplete_light from .models import Company class CompanyAutocomplete(autocomplete_light.AutocompleteModelBase): search_fields = ['name', 'official_name', 'common_name'] model = Company autocomplete_light.register(CompanyAutocomplete)
Add more search fields to autocomplete
Add more search fields to autocomplete
Python
bsd-3-clause
KlubJagiellonski/pola-backend,KlubJagiellonski/pola-backend,KlubJagiellonski/pola-backend,KlubJagiellonski/pola-backend
a06010fcb2f4424d085da1487a6666867a8cbf5b
dbaas/maintenance/admin/maintenance.py
dbaas/maintenance/admin/maintenance.py
# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals from django_services import admin from ..models import Maintenance from ..service.maintenance import MaintenanceService class MaintenanceAdmin(admin.DjangoServicesAdmin): service_class = MaintenanceService search_fields = ("sche...
# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals from django_services import admin from ..models import Maintenance from ..service.maintenance import MaintenanceService from ..forms import MaintenanceForm class MaintenanceAdmin(admin.DjangoServicesAdmin): service_class = Maintenanc...
Remove add_view and add form for the hole admin
Remove add_view and add form for the hole admin
Python
bsd-3-clause
globocom/database-as-a-service,globocom/database-as-a-service,globocom/database-as-a-service,globocom/database-as-a-service
6f822cf46957d038588e7a71eb91f8ca9f9c95f1
scaffolder/commands/install.py
scaffolder/commands/install.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from optparse import make_option from optparse import OptionParser from scaffolder.core.template import TemplateManager from scaffolder.core.commands import BaseCommand class InstallCommand(BaseCommand): option_list = BaseCommand.option_list + ( make_option( ...
#!/usr/bin/env python # -*- coding: utf-8 -*- from optparse import make_option from optparse import OptionParser from scaffolder import get_minion_path from scaffolder.core.template import TemplateManager from scaffolder.core.commands import BaseCommand class InstallCommand(BaseCommand): option_list = BaseCommand...
Use get_minion_path to get default dir.
InstallCommand: Use get_minion_path to get default dir.
Python
mit
goliatone/minions
95d9bb3a9500d80b5064c5fb4d5bd7b30406d1ae
conanfile.py
conanfile.py
from conans import ConanFile, CMake class GrpccbConan(ConanFile): name = "grpc_cb_core" version = "0.2" license = "Apache-2.0" url = "https://github.com/jinq0123/grpc_cb_core" description = "C++ gRPC core library with callback interface." settings = "os", "compiler", "build_type", "arch" op...
from conans import ConanFile, CMake class GrpccbConan(ConanFile): name = "grpc_cb_core" version = "0.2" license = "Apache-2.0" url = "https://github.com/jinq0123/grpc_cb_core" description = "C++ gRPC core library with callback interface." settings = "os", "compiler", "build_type", "arch" op...
Fix update remote to ConanCenter and grpc to highest buildable/supported version
Fix update remote to ConanCenter and grpc to highest buildable/supported version
Python
apache-2.0
jinq0123/grpc_cb_core,jinq0123/grpc_cb_core,jinq0123/grpc_cb_core
c13a12e6355423d6756b8b514942596c31b0e3a9
conanfile.py
conanfile.py
from conans import ConanFile from conans.tools import download, unzip import os VERSION = "0.0.7" class CMakeModuleCommonConan(ConanFile): name = "cmake-module-common" version = os.environ.get("CONAN_VERSION_OVERRIDE", VERSION) generators = "cmake" url = "http://github.com/polysquare/cmake-module-com...
from conans import ConanFile from conans.tools import download, unzip import os VERSION = "0.0.7" class CMakeModuleCommonConan(ConanFile): name = "cmake-module-common" version = os.environ.get("CONAN_VERSION_OVERRIDE", VERSION) generators = "cmake" url = "http://github.com/polysquare/cmake-module-com...
Make cmake-unit, cmake-linter-cmake and style-linter-cmake normal deps
conan: Make cmake-unit, cmake-linter-cmake and style-linter-cmake normal deps
Python
mit
polysquare/cmake-module-common
306e6939c5b369f4a4ef4bb4d16948dc1f027f53
tests/test_initial_ismaster.py
tests/test_initial_ismaster.py
# Copyright 2015 MongoDB, 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 law or agreed to in writing, so...
# Copyright 2015 MongoDB, 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 law or agreed to in writing, so...
Update for PYTHON 985: MongoClient properties now block until connected.
Update for PYTHON 985: MongoClient properties now block until connected.
Python
apache-2.0
ajdavis/pymongo-mockup-tests
af5e90cb544e2e37819302f5750084fc17f7ee12
make_example.py
make_example.py
#!/usr/bin/env python import os import sys import yaml import subprocess class SDBUSPlus(object): def __init__(self, path): self.path = path def __call__(self, *a, **kw): args = [ os.path.join(self.path, 'sdbus++'), '-t', os.path.join(self.path, 'template...
#!/usr/bin/env python import os import sys import yaml import subprocess if __name__ == '__main__': genfiles = { 'server-cpp': lambda x: '%s.cpp' % x, 'server-header': lambda x: os.path.join( os.path.join(*x.split('.')), 'server.hpp') } with open(os.path.join('example', 'inter...
Remove sdbus++ template search workaround
Remove sdbus++ template search workaround sdbus++ was fixed upstream to find its templates automatically. Change-Id: I29020b9d1ea4ae8baaca5fe869625a3d96cd6eaf Signed-off-by: Brad Bishop <713d098c0be4c8fd2bf36a94cd08699466677ecd@fuzziesquirrel.com>
Python
apache-2.0
openbmc/phosphor-inventory-manager,openbmc/phosphor-inventory-manager
1e07e9424a1ac69e1e660e6a6f1e58bba15472c1
make_spectra.py
make_spectra.py
# -*- coding: utf-8 -*- import halospectra as hs import randspectra as rs import sys snapnum=sys.argv[1] sim=sys.argv[2] #base="/n/hernquistfs1/mvogelsberger/projects/GFM/Production/Cosmo/Cosmo"+str(sim)+"_V6/L25n512/output/" #savedir="/n/home11/spb/scratch/Cosmo/Cosmo"+str(sim)+"_V6_512/snapdir_"+str(snapnum).rjust(3...
# -*- coding: utf-8 -*- import halospectra as hs import randspectra as rs import sys snapnum=sys.argv[1] sim=sys.argv[2] #base="/n/hernquistfs1/mvogelsberger/projects/GFM/Production/Cosmo/Cosmo"+str(sim)+"_V6/L25n512/output/" #savedir="/n/home11/spb/scratch/Cosmo/Cosmo"+str(sim)+"_V6_512/snapdir_"+str(snapnum).rjust(3...
Implement saving and loading the observer tau
Implement saving and loading the observer tau
Python
mit
sbird/vw_spectra
8316a60ba2887a511579e8cedb90b3a02fc1889a
dope/util.py
dope/util.py
from uuid import UUID from werkzeug.routing import BaseConverter class UUIDConverter(BaseConverter): to_python = UUID to_url = str
from uuid import UUID from werkzeug.routing import BaseConverter class UUIDConverter(BaseConverter): to_python = UUID def to_url(self, obj): return str(obj).replace('-', '')
Drop dashes from download urls.
Drop dashes from download urls.
Python
mit
mbr/dope,mbr/dope
9d46df1680e3d799971e73ec73043c2a6c0590ce
scripts/build_tar.py
scripts/build_tar.py
#! /usr/bin/python import os import subprocess root_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), "..")) tarfile = os.path.join(root_dir, "src_pkg.tar") def _is_dir_newer(directory, filename): file_mtime = os.stat(filename).st_mtime for dirname, _, filenames in os.walk(directory): for ...
#! /usr/bin/python import os import subprocess root_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), "..")) tarfile = os.path.join(root_dir, "src_pkg.tar") def _is_dir_newer(directory, filename): file_mtime = os.stat(filename).st_mtime for dirname, _, filenames in os.walk(directory): if _...
Fix building tar in deployment
Fix building tar in deployment
Python
bsd-3-clause
vmalloc/mailboxer,Infinidat/lanister,vmalloc/mailboxer,Infinidat/lanister,getslash/mailboxer,vmalloc/mailboxer,getslash/mailboxer,getslash/mailboxer
a1390619619a364b9fab13504fb5c2464491d449
Largest_Palindrome_Product.py
Largest_Palindrome_Product.py
# Find the largest palindrome made from the product of two n-digit numbers. # Since the result could be very large, you should return the largest palindrome mod 1337. # Example: # Input: 2 # Output: 987 # Explanation: 99 x 91 = 9009, 9009 % 1337 = 987 # Note: # The range of n is [1,8]. def largestPalindrome(n): "...
# Find the largest palindrome made from the product of two n-digit numbers. # Since the result could be very large, you should return the largest palindrome mod 1337. # Example: # Input: 2 # Output: 987 # Explanation: 99 x 91 = 9009, 9009 % 1337 = 987 # Note: # The range of n is [1,8]. from itertools import product...
Refactor Largest Palindrome Product for range of n is
Refactor Largest Palindrome Product for range of n is [1,8]
Python
mit
Kunal57/Python_Algorithms
de4af7935c1c8d6751c5a71ad90dd5f531f7a1b0
bin/trigger_upload.py
bin/trigger_upload.py
#!/bin/env python # -*- coding: utf8 -*- """ Triggers an upload process with the specified raw.xz URL. """ import argparse import logging import logging.config import multiprocessing.pool import fedmsg.config import fedimg.uploader logging.config.dictConfig(fedmsg.config.load_config()['logging']) log = logging.getLo...
#!/bin/env python # -*- coding: utf8 -*- """ Triggers an upload process with the specified raw.xz URL. """ import argparse import logging import logging.config import multiprocessing.pool import fedmsg.config import fedimg.uploader logging.config.dictConfig(fedmsg.config.load_config()['logging']) log = logging.getLo...
Fix the script function args
fedimg: Fix the script function args Signed-off-by: Sayan Chowdhury <5f0367a2b3b757615b57f51d912cf16f2c0ad827@gmail.com>
Python
agpl-3.0
fedora-infra/fedimg,fedora-infra/fedimg
166bff52496bfb47c5a3a03585bd10fb449b8d77
Lib/curses/__init__.py
Lib/curses/__init__.py
"""curses The main package for curses support for Python. Normally used by importing the package, and perhaps a particular module inside it. import curses from curses import textpad curses.initwin() ... """ __revision__ = "$Id$" from _curses import * from curses.wrapper import wrapper
"""curses The main package for curses support for Python. Normally used by importing the package, and perhaps a particular module inside it. import curses from curses import textpad curses.initwin() ... """ __revision__ = "$Id$" from _curses import * from curses.wrapper import wrapper # Some const...
Add wrapper for initscr() to copy the ACS_ and LINES,COLS bindings
Add wrapper for initscr() to copy the ACS_ and LINES,COLS bindings
Python
mit
sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator
17faea99343e37036b7ee35e5d3273f98a52dba9
Python/tomviz/utils.py
Python/tomviz/utils.py
import numpy as np import vtk.numpy_interface.dataset_adapter as dsa def get_scalars(dataobject): do = dsa.WrapDataObject(dataobject) # get the first rawarray = do.PointData.GetScalars() vtkarray = dsa.vtkDataArrayToVTKArray(rawarray, do) vtkarray.Association = dsa.ArrayAssociation.POINT return...
import numpy as np import vtk.numpy_interface.dataset_adapter as dsa import vtk.util.numpy_support as np_s def get_scalars(dataobject): do = dsa.WrapDataObject(dataobject) # get the first rawarray = do.PointData.GetScalars() vtkarray = dsa.vtkDataArrayToVTKArray(rawarray, do) vtkarray.Association =...
Fix numpy related errors on Mavericks.
Fix numpy related errors on Mavericks. The problem was due to the fact that operations (like sqrt) can return a float16 arrays which cannot be passed back to VTK directly. Added a temporary conversion to float64. We should potentially handle this in VTK.
Python
bsd-3-clause
cryos/tomviz,thewtex/tomviz,cjh1/tomviz,cryos/tomviz,cryos/tomviz,Hovden/tomviz,Hovden/tomviz,yijiang1/tomviz,cjh1/tomviz,thewtex/tomviz,OpenChemistry/tomviz,mathturtle/tomviz,yijiang1/tomviz,cjh1/tomviz,mathturtle/tomviz,OpenChemistry/tomviz,thewtex/tomviz,OpenChemistry/tomviz,mathturtle/tomviz,OpenChemistry/tomviz
e753038de039fd23f0d59bb0094f59fc73efe22b
flask_apscheduler/json.py
flask_apscheduler/json.py
import flask import json from datetime import datetime from apscheduler.job import Job from .utils import job_to_dict class JSONEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, datetime): return obj.isoformat() if isinstance(obj, Job): return job_to_d...
import datetime import flask import json from apscheduler.job import Job from .utils import job_to_dict loads = json.loads def dumps(obj, indent=None): return json.dumps(obj, indent=indent, cls=JSONEncoder) def jsonify(data, status=None): indent = None if flask.current_app.config['JSONIFY_PRETTYPRINT_...
Set a custom JSON Encoder to serialize date class.
Set a custom JSON Encoder to serialize date class.
Python
apache-2.0
viniciuschiele/flask-apscheduler
edcfe2b156af23943478bc86592b4c8d5dc07e10
flask_mongoengine/json.py
flask_mongoengine/json.py
from flask.json import JSONEncoder from bson import json_util from mongoengine.base import BaseDocument from mongoengine import QuerySet def _make_encoder(superclass): class MongoEngineJSONEncoder(superclass): ''' A JSONEncoder which provides serialization of MongoEngine documents and quer...
from flask.json import JSONEncoder from bson import json_util from mongoengine.base import BaseDocument try: from mongoengine.base import BaseQuerySet except ImportError as ie: # support mongoengine < 0.7 from mongoengine.queryset import QuerySet as BaseQuerySet def _make_encoder(superclass): class MongoEn...
Support older versions of MongoEngine
Support older versions of MongoEngine
Python
bsd-3-clause
gerasim13/flask-mongoengine-1,rochacbruno/flask-mongoengine,quokkaproject/flask-mongoengine,quokkaproject/flask-mongoengine,gerasim13/flask-mongoengine-1,losintikfos/flask-mongoengine,rochacbruno/flask-mongoengine,losintikfos/flask-mongoengine
3d7b5d61b7e985d409cd50c98d4bcbdc8ab9c723
mailer.py
mailer.py
from marrow.mailer import Mailer as MarrowMailer from message import Message import sys class Mailer: MAILER = MarrowMailer(dict(manager=dict(use='immediate'), transport=dict(use='sendmail'))) @staticmethod def send(message): Mailer.MAILER.send(message) @staticmethod def start(): Mailer.MAILER.s...
from marrow.mailer import Mailer as MarrowMailer from message import Message import sys import os import pwd import socket class Mailer: MAILER = MarrowMailer(dict(manager=dict(use='immediate'), transport=dict(use='sendmail'))) DEFAULT_AUTHOR = pwd.getpwuid(os.getuid()).pw_name + '@' + socket.getfqdn() @stat...
Use current user as email author
Use current user as email author
Python
isc
2mv/raapija
65973802a3e68e23f9a903937ef94f8afa277013
ibmcnx/doc/DataSources.py
ibmcnx/doc/DataSources.py
###### # Check ExId (GUID) by Email through JDBC # # Author: Christoph Stoettner # Mail: christoph.stoettner@stoeps.de # Documentation: http://scripting101.stoeps.de # # Version: 2.0 # Date: 2014-06-04 # # License: Apache 2.0 # # Check ExId of a User in all Connections Appli...
###### # Check ExId (GUID) by Email through JDBC # # Author: Christoph Stoettner # Mail: christoph.stoettner@stoeps.de # Documentation: http://scripting101.stoeps.de # # Version: 2.0 # Date: 2014-06-04 # # License: Apache 2.0 # # Check ExId of a User in all Connections Appli...
Create documentation of DataSource Settings
: Create documentation of DataSource Settings Task-Url:
Python
apache-2.0
stoeps13/ibmcnx2,stoeps13/ibmcnx2
93f2ff45ff3d61487ed061ae3d1a65051c3d1799
django/contrib/admin/__init__.py
django/contrib/admin/__init__.py
from django.contrib.admin.options import ModelAdmin, HORIZONTAL, VERTICAL from django.contrib.admin.options import StackedInline, TabularInline from django.contrib.admin.sites import AdminSite, site def autodiscover(): """ Auto-discover INSTALLED_APPS admin.py modules and fail silently when not present. T...
# ACTION_CHECKBOX_NAME is unused, but should stay since its import from here # has been referenced in documentation. from django.contrib.admin.helpers import ACTION_CHECKBOX_NAME from django.contrib.admin.options import ModelAdmin, HORIZONTAL, VERTICAL from django.contrib.admin.options import StackedInline, TabularInli...
Revert the removal of an unused import (in [14175]) that was referenced in documentation. Thanks for noticing, clong.
Revert the removal of an unused import (in [14175]) that was referenced in documentation. Thanks for noticing, clong. git-svn-id: 554f83ef17aa7291f84efa897c1acfc5d0035373@14359 bcc190cf-cafb-0310-a4f2-bffc1f526a37
Python
bsd-3-clause
svn2github/django,svn2github/django,svn2github/django
445f244ddac6001b65f03d058a14178a19919eed
diamondash/config.py
diamondash/config.py
import yaml from diamondash import utils class ConfigError(Exception): """Raised when there is an error parsing a configuration""" class ConfigMetaClass(type): def __new__(mcs, name, bases, dict): cls = type.__new__(mcs, name, bases, dict) defaults = {} for base in bases: ...
import yaml from diamondash import utils class ConfigError(Exception): """Raised when there is an error parsing a configuration""" class ConfigMetaClass(type): def __new__(mcs, name, bases, dict): cls = type.__new__(mcs, name, bases, dict) defaults = {} for base in bases: ...
Allow Config to be initialised without any args
Allow Config to be initialised without any args
Python
bsd-3-clause
praekelt/diamondash,praekelt/diamondash,praekelt/diamondash
bfcec696308ee8bfd226a54c17a7e15d49e2aed7
var/spack/repos/builtin/packages/nextflow/package.py
var/spack/repos/builtin/packages/nextflow/package.py
from spack import * from glob import glob import os class Nextflow(Package): """Data-driven computational pipelines""" homepage = "http://www.nextflow.io" version('0.20.1', '0e4e0e3eca1c2c97f9b4bffd944b923a', url='https://github.com/nextflow-io/nextflow/releases/download/v0.20.1/nextflow', ...
############################################################################## # Copyright (c) 2013-2016, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-64...
Add standard header, use spack helpers
Add standard header, use spack helpers Added the standard header (stolen from R). Touched up the install to use set_executable rather than doing it myself.
Python
lgpl-2.1
matthiasdiener/spack,mfherbst/spack,lgarren/spack,tmerrick1/spack,TheTimmy/spack,LLNL/spack,tmerrick1/spack,TheTimmy/spack,TheTimmy/spack,matthiasdiener/spack,LLNL/spack,iulian787/spack,matthiasdiener/spack,krafczyk/spack,tmerrick1/spack,EmreAtes/spack,TheTimmy/spack,tmerrick1/spack,iulian787/spack,matthiasdiener/spack...
e81b1ce7536ce32e022fb3132f8468d2472b2e31
atlas/prodtask/management/commands/extendopenended.py
atlas/prodtask/management/commands/extendopenended.py
from django.core.management.base import BaseCommand, CommandError from atlas.prodtask.open_ended import check_open_ended class Command(BaseCommand): args = '<request_id, request_id>' help = 'Extend open ended requests' def handle(self, *args, **options): if not args: try: ...
from django.core.management.base import BaseCommand, CommandError import time from atlas.prodtask.open_ended import check_open_ended class Command(BaseCommand): args = '<request_id, request_id>' help = 'Extend open ended requests' def handle(self, *args, **options): self.stdout.write('Start open ...
Improve logging of openended extension
Improve logging of openended extension
Python
apache-2.0
PanDAWMS/panda-bigmon-atlas,PanDAWMS/panda-bigmon-atlas,PanDAWMS/panda-bigmon-atlas,PanDAWMS/panda-bigmon-atlas
6632157febfed7ce99fa1aaecb72393b0301d3aa
geotrek/authent/migrations/0003_auto_20181203_1518.py
geotrek/authent/migrations/0003_auto_20181203_1518.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations from django.core.management import call_command from django.conf import settings def add_permissions(apps, schema_editor): if 'geotrek.infrastructure' in settings.INSTALLED_APPS: call_command('update_geotrek_...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('authent', '0002_auto_20181107_1620'), ] operations = [ ]
Make empty migration authent 3
Make empty migration authent 3
Python
bsd-2-clause
makinacorpus/Geotrek,GeotrekCE/Geotrek-admin,GeotrekCE/Geotrek-admin,makinacorpus/Geotrek,GeotrekCE/Geotrek-admin,GeotrekCE/Geotrek-admin,makinacorpus/Geotrek,makinacorpus/Geotrek
0324d220872ef063cb39ce62264bd4835f260920
test_project/urls.py
test_project/urls.py
from django.conf.urls import include, url from django.contrib import admin from django.views.generic import RedirectView from test_app.models import DummyModel, MushroomSpot from test_app.views import DummyDocumentOdt, DummyDocumentWeasyprint from mapentity.registry import registry handler403 = 'mapentity.views.hand...
from django.conf.urls import include, url from django.contrib import admin from django.views.generic import RedirectView from test_app.models import DummyModel, MushroomSpot from test_app.views import DummyDocumentOdt, DummyDocumentWeasyprint from mapentity.registry import registry from django.contrib.auth import view...
Replace str into call in url
Replace str into call in url
Python
bsd-3-clause
makinacorpus/django-mapentity,makinacorpus/django-mapentity,makinacorpus/django-mapentity
a53612d5f276180d204378b9e4974fcd812f6a5b
tests/fake_camera.py
tests/fake_camera.py
from os import listdir from os.path import isfile, join class Camera(object): def __init__(self, path): self.files = [join(path, f) for f in listdir(path)] self.files = sorted([f for f in self.files if isfile(f)]) self.current = 0 def reset(self): self.current = 0 def ha...
# -*- coding: utf-8 -*- # 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 # ...
Add licence header in fake camera test file.
Add licence header in fake camera test file.
Python
apache-2.0
angus-ai/angus-sdk-python
d1ea64d6645f60df38221cbd194c26dff9686dcd
scripts/utils.py
scripts/utils.py
import sys import hashlib def e(s): if type(s) == str: return str return s.encode('utf-8') def d(s): if type(s) == unicode: return s return unicode(s, 'utf-8') def mkid(s): return hashlib.sha1(e(s)).hexdigest()[:2*4] class Logger(object): def __init__(self): self._mod...
import sys import hashlib def e(s): if type(s) == str: return str return s.encode('utf-8') def d(s): if type(s) == unicode: return s return unicode(s, 'utf-8') def mkid(s): return hashlib.sha1(e(s)).hexdigest()[:2*4] class Logger(object): def __init__(self): self._mod...
Handle logging unicode messages in python2.
Handle logging unicode messages in python2. Former-commit-id: 257d94eb71d5597ff52a18ec1530d73496901ef4
Python
mit
guilherme-pg/citationhunt,eggpi/citationhunt,guilherme-pg/citationhunt,eggpi/citationhunt,eggpi/citationhunt,guilherme-pg/citationhunt,guilherme-pg/citationhunt,eggpi/citationhunt
a74e91613be376d6d71fb90c15cab689af661e37
money_conversion/money.py
money_conversion/money.py
from currency_rates import rates class Money(object): def __init__(self, amount, currency): self.amount = amount self.currency = currency.upper() def __repr__(self): return "%.2f %s" % (self.amount, self.currency) def to_currency(self, new_currency): new_currency = new_c...
from currency_rates import rates class Money(object): def __init__(self, amount, currency): self.amount = amount self.currency = currency.upper() def __repr__(self): return "%.2f %s" % (self.amount, self.currency) def __getattr__(self, currency): def convert(): ...
Add __getattr__ method in order to be able to call non-defined methods
Add __getattr__ method in order to be able to call non-defined methods
Python
mit
mdsrosa/money-conversion-py
9a698d1428fbe0744c9dba3532b778569dbe1dd4
server.py
server.py
import socket import sys class SimpleServer(object): """Simple server using the socket library""" def __init__(self, blocking=False, connection_oriented=True): """ The constructor initializes socket specifying the blocking status and if it must be a connection oriented socket. ...
""" A Simple Server class that allows to configure a socket in a very simple way. It is for studying purposes only. """ import socket import sys __author__ = "Facundo Victor" __license__ = "MIT" __email__ = "facundovt@gmail.com" class SimpleServer(object): """Simple server using the socket library""" def ...
Add docstrings and author reference
Add docstrings and author reference
Python
mit
facundovictor/non-blocking-socket-samples
5f501af61b416dae0e46236a8e1f9684dcc66e21
python/decoder_test.py
python/decoder_test.py
import argparse import scanner import numpy as np import cv2 from decode import db @db.loader('frame') def load_frames(buf, metadata): return np.frombuffer(buf, dtype=np.uint8) \ .reshape((metadata.height,metadata.width,3)) def extract_frames(args): job = load_frames(args['dataset'], 'edr') v...
import argparse import scanner import numpy as np import cv2 from decode import db @db.loader('frame') def load_frames(buf, metadata): return np.frombuffer(buf, dtype=np.uint8) \ .reshape((metadata.height,metadata.width,3)) def extract_frames(args): job = load_frames(args['dataset'], 'edr') v...
Write out concatenated frame on decode test failure
Write out concatenated frame on decode test failure
Python
apache-2.0
scanner-research/scanner,scanner-research/scanner,scanner-research/scanner,scanner-research/scanner
e2cba02550dfbe8628daf024a2a35c0dffb234e9
python/cli/request.py
python/cli/request.py
import requests import os aport = os.environ.get('MYAPORT') if aport is None: aport = "80" aport = "23456" url1 = 'http://localhost:' + aport + '/' url2 = 'http://localhost:' + aport + '/action/improvesimulateinvest' url3 = 'http://localhost:' + aport + '/action/autosimulateinvest' url4 = 'http://localhost:' + a...
import requests import os aport = os.environ.get('MYAPORT') if aport is None: aport = "80" aport = "23456" ahost = os.environ.get('MYAHOST') if ahost is None: ahost = "localhost" url1 = 'http://' + ahost + ':' + aport + '/' #headers = {'Content-type': 'application/json', 'Accept': 'text/plain'} #hea...
Handle different environments, for automation (I4).
Handle different environments, for automation (I4).
Python
agpl-3.0
rroart/aether,rroart/aether,rroart/aether,rroart/aether,rroart/aether
0adadcb3f04e2ecb98b5ca5de1afba2ba7208d23
spacy/tests/parser/test_beam_parse.py
spacy/tests/parser/test_beam_parse.py
import spacy import pytest @pytest.mark.models def test_beam_parse(): nlp = spacy.load('en_core_web_sm') doc = nlp(u'Australia is a country', disable=['ner']) ents = nlp.entity(doc, beam_width=2) print(ents)
# coding: utf8 from __future__ import unicode_literals import pytest @pytest.mark.models('en') def test_beam_parse(EN): doc = EN(u'Australia is a country', disable=['ner']) ents = EN.entity(doc, beam_width=2) print(ents)
Fix beam parse model test
Fix beam parse model test
Python
mit
aikramer2/spaCy,spacy-io/spaCy,recognai/spaCy,recognai/spaCy,explosion/spaCy,recognai/spaCy,explosion/spaCy,spacy-io/spaCy,recognai/spaCy,explosion/spaCy,spacy-io/spaCy,spacy-io/spaCy,aikramer2/spaCy,explosion/spaCy,spacy-io/spaCy,aikramer2/spaCy,spacy-io/spaCy,honnibal/spaCy,explosion/spaCy,honnibal/spaCy,aikramer2/sp...
1f2deb95ba543bf05dd78f1df2e9ee6d17a2c4c3
buffer/tests/test_profiles_manager.py
buffer/tests/test_profiles_manager.py
import json from nose.tools import eq_, raises from mock import MagicMock, patch from buffer.managers.profiles import Profiles from buffer.models.profile import PATHS mocked_response = { 'name': 'me', 'service': 'twiter', 'id': 1 } def test_profiles_manager_all_method(): ''' Test basic profiles retrievi...
import json from nose.tools import eq_, raises from mock import MagicMock, patch from buffer.managers.profiles import Profiles from buffer.models.profile import Profile, PATHS mocked_response = { 'name': 'me', 'service': 'twiter', 'id': 1 } def test_profiles_manager_all_method(): ''' Test basic profiles...
Test profiles manager filterting method
Test profiles manager filterting method
Python
mit
vtemian/buffpy,bufferapp/buffer-python
8d3931fd5effabf9c5d56cb03ae15630ae984963
postalcodes_mexico/cli.py
postalcodes_mexico/cli.py
# -*- coding: utf-8 -*- """Console script for postalcodes_mexico.""" import sys import click @click.command() def main(args=None): """Console script for postalcodes_mexico.""" click.echo("Replace this message by putting your code into " "postalcodes_mexico.cli.main") click.echo("See click ...
# -*- coding: utf-8 -*- """Console script for postalcodes_mexico.""" import sys import click from postalcodes_mexico import postalcodes_mexico @click.command() @click.argument('postalcode', type=str) def main(postalcode): """Console script for postalcodes_mexico.""" places = postalcodes_mexico.places(postal...
Create simple CLI for the `places` function
Create simple CLI for the `places` function
Python
mit
FlowFX/postalcodes_mexico
006b645315190eb532ede9c36c77a7fbc4c27237
quotations/apps/api/v1.py
quotations/apps/api/v1.py
from tastypie.authorization import DjangoAuthorization from tastypie import fields from tastypie.resources import ModelResource, ALL_WITH_RELATIONS from quotations.apps.quotations import models as quotations_models from quotations.libs.auth import MethodAuthentication from quotations.libs.serializers import Serializer ...
from tastypie.authorization import DjangoAuthorization from tastypie import fields from tastypie.resources import ModelResource, ALL_WITH_RELATIONS from quotations.apps.quotations import models as quotations_models from quotations.libs.auth import MethodAuthentication from quotations.libs.serializers import Serializer ...
Allow retrieval of a random quote
Allow retrieval of a random quote
Python
mit
jessamynsmith/socialjusticebingo,jessamynsmith/underquoted,jessamynsmith/socialjusticebingo,jessamynsmith/underquoted,jessamynsmith/underquoted,jessamynsmith/socialjusticebingo,jessamynsmith/underquoted
8be6b576007f89fad50ea1dfacad46614c0a97c5
apps/domain/src/main/core/exceptions.py
apps/domain/src/main/core/exceptions.py
"""Specific PyGrid exceptions.""" class PyGridError(Exception): def __init__(self, message): super().__init__(message) class AuthorizationError(PyGridError): def __init__(self, message=""): if not message: message = "User is not authorized for this operation!" super().__i...
"""Specific PyGrid exceptions.""" class PyGridError(Exception): def __init__(self, message): super().__init__(message) class AuthorizationError(PyGridError): def __init__(self, message=""): if not message: message = "User is not authorized for this operation!" super().__i...
ADD new exception -> EnvironmentNotFound!
ADD new exception -> EnvironmentNotFound!
Python
apache-2.0
OpenMined/PySyft,OpenMined/PySyft,OpenMined/PySyft,OpenMined/PySyft
e0b82cf9ed24870cb313328e5539acc5fe7f6508
stock_awesome/levels/chock_a_block.py
stock_awesome/levels/chock_a_block.py
import time from stock_awesome.obj import market def main(): """ Algorithm: Wait for an ask, then send a fill or kill for the quantity of the ask at the ask price. """ m = market.StockAPI('WEB29978261', 'NOWUEX', 'BBCM') #collection of orders placed orders = {} filled = 0 upper...
import time from stock_awesome.obj import market def main(): """ Algorithm: Wait for an ask, then send a fill or kill for the quantity of the ask at the ask price. """ m = market.StockAPI('RAJ40214463', 'SSMCEX', 'IPSO') #collection of orders placed orders = {} filled = 0 upper...
Add some (inefective) score maximizing attempts
Add some (inefective) score maximizing attempts
Python
mit
ForeverWintr/stock_awesome
89193a6571dd74501533160b409cad8835c51625
gcframe/tests/urls.py
gcframe/tests/urls.py
# -*- coding: utf-8 -*- """ Simple urls for use in testing the gcframe app. """ from __future__ import unicode_literals # The defaults module is deprecated in Django 1.5, but necessary to # support Django 1.3. drop ``.defaults`` when dropping 1.3 support. from django.conf.urls.defaults import patterns, url from .vi...
# -*- coding: utf-8 -*- """ Simple urls for use in testing the gcframe app. """ from __future__ import unicode_literals try: from django.conf.urls import patterns, url except ImportError: # Django 1.3 from django.conf.urls.defaults import patterns, url from .views import normal, framed, exempt urlpattern...
Handle a Django deprecation properly.
Handle a Django deprecation properly. Should have done this in commit cb4eae7b7.
Python
bsd-3-clause
benspaulding/django-gcframe
6bfb23294c2cc445479f4c8098b8e62647cf01bd
test/test_notification_integration.py
test/test_notification_integration.py
import os import select import groundstation.fs_watcher as fs_watcher from groundstation.peer_socket import PeerSocket from integration_fixture import StationIntegrationFixture, \ TestListener, \ TestClient class StationFSWatcherIntegration(StationInteg...
import os import select import groundstation.fs_watcher as fs_watcher from groundstation.peer_socket import PeerSocket from groundstation.utils import path2id from integration_fixture import StationIntegrationFixture, \ TestListener, \ TestClient class...
Validate that we can translate a NEWOBJECT into a FETCHOBJECT
Validate that we can translate a NEWOBJECT into a FETCHOBJECT
Python
mit
richo/groundstation,richo/groundstation,richo/groundstation,richo/groundstation,richo/groundstation
6fe5a416ed229e7ec8efab9d6b3dac43f16515b6
corehq/apps/domain/__init__.py
corehq/apps/domain/__init__.py
from corehq.preindex import ExtraPreindexPlugin from django.conf import settings ExtraPreindexPlugin.register('domain', __file__, ( settings.NEW_USERS_GROUPS_DB, settings.NEW_FIXTURES_DB, 'meta'))
from corehq.preindex import ExtraPreindexPlugin from django.conf import settings ExtraPreindexPlugin.register('domain', __file__, ( settings.NEW_DOMAINS_DB, settings.NEW_USERS_GROUPS_DB, settings.NEW_FIXTURES_DB, 'meta', ))
Add the new domains db
Add the new domains db
Python
bsd-3-clause
dimagi/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq
e12432b0c97d1ddebf16df821fe6c77bb8b6a66b
wagtail/wagtailsites/wagtail_hooks.py
wagtail/wagtailsites/wagtail_hooks.py
from django.conf.urls import include, url from django.core import urlresolvers from django.utils.translation import ugettext_lazy as _ from wagtail.wagtailcore import hooks from wagtail.wagtailadmin.menu import MenuItem from wagtail.wagtailsites import urls def register_admin_urls(): return [ url(r'^sit...
from django.conf.urls import include, url from django.core import urlresolvers from django.utils.translation import ugettext_lazy as _ from wagtail.wagtailcore import hooks from wagtail.wagtailadmin.menu import MenuItem from wagtail.wagtailsites import urls @hooks.register('register_admin_urls') def register_admin_...
Move Sites to the settings menu (and use decorator syntax for hooks)
Move Sites to the settings menu (and use decorator syntax for hooks)
Python
bsd-3-clause
mixxorz/wagtail,wagtail/wagtail,KimGlazebrook/wagtail-experiment,gasman/wagtail,mayapurmedia/wagtail,kaedroho/wagtail,jnns/wagtail,serzans/wagtail,hanpama/wagtail,iho/wagtail,marctc/wagtail,kurtw/wagtail,nilnvoid/wagtail,nrsimha/wagtail,gasman/wagtail,jorge-marques/wagtail,Toshakins/wagtail,rsalmaso/wagtail,takeflight/...
6689858b2364a668b362a5f00d4c86e57141dc37
numba/cuda/models.py
numba/cuda/models.py
from llvmlite import ir from numba.core.datamodel.registry import register_default from numba.core.extending import register_model, models from numba.core import types from numba.cuda.types import Dim3, GridGroup, CUDADispatcher @register_model(Dim3) class Dim3Model(models.StructModel): def __init__(self, dmm, f...
from llvmlite import ir from numba.core.datamodel.registry import register_default from numba.core.extending import register_model, models from numba.core import types from numba.cuda.types import Dim3, GridGroup, CUDADispatcher @register_model(Dim3) class Dim3Model(models.StructModel): def __init__(self, dmm, f...
Reorder FloatModel checks in ascending order
CUDA: Reorder FloatModel checks in ascending order
Python
bsd-2-clause
cpcloud/numba,numba/numba,numba/numba,seibert/numba,cpcloud/numba,cpcloud/numba,seibert/numba,seibert/numba,cpcloud/numba,numba/numba,IntelLabs/numba,numba/numba,IntelLabs/numba,cpcloud/numba,seibert/numba,IntelLabs/numba,IntelLabs/numba,seibert/numba,IntelLabs/numba,numba/numba
4a650922ee97b9cb54b203cab9709d511487d9ff
silver/tests/factories.py
silver/tests/factories.py
"""Factories for the silver app.""" # import factory # from .. import models
import factory from silver.models import Provider class ProviderFactory(factory.django.DjangoModelFactory): class Meta: model = Provider
Add factory for the Provider model
Add factory for the Provider model
Python
apache-2.0
PressLabs/silver,PressLabs/silver,PressLabs/silver
9a51358871f04e2a5552621b6ac2c9dbe1ee8345
main.py
main.py
#!/usr/bin/env python from pysnap import Snapchat import secrets s = Snapchat() s.login(secrets.USERNAME, secrets.PASSWORD) friends_to_add = [friend['name'] for friend in s.get_updates()['added_friends'] if friend['type'] == 1] for friend in friends_to_add: s.add_friend(friend) snaps = [snap['id'] for snap in s...
!/usr/bin/env python from pysnap import Snapchat import secrets s = Snapchat() s.login(secrets.USERNAME, secrets.PASSWORD) friends_to_add = [friend['name'] for friend in s.get_updates()['added_friends'] if friend['type'] == 1] for friend in friends_to_add: s.add_friend(friend) snaps = [snap['id'] for snap in s....
Save temporary pictures to local directory
Save temporary pictures to local directory
Python
mit
jollex/SnapchatBot
d0a907872749f1bb54d6e8e160ea170059289623
source/custom/combo.py
source/custom/combo.py
# -*- coding: utf-8 -*- ## \package custom.combo # MIT licensing # See: LICENSE.txt import wx from wx.combo import OwnerDrawnComboBox class ComboBox(OwnerDrawnComboBox): def __init__(self, parent, win_id, value=wx.EmptyString, pos=wx.DefaultPosition, size=wx.DefaultSize, choices=[], style=0, valid...
# -*- coding: utf-8 -*- ## \package custom.combo # MIT licensing # See: LICENSE.txt import wx from wx.combo import OwnerDrawnComboBox class ComboBox(OwnerDrawnComboBox): def __init__(self, parent, win_id=wx.ID_ANY, value=wx.EmptyString, pos=wx.DefaultPosition, size=wx.DefaultSize, choices=[], styl...
Set ComboBox class default ID to wx.ID_ANY
Set ComboBox class default ID to wx.ID_ANY
Python
mit
AntumDeluge/desktop_recorder,AntumDeluge/desktop_recorder
2560ca287e81cbefb6037e5688bfa4ef74d85149
clock.py
clock.py
from __future__ import print_function from apscheduler.schedulers.blocking import BlockingScheduler import logging import subprocess logging.basicConfig() scheduler = BlockingScheduler() @scheduler.scheduled_job('interval', minutes=1) def timed_job_min1(): print("Run notifier") subprocess.run( "notif...
from __future__ import print_function from apscheduler.schedulers.blocking import BlockingScheduler import logging import subprocess logging.basicConfig() scheduler = BlockingScheduler() @scheduler.scheduled_job('interval', minutes=1) def timed_job_min1(): print("Run notifier") subprocess.check_call( ...
Change call method for Python2.7
Change call method for Python2.7
Python
mit
oinume/lekcije,oinume/dmm-eikaiwa-fft,oinume/lekcije,oinume/dmm-eikaiwa-fft,oinume/lekcije,oinume/dmm-eikaiwa-fft,oinume/lekcije,oinume/lekcije,oinume/lekcije,oinume/dmm-eikaiwa-fft
6bb9a4ed50ad879c56cdeae0dedb49bba6780780
matchers/volunteer.py
matchers/volunteer.py
import random from base import BaseMatcher class VolunteerMatcher(BaseMatcher): dev_text = "volunteer someone" all_text = "volunteer a dev" dev_candidates = ['Steve', 'Arthur', 'Honza', 'Fernando', 'Nick'] all_candidates = dev_candidates + ['Craig', 'Evan'] def respond(self, message, user=None): ...
import random from base import BaseMatcher class VolunteerMatcher(BaseMatcher): dev_text = "volunteer someone" all_text = "volunteer a dev" dev_candidates = ['sjl', 'arthurdebert', 'honza', 'fernandotakai', 'nicksergeant'] all_candidates = dev_candidates + ['cz', 'ehazlett'] def respond(self, mes...
Use IRC Nicks instead of real names.
Use IRC Nicks instead of real names.
Python
bsd-2-clause
honza/nigel
b24083b0991157a1e0d8a533fc1cac3aa2e4523c
similarities/utils.py
similarities/utils.py
import echonest from artists.models import Artist from echonest.models import SimilarResponse from users.models import User from .models import (GeneralArtist, UserSimilarity, Similarity, update_similarities) def add_new_similarities(artist, force_update=False): similarities = [] response...
from django.db.models import Q import echonest from artists.models import Artist from echonest.models import SimilarResponse from users.models import User from .models import (GeneralArtist, UserSimilarity, Similarity, update_similarities) def add_new_similarities(artist, force_update=False): ...
Order similar artist results properly
Order similar artist results properly
Python
bsd-3-clause
FreeMusicNinja/api.freemusic.ninja
7016b7bb026e0fe557ca06efa81dace9999e526d
hubbot/Modules/Healthcheck.py
hubbot/Modules/Healthcheck.py
from twisted.internet import reactor, protocol from hubbot.moduleinterface import ModuleInterface class Echo(protocol.Protocol): """This is just about the simplest possible protocol""" def dataReceived(self, data): """As soon as any data is received, write it back.""" self.transport.write(da...
from twisted.protocols import basic from twisted.internet import protocol, reactor from hubbot.moduleinterface import ModuleInterface class HealthcheckProtocol(basic.LineReceiver): def lineReceived(self, line): response_body = "All is well. Ish." self.sendLine("HTTP/1.0 200 OK".encode("UTF-8")) ...
Write a slightly less dumb protocol?
Write a slightly less dumb protocol?
Python
mit
HubbeKing/Hubbot_Twisted
1704e66caa06524d9b595c312d3a5f5d93683261
app/models/cnes_bed.py
app/models/cnes_bed.py
from sqlalchemy import Column, Integer, String, func from app import db class CnesBed(db.Model): __tablename__ = 'cnes_bed' year = Column(Integer, primary_key=True) region = Column(String(1), primary_key=True) mesoregion = Column(String(4), primary_key=True) microregion = Colum...
from sqlalchemy import Column, Integer, String, func from app import db class CnesBed(db.Model): __tablename__ = 'cnes_bed' year = Column(Integer, primary_key=True) region = Column(String(1), primary_key=True) mesoregion = Column(String(4), primary_key=True) microregion = Colum...
Add bed_type to cnes_establishment model
Add bed_type to cnes_establishment model
Python
mit
DataViva/dataviva-api,daniel1409/dataviva-api
0eaff91695eefcf289e31d8ca93d19ab5bbd392d
katana/expr.py
katana/expr.py
import re class Expr(object): def __init__(self, name, regex): self.name = name self.regex = regex def on_match(self, string): return [self.name, string] def callback(self, _, string): return self.on_match(string) class Scanner(object): def __init__(self, exprs): ...
import re class Expr(object): def __init__(self, name, regex): self.name = name self.regex = regex def __iter__(self): yield self.regex yield lambda _, token: self.on_match(token) def on_match(self, string): return [self.name, string] class Scanner(object): ...
Refactor Expr object to be more self contained
Refactor Expr object to be more self contained
Python
mit
eugene-eeo/katana
ce2e5b0dc3ddafe931a902cb7aa24c3adbc246b7
fireplace/cards/wog/neutral_legendary.py
fireplace/cards/wog/neutral_legendary.py
from ..utils import * ## # Minions
from ..utils import * ## # Minions class OG_122: "Mukla, Tyrant of the Vale" play = Give(CONTROLLER, "EX1_014t") * 2 class OG_318: "Hogger, Doom of Elwynn" events = SELF_DAMAGE.on(Summon(CONTROLLER, "OG_318t")) class OG_338: "Nat, the Darkfisher" events = BeginTurn(OPPONENT).on(COINFLIP & Draw(OPPONENT))
Implement corrupted Mukla, Hogger and Nat
Implement corrupted Mukla, Hogger and Nat
Python
agpl-3.0
beheh/fireplace,NightKev/fireplace,jleclanche/fireplace
5ed9e43ec451aca9bdca4391bd35934e5fe4aea3
huts/management/commands/dumphutsjson.py
huts/management/commands/dumphutsjson.py
from django.core.management.base import BaseCommand from huts.utils import export class Command(BaseCommand): args = '' help = 'Dumps the huts, agencies, and regions in the json api format.' def handle(self, *args, **options): print(export.db_as_json().encode('utf-8'))
from optparse import make_option from django.core.management.base import BaseCommand from huts.utils import export class Command(BaseCommand): option_list = BaseCommand.option_list + ( make_option( '--file', help='Write to file instead of stdout' ), ) help = 'Dumps...
Update command to take file argument
Update command to take file argument
Python
mit
dylanfprice/hutmap,dylanfprice/hutmap,dylanfprice/hutmap,muescha/hutmap,muescha/hutmap,dylanfprice/hutmap,muescha/hutmap,muescha/hutmap
4f9db35566332778853e993f7791116d66c49dd4
grako/rendering.py
grako/rendering.py
# -*- coding: utf-8 -*- from __future__ import print_function, division, absolute_import, unicode_literals import itertools from .util import trim def render(item, **fields): """ Render the given item """ if item is None: return '' elif isinstance(item, Renderer): return item.render(**f...
# -*- coding: utf-8 -*- from __future__ import print_function, division, absolute_import, unicode_literals import itertools from .util import trim def render(item, **fields): """ Render the given item """ if item is None: return '' elif isinstance(item, Renderer): return item.render(**f...
Allow render_fields to override the default template.
Allow render_fields to override the default template.
Python
bsd-2-clause
swayf/grako,swayf/grako
2d3e52567d7d361428ce93d02cc42ecaddacab6c
tests/test_commands.py
tests/test_commands.py
# -*- coding: utf-8 -*- from couchapp import commands from couchapp.errors import AppError from mock import Mock, patch from nose.tools import raises @patch('couchapp.commands.document') def test_init_dest(mock_doc): commands.init(None, None, '/tmp/mk') mock_doc.assert_called_once_with('/tmp/mk', create=Tru...
# -*- coding: utf-8 -*- from couchapp import commands from couchapp.errors import AppError from mock import Mock, patch from nose.tools import raises @patch('couchapp.commands.document') def test_init_dest(mock_doc): commands.init(None, None, '/tmp/mk') mock_doc.assert_called_once_with('/tmp/mk', create=Tru...
Test cases for push with export flag
Test cases for push with export flag
Python
apache-2.0
couchapp/couchapp,h4ki/couchapp,couchapp/couchapp,couchapp/couchapp,h4ki/couchapp,h4ki/couchapp,couchapp/couchapp,h4ki/couchapp
9dc253b79d885ca205b557f88fca6fa35bd8fe21
tests/test_selector.py
tests/test_selector.py
from contextlib import contextmanager from scell import Selector from pytest import raises, fixture def test_select(selector): res = list(selector.select()) assert res for event in res: assert event.ready def test_select_empty(): sel = Selector() assert list(sel.select()) == [] def tes...
from contextlib import contextmanager from scell import Selector from pytest import raises, fixture def test_select(selector): res = list(selector.select()) assert res for event in res: assert event.ready def test_select_empty(): sel = Selector() assert list(sel.select()) == [] def tes...
Make Selector.scope test more rigorous
Make Selector.scope test more rigorous
Python
mit
eugene-eeo/scell
7520e1285af36292def45f892808841e78cc4a2b
bloop/index.py
bloop/index.py
missing = object() class GlobalSecondaryIndex(object): def __init__(self, hash_key=None, range_key=None, write_units=1, read_units=1, name=missing): self._model_name = None self._backing_name = name self.write_units = write_units self.read_units = read_units ...
class Index(object): def __init__(self, write_units=1, read_units=1, name=None, range_key=None): self._model_name = None self._dynamo_name = name self.write_units = write_units self.read_units = read_units self.range_key = range_key @property def model_name(self): ...
Refactor GSI, LSI to use base Index class
Refactor GSI, LSI to use base Index class
Python
mit
numberoverzero/bloop,numberoverzero/bloop
db4ccce9e418a1227532bde8834ca682bc873609
system/t04_mirror/show.py
system/t04_mirror/show.py
from lib import BaseTest class ShowMirror1Test(BaseTest): """ show mirror: regular mirror """ fixtureCmds = ["aptly mirror create mirror1 http://mirror.yandex.ru/debian/ wheezy"] runCmd = "aptly mirror show mirror1" class ShowMirror2Test(BaseTest): """ show mirror: missing mirror """...
from lib import BaseTest import re class ShowMirror1Test(BaseTest): """ show mirror: regular mirror """ fixtureCmds = ["aptly mirror create mirror1 http://mirror.yandex.ru/debian/ wheezy"] runCmd = "aptly mirror show mirror1" class ShowMirror2Test(BaseTest): """ show mirror: missing mirr...
Remove updated at while comparing.
Remove updated at while comparing.
Python
mit
gearmover/aptly,bsundsrud/aptly,adfinis-forks/aptly,vincentbernat/aptly,gdbdzgd/aptly,ceocoder/aptly,adfinis-forks/aptly,seaninspace/aptly,neolynx/aptly,scalp42/aptly,gdbdzgd/aptly,sobczyk/aptly,neolynx/aptly,scalp42/aptly,aptly-dev/aptly,seaninspace/aptly,aptly-dev/aptly,bsundsrud/aptly,gdbdzgd/aptly,bankonme/aptly,ad...
1e8c094c0f806b624a41447446676c1f2ac3590d
tools/debug_adapter.py
tools/debug_adapter.py
#!/usr/bin/python import sys if 'darwin' in sys.platform: sys.path.append('/Applications/Xcode.app/Contents/SharedFrameworks/LLDB.framework/Resources/Python') sys.path.append('.') import adapter adapter.main.run_tcp_server()
#!/usr/bin/python import sys import subprocess import string out = subprocess.check_output(['lldb', '-P']) sys.path.append(string.strip(out)) sys.path.append('.') import adapter adapter.main.run_tcp_server()
Fix adapter debugging on Linux.
Fix adapter debugging on Linux.
Python
mit
vadimcn/vscode-lldb,vadimcn/vscode-lldb,vadimcn/vscode-lldb,vadimcn/vscode-lldb,vadimcn/vscode-lldb,vadimcn/vscode-lldb,vadimcn/vscode-lldb
b757a5e24fa8018647827b8194c985881df872d5
scipy/signal/setup.py
scipy/signal/setup.py
#!/usr/bin/env python def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration('signal', parent_package, top_path) config.add_data_dir('tests') config.add_extension('sigtools', sources=['sigtoolsmodule.c',...
#!/usr/bin/env python def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration('signal', parent_package, top_path) config.add_data_dir('tests') config.add_extension('sigtools', sources=['sigtoolsmodule.c',...
Add newsig.c as a dependency to sigtools module.
Add newsig.c as a dependency to sigtools module.
Python
bsd-3-clause
andyfaff/scipy,sauliusl/scipy,newemailjdm/scipy,jor-/scipy,mikebenfield/scipy,jsilter/scipy,mortada/scipy,josephcslater/scipy,jjhelmus/scipy,trankmichael/scipy,larsmans/scipy,jamestwebber/scipy,jonycgn/scipy,haudren/scipy,petebachant/scipy,endolith/scipy,vigna/scipy,e-q/scipy,raoulbq/scipy,aeklant/scipy,fredrikw/scipy,...
73e8864e745ca75c2ea327b53244c9f2f4183e1a
lambda_function.py
lambda_function.py
#!/usr/bin/env python2 from StringIO import StringIO import boto3 from dmr_marc_users_cs750 import ( get_users, get_groups, write_contacts_csv, write_contacts_xlsx ) def s3_contacts(contacts, bucket, key): s3 = boto3.client('s3') o = StringIO() if key.endswith('.csv'): t = 'tex...
#!/usr/bin/env python2 from StringIO import StringIO import boto3 from dmr_marc_users_cs750 import ( get_users, get_groups, write_contacts_csv, write_contacts_xlsx, ) from dmrx_most_heard_n0gsg import ( get_users as get_most_heard, write_n0gsg_csv, ) def s3_contacts(contacts, bucket, key...
Add N0GSG DMRX MostHeard to AWS Lambda function
Add N0GSG DMRX MostHeard to AWS Lambda function
Python
apache-2.0
ajorg/DMR_contacts
6dfb0c1ea4fb3d12d14a07d0e831eb32f3b2f340
yaml_argparse.py
yaml_argparse.py
import argparse import yaml def parse_arguments_based_on_yaml(yaml_file): with open(yaml_file) as f: yaml_data = yaml.load(f) # to start with, support only a single parameter key = list(yaml_data.keys())[0] value = yaml_data[key] parser = argparse.ArgumentParser() parser.add_argument...
import argparse import yaml def parse_arguments_based_on_yaml(yaml_file): with open(yaml_file) as f: yaml_data = yaml.load(f) parser = argparse.ArgumentParser() for key, value in yaml_data.items(): parser.add_argument("-{}".format(key), default=value) args = parser.parse_args() r...
Implement creating arguments for multiple strings
Implement creating arguments for multiple strings
Python
mit
krasch/yaml_argparse,krasch/quickargs
fbcdd58775be1b6a72e1d1415f62a7bfade3dbd1
pages/views.py
pages/views.py
from django.http import Http404 from django.shortcuts import get_object_or_404 from django.contrib.sites.models import SITE_CACHE from pages import settings from pages.models import Page, Content from pages.utils import auto_render, get_language_from_request def details(request, page_id=None, slug=None, temp...
from django.http import Http404 from django.shortcuts import get_object_or_404 from django.contrib.sites.models import SITE_CACHE from pages import settings from pages.models import Page, Content from pages.utils import auto_render, get_language_from_request def details(request, page_id=None, slug=None, temp...
Add documentation to the default view
Add documentation to the default view git-svn-id: 54fea250f97f2a4e12c6f7a610b8f07cb4c107b4@292 439a9e5f-3f3e-0410-bc46-71226ad0111b
Python
bsd-3-clause
remik/django-page-cms,akaihola/django-page-cms,oliciv/django-page-cms,akaihola/django-page-cms,akaihola/django-page-cms,remik/django-page-cms,oliciv/django-page-cms,batiste/django-page-cms,pombredanne/django-page-cms-1,pombredanne/django-page-cms-1,remik/django-page-cms,pombredanne/django-page-cms-1,batiste/django-page...
eae4b06bd798eab3a46bdd5b7452411bb7fb02e1
dashcam.py
dashcam.py
# dashcam.py # A Raspberry Pi powered, GPS enabled, 3D printed bicycle dashcam # By Matthew Timmons-Brown, The Raspberry Pi Guy import pygame import picamera import os os.putenv('SDL_VIDEODRIVER', 'fbcon') os.putenv('SDL_FBDEV' , '/dev/fb1') os.putenv('SDL_MOUSEDRV' , 'TSLIB') os.putenv('SDL_MOUSEDEV' , '/de...
# dashcam.py # A Raspberry Pi powered, GPS enabled, 3D printed bicycle dashcam # By Matthew Timmons-Brown, The Raspberry Pi Guy import pygame import picamera import os import sys import io os.putenv('SDL_VIDEODRIVER', 'fbcon') os.putenv('SDL_FBDEV' , '/dev/fb1') os.putenv('SDL_MOUSEDRV' , 'TSLIB') os.putenv('S...
Update dascham with pygame GO button load
Update dascham with pygame GO button load
Python
mit
the-raspberry-pi-guy/bike_dashcam,the-raspberry-pi-guy/bike_dashcam
b35d4292e50e8a8dc56635bddeac5a1fc42a5d19
tveebot_tracker/source.py
tveebot_tracker/source.py
from abc import ABC, abstractmethod class TVShowNotFound(Exception): """ Raised when a reference does not match any TV Show available """ class EpisodeSource(ABC): """ Abstract base class to define the interface for and episode source. An episode source is used by the tracker to obtain episode file...
from abc import ABC, abstractmethod class TVShowNotFound(Exception): """ Raised when a reference does not match any TV Show available """ class EpisodeSource(ABC): """ Abstract base class to define the interface for and episode source. An episode source is used by the tracker to obtain episode file...
Rename Source's get_episodes_for() method to fetch()
Rename Source's get_episodes_for() method to fetch()
Python
mit
tveebot/tracker
c7601ed4144b12717f536f2fc2fc0ddb5745ec27
opentaxii/auth/sqldb/models.py
opentaxii/auth/sqldb/models.py
import hmac import bcrypt from sqlalchemy.schema import Column from sqlalchemy.types import Integer, String from sqlalchemy.ext.declarative import declarative_base __all__ = ['Base', 'Account'] Base = declarative_base() MAX_STR_LEN = 256 class Account(Base): __tablename__ = 'accounts' id = Column(Integ...
import bcrypt from sqlalchemy.schema import Column from sqlalchemy.types import Integer, String from sqlalchemy.ext.declarative import declarative_base from werkzeug.security import safe_str_cmp __all__ = ['Base', 'Account'] Base = declarative_base() MAX_STR_LEN = 256 class Account(Base): __tablename__ = 'a...
Use Werkzeug's safe_str_cmp() instead of hmac.compare_digest()
Use Werkzeug's safe_str_cmp() instead of hmac.compare_digest() Werkzeug will use the latter on Python >2.7.7, and provides a fallback for older Python versions.
Python
bsd-3-clause
EclecticIQ/OpenTAXII,Intelworks/OpenTAXII,EclecticIQ/OpenTAXII,Intelworks/OpenTAXII