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
01e2b7aeaefa54f5a45886ee19607906f7d9064f
app/views/post_view.py
app/views/post_view.py
from flask import render_template, redirect, url_for from flask_classy import FlaskView, route from ..models import PostModel from ..forms import PostForm class Post(FlaskView): """ Here will handle post creations, delete and update.""" def get(self, entity_id): post = PostModel() post = post...
from flask import render_template, redirect, url_for from flask_classy import FlaskView, route from flask_user import login_required from ..models import PostModel from ..forms import PostForm class Post(FlaskView): """ Here will handle post creations, delete and update.""" def get(self, entity_id): ...
Add login required to new and edit post views
Add login required to new and edit post views
Python
mit
oldani/nanodegree-blog,oldani/nanodegree-blog,oldani/nanodegree-blog
50be7fe6acf0c79af0263b4f1bd60629ecbde832
froide/routing.py
froide/routing.py
from django.urls import path from channels.routing import ProtocolTypeRouter, URLRouter from channels.auth import AuthMiddlewareStack from channels.security.websocket import AllowedHostsOriginValidator from froide.problem.consumers import ModerationConsumer websocket_urls = [ path('moderation/', ModerationConsu...
from django.urls import path from channels.routing import ProtocolTypeRouter, URLRouter from channels.auth import AuthMiddlewareStack from channels.security.websocket import AllowedHostsOriginValidator from froide.problem.consumers import ModerationConsumer websocket_urls = [ path('moderation/', ModerationConsu...
Fix ws consumers for channels 3.x
Fix ws consumers for channels 3.x
Python
mit
fin/froide,fin/froide,fin/froide,fin/froide
c559c639f7c3deea4e166dd2f6fee1cb8a1297b7
tests/integration/test_metrics.py
tests/integration/test_metrics.py
from kaneda import Metrics class TestMetrics(object): def test_elasticsearch_gauge(self, elasticsearch_backend): value = 42 metrics = Metrics(backend=elasticsearch_backend) metrics.gauge('test_gauge', value) result = elasticsearch_backend.client.search(index=elasticsearch_backend....
from kaneda import Metrics class TestMetrics(object): def test_elasticsearch_metric(self, elasticsearch_backend): metrics = Metrics(backend=elasticsearch_backend) result = metrics.gauge('test_gauge', 42) assert result assert result['_id'] def test_mongo_metric(self, mongo_bac...
Change integration test of metrics
Change integration test of metrics
Python
mit
APSL/kaneda
1ae2cc1c9b36c323f05c210812e383eb09bb6c7f
src/model/predict_rf_model.py
src/model/predict_rf_model.py
import numpy as np import pandas as pd import sys import os from sklearn.externals import joblib from sklearn.ensemble import RandomForestClassifier scriptpath = os.path.dirname(os.path.realpath(sys.argv[0])) + '/../' sys.path.append(os.path.abspath(scriptpath)) import utils parameter_str = '_'.join(['top', str(utils...
import numpy as np import pandas as pd import sys import os from sklearn.externals import joblib from sklearn.ensemble import RandomForestClassifier scriptpath = os.path.dirname(os.path.realpath(sys.argv[0])) + '/../' sys.path.append(os.path.abspath(scriptpath)) import utils parameter_str = '_'.join(['top', str(utils...
Update to use all the test
Update to use all the test
Python
bsd-3-clause
parkerzf/kaggle-expedia,parkerzf/kaggle-expedia,parkerzf/kaggle-expedia
d732eb43013eedd700ebb00630a26ae97ecdd0b9
onetime/views.py
onetime/views.py
from datetime import datetime from django.http import HttpResponse, HttpResponseRedirect, HttpResponseGone from django.contrib import auth from django.conf import settings from onetime import utils from onetime.models import Key def cleanup(request): utils.cleanup() return HttpResponse('ok', content_type='te...
from datetime import datetime from django.http import HttpResponse, HttpResponseRedirect, HttpResponseGone from django.contrib import auth from django.conf import settings from onetime import utils from onetime.models import Key def cleanup(request): utils.cleanup() return HttpResponse('ok', content_type='te...
Remove a don't-know-why-it's-still-there parameter: login_url
Remove a don't-know-why-it's-still-there parameter: login_url
Python
agpl-3.0
ISIFoundation/influenzanet-website,ISIFoundation/influenzanet-website,ISIFoundation/influenzanet-website,uploadcare/django-loginurl,ISIFoundation/influenzanet-website,ISIFoundation/influenzanet-website,ISIFoundation/influenzanet-website,fajran/django-loginurl,ISIFoundation/influenzanet-website,vanschelven/cmsplugin-jou...
ff138858fdc76527ee9f05f7573ddb00cd7eed21
conftest.py
conftest.py
import pytest def pytest_collection_modifyitems(config, items): try: import pandas except ImportError: pandas = None try: import cesium except ImportError: cesium = None if pandas is None: skip_marker = pytest.mark.skip(reason="pandas not installed!") ...
import pytest def pytest_collection_modifyitems(config, items): try: import pandas except ImportError: pandas = None try: import cesium except ImportError: cesium = None if pandas is None: skip_marker = pytest.mark.skip(reason="pandas not installed!") ...
Add all versions of conversion doctests
Add all versions of conversion doctests
Python
bsd-2-clause
rtavenar/tslearn
c803473c4bc552b9d82a4bbb0948e071a36821fd
web_scraper/core/html_fetchers.py
web_scraper/core/html_fetchers.py
import os import sys sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) import requests def fetch_html_document(url, user_agent='python_requests.cli-ws'): """Request html document from url Positional Arguments: url (str): a web address (http://example.com/) Keyword A...
import os import sys sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) import requests def fetch_html_document(url, user_agent='cli-ws/1.0'): """Request html document from url Positional Arguments: url (str): a web address (http://example.com/) Keyword Arguments: ...
Change default user_agent to match mozilla standard
Change default user_agent to match mozilla standard
Python
mit
Samuel-L/cli-ws,Samuel-L/cli-ws
ccd660c5deba37c0c324e64666eb6421696b3144
puffin/gui/form.py
puffin/gui/form.py
from flask_wtf import Form from wtforms import StringField, IntegerField, PasswordField, SubmitField, SelectField from wtforms.validators import Required, Length, Regexp from ..core.db import db from ..core.security import User from .. import app class ApplicationForm(Form): start = SubmitField('Start') stop =...
from flask_wtf import Form from wtforms import StringField, IntegerField, PasswordField, SubmitField, SelectField from wtforms.validators import Required, Length, Regexp from ..core.db import db from ..core.security import User from .. import app class ApplicationForm(Form): start = SubmitField('Start') stop =...
Allow changing to own domain name
Allow changing to own domain name
Python
agpl-3.0
loomchild/jenca-puffin,puffinrocks/puffin,loomchild/puffin,loomchild/puffin,loomchild/puffin,loomchild/puffin,puffinrocks/puffin,loomchild/jenca-puffin,loomchild/puffin
403f23ae486c14066e0a93c7deca91c5fbc15b87
plugins/brian.py
plugins/brian.py
"""Displays a randomly generated witticism from Brian Chu himself.""" import json import random __match__ = r"!brian" with open('plugins/brian_corpus/cache.json', 'r') as infile: cache = json.load(infile) with open('plugins/brian_corpus/phrases.json', 'r') as infile: phrases = json.load(infile) def gener...
"""Displays a randomly generated witticism from Brian Chu himself.""" import json import random __match__ = r"!brian" attribution = [ "salad master", "esquire", "the one and only", "startup enthusiast", "boba king", "not-dictator", "normal citizen", "ping-pong expert" ] with ...
Use bigrams in Markov chain generator
Use bigrams in Markov chain generator
Python
mit
kvchen/keffbot,kvchen/keffbot-py
791954f7a877aab75d615b4b00e5b40a849671f4
sheldon/bot.py
sheldon/bot.py
# -*- coding: utf-8 -*- """ @author: Seva Zhidkov @contact: zhidkovseva@gmail.com @license: The MIT license Copyright (C) 2015 """ from sheldon.exceptions import * from sheldon.manager import * from sheldon.config import * from sheldon.adapter import * from sheldon.storage import * class Sheldon: """ Main ...
# -*- coding: utf-8 -*- """ @author: Seva Zhidkov @contact: zhidkovseva@gmail.com @license: The MIT license Copyright (C) 2015 """ from sheldon.adapter import * from sheldon.config import * from sheldon.exceptions import * from sheldon.manager import * from sheldon.storage import * class Sheldon: """ Main ...
Move imports in alphabet order
Move imports in alphabet order
Python
mit
lises/sheldon
b3c01b61fd510aacd13d89c6ca1097746dfd99d5
pytips/__init__.py
pytips/__init__.py
#! /usr/bin/env python # -*- coding: utf-8 -*- """Primary setup for PyTips.""" from __future__ import print_function from __future__ import unicode_literals from __future__ import absolute_import from __future__ import division import os from flask import Flask from flask_heroku import Heroku from flask.ext.sqlalch...
#! /usr/bin/env python # -*- coding: utf-8 -*- """Primary setup for PyTips.""" from __future__ import print_function from __future__ import unicode_literals from __future__ import absolute_import from __future__ import division from flask import Flask from flask_heroku import Heroku from flask.ext.sqlalchemy import S...
Undo my 'work-around' for flask-heroku.
Undo my 'work-around' for flask-heroku.
Python
isc
gthank/pytips,gthank/pytips,gthank/pytips,gthank/pytips
dc18e64cd4ecaf624f62438a307cebe14bfbbad8
slack/views.py
slack/views.py
from flask import Flask, request import requests from urllib import urlencode app = Flask(__name__) @app.route("/", methods=['POST']) def meme(): form = request.form.to_dict() slackbot = form["slackbot"] text = form["text"] channel = form["channel_name"] text = text[:-1] if text[-1] == ";" else ...
from flask import Flask, request import requests from urllib import urlencode app = Flask(__name__) @app.route("/") def meme(): slackbot = request.args["slackbot"] text = request.args["text"] channel = request.args["channel_name"] text = text[:-1] if text[-1] == ";" else text params = text.split(...
Use a GET request instead
Use a GET request instead
Python
mit
joeynebula/slack-meme,tezzutezzu/slack-meme,DuaneGarber/slack-meme,nicolewhite/slack-meme
acaefa673edbbaa89dd51444a90e5c61bd952cc3
Demo/scripts/mpzpi.py
Demo/scripts/mpzpi.py
#! /usr/bin/env python # Print digits of pi forever. # # The algorithm, using Python's 'long' integers ("bignums"), works # with continued fractions, and was conceived by Lambert Meertens. # # See also the ABC Programmer's Handbook, by Geurts, Meertens & Pemberton, # published by Prentice-Hall (UK) Ltd., 1990. import ...
#! /usr/bin/env python # Print digits of pi forever. # # The algorithm, using Python's 'long' integers ("bignums"), works # with continued fractions, and was conceived by Lambert Meertens. # # See also the ABC Programmer's Handbook, by Geurts, Meertens & Pemberton, # published by Prentice-Hall (UK) Ltd., 1990. import ...
Revert previous change which didn't make sense the next day :-)
Revert previous change which didn't make sense the next day :-)
Python
mit
sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator
e24674011454ce60bf1c4582af25262ae277771c
spreadchimp.py
spreadchimp.py
import os import xlrd import xlwt # Assumes the directory with the workbook is relative to the script's location. directory = 'workbooks/' workbook = '' for dirpath, dirnames, filenames in os.walk(directory): for files in filenames: workbook = (dirpath + files) ''' Test films include: Repulsion The Cryin...
import os import xlrd import xlwt # Assumes the directory with the workbook is relative to the script's location. directory = 'workbooks/' workbook = '' for dirpath, dirnames, filenames in os.walk(directory): for files in filenames: workbook = (dirpath + files) ''' Test films include: Repulsion The Cryin...
Add header row to worksheet in workbooks
Add header row to worksheet in workbooks
Python
mit
deadlyraptor/reels
0f1a3d06b316590c029e4e6c0e474f716e047033
pokebattle/game_entrypoint.py
pokebattle/game_entrypoint.py
from nameko.web.handlers import http from pokebattle.scores import ScoreService class GameService(object): score_service = RpcProxy('score_service') @http('POST', '/signup') def signup(self): pass @http('POST', '/login') def login(self): pass @http('POST', '/battle') d...
import json from nameko.web.handlers import http from nameko.rpc import RpcProxy from pokebattle.scores import ScoreService class GameService(object): name = 'game_service' score_rpc = RpcProxy('score_service') @http('POST', '/signup') def signup(self, request): pass @http('POST', '/lo...
Add leaderbord rpc call and add request arg to all methods
Add leaderbord rpc call and add request arg to all methods
Python
mit
skooda/poke-battle,radekj/poke-battle
f27d2078a67a1a2ba0da0c000a68d8b0d212bf08
polyaxon/experiments/utils.py
polyaxon/experiments/utils.py
# -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function import os from django.conf import settings from libs.paths import delete_path, create_path def get_experiment_outputs_path(experiment_name): values = experiment_name.split('.') if len(values) == 3: values.inser...
# -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function import os from django.conf import settings from libs.paths import delete_path, create_path def get_experiment_outputs_path(experiment_name): values = experiment_name.split('.') if len(values) == 3: values.inser...
Update experiment logs path creation
Update experiment logs path creation
Python
apache-2.0
polyaxon/polyaxon,polyaxon/polyaxon,polyaxon/polyaxon
6370b362c77ae9c5f9aa64e11eae3941438b5359
openmc/deplete/__init__.py
openmc/deplete/__init__.py
""" openmc.deplete ============== A depletion front-end tool. """ from .dummy_comm import DummyCommunicator try: from mpi4py import MPI comm = MPI.COMM_WORLD have_mpi = True except ImportError: comm = DummyCommunicator() have_mpi = False from .nuclide import * from .chain import * from .operator ...
""" openmc.deplete ============== A depletion front-end tool. """ from .dummy_comm import DummyCommunicator try: from mpi4py import MPI comm = MPI.COMM_WORLD have_mpi = True # check if running with MPI and if hdf5 is MPI-enabled from h5py import get_config if not get_config().mpi and comm.s...
Check that hdf5 has MPI if performing depletion with MPI
Check that hdf5 has MPI if performing depletion with MPI Check added in openmc/depletion/__init__.py. Without this check, the exporting of the Results to hdf5 will hang, as the second process attempts to write to a file that has already been opened on another process. This error is only raised after a full transport c...
Python
mit
shikhar413/openmc,shikhar413/openmc,liangjg/openmc,amandalund/openmc,mit-crpg/openmc,mit-crpg/openmc,amandalund/openmc,walshjon/openmc,smharper/openmc,paulromano/openmc,paulromano/openmc,paulromano/openmc,walshjon/openmc,paulromano/openmc,walshjon/openmc,liangjg/openmc,walshjon/openmc,amandalund/openmc,smharper/openmc,...
09b69d7e650055f75562f740d552434d2dfa2d6d
tapiriik/services/service.py
tapiriik/services/service.py
from tapiriik.services import * from tapiriik.database import db class Service: def FromID(id): if id=="runkeeper": return RunKeeper elif id=="strava": return Strava raise ValueError def List(): return [RunKeeper, Strava] def WebInit(): glob...
from tapiriik.services import * from tapiriik.database import db class Service: def FromID(id): if id=="runkeeper": return RunKeeper elif id=="strava": return Strava raise ValueError def List(): return [RunKeeper, Strava] def WebInit(): glob...
Update auth details on reauthorization
Update auth details on reauthorization
Python
apache-2.0
marxin/tapiriik,campbellr/tapiriik,brunoflores/tapiriik,mduggan/tapiriik,abhijit86k/tapiriik,cpfair/tapiriik,gavioto/tapiriik,cmgrote/tapiriik,gavioto/tapiriik,gavioto/tapiriik,mjnbike/tapiriik,abhijit86k/tapiriik,dmschreiber/tapiriik,marxin/tapiriik,campbellr/tapiriik,mduggan/tapiriik,abs0/tapiriik,cmgrote/tapiriik,dm...
8c5edbf6d928ab937128b783782726c06592cc9f
rosetta/signals.py
rosetta/signals.py
from django import dispatch entry_changed = dispatch.Signal() post_save = dispatch.Signal()
from django import dispatch # providing_args=["user", "old_msgstr", "old_fuzzy", "pofile", "language_code"] entry_changed = dispatch.Signal() # providing_args=["language_code", "request"] post_save = dispatch.Signal()
Add providing_args as a comment
Add providing_args as a comment
Python
mit
mbi/django-rosetta,mbi/django-rosetta,mbi/django-rosetta,mbi/django-rosetta
8a81bef46b248f84ce43244ca82415cf0c7ffb6c
tests/databases/rgd/parser_test.py
tests/databases/rgd/parser_test.py
# -*- coding: utf-8 -*- """ Copyright [2009-2017] EMBL-European Bioinformatics Institute 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...
# -*- coding: utf-8 -*- """ Copyright [2009-2017] EMBL-European Bioinformatics Institute 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...
Mark another RGD test as failing
Mark another RGD test as failing RGD parsing is degrading more it seems.
Python
apache-2.0
RNAcentral/rnacentral-import-pipeline,RNAcentral/rnacentral-import-pipeline,RNAcentral/rnacentral-import-pipeline,RNAcentral/rnacentral-import-pipeline
ab7a546e4a7fb686f61b904777aa26c7d596ff03
pombola/south_africa/lib.py
pombola/south_africa/lib.py
import urlparse def make_pa_url(pombola_object, base_url): parsed_url = list(urlparse.urlparse(base_url)) parsed_url[2] = pombola_object.get_absolute_url() return urlparse.urlunparse(parsed_url) def add_extra_popolo_data_for_person(person, popolo_object, base_url): popolo_object['pa_url'] = make_pa_ur...
import urlparse def make_pa_url(pombola_object, base_url): parsed_url = list(urlparse.urlparse(base_url)) parsed_url[2] = pombola_object.get_absolute_url() return urlparse.urlunparse(parsed_url) def add_extra_popolo_data_for_person(person, popolo_object, base_url): popolo_object['pa_url'] = make_pa_ur...
Add members interests data to PopIt export
ZA: Add members interests data to PopIt export (Minor refactoring by Mark Longair.)
Python
agpl-3.0
hzj123/56th,mysociety/pombola,geoffkilpin/pombola,geoffkilpin/pombola,hzj123/56th,geoffkilpin/pombola,patricmutwiri/pombola,patricmutwiri/pombola,mysociety/pombola,ken-muturi/pombola,patricmutwiri/pombola,geoffkilpin/pombola,mysociety/pombola,patricmutwiri/pombola,ken-muturi/pombola,ken-muturi/pombola,patricmutwiri/pom...
156b7363ff51532cddbb8ce1c7a5e6b8a3c7cc0a
accounts/tests/test_views.py
accounts/tests/test_views.py
"""accounts app unittests for views """ from django.test import TestCase class WelcomePageTest(TestCase): """Tests relating to the welcome_page view. """ def test_uses_welcome_template(self): """The root url should response with the welcome page template. """ response = self.cli...
"""accounts app unittests for views """ from django.test import TestCase from django.urls import reverse class WelcomePageTest(TestCase): """Tests relating to the welcome_page view. """ def test_uses_welcome_template(self): """The root url should respond with the welcome page template. ...
Add test for send login email view
Add test for send login email view
Python
mit
randomic/aniauth-tdd,randomic/aniauth-tdd
cc6e1f096a63c9f52dbee6779c143b6df1f11c05
setup.py
setup.py
from distutils.core import setup setup( name="armstrong.templates.standard", version="1.0.0", description="Provides a basic project template for an Armstrong project", long_description=open("README.rst").read(), author='Texas Tribune & Bay Citizen', author_email='dev@armstrongcms.org', pack...
from distutils.core import setup import os package_data = [] BASE_DIR = os.path.dirname(__file__) walk_generator = os.walk(os.path.join(BASE_DIR, "project_template")) paths_and_files = [(paths, files) for paths, dirs, files in walk_generator] for path, files in paths_and_files: prefix = path[len("project_template/...
Add missing package_data to file (v1.0.1)
Add missing package_data to file (v1.0.1)
Python
apache-2.0
armstrong/armstrong.templates.standard,armstrong/armstrong.templates.standard
8513d765a071c6f7d8c3bc20ba73e0f8b0744252
setup.py
setup.py
#!/usr/bin/python2 ''' The setup script for salt ''' from distutils.core import setup setup(name='salt', version='0.1', description='Portable, distrubuted, remote execution system', author='Thomas S Hatch', author_email='thatch45@gmail.com', url='https://github.com/thatch45/salt', ...
#!/usr/bin/python2 ''' The setup script for salt ''' from distutils.core import setup setup(name='salt', version='0.1', description='Portable, distrubuted, remote execution system', author='Thomas S Hatch', author_email='thatch45@gmail.com', url='https://github.com/thatch45/salt', ...
Add the salt.modules module to the package
Add the salt.modules module to the package
Python
apache-2.0
saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt
e0f4135b90a3f920db3a14b14b70e0e57df3d717
setup.py
setup.py
## # Copyright (c) 2006-2007 Apple Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable l...
## # Copyright (c) 2006-2007 Apple Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable l...
Build for either python 2 or python 3
Build for either python 2 or python 3
Python
apache-2.0
admiyo/PyKerberos,admiyo/PyKerberos,admiyo/PyKerberos
5dcec96b7af384f7f753cb2d67d7cbd0c361c504
tests/helpers.py
tests/helpers.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals import json from elasticsearch import ( Elasticsearch, TransportError ) ELASTICSEARCH_URL = "localhost" conn = Elasticsearch(ELASTICSEARCH_URL) def homogeneous(a, b): json.dumps(a).should.equal(json.dumps(b)) def heterogeneous(a,...
# -*- coding: utf-8 -*- from __future__ import unicode_literals import json from elasticsearch import ( Elasticsearch, TransportError ) ELASTICSEARCH_URL = "localhost" conn = Elasticsearch(ELASTICSEARCH_URL) def homogeneous(a, b): json.dumps(a).should.equal(json.dumps(b)) def heterogeneous(a,...
Allow overriding doc type defaults
Allow overriding doc type defaults
Python
mit
Yipit/pyeqs
a10fb75a45bbb647f8071842773d79101c797529
corehq/project_limits/models.py
corehq/project_limits/models.py
from django.db import models class DynamicRateDefinition(models.Model): key = models.CharField(max_length=512, blank=False, null=False, unique=True, db_index=True) per_week = models.FloatField(default=None, blank=True, null=True) per_day = models.FloatField(default=None, blank=True, null=True) per_hou...
from django.db import models class DynamicRateDefinition(models.Model): key = models.CharField(max_length=512, blank=False, null=False, unique=True, db_index=True) per_week = models.FloatField(default=None, blank=True, null=True) per_day = models.FloatField(default=None, blank=True, null=True) per_hou...
Clear caches on DynamicRateDefinition deletion for completeness
Clear caches on DynamicRateDefinition deletion for completeness and to help with tests
Python
bsd-3-clause
dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq
2a77f5e9a2bcce6b11c21f40574f73cad133c4b8
slack.py
slack.py
import json from slackipycore import invite, get_team_info from slackipycore import (AlreadyInTeam, InvalidInviteeEmail, InvalidAuthToken, AlreadyInvited, APIRequestError) from flask import current_app def invite_user(email): api_token = current_app.config['SLACK_API_TOKEN'] team_id ...
import json from slackipycore import invite, get_team_info from slackipycore import (AlreadyInTeam, InvalidInviteeEmail, InvalidAuthToken, AlreadyInvited, APIRequestError) from flask import current_app def invite_user(email): api_token = current_app.config['SLACK_API_TOKEN'] team_id ...
Fix return statement for `invite`
Fix return statement for `invite`
Python
mit
avinassh/slackipy,avinassh/slackipy,avinassh/slackipy
603f2204327c5cac8dbae0a567676465e1ab0f70
data/settings.py
data/settings.py
import os PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(PROJECT_ROOT, 'operations.db'), } } INSTALLED_APPS = ( 'data', ) SECRET_KEY = '63cFWu$$lhT3bVP9U1k1Iv@Jo02SuM' LOG...
import os PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(PROJECT_ROOT, 'operations.db'), } } INSTALLED_APPS = ( 'data', ) SECRET_KEY = '63cFWu$$lhT3bVP9U1k1Iv@Jo02SuM' LOG...
Set MIDDLEWARE_CLASSES to empty list
Set MIDDLEWARE_CLASSES to empty list
Python
bsd-3-clause
giantas/sorter,giantas/sorter
f04b85d6536cdfcf3d51e237bde7c2e63a5c2946
server/server.py
server/server.py
import SimpleHTTPServer import SocketServer class KcaaHTTPRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler): def do_HEAD(self): # Note: HTTP request handlers are not new-style classes. # super() cannot be used. SimpleHTTPServer.SimpleHTTPRequestHandler.do_HEAD(self) def do_GE...
import SimpleHTTPServer import SocketServer class KcaaHTTPRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler): CLIENT_PREFIX = '/client/' def do_HEAD(self): # Note: HTTP request handlers are not new-style classes. # super() cannot be used. if self.rewrite_to_client_path(): ...
Handle only /client requests to file serving.
Handle only /client requests to file serving.
Python
apache-2.0
kcaa/kcaa,kcaa/kcaa,kcaa/kcaa,kcaa/kcaa
3735c090702cc8c290dbf8930223ff794c80775a
versionsapp.py
versionsapp.py
from webob import Response from apiversion import APIVersion from application import Application from apiv1app import APIv1App class VersionsApp(Application): version_classes = [ APIv1App ] def APIVersionList(self, args): return Response(content_type = 'application/json', body = self._resultset_to_json([ { ...
from webob import Response import webob.exc from apiversion import APIVersion from application import Application from apiv1app import APIv1App class VersionsApp(Application): version_classes = [ APIv1App ] def _api_version_detail(self, version): return { "id": version._version_identifier(), "links": [ ...
Correct the HTTP status from GET / - it should be 300 (Multiple Choices) not 200. Implement the details of a given version.
Correct the HTTP status from GET / - it should be 300 (Multiple Choices) not 200. Implement the details of a given version.
Python
apache-2.0
NeCTAR-RC/reporting-api,NCI-Cloud/reporting-api,NeCTAR-RC/reporting-api,NCI-Cloud/reporting-api
b836b2c39299cc6dbcbdbc8bcffe046f25909edc
test_portend.py
test_portend.py
import socket import pytest import portend def socket_infos(): """ Generate addr infos for connections to localhost """ host = '' port = portend.find_available_local_port() return socket.getaddrinfo(host, port, socket.AF_UNSPEC, socket.SOCK_STREAM) def id_for_info(info): af, = info[:1] return str(af) def...
import socket import pytest import portend def socket_infos(): """ Generate addr infos for connections to localhost """ host = '' port = portend.find_available_local_port() return socket.getaddrinfo(host, port, socket.AF_UNSPEC, socket.SOCK_STREAM) def id_for_info(info): af, = info[:1] return str(af) def...
Add tests for nonlistening addresses as well.
Add tests for nonlistening addresses as well.
Python
mit
jaraco/portend
21651120925cc3e51aeada4eac4dbfaa5bf98fae
src/header_filter/__init__.py
src/header_filter/__init__.py
from header_filter.matchers import Header # noqa: F401 from header_filter.middleware import HeaderFilterMiddleware # noqa: F401 from header_filter.rules import Enforce, Forbid # noqa: F401
from header_filter.matchers import Header, HeaderRegexp # noqa: F401 from header_filter.middleware import HeaderFilterMiddleware # noqa: F401 from header_filter.rules import Enforce, Forbid # noqa: F401
Allow HeaderRegexp to be imported directly from header_filter package.
Allow HeaderRegexp to be imported directly from header_filter package.
Python
mit
sanjioh/django-header-filter
5ebc53fccd79e479d1a39cf02160c8eb2eab247a
vulk/__init__.py
vulk/__init__.py
"""Vulk 3D engine Cross-plateform 3D engine """ __version__ = "0.2.0"
"""Vulk 3D engine Cross-plateform 3D engine """ from os import path as p __version__ = "0.2.0" PATH_VULK = p.dirname(p.abspath(__file__)) PATH_VULK_ASSET = p.join(PATH_VULK, 'asset') PATH_VULK_SHADER = p.join(PATH_VULK_ASSET, 'shader')
Add Path to Vulk package
Add Path to Vulk package
Python
apache-2.0
Echelon9/vulk,realitix/vulk,realitix/vulk,Echelon9/vulk
c3b1fef64b3a383b017ec2e155cbdc5b58a6bf5c
average_pixels/get_images.py
average_pixels/get_images.py
import os import urllib import requests from api_key import API_KEY from IPython import embed as qq URL = "https://bingapis.azure-api.net/api/v5/images/search" NUMBER_OF_IMAGES = 10 DIR = os.path.realpath('img') def search_images(term): params = {"q": term, "count":NUMBER_OF_IMAGES} headers = {'ocp-apim-sub...
import os import urllib import urllib.error import requests URL = "https://bingapis.azure-api.net/api/v5/images/search" NUMBER_OF_IMAGES = 10 DIR = '/tmp/average_images' def search_images(term, api_key): params = {"q": term, "count":NUMBER_OF_IMAGES} headers = {'ocp-apim-subscription-key': api_key} respo...
Store files in /tmp/ and fetch API key from $HOME
Store files in /tmp/ and fetch API key from $HOME
Python
mit
liviu-/average-pixels
5aefffff8a1004bc9a8289bf5907472e3434e6b3
modelreg/registration_view.py
modelreg/registration_view.py
#!/usr/bin/env python3 """Documentation about the module... may be multi-line""" from registration.backends.hmac.views import RegistrationView as BaseRegistrationView from django.contrib.sites.shortcuts import get_current_site class RegistrationView(BaseRegistrationView): def get_email_context(self, activation_k...
#!/usr/bin/env python3 """Documentation about the module... may be multi-line""" from registration.backends.hmac.views import RegistrationView as BaseRegistrationView from django.contrib.sites.shortcuts import get_current_site class RegistrationView(BaseRegistrationView): def get_email_context(self, activation_k...
Remove debugging code, not needed outside of DEV
Remove debugging code, not needed outside of DEV
Python
agpl-3.0
modelreg/modelreg,modelreg/modelreg,modelreg/modelreg
5d97b41a7b814b078b0b7b7d930317342d0db3de
yaml_writer.py
yaml_writer.py
import os.path import yaml from sphinx.util.osutil import ensuredir def create_directory(app): ''' Creates the yaml directory if necessary ''' app.env.yaml_dir = os.path.join(app.builder.confdir, '_build', 'yaml') ensuredir(app.env.yaml_dir) def file_path(env, name): ''' Creates complete yaml file p...
import io import os.path import yaml from sphinx.util.osutil import ensuredir def create_directory(app): ''' Creates the yaml directory if necessary ''' app.env.yaml_dir = os.path.join(app.builder.confdir, '_build', 'yaml') ensuredir(app.env.yaml_dir) def file_path(env, name): ''' Creates complete y...
Support python 2 with io.open
Support python 2 with io.open
Python
mit
Aalto-LeTech/a-plus-rst-tools,Aalto-LeTech/a-plus-rst-tools,Aalto-LeTech/a-plus-rst-tools
a2fe7d1bb38bedee808c6b1a21cd5e3d93863c6c
winthrop/urls.py
winthrop/urls.py
"""winthrop URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.10/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-b...
"""winthrop URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.10/topics/http/urls/ """ from django.conf.urls import url from django.contrib import admin from django.views.generic.base import RedirectView urlpatterns = [ # for no...
Add redirect from site base url to admin index for now
Add redirect from site base url to admin index for now
Python
apache-2.0
Princeton-CDH/winthrop-django,Princeton-CDH/winthrop-django,Princeton-CDH/winthrop-django
303bd2c3cd605581bd46410b3680f2ec5d193429
peripydic/util/functions.py
peripydic/util/functions.py
import numpy as np from ..util import linalgebra def w(problem,X,type): if type == "ONE": return 1. if type == "EXP": len = linalgebra.norm(X) return np.exp(- (len*len) / problem.neighbors.horizon) return 1.
import numpy as np from ..util import linalgebra def w(problem,X,type): if type == "ONE": return 1. if type == "EXP": len = linalgebra.norm(X) return np.exp(- (len*len) / problem.neighbors.horizon / problem.neighbors.horizon) if type == "NORM": return 1. / linalgebra.n...
Add NORM as influence function
Add NORM as influence function
Python
mit
ilyasst/peridynamics_1D,lm2-poly/peridynamics_1D,lm2-poly/peridynamics_1D
5e62db3e6abd19c99fb565c15cdd1527599dbd9d
tools/gyp_dart.py
tools/gyp_dart.py
#!/usr/bin/env python # Copyright (c) 2012 The Dart Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # This script is wrapper for Dart that adds some support for how GYP # is invoked by Dart beyond what can be done in the gclient hooks...
#!/usr/bin/env python # Copyright (c) 2012 The Dart Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Invoke gyp to generate build files for building the Dart VM. """ import os import subprocess import sys def execute(args): pro...
Make code follow the Python style guidelines
Make code follow the Python style guidelines + Use a doc string for the whole file. + Lower case function names. + Consistently use single-quotes for quoted strings. + align wrapped elements with opening delimiter. + use a main() function Review URL: https://chromiumcodereview.appspot.com//10837127 git-svn-id: c9...
Python
bsd-3-clause
dart-archive/dart-sdk,dartino/dart-sdk,dartino/dart-sdk,dartino/dart-sdk,dartino/dart-sdk,dart-archive/dart-sdk,dart-archive/dart-sdk,dartino/dart-sdk,dart-lang/sdk,dart-lang/sdk,dartino/dart-sdk,dart-archive/dart-sdk,dart-archive/dart-sdk,dart-archive/dart-sdk,dart-archive/dart-sdk,dartino/dart-sdk,dart-archive/dart-s...
1360df4f50417b472c51b679d64102f3b3d5ebec
property_transformation.py
property_transformation.py
from types import UnicodeType, StringType class PropertyMappingFailedException(Exception): pass def get_transformed_properties(source_properties, prop_map): results = {} for key, value in prop_map.iteritems(): if type(value) in (StringType, UnicodeType): if value in source_properties: ...
from types import UnicodeType, StringType class PropertyMappingFailedException(Exception): pass def get_transformed_properties(source_properties, prop_map): results = {} for key, value in prop_map.iteritems(): if type(value) in (StringType, UnicodeType): if value in source_properties: ...
Raise exception if unable to find a usable key in property mapping dict
Raise exception if unable to find a usable key in property mapping dict
Python
mit
OpenBounds/Processing
200efbba25130b84da80720329794e4c47806573
NDIR_RasPi_Python/example.py
NDIR_RasPi_Python/example.py
import NDIR import time sensor = NDIR.Sensor(0x4D) sensor.begin() while True: sensor.measure() print("CO2 Concentration: " + str(sensor.ppm) + "ppm") time.sleep(1)
import NDIR import time sensor = NDIR.Sensor(0x4D) if sensor.begin() == False: print("Adaptor initialization FAILED!") exit() while True: if sensor.measure(): print("CO2 Concentration: " + str(sensor.ppm) + "ppm") else: print("Sensor communication ERROR.") time.sleep(1)
Make use of the return value of begin() and measure()
Make use of the return value of begin() and measure()
Python
mit
SandboxElectronics/NDIR,SandboxElectronics/NDIR,SandboxElectronics/NDIR
c75071ad2dd8c2e5efdef660f1aa33ffa28f0613
frontends/etiquette_repl.py
frontends/etiquette_repl.py
# Use with # py -i etiquette_easy.py import etiquette import os import sys P = etiquette.photodb.PhotoDB() import traceback def easytagger(): while True: i = input('> ') if i.startswith('?'): i = i.split('?')[1] or None try: etiquette.tag_export.stdout([P.g...
# Use with # py -i etiquette_easy.py import argparse import os import sys import traceback import etiquette P = etiquette.photodb.PhotoDB() def easytagger(): while True: i = input('> ') if i.startswith('?'): i = i.split('?')[1] or None try: etiquette.tag_e...
Clean up the erepl code a little bit.
Clean up the erepl code a little bit.
Python
bsd-3-clause
voussoir/etiquette,voussoir/etiquette,voussoir/etiquette
b69db7ff67abe185bcf7e8e7badfa868a9ec882c
script/update-frameworks.py
script/update-frameworks.py
#!/usr/bin/env python import sys import os from lib.util import safe_mkdir, extract_zip, tempdir, download SOURCE_ROOT = os.path.abspath(os.path.dirname(os.path.dirname(__file__))) FRAMEWORKS_URL = 'http://atom-alpha.s3.amazonaws.com' def main(): os.chdir(SOURCE_ROOT) safe_mkdir('frameworks') download_and_u...
#!/usr/bin/env python import sys import os from lib.util import safe_mkdir, extract_zip, tempdir, download SOURCE_ROOT = os.path.abspath(os.path.dirname(os.path.dirname(__file__))) FRAMEWORKS_URL = 'https://github.com/atom/atom-shell/releases/download/v0.11.10' def main(): os.chdir(SOURCE_ROOT) safe_mkdir('fra...
Move framework downloads to github release
Move framework downloads to github release
Python
mit
bpasero/electron,fomojola/electron,simonfork/electron,micalan/electron,neutrous/electron,stevemao/electron,jtburke/electron,medixdev/electron,Andrey-Pavlov/electron,yalexx/electron,synaptek/electron,Neron-X5/electron,stevekinney/electron,christian-bromann/electron,benweissmann/electron,mirrh/electron,leftstick/electron...
04110d34b5f385103a77e0a1459e984d8210fa92
updates/models.py
updates/models.py
from django.db import models from cms.models import CMSPlugin from django.utils.translation import ugettext_lazy as _ class Update(models.Model): """ Defines a date on which updates were made. """ date = models.DateField(_('Update Date')) def __str__(self): return str(self.date) clas...
from django.db import models from cms.models import CMSPlugin from django.utils.translation import ugettext_lazy as _ class Update(models.Model): """ Defines a date on which updates were made. """ date = models.DateField(_('Update Date')) def __str__(self): return str(self.date) clas...
Remove choices for any number of updates.
Remove choices for any number of updates.
Python
bsd-3-clause
theherk/django-theherk-updates
4efd5de76f9f192ab9ceb73254e500c47c46090a
django_git/management/commands/git_pull_utils/multiple_repo_updater.py
django_git/management/commands/git_pull_utils/multiple_repo_updater.py
import os import traceback from django.utils import timezone from django_git.management.commands.git_pull_utils.git_synchronizer import GitSynchronizer def no_action(msg): pass try: from iconizer.gui_client.notification_service_client import NotificationServiceClient notification_method = NotificationSe...
import os import traceback from django.utils import timezone from django_git.management.commands.git_pull_utils.git_synchronizer import GitSynchronizer def no_action(msg): pass try: from iconizer.gui_client.notification_service_client import NotificationServiceClient notification_method = NotificationSe...
Fix no notification service client issue.
Fix no notification service client issue.
Python
bsd-3-clause
weijia/django-git,weijia/django-git
3d037ed7142ed7b1c7382eded4de6443050543ee
vimiv/__init__.py
vimiv/__init__.py
#!/usr/bin/env python3 # encoding: utf-8 try: import argparse import configparser import mimetypes import os import re import shutil import signal import sys from gi import require_version require_version('Gtk', '3.0') from gi.repository import GLib, Gtk, Gdk, GdkPixbuf, Pan...
#!/usr/bin/env python3 # encoding: utf-8 try: from gi import require_version require_version('Gtk', '3.0') from gi.repository import GLib, Gtk, Gdk, GdkPixbuf, Pango from PIL import Image, ImageEnhance except ImportError as import_error: print(import_error) print("Are all dependencies installe...
Remove standard imports from check in init
Remove standard imports from check in init
Python
mit
karlch/vimiv,karlch/vimiv,karlch/vimiv
fee6f9753b1b5209f605b6dd329ac5af00f87174
Lib/__init__.py
Lib/__init__.py
"""\ SciPy --- A scientific computing package for Python =================================================== You can support the development of SciPy by purchasing documentation at http://www.trelgol.com It is being distributed for a fee for a limited time to try and raise money for development. Documentation is ...
"""\ SciPy --- A scientific computing package for Python =================================================== You can support the development of SciPy by purchasing documentation at http://www.trelgol.com It is being distributed for a fee for a limited time to try and raise money for development. Documentation is ...
Put numpy namespace in scipy for backward compatibility...
Put numpy namespace in scipy for backward compatibility... git-svn-id: 003f22d385e25de9cff933a5ea4efd77cb5e7b28@1530 d6536bca-fef9-0310-8506-e4c0a848fbcf
Python
bsd-3-clause
scipy/scipy-svn,jasonmccampbell/scipy-refactor,scipy/scipy-svn,scipy/scipy-svn,lesserwhirls/scipy-cwt,lesserwhirls/scipy-cwt,lesserwhirls/scipy-cwt,jasonmccampbell/scipy-refactor,lesserwhirls/scipy-cwt,jasonmccampbell/scipy-refactor,jasonmccampbell/scipy-refactor,scipy/scipy-svn
19433ab423abdd16dddf3508e8d73f0a0edae83c
bot/utils/attributeobject.py
bot/utils/attributeobject.py
class AttributeObject: def __init__(self, *excluded_keys): self._excluded_keys = excluded_keys def __getattr__(self, item): return self._getattr(item) def __setattr__(self, key, value): if key == "_excluded_keys" or key in self._excluded_keys: super().__setattr__(key, v...
class AttributeObject: def __init__(self, *excluded_keys): self._excluded_keys = excluded_keys def __getattr__(self, item): return self._getattr(item) def __setattr__(self, key, value): if key == "_excluded_keys" or key in self._excluded_keys: super().__setattr__(key, v...
Raise NotImplementedError instead of just passing in AttributeObject
Raise NotImplementedError instead of just passing in AttributeObject That way, if somebody uses it directly, it will fail with a proper error.
Python
agpl-3.0
alvarogzp/telegram-bot,alvarogzp/telegram-bot
365e4abca73d55fe4ba1b51a0057556ff8487c41
changes/listeners/build_revision.py
changes/listeners/build_revision.py
import logging from flask import current_app from fnmatch import fnmatch from changes.api.build_index import BuildIndexAPIView from changes.config import db from changes.models import ItemOption, Project logger = logging.getLogger('build_revision') def should_build_branch(revision, allowed_branches): if not r...
import logging from flask import current_app from fnmatch import fnmatch from changes.api.build_index import BuildIndexAPIView from changes.config import db from changes.models import ItemOption logger = logging.getLogger('build_revision') def should_build_branch(revision, allowed_branches): if not revision.b...
Revert "Move build.branch-names to project settings"
Revert "Move build.branch-names to project settings" This reverts commit a38fc17616ae160aa41046470964034294eade1a.
Python
apache-2.0
bowlofstew/changes,dropbox/changes,dropbox/changes,bowlofstew/changes,wfxiang08/changes,wfxiang08/changes,wfxiang08/changes,dropbox/changes,bowlofstew/changes,dropbox/changes,bowlofstew/changes,wfxiang08/changes
2c67fcd8ec55324366087c2f69bcd232592ac312
pirx/base.py
pirx/base.py
class Settings(object): def __init__(self): self._settings = {} def __setattr__(self, name, value): if name != '_settings': self._settings[name] = value else: super(Settings, self).__setattr__(name, value) def write(self): for name, value in self._se...
class Settings(object): def __init__(self): self._settings = {} def __setattr__(self, name, value): if name != '_settings': self._settings[name] = value else: super(Settings, self).__setattr__(name, value) def write(self): for name, value in self._se...
Use __repr__ instead of __str__ to print setting's value
Use __repr__ instead of __str__ to print setting's value
Python
mit
piotrekw/pirx
da6f284cf1ffa1397c32167e1e23189ea29e5b2f
IPython/html/widgets/widget_container.py
IPython/html/widgets/widget_container.py
"""ContainerWidget class. Represents a container that can be used to group other widgets. """ # Copyright (c) IPython Development Team. # Distributed under the terms of the Modified BSD License. from .widget import DOMWidget from IPython.utils.traitlets import Unicode, Tuple, TraitError class ContainerWidget(DOMW...
"""ContainerWidget class. Represents a container that can be used to group other widgets. """ # Copyright (c) IPython Development Team. # Distributed under the terms of the Modified BSD License. from .widget import DOMWidget from IPython.utils.traitlets import Unicode, Tuple, TraitError class ContainerWidget(DOMW...
Make Container widgets take children as the first positional argument
Make Container widgets take children as the first positional argument This makes creating containers less cumbersome: Container([list, of, children]), rather than Container(children=[list, of, children])
Python
bsd-3-clause
ipython/ipython,ipython/ipython
efb0aa6c68ed9b5ab5c855464dc0b611506326d2
wafer/kv/migrations/0001_initial.py
wafer/kv/migrations/0001_initial.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models import jsonfield.fields class Migration(migrations.Migration): dependencies = [ ('auth', '0006_require_contenttypes_0002'), ] operations = [ migrations.CreateModel( name=...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models from django.conf import settings import jsonfield.fields class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL) ] operations = [ ...
Tweak kv migration to improve compatibility across Django versions
Tweak kv migration to improve compatibility across Django versions
Python
isc
CTPUG/wafer,CTPUG/wafer,CTPUG/wafer,CTPUG/wafer
29c3d87881ce9c57478eb821da60d77e9f5eeb48
eventsourcing/application/base.py
eventsourcing/application/base.py
from abc import abstractmethod, ABCMeta from six import with_metaclass from eventsourcing.infrastructure.event_store import EventStore from eventsourcing.infrastructure.persistence_subscriber import PersistenceSubscriber class EventSourcingApplication(with_metaclass(ABCMeta)): def __init__(self, json_encoder_c...
from abc import abstractmethod, ABCMeta from six import with_metaclass from eventsourcing.infrastructure.event_store import EventStore from eventsourcing.infrastructure.persistence_subscriber import PersistenceSubscriber class EventSourcingApplication(with_metaclass(ABCMeta)): persist_events = True def __i...
Allow to disable events persistence at app class
Allow to disable events persistence at app class
Python
bsd-3-clause
johnbywater/eventsourcing,johnbywater/eventsourcing
bfaf081b0e3c3cb8a37270ca7c0a16d52795a3de
kozmic/auth/views.py
kozmic/auth/views.py
import github3 from flask import render_template, current_app, redirect, url_for from flask.ext.login import login_user, logout_user, login_required from kozmic import db from kozmic.models import User from . import bp @bp.route('/_auth/auth-callback/') @bp.github_oauth_app.authorized_handler def auth_callback(respo...
import github3 from flask import render_template, current_app, redirect, url_for from flask.ext.login import login_user, logout_user, login_required from kozmic import db from kozmic.models import User from . import bp @bp.route('/_auth/auth-callback/') @bp.github_oauth_app.authorized_handler def auth_callback(respo...
Update GitHub access token on each login
Update GitHub access token on each login
Python
bsd-3-clause
aromanovich/kozmic-ci,abak-press/kozmic-ci,abak-press/kozmic-ci,abak-press/kozmic-ci,aromanovich/kozmic-ci,aromanovich/kozmic-ci,artofhuman/kozmic-ci,abak-press/kozmic-ci,aromanovich/kozmic-ci,artofhuman/kozmic-ci,artofhuman/kozmic-ci,artofhuman/kozmic-ci
0d93a0dff18165c36788a140af40208ec48d505f
prep.py
prep.py
from os import listdir from os.path import join def file_paths(data_path): return [join(data_path, name) for name in listdir(data_path)] def training_data(data_path): paths = file_paths(data_path) raw_text = [ open(path, 'r').read() for path in paths] dataX = [] dataY = [] for text in raw_text: data ...
from os import listdir from os.path import join import re def file_paths(data_path): return [join(data_path, name) for name in listdir(data_path)] def training_data(data_path): paths = file_paths(data_path) raw_text = [open(path, 'r').read() for path in paths] dataX = [] dataY = [] for text in raw_text:...
Transform sentences to arrays of words
Transform sentences to arrays of words
Python
mit
vdragan1993/python-coder
4d01eb0c1b11680d463d4fcb0888fac4ab6c45c8
panoptes/utils/data.py
panoptes/utils/data.py
import os import argparse from astropy.utils import data from astroplan import download_IERS_A def download_all_files(data_folder="{}/astrometry/data".format(os.getenv('PANDIR'))): download_IERS_A() for i in range(4214, 4219): fn = 'index-{}.fits'.format(i) dest = "{}/{}".format(data_folder, ...
import os import shutil import argparse from astropy.utils import data from astroplan import download_IERS_A def download_all_files(data_folder="{}/astrometry/data".format(os.getenv('PANDIR'))): download_IERS_A() for i in range(4214, 4219): fn = 'index-{}.fits'.format(i) dest = "{}/{}".format...
Use shutil instead of `os.rename`
Use shutil instead of `os.rename`
Python
mit
panoptes/POCS,AstroHuntsman/POCS,joshwalawender/POCS,AstroHuntsman/POCS,joshwalawender/POCS,AstroHuntsman/POCS,panoptes/POCS,AstroHuntsman/POCS,panoptes/POCS,joshwalawender/POCS,panoptes/POCS
8556437ee02de028ec5de3b867abaab82533cb91
keystone/tests/unit/common/test_manager.py
keystone/tests/unit/common/test_manager.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...
Correct test to support changing N release name
Correct test to support changing N release name oslo.log is going to change to use Newton rather than N so this test should not make an assumption about the way that versionutils.deprecated is calling report_deprecated_feature. Change-Id: I06aa6d085232376811f73597b2d84b5174bc7a8d Closes-Bug: 1561121
Python
apache-2.0
ilay09/keystone,rajalokan/keystone,openstack/keystone,mahak/keystone,klmitch/keystone,openstack/keystone,ilay09/keystone,cernops/keystone,rajalokan/keystone,cernops/keystone,mahak/keystone,ilay09/keystone,rajalokan/keystone,klmitch/keystone,mahak/keystone,openstack/keystone
014f7255ea62c748e0935bbb36e279a35626df38
kokki/cookbooks/ssh/libraries/resources.py
kokki/cookbooks/ssh/libraries/resources.py
__all__ = ["SSHKnownHost", "SSHAuthorizedKey"] import os.path from kokki import * class SSHKnownHost(Resource): provider = "*ssh.SSHKnownHostProvider" action = ForcedListArgument(default="include") host = ResourceArgument(default=lambda obj:obj.name) keytype = ResourceArgument() key = ResourceAr...
__all__ = ["SSHKnownHost", "SSHAuthorizedKey"] import os.path from kokki import * class SSHKnownHost(Resource): provider = "*ssh.SSHKnownHostProvider" action = ForcedListArgument(default="include") host = ResourceArgument(default=lambda obj:obj.name) keytype = ResourceArgument() key = ResourceAr...
Make sure ssh config directory exists
Make sure ssh config directory exists
Python
bsd-3-clause
samuel/kokki
70842a821d713525e1fe3c6376a30fcc0a39155c
zoe_lib/predefined_apps/__init__.py
zoe_lib/predefined_apps/__init__.py
# Copyright (c) 2016, Daniele Venzano # # 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 w...
# Copyright (c) 2016, Daniele Venzano # # 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 w...
Fix import error due to wrong import line
Fix import error due to wrong import line
Python
apache-2.0
DistributedSystemsGroup/zoe,DistributedSystemsGroup/zoe,DistributedSystemsGroup/zoe,DistributedSystemsGroup/zoe,DistributedSystemsGroup/zoe
fa16e93e4d00db3ef68f9de16f5c1eb28988dc18
apps/local_apps/account/context_processors.py
apps/local_apps/account/context_processors.py
from account.models import Account, AnonymousAccount def openid(request): return {'openid': request.openid} def account(request): if request.user.is_authenticated(): try: account = Account._default_manager.get(user=request.user) except (Account.DoesNotExist, Account.MultipleObject...
from account.models import Account, AnonymousAccount def openid(request): return {'openid': request.openid} def account(request): if request.user.is_authenticated(): try: account = Account._default_manager.get(user=request.user) except Account.DoesNotExist: account = A...
Throw 500 error on multiple accounts in account context processor
Throw 500 error on multiple accounts in account context processor
Python
mit
ingenieroariel/pinax,ingenieroariel/pinax
52a3a7b2a6aac284b9dd1a7edfb27cdec4d33675
lib/pyfrc/test_support/pyfrc_fake_hooks.py
lib/pyfrc/test_support/pyfrc_fake_hooks.py
from hal_impl.data import hal_data class PyFrcFakeHooks: ''' Defines hal hooks that use the fake time object ''' def __init__(self, fake_time): self.fake_time = fake_time # # Hook functions # def getTime(self): return self.fake_time.get() def getFP...
from hal_impl.sim_hooks import SimHooks class PyFrcFakeHooks(SimHooks): ''' Defines hal hooks that use the fake time object ''' def __init__(self, fake_time): self.fake_time = fake_time super().__init__() # # Time related hooks # def getTime(self): ...
Update sim hooks for 2018
Update sim hooks for 2018
Python
mit
robotpy/pyfrc
32671085ddd8362db14e22d98d4fa5910dd0aa62
ui/tcmui/testexecution/views.py
ui/tcmui/testexecution/views.py
from django.template.response import TemplateResponse from ..products.models import Product from ..static import testcyclestatus from ..users.decorators import login_required from .models import TestCycleList @login_required def cycles(request, product_id): product = Product.get("products/%s" % product_id, aut...
from django.template.response import TemplateResponse from ..products.models import Product from ..static import testcyclestatus from ..users.decorators import login_required from .models import TestCycleList @login_required def cycles(request, product_id): product = Product.get("products/%s" % product_id, aut...
Use correct auth in cycles view, now that API permissions are fixed.
Use correct auth in cycles view, now that API permissions are fixed.
Python
bsd-2-clause
mccarrmb/moztrap,mccarrmb/moztrap,mccarrmb/moztrap,shinglyu/moztrap,mozilla/moztrap,shinglyu/moztrap,shinglyu/moztrap,mozilla/moztrap,bobsilverberg/moztrap,shinglyu/moztrap,mccarrmb/moztrap,bobsilverberg/moztrap,mozilla/moztrap,shinglyu/moztrap,mccarrmb/moztrap,bobsilverberg/moztrap,mozilla/moztrap,mozilla/moztrap,bobs...
901c482f357ba3a845d40cb126667490472a6bf6
Code/divide.py
Code/divide.py
def divide(a, b): return a / b print divide(20, 2)
num1 = input('Enter first number: ') num2 = input('Enter second number: ') if num2==0: print 'Denominator cannot be 0' else: Division=float(num1)/float(num2) print Division
Divide two numbers using python code
Divide two numbers using python code
Python
mit
HarendraSingh22/Python-Guide-for-Beginners
11889613df601a54a169bb51511e6eb54dec3988
tree.py
tree.py
import math def succ_fcn(x): """ takes an element of the Calkin Wilf tree and returns the next element following a breadth first traversal """ return 1 / (math.floor(x) + 1 - (x % 1)) def get_nth(n): """ takes a natural number n and returns the nth element of the Calkin Wilf tree foll...
import math def succ_fcn(x): """ takes an element of the Calkin Wilf tree and returns the next element following a breadth first traversal """ return 1 / (math.floor(x) + 1 - (x % 1)) def get_nth(n): """ takes a natural number n and returns the nth element of the Calkin Wilf tree fol...
Add basic breadth first return
Add basic breadth first return
Python
mit
richardmillson/Calkin_Wilf_tree
feb630b75f2a28bb098a4a192a4bbb528e2251fa
addons/email/res_partner.py
addons/email/res_partner.py
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU...
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU...
Remove history domain in partner in eamil module.
Remove history domain in partner in eamil module. bzr revid: ysa@tinyerp.com-20110204091248-wnzm7ft6cx3v34p1
Python
agpl-3.0
gsmartway/odoo,odootr/odoo,gdgellatly/OCB1,frouty/odoo_oph,waytai/odoo,NeovaHealth/odoo,jpshort/odoo,zchking/odoo,Elico-Corp/odoo_OCB,Maspear/odoo,takis/odoo,Gitlab11/odoo,0k/OpenUpgrade,gsmartway/odoo,grap/OpenUpgrade,cloud9UG/odoo,jfpla/odoo,syci/OCB,joariasl/odoo,vrenaville/ngo-addons-backport,mmbtba/odoo,osvalr/odo...
a80297b8e52ccc2560bcd0b8a204dad7eab4c925
website_payment_v10/__init__.py
website_payment_v10/__init__.py
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2013-Today OpenERP SA (<http://www.openerp.com>). # # This program is free software: you can redistribute it and/or modify # it under the terms ...
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details.
Use global LICENSE/COPYRIGHT files, remove boilerplate text
[LEGAL] Use global LICENSE/COPYRIGHT files, remove boilerplate text - Preserved explicit 3rd-party copyright notices - Explicit boilerplate should not be necessary - copyright law applies automatically in all countries thanks to Berne Convention + WTO rules, and a reference to the applicable license is clear enoug...
Python
agpl-3.0
nicolas-petit/website,JayVora-SerpentCS/website,RoelAdriaans-B-informed/website,Tecnativa/website,RoelAdriaans-B-informed/website,khaeusler/website,khaeusler/website,Tecnativa/website,nicolas-petit/website,nicolas-petit/website,JayVora-SerpentCS/website,RoelAdriaans-B-informed/website,RoelAdriaans-B-informed/website,kh...
e7805528be294374b128dd6e40e3f8990b03cdac
main.py
main.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """Run the Better Bomb Defusal Manual :Copyright: 2015 Jochen Kupperschmidt :License: MIT, see LICENSE for details. """ from importlib import import_module from bombdefusalmanual.ui.console import ConsoleUI from bombdefusalmanual.ui.models import Answer ANSWERS = [ ...
#!/usr/bin/env python # -*- coding: utf-8 -*- """Run the Better Bomb Defusal Manual :Copyright: 2015 Jochen Kupperschmidt :License: MIT, see LICENSE for details. """ from argparse import ArgumentParser from importlib import import_module from bombdefusalmanual.ui.console import ConsoleUI from bombdefusalmanual.ui.m...
Allow to enable graphical UI via command line option.
Allow to enable graphical UI via command line option.
Python
mit
homeworkprod/better-bomb-defusal-manual,homeworkprod/better-bomb-defusal-manual
8541737b5a3a50188162349727a0d0230613e630
test/features/test_create_pages.py
test/features/test_create_pages.py
from hamcrest import * from nose.tools import nottest from test.features import BrowserTest class test_create_pages(BrowserTest): def test_about_page(self): self.browser.visit("http://0.0.0.0:8000/high-volume-services/by-transactions-per-year/descending") assert_that(self.browser.find_by_css('h1...
from hamcrest import * from nose.tools import nottest from test.features import BrowserTest class test_create_pages(BrowserTest): def test_about_page(self): self.browser.visit("http://0.0.0.0:8000/high-volume-services/" "by-transactions-per-year/descending") assert_tha...
Change services number in test
Change services number in test
Python
mit
alphagov/transactions-explorer,gds-attic/transactions-explorer,alphagov/transactions-explorer,alphagov/transactions-explorer,gds-attic/transactions-explorer,gds-attic/transactions-explorer,alphagov/transactions-explorer,alphagov/transactions-explorer,gds-attic/transactions-explorer,gds-attic/transactions-explorer
9696b687a31a249fc228e58773ff55eacf8beaaa
src/vrun/compat.py
src/vrun/compat.py
# flake8: noqa import sys PY2 = sys.version_info[0] == 2 try: from configparser import ConfigParser except ImportError: from ConfigParser import SafeConfigParser as ConfigParser
# flake8: noqa import sys PY2 = sys.version_info[0] == 2 try: from configparser import ConfigParser except ImportError: from ConfigParser import SafeConfigParser as ConfigParser if not hasattr(ConfigParser, 'read_dict'): def read_dict(self, dictionary, source='<dict>'): for (section, options) in...
Add a read_dict function if it does not exist
Add a read_dict function if it does not exist This is used for testing purposes, but when we drop Py2 support we can more easily remove it here than worrying about removing a monkeypatch in the testing code.
Python
isc
bertjwregeer/vrun
5da3928442a884c7b5905ca2b17362ca99fffc2c
marten/__init__.py
marten/__init__.py
"""Stupid simple Python configuration management""" from __future__ import absolute_import import os as _os __version__ = '0.5.0' # Attempt to auto-load a default configuration from files in <cwd>/.marten/ based on the MARTEN_ENV env variable # MARTEN_ENV defaults to 'default' config = None _marten_dir = _os.path...
"""Stupid simple Python configuration management""" from __future__ import absolute_import import os as _os __version__ = '0.5.1' # Attempt to auto-load a default configuration from files in <cwd>/.marten/ based on the MARTEN_ENV env variable # MARTEN_ENV defaults to 'default' _marten_dir = _os.path.join(_os.getc...
Return empty Configuration instance when .marten/ directory is missing
Return empty Configuration instance when .marten/ directory is missing
Python
mit
nick-allen/marten
c39d3801beece54d7403b1a1c7956839aa20df79
plot.py
plot.py
#!/usr/bin/python # -*- coding: utf-8 -*- import argparse import matplotlib.pyplot as plt import pandas as pd parser = argparse.ArgumentParser(description='Plot data from output of the n-body simulation.') parser.add_argument('--output', type=str, default='output_int.dat', help='The output file (d...
#!/usr/bin/python # -*- coding: utf-8 -*- import argparse import matplotlib.pyplot as plt import pandas as pd parser = argparse.ArgumentParser(description='Plot data from output of the n-body simulation.') parser.add_argument('--output', type=str, default='output_int.dat', help='The output file (d...
Use absolute value for E and logscale
Use absolute value for E and logscale
Python
mit
cphyc/n-body,cphyc/n-body
2d5c1064b951f3628e8a4f4a6fadc9c45d490094
tools/bots/pub_integration_test.py
tools/bots/pub_integration_test.py
#!/usr/bin/env python # Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file # for details. All rights reserved. Use of this source code is governed by a # BSD-style license that can be found in the LICENSE file. import os import subprocess import sys import shutil import tempfile PUBSPEC = """n...
#!/usr/bin/env python # Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file # for details. All rights reserved. Use of this source code is governed by a # BSD-style license that can be found in the LICENSE file. import os import subprocess import sys import shutil import tempfile PUBSPEC = """n...
Add .bat to pub command on Windows
[infra] Add .bat to pub command on Windows #32656 Change-Id: I3a34bf2c81676eea0ab112a8aad701962590a6c3 Reviewed-on: https://dart-review.googlesource.com/55165 Commit-Queue: Alexander Thomas <29642742b6693024c89de8232f2e2542cf7eedf7@google.com> Reviewed-by: William Hesse <a821cddceae7dc400f272e3cb1a72f400f9fed6d@googl...
Python
bsd-3-clause
dart-lang/sdk,dartino/dart-sdk,dart-lang/sdk,dartino/dart-sdk,dart-archive/dart-sdk,dart-archive/dart-sdk,dart-lang/sdk,dartino/dart-sdk,dart-archive/dart-sdk,dart-archive/dart-sdk,dart-lang/sdk,dartino/dart-sdk,dart-lang/sdk,dart-archive/dart-sdk,dartino/dart-sdk,dart-lang/sdk,dart-archive/dart-sdk,dartino/dart-sdk,da...
7325eacc1066970a98be30b56fdf4cd31ecc2f57
db_file_storage/views.py
db_file_storage/views.py
# django from wsgiref.util import FileWrapper from django.http import HttpResponse, HttpResponseBadRequest from django.utils.translation import ugettext as _ # project from db_file_storage.storage import DatabaseFileStorage storage = DatabaseFileStorage() def get_file(request, add_attachment_headers): name = re...
# django from wsgiref.util import FileWrapper from django.http import HttpResponse, HttpResponseBadRequest from django.utils.translation import ugettext as _ # project from db_file_storage.storage import DatabaseFileStorage storage = DatabaseFileStorage() def get_file(request, add_attachment_headers): name = re...
Set Content-Length header in get_file view
Set Content-Length header in get_file view
Python
mit
victor-o-silva/db_file_storage,victor-o-silva/db_file_storage
9413b4b24c318df4bf68069038081d08fa9ad2e8
vumi/transports/infobip/__init__.py
vumi/transports/infobip/__init__.py
"""Infobip transport.""" from vumi.transports.infobip.infobip import InfobipTransport __all__ = ['InfobipTransport']
"""Infobip transport.""" from vumi.transports.infobip.infobip import InfobipTransport, InfobipError __all__ = ['InfobipTransport', 'InfobipError']
Add InfobipError to things exported by Infobip package.
Add InfobipError to things exported by Infobip package.
Python
bsd-3-clause
TouK/vumi,harrissoerja/vumi,vishwaprakashmishra/xmatrix,TouK/vumi,TouK/vumi,vishwaprakashmishra/xmatrix,harrissoerja/vumi,harrissoerja/vumi,vishwaprakashmishra/xmatrix
4ead2d0b2bc987bcc75a5f94c31553a8024aa8a8
src/vault.py
src/vault.py
from fabric.api import task, local from buildercore import project import utils import sys import logging LOG = logging.getLogger(__name__) def vault_addr(): defaults, _ = project.raw_project_map() return defaults['aws']['vault']['address'] def vault_policy(): return 'builder-user' @task def login(): ...
from fabric.api import task, local from buildercore import project import utils import sys import logging LOG = logging.getLogger(__name__) def vault_addr(): defaults, _ = project.raw_project_map() return defaults['aws']['vault']['address'] def vault_policy(): return 'builder-user' @task def login(): ...
Add task to update policies
Add task to update policies
Python
mit
elifesciences/builder,elifesciences/builder
5f6a404f8a4357c3de72b7ac506168e1bec810a8
quicksort/quicksort.py
quicksort/quicksort.py
from random import randint def sort(arr, start, length): if length <= 1: return arr pivot = choose_pivot(arr, length) i = j = start + 1 while j < length: if arr[j] < pivot: swap(arr, j, i) i += 1 j += 1 swap(arr, start, i-1) return (arr, length, pivot) def swap(arr, x, y): temp = arr[x] arr[...
from random import randint def sort(arr, start, length): if length <= 1: return arr pivot = choose_pivot(arr, length) i = j = start + 1 while j < length: if arr[j] < pivot: swap(arr, j, i) i += 1 j += 1 swap(arr, start, i-1) first_part = sort(arr[start:i], start, i) second_part = sort(arr[i:len...
Sort list by recursing through both parts
Sort list by recursing through both parts The array is split into two parts: everything up to and including the pivot, and everything after the pivot. Sort() is called on each part and the resulting arrays are combined and returned. This sorts the array.
Python
mit
timpel/stanford-algs,timpel/stanford-algs
ee070606be405b86bfcc6e6796bbe322a78511ed
ui/assetmanager.py
ui/assetmanager.py
"""Loads and manages art assets""" import pyglet _ASSET_PATHS = ["res"] _ASSET_FILE_NAMES = [ "black_key_down.png", "black_key_up.png", "white_key_down.png", "white_key_up.png", "staff_line.png", ] class Assets(object): _loadedAssets = None @staticmethod def loadAssets(): Ass...
"""Loads and manages art assets""" import pyglet import os _ASSET_PATHS = ["res"] _ASSET_FILE_NAMES = [ "black_key_down.png", "black_key_up.png", "white_key_down.png", "white_key_up.png", "staff_line.png", ] class Assets(object): _loadedAssets = None @staticmethod def loadAssets(): ...
Use absolute resource path in Pyglet
Use absolute resource path in Pyglet It appears that a recent change in Pyglet causes relative paths to fail here.
Python
bsd-2-clause
aschmied/keyzer
dd9f11f36668717ee349b357b2f32a7a52e38863
pagerduty_events_api/pagerduty_incident.py
pagerduty_events_api/pagerduty_incident.py
from pagerduty_events_api.pagerduty_rest_client import PagerdutyRestClient class PagerdutyIncident: def __init__(self, service_key, incident_key): self.__service_key = service_key self.__incident_key = incident_key def get_service_key(self): return self.__service_key def get_inci...
from pagerduty_events_api.pagerduty_rest_client import PagerdutyRestClient class PagerdutyIncident: def __init__(self, service_key, incident_key): self.__service_key = service_key self.__incident_key = incident_key def get_service_key(self): return self.__service_key def get_inci...
Remove code duplication from PD Incident class.
Remove code duplication from PD Incident class.
Python
mit
BlasiusVonSzerencsi/pagerduty-events-api
67fadc0ed846a95f6d603827313b555e98985959
skimage/viewer/qt.py
skimage/viewer/qt.py
has_qt = True try: from matplotlib.backends.qt_compat import QtGui, QtCore, QtWidgets except ImportError: try: from matplotlib.backends.qt4_compat import QtGui, QtCore QtWidgets = QtGui except ImportError: # Mock objects class QtGui(object): QMainWindow = object ...
has_qt = True try: from matplotlib.backends.qt_compat import QtGui, QtCore, QtWidgets except ImportError: try: from matplotlib.backends.qt4_compat import QtGui, QtCore QtWidgets = QtGui except ImportError: # Mock objects class QtGui_cls(object): QMainWindow = obj...
Fix mock Qt objects again
Fix mock Qt objects again
Python
bsd-3-clause
jwiggins/scikit-image,Hiyorimi/scikit-image,paalge/scikit-image,michaelaye/scikit-image,ajaybhat/scikit-image,ofgulban/scikit-image,oew1v07/scikit-image,newville/scikit-image,juliusbierk/scikit-image,chriscrosscutler/scikit-image,vighneshbirodkar/scikit-image,newville/scikit-image,keflavich/scikit-image,bennlich/scikit...
0f04e6ed48227c6904d75a78be9c893f47f9cb80
joku/cogs/_common.py
joku/cogs/_common.py
from collections import OrderedDict import threading from joku.bot import Jokusoramame class _CogMeta(type): def __prepare__(*args, **kwargs): # Use an OrderedDict for the class body. return OrderedDict() class Cog(metaclass=_CogMeta): """ A common class for all cogs. This makes the cl...
from collections import OrderedDict import threading from joku.bot import Jokusoramame class _CogMeta(type): def __prepare__(*args, **kwargs): # Use an OrderedDict for the class body. return OrderedDict() class Cog(metaclass=_CogMeta): def __init__(self, bot: Jokusoramame): self._b...
Remove false docstring from common cog.
Remove false docstring from common cog.
Python
mit
MJB47/Jokusoramame,MJB47/Jokusoramame,MJB47/Jokusoramame
87ba878afe9fac0e8ebe3b11719982148b8ac89a
conanfile.py
conanfile.py
from conans import ConanFile from conans.tools import download, unzip import os VERSION = "0.0.2" class VeraPPTargetCmakeConan(ConanFile): name = "verapp-target-cmake" version = os.environ.get("CONAN_VERSION_OVERRIDE", VERSION) generators = "cmake" requires = ("cmake-include-guard/master@smspillaz/cm...
from conans import ConanFile from conans.tools import download, unzip import os VERSION = "0.0.2" class VeraPPTargetCmakeConan(ConanFile): name = "verapp-target-cmake" version = os.environ.get("CONAN_VERSION_OVERRIDE", VERSION) generators = "cmake" requires = ("cmake-include-guard/master@smspillaz/cm...
Copy find modules to root of module path
conan: Copy find modules to root of module path
Python
mit
polysquare/veracpp-cmake,polysquare/verapp-cmake
0d8ce87cda68a0e882cf1108066e2bde6c9cb1fa
shopping_app/forms.py
shopping_app/forms.py
from wtforms import Form, BooleanField, StringField, PasswordField, validators from wtforms.validators import DataRequired, InputRequired class LoginForm(Form): username = StringField('username', validators=[InputRequired(), DataRequired()]) password = PasswordField('password', validators=[InputRequired(), Da...
from wtforms import Form, DecimalField, IntegerField, StringField, PasswordField, validators, ValidationError from wtforms.validators import DataRequired, InputRequired from .utils.helpers import check_duplicate_item_name class LoginForm(Form): username = StringField('username', validators=[InputRequired(), DataR...
Add create shopping item form
Add create shopping item form
Python
mit
gr1d99/shopping-list,gr1d99/shopping-list,gr1d99/shopping-list
582460dcfeb85e2132705ba789eb88d1c67ae022
counting_sort.py
counting_sort.py
import random import time def counting_sort(array): k = max(array) counts = [0]*(k+1) for x in array: counts[x] += 1 total = 0 for i in range(0,k+1): c = counts[i] counts[i] = total total = total + c output = [0]*len(array) for x in array: output[co...
import random import time def counting_sort(array): k = max(array) counts = [0]*(k+1) for x in array: counts[x] += 1 output = [] for x in xrange(k+1): output += [x]*counts[x] return output if __name__ == "__main__": assert counting_sort([5,3,2,1]) == [1,2,3,5] x = []...
Use a much simpler (and faster) output building step.
Use a much simpler (and faster) output building step. This implementation is much easeir to read, and is a lot clearer about what's going on. It turns out that it's about 3 times faster in python too!
Python
mit
samphippen/linear_sort
71671f30589464c4d714110a6f00ca6ab327c5c6
blogs/middleware.py
blogs/middleware.py
from django.shortcuts import get_object_or_404 from django.contrib.auth.models import User from annoying.functions import get_object_or_None class BlogMiddleware: def process_request(self, request): request.blog_user = None host = request.META.get('HTTP_HOST', '') host_s = host.replace('...
from django.shortcuts import get_object_or_404 from django.contrib.auth.models import User from annoying.functions import get_object_or_None class BlogMiddleware: def process_request(self, request): request.blog_user = None host = request.META.get('HTTP_HOST', '') host_s = host.replace('...
Allow Pro users to specify multiple domains to serve their blog. Specifically for www/non-www setups.
Allow Pro users to specify multiple domains to serve their blog. Specifically for www/non-www setups.
Python
mit
nicksergeant/snipt,nicksergeant/snipt,nicksergeant/snipt
99e443f51e5cab27b4a511d1ff9db8e5fc571a62
hostmonitor/management/commands/addhost.py
hostmonitor/management/commands/addhost.py
from iptools import validate_ip, validate_cidr, IpRange from django.core.management.base import BaseCommand, CommandError from hostmonitor.models import Host class Command(BaseCommand): args = '<target target ...>' help = 'Add the specified hosts or CIDR networks (not network/broadcast)' def add_host(sel...
import socket from django.core.management.base import BaseCommand, CommandError from django.db.utils import IntegrityError from iptools import validate_ip, validate_cidr, IpRange from hostmonitor.models import Host def resolve_dns(name): return set([x[4][0] for x in socket.getaddrinfo(name, 80)]) class Comman...
Support adding hosts by DNS
Support adding hosts by DNS
Python
mit
kapsiry/vahti
6f0519eebb8449fdc384bdfdd724405cb06b45eb
main.py
main.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from website.app import init_app app = init_app('website.settings', set_backends=True, routes=True) if __name__ == '__main__': app.run(host='127.0.0.1', port=5000)
#!/usr/bin/env python # -*- coding: utf-8 -*- import os from website.app import init_app app = init_app('website.settings', set_backends=True, routes=True) if __name__ == '__main__': host = os.environ.get('OSF_HOST', None) port = os.environ.get('OSF_PORT', None) app.run(host=host, port=port)
Make host and port configurable thru envvars
Make host and port configurable thru envvars
Python
apache-2.0
alexschiller/osf.io,binoculars/osf.io,sbt9uc/osf.io,adlius/osf.io,MerlinZhang/osf.io,samanehsan/osf.io,monikagrabowska/osf.io,ZobairAlijan/osf.io,dplorimer/osf,samchrisinger/osf.io,zachjanicki/osf.io,samchrisinger/osf.io,leb2dg/osf.io,zkraime/osf.io,petermalcolm/osf.io,chrisseto/osf.io,mfraezz/osf.io,hmoco/osf.io,Cente...
4f0c3e800fbbfab2d576a82b5a1db20d7feb676e
linked_accounts/authentication.py
linked_accounts/authentication.py
from django.http import HttpResponse from django.template import loader from django.utils.crypto import salted_hmac, constant_time_compare from django.contrib.auth.models import User class HMACAuth(object): def __init__(self, realm='API'): self.realm = realm def process_request(self, request): ...
from django.http import HttpResponse from django.template import loader from django.utils.crypto import salted_hmac, constant_time_compare from django.contrib.auth.models import User class HMACAuth(object): def __init__(self, realm='API'): self.realm = realm def process_request(self, request): ...
Return is_authenticated true if we got user and it is active
Return is_authenticated true if we got user and it is active
Python
mit
zen4ever/django-linked-accounts,zen4ever/django-linked-accounts
ba3210b802c9cc1395edee1ad84cea025cc275cf
regconfig/reg_d.py
regconfig/reg_d.py
#### Regulation D INCLUDE_DEFINITIONS_IN_PART_1004 = [ ('Alternative mortgage transaction', 'Alternative mortgage transaction'), ('Creditor', 'Creditor'), ('State', 'State'), ('State law', 'State law'), ] PARAGRAPH_HIERARCHY_1004 = { '1004.2': [ 1, 1, 2, 2, 2, 1, ...
#### Regulation D INCLUDE_DEFINITIONS_IN_PART_1004 = [ ('Creditor', 'Creditor shall have the same meaning as in 12 CFR 226.2'), ] PARAGRAPH_HIERARCHY_1004 = { '1004.2': [ 1, 1, 2, 2, 2, 1, 1, 2, 2, 2, 2, 1, 1, ], }
Fix reg d included definitions
Fix reg d included definitions
Python
cc0-1.0
cfpb/regulations-configs,ascott1/regulations-configs,grapesmoker/regulations-configs
e6acee0000b68bf57a59d13bda0ca3b547d11c2b
tests/acceptance/test_dcos_command.py
tests/acceptance/test_dcos_command.py
from shakedown import * def test_run_command(): exit_status, output = run_command(master_ip(), 'cat /etc/motd') assert exit_status def test_run_command_on_master(): exit_status, output = run_command_on_master('uname -a') assert exit_status assert output.startswith('Linux') def test_run_command_o...
from shakedown import * def test_run_command(): exit_status, output = run_command(master_ip(), 'cat /etc/motd') assert exit_status def test_run_command_on_master(): exit_status, output = run_command_on_master('uname -a') assert exit_status assert output.startswith('Linux') def test_run_command_o...
Make test_run_command_on_agent connect to all agents
Make test_run_command_on_agent connect to all agents Increase testing of SSH connection handling by connecting to all agents in the cluster.
Python
apache-2.0
dcos/shakedown
db4620130cf8444dec7c42bc1f907acdec89dfed
maws.py
maws.py
#!/usr/bin/python3 import argparse import sys from mawslib.manager import Manager configfile="cloudconfig.yaml" parser = argparse.ArgumentParser( #add_help=False, description='AWS Manager', usage='''maws [<options>] <command> <subcommand> [<args>] For help: maws help maws <command> help maws <c...
#!/usr/bin/python3 import argparse import sys from mawslib.manager import Manager import importlib configfile="cloudconfig.yaml" parser = argparse.ArgumentParser( #add_help=False, description='AWS Manager', usage='''maws [<options>] <command> <subcommand> [<args>] For help: maws help maws <command...
Use importlib instead of exec (exec was pretty ugly)
Use importlib instead of exec (exec was pretty ugly)
Python
mit
uva-its/awstools
4851e57059e496b311fb68fc566e47e3d76745fb
string/first-str-substr-occr.py
string/first-str-substr-occr.py
# Implement a function that takes two strings, s and x, as arguments and finds the first occurrence of the string x in s. The function should return an integer indicating the index in s of the first occurrence of x. If there are no occurrences of x in s, return -1 def find_substring(string, substr): string_len = len(...
# Implement a function that takes two strings, s and x, as arguments and finds the first occurrence of the string x in s. The function should return an integer indicating the index in s of the first occurrence of x. If there are no occurrences of x in s, return -1 def find_substring(string, substr): string_len = len(...
Debug and add first test case
Debug and add first test case
Python
mit
derekmpham/interview-prep,derekmpham/interview-prep
beaa9f56cc76dc9ebd531d84e595420a4037a9a9
tests/factories/user.py
tests/factories/user.py
# -*- coding: utf-8 -*- # Copyright (c) 2016 The Pycroft Authors. See the AUTHORS file. # This file is part of the Pycroft project and licensed under the terms of # the Apache License, Version 2.0. See the LICENSE file for details. import factory from factory.faker import Faker from pycroft.model.user import User from...
# -*- coding: utf-8 -*- # Copyright (c) 2016 The Pycroft Authors. See the AUTHORS file. # This file is part of the Pycroft project and licensed under the terms of # the Apache License, Version 2.0. See the LICENSE file for details. import factory from factory.faker import Faker from pycroft.model.user import User, Roo...
Add correct room_history_entry in UserFactory
Add correct room_history_entry in UserFactory
Python
apache-2.0
agdsn/pycroft,agdsn/pycroft,agdsn/pycroft,agdsn/pycroft,agdsn/pycroft
327d9c762ddbbfb2c90cea347dd5612499ade3d4
tests/setup_teardown.py
tests/setup_teardown.py
import os from skidl import * files_at_start = set([]) def setup_function(f): global files_at_start files_at_start = set(os.listdir('.')) # Make this test directory the library search paths for all ECAD tools for tool_lib_path in lib_search_paths: tool_lib_path = [os.path.dirname(os.path.abs...
import os from skidl import * files_at_start = set([]) def setup_function(f): global files_at_start files_at_start = set(os.listdir('.')) default_circuit.mini_reset() lib_search_paths.clear() lib_search_paths.update({ KICAD: [".", get_filename(".")], SKIDL: [".", get_filename("../s...
Set up library search paths for tests.
Set up library search paths for tests. When running tests, exclusively use the libraries that are either built-in, or are provided with the test suite.
Python
mit
xesscorp/skidl,xesscorp/skidl
6ef2973fe269ec17d607f63b565ac3a82ff86c0a
examples/treeping64.py
examples/treeping64.py
#!/usr/bin/python "Create a 64-node tree network, and test connectivity using ping." from mininet.log import setLogLevel from mininet.net import init, Mininet from mininet.node import KernelSwitch, UserSwitch, OVSKernelSwitch from mininet.topolib import TreeNet def treePing64(): "Run ping test on 64-node tree ne...
#!/usr/bin/python "Create a 64-node tree network, and test connectivity using ping." from mininet.log import setLogLevel from mininet.net import init, Mininet from mininet.node import KernelSwitch, UserSwitch, OVSKernelSwitch from mininet.topolib import TreeNet def treePing64(): "Run ping test on 64-node tree ne...
Use switches rather than switches.keys().
Use switches rather than switches.keys(). Minor cosmetic change, really.
Python
bsd-3-clause
mininet/mininet,mininet/mininet,mininet/mininet
9188c2bd910d86a4dc2e57c991d9ce21aecc3316
malcolm/core/vmetas/choicemeta.py
malcolm/core/vmetas/choicemeta.py
from malcolm.compat import str_ from malcolm.core.serializable import Serializable, deserialize_object from malcolm.core.vmeta import VMeta @Serializable.register_subclass("malcolm:core/ChoiceMeta:1.0") class ChoiceMeta(VMeta): """Meta object containing information for a enum""" endpoints = ["description", "...
from malcolm.compat import str_ from malcolm.core.serializable import Serializable, deserialize_object from malcolm.core.vmeta import VMeta @Serializable.register_subclass("malcolm:core/ChoiceMeta:1.0") class ChoiceMeta(VMeta): """Meta object containing information for a enum""" endpoints = ["description", "...
Fix PandA firmware issue with a hack
Fix PandA firmware issue with a hack
Python
apache-2.0
dls-controls/pymalcolm,dls-controls/pymalcolm,dls-controls/pymalcolm
c8a7a53f09f72d9dbe44b1bcb5b85c8ee5ba2c2c
services/migrations/0012_unit_data_source.py
services/migrations/0012_unit_data_source.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('services', '0011_unit_extensions'), ] operations = [ migrations.AddField( model_name='unit', name='d...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('services', '0011_unit_extensions'), ] operations = [ migrations.AddField( model_name='unit', name='d...
Add default to data_source migration.
Add default to data_source migration.
Python
agpl-3.0
City-of-Helsinki/smbackend,City-of-Helsinki/smbackend
c86569d46aac2372107a5e2af66208de8c4a4c1d
kaleo/receivers.py
kaleo/receivers.py
from django.db.models.signals import post_save from django.dispatch import receiver from django.contrib.auth.models import User from account.models import SignupCodeResult, EmailConfirmation from account.signals import signup_code_used, email_confirmed from kaleo.models import JoinInvitation, InvitationStat @recei...
from django.db.models.signals import post_save from django.dispatch import receiver from django.contrib.auth.models import User from account.models import SignupCodeResult, EmailConfirmation from account.signals import signup_code_used, email_confirmed, user_signed_up from kaleo.models import JoinInvitation, Invitat...
Handle case where a user skips email confirmation
Handle case where a user skips email confirmation In DUA, if you are invited to a site and you end up signing up with the same email address, DUA will skip the confirmation cycle and count it as confirmed already.
Python
bsd-3-clause
JPWKU/kaleo,abramia/kaleo,rizumu/pinax-invitations,ntucker/kaleo,jacobwegner/pinax-invitations,pinax/pinax-invitations,eldarion/kaleo
d12884572175cc74ea9e410909128e590a29d1d8
pygments/styles/igor.py
pygments/styles/igor.py
from pygments.style import Style from pygments.token import Keyword, Name, Comment, String, Error, \ Number, Operator, Generic class IgorStyle(Style): default_style = "" styles = { Comment: 'italic #FF0000', Keyword: '#0000FF', Name.Function: ...
from pygments.style import Style from pygments.token import Keyword, Name, Comment, String, Error, \ Number, Operator, Generic class IgorStyle(Style): """ Pygments version of the official colors for Igor Pro procedures. """ default_style = "" styles = { Comment: 'italic ...
Add class comment and a custom color for the decorator
Add class comment and a custom color for the decorator
Python
bsd-2-clause
spencerlyon2/pygments,spencerlyon2/pygments,spencerlyon2/pygments,spencerlyon2/pygments,spencerlyon2/pygments,spencerlyon2/pygments,spencerlyon2/pygments,spencerlyon2/pygments,spencerlyon2/pygments,spencerlyon2/pygments,spencerlyon2/pygments,spencerlyon2/pygments,spencerlyon2/pygments,spencerlyon2/pygments,spencerlyon2...
27839484173c4d505ddb9f949da3576f180b8266
tests/test_short_url.py
tests/test_short_url.py
# -*- coding: utf-8 -*- from random import randrange from pytest import raises import short_url def test_custom_alphabet(): encoder = short_url.UrlEncoder(alphabet='ab') url = encoder.encode_url(12) assert url == 'bbaaaaaaaaaaaaaaaaaaaa' key = encoder.decode_url('bbaaaaaaaaaaaaaaaaaaaa') ass...
# -*- coding: utf-8 -*- import os from random import randrange from pytest import raises import short_url TEST_DATA = os.path.dirname(os.path.abspath(os.path.dirname(__file__))) TEST_DATA = os.path.join(TEST_DATA, 'tests/data') def generate_test_data(count=10000): result = {} for i in range(1000): ...
Add function for generating test data
Add function for generating test data
Python
mit
Alir3z4/python-short_url