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
5864b503bced36d51ab911d5b306284dbc0cdb13
rest_framework_simplejwt/settings.py
rest_framework_simplejwt/settings.py
from __future__ import unicode_literals from datetime import timedelta from django.conf import settings from rest_framework.settings import APISettings USER_SETTINGS = getattr(settings, 'SIMPLE_JWT', None) DEFAULTS = { 'AUTH_HEADER_TYPE': 'Bearer', 'USER_ID_FIELD': 'id', 'USER_ID_CLAIM': 'user_id', ...
from __future__ import unicode_literals from datetime import timedelta from django.conf import settings from rest_framework.settings import APISettings USER_SETTINGS = getattr(settings, 'SIMPLE_JWT', None) DEFAULTS = { 'AUTH_HEADER_TYPE': 'Bearer', 'USER_ID_FIELD': 'id', 'USER_ID_CLAIM': 'user_id', ...
Make sliding token lifetime defaults a bit more conservative
Make sliding token lifetime defaults a bit more conservative
Python
mit
davesque/django-rest-framework-simplejwt,davesque/django-rest-framework-simplejwt
1c9f3b95cca8439ec8c4a5a5cb1959e8b2edaff2
osmaxx-py/excerptconverter/converter_helper.py
osmaxx-py/excerptconverter/converter_helper.py
from django.contrib import messages from django.core.mail import send_mail from django.utils.translation import ugettext_lazy as _ import stored_messages from osmaxx.excerptexport import models class ConverterHelper: def __init__(self, extraction_order): self.extraction_order = extraction_order ...
from django.contrib import messages from django.core.mail import send_mail from django.utils.translation import ugettext_lazy as _ import stored_messages from osmaxx.excerptexport import models # functions using database (extraction_order) must be instance methods of a class # -> free functions will not work: datab...
Document reason for class instead of free function
Document reason for class instead of free function
Python
isc
geometalab/drf-utm-zone-info,geometalab/drf-utm-zone-info,geometalab/osmaxx-frontend,geometalab/osmaxx-frontend,geometalab/osmaxx,geometalab/osmaxx,geometalab/osmaxx-frontend,geometalab/osmaxx,geometalab/osmaxx-frontend,geometalab/osmaxx
65d6563d22c8500402b23c09d3b8991b79c94dee
setup.py
setup.py
# # Copyright 2016 BMC Software, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in w...
# # Copyright 2016 BMC Software, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in w...
Add versions to install requirements
Add versions to install requirements
Python
apache-2.0
jdgwartney/meter-plugin-sdk-python,jdgwartney/meter-plugin-sdk-python
26a5b169f1cc67911f49c2ba835b078135f57dda
setup.py
setup.py
from distutils.core import setup setup( name='Juju XaaS Client Binding', version='0.1.0', author='Justin SB', author_email='justin@fathomdb.com', packages=['jujuxaas', 'jujuxaas.auth'], url='http://pypi.python.org/pypi/JujuXaasClient/', license='LICENSE.txt', description='Client library...
from distutils.core import setup setup( name='Juju XaaS Client Binding', version='0.1.0', author='Justin SB', author_email='justin@fathomdb.com', packages=['jujuxaas', 'jujuxaas.auth'], url='http://pypi.python.org/pypi/JujuXaasClient/', license='LICENSE.txt', description='Client library...
Add python-keystoneclient as a dependency
Add python-keystoneclient as a dependency
Python
apache-2.0
jxaas/python-client
fcf30e1dfada272d0344ccb9e4054afeda003c8e
setup.py
setup.py
#!/usr/bin/env python from distutils.core import setup from os.path import dirname, join setup(name='hashids', version='0.8.3', description='Python implementation of hashids (http://www.hashids.org).' 'Compatible with python 2.5--3.', long_description=open(join(dirname(__file__), 'R...
#!/usr/bin/env python from distutils.core import setup from os.path import dirname, join from codecs import open setup(name='hashids', version='0.8.3', description='Python implementation of hashids (http://www.hashids.org).' 'Compatible with python 2.5--3.', long_description=open(jo...
Make it work with older python versions as well
Make it work with older python versions as well
Python
mit
davidaurelio/hashids-python,Dubz/hashids-python,pombredanne/hashids-python
0e98542f2b703de66dda71fb1b5efb7ae6d5b93d
setup.py
setup.py
#!/usr/bin/env python from distutils.core import setup from vaspy import __version__ as version maintainer = 'Shao-Zheng-Jiang' maintainer_email = 'shaozhengjiang@gmail.com' author = maintainer author_email = maintainer_email description = __doc__ requires = [ 'numpy', 'matplotlib' ] license = 'LICENSE' lon...
#!/usr/bin/env python from distutils.core import setup from vaspy import __version__ as version maintainer = 'Shao-Zheng-Jiang' maintainer_email = 'shaozhengjiang@gmail.com' author = maintainer author_email = maintainer_email description = __doc__ requires = [ 'numpy', 'matplotlib' ] license = 'LICENSE' wit...
Fix bug in getting long_description.
Fix bug in getting long_description.
Python
mit
PytLab/VASPy,PytLab/VASPy
0452180ce246d86da8b02b0721f11a4346cbd9a5
cozify/multisensor.py
cozify/multisensor.py
import time from influxdb import InfluxDBClient from influxdb import SeriesHelper from . import config # expects Cozify devices type json data def getMultisensorData(data): out = [] for device in data: state=data[device]['state'] devtype = state['type'] if devtype == 'STATE_MULTI_SEN...
import time from influxdb import InfluxDBClient from influxdb import SeriesHelper from . import config # expects Cozify devices type json data def getMultisensorData(data): out = [] for device in data: state=data[device]['state'] devtype = state['type'] if devtype == 'STATE_MULTI_SEN...
Make comment about time accuracy more universal
Make comment about time accuracy more universal
Python
mit
Artanicus/python-cozify,Artanicus/python-cozify
4446a700fcf057f83645b4861b5655773983511c
tests.py
tests.py
import unittest import os from main import generate_files class WordsTest(unittest.TestCase): def setUp(self): for fname in ["test_sequences", "test_words"]: if os.path.exists(fname): os.remove(fname) def test_files_created(self): self.assertFalse(os.path.exists("t...
import unittest import os from main import generate_files class WordsTest(unittest.TestCase): def setUp(self): # Make sure the expected files don't exist yet for fname in ["test_sequences", "test_words"]: if os.path.exists(fname): os.remove(fname) def test_files_cr...
Add teardown function as well
Add teardown function as well
Python
mit
orblivion/hellolabs_word_test
f5abc26cf9e7fa80bc74028e4c5e3552772f2e93
tasks.py
tasks.py
# Project tasks (for use with invoke task runner) import subprocess from invoke import task @task def test(cover=False): # Run tests using nose called with coverage code = subprocess.call(['coverage', 'run', '-m', 'nose', '--rednose']) # Also generate coverage reports when --cover flag is given if co...
# Project tasks (for use with invoke task runner) import subprocess from invoke import task @task def test(cover=False): if cover: # Run tests via coverage and generate reports if --cover flag is given code = subprocess.call(['coverage', 'run', '-m', 'nose', '--rednose']) # Only show cove...
Improve performance of 'test' task
Improve performance of 'test' task
Python
mit
caleb531/youversion-suggest,caleb531/youversion-suggest
393bc0dc82524802c8d548216d4c51b4394e5394
tests.py
tests.py
#coding:utf8 import unittest class TestFunctions(unittest.TestCase): def first(self): assertEqual('test', 'test') def second(self): """second test""" assertEqual('2','2')
# coding: utf-8 import unittest class TestFunctions(unittest.TestCase): def first(self): self.assertEqual('test', 'test') def second(self): """second test""" self.assertEqual('2','2')
Add self to test cases
Add self to test cases Change-Id: Ib8a8fea97fb7390613a5521103f0f9d31615f262
Python
apache-2.0
khoser/mini_games
f2ab0c74986881e017199ac8a56dd09334a8b42b
magnum/tests/unit/template/test_template.py
magnum/tests/unit/template/test_template.py
# Copyright 2015 Intel, Inc # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
# Copyright 2015 Intel, Inc # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
Improve yml template test case.
Improve yml template test case. Print out yml file name when failed to loading yml. Change-Id: Ie34282b91ec8101ffa2676e3144acf5a054578b0
Python
apache-2.0
ArchiFleKs/magnum,openstack/magnum,ArchiFleKs/magnum,openstack/magnum,jay-lau/magnum
ae4519a26e372f8a27a7e460fc08d409c5bafe55
networkx/algorithms/flow/__init__.py
networkx/algorithms/flow/__init__.py
from networkx.algorithms.flow.maxflow import * from networkx.algorithms.flow.mincost import * from networkx.algorithms.flow.preflow_push import * from networkx.algorithms.flow.shortest_augmenting_path import * del utils
from . import maxflow, mincost, preflow_push, shortest_augmenting_path __all__ = sum([maxflow.__all__, mincost.__all__, preflow_push.__all__, shortest_augmenting_path.__all__], []) from .maxflow import * from .mincost import * from .preflow_push import * from .shortest_augmenting_path import *
Modify handling of module conflict in shortest augmenting path maxflow
Modify handling of module conflict in shortest augmenting path maxflow
Python
bsd-3-clause
nathania/networkx,ionanrozenfeld/networkx,dmoliveira/networkx,aureooms/networkx,kernc/networkx,dmoliveira/networkx,aureooms/networkx,kernc/networkx,harlowja/networkx,jni/networkx,jakevdp/networkx,jni/networkx,jakevdp/networkx,Sixshaman/networkx,RMKD/networkx,RMKD/networkx,ionanrozenfeld/networkx,sharifulgeo/networkx,de...
22d72a2daf1cd7ba46ded5f75a2322357762a86c
fireplace/cards/gvg/druid.py
fireplace/cards/gvg/druid.py
from ..utils import * ## # Minions # Druid of the Fang class GVG_080: def action(self): if self.poweredUp: self.morph("GVG_080t")
from ..utils import * ## # Minions # Attack Mode (Anodized Robo Cub) class GVG_030a: action = buffSelf("GVG_030ae") # Tank Mode (Anodized Robo Cub) class GVG_030b: action = buffSelf("GVG_030be") # Gift of Mana (Grove Tender) class GVG_032a: def action(self): for player in self.game.players: player.maxMana...
Implement Anodized Robo Cub, Grove Tender
Implement Anodized Robo Cub, Grove Tender
Python
agpl-3.0
Ragowit/fireplace,liujimj/fireplace,Ragowit/fireplace,Meerkov/fireplace,beheh/fireplace,butozerca/fireplace,oftc-ftw/fireplace,jleclanche/fireplace,amw2104/fireplace,liujimj/fireplace,NightKev/fireplace,amw2104/fireplace,butozerca/fireplace,smallnamespace/fireplace,Meerkov/fireplace,oftc-ftw/fireplace,smallnamespace/fi...
8126a93ec002c3cbff8f9cd7bfe996de740f4bef
setup.py
setup.py
from distutils.core import setup setup( name='buqeyemodel', # packages=['buqeyemodel'], py_modules=['buqeyemodel'], version='0.1', description='A statistical model of EFT convergence.', author='Jordan Melendez', author_email='jmelendez1992@gmail.com', license='MIT', url='https://git...
from distutils.core import setup setup( name='buqeyemodel', packages=['buqeyemodel'], # py_modules=['buqeyemodel', 'pymc3_additions'], version='0.1', description='A statistical model of EFT convergence.', author='Jordan Melendez', author_email='jmelendez1992@gmail.com', license='MIT', ...
Put buqeyemodel back in folder for multi-file use
Put buqeyemodel back in folder for multi-file use
Python
mit
jordan-melendez/buqeyemodel,jordan-melendez/buqeyemodel
6c67d06a691be8a930c0e82fcf404057580645d8
tests/conftest.py
tests/conftest.py
import os import sys from pathlib import Path import pytest if sys.version_info < (3, 4): print("Requires Python 3.4+") sys.exit(1) TESTS_ROOT = os.path.abspath(os.path.dirname(__file__)) PROJECT_ROOT = os.path.dirname(TESTS_ROOT) @pytest.fixture def resources(): return Path(TESTS_ROOT) / 'resources'...
import os import sys from pathlib import Path import pytest if sys.version_info < (3, 4): print("Requires Python 3.4+") sys.exit(1) TESTS_ROOT = os.path.abspath(os.path.dirname(__file__)) PROJECT_ROOT = os.path.dirname(TESTS_ROOT) @pytest.fixture(scope="session") def resources(): return Path(TESTS_ROO...
Fix warning from hypothesis above scope of resources() fixture
Fix warning from hypothesis above scope of resources() fixture
Python
mpl-2.0
pikepdf/pikepdf,pikepdf/pikepdf,pikepdf/pikepdf
34977275dc0502896846e937097d18d31103bcb0
tests/conftest.py
tests/conftest.py
"""Global test configuration""" import os from pathlib import Path import betamax import pytest from mccurse import curse # Ensure cassete dir CASSETE_DIR = 'tests/cassetes/' if not os.path.exists(CASSETE_DIR): os.makedirs(CASSETE_DIR) record_mode = 'none' if os.environ.get('TRAVIS_BUILD') else 'once' with ...
"""Global test configuration""" import os from pathlib import Path import betamax import pytest from mccurse import addon, curse # Ensure cassete dir CASSETE_DIR = 'tests/cassetes/' if not os.path.exists(CASSETE_DIR): os.makedirs(CASSETE_DIR) record_mode = 'none' if os.environ.get('TRAVIS_BUILD') else 'once'...
Add shared fixtures for Mod and Game
Add shared fixtures for Mod and Game
Python
agpl-3.0
khardix/mccurse
ef695f9bbd24c88fd3b802c8964313c5a182fed5
accelerator/tests/test_program_cycle.py
accelerator/tests/test_program_cycle.py
# MIT License # Copyright (c) 2017 MassChallenge, Inc. from __future__ import unicode_literals from django.test import TestCase from accelerator.tests.factories import ProgramCycleFactory class TestProgramCycle(TestCase): def test_display_name_no_short_name(self): cycle = ProgramCycleFactory(short_name...
# MIT License # Copyright (c) 2017 MassChallenge, Inc. from __future__ import unicode_literals from django.test import TestCase from accelerator.tests.factories import ProgramCycleFactory class TestProgramCycle(TestCase): def test_display_name_no_short_name(self): cycle = ProgramCycleFactory(short_name...
Add tests for the functionality added
[AC-7049] Add tests for the functionality added
Python
mit
masschallenge/django-accelerator,masschallenge/django-accelerator
ba3d399c8c959dcfbf2d507a8b2767b26625f9ae
app/models/compare.py
app/models/compare.py
# 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 the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be usefu...
# 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 the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be usefu...
Add build comparison model keys
Add build comparison model keys
Python
lgpl-2.1
kernelci/kernelci-backend,kernelci/kernelci-backend
8564a355473afe76c307701c5c347d58d0f7ca18
test_ir.py
test_ir.py
import unittest import kerneltest class IRkernelTests(kerneltest.KernelTests): kernel_name = "ir" language_name = "R" code_hello_world = "print('hello, world')" completion_samples = [ { 'text': 'zi', 'matches': {'zip'}, }, ] if __name__ == '__main__': ...
import unittest import kerneltest class IRkernelTests(kerneltest.KernelTests): kernel_name = "ir" language_name = "R" code_hello_world = "print('hello, world')" completion_samples = [ { 'text': 'zi', 'matches': {'zip'}, }, ] complete_code_samples = ['...
Add tests for is_complete requests
Add tests for is_complete requests
Python
mit
ibm-et/IRkernel,ibm-et/IRkernel
c092a9a836046aa098b8ac10f63bc60f70da9e76
tests/test_str.py
tests/test_str.py
import pytest from hypothesis import given from hypothesis.strategies import integers, text from datatyping.datatyping import validate @given(string=text()) def test_simple(string): assert validate(str, string) is None @given(not_string=integers()) def test_simple_error(not_string): with pytest.raises(Type...
import pytest from hypothesis import given from hypothesis.strategies import integers, text, lists, iterables, one_of from datatyping.datatyping import validate @given(string=text()) def test_simple(string): assert validate(str, string) is None @given(not_string=one_of(integers(), lists(integers()), iterables(...
Improve the str tests by adding bad types
Improve the str tests by adding bad types
Python
mit
Zaab1t/datatyping
4e8c3e66b6956c88adcf275d771d06fad0c0bb34
mrbelvedereci/build/utils.py
mrbelvedereci/build/utils.py
from django.core.paginator import EmptyPage from django.core.paginator import PageNotAnInteger from django.core.paginator import Paginator from mrbelvedereci.build.models import Build def paginate(build_list, request): page = request.GET.get('page') per_page = request.GET.get('per_page', '25') paginator = ...
from django.core.paginator import EmptyPage from django.core.paginator import PageNotAnInteger from django.core.paginator import Paginator from mrbelvedereci.build.models import Build def paginate(build_list, request): page = request.GET.get('page') per_page = request.GET.get('per_page', '25') paginator = ...
Change build listings to sort by -time_queue instead of -id so that rebuilds show up higher in the listing
Change build listings to sort by -time_queue instead of -id so that rebuilds show up higher in the listing
Python
bsd-3-clause
SalesforceFoundation/mrbelvedereci,SalesforceFoundation/mrbelvedereci,SalesforceFoundation/mrbelvedereci,SalesforceFoundation/mrbelvedereci
ae5626eaf36c6be94860d2a9570a777ff7f4e148
apps/client_config.py
apps/client_config.py
import superdesk from flask import current_app as app from superdesk.utils import ListCursor class ClientConfigResource(superdesk.Resource): item_methods = [] public_methods = ['GET'] resource_methods = ['GET'] class ClientConfigService(superdesk.Service): def get(self, req, lookup): retu...
import superdesk from flask import current_app as app from superdesk.utils import ListCursor class ClientConfigResource(superdesk.Resource): item_methods = [] public_methods = ['GET'] resource_methods = ['GET'] class ClientConfigService(superdesk.Service): def get(self, req, lookup): retu...
Add feedback url to served client configuration
[SDESK-2128] Add feedback url to served client configuration
Python
agpl-3.0
superdesk/superdesk-core,petrjasek/superdesk-core,mugurrus/superdesk-core,mdhaman/superdesk-core,ioanpocol/superdesk-core,ioanpocol/superdesk-core,mugurrus/superdesk-core,ioanpocol/superdesk-core,superdesk/superdesk-core,mdhaman/superdesk-core,petrjasek/superdesk-core,petrjasek/superdesk-core,hlmnrmr/superdesk-core,mug...
ab98637aa949a02618f6b119983f40bcbde80d43
examples/play_series_montecarlo_vs_random.py
examples/play_series_montecarlo_vs_random.py
from capstone.game import TicTacToe from capstone.player import MonteCarlo, RandPlayer from capstone.util import play_series game = TicTacToe() players = [MonteCarlo(), RandPlayer()] n_matches = 10 play_series(game, players, n_matches) players.reverse() play_series(game, players, n_matches)
from capstone.game import TicTacToe from capstone.player import MonteCarlo, RandPlayer from capstone.util import play_series game = TicTacToe() players = [MonteCarlo(), RandPlayer()] n_matches = 10 play_series(game, players, n_matches) print('') players.reverse() play_series(game, players, n_matches)
Add line break to play series monte carlo
Add line break to play series monte carlo
Python
mit
davidrobles/mlnd-capstone-code
dec2d1ce9bf0be0fa8e00b004ee59bfb66d4444a
wordpaths.py
wordpaths.py
import argparse from wp.main import WordPath def run(first_word, last_word): word_path = WordPath() word_path.load_word_list('tests/functional/misc/words', len(first_word)) chain = word_path.find(first_word, last_word) print(' > '.join(chain)) if __name__ == '__main__': parser = argparse.Argum...
#!/usr/bin/python import argparse from wp.main import WordPath def run(first_word, last_word): word_path = WordPath() word_path.load_word_list('tests/functional/misc/words', len(first_word)) chain = word_path.find(first_word, last_word) print(' > '.join(chain)) if __name__ == '__main__': parse...
Add shebang to main python script
Add shebang to main python script
Python
mit
reinaldons/word_paths,reinaldons/word_paths
3c44db39295945d544ba5a9fc20b2c5dddf4346d
nodeconductor/core/mixins.py
nodeconductor/core/mixins.py
from __future__ import unicode_literals from rest_framework import mixins from nodeconductor.core.models import SynchronizableMixin, SynchronizationStates from nodeconductor.core.exceptions import IncorrectStateException class ListModelMixin(mixins.ListModelMixin): def __init__(self, *args, **kwargs): i...
from __future__ import unicode_literals from rest_framework import mixins from nodeconductor.core.models import SynchronizableMixin, SynchronizationStates from nodeconductor.core.exceptions import IncorrectStateException class ListModelMixin(mixins.ListModelMixin): def __init__(self, *args, **kwargs): i...
Allow delete operation in NEW state
Allow delete operation in NEW state - nc-1148
Python
mit
opennode/nodeconductor,opennode/nodeconductor,opennode/nodeconductor
b6ccc6b6ae6c5fab45f7a27dbecbda88cc8775b8
SplitNavigation.py
SplitNavigation.py
import sublime, sublime_plugin class SplitNavigationCommand(sublime_plugin.TextCommand): def run(self, edit, direction): win = self.view.window() num = win.num_groups() act = win.active_group() if direction == "up": act = act + 1 else: act = act - 1 win.focus_group(act % num)
import sublime, sublime_plugin def focusNext(win): act = win.active_group() num = win.num_groups() act += 1 if act >= num: act = 0 win.focus_group(act) if len(win.views_in_group(act)) == 0: focusNext(win) def focusPrev(win): act = win.active_group() num = win.num_groups() act -= 1 if act < 0: act...
Fix some weird action when user navigates between blank groups.
Fix some weird action when user navigates between blank groups.
Python
mit
oleander/sublime-split-navigation,oleander/sublime-split-navigation
08edbb1b723880ac81b63e5d1ca31c331f79b0a8
awx/api/pagination.py
awx/api/pagination.py
# Copyright (c) 2015 Ansible, Inc. # All Rights Reserved. # Django REST Framework from rest_framework import pagination from rest_framework.utils.urls import replace_query_param class Pagination(pagination.PageNumberPagination): page_size_query_param = 'page_size' def get_next_link(self): if not se...
# Copyright (c) 2015 Ansible, Inc. # All Rights Reserved. # Django REST Framework from rest_framework import pagination from rest_framework.utils.urls import replace_query_param class Pagination(pagination.PageNumberPagination): page_size_query_param = 'page_size' max_page_size = 200 def get_next_link(...
Set an upper limit of 200 on the max page size
Set an upper limit of 200 on the max page size
Python
apache-2.0
snahelou/awx,wwitzel3/awx,snahelou/awx,wwitzel3/awx,snahelou/awx,snahelou/awx,wwitzel3/awx,wwitzel3/awx
32a3ab4f677086916bdba6e7a8be41c9e62d7da0
appengine_config.py
appengine_config.py
"""Configuration.""" import logging import os import re from google.appengine.ext.appstats import recording logging.info('Loading %s from %s', __name__, __file__) # Custom webapp middleware to add Appstats. def webapp_add_wsgi_middleware(app): app = recording.appstats_wsgi_middleware(app) return app # Custom A...
"""Configuration.""" import logging import os import re from google.appengine.ext.appstats import recording logging.info('Loading %s from %s', __name__, __file__) # Custom webapp middleware to add Appstats. def webapp_add_wsgi_middleware(app): app = recording.appstats_wsgi_middleware(app) return app # Custom A...
Improve custom appstats path normalization.
Improve custom appstats path normalization.
Python
apache-2.0
ligthyear/quick-check,ligthyear/quick-check
2fbead7ee90847a5c47d152f086d4a96f52733ce
LFI.TESTER.py
LFI.TESTER.py
import sys import urllib2 import getopt import time target = '' depth = 10 file = 'etc/passwd' html = '' prefix = '' url = '' def usage(): print "usage function" try: opts,args = getopt.getopt(sys.argv[1:],"ht:",["help","target="]) for opt, arg in opts: if opt in("-h","--help"): usage() sys.exit()...
import sys import urllib2 import getopt import time target = '' depth = 6 file = 'etc/passwd' html = '' prefix = '' url = '' keyword='root' def usage(): print "usage function" try: opts,args = getopt.getopt(sys.argv[1:],"ht:d:f:k:",["help","target=","depth=","file=","keyword="]) for opt, arg in opts: if o...
Add Deepth File And KeyWord Options
Add Deepth File And KeyWord Options
Python
apache-2.0
KaiyiZhang/Secipt,KaiyiZhang/Secipt,KaiyiZhang/Secipt
0c2a7bfebbb6d427ffea66f4a8df534c5b8be974
timed/subscription/admin.py
timed/subscription/admin.py
from django.contrib import admin from . import models @admin.register(models.Package) class PackageAdmin(admin.ModelAdmin): list_display = ['billing_type', 'duration', 'price']
from django import forms from django.contrib import admin from django.utils.translation import ugettext_lazy as _ from timed.forms import DurationInHoursField from . import models class PackageForm(forms.ModelForm): model = models.Package duration = DurationInHoursField( label=_('Duration in hours')...
Configure duration field on subscription package in hours
Configure duration field on subscription package in hours
Python
agpl-3.0
adfinis-sygroup/timed-backend,adfinis-sygroup/timed-backend,adfinis-sygroup/timed-backend
c745a6807a26173033bdbea8387e9c10275bb88d
step_stool/content.py
step_stool/content.py
__author__ = 'Chris Krycho' __copyright__ = '2013 Chris Krycho' from logging import error from os import path, walk from sys import exit try: from markdown import Markdown from mixins import DictAsMember except ImportError as import_error: error(import_error) exit() def convert_source(config): ...
__author__ = 'Chris Krycho' __copyright__ = '2013 Chris Krycho' from logging import error from os import path, walk from sys import exit try: from markdown import Markdown from mixins import DictAsMember except ImportError as import_error: error(import_error) exit() def convert_source(config): ...
Call the reset() method in the Markdown object to clear extensions (e.g. metadata) between processing each file.
Call the reset() method in the Markdown object to clear extensions (e.g. metadata) between processing each file.
Python
mit
chriskrycho/step-stool,chriskrycho/step-stool
77346899a001be6cee1f2bda50156647e6bca87a
deployer/views/util.py
deployer/views/util.py
import json from flask import Response def build_response(output, status=200, mimetype='application/json', headers={}): return Response( json.dumps(output), mimetype=mimetype ), status, headers
import json from flask import Response, jsonify def build_response(output, status=200, mimetype='application/json', headers={}): resp = jsonify(output) resp.mimetype = mimetype return resp, status, headers
Fix issue with datetime handling
Fix issue with datetime handling
Python
mit
totem/cluster-deployer,totem/cluster-deployer,totem/cluster-deployer
10494456af67270f28853872dd8072f01872b6db
src/pipelines/views.py
src/pipelines/views.py
from django.contrib.auth.mixins import LoginRequiredMixin from django.views.generic import CreateView from .forms import AbstractPipelineCreateForm class AbstractPipelineFormView(LoginRequiredMixin, CreateView): form_class = AbstractPipelineCreateForm template_name = None def get_form_kwargs(self): ...
from django.contrib import messages from django.contrib.auth.mixins import LoginRequiredMixin from django.utils.translation import ugettext_lazy as _ from django.views.generic import CreateView from .forms import AbstractPipelineCreateForm class AbstractPipelineFormView(LoginRequiredMixin, CreateView): form_cla...
Add message after successfully created an new analysis
Add message after successfully created an new analysis
Python
mit
ccwang002/biocloud-server-kai,ccwang002/biocloud-server-kai,ccwang002/biocloud-server-kai
d24cd893e3969eba6b23ee98ff0787622685f8c6
bin/testconnection.py
bin/testconnection.py
#!/usr/bin/python import psycopg2 import sys import os def parse_connection_uri(): here, _ = os.path.split(__file__) with open(os.path.join(here, '../portal/application.cfg'), 'r') as fh: conn_strings = [l for l in fh.readlines() if l.startswith('SQLALCHEMY_DATABASE_URI')] ...
#!/usr/bin/env python import psycopg2 import sys import os def parse_connection_uri(): here, _ = os.path.split(__file__) with open(os.path.join(here, '../instance/application.cfg'), 'r') as fh: conn_strings = [l for l in fh.readlines() if l.startswith('SQLALCHEMY_DATABASE_URI')]...
Use virtualenv python & look for config file in new instance directory.
Use virtualenv python & look for config file in new instance directory.
Python
bsd-3-clause
uwcirg/true_nth_usa_portal,uwcirg/true_nth_usa_portal,uwcirg/true_nth_usa_portal,uwcirg/true_nth_usa_portal
34af1fdb4f6c9c8b994cb710b97fe0ed9e1311a7
setup.py
setup.py
import os import glob from numpy.distutils.core import setup, Extension version = (os.popen('git config --get remote.origin.url').read() + ',' + os.popen('git describe --always --tags --dirty').read()) scripts = [] setup(name='matscipy', version=version, description='Generic Python Materials S...
import os import glob from numpy.distutils.core import setup, Extension version = (os.popen('git config --get remote.origin.url').read() + ',' + os.popen('git describe --always --tags --dirty').read()) scripts = [] setup(name='matscipy', version=version, description='Generic Python Materials S...
Add matscipy.fracture_mechanics to packages list to install subpackage
Add matscipy.fracture_mechanics to packages list to install subpackage
Python
lgpl-2.1
libAtoms/matscipy,libAtoms/matscipy,libAtoms/matscipy,libAtoms/matscipy
3193abd844bae92159258a5cc80221e9a7d16b06
setup.py
setup.py
#!/usr/bin/env python from distutils.core import setup from catkin_pkg.python_setup import generate_distutils_setup d = generate_distutils_setup( packages=['xacro'], package_dir={'': 'src'}, scripts=['scripts/xacro.py'] ) setup(**d)
#!/usr/bin/env python from distutils.core import setup from catkin_pkg.python_setup import generate_distutils_setup d = generate_distutils_setup( packages=['xacro'], package_dir={'': 'src'} ) setup(**d)
Remove bin copy of xacro.py
Remove bin copy of xacro.py
Python
bsd-3-clause
ros/xacro,ros/xacro
34b80fdca9387c05cf9000cd2c19b619aadff6e9
app/blog/management/commands/check_posts_state.py
app/blog/management/commands/check_posts_state.py
import os import logging from django.core.management.base import BaseCommand from blog.models import Post logger = logging.getLogger('app') class Command(BaseCommand): help = 'Check posts state' def handle(self, *args, **options): checked = 0 for post in Post.objects.all(): try...
import os import logging from django.core.management.base import BaseCommand from blog.models import Post logger = logging.getLogger('app') class Command(BaseCommand): help = 'Check posts state' def handle(self, *args, **options): checked = 0 for post in Post.objects.all(): try...
Update check posts state command
Update check posts state command
Python
bsd-3-clause
manti-by/M2MICRO,manti-by/M2MICRO,manti-by/M2-Blog-Engine,manti-by/M2-Blog-Engine,manti-by/M2MICRO,manti-by/M2-Blog-Engine,manti-by/m2,manti-by/m2,manti-by/m2,manti-by/M2MICRO,manti-by/M2-Blog-Engine,manti-by/m2
fa1a08aed5bc6659304097d5ad7e653c553c1b11
cactus/utils/file.py
cactus/utils/file.py
#coding:utf-8 import os import cStringIO import gzip import hashlib from cactus.utils.helpers import checksum class FakeTime: """ Monkey-patch gzip.time to avoid changing files every time we deploy them. """ def time(self): return 1111111111.111 def compressString(s): """Gzip a given st...
#coding:utf-8 import os import cStringIO import gzip import hashlib import subprocess from cactus.utils.helpers import checksum class FakeTime: """ Monkey-patch gzip.time to avoid changing files every time we deploy them. """ def time(self): return 1111111111.111 def compressString(s): ...
Use terminal md5 for perf
Use terminal md5 for perf
Python
bsd-3-clause
koenbok/Cactus,danielmorosan/Cactus,juvham/Cactus,dreadatour/Cactus,Bluetide/Cactus,chaudum/Cactus,koobs/Cactus,chaudum/Cactus,PegasusWang/Cactus,juvham/Cactus,eudicots/Cactus,Knownly/Cactus,danielmorosan/Cactus,page-io/Cactus,juvham/Cactus,fjxhkj/Cactus,koobs/Cactus,ibarria0/Cactus,PegasusWang/Cactus,danielmorosan/Cac...
09c0c2302460c6e32419f640b341c4b968d4227a
opendebates/tests/test_context_processors.py
opendebates/tests/test_context_processors.py
import urlparse from django.test import TestCase, override_settings from django.conf import settings from mock import patch, Mock from opendebates.context_processors import global_vars from opendebates.tests.factories import SubmissionFactory class NumberOfVotesTest(TestCase): def test_number_of_votes(self): ...
import urlparse from django.test import TestCase, override_settings from django.conf import settings from mock import patch, Mock from opendebates.context_processors import global_vars from opendebates.tests.factories import SubmissionFactory class NumberOfVotesTest(TestCase): def test_number_of_votes(self): ...
Fix type in overridden setting
Fix type in overridden setting
Python
apache-2.0
caktus/django-opendebates,ejucovy/django-opendebates,ejucovy/django-opendebates,caktus/django-opendebates,ejucovy/django-opendebates,caktus/django-opendebates,ejucovy/django-opendebates,caktus/django-opendebates
d816c7207d21c2c379f9409eebc42f4feb88afd9
attorch/constraints.py
attorch/constraints.py
def positive(weight): weight.data *= weight.data.ge(0).float() def negative(weight): weight.data *= weight.data.le(0).float() def positive_except_self(weight): pos = weight.data.ge(0).float() if pos.size()[2] % 2 == 0 or pos.size()[3] % 2 == 0: raise ValueError('kernel size must be odd') ...
from torch import nn def constrain_all(self): if hasattr(self, 'constrain'): self.constrain() for c in self.children(): c.constrain_all() # extend torch nn.Module to have constrain_all function nn.Module.constrain_all = constrain_all def positive(weight, cache=None): weight.data *= wei...
Add constraining extension to nn.Module
Add constraining extension to nn.Module
Python
mit
fabiansinz/attorch,atlab/attorch,eywalker/attorch
e05093338c6c2fa155ea4ffe102bb6fa9a9b5e0e
__init__.py
__init__.py
import spyral.memoize import spyral.point import spyral.camera import spyral.util import spyral.sprite import spyral.gui import spyral.scene import spyral._lib import spyral.event import pygame director = scene.Director() def init(): pygame.init() pygame.font.init() def quit(): pygame.quit() spyr...
""" Spyral, an awesome library for making games. """ __version__ = '0.1' __license__ = 'LGPLv2' __author__ = 'Robert Deaton' import spyral.memoize import spyral.point import spyral.camera import spyral.util import spyral.sprite import spyral.gui import spyral.scene import spyral._lib import spyral.event import pygame...
Make this more like a real python module.
Make this more like a real python module.
Python
lgpl-2.1
platipy/spyral
7b1f62b9eb561680d73daa2c201040850352727b
__init__.py
__init__.py
import account import account_move import account_move_line import partner import account_voucher_line import payment_selection import wizard import res_user
import account import account_move import account_move_line import partner import account_voucher import account_voucher_line import payment_selection import wizard import res_user
Fix bug when posting account_voucher in the case voucher line were in company currency Voucher computation considered a 100% exchange difference instead of ignoring the foreign amount computation.
Fix bug when posting account_voucher in the case voucher line were in company currency Voucher computation considered a 100% exchange difference instead of ignoring the foreign amount computation.
Python
agpl-3.0
xcgd/account_streamline
f1ac6853d9502023462b5d55dc16c45658733a4a
plugins/chrome_extensions.py
plugins/chrome_extensions.py
################################################################################################### # # chrome_extensions.py # Adds the name and description of each Chrome extension found in a URLItem to the Interpretation field # # Plugin Author: Ryan Benson (ryan@obsidianforensics.com) # ###########################...
################################################################################################### # # chrome_extensions.py # Adds the name and description of each Chrome extension found in a URLItem to the Interpretation field # # Plugin Author: Ryan Benson (ryan@obsidianforensics.com) # ###########################...
Update to work with new method of storing extension data.
Update to work with new method of storing extension data.
Python
apache-2.0
obsidianforensics/hindsight,obsidianforensics/hindsight
11ac44c41d9cd3431b7f2cc833656665c8a9947b
reddit_adzerk/adzerkads.py
reddit_adzerk/adzerkads.py
from urllib import quote from pylons import c, g from r2.lib.pages import Ads as BaseAds class Ads(BaseAds): def __init__(self): BaseAds.__init__(self) url_key = "adzerk_https_url" if c.secure else "adzerk_url" site_name = getattr(c.site, "analytics_name", c.site.name) self.ad_u...
from urllib import quote from pylons import c, g from r2.lib.pages import Ads as BaseAds from r2.models.subreddit import DefaultSR class Ads(BaseAds): def __init__(self): BaseAds.__init__(self) url_key = "adzerk_https_url" if c.secure else "adzerk_url" site_name = getattr(c.site, "analy...
Change frontpage keyword to "-reddit.com".
Change frontpage keyword to "-reddit.com".
Python
bsd-3-clause
madbook/reddit-plugin-adzerk,madbook/reddit-plugin-adzerk,madbook/reddit-plugin-adzerk
3b773f6b046215e8ef1a8cc701f9200bc7078964
test_octave_kernel.py
test_octave_kernel.py
"""Example use of jupyter_kernel_test, with tests for IPython.""" import unittest import jupyter_kernel_test as jkt class OctaveKernelTests(jkt.KernelTests): kernel_name = "octave" language_name = "octave" code_hello_world = "disp('hello, world')" completion_samples = [ { 'text...
"""Example use of jupyter_kernel_test, with tests for IPython.""" import unittest import jupyter_kernel_test as jkt class OctaveKernelTests(jkt.KernelTests): kernel_name = "octave" language_name = "octave" code_hello_world = "disp('hello, world')" code_display_data = [ {'code': '%plot -f p...
Add plot handling to test
Add plot handling to test
Python
bsd-3-clause
Calysto/octave_kernel,Calysto/octave_kernel
35b8dd77be54872bcf17b62e288cd4a2b5a37e5a
viper.py
viper.py
#!/usr/bin/env python3 from viper.interactive import * from viper.lexer import lex_file from viper.grammar import GRAMMAR if __name__ == '__main__': import argparse parser = argparse.ArgumentParser() parser.add_argument('-L', '--interactive-lexer', action='store_true', help='lexes input') parser.add_...
#!/usr/bin/env python3 from viper.interactive import * from viper.lexer import lex_file, NewLine from viper.grammar import GRAMMAR if __name__ == '__main__': import argparse parser = argparse.ArgumentParser() parser.add_argument('-L', '--interactive-lexer', action='store_true', help='lexes input') pa...
Add CLI option for outputting lexed files
Add CLI option for outputting lexed files
Python
apache-2.0
pdarragh/Viper
f9cc9e73774f2d3f4a9525e174976b912ba2bbba
ci/release.py
ci/release.py
import os import sys import xmlrpclib from shutil import rmtree from subprocess import check_call TEMP_DIR = 'tmp' PROJECT_NAME = 'cctrl' DIST_DIR = os.path.join(TEMP_DIR, 'dist') def main(): if is_current_version(): sys.exit("Version is not updated. Aborting release.") dist() cleanup() def i...
import os import sys import xmlrpclib from shutil import rmtree from subprocess import check_call TEMP_DIR = 'tmp' PROJECT_NAME = 'cctrl' DIST_DIR = os.path.join(TEMP_DIR, 'dist') def main(): if is_current_version(): sys.exit("Version is not updated. Aborting release.") dist() cleanup() def i...
Exit with error if dist upload fails
ci: Exit with error if dist upload fails
Python
apache-2.0
cloudControl/cctrl,cloudControl/cctrl
7512f4b5fb5ebad5781e76ecd61c0e2d24b54f6c
projects/urls.py
projects/urls.py
from django.conf import settings from django.conf.urls import include, url from django.views.generic import TemplateView # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() # Include any views from . import views urlpatterns = [ url(r'^$', views.index, name...
# This file is part of the FragDev Website. # # the FragDev Website is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # the FragDev W...
Add license statement, removed unused code, and set up the project URL mapping
Add license statement, removed unused code, and set up the project URL mapping
Python
agpl-3.0
lo-windigo/fragdev,lo-windigo/fragdev
e336b9d7648a9705f525905ba994f0b3612189a6
tests/test_convert.py
tests/test_convert.py
import pytest # type: ignore from hypothesis import given from ppb_vector import Vector2 from utils import vector_likes, vectors class V(Vector2): pass @pytest.mark.parametrize('vector_like', vector_likes(), ids=lambda x: type(x).__name__) # type: ignore @pytest.mark.parametrize('cls', [Vector2, V]) # type: ignore ...
import pytest # type: ignore from hypothesis import given from ppb_vector import Vector2 from utils import vector_likes, vectors class V(Vector2): pass @pytest.mark.parametrize('vector_like', vector_likes(), ids=lambda x: type(x).__name__) # type: ignore @pytest.mark.parametrize('cls', [Vector2, V]) # type: ignore ...
Add a round-trip test for tuple and list conversions
tests/convert: Add a round-trip test for tuple and list conversions
Python
artistic-2.0
ppb/ppb-vector,ppb/ppb-vector
8415776bb4d5b402aef43ab777072060420bd6b4
cloudly/ccouchdb.py
cloudly/ccouchdb.py
import os import couchdb from cloudly.memoized import Memoized import cloudly.logger as logger log = logger.init(__name__) @Memoized def get_server(hostname=None, port=5984, username=None, password=None): port = 5984 host = hostname or os.environ.get("COUCHDB_HOST", "127.0.0.1") url = "http://{host}:{p...
import os import yaml import couchdb from cloudly.memoized import Memoized import cloudly.logger as logger log = logger.init(__name__) @Memoized def get_server(hostname=None, port=None, username=None, password=None): host = hostname or os.environ.get("COUCHDB_HOST", "127.0.0.1") port = port or os.environ.g...
Add auth and a function to sync a design doc.
Add auth and a function to sync a design doc. With environment variables COUCHDB_USERNAME and COUCHDB_PASSWORD defined, will connect as that user. Now uses COUCHDB_PORT if defined. Add a function to save a design document defined as a YAML file. Why YAML? Because it's very easy to add Javascript code with syntax hig...
Python
mit
ooda/cloudly,ooda/cloudly
f70e0ec9ac51928fbd5ff9159859a9116227c3b9
pyglab/pyglab.py
pyglab/pyglab.py
_defaults = { 'api_url': 'api/v3', } from .apirequest import ApiRequest, RequestType from .users import Users class Pyglab(object): def __init__(self, url, token, api_url=_defaults['api_url']): self._base_url = url.rstrip('/') + '/' + api_url.strip() self._token = token self._user = No...
_defaults = { 'api_url': 'api/v3', } from .apirequest import ApiRequest, RequestType from .users import Users class Pyglab(object): def __init__(self, url, token, api_url=_defaults['api_url']): self._base_url = url.rstrip('/') + '/' + api_url.strip() self._token = token self._user = No...
Add capability to login through (name|email), password combination.
Add capability to login through (name|email), password combination.
Python
mit
sloede/pyglab,sloede/pyglab
3764bd2303df873d93a2d75311b27c9c632409b4
awx/wsgi.py
awx/wsgi.py
# Copyright (c) 2014 AnsibleWorks, Inc. # All Rights Reserved. """ WSGI config for AWX project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/dev/howto/deployment/wsgi/ """ # Prepare the AWX environment. from a...
# Copyright (c) 2014 AnsibleWorks, Inc. # All Rights Reserved. """ WSGI config for AWX project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/dev/howto/deployment/wsgi/ """ # Prepare the AWX environment. from a...
Reword errors when version metadata does not match or is absent
Reword errors when version metadata does not match or is absent
Python
apache-2.0
snahelou/awx,wwitzel3/awx,wwitzel3/awx,snahelou/awx,wwitzel3/awx,wwitzel3/awx,snahelou/awx,snahelou/awx
75075e85ef82aabee2a261b6a58502b32c60d348
tests/test_project/gallery/models.py
tests/test_project/gallery/models.py
from django.db import models from pyuploadcare.dj.models import FileField, ImageField, ImageGroupField class Gallery(models.Model): title = models.CharField(max_length=255) def __unicode__(self): return self.title class Photo(models.Model): gallery = models.ForeignKey(Gallery) title = mo...
from django.db import models from pyuploadcare.dj.models import FileField, ImageField, ImageGroupField class Gallery(models.Model): title = models.CharField(max_length=255) def __unicode__(self): return self.title class Photo(models.Model): gallery = models.ForeignKey(Gallery, on_delete=mode...
Add `on_delete` argument for `Photo.gallery` field
Add `on_delete` argument for `Photo.gallery` field
Python
mit
uploadcare/pyuploadcare
f49857658b992240eaf6627d153afb4808e366fb
warehouse/defaults.py
warehouse/defaults.py
from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals # The base domain name for this installation. Used to control linking to # sub-domains. SERVER_NAME = "warehouse.local:5000" # The URI for our PostgreSQL database. SQLALCHEMY_DATABASE_URI = "postgres://...
from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals # The base domain name for this installation. Used to control linking to # sub-domains. SERVER_NAME = "warehouse.local:5000" # The URI for our PostgreSQL database. SQLALCHEMY_DATABASE_URI = "postgres://...
Configure the default STORAGE_OPTION to enable a dummy url
Configure the default STORAGE_OPTION to enable a dummy url
Python
bsd-2-clause
davidfischer/warehouse
272ece1774cebaf8d6d6ae9e0dfb5fe0cce97083
manage.py
manage.py
#!/usr/bin/env python import os import sys if __name__ == '__main__': os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'conductor.settings.development') if 'test' in sys.argv: # For now, fake setting the environment for testing. os.environ['DJANGO_SETTINGS_MODULE'] = 'conductor.settings.test' ...
#!/usr/bin/env python import os import sys if __name__ == '__main__': os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'conductor.settings.development') if 'test' in sys.argv: # For now, fake setting the environment for testing. os.environ['DJANGO_SETTINGS_MODULE'] = 'conductor.settings.test' ...
Add missing env variables for testing.
Add missing env variables for testing.
Python
bsd-2-clause
mblayman/lcp,mblayman/lcp,mblayman/lcp
ae629597067817457db9e86121dde7f6ee3a2b7d
stagecraft/libs/request_logger/middleware.py
stagecraft/libs/request_logger/middleware.py
# encoding: utf-8 from __future__ import unicode_literals import logging import time logger = logging.getLogger(__name__) class RequestLoggerMiddleware(object): def process_request(self, request): self.request_time = time.time() logger.info("{method} {path}".format( method=request.m...
# encoding: utf-8 from __future__ import unicode_literals import logging import time logger = logging.getLogger(__name__) class RequestLoggerMiddleware(object): def process_request(self, request): request.start_request_time = time.time() logger.info("{method} {path}".format( method=...
Fix thread-safety issue in stagecraft
Fix thread-safety issue in stagecraft Django middleware is not thread-safe. We should store this context on the request object instance. Django always calls `process_response`, but it is possible that `process_request` has been skipped. So we have a guard checking that it’s safe to log the response time. See https:/...
Python
mit
alphagov/stagecraft,alphagov/stagecraft,alphagov/stagecraft,alphagov/stagecraft
bd9fc1b2adea718be089b8370d2e82ea55af6539
.gitlab/linters/check-cpp.py
.gitlab/linters/check-cpp.py
#!/usr/bin/env python3 # A linter to warn for ASSERT macros which are separated from their argument # list by a space, which Clang's CPP barfs on from linter import run_linters, RegexpLinter linters = [ RegexpLinter(r'WARN\s+\(', message='CPP macros should not have a space between the macro name...
#!/usr/bin/env python3 # A linter to warn for ASSERT macros which are separated from their argument # list by a space, which Clang's CPP barfs on from pathlib import Path from linter import run_linters, RegexpLinter linters = [ RegexpLinter(r'WARN\s+\(', message='CPP macros should not have a spa...
Make CPP linter skip certain files
Make CPP linter skip certain files - docs which document the lint and need to contain the unutterable - vendored code which is outside our purview
Python
bsd-3-clause
sdiehl/ghc,sdiehl/ghc,sdiehl/ghc,sdiehl/ghc,sdiehl/ghc,sdiehl/ghc,sdiehl/ghc
edc3a902a64c364168df6c10ebb825bd9e65a974
basin/urls.py
basin/urls.py
from django.conf.urls import patterns, include, url from django.contrib import admin from basin.routers import api_router admin.autodiscover() urlpatterns = patterns('', url(r'^$', 'basin.views.index'), url(r'^display/', 'basin.views.display'), url(r'^api/', include(api_router.urls)), url(r'^admin/',...
from django.conf.urls import patterns, include, url from django.contrib import admin from basin.routers import api_router admin.autodiscover() urlpatterns = patterns('', url(r'^$', 'basin.views.display'), url(r'^backbone/', 'basin.views.index'), url(r'^api/', include(api_router.urls)), url(r'^admin/'...
Move static mockup to root
Move static mockup to root
Python
mit
Pringley/basinweb,Pringley/basinweb
cec10f55b280311161033ad3c9457b20822f7353
geotrek/outdoor/migrations/0003_auto_20201214_1408.py
geotrek/outdoor/migrations/0003_auto_20201214_1408.py
# Generated by Django 3.1.4 on 2020-12-14 14:08 from django.conf import settings import django.contrib.gis.db.models.fields from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('outdoor', '0002_practice_sitepractice'), ] ...
# Generated by Django 3.1.4 on 2020-12-14 14:08 from django.conf import settings import django.contrib.gis.db.models.fields from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('outdoor', '0002_practice_sitepractice'), ] ...
Fix migration Site geom to GeometryCollection
Fix migration Site geom to GeometryCollection
Python
bsd-2-clause
GeotrekCE/Geotrek-admin,GeotrekCE/Geotrek-admin,makinacorpus/Geotrek,GeotrekCE/Geotrek-admin,makinacorpus/Geotrek,GeotrekCE/Geotrek-admin,makinacorpus/Geotrek,makinacorpus/Geotrek
e824d8ad284603b73df48f1a413b129280318937
examples/annotation.py
examples/annotation.py
# encoding: utf-8 """Basic class-based demonstration application. Applications can be as simple or as complex and layered as your needs dictate. """ class Root(object): def __init__(self, context): self._ctx = context def mul(self, a: int = None, b: int = None) -> 'json': if not a and not b...
# encoding: utf-8 """Basic class-based demonstration application. Applications can be as simple or as complex and layered as your needs dictate. """ class Root(object): def __init__(self, context): self._ctx = context def mul(self, a: int = None, b: int = None) -> 'json': """Multiply two va...
Split the HTTPServer line into multiple.
Split the HTTPServer line into multiple. Also added comments and a docstring, since this is an example after all.
Python
mit
marrow/WebCore,marrow/WebCore
1c76ec9c600b6a85f7a9a48b72c1c6c4f447ec24
capstone/player.py
capstone/player.py
import abc import six @six.add_metaclass(abc.ABCMeta) class Player(object): '''Interface for a Player of a Game''' @abc.abstractmethod def choose_move(self, move): pass
import abc import six @six.add_metaclass(abc.ABCMeta) class Player(object): '''Interface for a Player of a Game''' @abc.abstractmethod def choose_move(self, game): '''Returns the chosen move from game.legal_moves().''' pass
Rename move parameter to game
Rename move parameter to game
Python
mit
davidrobles/mlnd-capstone-code
ca321b449f16d966bccf3d30680819b6dafa00bc
normalize_data.py
normalize_data.py
import numpy as np from sklearn import preprocessing as pp print('normalization function imported') #normalize data in respect with keys in dictionary def normalize_data(data): # get keys from original data gestures = list(data) # create empty dictionary to store normalized data with gestures gda...
import numpy as np from sklearn import preprocessing as pp print('normalization function imported') #normalize data in respect with keys in dictionary def normalize_data(data): # get keys from original data gestures = list(data) # create empty dictionary to store normalized data with gestures gda...
Replace integer indices with ellipsis
Replace integer indices with ellipsis
Python
mit
JustinShenk/sonic-face,JustinShenk/sonic-face
a6702e839eec2b4d6d75f4126ed975456e9795dc
contacts/middleware.py
contacts/middleware.py
import logging from django.http import Http404 from gargoyle import gargoyle from contacts.models import Book sentry = logging.getLogger('sentry') class ContactBookMiddleware(object): def process_view(self, request, view_func, view_args, view_kwargs): if hasattr(request, 'user'): if request....
import logging from django.http import Http404 from gargoyle import gargoyle from contacts.models import Book sentry = logging.getLogger('sentry') class ContactBookMiddleware(object): def process_view(self, request, view_func, view_args, view_kwargs): # CONTRACT: At the end of this, if the user is authen...
Update ContactBook Middleware to obey contract
Update ContactBook Middleware to obey contract
Python
mit
phildini/logtacts,phildini/logtacts,phildini/logtacts,phildini/logtacts,phildini/logtacts
32410e639f3202c10d9c75083319a9ab81932b82
client/api.py
client/api.py
# Client uses HTTP API import os import sys import json import urllib import urllib2 import cookielib sys.path.append((os.path.dirname(__file__) or ".") + "/../") import config cj = cookielib.CookieJar() def callapi(action, postdata={}): postdata.update({"action": action}) opener = urllib2.build_opener(urll...
# Client uses HTTP API import os import sys import json import urllib import httplib import urllib2 import cookielib sys.path.append((os.path.dirname(__file__) or ".") + "/../") import config cj = cookielib.CookieJar() class HTTPSClientAuthHandler(urllib2.HTTPSHandler): def __init__(self, key): urllib2....
Use ssl client cert if given.
Use ssl client cert if given.
Python
agpl-3.0
vincebusam/pyWebCash,vincebusam/pyWebCash,vincebusam/pyWebCash
f13c08b2793b72f373785d2fa5b004ec79da93d6
flask_boost/project/application/models/user.py
flask_boost/project/application/models/user.py
# coding: utf-8 from datetime import datetime from werkzeug.security import generate_password_hash, check_password_hash from ._base import db class User(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(50), unique=True) email = db.Column(db.String(50), unique=True) av...
# coding: utf-8 from datetime import datetime from werkzeug.security import generate_password_hash, check_password_hash from ._base import db from ..utils.uploadsets import avatars class User(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(50), unique=True) email = db.Co...
Add avatar_url property to User.
Add avatar_url property to User.
Python
mit
1045347128/Flask-Boost,hustlzp/Flask-Boost,hustlzp/Flask-Boost,1045347128/Flask-Boost,1045347128/Flask-Boost,1045347128/Flask-Boost,hustlzp/Flask-Boost,hustlzp/Flask-Boost
41478d9ef0f8506ebe11ea5746450fe6dca02982
uplink/clients/io/__init__.py
uplink/clients/io/__init__.py
from uplink.clients.io.interfaces import ( Client, Executable, IOStrategy, RequestTemplate, ) from uplink.clients.io.execution import RequestExecutionBuilder from uplink.clients.io.templates import CompositeRequestTemplate from uplink.clients.io.blocking_strategy import BlockingStrategy from uplink.clie...
from uplink.clients.io.interfaces import ( Client, Executable, IOStrategy, RequestTemplate, ) from uplink.clients.io.execution import RequestExecutionBuilder from uplink.clients.io.templates import CompositeRequestTemplate from uplink.clients.io.blocking_strategy import BlockingStrategy __all__ = [ ...
Remove mandatory dependency on twisted
Remove mandatory dependency on twisted
Python
mit
prkumar/uplink
e0f6dba294e062d0a93b7cdf8a6c8fc1557671a2
cmsplugin_simple_markdown/models.py
cmsplugin_simple_markdown/models.py
from django.db import models from django.utils.translation import ugettext_lazy as _ from cms.models.pluginmodel import CMSPlugin class SimpleMarkdownPlugin(CMSPlugin): markdown_text = models.TextField(verbose_name=_('text')) def __unicode__(self): return self.markdown_text
import threading from django.db import models from django.utils.translation import ugettext_lazy as _ from cms.models.pluginmodel import CMSPlugin from cmsplugin_simple_markdown import utils localdata = threading.local() localdata.TEMPLATE_CHOICES = utils.autodiscover_templates() TEMPLATE_CHOICES = localdata.TEMPLATE...
Add template field to SimpleMarkdownPlugin model
Add template field to SimpleMarkdownPlugin model
Python
bsd-3-clause
Alir3z4/cmsplugin-simple-markdown,Alir3z4/cmsplugin-simple-markdown
e288e8a52df0ac67a24271c40e23ae054e39fa52
monascaclient/common/monasca_manager.py
monascaclient/common/monasca_manager.py
# (C) Copyright 2014 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 by...
# (C) Copyright 2014 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 by...
Fix metric dimensions having only key
Fix metric dimensions having only key When metric dimensions have only key, query parameter will be ending with ':' delimiter. But api can not handle this query parameter. So change to eliminate ':' delimiter when metric dimensions have only key. Change-Id: I1327f8fe641fe98cf16c28911ef19908468d1bc0
Python
apache-2.0
openstack/python-monascaclient,stackforge/python-monascaclient,sapcc/python-monascaclient,sapcc/python-monascaclient,stackforge/python-monascaclient,openstack/python-monascaclient
1991dc4c60a338c2a5c3548684160e6ff9e858a2
examples/expl_google.py
examples/expl_google.py
import re import mechanicalsoup # Connect to Google browser = mechanicalsoup.StatefulBrowser() browser.open("https://www.google.com/") # Fill-in the form browser.select_form('form[action="/search"]') browser["q"] = "MechanicalSoup" browser.submit_selected(btnName="btnG") # Display links for link in browser.links(): ...
import re import mechanicalsoup # Connect to Google browser = mechanicalsoup.StatefulBrowser() browser.open("https://www.google.com/") # Fill-in the form browser.select_form('form[action="/search"]') browser["q"] = "MechanicalSoup" # Note: the button name is btnK in the content served to actual # browsers, but btnG f...
Add comment about button name on google example
Add comment about button name on google example
Python
mit
MechanicalSoup/MechanicalSoup,hemberger/MechanicalSoup,hickford/MechanicalSoup
3ff24c90c9f50c849ea22e7d2d0a5fa11d1e777a
examples/hello-world.py
examples/hello-world.py
# ----------------------------------------------------------------------------- # Copyright (c) 2009-2016 Nicolas P. Rougier. All rights reserved. # Distributed under the (new) BSD License. # ----------------------------------------------------------------------------- from glumpy import app, gl, gloo, glm, data, text ...
# ----------------------------------------------------------------------------- # Copyright (c) 2009-2016 Nicolas P. Rougier. All rights reserved. # Distributed under the (new) BSD License. # ----------------------------------------------------------------------------- from glumpy import app, gl, gloo, glm, data from g...
Fix hello world example broken imports
Fix hello world example broken imports
Python
bsd-3-clause
glumpy/glumpy,glumpy/glumpy
fe362e1950e8cc6c993223d7b7236e285e7a368f
neurodsp/plts/utils.py
neurodsp/plts/utils.py
"""Utility functions for NeuroDSP plots.""" import matplotlib.pyplot as plt ################################################################################################### ################################################################################################### def check_ax(ax, figsize=None): """Ch...
"""Utility functions for NeuroDSP plots.""" from functools import wraps from os.path import join as pjoin import matplotlib.pyplot as plt ################################################################################################### ###############################################################################...
Add decorator for saving plts
Add decorator for saving plts
Python
apache-2.0
voytekresearch/neurodsp,srcole/neurodsp,srcole/neurodsp
355b78dfa8be2000a1e3198231088c7b3cec0d18
alexandria/__init__.py
alexandria/__init__.py
import logging log = logging.getLogger(__name__) from pyramid.config import Configurator from sqlalchemy import engine_from_config from .models import DBSession required_settings = [ 'pyramid.secret.session', 'pyramid.secret.auth', ] def main(global_config, **settings): """ This function...
import logging log = logging.getLogger(__name__) from pyramid.config import Configurator from sqlalchemy import engine_from_config from .models import DBSession required_settings = [ 'pyramid.secret.session', 'pyramid.secret.auth', ] def main(global_config, **settings): """ This function...
Set up the factory for the default route
Set up the factory for the default route
Python
isc
bertjwregeer/alexandria,bertjwregeer/alexandria,cdunklau/alexandria,cdunklau/alexandria,cdunklau/alexandria
b785fdc041a41f06c10e08d1e4e4b2bd4a5e5f90
tests/test_uploader.py
tests/test_uploader.py
"""Tests for the uploader module""" from __future__ import unicode_literals from __future__ import print_function from __future__ import division from __future__ import absolute_import from builtins import open from future import standard_library standard_library.install_aliases() from os.path import join from datap...
"""Tests for the uploader module""" from __future__ import unicode_literals from __future__ import print_function from __future__ import division from __future__ import absolute_import from datapackage import DataPackage from future import standard_library from gobble.user import User standard_library.install_alias...
Refactor uploader tests to use the fixture module.
Refactor uploader tests to use the fixture module.
Python
mit
openspending/gobble
69d013b768edabb6bc7dbe78b1f219ea1b49db16
sqlitebiter/_config.py
sqlitebiter/_config.py
#!/usr/bin/env python # encoding: utf-8 """ .. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com> """ from __future__ import absolute_import from __future__ import unicode_literals import appconfigpy from ._const import PROGRAM_NAME class ConfigKey(object): PROXY_SERVER = "proxy_server" GS_CREDE...
#!/usr/bin/env python # encoding: utf-8 """ .. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com> """ from __future__ import absolute_import from __future__ import unicode_literals import appconfigpy from ._const import PROGRAM_NAME class ConfigKey(object): DEFAULT_ENCODING = "default_encoding" ...
Add default encoding parameter to configure subcommand
Add default encoding parameter to configure subcommand
Python
mit
thombashi/sqlitebiter,thombashi/sqlitebiter
71677afa8e5146023dc63c28a187ad5610d5b90a
upsrv/conary_schema.py
upsrv/conary_schema.py
#!/usr/bin/python # # Copyright (c) SAS Institute Inc. # import sys import os import pwd from conary.server import schema from conary.lib import cfgtypes, tracelog from conary import dbstore from .config import UpsrvConfig class SimpleFileLog(tracelog.FileLog): def printLog(self, level, msg): self.fd.wri...
#!/usr/bin/python # # Copyright (c) SAS Institute Inc. # import sys import os import pwd from conary.server import schema from conary.lib import cfgtypes, tracelog from conary import dbstore from .config import UpsrvConfig class SimpleFileLog(tracelog.FileLog): def printLog(self, level, msg): self.fd.wri...
Fix traceback being emitted when updating a proxy-mode rus (RCE-2260)
Fix traceback being emitted when updating a proxy-mode rus (RCE-2260)
Python
apache-2.0
sassoftware/rbm,sassoftware/rbm,sassoftware/rbm
f4c8f003a4ffdd8e64468d261aa2cd34d58f1b9d
src/compdb/__init__.py
src/compdb/__init__.py
import warnings from signac import * msg = "compdb was renamed to signac. Please import signac in the future." warnings.warn(DeprecationWarning, msg)
import warnings from signac import * __all__ = ['core', 'contrib', 'db'] msg = "compdb was renamed to signac. Please import signac in the future." print('Warning!',msg) warnings.warn(msg, DeprecationWarning)
Add surrogate compdb package, linking to signac.
Add surrogate compdb package, linking to signac. Provided to guarantee compatibility. Prints warning on import.
Python
bsd-3-clause
csadorf/signac,csadorf/signac
a25d7cbe7a2fb583e08e642e846edd7d647f2013
tests/test_engine_import.py
tests/test_engine_import.py
import unittest import os from stevedore.extension import ExtensionManager ENGINES = [ 'lammps', 'openfoam', 'kratos', 'jyulb'] if os.getenv("HAVE_NUMERRIN", "no") == "yes": ENGINES.append("numerrin") class TestEngineImport(unittest.TestCase): def test_engine_import(self): extensio...
import unittest import os from stevedore.extension import ExtensionManager ENGINES = [ 'lammps', 'openfoam_file_io', 'openfoam_internal', 'kratos', 'jyulb_fileio_isothermal', 'jyulb_internal_isothermal'] if os.getenv("HAVE_NUMERRIN", "no") == "yes": ENGINES.append("numerrin") class Test...
Fix engine extension names for jyulb and openfoam
Fix engine extension names for jyulb and openfoam
Python
bsd-2-clause
simphony/simphony-framework
8a19543354a82f586d7aed7913c71e52dbd7d55c
src/librement/account/backends.py
src/librement/account/backends.py
from django.contrib.auth.backends import ModelBackend from .models import Email class LibrementBackend(ModelBackend): def authenticate(self, email=None, password=None): try: email = Email.objects.get(email__iexact=email) if email.user.check_password(password): retu...
from django.contrib.auth.backends import ModelBackend from .models import Email class LibrementBackend(ModelBackend): def authenticate(self, email=None, password=None): try: email = Email.objects.get(email__iexact=email) for candidate in ( password, ...
Allow a bunch of different combinations of password.
Allow a bunch of different combinations of password. Signed-off-by: Chris Lamb <29e6d179a8d73471df7861382db6dd7e64138033@debian.org>
Python
agpl-3.0
rhertzog/librement,rhertzog/librement,rhertzog/librement
261883f80174873af38a17ac7b0ebe7a79263d85
project/scripts/unit_tests.py
project/scripts/unit_tests.py
#!/usr/bin/env python3 import unittest import pandas as pd from fetch_trends import fetch_hourly_data class TestFetch(unittest.TestCase): def test_fetch_type(self): result = fetch_hourly_data("test", 2021, 1, 1, 2021, 1, 12) self.assertIsInstance(result, pd.DataFrame, "Should be a dataframe") ...
#!/usr/bin/env python3 import unittest import pandas as pd from fetch_trends import fetch_hourly_data, aggregate_hourly_to_daily from dates import get_end_times, get_start_times class TestFetch(unittest.TestCase): def setUp(self): self.hourly_result = fetch_hourly_data("test", 2021, 1, 1, 2021, 1, 1) ...
Add unit testing of dates and fetch functions
Add unit testing of dates and fetch functions
Python
apache-2.0
googleinterns/sgonks,googleinterns/sgonks,googleinterns/sgonks,googleinterns/sgonks
1d555c184a10ae4fd84d758105e19b10828543c2
q2_feature_classifier/tests/__init__.py
q2_feature_classifier/tests/__init__.py
# ---------------------------------------------------------------------------- # Copyright (c) 2016--, Ben Kaehler # # Distributed under the terms of the Modified BSD License. # # The full license is in the file LICENSE, distributed with this software. # -----------------------------------------------------------------...
# ---------------------------------------------------------------------------- # Copyright (c) 2016--, Ben Kaehler # # Distributed under the terms of the Modified BSD License. # # The full license is in the file LICENSE, distributed with this software. # -----------------------------------------------------------------...
Update import location of TestPluginBase
TST: Update import location of TestPluginBase
Python
bsd-3-clause
BenKaehler/q2-feature-classifier
c15dab903d3759578449279cc034d766d362d41f
rest_framework/authtoken/serializers.py
rest_framework/authtoken/serializers.py
from django.contrib.auth import authenticate from rest_framework import serializers class AuthTokenSerializer(serializers.Serializer): username = serializers.CharField() password = serializers.CharField() def validate(self, attrs): username = attrs.get('username') password = attrs.get('pa...
from django.contrib.auth import authenticate from django.utils.translation import ugettext_lazy as _ from rest_framework import serializers class AuthTokenSerializer(serializers.Serializer): username = serializers.CharField() password = serializers.CharField() def validate(self, attrs): username...
Mark strings in AuthTokenSerializer as translatable
Mark strings in AuthTokenSerializer as translatable
Python
bsd-2-clause
linovia/django-rest-framework,nhorelik/django-rest-framework,rafaelang/django-rest-framework,iheitlager/django-rest-framework,fishky/django-rest-framework,bluedazzle/django-rest-framework,damycra/django-rest-framework,HireAnEsquire/django-rest-framework,jerryhebert/django-rest-framework,gregmuellegger/django-rest-frame...
52c9768b30bf758a3ffeb2a94e10e28ab52541ab
test/__init__.py
test/__init__.py
import unittest from controller import c3bottles, db from view.user import User NAME = 'user' PASSWORD = 'test' def load_config(): c3bottles.config['SQLALCHEMY_DATABASE_URI'] = "sqlite://" c3bottles.config['TESTING'] = True class C3BottlesTestCase(unittest.TestCase): def setUp(self): load_con...
import unittest from controller import c3bottles, db from view.user import User NAME = 'user' PASSWORD = 'test' def load_config(): c3bottles.config['SQLALCHEMY_DATABASE_URI'] = "sqlite://" c3bottles.config['TESTING'] = True c3bottles.config['WTF_CSRF_ENABLED'] = False c3bottles.config['SECRET_KEY']...
Add ability to test requests
test: Add ability to test requests Disable CSRF and set the SECRET_KEY in tests so that it's possible to write HTTP based tests.
Python
mit
der-michik/c3bottles,der-michik/c3bottles,der-michik/c3bottles,der-michik/c3bottles
733f116125e7c061cf9f0e11e5b1008ee5272131
test/conftest.py
test/conftest.py
# -*- coding: utf-8 -*- import pytest import os import json import sys if sys.version_info[0] == 2: from codecs import open # This pair of generator expressions are pretty lame, but building lists is a # bad idea as I plan to have a substantial number of tests here. story_directories = ( os.path.join('test/te...
# -*- coding: utf-8 -*- import pytest import os import json import sys from hypothesis.strategies import text if sys.version_info[0] == 2: from codecs import open # We need to grab one text example from hypothesis to prime its cache. text().example() # This pair of generator expressions are pretty lame, but bui...
Fix some test breakages with Hypothesis.
Fix some test breakages with Hypothesis.
Python
mit
python-hyper/hpack,python-hyper/hpack
095d77b74a3bfad6d97387a860ac67f82f31c478
test/conftest.py
test/conftest.py
import pytest def pytest_addoption(parser): parser.addoption("--travis", action="store_true", default=False, help="Only run tests marked for Travis") def pytest_configure(config): config.addinivalue_line("markers", "not_travis: Mark a test that should not be ...
import pytest def pytest_addoption(parser): parser.addoption("--travis", action="store_true", default=False, help="Only run tests marked for Travis") def pytest_configure(config): config.addinivalue_line("markers", "not_travis: Mark a test that should not be ...
Print "still alive" progress when testing on travis
test: Print "still alive" progress when testing on travis
Python
mit
tkarna/cofs
50bd3ae1cac853d34d29c697573ccf8a3fc4cd96
tweepy/utils.py
tweepy/utils.py
# Tweepy # Copyright 2010-2022 Joshua Roesslein # See LICENSE for details. import datetime def list_to_csv(item_list): if item_list: return ','.join(map(str, item_list)) def parse_datetime(datetime_string): return datetime.datetime.strptime( datetime_string, "%Y-%m-%dT%H:%M:%S.%fZ" ).re...
# Tweepy # Copyright 2010-2022 Joshua Roesslein # See LICENSE for details. import datetime def list_to_csv(item_list): if item_list: return ','.join(map(str, item_list)) def parse_datetime(datetime_string): return datetime.datetime.strptime( datetime_string, "%Y-%m-%dT%H:%M:%S.%f%z" ).r...
Use %z directive in parse_datetime
Use %z directive in parse_datetime
Python
mit
svven/tweepy,tweepy/tweepy
7b26b893d642d829c55126452fcbebca8cfff806
test_settings.py
test_settings.py
DATABASES = { 'default' : { 'ENGINE': 'django.db.backends.sqlite3' } } INSTALLED_APPS = ( 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.auth', 'django.contrib.sites', 'django_extensions', 'newsletter', ) ROOT_URLCONF = 'test_urls' SITE_ID = 1 TEMPL...
DATABASES = { 'default' : { 'ENGINE': 'django.db.backends.sqlite3' } } INSTALLED_APPS = ( 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.auth', 'django.contrib.sites', 'django_extensions', 'newsletter', ) ROOT_URLCONF = 'test_urls' SITE_ID = 1 TEMPL...
Enable timezone support in tests.
Enable timezone support in tests.
Python
agpl-3.0
ctxis/django-newsletter,ctxis/django-newsletter,dsanders11/django-newsletter,dsanders11/django-newsletter,dsanders11/django-newsletter,viaregio/django-newsletter,viaregio/django-newsletter,ctxis/django-newsletter
e586b8ba3bb896dabe97d65d1b564c749faa4d42
src/ocspdash/web/blueprints/ui.py
src/ocspdash/web/blueprints/ui.py
# -*- coding: utf-8 -*- """The OCSPdash homepage UI blueprint.""" from flask import Blueprint, render_template from ocspdash.web.proxies import manager __all__ = [ 'ui', ] ui = Blueprint('ui', __name__) @ui.route('/') def home(): """Show the user the home view.""" payload = manager.get_payload() ...
# -*- coding: utf-8 -*- """Blueprint for non-API endpoints in OCSPdash.""" from flask import Blueprint, render_template from ocspdash.web.proxies import manager __all__ = [ 'ui', ] ui = Blueprint('ui', __name__) @ui.route('/') def home(): """Show the user the home view.""" payload = manager.get_paylo...
Update docstring and remove unused code from UI blueprint.
Update docstring and remove unused code from UI blueprint.
Python
mit
scolby33/OCSPdash,scolby33/OCSPdash,scolby33/OCSPdash
fef4e4ce6b05506babc2c325b08aed77af8b9a3c
cryptex/exchange.py
cryptex/exchange.py
class Exchange(object): def get_markets(self): """ Returns a list of tuples of the form ('XXX', 'YYY') representing the available markets on the exchange, where XXX and YYY are the currency codes for the base currency and counter currency, respectively. """ raise No...
class Exchange(object): def get_markets(self): """ Returns a list of tuples of the form ('XXX', 'YYY') representing the available markets on the exchange, where XXX and YYY are the currency codes for the base currency and counter currency, respectively. """ raise No...
Modify buy and sell interface to take market tuples
Modify buy and sell interface to take market tuples
Python
mit
coink/cryptex
e7b7c93efe20ac50256c33ac7b37e4e51151123f
OIPA/api/region/urls.py
OIPA/api/region/urls.py
from django.conf.urls import patterns, url from api.region import views urlpatterns = patterns( '', url(r'^$', views.RegionList.as_view(), name='region-list'), url( r'^/(?P<pk>[0-9]+)$', views.RegionDetail.as_view(), name='region-detail' ), url( r'^/(?P<pk>[0-9]+)/c...
from django.conf.urls import patterns, url from api.region import views urlpatterns = patterns( '', url(r'^$', views.RegionList.as_view(), name='region-list'), url( r'^/(?P<pk>[A-Za-z0-9]+)$', views.RegionDetail.as_view(), name='region-detail' ), url( r'^/(?P<pk>[A-...
Fix region resolve on non Integer
Fix region resolve on non Integer
Python
agpl-3.0
openaid-IATI/OIPA,zimmerman-zimmerman/OIPA,zimmerman-zimmerman/OIPA,openaid-IATI/OIPA,openaid-IATI/OIPA,openaid-IATI/OIPA,openaid-IATI/OIPA,zimmerman-zimmerman/OIPA,zimmerman-zimmerman/OIPA,zimmerman-zimmerman/OIPA
ab845dfd7eb2142ee8bf2fb86f58544e65ac97b8
auth0/v2/authentication/enterprise.py
auth0/v2/authentication/enterprise.py
from .base import AuthenticationBase class Enterprise(AuthenticationBase): def __init__(self, domain): self.domain = domain def saml_metadata(self, client_id): return self.get(url='https://%s/samlp/metadata/%s' % (self.domain, cli...
from .base import AuthenticationBase class Enterprise(AuthenticationBase): """Enterprise endpoints. Args: domain (str): Your auth0 domain (e.g: username.auth0.com) """ def __init__(self, domain): self.domain = domain def saml_metadata(self, client_id): """Get SAML2.0 Me...
Add docstrings in Enterprise class
Add docstrings in Enterprise class
Python
mit
auth0/auth0-python,auth0/auth0-python
082e34ae8d336d2fe93ea428db0b9a72bbfd649e
templatetags/stringformat.py
templatetags/stringformat.py
from django import template register=template.Library() @register.filter def stringformat(value, fmt='{}'): ''' format the value ''' return fmt.format(value)
from django import template register=template.Library() @register.filter def stringformat(value, fmt='{}'): ''' format the value ''' if isinstance(value, dict): return fmt.format(**value) return fmt.format(value)
Add named format support if dict
Add named format support if dict
Python
apache-2.0
kensonman/webframe,kensonman/webframe,kensonman/webframe
e502c906e0515dc753c972656751c9fd1ef939f9
backend/project_name/settings/test.py
backend/project_name/settings/test.py
from .base import * # noqa SECRET_KEY = 'test' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': base_dir_join('db.sqlite3'), } } STATIC_ROOT = base_dir_join('staticfiles') STATIC_URL = '/static/' MEDIA_ROOT = base_dir_join('mediafiles') MEDIA_URL = '/media/' DEFA...
from .base import * # noqa SECRET_KEY = 'test' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': base_dir_join('db.sqlite3'), } } STATIC_ROOT = "staticfiles" STATIC_URL = "/static/" MEDIA_ROOT = "mediafiles" MEDIA_URL = "/media/" DEFAULT_FILE_STORAGE = 'django.cor...
Fix ci build by adjust static root and media root path
Fix ci build by adjust static root and media root path
Python
mit
vintasoftware/django-react-boilerplate,vintasoftware/django-react-boilerplate,vintasoftware/django-react-boilerplate,vintasoftware/django-react-boilerplate
6b42983178f2a6fc3c485dc23825b748859351e5
gimlet/backends/sql.py
gimlet/backends/sql.py
from sqlalchemy import MetaData, Table, Column, types, create_engine, select from .base import BaseBackend class SQLBackend(BaseBackend): def __init__(self, url, table_name='gimlet_channels'): engine = create_engine(url) meta = MetaData() meta.bind = engine self.table = Table(ta...
from sqlalchemy import MetaData, Table, Column, types, create_engine, select from .base import BaseBackend class SQLBackend(BaseBackend): def __init__(self, url, table_name='gimlet_channels'): meta = MetaData(bind=create_engine(url)) self.table = Table(table_name, meta, ...
Simplify creation of MetaData in SQLBackend
Simplify creation of MetaData in SQLBackend Squash a few lines into one.
Python
mit
storborg/gimlet
cf44260d057e289a089c1c3c440e5f64366facfa
scraping/urls/scrape_fish.py
scraping/urls/scrape_fish.py
import pandas as pd from subprocess import check_output import sys fish_df = pd.read_csv(sys.argv[1],names=['fish']) url_dict = {} for fish in fish_df.fish: output = check_output(['node','scrape_image_urls.js',fish,sys.argv[2]]) splits = str(output).replace('\\n','').split(' url: ') urls = [s.split(', ...
import pandas as pd from subprocess import check_output import sys fish_df = pd.read_csv(sys.argv[1],names=['fish']) dfs = [] for fish in fish_df.fish: output = check_output(['node','scrape_image_urls.js',fish + ' fish',sys.argv[2]]) splits = str(output).replace('\\n','').split(' url: ') urls = [s.split('...
Update scrape fish to handle different size url sets and to specify to google that we want fish
Update scrape fish to handle different size url sets and to specify to google that we want fish
Python
mit
matthew-sochor/fish.io.ai,matthew-sochor/fish.io.ai,matthew-sochor/fish.io.ai,matthew-sochor/fish.io.ai
a41f468f667869a433e5fbb2bd2dde797ae24586
examples/img_client.py
examples/img_client.py
#!/usr/bin/env python """ This example demonstrates a client fetching images from a server running img_server.py. The first packet contains the number of chunks to expect, and then that number of chunks is read. Lost packets are not handled in any way. """ from nuts import UDPAuthChannel channel = UDPAu...
#!/usr/bin/env python """ This example demonstrates a client fetching images from a server running img_server.py. The first packet contains the number of chunks to expect, and then that number of chunks is read. Lost packets are not handled in any way. """ from nuts import UDPAuthChannel channel = UDPAu...
Set 4s timeout for img client
Set 4s timeout for img client
Python
mit
thusoy/nuts-auth,thusoy/nuts-auth
3cc8f2f212199d956c0132cc0aa12bd33e94e8dc
tests/drivers/test-facets.py
tests/drivers/test-facets.py
import pyxb.binding.generate import pyxb.utils.domutils from xml.dom import Node import os.path schema_path = '%s/../schemas/test-facets.xsd' % (os.path.dirname(__file__),) code = pyxb.binding.generate.GeneratePython(schema_location=schema_path) rv = compile(code, 'test', 'exec') eval(rv) from pyxb.exceptions_ impor...
import pyxb.binding.generate import pyxb.utils.domutils from xml.dom import Node import os.path schema_path = '%s/../schemas/test-facets.xsd' % (os.path.dirname(__file__),) code = pyxb.binding.generate.GeneratePython(schema_location=schema_path) rv = compile(code, 'test', 'exec') eval(rv) from pyxb.exceptions_ impor...
Change to support new binding model
Change to support new binding model
Python
apache-2.0
jonfoster/pyxb2,jonfoster/pyxb-upstream-mirror,balanced/PyXB,jonfoster/pyxb1,jonfoster/pyxb-upstream-mirror,balanced/PyXB,CantemoInternal/pyxb,jonfoster/pyxb-upstream-mirror,pabigot/pyxb,jonfoster/pyxb2,balanced/PyXB,CantemoInternal/pyxb,pabigot/pyxb,jonfoster/pyxb1,CantemoInternal/pyxb,jonfoster/pyxb2
a2a4b9f400fa6d62d3671d69d9742d06c165f7da
amaranth/ml/__main__.py
amaranth/ml/__main__.py
# Lint as: python3 """This script is used to run the amaranth.ml module as an executable. For now, this script just delegates it's main to amaranth.ml.train """ from amaranth.ml import train def main(): train.main() if __name__ == '__main__': main()
# Lint as: python3 """This script is used to run the amaranth.ml module as an executable. For now, this script just delegates it's main to amaranth.ml.train """ from amaranth.ml import train from amaranth.ml import interactive def main(): # List of possible functions this module can perform # List elements shou...
Allow user to choose what to run in amaranth.ml
Allow user to choose what to run in amaranth.ml Choose between the executables for training the model or interacting with the model.
Python
apache-2.0
googleinterns/amaranth,googleinterns/amaranth
fa0d138ce465efdd630b83ba4a7ee10888a68b4a
alg_factorial.py
alg_factorial.py
"""Factorial series: 1!, 2!, 3!, ... - Factorial(1) = 1! = 1 - Factorial(2) = 2! = 2 - Factorial(n) = n! = n * (n - 1)! = n * Factorial(n - 1) """ from __future__ import absolute_import from __future__ import print_function from __future__ import division def factorial_recur(n): """Get the nth number of Fibonac...
"""Factorial series: 1!, 2!, 3!, ... - Factorial(1) = 1! = 1 - Factorial(2) = 2! = 2 - Factorial(n) = n! = n * (n - 1)! = n * Factorial(n - 1) """ from __future__ import absolute_import from __future__ import print_function from __future__ import division def factorial_recur(n): """Get the nth number of factori...
Complete factorial_recur(), factorial_memo() & factorial_dp() from Hokaido
Complete factorial_recur(), factorial_memo() & factorial_dp() from Hokaido
Python
bsd-2-clause
bowen0701/algorithms_data_structures
cd7a8b999280e0e834e196066068f78375cfb88a
water_level/water_level.py
water_level/water_level.py
''' Created on Aug 1, 2017 @author: alkaitz ''' if __name__ == '__main__': pass
''' Created on Aug 1, 2017 @author: alkaitz ''' ''' [3 2 3] -> 1 ''' if __name__ == '__main__': pass
Include quick sample for water level identification
Include quick sample for water level identification
Python
mit
alkaitz/general-programming
3d1dba15097ac8b746c138b75fe1763aa4b8ac12
footballseason/urls.py
footballseason/urls.py
from django.conf.urls import url from . import views urlpatterns = [ # eg: /footballseason/ url(r'^$', views.index, name='index'), # eg: /footballseason/3 url(r'^(?P<week_id>[0-9]+)/$', views.display, name='display'), # eg: /footballseason/3/submit url(r'^(?P<week_id>[0-9]+)/submit$', views....
from django.conf.urls import url from . import views urlpatterns = [ # eg: /footballseason/ url(r'^$', views.index, name='index'), # eg: /footballseason/3/ url(r'^(?P<week_id>[0-9]+)/$', views.display, name='display'), # eg: /footballseason/3/submit/ url(r'^(?P<week_id>[0-9]+)/submit/$', vie...
Fix URLs so APPEND_SLASH works
Fix URLs so APPEND_SLASH works
Python
mit
mkokotovich/footballpicks,mkokotovich/footballpicks,mkokotovich/footballpicks,mkokotovich/footballpicks