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
cd92e7186d8b0e1f8103b6f622c0622e7db88fb8
thecodingloverss.py
thecodingloverss.py
import feedparser, sys, urllib2 from bs4 import BeautifulSoup as BS from feedgen.feed import FeedGenerator from flask import Flask app = Flask(__name__) @app.route('/') def index(): d = feedparser.parse('http://thecodinglove.com/rss') fg = FeedGenerator() fg.title('The coding love with images.') fg...
import feedparser, sys, urllib2 from bs4 import BeautifulSoup as BS from feedgen.feed import FeedGenerator from flask import Flask app = Flask(__name__) @app.route('/') def index(): d = feedparser.parse('http://thecodinglove.com/rss') fg = FeedGenerator() fg.title('The coding love with images.') fg...
Set published date so the posts come in order.
Set published date so the posts come in order.
Python
mit
chrillux/thecodingloverss
f71a166598ab35bc15f298226bb510d43f78c810
bids/analysis/transformations/__init__.py
bids/analysis/transformations/__init__.py
from .compute import (sum, product, scale, orthogonalize, threshold, and_, or_, not_, demean, convolve_HRF) from .munge import (split, rename, assign, copy, factor, filter, select, remove, replace, to_dense) __all__ = [ 'and_', 'assign', 'convolve_HRF', 'copy',...
from .compute import (sum, product, scale, orthogonalize, threshold, and_, or_, not_, demean, convolve) from .munge import (split, rename, assign, copy, factor, filter, select, delete, replace, to_dense) __all__ = [ 'and_', 'assign', 'convolve', 'copy', 'de...
Fix imports for renamed transformations
Fix imports for renamed transformations
Python
mit
INCF/pybids
b5bef82ea6eb4269a164eda3ba95d7212f1c76d1
lib/cli/run_worker.py
lib/cli/run_worker.py
import sys from rq import Queue, Connection, Worker import cli import worker class RunWorkerCli(cli.BaseCli): ''' A wrapper for RQ workers. Wrapping RQ is the only way to generate notifications when a job fails. ''' def _get_args(self, arg_parser): ''' Customize arguments. ''' ...
import sys from redis import Redis from rq import Queue, Connection, Worker import cli import worker class RunWorkerCli(cli.BaseCli): ''' A wrapper for RQ workers. Wrapping RQ is the only way to generate notifications when a job fails. ''' def _get_args(self, arg_parser): ''' Customize ...
Use connection settings from conf file.
Use connection settings from conf file.
Python
apache-2.0
TeamHG-Memex/hgprofiler,TeamHG-Memex/hgprofiler,TeamHG-Memex/hgprofiler,TeamHG-Memex/hgprofiler
cb08d632fac453403bc8b91391b14669dbe932cc
circonus/__init__.py
circonus/__init__.py
from __future__ import absolute_import __title__ = "circonus" __version__ = "0.0.0" from logging import NullHandler import logging from circonus.client import CirconusClient logging.getLogger(__name__).addHandler(NullHandler())
__title__ = "circonus" __version__ = "0.0.0" from logging import NullHandler import logging from circonus.client import CirconusClient logging.getLogger(__name__).addHandler(NullHandler())
Remove unnecessary absolute import statement.
Remove unnecessary absolute import statement.
Python
mit
monetate/circonus,monetate/circonus
b5ee678115391885a00cfd1ee114c6b5b22f7a55
setup.py
setup.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from distutils.core import setup setup( name='facebook-python-sdk', version='0.2.0', description='This client library is designed to support the Facebook Graph API and the official Facebook JavaScript SDK, which is the canonical way to implement Facebook authe...
#!/usr/bin/env python from distutils.core import setup setup( name='facebook-sdk', version='0.2.0', description='This client library is designed to support the Facebook Graph API and the official Facebook JavaScript SDK, which is the canonical way to implement Facebook authentication.', author='Facebo...
Rename the package so we can push to PyPi
Rename the package so we can push to PyPi
Python
apache-2.0
Aloomaio/facebook-sdk,mobolic/facebook-sdk
6122a8488613bdd7d5aaf80e7238cd2d80687a91
stock.py
stock.py
class Stock: def __init__(self, symbol): self.symbol = symbol self.price = None def update(self, timestamp, price): if price < 0: raise ValueError("price should not be negative") self.price = price
class Stock: def __init__(self, symbol): self.symbol = symbol self.price_history = [] @property def price(self): if self.price_history: return self.price_history[-1] else: return None def update(self, timestamp, price): if price < 0: ...
Update price attribute to price_history list as well as update function accordingly.
Update price attribute to price_history list as well as update function accordingly.
Python
mit
bsmukasa/stock_alerter
1583aaf429e252f32439759e1363f3908efa0b03
tasks.py
tasks.py
from celery import Celery from allsky import single_image_raspistill celery = Celery('tasks', broker='redis://localhost:6379/0', backend='redis://localhost:6379/0') @celery.task def background_task(): # some long running task here (this simple example has no output) pid = single_image_raspistill(filename='st...
from celery import Celery from allsky import single_image_raspistill celery = Celery('tasks', broker='redis://localhost:6379/0', backend='redis://localhost:6379/0') @celery.task def background_task(): # some long running task here (this simple example has no output) pid = single_image_raspistill(filename='st...
Set a higher default for darks
Set a higher default for darks
Python
mit
zemogle/raspberrysky
43c1f230382a3b7ad7776d28840c5305bb919ab9
jujugui/__init__.py
jujugui/__init__.py
# Copyright 2015 Canonical Ltd. This software is licensed under the # GNU Affero General Public License version 3 (see the file LICENSE). from pyramid.config import Configurator def main(global_config, **settings): """Return a Pyramid WSGI application.""" config = Configurator(settings=settings) return ...
# Copyright 2015 Canonical Ltd. This software is licensed under the # GNU Affero General Public License version 3 (see the file LICENSE). from pyramid.config import Configurator def main(global_config, **settings): """Return a Pyramid WSGI application.""" config = Configurator(settings=settings) return ...
Fix load order to fix routes.
Fix load order to fix routes.
Python
agpl-3.0
bac/juju-gui,bac/juju-gui,mitechie/juju-gui,mitechie/juju-gui,mitechie/juju-gui,mitechie/juju-gui,bac/juju-gui,bac/juju-gui
75a4733d059f6aad758f93a9c6e4878093afd184
test-messages.py
test-messages.py
#!/usr/bin/python2 # # test-messages.py - This script publish a random MQTT messages every 2 s. # # Copyright (c) 2013-2015, Fabian Affolter <fabian@affolter-engineering.ch> # Released under the MIT license. See LICENSE file for details. # import random import time import mosquitto timestamp = int(time.time()) broke...
#!/usr/bin/python3 # # test-messages.py - This script publish a random MQTT messages every 2 s. # # Copyright (c) 2013-2016, Fabian Affolter <fabian@affolter-engineering.ch> # Released under the MIT license. See LICENSE file for details. # import random import time import paho.mqtt.client as mqtt timestamp = int(time...
Switch to paho-mqtt and make ready for py3
Switch to paho-mqtt and make ready for py3
Python
mit
fabaff/mqtt-panel,fabaff/mqtt-panel,fabaff/mqtt-panel
de1afc2feb1e7572ee7a59909247a2cde67492c9
tests/sample3.py
tests/sample3.py
class Bad(Exception): def __repr__(self): raise RuntimeError("I'm a bad class!") def a(): x = Bad() return x def b(): x = Bad() raise x a() try: b() except Exception as exc: print(exc)
class Bad(Exception): __slots__ = [] def __repr__(self): raise RuntimeError("I'm a bad class!") def a(): x = Bad() return x def b(): x = Bad() raise x a() try: b() except Exception as exc: print(exc)
Add __slots__ to satisfy tests (rudimentary_repr is still ordinary __repr__ if __slots__ are there).
Add __slots__ to satisfy tests (rudimentary_repr is still ordinary __repr__ if __slots__ are there).
Python
bsd-2-clause
ionelmc/python-hunter
9274cd94442b2507b2d83e2a3e305a0a3b5dc802
zhihudaily/utils.py
zhihudaily/utils.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals import re import requests from zhihudaily.cache import cache @cache.memoize(timeout=1200) def make_request(url): session = requests.Session() session.headers.update({'User-Agent': 'Mozilla/5.0 (X11; Ubun...
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals import re import requests from zhihudaily.cache import cache @cache.memoize(timeout=1200) def make_request(url): session = requests.Session() session.headers.update({'User-Agent': 'Mozilla/5.0 (X11; Ubun...
Fix the unnecessary list comprehension
Fix the unnecessary list comprehension
Python
mit
lord63/zhihudaily,lord63/zhihudaily,lord63/zhihudaily
9aa673593baa67d6e7fc861015041cfb6b69c6c3
bin/list_winconf.py
bin/list_winconf.py
#!/usr/bin/env python def main(): import argparse from ranwinconf.common import generate_host_config parser = argparse.ArgumentParser() parser.add_argument('host', type=str, help="Name or IP of the host to get configuration from") parser.add_argument('--output', type=str, nargs='?', default='<stdo...
#!/usr/bin/env python def main(): import argparse from ranwinconf.common import generate_host_config parser = argparse.ArgumentParser() parser.add_argument('host', type=str, help="Name or IP of the host to get configuration from") parser.add_argument('--output', type=str, nargs='?', default='<stdo...
Fix import of common module
Fix import of common module
Python
mit
sebbrochet/ranwinconf
c5127ec22cc5328baf829159a21c7bdf78044f55
webapp.py
webapp.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import print_function import json import traceback from bottle import route, run, get, request, response, abort from db import search, info @route('/v1/pois.json') def pois_v1(): global _db filter = request.query.get('filter', None) if filter i...
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import print_function import json import re import traceback from bottle import route, run, get, request, response, abort from db import search, info @route('/v1/pois.json') def pois_v1(): global _db filter = request.query.get('filter', None) i...
Replace all extra characters with commas in queries; improves matching
Replace all extra characters with commas in queries; improves matching
Python
mit
guaq/paikkis
0004bde0d40dfea167d76a83c20acfffc0abfa28
poyo/__init__.py
poyo/__init__.py
# -*- coding: utf-8 -*- from .exceptions import PoyoException from .parser import parse_string __author__ = 'Raphael Pierzina' __email__ = 'raphael@hackebrot.de' __version__ = '0.3.0' __all__ = ['parse_string', 'PoyoException']
# -*- coding: utf-8 -*- import logging from .exceptions import PoyoException from .parser import parse_string __author__ = 'Raphael Pierzina' __email__ = 'raphael@hackebrot.de' __version__ = '0.3.0' logging.getLogger(__name__).addHandler(logging.NullHandler()) __all__ = ['parse_string', 'PoyoException']
Add NullHandler to poyo root logger
Add NullHandler to poyo root logger
Python
mit
hackebrot/poyo
9ef86f0b5ff1b4e1521a3dc075ff16bc6aef2d0c
museum_site/scroll.py
museum_site/scroll.py
from django.db import models class Scroll(models.Model): # Constants SCROLL_TOP = """``` β•žβ•€β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•€β•‘ β”‚ Scroll ### β”‚ β•žβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•‘ β”‚ β€’ β€’ β€’ β€’ β€’ β€’ β€’ β€’ β€’β”‚""" SCROLL_BOTTOM = ...
from django.db import models class Scroll(models.Model): # Constants SCROLL_TOP = """``` β•žβ•€β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•€β•‘ β”‚ Scroll ### β”‚ β•žβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•‘ β”‚ β€’ β€’ β€’ β€’ β€’ β€’ β€’ β€’ β€’β”‚""" SCROLL_BOTTOM = ...
Fix for truncated whitespace on DB level
Fix for truncated whitespace on DB level
Python
mit
DrDos0016/z2,DrDos0016/z2,DrDos0016/z2
530f540b11959956c0cd08b95b2c7c373d829c8e
python/sherlock-and-valid-string.py
python/sherlock-and-valid-string.py
#!/bin/python3 import math import os import random import re import sys from collections import Counter def isValid(s): return "YES" if containsOnlyOneDifferentCharacterCount(s) else "NO" def containsOnlyOneDifferentCharacterCount(string): characterCounts = Counter(string) if allOccurencesAreEqual(char...
#!/bin/python3 import math import os import random import re import sys from collections import Counter import copy def isValid(s): return "YES" if containsOnlyOneDifferentCharacterCount(s) else "NO" def containsOnlyOneDifferentCharacterCount(string): characterCounts = Counter(string) if allOccurencesA...
Handle edge case with zero count
Handle edge case with zero count
Python
mit
rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank
a67b71ebadbffa864f60869878198ce4e2eb3fa3
class4/exercise7.py
class4/exercise7.py
from getpass import getpass from netmiko import ConnectHandler def main(): password = getpass() pynet_rtr2 = {'device_type': 'cisco_ios', 'ip': '50.76.53.27', 'username': 'pyclass', 'password': password, 'port': 8022} ssh_connection = ConnectHandler(**pynet_rtr2) ssh_connection.config_mode() lo...
# Use Netmiko to change the logging buffer size (logging buffered <size>) on pynet-rtr2. from getpass import getpass from netmiko import ConnectHandler def main(): password = getpass() pynet_rtr2 = {'device_type': 'cisco_ios', 'ip': '50.76.53.27', 'username': 'pyclass', 'password': password, 'port': 8022} ...
Use Netmiko to change the logging buffer size (logging buffered <size>) on pynet-rtr2.
Use Netmiko to change the logging buffer size (logging buffered <size>) on pynet-rtr2.
Python
apache-2.0
linkdebian/pynet_course
6e67e2882c71e291dc1f161ffc7638f42c86ddbc
dmdlib/randpatterns/ephys_comms.py
dmdlib/randpatterns/ephys_comms.py
import zmq def send_message(msg, hostname='localhost', port=5556): """ sends a message to openephys ZMQ socket. :param msg: string :param hostname: ip address to send to :param port: zmq port number :return: none """ with zmq.Context() as ctx: with ctx.socket(zmq.REQ) as sock: ...
""" Module handling the communication with OpenEphys. """ import zmq TIMEOUT_MS = 250 # time to wait for ZMQ socket to respond before error. HOSTNAME = 'localhost' PORT = 5556 _ctx = zmq.Context() # should be only one made per process. def send_message(msg, hostname=HOSTNAME, port=PORT): """ sends a messa...
Fix zmq communications module Does not hang when connection is unavailable
Fix zmq communications module Does not hang when connection is unavailable
Python
mit
olfa-lab/DmdLib
3d3d6ef8393339f7246e6c6a9693d883ca3246f2
marconi/__init__.py
marconi/__init__.py
# Copyright (c) 2013 Rackspace Hosting, 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 ...
# Copyright (c) 2013 Rackspace Hosting, 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 ...
Remove the __MARCONI_SETUP_ global from init
Remove the __MARCONI_SETUP_ global from init This was used to know when Marconi was being loaded and avoid registering configuration options and doing other things. This is not necessary anymore. Change-Id: Icf43302581eefb563b10ddec5831eeec0d068872 Partially-Implements: py3k-support
Python
apache-2.0
openstack/zaqar,openstack/zaqar,rackerlabs/marconi,openstack/zaqar,openstack/zaqar
7a571230e9678f30e6178da01769424213471355
libapol/__init__.py
libapol/__init__.py
"""The SETools SELinux policy analysis library.""" # Copyright 2014, Tresys Technology, LLC # # This file is part of SETools. # # SETools is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as # published by the Free Software Foundation, either version 2...
"""The SETools SELinux policy analysis library.""" # Copyright 2014, Tresys Technology, LLC # # This file is part of SETools. # # SETools is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as # published by the Free Software Foundation, either version 2...
Add missing libapol rolequery import.
Add missing libapol rolequery import.
Python
lgpl-2.1
TresysTechnology/setools,TresysTechnology/setools,TresysTechnology/setools,TresysTechnology/setools
e6c41d8bd83b6710114a9d37915a0b3bbeb78d2a
sms_sponsorship/tests/load_tests.py
sms_sponsorship/tests/load_tests.py
# coding: utf-8 # pylint: disable=W7936 from locust import HttpLocust, TaskSet, task from random import randint class SmsSponsorWorkflow(TaskSet): @task(1) def send_sms(self): url = "/sms/mnc?sender=%2B41789364{}&service=compassion".format( randint(100, 999)) self.client.get(url) ...
# coding: utf-8 # pylint: disable=W7936 from locust import HttpLocust, TaskSet, task from random import randint class SmsSponsorWorkflow(TaskSet): @task(1) def send_sms(self): url = "/sms/mnc?sender=%2B4199{}&service=compassion&text=test".format( randint(1000000, 9999999)) self.cl...
Replace phone number and avoid sending SMS for load testing
Replace phone number and avoid sending SMS for load testing
Python
agpl-3.0
eicher31/compassion-modules,eicher31/compassion-modules,ecino/compassion-modules,ecino/compassion-modules,CompassionCH/compassion-modules,ecino/compassion-modules,CompassionCH/compassion-modules,CompassionCH/compassion-modules,eicher31/compassion-modules,eicher31/compassion-modules,ecino/compassion-modules,ecino/compas...
fdd57913aa11c29ecf160f32a9091e59de598899
plugins/YTranslate.py
plugins/YTranslate.py
""" Yandex Translation API """ import logging from urllib.parse import quote from telegram import Bot, Update from telegram.ext import Updater from requests import post import constants # pylint: disable=E0401 import settings LOGGER = logging.getLogger("YTranslate") YAURL = "https://translate.yandex.net/api/v1.5/tr....
""" Yandex Translation API """ import logging from urllib.parse import quote from telegram import Bot, Update from telegram.ext import Updater from requests import post import constants # pylint: disable=E0401 import settings import octeon LOGGER = logging.getLogger("YTranslate") YAURL = "https://translate.yandex.ne...
Update translate plugin to new message format
Update translate plugin to new message format
Python
mit
ProtoxiDe22/Octeon
7c08497e3e3e08f3ebf82eb594c25c1ab65b4d9d
SocialNPHS/language/tweet.py
SocialNPHS/language/tweet.py
""" Given a tweet, tokenize it and shit. """ import nltk from nltk.tokenize import TweetTokenizer from SocialNPHS.sources.twitter.auth import api from SocialNPHS.sources.twitter import user def get_tweet_tags(tweet): """ Break up a tweet into individual word parts """ tknzr = TweetTokenizer() tokens = t...
""" Given a tweet, tokenize it and shit. """ import nltk from nltk.tokenize import TweetTokenizer from SocialNPHS.sources.twitter.auth import api from SocialNPHS.sources.twitter import user def get_tweet_tags(tweet): """ Break up a tweet into individual word parts """ tknzr = TweetTokenizer() tokens = t...
Implement fallback for tokenizing non-nphs tagged users
Implement fallback for tokenizing non-nphs tagged users
Python
mit
SocialNPHS/SocialNPHS
68680b8b116e10ae4e35c39b8a62c0307ee65fe4
node/deduplicate.py
node/deduplicate.py
#!/usr/bin/env python from nodes import Node class Deduplicate(Node): char = "}" args = 1 results = 2 @Node.test_func([2], [4]) @Node.test_func([1.5], [3]) def double(self, inp: Node.number): """inp*2""" self.results = 1 return inp*2 def func(self, seq...
#!/usr/bin/env python from nodes import Node class Deduplicate(Node): char = "}" args = 1 results = 1 @Node.test_func([2], [4]) @Node.test_func([1.5], [3]) def double(self, inp: Node.number): """inp*2""" return inp*2 @Node.test_func([[1,2,3,1,1]], [[1,2,3]]) ...
Fix dedupe not preserving order
Fix dedupe not preserving order
Python
mit
muddyfish/PYKE,muddyfish/PYKE
8f98b52ec670ecfe89f243348f7815b0ae71eed7
gog_utils/gol_connection.py
gog_utils/gol_connection.py
"""Module hosting class representing connection to GoL.""" import json import requests import os import stat WEBSITE_URL = "http://www.gogonlinux.com" AVAILABLE_GAMES = "/available" BETA_GAMES = "/available-beta" def obtain_available_games(): """Returns JSON list of all available games.""" resp = requests.ge...
"""Module hosting class representing connection to GoL.""" import json import requests import os import stat WEBSITE_URL = "http://www.gogonlinux.com" AVAILABLE_GAMES = "/available" BETA_GAMES = "/available-beta" def obtain_available_games(): """Returns JSON list of all available games.""" resp = requests.ge...
Disable falsely reported pylint errors due to unresolved library type
Disable falsely reported pylint errors due to unresolved library type Signed-off-by: Morgawr <528620cabbf4155b02d05fdb6013cd6bb6ad54b5@gmail.com>
Python
bsd-3-clause
Morgawr/gogonlinux,Morgawr/gogonlinux
31cf067f3e4da104551baf0e02332e22a75bb80a
tests/commit/field/test__field_math.py
tests/commit/field/test__field_math.py
from unittest import TestCase from phi import math from phi.geom import Box from phi import field from phi.physics import Domain class TestFieldMath(TestCase): def test_gradient(self): domain = Domain(x=4, y=3) phi = domain.grid() * (1, 2) grad = field.gradient(phi, stack_dim='gradient')...
from unittest import TestCase from phi import math from phi.field import StaggeredGrid, CenteredGrid from phi.geom import Box from phi import field from phi.physics import Domain class TestFieldMath(TestCase): def test_gradient(self): domain = Domain(x=4, y=3) phi = domain.grid() * (1, 2) ...
Add unit test, update documentation
Add unit test, update documentation
Python
mit
tum-pbs/PhiFlow,tum-pbs/PhiFlow
04cd17bb03f2b15cf37313cb3261dd37902d82b0
run_coveralls.py
run_coveralls.py
#!/bin/env/python # -*- coding: utf-8 import os from subprocess import call if __name__ == '__main__': if 'TRAVIS' in os.environ: rc = call('coveralls') raise SystemExit(rc)
#!/bin/env/python # -*- coding: utf-8 import os from subprocess import call if __name__ == '__main__': if 'TRAVIS' in os.environ: print("Calling coveralls") rc = call('coveralls') raise SystemExit(rc)
Add a check that coveralls is actually called
Add a check that coveralls is actually called
Python
mit
browniebroke/deezer-python,browniebroke/deezer-python,pfouque/deezer-python,browniebroke/deezer-python
f13f14b134d76acac9cad8a93b47315fb0df1ba9
utils/stepvals.py
utils/stepvals.py
import math def get_range(val, step): stepvals = [i*step for i in xrange(int(math.ceil(val/step)))][1:] if not stepvals[-1] == val: # if last element isn't the actual value stepvals += [val] # add it in return stepvals
import math def get_range(val, step): if args.step >= val: raise Exception("Step value is too large! Must be smaller than value.") stepvals = [i*step for i in xrange(int(math.ceil(val/step)))][1:] if not stepvals[-1] == val: # if last element isn't the actual value stepvals += [val] # add it in return stepval...
Raise exception if step value is invalid.
Raise exception if step value is invalid.
Python
mit
wei2912/bce-simulation,wei2912/bce-simulation,wei2912/bce-simulation,wei2912/bce-simulation
beac0323253454f343b32d42d8c065cfc4fcc04f
src/epiweb/apps/reminder/models.py
src/epiweb/apps/reminder/models.py
import datetime from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save class Reminder(models.Model): user = models.ForeignKey(User, unique=True) last_reminder = models.DateTimeField() next_reminder = models.DateField() wday = models.Inte...
import datetime from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save _ = lambda x: x # Reference: http://docs.python.org/library/time.html # - tm_wday => range [0,6], Monday is 0 MONDAY = 0 TUESDAY = 1 WEDNESDAY = 2 THURSDAY = 3 FRIDAY = 4 SATURDAY =...
Set available options for weekday field of reminder's model
Set available options for weekday field of reminder's model
Python
agpl-3.0
ISIFoundation/influenzanet-website,ISIFoundation/influenzanet-website,ISIFoundation/influenzanet-website,ISIFoundation/influenzanet-website,ISIFoundation/influenzanet-website,ISIFoundation/influenzanet-website,ISIFoundation/influenzanet-website
4f4d083ea8be7da6a4aecfd4bf15dc4e91a2d72d
palm/blink_model.py
palm/blink_model.py
import numpy from palm.aggregated_kinetic_model import AggregatedKineticModel from palm.probability_vector import make_prob_vec_from_state_ids from palm.state_collection import StateIDCollection class BlinkModel(AggregatedKineticModel): ''' BlinkModel is an AggregatedKineticModel. Two observation classes a...
import numpy from palm.aggregated_kinetic_model import AggregatedKineticModel from palm.probability_vector import make_prob_vec_from_state_ids from palm.state_collection import StateIDCollection class BlinkModel(AggregatedKineticModel): ''' BlinkModel is an AggregatedKineticModel. Two observation classes a...
Add method for final probability vector, which corresponds to all-photobleached collection.
Add method for final probability vector, which corresponds to all-photobleached collection.
Python
bsd-2-clause
grollins/palm
939a96a93d959bf2c26da37adb672f5538c1f222
mmmpaste/db.py
mmmpaste/db.py
from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import scoped_session, sessionmaker from hashlib import md5 engine = create_engine("sqlite:///db/pastebin.db") session = scoped_session(sessionmaker(bind = engine, autoflush = False)) Base = declarative_b...
from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import scoped_session, sessionmaker from hashlib import md5 engine = create_engine("sqlite:///db/pastebin.db") session = scoped_session(sessionmaker(bind = engine, autoflush = False)) Base = declarative_b...
Update base 62 id after paste creation.
Update base 62 id after paste creation.
Python
bsd-2-clause
ryanc/mmmpaste,ryanc/mmmpaste
1ecc62d453a122443924b21cf04edf661f9d1878
mwikiircbot.py
mwikiircbot.py
import ircbotframe import sys class Handler: def __init__(self, host, port=6667, name="MediaWiki", description="MediaWiki recent changes bot", channels=[]): self.channels = channels self.bot = ircbotframe.ircBot(host, port, name, description) self.bot.bind("376", self.endMOTD) self....
import ircbotframe import sys class Handler: def __init__(self, host, port=6667, name="MediaWiki", description="MediaWiki recent changes bot", channels=[]): self.channels = channels self.bot = ircbotframe.ircBot(host, port, name, description) self.bot.bind("376", self.endMOTD) self....
Add command line argument to set bot name
Add command line argument to set bot name
Python
mit
fenhl/mwikiircbot
e7ad2be6cdb87b84bfa77ff9824f2e9913c17599
tests/test_cmd.py
tests/test_cmd.py
import base64 import os from distutils.core import Command class TestCommand(Command): description = "Launch all tests under fusion_tables app" user_options = [] def initialize_options(self): pass def finalize_options(self): pass def create_client_secret_file(self): clie...
import base64 import os from distutils.core import Command class TestCommand(Command): description = "Launch all tests under fusion_tables app" user_options = [] def initialize_options(self): pass def finalize_options(self): pass def create_client_secret_file(self): clie...
Revert "Fix unit test python3 compatibility."
Revert "Fix unit test python3 compatibility." This reverts commit 6807e5a5966f1f37f69a54e255a9981918cc8fb6.
Python
mit
bsvetchine/django-fusion-tables
40d1645f4ad2aca18203ee5ebef1cbbecffa3c51
project/apps/api/signals.py
project/apps/api/signals.py
from django.db.models.signals import ( post_save, ) from django.dispatch import receiver from rest_framework.authtoken.models import Token from django.conf import settings from .models import ( Contest, ) @receiver(post_save, sender=settings.AUTH_USER_MODEL) def user_post_save(sender, instance=None, creat...
from django.db.models.signals import ( post_save, ) from django.dispatch import receiver from rest_framework.authtoken.models import Token from django.conf import settings from .models import ( Contest, ) @receiver(post_save, sender=settings.AUTH_USER_MODEL) def user_post_save(sender, instance=None, creat...
Add check for fixture loading
Add check for fixture loading
Python
bsd-2-clause
dbinetti/barberscore-django,barberscore/barberscore-api,dbinetti/barberscore-django,barberscore/barberscore-api,dbinetti/barberscore,barberscore/barberscore-api,dbinetti/barberscore,barberscore/barberscore-api
d48ae791364a0d29d60636adfde1f143858794cd
api/identifiers/serializers.py
api/identifiers/serializers.py
from rest_framework import serializers as ser from api.base.utils import absolute_reverse from api.base.serializers import JSONAPISerializer, RelationshipField, IDField, LinksField class IdentifierSerializer(JSONAPISerializer): category = ser.CharField(read_only=True) filterable_fields = frozenset(['categor...
from rest_framework import serializers as ser from api.base.utils import absolute_reverse from api.base.serializers import JSONAPISerializer, RelationshipField, IDField, LinksField class IdentifierSerializer(JSONAPISerializer): category = ser.CharField(read_only=True) filterable_fields = frozenset(['categor...
Remove rogue debugger how embarassing
Remove rogue debugger how embarassing
Python
apache-2.0
rdhyee/osf.io,alexschiller/osf.io,Johnetordoff/osf.io,caneruguz/osf.io,acshi/osf.io,abought/osf.io,amyshi188/osf.io,erinspace/osf.io,DanielSBrown/osf.io,chrisseto/osf.io,leb2dg/osf.io,mattclark/osf.io,samchrisinger/osf.io,alexschiller/osf.io,mluke93/osf.io,monikagrabowska/osf.io,mfraezz/osf.io,DanielSBrown/osf.io,crcre...
b375210cf7c6d6d327af61206b6ab36aaaeec6e0
posts/admin.py
posts/admin.py
from django.contrib import admin from reversion import VersionAdmin from base.admin import PrettyFilterMixin, RestrictedCompetitionAdminMixin from base.util import admin_commentable, editonly_fieldsets from .models import Post # Reversion-enabled Admin for problems @admin_commentable @editonly_fieldsets class PostA...
from django.contrib import admin from reversion import VersionAdmin from base.admin import PrettyFilterMixin, RestrictedCompetitionAdminMixin from base.util import admin_commentable, editonly_fieldsets from .models import Post # Reversion-enabled Admin for problems @admin_commentable @editonly_fieldsets class PostA...
Add ability to filter posts by site
posts: Add ability to filter posts by site
Python
mit
rtrembecky/roots,tbabej/roots,rtrembecky/roots,tbabej/roots,rtrembecky/roots,matus-stehlik/roots,matus-stehlik/roots,tbabej/roots,matus-stehlik/roots
4fde2d2c5ccd82373dab802f731d83cc2d3345df
tests/tests_core/test_core_util.py
tests/tests_core/test_core_util.py
import numpy as np from poliastro.core import util def test_rotation_matrix_x(): result = util.rotation_matrix(0.218, 0) expected = np.array( [[1.0, 0.0, 0.0], [0.0, 0.97633196, -0.21627739], [0.0, 0.21627739, 0.97633196]] ) assert np.allclose(expected, result) def test_rotatio...
import numpy as np from poliastro.core import util def test_rotation_matrix_x(): result = util.rotation_matrix(0.218, 0) expected = np.array( [[1.0, 0.0, 0.0], [0.0, 0.97633196, -0.21627739], [0.0, 0.21627739, 0.97633196]] ) assert np.allclose(expected, result) def test_rotation_matrix_y():...
Fix line endings in file
Fix line endings in file
Python
mit
Juanlu001/poliastro,Juanlu001/poliastro,Juanlu001/poliastro,poliastro/poliastro
ccdfafcf58fdf3dc1d95acc090445e56267bd4ab
numpy/distutils/__init__.py
numpy/distutils/__init__.py
from __version__ import version as __version__ # Must import local ccompiler ASAP in order to get # customized CCompiler.spawn effective. import ccompiler import unixccompiler from info import __doc__ from npy_pkg_config import * try: import __config__ _INSTALLED = True except ImportError: _INSTALLED = ...
import sys if sys.version_info[0] < 3: from __version__ import version as __version__ # Must import local ccompiler ASAP in order to get # customized CCompiler.spawn effective. import ccompiler import unixccompiler from info import __doc__ from npy_pkg_config import * try: imp...
Fix relative import in top numpy.distutils.
Fix relative import in top numpy.distutils.
Python
bsd-3-clause
stefanv/numpy,madphysicist/numpy,matthew-brett/numpy,githubmlai/numpy,Dapid/numpy,ahaldane/numpy,bringingheavendown/numpy,GrimDerp/numpy,matthew-brett/numpy,KaelChen/numpy,dwf/numpy,ewmoore/numpy,shoyer/numpy,GaZ3ll3/numpy,stefanv/numpy,gfyoung/numpy,mhvk/numpy,numpy/numpy,SunghanKim/numpy,Anwesh43/numpy,rgommers/numpy...
fa0821f49e26f508971c2f3c97b8696c98901e49
opensimplex_test.py
opensimplex_test.py
from PIL import Image # Depends on the Pillow lib from opensimplex import OpenSimplexNoise WIDTH = 512 HEIGHT = 512 FEATURE_SIZE = 24 def main(): simplex = OpenSimplexNoise() im = Image.new('L', (WIDTH, HEIGHT)) for y in range(0, HEIGHT): for x in range(0, WIDTH): #value = simplex.n...
from PIL import Image # Depends on the Pillow lib from opensimplex import OpenSimplexNoise WIDTH = 512 HEIGHT = 512 FEATURE_SIZE = 24 def main(): simplex = OpenSimplexNoise() im = Image.new('L', (WIDTH, HEIGHT)) for y in range(0, HEIGHT): for x in range(0, WIDTH): #value = simplex.n...
Save the generated noise image.
Save the generated noise image.
Python
mit
lmas/opensimplex,antiface/opensimplex
e8ab72d069633aca71ae60d62ece3c0146289b18
xc7/utils/vivado_output_timing.py
xc7/utils/vivado_output_timing.py
""" Utility for generating TCL script to output timing information from a design checkpoint. """ import argparse def create_runme(f_out, args): print( """ report_timing_summary source {util_tcl} write_timing_info timing_{name}.json5 """.format(name=args.name, util_tcl=args.util_tcl), file=f_out ...
""" Utility for generating TCL script to output timing information from a design checkpoint. """ import argparse def create_output_timing(f_out, args): print( """ source {util_tcl} write_timing_info timing_{name}.json5 report_timing_summary """.format(name=args.name, util_tcl=args.util_tcl), file...
Correct function name and put report_timing_summary at end of script.
Correct function name and put report_timing_summary at end of script. Signed-off-by: Keith Rothman <1bc19627a439baf17510dc2d0b2d250c96d445a5@users.noreply.github.com>
Python
isc
SymbiFlow/symbiflow-arch-defs,SymbiFlow/symbiflow-arch-defs
3bd8354db0931e8721e397a32bf696b023e692b7
test/664-raceway.py
test/664-raceway.py
# https://www.openstreetmap.org/way/28825404 assert_has_feature( 16, 10476, 25242, 'roads', { 'id': 28825404, 'kind': 'minor_road', 'highway': 'raceway' }) # Thunderoad Speedway Go-carts https://www.openstreetmap.org/way/59440900 assert_has_feature( 16, 10516, 25247, 'roads', { 'id': 59440900, 'kind': ...
# https://www.openstreetmap.org/way/28825404 assert_has_feature( 16, 10476, 25242, 'roads', { 'id': 28825404, 'kind': 'minor_road', 'highway': 'raceway' }) # https://www.openstreetmap.org/way/59440900 # Thunderoad Speedway Go-carts assert_has_feature( 16, 10516, 25247, 'roads', { 'id': 59440900, 'kind'...
Put weblink on separate line
Put weblink on separate line
Python
mit
mapzen/vector-datasource,mapzen/vector-datasource,mapzen/vector-datasource
998ab6f457a04ab24bbe062d9704242a207356fb
numpy/setupscons.py
numpy/setupscons.py
#!/usr/bin/env python def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration('numpy',parent_package,top_path, setup_name = 'setupscons.py') config.add_subpackage('distutils') config.add_subpackage('testing') config.add_subpacka...
#!/usr/bin/env python from os.path import join as pjoin def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration from numpy.distutils.misc_util import scons_generate_config_py pkgname = 'numpy' config = Configuration(pkgname,parent_package,top_path, setup...
Handle inplace generation of __config__.
Handle inplace generation of __config__. git-svn-id: 77a43f9646713b91fea7788fad5dfbf67e151ece@5583 94b884b6-d6fd-0310-90d3-974f1d3f35e1
Python
bsd-3-clause
efiring/numpy-work,Ademan/NumPy-GSoC,jasonmccampbell/numpy-refactor-sprint,efiring/numpy-work,illume/numpy3k,Ademan/NumPy-GSoC,illume/numpy3k,teoliphant/numpy-refactor,jasonmccampbell/numpy-refactor-sprint,chadnetzer/numpy-gaurdro,chadnetzer/numpy-gaurdro,efiring/numpy-work,jasonmccampbell/numpy-refactor-sprint,teoliph...
7644ed0e5f0fb3f57798ae65ecd87488d6a7cee1
sync_watchdog.py
sync_watchdog.py
from tapiriik.database import db, close_connections from tapiriik.sync import SyncStep import os import signal import socket from datetime import timedelta, datetime print("Sync watchdog run at %s" % datetime.now()) host = socket.gethostname() for worker in db.sync_workers.find({"Host": host}): # Does the proces...
from tapiriik.database import db, close_connections from tapiriik.sync import SyncStep import os import signal import socket from datetime import timedelta, datetime print("Sync watchdog run at %s" % datetime.now()) host = socket.gethostname() for worker in db.sync_workers.find({"Host": host}): # Does the proces...
Remove locking logic from sync watchdog
Remove locking logic from sync watchdog
Python
apache-2.0
abs0/tapiriik,marxin/tapiriik,cgourlay/tapiriik,cheatos101/tapiriik,brunoflores/tapiriik,olamy/tapiriik,abs0/tapiriik,abs0/tapiriik,cmgrote/tapiriik,marxin/tapiriik,cheatos101/tapiriik,mjnbike/tapiriik,cheatos101/tapiriik,campbellr/tapiriik,gavioto/tapiriik,abhijit86k/tapiriik,cpfair/tapiriik,dmschreiber/tapiriik,niosu...
4ad6f599cdcebc34e9f32a5ab8eaf44a3845ed21
pinry/pins/forms.py
pinry/pins/forms.py
from django import forms from .models import Pin class PinForm(forms.ModelForm): url = forms.CharField(required=False) image = forms.ImageField(label='or Upload', required=False) class Meta: model = Pin fields = ['url', 'image', 'description', 'tags'] def clean(self): cleane...
from django import forms from .models import Pin class PinForm(forms.ModelForm): url = forms.CharField(required=False) image = forms.ImageField(label='or Upload', required=False) _errors = { 'not_image': 'Requested URL is not an image file. Only images are currently supported.', 'pinned'...
Move ValidationError messages to a dictionary that can be accessed from PinForm.clean
Move ValidationError messages to a dictionary that can be accessed from PinForm.clean
Python
bsd-2-clause
supervacuo/pinry,Stackato-Apps/pinry,wangjun/pinry,dotcom900825/xishi,QLGu/pinry,pinry/pinry,lapo-luchini/pinry,dotcom900825/xishi,supervacuo/pinry,MSylvia/pinry,Stackato-Apps/pinry,lapo-luchini/pinry,wangjun/pinry,QLGu/pinry,pinry/pinry,MSylvia/pinry,MSylvia/pinry,pinry/pinry,Stackato-Apps/pinry,pinry/pinry,supervacuo...
b8bad6cda4bdc78d15303002db6687fbae447e51
openacademy/model/openacademy_course.py
openacademy/model/openacademy_course.py
from openerp import models, fields, api class Course(models.Model): _name = 'openacademy.course' # Model odoo name name = fields.Char(string='Title', required=True) # Field reserved to identified name record description = fields.Text(string='Description') responsible_id = fields.Many2one('res.use...
from openerp import models, fields, api class Course(models.Model): _name = 'openacademy.course' # Model odoo name name = fields.Char(string='Title', required=True) # Field reserved to identified name record description = fields.Text(string='Description') responsible_id = fields.Many2one('res.use...
Modify copy method into inherit
[REF] openacademy: Modify copy method into inherit
Python
apache-2.0
felipejta/openacademy-project_072015
f80bd7dbb1b66f3fec52200ecfbc50d779caca05
src/tmlib/workflow/jterator/args.py
src/tmlib/workflow/jterator/args.py
from tmlib.workflow.args import Argument from tmlib.workflow.args import BatchArguments from tmlib.workflow.args import SubmissionArguments from tmlib.workflow.args import ExtraArguments from tmlib.workflow.registry import batch_args from tmlib.workflow.registry import submission_args from tmlib.workflow.registry impor...
from tmlib.workflow.args import Argument from tmlib.workflow.args import BatchArguments from tmlib.workflow.args import SubmissionArguments from tmlib.workflow.args import ExtraArguments from tmlib.workflow.registry import batch_args from tmlib.workflow.registry import submission_args from tmlib.workflow.registry impor...
Fix bug in function that lists existing jterator projects
Fix bug in function that lists existing jterator projects
Python
agpl-3.0
TissueMAPS/TmLibrary,TissueMAPS/TmLibrary,TissueMAPS/TmLibrary,TissueMAPS/TmLibrary,TissueMAPS/TmLibrary
86df5fe205e3a913f5048bef3aa29804dd731d4b
docdown/__init__.py
docdown/__init__.py
# -*- coding: utf-8 -*- __author__ = """Jason Emerick""" __email__ = 'jason@mobelux.com' __version__ = '__version__ = '__version__ = '__version__ = '0.2.7''''
# -*- coding: utf-8 -*- __author__ = """Jason Emerick""" __email__ = 'jason@mobelux.com' __version__ = '0.2.7'
Fix (another) syntax error. Thanks, bumpversion
Fix (another) syntax error. Thanks, bumpversion
Python
bsd-3-clause
livio/DocDown-Python,livio/DocDown-Python,livio/DocDown-Python,livio/DocDown-Python,livio/DocDown-Python,livio/DocDown-Python
7e1d42e6730336296ef3b702eb4cde64ce8410c5
dockerpuller/app.py
dockerpuller/app.py
from flask import Flask from flask import request from flask import jsonify import json import subprocess app = Flask(__name__) config = None @app.route('/', methods=['POST']) def hook_listen(): if request.method == 'POST': token = request.args.get('token') if token == config['token']: ...
from flask import Flask from flask import request from flask import jsonify import json import subprocess app = Flask(__name__) config = None @app.route('/', methods=['POST']) def hook_listen(): if request.method == 'POST': token = request.args.get('token') if token == config['token']: ...
Define default values for host and port
Define default values for host and port
Python
mit
glowdigitalmedia/docker-puller,nicocoffo/docker-puller,nicocoffo/docker-puller,glowdigitalmedia/docker-puller
9808e97747785c27387ad1ce9ffc3e9a05c80f08
enigma.py
enigma.py
import string class Steckerbrett: def __init__(self): pass class Walzen: def __init__(self): pass class Enigma: def __init__(self): pass def cipher(self, message): pass
import string class Steckerbrett: def __init__(self): pass class Umkehrwalze: def __init__(self, wiring): self.wiring = wiring def encode(self, letter): return self.wiring[string.ascii_uppercase.index(letter)] class Walzen: def __init__(self): pass class Enigma: ...
Create class for the reflectors
Create class for the reflectors
Python
mit
ranisalt/enigma
f710479e01d50dad03133d76b349398ab11e8675
backend/constants.py
backend/constants.py
# Fill out with value from # https://firebase.corp.google.com/project/trogdors-29fa4/settings/database FIREBASE_SECRET = "ZiD9uLhDnrLq2n416MjWjn0JOrci6H0oGm7bKyVN" FIREBASE_EMAIL = "" ALLEGIANCES = ('horde', 'resistance', 'none') TEST_ENDPOINT = 'http://localhost:8080' PLAYER_VOLUNTEER_ARGS = ( 'helpAdvertising', '...
# Fill out with value from # https://console.firebase.google.com/project/trogdors-29fa4/settings/serviceaccounts/databasesecrets FIREBASE_SECRET = "" FIREBASE_EMAIL = "" ALLEGIANCES = ('horde', 'resistance', 'none') TEST_ENDPOINT = 'http://localhost:8080' PLAYER_VOLUNTEER_ARGS = ( 'helpAdvertising', 'helpLogistics'...
Drop FIREBASE_SECRET (since been revoked)
Drop FIREBASE_SECRET (since been revoked)
Python
apache-2.0
google/playhvz,google/playhvz,google/playhvz,google/playhvz,google/playhvz,google/playhvz,google/playhvz,google/playhvz
b85751e356c091d2dffe8366a94fbb42bfcad34e
src/SMESH_SWIG/SMESH_GroupLyingOnGeom.py
src/SMESH_SWIG/SMESH_GroupLyingOnGeom.py
import SMESH def BuildGroupLyingOn(theMesh, theElemType, theName, theShape): aMeshGen = salome.lcc.FindOrLoadComponent("FactoryServer", "SMESH") aFilterMgr = aMeshGen.CreateFilterManager() aFilter = aFilterMgr.CreateFilter() aLyingOnGeom = aFilterMgr.CreateLyingOnGeom() aLyingOnGeom.SetGeom(th...
from meshpy import * def BuildGroupLyingOn(theMesh, theElemType, theName, theShape): aFilterMgr = smesh.CreateFilterManager() aFilter = aFilterMgr.CreateFilter() aLyingOnGeom = aFilterMgr.CreateLyingOnGeom() aLyingOnGeom.SetGeom(theShape) aLyingOnGeom.SetElementType(theElemType) aFilte...
Fix a bug - salome.py is not imported here and this causes run-time Python exception
Fix a bug - salome.py is not imported here and this causes run-time Python exception
Python
lgpl-2.1
FedoraScientific/salome-smesh,FedoraScientific/salome-smesh,FedoraScientific/salome-smesh,FedoraScientific/salome-smesh
c3957dbb25a8b5eeeccd37f218976721249b93e2
src/competition/tests/validator_tests.py
src/competition/tests/validator_tests.py
from django.test import TestCase from django.template.defaultfilters import slugify from django.core.exceptions import ValidationError from competition.validators import greater_than_zero, non_negative, validate_name class ValidationFunctionTest(TestCase): def test_greater_than_zero(self): """Check grea...
from django.test import TestCase from django.template.defaultfilters import slugify from django.core.exceptions import ValidationError from competition.validators import greater_than_zero, non_negative, validate_name class ValidationFunctionTest(TestCase): def test_greater_than_zero(self): """Check grea...
Correct unit tests to comply with new team name RE
Correct unit tests to comply with new team name RE
Python
bsd-3-clause
michaelwisely/django-competition,michaelwisely/django-competition,michaelwisely/django-competition
5ab6c21bbcaaf9b919c9a796ec00d1a805ec1b0d
apps/bplan/emails.py
apps/bplan/emails.py
from adhocracy4.emails import Email class OfficeWorkerNotification(Email): template_name = 'meinberlin_bplan/emails/office_worker_notification' @property def office_worker_email(self): project = self.object.project return project.externalproject.bplan.office_worker_email def get_rece...
from adhocracy4.emails import Email class OfficeWorkerNotification(Email): template_name = 'meinberlin_bplan/emails/office_worker_notification' @property def office_worker_email(self): project = self.object.project return project.externalproject.bplan.office_worker_email def get_rece...
Set bplan default email to english as default
Set bplan default email to english as default
Python
agpl-3.0
liqd/a4-meinberlin,liqd/a4-meinberlin,liqd/a4-meinberlin,liqd/a4-meinberlin
fa86706ae6cf77ef71402bb86d12cdd3cb79dafc
shub/logout.py
shub/logout.py
import re, click from shub.utils import get_key_netrc, NETRC_FILE @click.command(help='remove Scrapinghug API key from the netrc file') @click.pass_context def cli(context): if not get_key_netrc(): context.fail('Key not found in netrc file') with open(NETRC_FILE, 'r+') as out: key_re = r'machin...
import re, click from shub.utils import get_key_netrc, NETRC_FILE @click.command(help='remove Scrapinghug API key from the netrc file') @click.pass_context def cli(context): if not get_key_netrc(): context.fail('Key not found in netrc file') error, msg = remove_sh_key() if error: context.fa...
Add verification for removing key from netrc file
Add verification for removing key from netrc file
Python
bsd-3-clause
scrapinghub/shub
5ff35d282b61cfdfc53deaa0f1bc0f83850ff7a5
downstream_node/lib/utils.py
downstream_node/lib/utils.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import json def model_to_json(model): """ Returns a JSON representation of an SQLAlchemy-backed object. From Zato: https://github.com/zatosource/zato """ _json = {} _json['fields'] = {} _json['pk'] = getattr(model, 'id') for col in model._sa...
#!/usr/bin/env python # -*- coding: utf-8 -*- import json def model_to_json(model): """ Returns a JSON representation of an SQLAlchemy-backed object. From Zato: https://github.com/zatosource/zato """ _json = {} _json['fields'] = {} _json['pk'] = getattr(model, 'id') for col in model._sa...
Add helper method to turn queries into json-serializable lists
Add helper method to turn queries into json-serializable lists
Python
mit
Storj/downstream-node,Storj/downstream-node
a589aa63f250a347ab24b7309e65ef25c7281437
src/sentry/utils/imports.py
src/sentry/utils/imports.py
""" sentry.utils.imports ~~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2010-2014 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from __future__ import absolute_import import pkgutil import six class ModuleProxyCache(dict): def __missing__(self, key): if '.' not...
""" sentry.utils.imports ~~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2010-2014 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from __future__ import absolute_import import pkgutil import six class ModuleProxyCache(dict): def __missing__(self, key): if '.' not...
Correct import behavior to prevent Runtime error
Correct import behavior to prevent Runtime error
Python
bsd-3-clause
gencer/sentry,jean/sentry,fotinakis/sentry,gencer/sentry,looker/sentry,BuildingLink/sentry,gencer/sentry,jean/sentry,JackDanger/sentry,fotinakis/sentry,BuildingLink/sentry,beeftornado/sentry,zenefits/sentry,beeftornado/sentry,looker/sentry,ifduyue/sentry,ifduyue/sentry,JamesMura/sentry,ifduyue/sentry,JamesMura/sentry,B...
697d56dcd4aae19e6cb2351eb39a5c195f8ed029
instana/instrumentation/urllib3.py
instana/instrumentation/urllib3.py
import opentracing.ext.tags as ext import opentracing import wrapt @wrapt.patch_function_wrapper('urllib3', 'PoolManager.urlopen') def urlopen_with_instana(wrapped, instance, args, kwargs): try: span = opentracing.global_tracer.start_span("urllib3") span.set_tag(ext.HTTP_URL, args[1]) span...
from __future__ import absolute_import import opentracing.ext.tags as ext import instana import opentracing import wrapt @wrapt.patch_function_wrapper('urllib3', 'PoolManager.urlopen') def urlopen_with_instana(wrapped, instance, args, kwargs): try: span = instana.internal_tracer.start_span("urllib3") ...
Expand 5xx coverage; log exceptions
Expand 5xx coverage; log exceptions
Python
mit
instana/python-sensor,instana/python-sensor
f48c15a6b0c09db26a0f1b0e8846acf1c5e8cc62
plyer/platforms/ios/gyroscope.py
plyer/platforms/ios/gyroscope.py
''' iOS Gyroscope --------------------- ''' from plyer.facades import Gyroscope from pyobjus import autoclass from pyobjus.dylib_manager import load_framework load_framework('/System/Library/Frameworks/UIKit.framework') UIDevice = autoclass('UIDevice') device = UIDevice.currentDevice() class IosGyroscope(Gyroscop...
''' iOS Gyroscope --------------------- ''' from plyer.facades import Gyroscope from pyobjus import autoclass from pyobjus.dylib_manager import load_framework load_framework('/System/Library/Frameworks/UIKit.framework') UIDevice = autoclass('UIDevice') device = UIDevice.currentDevice() class IosGyroscope(Gyroscop...
Add method for uncalibrated values of iOS Gyroscope
Add method for uncalibrated values of iOS Gyroscope
Python
mit
KeyWeeUsr/plyer,KeyWeeUsr/plyer,kivy/plyer,KeyWeeUsr/plyer,kivy/plyer,kivy/plyer
9bcacb5488d32e9e4483c0b54abfa548885148d2
tamarackcollector/worker.py
tamarackcollector/worker.py
import json import requests import time from collections import Counter from multiprocessing import Process, Queue from queue import Empty shared_queue = None def datetime_by_minute(dt): return dt.replace(second=0, microsecond=0).isoformat() + 'Z' def process_jobs(url, app_id, queue): while True: ...
import json import requests import time from collections import Counter from multiprocessing import Process, Queue from queue import Empty shared_queue = None def datetime_by_minute(dt): return dt.replace(second=0, microsecond=0).isoformat() + 'Z' def process_jobs(url, app_id, queue): while True: ...
Send request_count and error_count outside sensor_data
Send request_count and error_count outside sensor_data
Python
bsd-3-clause
tamarackapp/tamarack-collector-py
46dda5e761d3752fce26b379cc8542e3f5244376
examples/fabfile.py
examples/fabfile.py
"""Example of integration between Fabric and Datadog. """ from fabric.api import * from fabric.colors import * from dogapi.fab import setup, notify setup(api_key = "YOUR API KEY HERE") # Make sure @notify is just below @task @task(default=True, alias="success") @notify def sweet_task(some_arg, other_arg): """Alw...
"""Example of integration between Fabric and Datadog. """ from fabric.api import * from fabric.colors import * from dogapi.fab import setup, notify setup(api_key = "YOUR API KEY HERE") # Make sure @notify is just below @task @notify @task(default=True, alias="success") def sweet_task(some_arg, other_arg): """Alw...
Make sure @ notify is the first decorator
Make sure @ notify is the first decorator fixes #91
Python
bsd-3-clause
DataDog/dogapi,DataDog/dogapi
235bf56a4f80475f618a62db15844d7a004dd967
scripts/TestFontCompilation.py
scripts/TestFontCompilation.py
from string import split from os import remove from mojo.roboFont import version from jkRFoTools.FontChooser import ProcessFonts def test_compilation(font): temp_font = font.copy(showUI=False) for g in temp_font: g.clear() if font.path is None: return "ERROR: The font needs to be sav...
from os import remove from os.path import exists from mojo.roboFont import version from jkRFoTools.FontChooser import ProcessFonts from fontCompiler.compiler import FontCompilerOptions from fontCompiler.emptyCompiler import EmptyOTFCompiler def test_compilation(font): if font.path is None: return "ERROR:...
Use EmptyOTFCompiler for test compilation
Use EmptyOTFCompiler for test compilation
Python
mit
jenskutilek/RoboFont,jenskutilek/RoboFont
61e6fbbba42256f0a4b9d8b6ad25575ec6c21fee
scripts/datachain/datachain.py
scripts/datachain/datachain.py
import os import sys import MySQLdb sys.path.append('D:\\Projects\\PySQLKits\\lib\\simplequery') from table_data import * from simplequery import * def get_mysql_connection(): args = {'host':'localhost', 'user':'root', 'passwd':'root', 'db':"test"} conn = MySQLdb.connect(**args) with conn.cursor() as c:...
import os from os.path import dirname import sys import MySQLdb root_path = dirname(dirname(os.getcwd())) require_path = os.path.join(root_path, 'lib\\simplequery') sys.path.append(require_path) from table_data import * from simplequery import * def get_mysql_connection(): args = {'host':'localhost', 'user':'r...
Refactor import path and usage
Refactor import path and usage
Python
mit
healerkx/PySQLKits,healerkx/PySQLKits
0e04613306defe11f1c358a594352008120c7b41
datasets/admin.py
datasets/admin.py
from django.contrib import admin from datasets.models import Dataset, Sound, Vote, Taxonomy, DatasetRelease, TaxonomyNode class TaxonomyNodeAdmin(admin.ModelAdmin): fields = ('node_id', 'name', 'description', 'citation_uri', 'faq', 'omitted', 'list_freesound_examples', 'list_freesound_examples_verif...
from django.contrib import admin from datasets.models import Dataset, Sound, Vote, Taxonomy, DatasetRelease, TaxonomyNode class TaxonomyNodeAdmin(admin.ModelAdmin): fields = ('node_id', 'name', 'description', 'citation_uri', 'faq', 'omitted', 'list_freesound_examples', 'list_freesound_examples_verif...
Add Admin beginner task field TaxonomyNode
Add Admin beginner task field TaxonomyNode
Python
agpl-3.0
MTG/freesound-datasets,MTG/freesound-datasets,MTG/freesound-datasets,MTG/freesound-datasets
fb5fc6e62a3c1b018d8f68cc37e4d541226a564b
integration-tests/features/steps/gremlin.py
integration-tests/features/steps/gremlin.py
"""Tests for Gremlin database.""" import os import requests from behave import given, then, when from urllib.parse import urljoin @when('I access Gremlin API') def gremlin_url_access(context): """Access the Gremlin service API using the HTTP POST method.""" post_query(context, "") def post_query(context, q...
"""Tests for Gremlin database.""" import os import requests from behave import given, then, when from urllib.parse import urljoin from src.json_utils import * @when('I access Gremlin API') def gremlin_url_access(context): """Access the Gremlin service API using the HTTP POST method.""" post_query(context, ""...
Test step for check the Gremlin response structure
Test step for check the Gremlin response structure
Python
apache-2.0
tisnik/fabric8-analytics-common,jpopelka/fabric8-analytics-common,jpopelka/fabric8-analytics-common,tisnik/fabric8-analytics-common,tisnik/fabric8-analytics-common,jpopelka/fabric8-analytics-common
0bd469751034c9a9bc9c3b6f396885670722a692
manage.py
manage.py
#!/usr/bin/env python import os from flask_script import Manager, Server from flask_script.commands import ShowUrls, Clean from mothership import create_app from mothership.models import db # default to dev config because no one should use this in # production anyway env = os.environ.get('MOTHERSHIP_ENV', 'dev') app...
#!/usr/bin/env python import os from flask_script import Manager, Server from flask_script.commands import ShowUrls, Clean from mothership import create_app from mothership.models import db # default to dev config because no one should use this in # production anyway env = os.environ.get('MOTHERSHIP_ENV', 'dev') app...
Remove comment for running under uwsgi
Remove comment for running under uwsgi
Python
mit
afl-mothership/afl-mothership,afl-mothership/afl-mothership,afl-mothership/afl-mothership,afl-mothership/afl-mothership
243f973ee1757b7b8426e9e4b62de2a272d82407
protocols/urls.py
protocols/urls.py
from django.conf.urls import patterns, url urlpatterns = patterns('protocols.views', url(r'^archive/$', 'list_all_protocols', name='list_all_protocols'), url(r'^add/$', 'add', name='add_protocol'), )
from django.conf.urls import patterns, url urlpatterns = patterns('protocols.views', url(r'^archive/$', 'list_all_protocols', name='list_all_protocols'), url(r'^add/$', 'add', name='add_protocol'), url(r'^page/(?P<page>.*)/$', 'listing', name='pagination') )
Add url for listing protocols
Add url for listing protocols
Python
mit
Hackfmi/Diaphanum,Hackfmi/Diaphanum
ef98d8bf242bfd182b4e5c8675db599182a371a5
metpy/io/__init__.py
metpy/io/__init__.py
# Copyright (c) 2015,2016,2018 MetPy Developers. # Distributed under the terms of the BSD 3-Clause License. # SPDX-License-Identifier: BSD-3-Clause """MetPy's IO module contains classes for reading files. These classes are written to take both file names (for local files) or file-like objects; this allows reading files...
# Copyright (c) 2015,2016,2018 MetPy Developers. # Distributed under the terms of the BSD 3-Clause License. # SPDX-License-Identifier: BSD-3-Clause """Classes for reading various file formats. These classes are written to take both file names (for local files) or file-like objects; this allows reading files that are a...
Make io module docstring conform to standards
MNT: Make io module docstring conform to standards Picked up by pydocstyle 3.0.
Python
bsd-3-clause
Unidata/MetPy,ShawnMurd/MetPy,ahaberlie/MetPy,jrleeman/MetPy,dopplershift/MetPy,jrleeman/MetPy,Unidata/MetPy,ahaberlie/MetPy,dopplershift/MetPy
8e3cc5821f3b597b256eb9f586380f3b3cfd35a8
qnd/experiment.py
qnd/experiment.py
import tensorflow as tf from .flag import FLAGS, FlagAdder from .estimator import def_estimator from .inputs import def_def_train_input_fn from .inputs import def_def_eval_input_fn def def_def_experiment_fn(): adder = FlagAdder() works_with = lambda name: "Works only with {}".format(name) train_help = w...
import tensorflow as tf from .flag import FLAGS, FlagAdder from .estimator import def_estimator from .inputs import DataUse, def_def_train_input_fn, def_def_eval_input_fn def def_def_experiment_fn(): adder = FlagAdder() for use in DataUse: use = use.value adder.add_flag("{}_steps".format(use...
Fix outdated command line help
Fix outdated command line help
Python
unlicense
raviqqe/tensorflow-qnd,raviqqe/tensorflow-qnd
2609042ba2a11089561d3c9d9f0542f263619951
src/models/event.py
src/models/event.py
from flock import db class Event(db.Model): id = db.Column(db.Integer, primary_key=True) def __init__(self): pass
from flock import db class Event(db.Model): id = db.Column(db.Integer, primary_key=True) owner_id = db.Column(db.Integer, foreign_key('user.id'), primary_key=True) def __init__(self): pass
Add owner as a primary, foreign key
Add owner as a primary, foreign key
Python
agpl-3.0
DavidJFelix/hatchit,DavidJFelix/hatchit,DavidJFelix/hatchit
ffee30cb1a5b9e477a7456bcd753a45c2a02fb4f
glance_registry_local_check.py
glance_registry_local_check.py
#!/usr/bin/env python from maas_common import (status_ok, status_err, metric, get_keystone_client, get_auth_ref) from requests import Session from requests import exceptions as exc def check(auth_ref): keystone = get_keystone_client(auth_ref) tenant_id = keystone.tenant_id auth_t...
#!/usr/bin/env python from maas_common import (status_ok, status_err, metric, get_keystone_client, get_auth_ref) from requests import Session from requests import exceptions as exc def check(auth_ref): keystone = get_keystone_client(auth_ref) tenant_id = keystone.tenant_id auth_t...
Send proper response time even if non-200
Send proper response time even if non-200
Python
apache-2.0
claco/rpc-openstack,robb-romans/rpc-openstack,cloudnull/rpc-maas,mattt416/rpc-openstack,stevelle/rpc-openstack,nrb/rpc-openstack,npawelek/rpc-maas,xeregin/rpc-openstack,xeregin/rpc-openstack,shannonmitchell/rpc-openstack,cfarquhar/rpc-openstack,git-harry/rpc-openstack,sigmavirus24/rpc-openstack,prometheanfire/rpc-opens...
0cebce08025844ae1e0154b7332779be0567e9ab
ipywidgets/widgets/__init__.py
ipywidgets/widgets/__init__.py
from .widget import Widget, CallbackDispatcher, register, widget_serialization from .domwidget import DOMWidget from .trait_types import Color, EventfulDict, EventfulList from .widget_bool import Checkbox, ToggleButton, Valid from .widget_button import Button from .widget_box import Box, FlexBox, Proxy, PlaceProxy, H...
from .widget import Widget, CallbackDispatcher, register, widget_serialization from .domwidget import DOMWidget from .trait_types import Color, EventfulDict, EventfulList from .widget_bool import Checkbox, ToggleButton, Valid from .widget_button import Button from .widget_box import Box, FlexBox, Proxy, PlaceProxy, H...
Add ScrollableDropdown import to ipywidgets
Add ScrollableDropdown import to ipywidgets
Python
bsd-3-clause
ipython/ipywidgets,cornhundred/ipywidgets,SylvainCorlay/ipywidgets,ipython/ipywidgets,jupyter-widgets/ipywidgets,cornhundred/ipywidgets,SylvainCorlay/ipywidgets,SylvainCorlay/ipywidgets,ipython/ipywidgets,SylvainCorlay/ipywidgets,cornhundred/ipywidgets,jupyter-widgets/ipywidgets,ipython/ipywidgets,ipython/ipywidgets,ju...
f0c7e1b8a2de6f7e9445e2158cf679f399df6545
jupyternotify/jupyternotify.py
jupyternotify/jupyternotify.py
# see https://ipython.org/ipython-doc/3/config/custommagics.html # for more details on the implementation here import uuid from IPython.core.getipython import get_ipython from IPython.core.magic import Magics, magics_class, cell_magic from IPython.display import display, Javascript from pkg_resources import resource_f...
# see https://ipython.org/ipython-doc/3/config/custommagics.html # for more details on the implementation here import uuid from IPython.core.getipython import get_ipython from IPython.core.magic import Magics, magics_class, cell_magic from IPython.display import display, Javascript from pkg_resources import resource_f...
Make this work with python2 too.
Make this work with python2 too.
Python
bsd-3-clause
ShopRunner/jupyter-notify,ShopRunner/jupyter-notify
582fb412560ce068e2ac516a64ab1979beaccdb2
keystonemiddleware_echo/app.py
keystonemiddleware_echo/app.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 # distributed under t...
# 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 # distributed under t...
Use pprint instead of json for formatting
Use pprint instead of json for formatting json.dumps fails to print anything for an object. I would prefer to show a representation of the object rather than filter it out so rely on pprint instead.
Python
apache-2.0
jamielennox/keystonemiddleware-echo
ac173dd3eace738b705ad5924aa830d3c3dffcf6
Instanssi/admin_screenshow/forms.py
Instanssi/admin_screenshow/forms.py
# -*- coding: utf-8 -*- from django import forms from django.core.exceptions import ValidationError from crispy_forms.helper import FormHelper from crispy_forms.layout import Submit, Layout, Fieldset, ButtonHolder from Instanssi.screenshow.models import Sponsor,Message,IRCMessage import os class MessageForm(forms.Mod...
# -*- coding: utf-8 -*- from django import forms from django.core.exceptions import ValidationError from crispy_forms.helper import FormHelper from crispy_forms.layout import Submit, Layout, Fieldset, ButtonHolder from Instanssi.screenshow.models import Sponsor,Message,IRCMessage import os class IRCMessageForm(forms....
Add form for irc messages.
admin_screenshow: Add form for irc messages.
Python
mit
Instanssi/Instanssi.org,Instanssi/Instanssi.org,Instanssi/Instanssi.org,Instanssi/Instanssi.org
4b127103d8bea8e9dc9793e92abee9f7a111a018
doc/Manual/config.py
doc/Manual/config.py
from Synopsis.Config import Base class Config (Base): class Formatter (Base.Formatter): class HTML (Base.Formatter.HTML): toc_output = 'links.toc' pages = [ 'ScopePages', 'ModuleListingJS', 'ModuleIndexer', 'FileTreeJS', 'InheritanceTree', 'InheritanceGraph', 'NameIndex', 'FilePages', '...
from Synopsis.Config import Base class Config (Base): class Formatter (Base.Formatter): class HTML (Base.Formatter.HTML): toc_output = 'links.toc' pages = [ 'ScopePages', 'ModuleListingJS', 'ModuleIndexer', 'FileTreeJS', 'InheritanceTree', 'InheritanceGraph', 'NameIndex', 'FilePages', (...
Use custom modules in modules.py
Use custom modules in modules.py
Python
lgpl-2.1
stefanseefeld/synopsis,stefanseefeld/synopsis,stefanseefeld/synopsis,stefanseefeld/synopsis,stefanseefeld/synopsis,stefanseefeld/synopsis
b26fc811872caf3393be0a6b6c0800f5335ad2df
netbox/utilities/metadata.py
netbox/utilities/metadata.py
from rest_framework.metadata import SimpleMetadata from django.utils.encoding import force_str from utilities.api import ContentTypeField class ContentTypeMetadata(SimpleMetadata): def get_field_info(self, field): field_info = super().get_field_info(field) if hasattr(field, 'queryset') and not fi...
from rest_framework.metadata import SimpleMetadata from django.utils.encoding import force_str from utilities.api import ContentTypeField class ContentTypeMetadata(SimpleMetadata): def get_field_info(self, field): field_info = super().get_field_info(field) if hasattr(field, 'queryset') and not fi...
Sort the list for consistent output
Sort the list for consistent output
Python
apache-2.0
digitalocean/netbox,digitalocean/netbox,digitalocean/netbox,digitalocean/netbox
7cdbf0c989109c089c758d28b68f5f1925ebf388
securedrop/worker.py
securedrop/worker.py
import os from redis import Redis from rq import Queue queue_name = 'test' if os.environ.get('SECUREDROP_ENV') == 'test' else 'default' q = Queue(name=queue_name, connection=Redis()) def enqueue(*args, **kwargs): q.enqueue(*args, **kwargs)
import os from redis import Redis from rq import Queue queue_name = 'test' if os.environ.get('SECUREDROP_ENV') == 'test' else 'default' # `srm` can take a long time on large files, so allow it run for up to an hour q = Queue(name=queue_name, connection=Redis(), default_timeout=3600) def enqueue(*args, **kwargs): ...
Increase job timeout for securely deleting files
Increase job timeout for securely deleting files
Python
agpl-3.0
garrettr/securedrop,kelcecil/securedrop,jaseg/securedrop,jeann2013/securedrop,jeann2013/securedrop,chadmiller/securedrop,micahflee/securedrop,micahflee/securedrop,pwplus/securedrop,harlo/securedrop,ageis/securedrop,ageis/securedrop,jeann2013/securedrop,kelcecil/securedrop,micahflee/securedrop,harlo/securedrop,jrosco/se...
e2b7ebf9a559a50462f64ca15a7688166fd4de9f
modules/music/gs.py
modules/music/gs.py
import subprocess from grooveshark import Client client = Client() client.init() def get_song_url(song_name): song = client.search(song_name).next() return song.stream.url def play_song_url(song_url): subprocess.call(['cvlc', song_url]) def play_song(song_name): play_song_url(get_song_url(song_name)...
import subprocess from grooveshark import Client client = Client() client.init() def get_song_url(song_name): song = client.search(song_name).next() return song.stream.url def play_song_url(song_url): subprocess.call(['cvlc', '--play-and-exit', song_url]) def play_song(song_name): play_song_url(get_...
Make vlc exit at end of play
Make vlc exit at end of play
Python
mit
adelq/mirror
268753ad6e4c3345e821c541e1851ee7f7a2b649
eachday/tests/test_resource_utils.py
eachday/tests/test_resource_utils.py
from eachday.tests.base import BaseTestCase import json class TestResourceUtils(BaseTestCase): def test_invalid_json_error(self): ''' Test that an invalid JSON body has a decent error message ''' resp = self.client.post( '/register', data='{"invalid": json}', co...
from eachday.resources import LoginResource from eachday.tests.base import BaseTestCase from unittest.mock import patch import json class TestResourceUtils(BaseTestCase): def test_invalid_json_error(self): ''' Test that an invalid JSON body has a decent error message ''' resp = self.client.post( ...
Add test for exception handling in flask app
Add test for exception handling in flask app
Python
mit
bcongdon/EachDay,bcongdon/EachDay,bcongdon/EachDay,bcongdon/EachDay
24089dfb12c3ecbec40423acf4d3c89c0b833f40
share/models/util.py
share/models/util.py
import zlib import base64 import binascii from django.db import models from django.core import exceptions class ZipField(models.Field): def db_type(self, connection): return 'bytea' def pre_save(self, model_instance, add): value = getattr(model_instance, self.attname) assert isinsta...
import zlib import base64 import binascii from django.db import models from django.core import exceptions class ZipField(models.Field): def db_type(self, connection): return 'bytea' def pre_save(self, model_instance, add): value = getattr(model_instance, self.attname) assert isinsta...
Make it just return the string if it is not base64
Make it just return the string if it is not base64
Python
apache-2.0
CenterForOpenScience/SHARE,aaxelb/SHARE,laurenbarker/SHARE,CenterForOpenScience/SHARE,zamattiac/SHARE,laurenbarker/SHARE,aaxelb/SHARE,zamattiac/SHARE,laurenbarker/SHARE,zamattiac/SHARE,aaxelb/SHARE,CenterForOpenScience/SHARE
eb368c344075ce78606d4656ebfb19c7e7ccdf50
src/054.py
src/054.py
from path import dirpath def ans(): lines = open(dirpath() + '054.txt').readlines() cards = [line.strip().split() for line in lines] return None if __name__ == '__main__': print(ans())
from collections import ( defaultdict, namedtuple, ) from path import dirpath def _value(rank): try: return int(rank) except ValueError: return 10 + 'TJQKA'.index(rank) def _sort_by_rank(hand): return list(reversed(sorted( hand, key=lambda card: _value(card[0]), ...
Write some logic for 54
Write some logic for 54
Python
mit
mackorone/euler
88517c2f458a0e94b1a526bf99e565571353ed56
flicktor/__main__.py
flicktor/__main__.py
from flicktor import subcommands def main(): parser = subcommands._argpaser() args = parser.parse_args() try: args.func(args) # except AttributeError: # parser.print_help() except KeyboardInterrupt: print("bye.") if __name__ == '__main__': main()
from flicktor import subcommands def main(): parser = subcommands._argpaser() args = parser.parse_args() try: if hasattr(args, "func"): args.func(args) else: parser.print_help() except KeyboardInterrupt: print("bye.") if __name__ == '__main__': ...
Print help when subcommand is not supecified
Print help when subcommand is not supecified
Python
mit
minamorl/flicktor
6c19837ec2d29e2ad48c09b6287e64c825830bc9
prototypes/regex/__init__.py
prototypes/regex/__init__.py
# coding: utf-8 """ regex ~~~~~ This is a prototype for an implementation of regular expressions. The goal of this prototype is to develop a completely transparent implementation, that can be better reasoned about and used in a parser. Note that as of now "regular expressions" actually means *...
# coding: utf-8 """ regex ~~~~~ This is a prototype for an implementation of regular expressions. The goal of this prototype is to develop a completely transparent implementation, that can be better reasoned about and used in a parser. This is not meant to be an implementation that will see rea...
Add warning about real-world usage
Add warning about real-world usage
Python
bsd-3-clause
DasIch/editor
c458126baac92e1152026f51a9d3a544e8c6826f
testsV2/ut_repy2api_copycontext.py
testsV2/ut_repy2api_copycontext.py
""" Check that copy and repr of _context SafeDict don't result in inifinite loop """ #pragma repy # Create an almost shallow copy of _context # Contained self-reference is moved from _context to _context_copy _context_copy = _context.copy() repr(_context) repr(_context_copy)
""" Check that copy and repr of _context SafeDict don't result in infinite loop """ #pragma repy # Create an "almost" shallow copy of _context, i.e. the contained reference # to _context is not copied as such but is changed to reference the new # _context_copy. # In consequence repr immediately truncates the contained...
Update comment in copycontext unit test
Update comment in copycontext unit test Following @vladimir-v-diaz's review comment this change adds more information about how repr works with Python dicts and with repy's SafeDict to the unit test's comments. Even more information can be found on the issue tracker SeattleTestbed/repy_v2#97.
Python
mit
SeattleTestbed/repy_v2
d10199e4e3cd5b0557cf2dc2f4aea1014f18a290
lib/wordfilter.py
lib/wordfilter.py
import os import json class Wordfilter: def __init__(self): # json is in same directory as this class, given by __location__. __location__ = os.path.realpath( os.path.join(os.getcwd(), os.path.dirname(__file__))) with open(os.path.join(__location__, 'badwords.json')) as f: self.blacklist = ...
import os import json class Wordfilter: def __init__(self): # json is in same directory as this class, given by __location__. __location__ = os.path.realpath( os.path.join(os.getcwd(), os.path.dirname(__file__))) with open(os.path.join(__location__, 'badwords.json')) as f: self.blacklist = ...
Fix AttributeError: 'list' object has no attribute 'lower'
Fix AttributeError: 'list' object has no attribute 'lower'
Python
mit
dariusk/wordfilter,hugovk/wordfilter,hugovk/wordfilter,mwatson/wordfilter,hugovk/wordfilter,dariusk/wordfilter,mwatson/wordfilter,dariusk/wordfilter,mwatson/wordfilter,mwatson/wordfilter,dariusk/wordfilter,hugovk/wordfilter
322d8f90f86c40a756716a79e7e5719196687ece
saic/paste/search_indexes.py
saic/paste/search_indexes.py
import datetime from haystack.indexes import * from haystack import site from models import Paste, Commit class CommitIndex(RealTimeSearchIndex): text = CharField(document=True, use_template=True) commit = CharField(model_attr='commit') created = DateField(model_attr='created') user = CharField(model_a...
import datetime from haystack.indexes import * from haystack import site from models import Paste, Commit class CommitIndex(RealTimeSearchIndex): text = CharField(document=True, use_template=True) commit = CharField(model_attr='commit') created = DateField(model_attr='created') user = CharField(model_a...
Update search index to look for all objects.
Update search index to look for all objects.
Python
bsd-3-clause
justinvh/gitpaste,GarrettHeel/quark-paste,GarrettHeel/quark-paste,justinvh/gitpaste,justinvh/gitpaste,justinvh/gitpaste,GarrettHeel/quark-paste
1bda3fa8b3bffaca38b26191602e74d0afeaad19
app/views.py
app/views.py
from flask import render_template, request, Blueprint import json from app.state import state index = Blueprint('index', __name__, template_folder='templates') @index.route('/', methods=['POST', 'GET']) def show(): if request.method == 'GET': return render_template('index.html', program = '...
from flask import render_template, request, Blueprint import json from app.state import state index = Blueprint('index', __name__, template_folder='templates') @index.route('/', methods=['GET']) def show(): if request.method == 'GET': return render_template('index.html')
Remove old web ui backend
Remove old web ui backend
Python
mit
njbbaer/unicorn-remote,njbbaer/unicorn-remote,njbbaer/unicorn-remote
5fcc90741e443133695c65e04b26fc9d1313e530
djangae/models.py
djangae/models.py
from django.db import models from djangae import patches class CounterShard(models.Model): count = models.PositiveIntegerField() # Apply our django patches patches.patch()
from django.db import models from djangae import patches class CounterShard(models.Model): count = models.PositiveIntegerField() class Meta: app_label = "djangae" # Apply our django patches patches.patch()
Fix a warning in 1.8
Fix a warning in 1.8
Python
bsd-3-clause
wangjun/djangae,trik/djangae,martinogden/djangae,asendecka/djangae,grzes/djangae,leekchan/djangae,chargrizzle/djangae,grzes/djangae,martinogden/djangae,armirusco/djangae,potatolondon/djangae,SiPiggles/djangae,kirberich/djangae,potatolondon/djangae,armirusco/djangae,asendecka/djangae,leekchan/djangae,SiPiggles/djangae,c...
3d9b7fe808f2c8a64e0b834c0a67fa53631e5235
dbaas/api/integration_credential.py
dbaas/api/integration_credential.py
# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals from rest_framework import viewsets, serializers from integrations.credentials.models import IntegrationCredential from .environment import EnvironmentSerializer from .integration_type import IntegrationTypeSerializer class IntegrationCr...
# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals from rest_framework import viewsets, serializers from integrations.credentials.models import IntegrationCredential from .environment import EnvironmentSerializer from .integration_type import IntegrationTypeSerializer class IntegrationCr...
Add project to integration credential api fields
Add project to integration credential api fields
Python
bsd-3-clause
globocom/database-as-a-service,globocom/database-as-a-service,globocom/database-as-a-service,globocom/database-as-a-service
db78e585c9b2edfdf9ccb5025d429b2e25f641fd
jupyterhub_config.py
jupyterhub_config.py
import os import re c = get_config() c.JupyterHub.hub_ip = '0.0.0.0' c.DockerSpawner.use_docker_client_env = True c.DockerSpawner.tls_assert_hostname = True c.JupyterHub.spawner_class = 'dockerspawner.DockerSpawner' c.JupyterHub.authenticator_class = 'oauthenticator.GitHubOAuthenticator' c.JupyterHub.login_url = '...
import os import re c = get_config() c.JupyterHub.hub_ip = '0.0.0.0' c.JupyterHub.spawner_class = 'dockerspawner.DockerSpawner' c.DockerSpawner.tls_verify = True c.DockerSpawner.tls_ca = "/etc/docker/ca.pem" c.DockerSpawner.tls_cert = "/etc/docker/server-cert.pem" c.DockerSpawner.tls_key = "/etc/docker/server-key.pe...
Configure TLS for the DockerSpawner.
Configure TLS for the DockerSpawner.
Python
apache-2.0
smashwilson/jupyterhub-carina,smashwilson/jupyterhub-carina
3bf9853e83bf8d95844b58acac0d027b0ef5b863
fbanalysis.py
fbanalysis.py
import random import operator def get_sentiment(current_user, users, threads): friend_msg_count = {} for user in users.keys(): friend_msg_count[user] = 0 for thread in threads: for comment in thread: try: sender = comment['from']['id'] if sender n...
import random import operator def get_sentiment(current_user, users, threads): friend_msg_count = {} for user in users.keys(): friend_msg_count[user] = 0 for thread in threads: for comment in thread: try: sender = comment['from']['id'] if sender n...
Change romance to outlook, outlook to volume
Change romance to outlook, outlook to volume
Python
mit
tomshen/dearstalker,tomshen/dearstalker
ebd7a18402168ae7a27f771e1a27daffa88791d0
file_stats.py
file_stats.py
from heapq import heappush, heappushpop, heappop import os from pathlib import Path import sys from typing import List, Tuple N_LARGEST = 50 """Number of long file names to list.""" def main(): try: root = sys.argv[1] except IndexError: root = Path.home() / 'Dropbox (Springboard)' leng...
from heapq import heappush, heappushpop import os from pathlib import Path import sys from typing import List, Tuple N_LARGEST = 50 """Number of long file names to list.""" def main(): try: root = sys.argv[1] except IndexError: root = Path.home() / 'Dropbox (Springboard)' lengths: List...
Print stats highest to lowest
Print stats highest to lowest
Python
apache-2.0
blokeley/dfb,blokeley/backup_dropbox
82ab7f6e618367b5544fe71dea57f793ebb6b453
auth0/v2/client.py
auth0/v2/client.py
from .rest import RestClient class Client(object): """Docstring for Client. """ def __init__(self, domain, jwt_token): url = 'https://%s/api/v2/clients' % domain self.client = RestClient(endpoint=url, jwt=jwt_token) def all(self, fields=[], include_fields=True): params = {'fiel...
from .rest import RestClient class Client(object): """Docstring for Client. """ def __init__(self, domain, jwt_token): url = 'https://%s/api/v2/clients' % domain self.client = RestClient(endpoint=url, jwt=jwt_token) def all(self, fields=[], include_fields=True): """Retrieves a ...
Add docstring for Client.all() method
Add docstring for Client.all() method
Python
mit
auth0/auth0-python,auth0/auth0-python
c7af37a407a2cab7319f910830c6149addcde7d1
djangoautoconf/tastypie_utils.py
djangoautoconf/tastypie_utils.py
from tastypie.authorization import DjangoAuthorization from tastypie.resources import ModelResource from req_with_auth import DjangoUserAuthentication def create_tastypie_resource_class(class_inst): resource_class = type(class_inst.__name__ + "Resource", (ModelResource, ), { "Meta": type("Meta", (), { ...
from tastypie.authorization import DjangoAuthorization from tastypie.resources import ModelResource from req_with_auth import DjangoUserAuthentication import re def class_name_to_low_case(class_name): s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', class_name) return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower(...
Fix tastypie resource name issue.
Fix tastypie resource name issue.
Python
bsd-3-clause
weijia/djangoautoconf,weijia/djangoautoconf
20d63ba3fa1a9780d4a13c5119ae97a772efb502
teardown_tests.py
teardown_tests.py
#!/usr/bin/env python import os import shutil import sys if not os.environ.get("TEST_NOTEBOOKS"): sys.exit(0) for each in list(sys.argv[1:]) + [ "reg.h5", "reg_sub.h5", "reg_f_f0.h5", "reg_wt.h5", "reg_norm.h5", "reg_dict.h5", "reg_post.h5", "reg_traces.h5", "reg_rois.h5", ...
#!/usr/bin/env python import os import shutil import sys if not os.environ.get("TEST_NOTEBOOKS"): sys.exit(0) for each in list(sys.argv[1:]) + [ "reg.h5", "reg_sub.h5", "reg_f_f0.h5", "reg_wt.h5", "reg_norm.h5", "reg_dict.h5", "reg_post.h5", "reg_traces.h5", "reg_rois.h5", ...
Remove test Zarr files after completion.
Remove test Zarr files after completion.
Python
apache-2.0
nanshe-org/nanshe_workflow,DudLab/nanshe_workflow
b0105f42f13b81741b4be2b52e295b906aa0c144
service/__init__.py
service/__init__.py
import logging from logging import config from flask import Flask import dateutil import dateutil.parser import json from flask_login import LoginManager from config import CONFIG_DICT app = Flask(__name__) app.config.update(CONFIG_DICT) login_manager = LoginManager() login_manager.init_app(app) login_manager.login...
import logging from logging import config from flask import Flask import dateutil import dateutil.parser import json from flask_login import LoginManager from config import CONFIG_DICT app = Flask(__name__) app.config.update(CONFIG_DICT) login_manager = LoginManager() login_manager.init_app(app) login_manager.login...
Set cookie protection mode to strong
Set cookie protection mode to strong
Python
mit
LandRegistry/digital-register-frontend,LandRegistry/digital-register-frontend,LandRegistry/digital-register-frontend,LandRegistry/digital-register-frontend
58b5a991d91101b9149014def8e93fe70852ae32
measurement/views.py
measurement/views.py
from .models import Measurement from rest_framework import viewsets from graph.serializers import MeasurementGraphSeriesSerializer from rest_framework.exceptions import ParseError from api.permissions import IsPatient from rest_framework.permissions import IsAuthenticated from rest_framework.views import APIView from d...
from .models import Measurement from rest_framework import viewsets from graph.serializers import MeasurementGraphSeriesSerializer from rest_framework.exceptions import ParseError from api.permissions import IsPatient from rest_framework.permissions import IsAuthenticated from rest_framework.views import APIView from d...
Update measurements endpoint of current patient
Update measurements endpoint of current patient
Python
mit
sigurdsa/angelika-api
68086a879b13040d62a8958bcb4839d6661f9d0c
knowledge_repo/app/auth_providers/ldap.py
knowledge_repo/app/auth_providers/ldap.py
from flask import request, render_template, redirect, url_for from ldap3 import Server, Connection, ALL from ldap3.core.exceptions import LDAPSocketOpenError from ..models import User from ..auth_provider import KnowledgeAuthProvider class LdapAuthProvider(KnowledgeAuthProvider): _registry_keys = ['ldap'] d...
from ..auth_provider import KnowledgeAuthProvider from ..models import User from flask import ( redirect, render_template, request, url_for, ) from ldap3 import Server, Connection, ALL class LdapAuthProvider(KnowledgeAuthProvider): _registry_keys = ['ldap'] def init(self): if not sel...
Sort import statements in another file
Sort import statements in another file
Python
apache-2.0
airbnb/knowledge-repo,airbnb/knowledge-repo,airbnb/knowledge-repo,airbnb/knowledge-repo,airbnb/knowledge-repo
1c6b06f240d4388b3e140e3d9ab610711616f539
src/python/expedient/clearinghouse/resources/models.py
src/python/expedient/clearinghouse/resources/models.py
''' @author: jnaous ''' from django.db import models from expedient.clearinghouse.aggregate.models import Aggregate from expedient.common.extendable.models import Extendable from expedient.clearinghouse.slice.models import Slice class Resource(Extendable): ''' Generic model of a resource. @param aggre...
''' @author: jnaous ''' from django.db import models from expedient.clearinghouse.aggregate.models import Aggregate from expedient.common.extendable.models import Extendable from expedient.clearinghouse.slice.models import Slice from datetime import datetime class Resource(Extendable): ''' Generic model of a r...
Add functions to manage status change timestamp better
Add functions to manage status change timestamp better
Python
bsd-3-clause
avlach/univbris-ocf,avlach/univbris-ocf,avlach/univbris-ocf,avlach/univbris-ocf
570264014456ea0405af28feb92af7639fb7b7e3
metaopt/invoker/util/determine_package.py
metaopt/invoker/util/determine_package.py
""" Utility that detects the package of a given object. """ from __future__ import division, print_function, with_statement import inspect import os def determine_package(some_object): """ Resolves a call by object to a call by package. - Determine absolute package name of the given object. - When th...
""" Utility that detects the package of a given object. """ from __future__ import division, print_function, with_statement import inspect import os def determine_package(some_object): """ Resolves a call by object to a call by package. - Determine absolute package name of the given object. - When th...
Fix a bug (?) in detmine_package
Fix a bug (?) in detmine_package Canditates have their first character removed if it is ".".
Python
bsd-3-clause
cigroup-ol/metaopt,cigroup-ol/metaopt,cigroup-ol/metaopt