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
179365edffa9333afaed71568d89ab5c57607c42
vinepy/utils.py
vinepy/utils.py
from datetime import datetime def strptime(string, fmt='%Y-%m-%dT%H:%M:%S.%f'): return datetime.strptime(string, fmt) # From http://stackoverflow.com/a/14620633 # CAUTION: it causes memory leak in < 2.7.3 and < 3.2.3 class AttrDict(dict): def __init__(self, *args, **kwargs): super(AttrDict, self).__in...
from datetime import datetime def strptime(string, fmt='%Y-%m-%dT%H:%M:%S.%f'): return datetime.strptime(string, fmt) # From http://stackoverflow.com/a/14620633 # CAUTION: it causes memory leak in < 2.7.3 and < 3.2.3 class AttrDict(dict): def __init__(self, *args, **kwargs): super(AttrDict, self).__in...
Add util to convert between short and long postId formats
Add util to convert between short and long postId formats
Python
mit
davoclavo/vinepy
2565df456ecb290f620ce4dadca19c76b0eeb1af
widgets/card.py
widgets/card.py
# -*- coding: utf-8 -*- from flask import render_template from cache import cache from models.person import Person @cache.memoize(24 * 60 * 60) def card(person_or_id, **kwargs): if isinstance(person_or_id, Person): person = person_or_id else: person = Person.query.filter_by(id=person_or_id)...
# -*- coding: utf-8 -*- from flask import render_template from cache import cache from models.person import Person @cache.memoize(24 * 60 * 60) def card(person_or_id, detailed=False, small=False): if isinstance(person_or_id, Person): person = person_or_id else: person = Person.query.filter_...
Fix a bug in caching
Fix a bug in caching
Python
apache-2.0
teampopong/pokr.kr,teampopong/pokr.kr,teampopong/pokr.kr,teampopong/pokr.kr
4320eecc294fa1233a2ad7b4cdec1e2dc1e83b37
testing/test_simbad.py
testing/test_simbad.py
import pytest import vcr try: from unittest import mock except ImportError: import mock from k2catalogue.models import EPIC, create_session from k2catalogue.simbad import Simbad @pytest.fixture def session(): return create_session() @pytest.fixture def epic(session): return session.query(EPIC).filt...
import pytest import vcr try: from unittest import mock except ImportError: import mock from k2catalogue.models import EPIC, create_session from k2catalogue.simbad import Simbad @pytest.fixture def session(): return create_session() @pytest.fixture def epic(session): return mock.Mock(ra=123.456, de...
Remove real database during testing
Remove real database during testing
Python
mit
mindriot101/k2catalogue
8ae44c3645eb6ec0bc0063299a193c14280430c7
tests/capstone/policy/test_greedy.py
tests/capstone/policy/test_greedy.py
import unittest from capstone.policy import GreedyPolicy from capstone.util import play_match class FakeEnv(object): def __init__(self): self._actions = [] def cur_state(self): return 'FakeState' def actions(self, state): return self._actions class TestGreedy(unittest.TestCase...
import unittest from capstone.policy import GreedyPolicy class TestGreedy(unittest.TestCase): def setUp(self): self.policy = GreedyPolicy() def test_max_action(self): state = 1 actions = [1, 5, 8] fake_qf = { (state, 1): 5, (state, 5): 33, ...
Remove FakeEnv from Greedy test suite
Remove FakeEnv from Greedy test suite
Python
mit
davidrobles/mlnd-capstone-code
02af21600824ee1f836e89e825cc94fd1d949628
resolwe/flow/migrations/0046_purge_data_dependencies.py
resolwe/flow/migrations/0046_purge_data_dependencies.py
# Generated by Django 2.2.15 on 2020-09-21 11:38 from django.db import migrations from resolwe.flow.utils import iterate_fields def purge_data_dependencies(apps, schema_editor): Data = apps.get_model("flow", "Data") DataDependency = apps.get_model("flow", "DataDependency") for data in Data.objects.iter...
# Generated by Django 2.2.15 on 2020-09-21 11:38 from django.db import migrations from resolwe.flow.utils import iterate_fields def purge_data_dependencies(apps, schema_editor): Data = apps.get_model("flow", "Data") DataDependency = apps.get_model("flow", "DataDependency") for data in Data.objects.iter...
Fix migration to use actual value instead of non-existing attribute
Fix migration to use actual value instead of non-existing attribute
Python
apache-2.0
genialis/resolwe,genialis/resolwe
9934fefe478bfa99bc8998ea5021700696160444
sale_payment_method_automatic_workflow/__openerp__.py
sale_payment_method_automatic_workflow/__openerp__.py
# -*- coding: utf-8 -*- ############################################################################## # # Author: Guewen Baconnier # Copyright 2015 Camptocamp SA # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # pu...
# -*- coding: utf-8 -*- ############################################################################## # # Author: Guewen Baconnier # Copyright 2015 Camptocamp SA # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # pu...
Correct author list, add OCA
Correct author list, add OCA
Python
agpl-3.0
Endika/e-commerce,BT-fgarbely/e-commerce,cloud9UG/e-commerce,JayVora-SerpentCS/e-commerce,BT-ojossen/e-commerce,Antiun/e-commerce,brain-tec/e-commerce,raycarnes/e-commerce,BT-ojossen/e-commerce,raycarnes/e-commerce,vauxoo-dev/e-commerce,damdam-s/e-commerce,Antiun/e-commerce,jt-xx/e-commerce,brain-tec/e-commerce,JayVora...
0d7f93a787dcf723d79e9122702833c4942f09cc
photo/qt/image.py
photo/qt/image.py
"""Provide the class Image corresponding to an IdxItem. """ import os.path import re from PySide import QtGui class ImageNotFoundError(Exception): pass class Image(object): def __init__(self, basedir, item): self.item = item self.fileName = os.path.join(basedir, item.filename) self...
"""Provide the class Image corresponding to an IdxItem. """ import os.path import re from PySide import QtGui class ImageNotFoundError(Exception): pass class Image(object): def __init__(self, basedir, item): self.item = item self.fileName = os.path.join(basedir, item.filename) self...
Store the rotation matrix corresponding to the orientation in the item.
Store the rotation matrix corresponding to the orientation in the item.
Python
apache-2.0
RKrahl/photo-tools
1cf7b11cdb12a135f2dfa99d7e625eb160b0d7c2
apps/orders/models.py
apps/orders/models.py
from django.db import models # Create your models here.
from django.db import models from ..shop.models import Product class Order(models.Model): first_name = models.CharField(verbose_name="Ім,я", max_length=50) last_name = models.CharField(verbose_name="Прізвище", max_length=50) email = models.EmailField(verbose_name="Email") address = models.CharField(v...
Create Order and OrderItem Models
Create Order and OrderItem Models
Python
mit
samitnuk/online_shop,samitnuk/online_shop,samitnuk/online_shop
e5c5d7fae40eee638175c180c9cc7317d4bfe4b3
scripts/migration/migrate_date_modified_for_existing_nodes.py
scripts/migration/migrate_date_modified_for_existing_nodes.py
""" This will add a date_modified field to all nodes. Date_modified will be equivalent to the date of the last log. """ import sys import logging from modularodm import Q from website.app import init_app from website import models from scripts import utils as script_utils from framework.transactions.context import Tok...
""" This will add a date_modified field to all nodes. Date_modified will be equivalent to the date of the last log. """ import sys import logging from modularodm import Q from website.app import init_app from website import models from scripts import utils as script_utils from framework.transactions.context import Tok...
Fix migration; work around node whose files were unmigrated
Fix migration; work around node whose files were unmigrated [skip ci]
Python
apache-2.0
cwisecarver/osf.io,cslzchen/osf.io,baylee-d/osf.io,crcresearch/osf.io,TomHeatwole/osf.io,kwierman/osf.io,KAsante95/osf.io,acshi/osf.io,zachjanicki/osf.io,mluo613/osf.io,kwierman/osf.io,chennan47/osf.io,RomanZWang/osf.io,KAsante95/osf.io,asanfilippo7/osf.io,chrisseto/osf.io,mluke93/osf.io,emetsger/osf.io,amyshi188/osf.i...
ab2d1296dd189016daa8012fc80d821d1b71486c
telephony/radio_station.py
telephony/radio_station.py
import time from rootio.radio.models import Station from call_handler import CallHandler from program_handler import ProgramHandler from community_menu import CommunityMenu class RadioStation: def run(self): self.__program_handler.run() while True: time.sleep(1) return ...
import time from rootio.radio.models import Station from call_handler import CallHandler from program_handler import ProgramHandler from community_menu import CommunityMenu class RadioStation: def run(self): self.__program_handler.run() while True: time.sleep(1) return ...
Fix no id property for RadioStation
Fix no id property for RadioStation
Python
agpl-3.0
rootio/rootio_web,rootio/rootio_web,rootio/rootio_web,rootio/rootio_web
18374ff4e3906f704276bb0a7b5a5feae50875a2
aspy/yaml/__init__.py
aspy/yaml/__init__.py
from __future__ import absolute_import from __future__ import unicode_literals from collections import OrderedDict import yaml # Adapted from http://stackoverflow.com/a/21912744/812183 class OrderedLoader(yaml.loader.Loader): pass OrderedLoader.add_constructor( yaml.resolver.BaseResolver.DEFAULT_MAPPING_...
from __future__ import absolute_import from __future__ import unicode_literals from collections import OrderedDict import yaml # Adapted from http://stackoverflow.com/a/21912744/812183 class OrderedLoader(getattr(yaml, 'CSafeLoader', yaml.SafeLoader)): pass OrderedLoader.add_constructor( yaml.resolver.Ba...
Use the C Loader/Dumper when available
Use the C Loader/Dumper when available
Python
mit
asottile/aspy.yaml
942b5603da12f43395c0fba35ffd34a31462a023
schedule.py
schedule.py
#!/usr/bin/python print "(set-info :status unknown)" print "(set-option :produce-models true)" print "; Logic is now \"Whatever Z3 accepts\" (set-logic AUFBV)" print "" # Configurable number of enum members print "(declare-datatypes () ((TEAM " for i in range(12): print "t{0}".format(i), print ")"
#!/usr/bin/python print "(set-info :status unknown)" print "(set-option :produce-models true)" print "; Logic is now \"Whatever Z3 accepts\" (set-logic AUFBV)" print "" # Configurable number of enum members print "(declare-datatypes () ((TEAM " for i in range(12): print "t{0}".format(i), print ")" # The uninterpr...
Define an uninterpreted scheduling function
Define an uninterpreted scheduling function
Python
bsd-2-clause
jmorse/numbness
5a6b903fc0a309d61e02d020f46ebf2d6c482ed3
tests/factory_tests/test_images.py
tests/factory_tests/test_images.py
from io import BufferedReader, BytesIO import factory from django.core.files import File from incuna_test_utils.factories import images def test_local_file_field(): class FileFactory(factory.StubFactory): file = images.LocalFileField() file = FileFactory.build().file assert isinstance(file, Fil...
from io import BufferedReader, BytesIO import factory from django.core.files import File from incuna_test_utils.factories import images # In Python 2 Django's File wraps the builtin `file`, but that doesn't exist in Python 3. try: FILE_TYPE = file except NameError: FILE_TYPE = BufferedReader def test_loca...
Fix the file type asserts on Python 2 (I hope).
Fix the file type asserts on Python 2 (I hope).
Python
bsd-2-clause
incuna/incuna-test-utils,incuna/incuna-test-utils
6423bb87a392bf6f8abd3b04a0a1bab3181542a0
run_time/src/gae_server/font_mapper.py
run_time/src/gae_server/font_mapper.py
""" Copyright 2014 Google 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 law or ...
""" Copyright 2014 Google 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 law or ...
Add support for NotoSans and Arimo.
Add support for NotoSans and Arimo.
Python
apache-2.0
googlefonts/TachyFont,googlei18n/TachyFont,moyogo/tachyfont,googlei18n/TachyFont,moyogo/tachyfont,bstell/TachyFont,bstell/TachyFont,bstell/TachyFont,moyogo/tachyfont,googlefonts/TachyFont,googlei18n/TachyFont,googlei18n/TachyFont,googlei18n/TachyFont,moyogo/tachyfont,googlefonts/TachyFont,bstell/TachyFont,googlefonts/T...
691ccb9e99240f36ab954974e1ecbdea61c4c7b6
datagroupings/templatetags/key.py
datagroupings/templatetags/key.py
import json from django import template register = template.Library() @register.filter(name='key') def key(d, key_name): if key_name in d: return d[key_name] return '' @register.filter(name='value') def value(d, key_name): if key_name in d: return d[key_name] return '' @register...
import json from django import template register = template.Library() @register.filter(name='key') def key(d, key_name): if d is not None: if key_name in d: return d[key_name] return '' @register.filter(name='value') def value(d, key_name): if d is not None: if key_name in ...
Fix TemplateTag issue with filters
Fix TemplateTag issue with filters
Python
apache-2.0
nagyistoce/geokey,nagyistoce/geokey,nagyistoce/geokey
1e84e4f8cadd6f776bde4b64839a7e919cb95228
website/addons/s3/tests/factories.py
website/addons/s3/tests/factories.py
# -*- coding: utf-8 -*- """Factories for the S3 addon.""" from factory import SubFactory, Sequence from tests.factories import ModularOdmFactory, UserFactory, ProjectFactory, ExternalAccountFactory from website.addons.s3.model import ( S3UserSettings, S3NodeSettings ) class S3AccountFactory(ExternalAccountFac...
# -*- coding: utf-8 -*- """Factories for the S3 addon.""" from factory import SubFactory, Sequence from tests.factories import ModularOdmFactory, UserFactory, ProjectFactory, ExternalAccountFactory from website.addons.s3.model import ( S3UserSettings, S3NodeSettings ) class S3AccountFactory(ExternalAccountFac...
Use newer factory-boy Meta syntax for s3
Use newer factory-boy Meta syntax for s3
Python
apache-2.0
mluke93/osf.io,mattclark/osf.io,abought/osf.io,adlius/osf.io,laurenrevere/osf.io,kch8qx/osf.io,RomanZWang/osf.io,chrisseto/osf.io,asanfilippo7/osf.io,hmoco/osf.io,caseyrollins/osf.io,rdhyee/osf.io,brianjgeiger/osf.io,zamattiac/osf.io,alexschiller/osf.io,kch8qx/osf.io,mfraezz/osf.io,alexschiller/osf.io,pattisdr/osf.io,S...
d314504621b3b0d36d8248a4ef36d089cd593108
153957_theme/theme.py
153957_theme/theme.py
"""Use the 153957-theme as theme for the gallery""" from pathlib import Path from sigal import signals def get_path(): return str(Path(__file__).resolve().parent) def theme(gallery): """Set theme settings to this theme""" gallery.settings['theme'] = get_path() def register(settings): signals.ga...
"""Use the 153957-theme as theme for the gallery""" from pathlib import Path from shutil import rmtree from sigal import signals def get_path(): return str(Path(__file__).resolve().parent) def theme(gallery): """Set theme settings to this theme""" gallery.settings['theme'] = get_path() def remove_l...
Remove leaflet static files included by default by sigal
Remove leaflet static files included by default by sigal Leaflet is not used by this theme, those static files are unnecessary.
Python
mit
153957/153957-theme,153957/153957-theme
57ca59e225119a031dee6b0c10a27c43a41f56ce
settings.py
settings.py
# ##### BEGIN AGPL LICENSE BLOCK ##### # This file is part of SimpleMMO. # # Copyright (C) 2011, 2012 Charles Nelson # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of...
# ##### BEGIN AGPL LICENSE BLOCK ##### # This file is part of SimpleMMO. # # Copyright (C) 2011, 2012 Charles Nelson # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of...
Add a zone port range.
Add a zone port range.
Python
agpl-3.0
cnelsonsic/SimpleMMO,cnelsonsic/SimpleMMO,cnelsonsic/SimpleMMO
2a6e7ffdfcaa916557da2e65ad23d3789d430dbd
doc/examples/plot_rag_draw.py
doc/examples/plot_rag_draw.py
""" ====================================== Drawing Region Adjacency Graphs (RAGs) ====================================== This example constructs a Region Adjacency Graph (RAG) and draws it with the `rag_draw` method. """ from skimage import data, segmentation from skimage.future import graph from matplotlib import pyp...
""" ====================================== Drawing Region Adjacency Graphs (RAGs) ====================================== This example constructs a Region Adjacency Graph (RAG) and draws it with the `rag_draw` method. """ from skimage import data, segmentation from skimage.future import graph from matplotlib import pyp...
Replace cubehelix with the viridis colormap in the RAG drawing example
Replace cubehelix with the viridis colormap in the RAG drawing example
Python
bsd-3-clause
rjeli/scikit-image,paalge/scikit-image,oew1v07/scikit-image,ClinicalGraphics/scikit-image,WarrenWeckesser/scikits-image,vighneshbirodkar/scikit-image,emon10005/scikit-image,rjeli/scikit-image,Midafi/scikit-image,blink1073/scikit-image,rjeli/scikit-image,youprofit/scikit-image,jwiggins/scikit-image,ajaybhat/scikit-image...
38bc8c8599d4165485ada8ca0b55dafd547385c4
runserver.py
runserver.py
import sys from swift.common.utils import parse_options from swift.common.wsgi import run_wsgi if __name__ == '__main__': conf_file, options = parse_options() sys.exit(run_wsgi(conf_file, 'proxy-server', **options))
import sys from optparse import OptionParser from swift.common.utils import parse_options from swift.common.wsgi import run_wsgi def run_objgraph(types): import objgraph import os import random objgraph.show_most_common_types(limit=50, shortnames=False) for type_ in types: count = objgraph...
Allow to run objgraph before exiting
Allow to run objgraph before exiting Use "--objgraph" to show most common types. Add "--show-backrefs <some type>" do draw a graph of backreferences.
Python
apache-2.0
open-io/oio-swift,open-io/oio-swift
2280d17fc2c6c144c1490617811b4665d5d41545
tests/unit/test_context.py
tests/unit/test_context.py
# Copyright 2011 OpenStack Foundation. # 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 req...
# Copyright 2011 OpenStack Foundation. # 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 req...
Use oslotest instead of common test module
Use oslotest instead of common test module Module openstack.common.test is obsolete, so we should use oslotest library instead of it. Modified tests and common database code, new requirement added. Change-Id: I853e548f11a4c3785eaf75124510a6d789536634
Python
apache-2.0
varunarya10/oslo.context,JioCloud/oslo.context,dims/oslo.context,citrix-openstack-build/oslo.context,openstack/oslo.context,yanheven/oslo.middleware
03f3ee254c2a1c4ebd91728263b66ff29e8b4f78
defenses/torch/audio/input_tranformation/resampling.py
defenses/torch/audio/input_tranformation/resampling.py
import torchaudio import librosa # resampling reference https://core.ac.uk/download/pdf/228298313.pdf # resampling input transformation defense for audio T = torchaudio.transforms # Read audio file audio_data = librosa.load(files, sr=16000)[0][-19456:] audio_data = torch.tensor(audio_data).float().to(device) # Di...
import torchaudio import librosa # There exist a limitation of this defense that it may lead to the problem of aliasing, and we can use the narrowband sample rate # rather than downsampling followed by upsampling. # resampling reference https://core.ac.uk/download/pdf/228298313.pdf # resampling input transformation de...
Add limitation of this defence in the comment
Add limitation of this defence in the comment
Python
mit
cleverhans-lab/cleverhans,cleverhans-lab/cleverhans,cleverhans-lab/cleverhans
1f3dc9aee3a73582c75ac14ef079f2cf970537e6
service_config.py
service_config.py
# This is the config file for the pegasus service. Save a copy of it in # one of the following locations: # # 1. $PWD/service_config.py # 2. ~/.pegasus/service_config.py # 3. /etc/pegasus/service_config.py # # The first file found is the one that will be used. # import os # The secret key used by Flask to encryp...
# This is the config file for the pegasus service. Save a copy of it in # one of the following locations: # # 1. $PWD/service_config.py # 2. ~/.pegasus/service_config.py # 3. /etc/pegasus/service_config.py # # The first file found is the one that will be used. # import os # The secret key used by Flask to encryp...
Update configuration options for Flask-SQLAlchemy
Update configuration options for Flask-SQLAlchemy
Python
apache-2.0
pegasus-isi/pegasus-service,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus-service,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus-service,pegasus-isi/pegasus
3929484162d4fde2b71100a1d0b6265f40499b59
plugins/anime_planet.py
plugins/anime_planet.py
from motobot import command @command('rr') def rr_command(message, database): return "If you are looking for anime/manga recommendations we have a database created specifically for that! Just visit www.anime-planet.com and let us do the hard work for you! For channel rules, please go to http://bit.ly/1aRaMhh"
from motobot import command from requests import get from bs4 import BeautifulSoup @command('rr') def rr_command(message, database): return "If you are looking for anime/manga recommendations we have a database created specifically for that! Just visit www.anime-planet.com and let us do the hard work for you! For...
Add search functions (currently disabled)
Add search functions (currently disabled)
Python
mit
Motoko11/MotoBot
6ab6d1ddfd0a8a94956223014af634e4768f57bd
vdirsyncer/utils/compat.py
vdirsyncer/utils/compat.py
# -*- coding: utf-8 -*- import sys PY2 = sys.version_info[0] == 2 if PY2: # pragma: no cover import urlparse from urllib import \ quote as urlquote, \ unquote as urlunquote text_type = unicode # flake8: noqa iteritems = lambda x: x.iteritems() itervalues = lambda x: x.iterval...
# -*- coding: utf-8 -*- import sys PY2 = sys.version_info[0] == 2 if sys.version_info < (3, 3) and sys.version_info[:2] != (2, 7): raise RuntimeError( 'vdirsyncer only works on Python versions 2.7.x and 3.3+' ) if PY2: # pragma: no cover import urlparse from urllib import \ quote ...
Check Python version at runtime
Check Python version at runtime
Python
mit
hobarrera/vdirsyncer,tribut/vdirsyncer,credativUK/vdirsyncer,untitaker/vdirsyncer,hobarrera/vdirsyncer,tribut/vdirsyncer,untitaker/vdirsyncer,credativUK/vdirsyncer,untitaker/vdirsyncer
ecbbc523ab3349a3f05403c06106b41562f9ca03
fireplace/cards/game/all.py
fireplace/cards/game/all.py
# The Coin class GAME_005: def play(self): self.controller.temp_mana += 1
""" GAME set and other special cards """ from ..utils import * # The Coin class GAME_005: play = ManaThisTurn(CONTROLLER, 1)
Use ManaThisTurn action for The Coin
Use ManaThisTurn action for The Coin
Python
agpl-3.0
butozerca/fireplace,smallnamespace/fireplace,Meerkov/fireplace,amw2104/fireplace,Ragowit/fireplace,amw2104/fireplace,NightKev/fireplace,liujimj/fireplace,butozerca/fireplace,Meerkov/fireplace,smallnamespace/fireplace,jleclanche/fireplace,oftc-ftw/fireplace,beheh/fireplace,Ragowit/fireplace,liujimj/fireplace,oftc-ftw/fi...
c22554f7979d07be881db5cb27c249581f99ce5a
nflpool/data/secret-config.py
nflpool/data/secret-config.py
from nflpool.data.dbsession import DbSessionFactory # You will need an account from MySportsFeed to access their API. They offer free access to developers # Edit below with your credentials and then save as secret.py msf_username = 'YOURUSERNAME' msf_pw = 'YOURPASSWORD' su_email = '' slack_webhook_url = ''
from nflpool.data.dbsession import DbSessionFactory # You will need an account from MySportsFeed to access their API. They offer free access to developers # Edit below with your credentials and then save as secret.py msf_username = 'YOURUSERNAME' msf_pw = 'YOURPASSWORD' su_email = '' slack_webhook_url = '' msf_a...
Add the MSF API key and password fields
Add the MSF API key and password fields
Python
mit
prcutler/nflpool,prcutler/nflpool
7e2c31d748b458b96b0d31c40868e538727862eb
Lib/hotshot/stones.py
Lib/hotshot/stones.py
import errno import hotshot import hotshot.stats import os import sys import test.pystone if sys.argv[1:]: logfile = sys.argv[1] else: import tempfile logf = tempfile.NamedTemporaryFile() logfile = logf.name p = hotshot.Profile(logfile) benchtime, stones = p.runcall(test.pystone.pystones) p.close() ...
import errno import hotshot import hotshot.stats import os import sys import test.pystone def main(logfile): p = hotshot.Profile(logfile) benchtime, stones = p.runcall(test.pystone.pystones) p.close() print "Pystone(%s) time for %d passes = %g" % \ (test.pystone.__version__, test.pystone.LOO...
Move testing code into "if __name__ == '__main__'" so it's not run on import.
Move testing code into "if __name__ == '__main__'" so it's not run on import.
Python
mit
sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator
dc56d2634f05ec57ba594c5c70193d2b113c53e5
Mathematics/Fundamentals/jim-and-the-jokes.py
Mathematics/Fundamentals/jim-and-the-jokes.py
# Python 2 # Enter your code here. Read input from STDIN. Print output to STDOUT def base(m,d): # Converts d (base m) to its decimal equivalent result = 0 c = 1 while(d > 0): x = d%10 if(x >= m): return -1 d /= 10 result += x*c c *= m r...
# Python 2 # Enter your code here. Read input from STDIN. Print output to STDOUT def base(m,d): # Converts d (base m) to its decimal equivalent result = 0 c = 1 while(d > 0): x = d%10 if(x >= m): return -1 d /= 10 result += x*c c *= m r...
Fix code to deal with large numbers
Fix code to deal with large numbers
Python
mit
ugaliguy/HackerRank,ugaliguy/HackerRank,ugaliguy/HackerRank
c4e0bc68db9e0e897c51181e5dd23370a7a08734
pypocketexplore/jobs.py
pypocketexplore/jobs.py
from datetime import datetime import requests as req from pymongo import MongoClient from pypocketexplore.config import MONGO_URI from time import sleep def extract_topic_items(topic): db = MongoClient(MONGO_URI).get_default_database() data = req.get('http://localhost:5000/api/topic/{}'.format(topic)).json()...
from datetime import datetime import requests as req from pymongo import MongoClient from pypocketexplore.config import MONGO_URI from time import sleep def extract_topic_items(topic): db = MongoClient(MONGO_URI).get_default_database() resp = req.get('http://localhost:5000/api/topic/{}'.format(topic))\ d...
Handle topics with zero elements
Handle topics with zero elements
Python
mit
Florents-Tselai/PyPocketExplore
771c3bead487aa989dd19558bc2a4107abc29b6b
webapp/apps/staff/views.py
webapp/apps/staff/views.py
from django.shortcuts import get_object_or_404, render, redirect from django.shortcuts import render from apps.staff.forms import NewUserForm from django.contrib.auth.models import User from django.contrib import messages def admin_view(request): return render(request, 'staff/base.jinja', {}) def users_new_view(...
from django.shortcuts import get_object_or_404, render, redirect from django.shortcuts import render from apps.staff.forms import NewUserForm from django.contrib.auth.models import User from django.contrib import messages def admin_view(request): return render(request, 'staff/base.jinja', {}) def users_new_view(...
Add more msgs for staff/user/new view
Add more msgs for staff/user/new view
Python
apache-2.0
patrickspencer/compass-python,patrickspencer/compass-python,patrickspencer/compass,patrickspencer/compass-python,patrickspencer/compass-python,patrickspencer/compass-python,patrickspencer/compass,patrickspencer/compass,patrickspencer/compass,patrickspencer/compass
3544f211913ba67f0bd7e433c23d2e5b22bba719
lightcurve_pipeline/database/reset_database.py
lightcurve_pipeline/database/reset_database.py
#! /usr/bin/env python """ Reset all tables in the database. """ from lightcurve_pipeline.database.database_interface import base from lightcurve_pipeline.utils.utils import SETTINGS if __name__ == '__main__': prompt = 'About to reset database instance {}. '.format(SETTINGS['db_connection_string']) prompt +...
#! /usr/bin/env python """ Reset all tables in the database. """ from __future__ import print_function from lightcurve_pipeline.database.database_interface import base from lightcurve_pipeline.utils.utils import SETTINGS if __name__ == '__main__': prompt = 'About to reset database instance {}. '.format(SETTING...
Change the print statement to use __future__.
Change the print statement to use __future__.
Python
bsd-3-clause
justincely/lightcurve_pipeline
62ebb94f09ea2dee3276041bd471502d57078650
mcrouter/test/test_mcrouter_to_mcrouter_tko.py
mcrouter/test/test_mcrouter_to_mcrouter_tko.py
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import re from mcrouter.test.McrouterTestCase import McrouterTestCase class TestMcrouterToMcrouterTko(McrouterTestCas...
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import re import time from mcrouter.test.McrouterTestCase import McrouterTestCase class TestMcrouterToMcrouterTko(Mcr...
Fix flaky mcrouter tko tests
Fix flaky mcrouter tko tests Summary: As above Reviewed By: edenzik Differential Revision: D25722019 fbshipit-source-id: 06ff9200e99f3580db25fef9ca5ab167c50b97ed
Python
mit
facebook/mcrouter,facebook/mcrouter,facebook/mcrouter,facebook/mcrouter
5fdd28a4707c8dcc9fe9ef3607742e6856725288
examples/connect4/connect4.py
examples/connect4/connect4.py
class Connect4(object): def __init__(self): self.pieces = [[] for i in xrange(7)] self.turn = 0 def move(self, column): for i in xrange(column, column + 7): if len(self.pieces[i % 7]) < 6: self.pieces[i % 7].append(self.turn) self.turn = 1 - s...
class Connect4(object): def __init__(self): self.pieces = [[] for i in xrange(7)] self.turn = 0 def move(self, column): for i in xrange(column, column + 7): if len(self.pieces[i % 7]) < 6: self.pieces[i % 7].append(self.turn) self.turn = 1 - s...
Make Connect4's __str__ more readable
Make Connect4's __str__ more readable
Python
mit
tysonzero/py-ann
90ee1f19ad1b99c3960f5b4917d6801cd4d4d607
paypal_registration/models.py
paypal_registration/models.py
from django.db import models # Create your models here.
from django.db import models from registration.models import RegistrationProfile class PaypalRegistrationProfile(RegistrationProfile): paid = models.BooleanField(default=False)
Make a bit more sensible model.
Make a bit more sensible model.
Python
bsd-3-clause
buchuki/django-registration-paypal
4c6c0561743c03ac70d82fc0e7af1a3a135b7c84
test/test_pipeline/components/regression/test_liblinear_svr.py
test/test_pipeline/components/regression/test_liblinear_svr.py
import unittest from autosklearn.pipeline.components.regression.liblinear_svr import \ LibLinear_SVR from autosklearn.pipeline.util import _test_regressor import sklearn.metrics class SupportVectorComponentTest(unittest.TestCase): def test_default_configuration(self): for i in range(10): ...
import unittest from autosklearn.pipeline.components.regression.liblinear_svr import \ LibLinear_SVR from autosklearn.pipeline.util import _test_regressor import sklearn.metrics class SupportVectorComponentTest(unittest.TestCase): def test_default_configuration(self): for i in range(10): ...
FIX numerical issues in test on travis-ci
FIX numerical issues in test on travis-ci
Python
bsd-3-clause
automl/auto-sklearn,automl/auto-sklearn
1dc7383a2f51c225f0138792eff6d35dc35dac8c
infinite_memcached/tests.py
infinite_memcached/tests.py
import time from django.test import TestCase from infinite_memcached.cache import MemcachedCache class InfiniteMemcached(TestCase): def test_handle_timeouts(self): mc = MemcachedCache( server="127.0.0.1:11211", params={}, ) self.assertEqual(0, mc._get_memcache_timeou...
import time from django.test import TestCase from django.core.cache import get_cache class InfiniteMemcached(TestCase): def test_handle_timeouts(self): mc = get_cache('infinite_memcached.cache.MemcachedCache', LOCATION='127.0.0.1:11211') self.assertEqual(0, mc._get_memcache_...
Load the backend with get_cache
Load the backend with get_cache
Python
bsd-3-clause
edavis/django-infinite-memcached,edavis/django-infinite-memcached
86091dedfe1fc9ececb5c9e36a79866660525e90
ckanext/ckanext-apicatalog_routes/ckanext/apicatalog_routes/tests/test_plugin.py
ckanext/ckanext-apicatalog_routes/ckanext/apicatalog_routes/tests/test_plugin.py
"""Tests for plugin.py.""" def test_plugin(): pass
"""Tests for plugin.py.""" import pytest from ckan.tests import factories import ckan.tests.helpers as helpers from ckan.plugins.toolkit import NotAuthorized @pytest.mark.ckan_config('ckan.plugins', 'apicatalog_routes') @pytest.mark.usefixtures('clean_db', 'with_plugins', 'with_request_context') class Apicatalog_Rout...
Add test for deleting subsystem as normal user
Add test for deleting subsystem as normal user
Python
mit
vrk-kpa/api-catalog,vrk-kpa/api-catalog,vrk-kpa/api-catalog,vrk-kpa/api-catalog
d921858302f8bba715a7f4e63eaec68dfe04927a
app/grandchallenge/workstations/context_processors.py
app/grandchallenge/workstations/context_processors.py
from grandchallenge.workstations.models import Session def workstation_session(request): """ Adds workstation_session. request.user must be set """ s = None if not request.user.is_anonymous: s = ( Session.objects.filter(creator=request.user) .exclude(status__in=[Session.Q...
from grandchallenge.workstations.models import Session def workstation_session(request): """ Adds workstation_session. request.user must be set """ s = None try: if not request.user.is_anonymous: s = ( Session.objects.filter(creator=request.user) .excl...
Handle no user at all
Handle no user at all
Python
apache-2.0
comic/comic-django,comic/comic-django,comic/comic-django,comic/comic-django,comic/comic-django
76dff207a128cb9230d8dceea24d0fb8e174ac3d
exporter/settings.py
exporter/settings.py
# Settings for Exporter module. # Exportable modules. # Modules must be a valid python module, in the import path. EXPORT_MODULES = ('sjtools', 'sjfs', 'utils')
# Settings for Exporter module. # Exportable modules. # Modules must be a valid python module, in the import path. EXPORT_MODULES = ('sjtools', 'sjfs', 'utils', 'sjevents')
Add sjevents to modules exported.
Add sjevents to modules exported.
Python
lgpl-2.1
SmartJog/webengine,SmartJog/webengine
907169a645cd779de1a382dc09765a04c0217206
dyngraph/exporter.py
dyngraph/exporter.py
from __future__ import print_function class Exporter(): def __init__(self, plotinfo, viewbox): self.plotinfo = plotinfo self.viewbox = viewbox def updaterange(self): datalen = self.plotinfo.plotdata.shape[0] vbrange = self.viewbox.viewRange() xmin,xmax = vbrange[0] ...
from __future__ import print_function class Exporter(): def __init__(self, plotinfo, viewbox): self.plotinfo = plotinfo self.viewbox = viewbox def updaterange(self): datalen = self.plotinfo.plotdata.shape[0] vbrange = self.viewbox.viewRange() xmin,xmax = vbrange[0] ...
Remove NA values from export.
Remove NA values from export.
Python
isc
jaj42/GraPhysio,jaj42/dyngraph,jaj42/GraPhysio
355205554a7b95ae81fe7fc04fa65c3a850b3c47
Tools/ecl_ekf/batch_process_logdata_ekf.py
Tools/ecl_ekf/batch_process_logdata_ekf.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import argparse import os """ Runs process_logdata_ekf.py on all the files in the suplied directory with a .ulg extension """ parser = argparse.ArgumentParser(description='Analyse the estimator_status and ekf2_innovation message data for all .ulg files in the specified di...
#!/usr/bin/env python # -*- coding: utf-8 -*- import argparse import os """ Runs process_logdata_ekf.py on all the files in the suplied directory with a .ulg extension """ parser = argparse.ArgumentParser(description='Analyse the estimator_status and ekf2_innovation message data for all .ulg files in the specified di...
Use format to properly format file for process_logdata_parser.py
Use format to properly format file for process_logdata_parser.py
Python
bsd-3-clause
acfloria/Firmware,mje-nz/PX4-Firmware,dagar/Firmware,dagar/Firmware,krbeverx/Firmware,mje-nz/PX4-Firmware,mje-nz/PX4-Firmware,PX4/Firmware,mcgill-robotics/Firmware,jlecoeur/Firmware,krbeverx/Firmware,dagar/Firmware,krbeverx/Firmware,Aerotenna/Firmware,Aerotenna/Firmware,dagar/Firmware,acfloria/Firmware,acfloria/Firmwar...
2a731fba72268c9a07d81c591be608f2292b06cb
byceps/blueprints/core_admin/views.py
byceps/blueprints/core_admin/views.py
# -*- coding: utf-8 -*- """ byceps.blueprints.core_admin.views ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2016 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from ...util.framework import create_blueprint from ..brand.models import Brand blueprint = create_blueprint('core_admin...
# -*- coding: utf-8 -*- """ byceps.blueprints.core_admin.views ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2016 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from ...util.framework import create_blueprint from ..brand import service as brand_service blueprint = create_blueprint...
Move database query assembly and execution from view functions to services ('core_admin' blueprint)
Move database query assembly and execution from view functions to services ('core_admin' blueprint)
Python
bsd-3-clause
homeworkprod/byceps,homeworkprod/byceps,m-ober/byceps,homeworkprod/byceps,m-ober/byceps,m-ober/byceps
c5ef250240cbaa894ee84615c5d07a383bd16962
fluent_contents/plugins/oembeditem/content_plugins.py
fluent_contents/plugins/oembeditem/content_plugins.py
""" Definition of the plugin. """ from django.utils.translation import ugettext_lazy as _ from fluent_contents.extensions import ContentPlugin, plugin_pool from fluent_contents.plugins.oembeditem.forms import OEmbedItemForm from fluent_contents.plugins.oembeditem.models import OEmbedItem @plugin_pool.register class O...
""" Definition of the plugin. """ from django.utils.translation import ugettext_lazy as _ from fluent_contents.extensions import ContentPlugin, plugin_pool from fluent_contents.plugins.oembeditem.forms import OEmbedItemForm from fluent_contents.plugins.oembeditem.models import OEmbedItem import re re_safe = re.compile...
Make sure the OEmbed type can never be used to control filenames.
Make sure the OEmbed type can never be used to control filenames. Minor risk, as it's still a template path, but better be safe then sorry.
Python
apache-2.0
pombredanne/django-fluent-contents,edoburu/django-fluent-contents,jpotterm/django-fluent-contents,ixc/django-fluent-contents,pombredanne/django-fluent-contents,ixc/django-fluent-contents,jpotterm/django-fluent-contents,edoburu/django-fluent-contents,django-fluent/django-fluent-contents,pombredanne/django-fluent-content...
1569da946dbe3010984b90f83382c31750551935
testapp/settings.py
testapp/settings.py
# CQLENGINE settings CQLENGINE_HOSTS= 'localhost:9160'
# CQLENGINE settings CQLENGINE_HOSTS= 'localhost:9160' CQLENGINE_DEFAULT_KEYSPACE = 'flask_cqlengine'
Add setting for CQLENGINE_DEFAULT_KEYSPACE to test app
Add setting for CQLENGINE_DEFAULT_KEYSPACE to test app
Python
apache-2.0
chillinc/Flask-CQLEngine
dbe40d21d6f38cbb0827eeaaaaab425dd9b724ca
tasks/__init__.py
tasks/__init__.py
from celery import Celery from tornado.options import options from tasks.helpers import create_mq_url queue_conf = { 'CELERY_TASK_SERIALIZER': 'json', 'CELERY_ACCEPT_CONTENT': ['json'], 'CELERY_RESULT_SERIALIZER': 'json', 'CELERY_TASK_RESULT_EXPIRES': 3600 } selftest_task_queue = Celery( 'selftes...
from celery import Celery from tornado.options import options from tasks.helpers import create_mq_url queue_conf = { 'CELERY_TASK_SERIALIZER': 'json', 'CELERY_ACCEPT_CONTENT': ['json'], 'CELERY_RESULT_SERIALIZER': 'json', 'CELERY_TASK_RESULT_EXPIRES': 3600 } selftest_task_queue = Celery( 'selftes...
Add tasks to list of mq tasks
Add tasks to list of mq tasks
Python
apache-2.0
BishopFox/SpoofcheckSelfTest,BishopFox/SpoofcheckSelfTest,BishopFox/SpoofcheckSelfTest
8a0953345279c40e3b3cf63a748e8ca7b3ad0199
test_urlconf.py
test_urlconf.py
from django.conf.urls import patterns, url, include from django.contrib import admin admin.autodiscover() urlpatterns = patterns( '', url(r'^admin/', include(admin.site.urls)), )
from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^admin/', include(admin.site.urls)), ]
Test urls - list of urls instead of patterns()
Test urls - list of urls instead of patterns()
Python
isc
yprez/django-logentry-admin,yprez/django-logentry-admin
7923baf30bcd41e17182599e46b4efd86f4eab49
tests/conftest.py
tests/conftest.py
# -*- coding: utf-8 -*- # Copyright (c) 2015-2016 MIT Probabilistic Computing Project # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unles...
# -*- coding: utf-8 -*- # Copyright (c) 2015-2016 MIT Probabilistic Computing Project # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unles...
Stop making --integration an argument.
Stop making --integration an argument.
Python
apache-2.0
probcomp/cgpm,probcomp/cgpm
0b74a76899d4ece2b3d7a8559fdc58c312231174
tests/conftest.py
tests/conftest.py
"""Base for all tests with definitions of fixtures""" import glob import os TEST_DATA_FILES_LOCATION = os.path.join(os.path.dirname(__file__), "data") TEST_DATA_FILES = glob.glob(os.path.join(TEST_DATA_FILES_LOCATION, "*.txt")) DATA_FILES_FIXTURE_NAME = "data_file" def _load_files_contents(*files): for file_ in ...
"""Base for all tests with definitions of fixtures""" import glob import os TEST_DATA_FILES_LOCATION = os.path.join(os.path.dirname(__file__), "data") TEST_DATA_FILES = glob.glob(os.path.join(TEST_DATA_FILES_LOCATION, "*.txt")) DATA_FILES_FIXTURE_NAME = "data_file" def _load_files_contents(*files): for file_ in ...
Add docstring explaining the parametrization of data files
Add docstring explaining the parametrization of data files
Python
mit
rmariano/compr,rmariano/compr
4165ca1eb5ea43c198c86c4dcf2cfbfe4a6b1c6c
run_tests.py
run_tests.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ This is a convenience nose wrapper, for use with 'coverage' and 'setup.py test'; run it using: $ ./run_tests.py You can also pass 'nose' arguments to this script, for instance to run individual tests or to skip redirection of output so 'pdb.set_trace()' works: ...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ This is a convenience nose wrapper, for use with 'coverage' and 'setup.py test'; run it using: $ ./run_tests.py You can also pass 'nose' arguments to this script, for instance to run individual tests or to skip redirection of output so 'pdb.set_trace()' works: ...
Make sure tests run on 'setup.py test'
Make sure tests run on 'setup.py test' Nose was parsing the argv passed to setup.py (oh, global variables). Assume that if 'distutils' are loaded then this is the case; and pass through argv if it isn't. Also, update the suggested commands for the extra requirements.
Python
mit
tomo-otsuka/normalize,hearsaycorp/normalize,samv/normalize
0c21d60108d38f43d22aa03c882a62c93754d5da
tests/test_cli.py
tests/test_cli.py
from mdformat._cli import run UNFORMATTED_MARKDOWN = "\n\n# A header\n\n" FORMATTED_MARKDOWN = "# A header\n" def test_no_files_passed(): assert run(()) == 0 def test_format(tmp_path): file_path = tmp_path / "test_markdown.md" file_path.write_text(UNFORMATTED_MARKDOWN) assert run((str(file_path),))...
from io import StringIO import sys from mdformat._cli import run UNFORMATTED_MARKDOWN = "\n\n# A header\n\n" FORMATTED_MARKDOWN = "# A header\n" def test_no_files_passed(): assert run(()) == 0 def test_format(tmp_path): file_path = tmp_path / "test_markdown.md" file_path.write_text(UNFORMATTED_MARKDOW...
Test read from stdin and write to stdout
Test read from stdin and write to stdout
Python
mit
executablebooks/mdformat
30ea5b30746f12feb7b5915bce180ff4934ae204
problem67.py
problem67.py
import math def blad(): ins = open( "triangles_18.txt", "r" ) arr = [] idx = 0 for line in ins: try: l = [int(x) for x in line.split()] if ( l[idx] < l[idx+1] ): idx += 1 except IndexError: pass arr.append(l[idx]) ins.close() pr...
# Project Euler # problems 18 and 67 def generic(): data = [] ins = open( "triangles.txt", "r" ) for i,line in enumerate(ins): data.insert(0, [int(x) for x in line.split()] ) ins.close() for n,d in enumerate(data): if n == 0: pass else: data[n] = [ max(i+data[n-1][nn], i+data[n-1][nn+1]) ...
Add proper solution for projects 18 and 67
Add proper solution for projects 18 and 67
Python
mit
jakubczaplicki/projecteuler,jakubczaplicki/projecteuler
64745f9dc3e31d55c5b73457b719484384ba0d76
runserver.py
runserver.py
from gepify import create_app app = create_app() if __name__ == "__main__": app.run(host='0.0.0.0')
from gepify import create_app app = create_app() if __name__ == "__main__": app.run(host='0.0.0.0', port=8000)
Set default port to 8000
Set default port to 8000
Python
mit
nvlbg/gepify,nvlbg/gepify
20dbd80d0262869f3378597d7152dab7a6104de8
routes/__init__.py
routes/__init__.py
import threadinglocal, sys if sys.version < '2.4': class _RequestConfig(object): __shared_state = threadinglocal.local() def __getattr__(self, name): return self.__shared_state.__getattr__(name) def __setattr__(self, name, value): return self.__shared_state.__setattr__(name, va...
import threadinglocal, sys if sys.version < '2.4': class _RequestConfig(object): __shared_state = threadinglocal.local() def __getattr__(self, name): return self.__shared_state.__getattr__(name) def __setattr__(self, name, value): return self.__shared_state.__setattr__(name, va...
Tweak for exporting the symbols
[svn] Tweak for exporting the symbols --HG-- branch : trunk
Python
mit
alex/routes,bbangert/routes,mikepk/routes,webknjaz/routes,mikepk/pybald-routes
1bb7ff80906058370839eb22ff2ebc67f11ad09e
django_auth_adfs/rest_framework.py
django_auth_adfs/rest_framework.py
import logging from django.contrib.auth import authenticate from rest_framework import exceptions from rest_framework.authentication import ( BaseAuthentication, get_authorization_header ) logger = logging.getLogger(__name__) class AdfsAccessTokenAuthentication(BaseAuthentication): """ ADFS access Token...
from __future__ import absolute_import import logging from django.contrib.auth import authenticate from rest_framework import exceptions from rest_framework.authentication import ( BaseAuthentication, get_authorization_header ) logger = logging.getLogger(__name__) class AdfsAccessTokenAuthentication(BaseAuthen...
Make sure we don't have a import namespace clash with DRF
Make sure we don't have a import namespace clash with DRF For python 2.7 you need to add from __future__ import absolute_import
Python
bsd-2-clause
jobec/django-auth-adfs,jobec/django-auth-adfs
a67e45347f0119c4e1a3fb55b401a9acce939c7a
script/lib/util.py
script/lib/util.py
#!/usr/bin/env python import sys def get_output_dir(target_arch, component): # Build in "out_component" for component build. output_dir = 'out' if component == 'shared_library': output_dir += '_component' # Build in "out_32" for 32bit target. if target_arch == 'ia32': output_dir += '_32' return ...
#!/usr/bin/env python import sys def get_output_dir(target_arch, component): # Build in "out_component" for component build. output_dir = 'out' if component == 'shared_library': output_dir += '_component' # Build in "out_32" for 32bit target. if target_arch == 'ia32': output_dir += '_32' elif ta...
Fix output dir for arm target
Fix output dir for arm target
Python
mit
atom/libchromiumcontent,eric-seekas/libchromiumcontent,paulcbetts/libchromiumcontent,adamjgray/libchromiumcontent,synaptek/libchromiumcontent,atom/libchromiumcontent,electron/libchromiumcontent,bbondy/libchromiumcontent,hokein/libchromiumcontent,adamjgray/libchromiumcontent,synaptek/libchromiumcontent,hokein/libchromiu...
d27723ed3c3006a5bd9567e992c6d37a9ca0d159
run_tests.py
run_tests.py
#!/usr/bin/env python # This file is closely based on tests.py from matplotlib # # This allows running the matplotlib tests from the command line: e.g. # # $ python tests.py -v -d # # The arguments are identical to the arguments accepted by nosetests. # # See https://nose.readthedocs.org/ for a detailed description o...
#!/usr/bin/env python # This file is closely based on tests.py from matplotlib # # This allows running the matplotlib tests from the command line: e.g. # # $ python tests.py -v -d # # The arguments are identical to the arguments accepted by nosetests. # # See https://nose.readthedocs.org/ for a detailed description o...
Remove coverage on replay; development is suspended.
MNT: Remove coverage on replay; development is suspended.
Python
bsd-3-clause
tacaswell/dataportal,danielballan/datamuxer,NSLS-II/dataportal,danielballan/dataportal,ericdill/databroker,NSLS-II/datamuxer,NSLS-II/dataportal,tacaswell/dataportal,ericdill/databroker,ericdill/datamuxer,danielballan/dataportal,danielballan/datamuxer,ericdill/datamuxer
9bb312c505c2749862372c0ff56ba47e087a9edc
searx/engines/semantic_scholar.py
searx/engines/semantic_scholar.py
# SPDX-License-Identifier: AGPL-3.0-or-later """ Semantic Scholar (Science) """ from json import dumps, loads search_url = 'https://www.semanticscholar.org/api/1/search' def request(query, params): params['url'] = search_url params['method'] = 'POST' params['headers']['content-type'] = 'application/js...
# SPDX-License-Identifier: AGPL-3.0-or-later """ Semantic Scholar (Science) """ from json import dumps, loads search_url = 'https://www.semanticscholar.org/api/1/search' def request(query, params): params['url'] = search_url params['method'] = 'POST' params['headers']['content-type'] = 'application/js...
Remove duplicated key from dict in Semantic Scholar
Remove duplicated key from dict in Semantic Scholar
Python
agpl-3.0
dalf/searx,dalf/searx,dalf/searx,dalf/searx
129081d873a4e812a32b126cd7738b72979a814f
softwareindex/handlers/coreapi.py
softwareindex/handlers/coreapi.py
import requests, json, urllib SEARCH_URL = 'http://core.kmi.open.ac.uk/api/search/' API_KEY = 'FILL THIS IN' def getCOREMentions(identifier, **kwargs): """Return the number of mentions in CORE and a descriptor, as a tuple. Needs an API key, which can be obtained here: http://core.ac.uk/api-keys/register"...
# This is a software index handler that gives a score based on the # number of mentions in open access articles. It uses the CORE # aggregator (http://core.ac.uk/) to search the full text of indexed # articles. # # Inputs: # - identifier (String) # # Outputs: # - score (Number) # - description (String) import reque...
Convert into a class to match the other handlers.
Convert into a class to match the other handlers.
Python
bsd-3-clause
softwaresaved/softwareindex,softwaresaved/softwareindex
98f0313e935db2491a615e868e3bd5da21769c03
gocd/api/pipeline.py
gocd/api/pipeline.py
from gocd.api.endpoint import Endpoint class Pipeline(Endpoint): base_path = 'go/api/pipelines/{id}' id = 'name' def __init__(self, server, name): self.server = server self.name = name def history(self, offset=0): return self._get('/history/{offset:d}'.format(offset=offset or...
from gocd.api.endpoint import Endpoint class Pipeline(Endpoint): base_path = 'go/api/pipelines/{id}' id = 'name' def __init__(self, server, name): self.server = server self.name = name def history(self, offset=0): return self._get('/history/{offset:d}'.format(offset=offset or...
Add trigger as an alias for schedule
Add trigger as an alias for schedule "Have you triggered that pipeline" is a fairly common thing to say.
Python
mit
henriquegemignani/py-gocd,gaqzi/py-gocd
936302bf5db057a01644014aabc1357f925c6afa
mezzanine/accounts/models.py
mezzanine/accounts/models.py
from django.db import DatabaseError, connection from django.db.models.signals import post_save from mezzanine.accounts import get_profile_for_user from mezzanine.conf import settings __all__ = () if getattr(settings, "AUTH_PROFILE_MODULE", None): def create_profile(user_model, instance, created, **kwargs): ...
from django.db import DatabaseError, connection from django.db.models.signals import post_save from mezzanine.accounts import get_profile_for_user from mezzanine.conf import settings __all__ = () if getattr(settings, "AUTH_PROFILE_MODULE", None): def create_profile(**kwargs): if kwargs["created"]: ...
Fix user profile signal handler.
Fix user profile signal handler.
Python
bsd-2-clause
wbtuomela/mezzanine,Cicero-Zhao/mezzanine,gradel/mezzanine,christianwgd/mezzanine,eino-makitalo/mezzanine,frankier/mezzanine,jerivas/mezzanine,Cicero-Zhao/mezzanine,frankier/mezzanine,readevalprint/mezzanine,dsanders11/mezzanine,stephenmcd/mezzanine,frankier/mezzanine,eino-makitalo/mezzanine,ryneeverett/mezzanine,viare...
148ebbb82f824a091ae439f49b543165878eeee4
cloudly/cache.py
cloudly/cache.py
import os import redis as pyredis from cloudly.aws import ec2 from cloudly.memoized import Memoized import cloudly.logger as logger log = logger.init(__name__) @Memoized def get_conn(): """ Get a connection to a Redis server. The priority is: - look for an environment variable REDIS_HOST, else ...
import os import redis as pyredis from cloudly.aws import ec2 from cloudly.memoized import Memoized import cloudly.logger as logger log = logger.init(__name__) @Memoized def get_conn(): """ Get a connection to a Redis server. The priority is: - look for an environment variable REDIS_HOST, else ...
Fix missing auth handler when trying to access EC2.
Fix missing auth handler when trying to access EC2.
Python
mit
ooda/cloudly,ooda/cloudly
54121f2b82950868db596d75e37e12f4c10c3339
troposphere/ce.py
troposphere/ce.py
# Copyright (c) 2020, Mark Peek <mark@peek.org> # All rights reserved. # # See LICENSE file for full license. from . import AWSObject class CostCategory(AWSObject): resource_type = "AWS::CE::CostCategory" props = { 'Name': (basestring, True), 'Rules': (basestring, True), 'RuleVersion...
# Copyright (c) 2012-2021, Mark Peek <mark@peek.org> # All rights reserved. # # See LICENSE file for full license. # # *** Do not modify - this file is autogenerated *** # Resource specification version: 31.0.0 from . import AWSObject from . import AWSProperty from .validators import double class AnomalyMonitor(AWS...
Update CE per 2021-03-11 changes
Update CE per 2021-03-11 changes
Python
bsd-2-clause
cloudtools/troposphere,cloudtools/troposphere
fedf54fba832fd073f1a984e48b4e76400018aa0
mamba/application_factory.py
mamba/application_factory.py
# -*- coding: utf-8 -*- from mamba import settings, formatters, reporter, runners, example_collector class ApplicationFactory(object): def __init__(self, arguments): self._instances = {} self.arguments = arguments def create_settings(self): settings_ = settings.Settings() se...
# -*- coding: utf-8 -*- from mamba import settings, formatters, reporter, runners, example_collector class ApplicationFactory(object): def __init__(self, arguments): self._instances = {} self.arguments = arguments def create_settings(self): settings_ = settings.Settings() se...
Fix the enable coverage issue
Fix the enable coverage issue
Python
mit
dex4er/mamba,alejandrodob/mamba,markng/mamba,eferro/mamba,angelsanz/mamba,nestorsalceda/mamba,jaimegildesagredo/mamba
f5ac1fa0738384fada4abb979ba25dddecc56372
compose/utils.py
compose/utils.py
import json import hashlib def json_hash(obj): dump = json.dumps(obj, sort_keys=True) h = hashlib.sha256() h.update(dump) return h.hexdigest()
import json import hashlib def json_hash(obj): dump = json.dumps(obj, sort_keys=True, separators=(',', ':')) h = hashlib.sha256() h.update(dump) return h.hexdigest()
Remove whitespace from json hash
Remove whitespace from json hash Reasoning: https://github.com/aanand/fig/commit/e5d8447f063498164f12567554a2eec16b4a3c88#commitcomment-11243708 Signed-off-by: Ben Firshman <73675debcd8a436be48ec22211dcf44fe0df0a64@firshman.co.uk>
Python
apache-2.0
alunduil/fig,danix800/docker.github.io,joaofnfernandes/docker.github.io,tiry/compose,mrfuxi/compose,mnowster/compose,talolard/compose,joaofnfernandes/docker.github.io,JimGalasyn/docker.github.io,bdwill/docker.github.io,jrabbit/compose,uvgroovy/compose,rgbkrk/compose,Chouser/compose,anweiss/docker.github.io,shin-/docker...
e78ce4d29fda36bcd946e6c54a745761596ee7f1
spec/puzzle/examples/gph/a_basic_puzzle_spec.py
spec/puzzle/examples/gph/a_basic_puzzle_spec.py
from data import warehouse from puzzle.examples.gph import a_basic_puzzle from puzzle.problems import number_problem from puzzle.puzzlepedia import prod_config from spec.mamba import * with _description('a_basic_puzzle'): with before.all: warehouse.save() prod_config.init() self.subject = a_basic_puzzle....
from data import warehouse from puzzle.examples.gph import a_basic_puzzle from puzzle.problems import number_problem from puzzle.puzzlepedia import prod_config from spec.mamba import * with _description('a_basic_puzzle'): with before.all: warehouse.save() prod_config.init() self.subject = a_basic_puzzle....
Update test values. Trie no longer provides 2 of the answers.
Update test values. Trie no longer provides 2 of the answers.
Python
mit
PhilHarnish/forge,PhilHarnish/forge,PhilHarnish/forge,PhilHarnish/forge,PhilHarnish/forge,PhilHarnish/forge
03a3f15daf7c90f8146987f09491c69b899a0130
corehq/apps/domainsync/management/commands/copy_utils.py
corehq/apps/domainsync/management/commands/copy_utils.py
from casexml.apps.stock.models import StockReport, StockTransaction, DocDomainMapping from corehq.apps.products.models import SQLProduct def copy_postgres_data_for_docs(remote_postgres_slug, doc_ids, simulate=False): """ Copies a set of data associated with a list of doc-ids from a remote postgres databas...
from casexml.apps.stock.models import StockReport, StockTransaction, DocDomainMapping from corehq.apps.products.models import SQLProduct from phonelog.models import DeviceReportEntry def copy_postgres_data_for_docs(remote_postgres_slug, doc_ids, simulate=False): """ Copies a set of data associated with a list...
Add phonelog to postgres models copied by copy_domain
Add phonelog to postgres models copied by copy_domain
Python
bsd-3-clause
dimagi/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq
0c593f66c0b51903c38b76bf1163d716f59c56d8
FreeMemory.py
FreeMemory.py
/* * Copyright 2012-2014 inBloom, Inc. and its affiliates. * * 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 appli...
/* * Copyright 2012-2014 inBloom, Inc. and its affiliates. * * 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 appli...
Fix to ensure we dont leave any open file handles laying around
Fix to ensure we dont leave any open file handles laying around
Python
apache-2.0
inbloom/server-density-plugins
0e2d792cfe8d7afff08e08f5eaecdc126c369f54
asyncio/compat.py
asyncio/compat.py
""" Compatibility constants and functions for the different Python versions. """ import sys # Python 2.6 or older? PY26 = (sys.version_info < (2, 7)) # Python 3.0 or newer? PY3 = (sys.version_info >= (3,)) # Python 3.3 or newer? PY33 = (sys.version_info >= (3, 3)) # Python 3.4 or newer? PY34 = sys.version_info >= (...
""" Compatibility constants and functions for the different Python versions. """ import sys # Python 2.6 or older? PY26 = (sys.version_info < (2, 7)) # Python 3.0 or newer? PY3 = (sys.version_info >= (3,)) # Python 3.3 or newer? PY33 = (sys.version_info >= (3, 3)) # Python 3.4 or newer? PY34 = sys.version_info >= (...
Use str type instead of bytes in Python 2
Use str type instead of bytes in Python 2
Python
apache-2.0
overcastcloud/trollius,overcastcloud/trollius,overcastcloud/trollius
0e0b33a88ee050d7c02c0ba292d56478ba99e75d
stag/base.py
stag/base.py
try: from StringIO import StringIO except ImportError: from io import StringIO from inspect import isgenerator class Element(object): tag = '' self_closing = False def __init__(self, *children, **attrs): if children and isinstance(children[0], dict): self.attrs = children[0] ...
try: from StringIO import StringIO except ImportError: from io import StringIO from inspect import isgenerator class Element(object): tag = '' self_closing = False def __init__(self, *children, **attrs): if children and isinstance(children[0], dict): self.attrs = children[0] ...
Add __repr__ for elements for easier debugging
Add __repr__ for elements for easier debugging
Python
mit
russiancow/stag
7a6e8af11ac28cf10e5ce33637bc883324dde641
game/models.py
game/models.py
from django.db import models from django.utils import timezone class Task(models.Model): EQUALS_CHECK = 'EQ' REGEX_CHECK = 'RE' CHECK_CHOICES = ( (EQUALS_CHECK, 'Equals'), (REGEX_CHECK, 'Regex'), ) title_ru = models.CharField(null=False, blank=False, max_length=256) title_en...
from django.db import models from django.utils import timezone class Task(models.Model): EQUALS_CHECK = 'EQ' REGEX_CHECK = 'RE' CHECK_CHOICES = ( (EQUALS_CHECK, 'Equals'), (REGEX_CHECK, 'Regex'), ) title_ru = models.CharField(null=False, blank=False, max_length=256) title_en...
Add new fields to the task model
Add new fields to the task model
Python
bsd-3-clause
stefantsov/blackbox3,stefantsov/blackbox3,stefantsov/blackbox3
ddae9e02ab2bc9099fcb215ba5803210767f72a5
common/lib/xmodule/xmodule/edxnotes_utils.py
common/lib/xmodule/xmodule/edxnotes_utils.py
""" Utilities related to edXNotes. """ import sys def edxnotes(cls): """ Conditional decorator that loads edxnotes only when they exist. """ if "edxnotes" in sys.modules: from edxnotes.decorators import edxnotes as notes return notes(cls) else: return cls
""" Utilities related to edXNotes. """ import sys def edxnotes(cls): """ Conditional decorator that loads edxnotes only when they exist. """ if "lms.djangoapps.edxnotes" in sys.modules: from lms.djangoapps.edxnotes.decorators import edxnotes as notes return notes(cls) else: ...
Use fully-qualified edxnotes app name when checking if installed
Use fully-qualified edxnotes app name when checking if installed
Python
agpl-3.0
angelapper/edx-platform,stvstnfrd/edx-platform,arbrandes/edx-platform,arbrandes/edx-platform,edx/edx-platform,eduNEXT/edunext-platform,EDUlib/edx-platform,EDUlib/edx-platform,angelapper/edx-platform,edx/edx-platform,eduNEXT/edx-platform,angelapper/edx-platform,EDUlib/edx-platform,edx/edx-platform,stvstnfrd/edx-platform...
61b2266cbd70eacf1382f3a6c46dd16485e4f7e7
utils/exporter.py
utils/exporter.py
import plotly as py from os import makedirs from utils.names import output_file_name _out_dir = 'graphs/' def export(fig, module, dates): graph_dir = '{}{}/'.format(_out_dir, str(module))[:-3] # remove .py extension from dir names makedirs(graph_dir, exist_ok=True) py.offline.plot(fig, filename=graph_di...
import plotly as py from os import makedirs from utils.names import output_file_name _out_dir = 'graphs' def export(fig, module, dates): graph_dir = '{}/{}'.format(_out_dir, module[:-3]) # remove .py extension from dir names makedirs(graph_dir, exist_ok=True) py.offline.plot(fig, filename='{}/{}'.format(...
Fix naming of output dir and file names
Fix naming of output dir and file names
Python
mit
f-jiang/sleep-pattern-grapher
9c7b617829a953c8e7a4b377f8da84f8de94c9bf
src/rgrep.py
src/rgrep.py
def rgrep(pattern='', text='', case=''): if pattern == '' or text == '': return 'Usage: python rgrep [options] pattern files\nThe options are the same as grep\n' else: if case == 'i': return pattern.lower() in text.lower() else: return pattern in text
def display_usage(): return 'Usage: python rgrep [options] pattern files\nThe options are the same as grep\n' def rgrep(pattern='', text='', case=''): if pattern == '' or text == '': return display_usage() else: if case == 'i': pattern = pattern.lower() text = text....
Refactor the case insensitive option
Refactor the case insensitive option
Python
bsd-2-clause
ambidextrousTx/RGrep-Python
894fb1d68e82679720ed0acb71d478a8a1ba525d
openchordcharts/views/api.py
openchordcharts/views/api.py
# -*- coding: utf-8 -*- from pyramid.view import view_config from openchordcharts import model @view_config(route_name='charts.json', renderer='jsonp') def charts_json(request): return [chart.to_json() for chart in model.Chart.find()]
# -*- coding: utf-8 -*- from pyramid.view import view_config from openchordcharts import model @view_config(route_name='charts.json', renderer='jsonp') def charts_json(request): title = request.GET.get('title') user = request.GET.get('user') spec = {} if title: spec['title'] = title if u...
Add search by title and user for API.
Add search by title and user for API.
Python
agpl-3.0
openchordcharts/web-api,openchordcharts/openchordcharts-api
2fabca2c3a358e5c744c85eeeefcc78be3537a57
Demo/sockets/unixserver.py
Demo/sockets/unixserver.py
# Echo server program using Unix sockets (handles one connection only) from socket import * FILE = 'blabla' s = socket(AF_UNIX, SOCK_STREAM) s.bind(FILE) print 'Sock name is: ['+s.getsockname()+']' s.listen(1) conn, addr = s.accept() print 'Connected by', addr while 1: data = conn.recv(1024) if not...
# Echo server demo using Unix sockets (handles one connection only) # Piet van Oostrum from socket import * FILE = 'blabla' s = socket(AF_UNIX, SOCK_STREAM) s.bind(FILE) print 'Sock name is: ['+s.getsockname()+']' s.listen(1) conn, addr = s.accept() print 'Connected by', addr while 1: data = conn.recv(...
Add Piet van Oostrum's name to the comments.
Add Piet van Oostrum's name to the comments.
Python
mit
sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator
501ede985c034f4883ac93a38f8486af6fddf766
src/nodeconductor_saltstack/saltstack/perms.py
src/nodeconductor_saltstack/saltstack/perms.py
from nodeconductor.core.permissions import FilteredCollaboratorsPermissionLogic from nodeconductor.structure.models import CustomerRole, ProjectGroupRole, ProjectRole PERMISSION_LOGICS = ( ('saltstack.SaltStackService', FilteredCollaboratorsPermissionLogic( collaborators_query='customer__roles__permission...
from nodeconductor.structure import perms as structure_perms PERMISSION_LOGICS = ( ('saltstack.SaltStackService', structure_perms.service_permission_logic), ('saltstack.SaltStackServiceProjectLink', structure_perms.service_project_link_permission_logic), ) property_permission_logic = structure_perms.property...
Make permissions declaration DRY (NC-1282)
Make permissions declaration DRY (NC-1282)
Python
mit
opennode/nodeconductor-saltstack
7ad5e00abc9158951697e86242781567b82dd52c
oauth2_provider/generators.py
oauth2_provider/generators.py
from oauthlib.common import CLIENT_ID_CHARACTER_SET, generate_client_id as oauthlib_generate_client_id from .settings import oauth2_settings class BaseHashGenerator(object): """ All generators should extend this class overriding `.hash()` method. """ def hash(self): raise NotImplementedError(...
from oauthlib.common import generate_client_id as oauthlib_generate_client_id from .settings import oauth2_settings CLIENT_ID_CHARACTER_SET = r'_-.:;=?!@0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' class BaseHashGenerator(object): """ All generators should extend this class overriding `....
Change default generator for client_id and client_secret: now use a safe set of characters that don't need escaping. That way we should avoid problems with many dummy client implementations
Change default generator for client_id and client_secret: now use a safe set of characters that don't need escaping. That way we should avoid problems with many dummy client implementations
Python
bsd-2-clause
cheif/django-oauth-toolkit,svetlyak40wt/django-oauth-toolkit,jensadne/django-oauth-toolkit,bleib1dj/django-oauth-toolkit,vmalavolta/django-oauth-toolkit,Knotis/django-oauth-toolkit,jensadne/django-oauth-toolkit,mjrulesamrat/django-oauth-toolkit,andrefsp/django-oauth-toolkit,DeskConnect/django-oauth-toolkit,CloudNcodeIn...
b7238c0178eee43ccc6cfb3ac2039aad3bf0f2ce
relengapi/blueprints/slaveloan/tests/test_slaveloan.py
relengapi/blueprints/slaveloan/tests/test_slaveloan.py
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. from nose.tools import eq_ from relengapi.lib.testing.context import TestContext test_context = TestContext() @test_c...
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. from nose.tools import eq_ from relengapi.lib.testing.context import TestContext def userperms(perms, email='me@exampl...
Add a few tests that some endpoints load
Add a few tests that some endpoints load
Python
mpl-2.0
Callek/build-relengapi,andrei987/services,lundjordan/build-relengapi,djmitche/build-relengapi,Callek/build-relengapi,lundjordan/services,srfraser/services,garbas/mozilla-releng-services,Callek/build-relengapi,Callek/build-relengapi,mozilla/build-relengapi,djmitche/build-relengapi,andrei987/services,Callek/build-relenga...
1fa6bcbd5ab5e51f9e4250024c848933ea0911e7
examples/upsidedownternet.py
examples/upsidedownternet.py
import Image, cStringIO def response(context, flow): if flow.response.headers["content-type"] == ["image/png"]: s = cStringIO.StringIO(flow.response.content) img = Image.open(s).rotate(180) s2 = cStringIO.StringIO() img.save(s2, "png") flow.response.content = s2.getvalue()
import cStringIO from PIL import Image def response(context, flow): if flow.response.headers["content-type"] == ["image/png"]: s = cStringIO.StringIO(flow.response.content) img = Image.open(s).rotate(180) s2 = cStringIO.StringIO() img.save(s2, "png") flow.response.content = ...
Update another reference to PIL.
Update another reference to PIL.
Python
mit
dwfreed/mitmproxy,tdickers/mitmproxy,StevenVanAcker/mitmproxy,bazzinotti/mitmproxy,owers19856/mitmproxy,liorvh/mitmproxy,liorvh/mitmproxy,ryoqun/mitmproxy,guiquanz/mitmproxy,Endika/mitmproxy,dufferzafar/mitmproxy,dwfreed/mitmproxy,laurmurclar/mitmproxy,jvillacorta/mitmproxy,dufferzafar/mitmproxy,mosajjal/mitmproxy,dxq-...
98bed3a2c410fc0a6fee491c35f3b49bf48c08db
arguments.py
arguments.py
import argparse from settings import HONEYPORT """ Here we define command line arguments. `port` stands for port, to listen on. `-v` to increase verbose of the server """ def parse(): parser = argparse.ArgumentParser( description='Serve some sweet honey to the ubiquitous bots!', epilog='And that...
import argparse from settings import HONEYPORT """ Here we define command line arguments. `port` stands for port, to listen on. `-v` to increase verbose of the server """ def parse(): parser = argparse.ArgumentParser( description='Serve some sweet honey to the ubiquitous bots!', epilog='And that...
Add argument for launching client
Add argument for launching client Before, client would launch automatically on port you specify as a positional argument. This means you can't just not to launch the client. Now, there are 2 options: 1) -c to launch client on the port defined in settings 2) --client to specify the port explicitly So, if you wa...
Python
mit
Zloool/manyfaced-honeypot
1d0cd4bcc35042bf5146339a817a953e20229f30
freezer_api/tests/freezer_api_tempest_plugin/clients.py
freezer_api/tests/freezer_api_tempest_plugin/clients.py
# (C) Copyright 2016 Hewlett Packard Enterprise Development Company LP # # 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 ...
# (C) Copyright 2016 Hewlett Packard Enterprise Development Company LP # # 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 ...
Fix failed tempest tests with KeystoneV2
Fix failed tempest tests with KeystoneV2 Change-Id: I78e6a2363d006c6feec84db4d755974e6a6a81b4 Signed-off-by: Ruslan Aliev <f0566964e0d23c2ac49e399e34dbe87edb487aa1@mirantis.com>
Python
apache-2.0
openstack/freezer-api,szaher/freezer-api,szaher/freezer-api,openstack/freezer-api,openstack/freezer-api,szaher/freezer-api,openstack/freezer-api,szaher/freezer-api
7b3faffb655a3d4b44b52bd907b7e17f952a9f43
src/pve_exporter/cli.py
src/pve_exporter/cli.py
""" Proxmox VE exporter for the Prometheus monitoring system. """ import sys from pve_exporter.http import start_http_server def main(args=None): """ Main entry point. """ if args is None: args = sys.argv if len(args) not in [1, 2, 3]: print("Usage: pve_exporter [config_file] [po...
""" Proxmox VE exporter for the Prometheus monitoring system. """ import sys from argparse import ArgumentParser from pve_exporter.http import start_http_server def main(args=None): """ Main entry point. """ parser = ArgumentParser() parser.add_argument('config', nargs='?', default='pve.yml', ...
Add argparse and provide usage/command line help
Add argparse and provide usage/command line help
Python
apache-2.0
znerol/prometheus-pve-exporter
b8764c10f108393b7de1332f5061bb7a8b7def25
future/disable_obsolete_builtins.py
future/disable_obsolete_builtins.py
""" This disables builtin functions (and one exception class) which are removed from Python 3.3. This module is designed to be used like this: from future import disable_obsolete_builtins We don't hack __builtin__, which is very fragile because it contaminates imported modules too. Instead, we just create new gl...
""" This disables builtin functions (and one exception class) which are removed from Python 3.3. This module is designed to be used like this: from future import disable_obsolete_builtins We don't hack __builtin__, which is very fragile because it contaminates imported modules too. Instead, we just create new gl...
Add reduce() and reload() to disabled builtins
Add reduce() and reload() to disabled builtins
Python
mit
PythonCharmers/python-future,krischer/python-future,michaelpacer/python-future,PythonCharmers/python-future,michaelpacer/python-future,QuLogic/python-future,krischer/python-future,QuLogic/python-future
7051e7bb98c1d1227d3beebc809498b963124a41
pal/services/joke_service.py
pal/services/joke_service.py
import re from pal.services.service import Service from pal.services.service import wrap_response class JokeService(Service): _JOKES = { 'open the pod bay doors pal': "I'm sorry, Jeff, I'm afraid I can't do that.", 'laws of robotics': "1. A robot may not injure a human bei...
import re from pal.services.service import Service from pal.services.service import wrap_response class JokeService(Service): _JOKES = { 'open the pod bay doors pal': "I'm sorry, Jeff, I'm afraid I can't do that.", 'laws of robotics': "1. A robot may not injure a human bei...
Add Tom Hanks in a way that's actually reachable
Add Tom Hanks in a way that's actually reachable
Python
bsd-3-clause
Machyne/pal,Machyne/pal,Machyne/pal,Machyne/pal
aa3f4120bf3915fd99a8ef5affb620920aeed99b
aioredlock/lock.py
aioredlock/lock.py
import attr @attr.s class Lock: lock_manager = attr.ib() resource = attr.ib() id = attr.ib() lock_timeout = attr.ib(default=10.0) valid = attr.ib(default=False) async def __aenter__(self): return self async def __aexit__(self, exc_type, exc, tb): await self.lock_manager....
import attr @attr.s class Lock: lock_manager = attr.ib() resource = attr.ib() id = attr.ib() lock_timeout = attr.ib(default=10.0) valid = attr.ib(default=False) async def __aenter__(self): return self async def __aexit__(self, exc_type, exc, tb): await self.lock_manager....
Add release() method to Lock.
Add release() method to Lock.
Python
mit
joanvila/aioredlock
80cc986ebf16c59fa79c3c406e9060e49b93ad24
test/test_getavgpdb.py
test/test_getavgpdb.py
import os import unittest import subprocess import utils TOPDIR = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) utils.set_search_paths(TOPDIR) from allosmod.util import check_output class Tests(unittest.TestCase): def test_bad(self): """Test wrong arguments to getavgpdb""" for arg...
import os import unittest import subprocess import utils TOPDIR = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) test_dir = utils.set_search_paths(TOPDIR) utils.set_search_paths(TOPDIR) from allosmod.util import check_output ALIGN_ALI = """ >P1;pdb1 structureX:asite_pdb1: 1 :A:+30 :A:::-1.00:-1.00 ...
Add a simple test of getavgpdb.
Add a simple test of getavgpdb.
Python
lgpl-2.1
salilab/allosmod-lib,salilab/allosmod-lib,salilab/allosmod-lib,salilab/allosmod-lib,salilab/allosmod-lib
8e0d28d23c7ceb6a200773dde035b85965273ac6
inbox/events/actions/base.py
inbox/events/actions/base.py
from inbox.models.account import Account from inbox.models.event import Event from inbox.events.actions.backends import module_registry def create_event(account_id, event_id, db_session): account = db_session.query(Account).get(account_id) event = db_session.query(Event).get(event_id) remote_create_event...
from inbox.models.account import Account from inbox.models.event import Event from inbox.events.actions.backends import module_registry def create_event(account_id, event_id, db_session, *args): account = db_session.query(Account).get(account_id) event = db_session.query(Event).get(event_id) remote_creat...
Add args flexibility to event create to match EAS requirements
Add args flexibility to event create to match EAS requirements
Python
agpl-3.0
PriviPK/privipk-sync-engine,ErinCall/sync-engine,nylas/sync-engine,Eagles2F/sync-engine,closeio/nylas,nylas/sync-engine,jobscore/sync-engine,PriviPK/privipk-sync-engine,PriviPK/privipk-sync-engine,wakermahmud/sync-engine,gale320/sync-engine,wakermahmud/sync-engine,jobscore/sync-engine,jobscore/sync-engine,closeio/nylas...
ea22f4bf62204805e698965300b6d8dfa637a662
pybossa_discourse/globals.py
pybossa_discourse/globals.py
# -*- coding: utf8 -*- """Jinja globals module for pybossa-discourse.""" from flask import Markup, request class DiscourseGlobals(object): """A class to implement Discourse Global variables.""" def __init__(self, app): self.url = app.config['DISCOURSE_URL'] app.jinja_env.globals.update(disco...
# -*- coding: utf8 -*- """Jinja globals module for pybossa-discourse.""" from flask import Markup, request from . import discourse_client class DiscourseGlobals(object): """A class to implement Discourse Global variables.""" def __init__(self, app): self.url = app.config['DISCOURSE_URL'] app...
Add notifications count to global envar
Add notifications count to global envar
Python
bsd-3-clause
alexandermendes/pybossa-discourse
1d292feebd2999eb042da1f606c0fdc33103225f
api/models.py
api/models.py
class MessageModel: def __init__(self, message, duration, creation_date, message_category): # We will automatically generate the new id self.id = 0 self.message = message self.duration = duration self.creation_date = creation_date self.message_category = message_categ...
class MessageModel: def __init__(self, message, duration, creation_date, message_category): # We will automatically generate the new id self.id = 0 self.message = message self.duration = duration self.creation_date = creation_date self.message_category = message_categ...
Update model script to support task database schema
Update model script to support task database schema
Python
mit
candidate48661/BEA
e0d8099e57fb890649490b9e9bb201b98b041212
libcloud/__init__.py
libcloud/__init__.py
# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # libcloud.org licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not...
# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # libcloud.org licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not...
Add version string to libcloud
Add version string to libcloud git-svn-id: 353d90d4d8d13dcb4e0402680a9155a727f61a5a@895867 13f79535-47bb-0310-9956-ffa450edef68
Python
apache-2.0
cloudkick/libcloud,cloudkick/libcloud
46a0caa1bc162d11b26a996379170b2fc49f2940
mcbench/client.py
mcbench/client.py
import collections import redis BENCHMARK_FIELDS = [ 'author', 'author_url', 'date_submitted', 'date_updated', 'name', 'summary', 'tags', 'title', 'url' ] Benchmark = collections.namedtuple('Benchmark', ' '.join(BENCHMARK_FIELDS)) class McBenchClient(object): def __init__(self, redis): self.red...
import redis class Benchmark(object): def __init__(self, author, author_url, date_submitted, date_updated, name, summary, tags, title, url): self.author = author self.author_url = author_url self.date_submitted = date_submitted self.date_updated = date_updated ...
Make Benchmark a class, not a namedtuple.
Make Benchmark a class, not a namedtuple.
Python
mit
isbadawi/mcbench,isbadawi/mcbench
1b9c4935b2edf6601c2d75d8a2d318266de2d456
circuits/tools/__init__.py
circuits/tools/__init__.py
# Module: __init__ # Date: 8th November 2008 # Author: James Mills, prologic at shortcircuit dot net dot au """Circuits Tools circuits.tools contains a standard set of tools for circuits. These tools are installed as executables with a prefix of "circuits." """ try: from cStringIO import StringIO except ImportE...
# Module: __init__ # Date: 8th November 2008 # Author: James Mills, prologic at shortcircuit dot net dot au """Circuits Tools circuits.tools contains a standard set of tools for circuits. These tools are installed as executables with a prefix of "circuits." """ try: from cStringIO import StringIO except ImportE...
Store the depth (d) on the stack and restore when backtracking
tools: Store the depth (d) on the stack and restore when backtracking
Python
mit
treemo/circuits,treemo/circuits,eriol/circuits,treemo/circuits,eriol/circuits,nizox/circuits,eriol/circuits
7ba2299e2d429bd873539507b3edbe3cdd3de9d6
linkatos/firebase.py
linkatos/firebase.py
import pyrebase def initialise(FB_API_KEY, project_name): config = { "apiKey": FB_API_KEY, "authDomain": "{}.firebaseapp.com".format(project_name), "databaseURL": "https://{}.firebaseio.com".format(project_name), "storageBucket": "{}.appspot.com".format(project_name), } return pyr...
import pyrebase def initialise(api_key, project_name): config = { "apiKey": api_key, "authDomain": "{}.firebaseapp.com".format(project_name), "databaseURL": "https://{}.firebaseio.com".format(project_name), "storageBucket": "{}.appspot.com".format(project_name), } return pyrebase....
Change variables to lower case
style: Change variables to lower case
Python
mit
iwi/linkatos,iwi/linkatos
56edfe1bacff53eec22b05d43f32063f83f43ea5
studies/helpers.py
studies/helpers.py
from django.core.mail.message import EmailMultiAlternatives from django.template.loader import get_template from project.celery import app from project.settings import EMAIL_FROM_ADDRESS, BASE_URL @app.task def send_mail(template_name, subject, to_addresses, cc=None, bcc=None, from_email=None, **context): """ ...
from django.core.mail.message import EmailMultiAlternatives from django.template.loader import get_template from project.celery import app from project.settings import EMAIL_FROM_ADDRESS, BASE_URL, OSF_URL @app.task def send_mail(template_name, subject, to_addresses, cc=None, bcc=None, from_email=None, **context): ...
Add OSF_URL to send_email helper.
Add OSF_URL to send_email helper.
Python
apache-2.0
CenterForOpenScience/lookit-api,pattisdr/lookit-api,pattisdr/lookit-api,pattisdr/lookit-api,CenterForOpenScience/lookit-api,CenterForOpenScience/lookit-api
6fcf03532dcc549a3a95390b7c999482a64fc6c6
tests/unit/utils/test_pycrypto.py
tests/unit/utils/test_pycrypto.py
# -*- coding: utf-8 -*- # Import python libs from __future__ import absolute_import, print_function, unicode_literals import logging import re # Import Salt Libs import salt.utils.pycrypto import salt.utils.platform # Import Salt Testing Libs from tests.support.unit import TestCase, skipIf log = logging.getLogger(_...
# -*- coding: utf-8 -*- # Import python libs from __future__ import absolute_import, print_function, unicode_literals import logging import re # Import Salt Libs import salt.utils.pycrypto import salt.utils.platform # Import Salt Testing Libs from tests.support.unit import TestCase, skipIf log = logging.getLogger(_...
Make the skip apply to any system missing crypt
Make the skip apply to any system missing crypt
Python
apache-2.0
saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt
edebe37458da391723e3206c63102cbb69606c5b
ideascube/conf/idb_irq_bardarash.py
ideascube/conf/idb_irq_bardarash.py
"""Bardarash in Kurdistan, Iraq""" from .idb_jor_azraq import * # pragma: no flakes from django.utils.translation import ugettext_lazy as _ USER_FORM_FIELDS = ( ('Ideasbox', ['serial', 'box_awareness']), (_('Personal informations'), ['short_name', 'full_name', 'latin_name', 'birth_year', 'gender', 'country_o...
"""Bardarash in Kurdistan, Iraq""" from .idb_jor_azraq import * # pragma: no flakes from django.utils.translation import ugettext_lazy as _ USER_FORM_FIELDS = ( ('Ideasbox', ['serial', 'box_awareness']), (_('Personal informations'), ['short_name', 'full_name', 'latin_name', 'birth_year', 'gender', 'country_o...
Remove Kalite until Arabic language is available
Remove Kalite until Arabic language is available
Python
agpl-3.0
ideascube/ideascube,ideascube/ideascube,ideascube/ideascube,ideascube/ideascube
066833caebddb9a6e0735e635ff214448e078405
check_env.py
check_env.py
""" Run this file to check your python installation. """ def test_import_pandas(): import pandas def test_pandas_version(): import pandas version_found = pandas.__version__.split(".") version_found = tuple(int(num) for num in version_found) assert version_found > (0, 15) def test_import_numpy()...
""" Run this file to check your python installation. """ from os.path import dirname, join HERE = dirname(__file__) def test_import_pandas(): import pandas def test_pandas_version(): import pandas version_found = pandas.__version__.split(".") version_found = tuple(int(num) for num in version_found) ...
Add some more content in tests including with statsmodels.
Add some more content in tests including with statsmodels.
Python
mit
wateryhcho/pandas_tutorial,linan7788626/pandas_tutorial,jonathanrocher/pandas_tutorial,wateryhcho/pandas_tutorial,Sandor-PRA/pandas_tutorial,Sandor-PRA/pandas_tutorial,ajaykliyara/pandas_tutorial,ajaykliyara/pandas_tutorial,jonathanrocher/pandas_tutorial,jonathanrocher/pandas_tutorial,ajaykliyara/pandas_tutorial,linan7...
9b5b6514ace9d08d2dca563b71c8b6a1ca3f4f70
wordcloud.py
wordcloud.py
import falcon, json, pymongo MONGO_DB_USER_FILE = '/home/frank/word_cloud-backend/config/mongodb-user' mongo_db_user_config = open(MONGO_DB_USER_FILE, 'r').read() user_name = mongo_db_user_config.split(':')[0] password = mongo_db_user_config.split(':')[1] mongo_db_client = pymongo.MongoClient('wordcloud-mongo.hom...
import falcon, json, pymongo MONGO_DB_USER_FILE = '/home/frank/word_cloud-backend/config/mongodb-user' mongo_db_user_config = open(MONGO_DB_USER_FILE, 'r').read() user_name = mongo_db_user_config.rstrip('\n').split(':')[0] password = mongo_db_user_config.rstrip('\n').split(':')[1] mongo_db_client = pymongo.MongoC...
Read mongo user and passwd from config file
Read mongo user and passwd from config file
Python
apache-2.0
Frank-Krick/word_cloud-backend
2b0edbadec80300d20a280db0f06281040e00e25
radar/radar/validation/consultants.py
radar/radar/validation/consultants.py
from radar.validation.core import Field, Validation, ListField, ValidationError from radar.validation.meta import MetaValidationMixin from radar.validation.validators import not_empty, none_if_blank, optional, email_address, max_length, required, upper, lower from radar.validation.number_validators import gmc_number ...
from radar.validation.core import Field, Validation, ListField, ValidationError from radar.validation.meta import MetaValidationMixin from radar.validation.validators import not_empty, none_if_blank, optional, email_address, max_length, required, upper, lower from radar.validation.number_validators import gmc_number ...
Check consultant groups aren't duplicated
Check consultant groups aren't duplicated
Python
agpl-3.0
renalreg/radar,renalreg/radar,renalreg/radar,renalreg/radar