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
98cbd5207bd25fb0fafd25f18870c771479255e1
run-tests.py
run-tests.py
#!/usr/bin/env python3 import os import subprocess import sys args = [ sys.executable or 'python', # Python interpreter to call for testing. '-B', # Don't write .pyc files on import. '-m', 'unittest', # Run the unittest module as a script. 'discover', # Use test discovery. '-s', 'tests', # Sta...
#!/usr/bin/env python3 import os import subprocess import sys args = [ sys.executable or 'python', # Python interpreter to call for testing. '-B', # Don't write .pyc files on import. '-W', 'default', # Enable default handling for all warnings. '-m', 'unittest', # Run the unittest module as a script...
Enable default warnings while testing.
Enable default warnings while testing.
Python
mit
shawnbrown/gpn,shawnbrown/gpn
d6e4aa32b7b79adc734dfc2b058509cedf771944
munigeo/migrations/0004_building.py
munigeo/migrations/0004_building.py
# -*- coding: utf-8 -*- # Generated by Django 1.10.1 on 2016-11-10 08:46 from __future__ import unicode_literals import django.contrib.gis.db.models.fields from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('munigeo', '0003_...
# -*- coding: utf-8 -*- # Generated by Django 1.10.1 on 2016-11-10 08:46 from __future__ import unicode_literals import django.contrib.gis.db.models.fields from django.db import migrations, models import django.db.models.deletion from munigeo.utils import get_default_srid DEFAULT_SRID = get_default_srid() class Mig...
Fix building migration SRID logic
Fix building migration SRID logic Hardcoding the SRID in the migration could result in a mismatch between the model srid and the migration srid.
Python
agpl-3.0
City-of-Helsinki/munigeo
35397c33f1b52f158c11941e17211eb699836003
tests/integration/indexer-test.py
tests/integration/indexer-test.py
# -*- coding: utf-8 -*- from nose import tools as nose import unittest from shiva.app import app from shiva.indexer import Indexer class IndexerTestCase(unittest.TestCase): def test_main(self): with app.app_context(): lola = Indexer(app.config) nose.eq_(lola.run(), None)
# -*- coding: utf-8 -*- from nose import tools as nose import unittest from shiva.app import app, db from shiva.indexer import Indexer class IndexerTestCase(unittest.TestCase): def setUp(self): db.create_all() def test_main(self): with app.app_context(): app.config['MEDIA_DIRS']...
Fix to indexer integration tests
Fix to indexer integration tests
Python
mit
tooxie/shiva-server,maurodelazeri/shiva-server,tooxie/shiva-server,maurodelazeri/shiva-server
6421543ff423fc110cd660850f55f7097db5805d
contrib/performance/setbackend.py
contrib/performance/setbackend.py
## # Copyright (c) 2010 Apple Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable la...
## # Copyright (c) 2010 Apple Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable la...
Rewrite the config to disable the response cache, too.
Rewrite the config to disable the response cache, too. git-svn-id: 81e381228600e5752b80483efd2b45b26c451ea2@6929 e27351fd-9f3e-4f54-a53b-843176b1656c
Python
apache-2.0
trevor/calendarserver,trevor/calendarserver,trevor/calendarserver
eb46bc61a05279d338c9e1062988f7db67f060fb
makesty.py
makesty.py
import re # Input file created from http://astronautweb.co/snippet/font-awesome/ INPUT_FILE = 'htmlfontawesome.txt' with open(INPUT_FILE) as r: for line in r: # Expects to find 'fa-NAME' ending with " name = re.findall(r'fa-[^""]*', line)[0] # Expects to find '\fSYMBOL' ending with " symbol = re.fin...
import re # Input file created from http://astronautweb.co/snippet/font-awesome/ INPUT_FILE = 'htmlfontawesome.txt' OUTPUT_FILE = 'fontawesome.sty' with open(INPUT_FILE) as r, open(OUTPUT_FILE, 'w') as w: for line in r: # Expects to find 'fa-NAME' ending with " name = re.findall(r'fa-[^""]*', line)[0] #...
Write output to .sty file.
Write output to .sty file.
Python
mit
posquit0/latex-fontawesome
d1e2aacb7926a7e751cd27eb562b2c5d86f7e1e8
opal/tests/test_core_test_runner.py
opal/tests/test_core_test_runner.py
""" Unittests fror opal.core.test_runner """ import ffs from mock import MagicMock, patch from opal.core.test import OpalTestCase from opal.core import test_runner class RunPyTestsTestCase(OpalTestCase): @patch('subprocess.check_call') def test_run_tests(self, check_call): mock_args = MagicMock(name...
""" Unittests fror opal.core.test_runner """ import ffs from mock import MagicMock, patch from opal.core.test import OpalTestCase from opal.core import test_runner class RunPyTestsTestCase(OpalTestCase): @patch('subprocess.check_call') def test_run_tests(self, check_call): mock_args = MagicMock(name...
Add test for opal test py -t
Add test for opal test py -t
Python
agpl-3.0
khchine5/opal,khchine5/opal,khchine5/opal
9637218c8b544c397bcd5d433de47cafbfad973d
octodns/source/base.py
octodns/source/base.py
# # # from __future__ import absolute_import, division, print_function, \ unicode_literals class BaseSource(object): def __init__(self, id): self.id = id if not getattr(self, 'log', False): raise NotImplementedError('Abstract base class, log property ' ...
# # # from __future__ import absolute_import, division, print_function, \ unicode_literals class BaseSource(object): def __init__(self, id): self.id = id if not getattr(self, 'log', False): raise NotImplementedError('Abstract base class, log property ' ...
Add lenient to abstract BaseSource signature
Add lenient to abstract BaseSource signature
Python
mit
vanbroup/octodns,vanbroup/octodns,h-hwang/octodns,h-hwang/octodns
71d56354fb053c6cef3dc2c8960f78f588327114
project/views.py
project/views.py
#! coding: utf-8 from django.shortcuts import render_to_response, render from django.http import HttpResponseRedirect from django.contrib.auth import login from forms import LoginForm def index(request): return render_to_response('index.html', {}) def login_view(request): if request.method == 'POST': ...
#! coding: utf-8 from django.shortcuts import render_to_response, render from django.http import HttpResponseRedirect from django.contrib.auth import login from forms import LoginForm def index(request): return render_to_response('index.html', {}) def login_view(request): if request.method == 'POST': ...
Store password in session after successful login.
Store password in session after successful login.
Python
agpl-3.0
InScience/DAMIS-old,InScience/DAMIS-old
c65a475c38a611cbf55f2dacbe22ccd50597c9ed
tests/test_database/test_sql/test_median.py
tests/test_database/test_sql/test_median.py
import unittest from tkp.db import execute, rollback class testMedian(unittest.TestCase): def setUp(self): try: execute('drop table median_test') except: rollback() execute('create table median_test (i int, f float)') execute('insert into median_test values...
import unittest import tkp from tkp.db import execute, rollback, Database from tkp.testutil import db_subs from numpy import median class testMedian(unittest.TestCase): def setUp(self): self.database = tkp.db.Database() self.dataset = tkp.db.DataSet(database=self.database, ...
Use MonetDB friendly median query syntax in unit test.
Use MonetDB friendly median query syntax in unit test.
Python
bsd-2-clause
transientskp/tkp,mkuiack/tkp,bartscheers/tkp,mkuiack/tkp,transientskp/tkp,bartscheers/tkp
0f5f5677ac2a1aa10067cbb509de28752fa106c0
response.py
response.py
from __future__ import division import numpy as np import matplotlib.pyplot as plt def deconv(x, y, fs): X = np.fft.fft(x) Y = np.fft.fft(y) H = Y / X h = np.fft.ifft(H) print("h =", h) # complex vector? t = np.arange(len(x)) / fs plt.plot(t, h.real) plt.grid() plt.title("impulse ...
"""Response calculation.""" from __future__ import division import numpy as np def calculate(signal_excitation, signal_out): """Function returns impulse response.""" X = np.fft.fft(signal_excitation) Y = np.fft.fft(signal_out) H = Y / X h = np.fft.ifft(H) return h
Change function content and pep257
Change function content and pep257
Python
mit
franzpl/sweep,spatialaudio/sweep
0ede19a4f2c9c6f01db0040d9d108eb0a0b2558c
py/kafka-tmdb.py
py/kafka-tmdb.py
import json from get_tmdb import GetTMDB from kafka import KafkaConsumer try: from GLOBALS import KAFKA_BROKER, TMDB_API except ImportError: print('Get it somewhere else') class CollectTMDB(object): def __init__(self, ): self.tmdb = GetTMDB(TMDB_API) self.consumer = KafkaConsumer(group_i...
import json from get_tmdb import GetTMDB from kafka import KafkaConsumer, KafkaProducer try: from GLOBALS import KAFKA_BROKER, TMDB_API except ImportError: print('Get it somewhere else') class CollectTMDB(object): def __init__(self, ): self.tmdb = GetTMDB(TMDB_API) self.producer = KafkaP...
Change KAFKA_BROKER parameter, added a send producer
Change KAFKA_BROKER parameter, added a send producer
Python
mit
kinoreel/kino-gather
072d8fd3ccff957b427fca5e61b5a410a6762615
pulldb/publishers.py
pulldb/publishers.py
# Copyright 2013 Russell Heilling from google.appengine.ext import ndb class Publisher(ndb.Model): '''Publisher object in datastore. Holds publisher data. ''' identifier = ndb.IntegerProperty() name = ndb.StringProperty() image = ndb.StringProperty() def fetch_or_store(identifier, publisher): publishe...
# Copyright 2013 Russell Heilling from google.appengine.ext import ndb class Publisher(ndb.Model): '''Publisher object in datastore. Holds publisher data. ''' identifier = ndb.IntegerProperty() name = ndb.StringProperty() image = ndb.StringProperty() def fetch_or_store(identifier, publisher): publishe...
Handle null image attribute on publisher
Handle null image attribute on publisher
Python
mit
xchewtoyx/pulldb
4973656e6e569808fc9c7b50f52e67aae2c7b547
billjobs/tests/tests_export_account_email.py
billjobs/tests/tests_export_account_email.py
from django.test import TestCase from django.contrib.admin.sites import AdminSite from billjobs.admin import UserAdmin class EmailExportTestCase(TestCase): """ Tests for email account export """ def test_method_is_avaible(self): """ Test admin can select the action in dropdown list """ self.as...
from django.test import TestCase from django.http import HttpResponse from django.contrib.admin.sites import AdminSite from django.contrib.auth.models import User from billjobs.admin import UserAdmin class EmailExportTestCase(TestCase): """ Tests for email account export """ def test_method_is_avaible(self): ...
Test export email return an HttpResponse
Test export email return an HttpResponse
Python
mit
ioO/billjobs
a91a2d3468cb3bfc7fdc686327770365321ef102
qa_app/challenges.py
qa_app/challenges.py
# Copyright 2016 Mirantis, 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 ...
# Copyright 2016 Mirantis, 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 ...
Implement demo 'exercises' api method.
Implement demo 'exercises' api method.
Python
apache-2.0
molecul/qa_app_flask,molecul/qa_app_flask,molecul/qa_app_flask
5af61cae2ca438880357f88533cfa77ea161efac
corehq/ex-submodules/pillow_retry/admin.py
corehq/ex-submodules/pillow_retry/admin.py
from django.contrib import admin from .models import PillowError class PillowErrorAdmin(admin.ModelAdmin): model = PillowError list_display = [ 'pillow', 'doc_id', 'error_type', 'date_created', 'date_last_attempt', 'date_next_attempt' ] list_filter = ('...
from django.contrib import admin from pillow_retry.models import PillowError @admin.register(PillowError) class PillowErrorAdmin(admin.ModelAdmin): model = PillowError list_display = [ 'pillow', 'doc_id', 'error_type', 'date_created', 'date_last_attempt', 'dat...
Add delete action to PillowRetry
Add delete action to PillowRetry
Python
bsd-3-clause
dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq
d7391bb7ef8d1cb2e900724f89f1753a7feb6fa7
rsr/cmd.py
rsr/cmd.py
import os import signal import sys from argparse import ArgumentParser import gi gi.require_version('Gtk', '3.0') gi.require_version('GtkSource', '3.0') from gi.repository import Gio, GLib from rsr import __version__ from rsr.app import Application parser = ArgumentParser(prog='runsqlrun', description='Run SQL stat...
import os import signal import sys from argparse import ArgumentParser import gi gi.require_version('Gtk', '3.0') gi.require_version('GtkSource', '3.0') from gi.repository import Gio, GLib, Gtk from rsr import __version__ from rsr.app import Application parser = ArgumentParser(prog='runsqlrun', description='Run SQL...
Use dark theme if possible.
Use dark theme if possible.
Python
mit
andialbrecht/runsqlrun
3b07818db48a5e3a205389051ccd9640e1079cc7
tests/lib/__init__.py
tests/lib/__init__.py
from os.path import abspath, dirname, join import sh import psycopg2 import requests PROJECT_FOLDER=dirname(dirname(abspath(__file__))) DOCKER_FOLDER=join(PROJECT_FOLDER, 'docker') def docker_compose(version, *args): sh.docker_compose('-f', 'docker/{version}/docker-compose.yml'.format(version=version), *args) d...
from os.path import abspath, dirname, join import sh import psycopg2 import requests import time PROJECT_FOLDER=dirname(dirname(abspath(__file__))) DOCKER_FOLDER=join(PROJECT_FOLDER, 'docker') def docker_compose(version, *args): sh.docker_compose('-f', 'docker/{version}/docker-compose.yml'.format(version=version...
Make the lib pretty complete
Make the lib pretty complete Should be able to replicate set up and tear down now
Python
mit
matthewfranglen/postgres-elasticsearch-fdw
25054586406024e082f9836884d5198ffa669f5b
models/ras_220_genes/build_ras_gene_network.py
models/ras_220_genes/build_ras_gene_network.py
from indra.tools.gene_network import GeneNetwork, grounding_filter import csv # STEP 0: Get gene list gene_list = [] # Get gene list from ras_pathway_proteins.csv with open('../../data/ras_pathway_proteins.csv') as f: csvreader = csv.reader(f, delimiter='\t') for row in csvreader: gene_list.append(row[...
from indra.tools.gene_network import GeneNetwork, grounding_filter import csv import pickle # STEP 0: Get gene list gene_list = [] # Get gene list from ras_pathway_proteins.csv with open('../../data/ras_pathway_proteins.csv') as f: csvreader = csv.reader(f, delimiter='\t') for row in csvreader: gene_li...
Save the results of ras network
Save the results of ras network
Python
bsd-2-clause
bgyori/indra,sorgerlab/belpy,johnbachman/indra,johnbachman/belpy,johnbachman/belpy,sorgerlab/indra,johnbachman/belpy,pvtodorov/indra,jmuhlich/indra,bgyori/indra,sorgerlab/indra,pvtodorov/indra,johnbachman/indra,sorgerlab/belpy,sorgerlab/belpy,jmuhlich/indra,bgyori/indra,sorgerlab/indra,pvtodorov/indra,jmuhlich/indra,pv...
c98ab8807440e3cdbb98e11c53c7f246c35614fe
dedupe/convenience.py
dedupe/convenience.py
#!/usr/bin/python # -*- coding: utf-8 -*- """ Convenience functions for in memory deduplication """ import collections import dedupe.core def dataSample(data, sample_size): '''Randomly sample pairs of records from a data dictionary''' random_pairs = dedupe.core.randomPairs(len(data), sample_size) ...
#!/usr/bin/python # -*- coding: utf-8 -*- """ Convenience functions for in memory deduplication """ import collections import dedupe.core def dataSample(data, sample_size): '''Randomly sample pairs of records from a data dictionary''' data_list = data.values() random_pairs = dedupe.core.randomPair...
Change dataSample to generate indices of random pair using list of values
Change dataSample to generate indices of random pair using list of values
Python
mit
nmiranda/dedupe,01-/dedupe,neozhangthe1/dedupe,neozhangthe1/dedupe,nmiranda/dedupe,davidkunio/dedupe,dedupeio/dedupe,dedupeio/dedupe-examples,datamade/dedupe,tfmorris/dedupe,tfmorris/dedupe,davidkunio/dedupe,01-/dedupe,datamade/dedupe,pombredanne/dedupe,dedupeio/dedupe,pombredanne/dedupe
7733a84dc95d43070f476be42a3559b1a2a16ec0
dataset/print.py
dataset/print.py
import json with open('dataset_item.json') as dataset_file: dataset = json.load(dataset_file) for i in range(len(dataset)): if 'Continual' == dataset[i]['frequency']: print dataset[i]['name']
import json dataset = [] dataset_files = ['dataset_item.json'] for f in dataset_files: with open(f) as file: for line in file: dataset.append(json.loads(file)) for i in range(len(dataset)): if 'Continual' == dataset[i]['frequency']: print dataset[i]['name']
Update to line by line dataset JSON file parsing
Update to line by line dataset JSON file parsing New format under Feed Exports
Python
mit
MaxLikelihood/CODE
3de4665adae5f289fa896aa211ec32f72d956342
testproject/testproject/urls.py
testproject/testproject/urls.py
from django.conf import settings from django.conf.urls import patterns, include, url from django.conf.urls.static import static from django.contrib import admin from testproject import views urlpatterns = patterns('', # Examples: # url(r'^$', 'testproject.views.home', name='home'), # url(r'^blog/', includ...
from django.conf import settings from django.conf.urls import include, url from django.conf.urls.static import static from django.contrib import admin from testproject import views urlpatterns = [ # Examples: # url(r'^$', 'testproject.views.home', name='home'), # url(r'^blog/', include('blog.urls')), ...
Remove use of deprecated patterns function
Remove use of deprecated patterns function
Python
mit
vittoriozamboni/django-groups-manager,vittoriozamboni/django-groups-manager
a75d14ec1792404eadf4b23570c7d198839c97d2
day-02/solution.py
day-02/solution.py
from __future__ import print_function import fileinput from operator import mul from functools import reduce totalArea = 0 totalRibbon = 0 for line in fileinput.input(): parts = [int(i) for i in line.split('x')] parts.sort() sides = [parts[0] * parts[1], parts[0] * parts[2], parts[1] * parts[2]] total...
from __future__ import print_function import fileinput from operator import mul from functools import reduce import itertools totalArea = 0 totalRibbon = 0 for line in fileinput.input(): parts = [int(i) for i in line.split('x')] parts.sort() sides = [x * y for x, y in itertools.combinations(parts, 2)] ...
Use itertools for better readability.
Use itertools for better readability.
Python
mit
bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adventofcode,bertptrs/adv...
c07bacb73eec4b963ec53c067f23385dad246fb6
setup.py
setup.py
from distutils.core import setup setup(name='zencoder', version='0.5.2', description='Integration library for Zencoder', author='Alex Schworer', author_email='alex.schworer@gmail.com', url='http://github.com/schworer/zencoder-py', license="MIT License", install_requires=['htt...
from distutils.core import setup setup(name='zencoder', version='0.5.2', description='Integration library for Zencoder', author='Alex Schworer', author_email='alex.schworer@gmail.com', url='http://github.com/schworer/zencoder-py', license="MIT License", install_requires=['htt...
Add classifiers to zencoder-py package
Add classifiers to zencoder-py package
Python
mit
zencoder/zencoder-py
dfca8ac68d69e533b954462094890faf0e723891
autopoke.py
autopoke.py
#!/bin/env python from selenium import webdriver from selenium.common.exceptions import StaleElementReferenceException from time import sleep from getpass import getpass if __name__ == '__main__': driver = webdriver.phantomjs.webdriver.WebDriver() driver.get('https://facebook.com') driver.find_element_by_...
#!/bin/env python from selenium import webdriver from selenium.common.exceptions import StaleElementReferenceException from time import sleep from getpass import getpass if __name__ == '__main__': driver = webdriver.phantomjs.webdriver.WebDriver() driver.get('https://facebook.com') driver.find_element_by_...
Fix bug where page stops updating by forcing it to reload after a minute of no activity
Fix bug where page stops updating by forcing it to reload after a minute of no activity
Python
mit
matthewbentley/autopoke
27c6df9b0e936ce4fb173ec64230931ffe0719c7
querylist/querylist.py
querylist/querylist.py
from betterdict import BetterDict class QueryList(list): def __init__(self, data=None, wrapper=BetterDict): """Create a QueryList from an iterable and a wrapper object.""" self._wrapper = wrapper self.src_data = data # Wrap our src_data with wrapper converted_data = self._...
from betterdict import BetterDict class QueryList(list): def __init__(self, data=None, wrapper=BetterDict): """Create a QueryList from an iterable and a wrapper object.""" self._wrapper = wrapper self.src_data = data # Wrap our src_data with wrapper converted_data = self._...
Add missing docs tring to QueryList._convert_iterable()
Add missing docs tring to QueryList._convert_iterable()
Python
mit
zoidbergwill/querylist,thomasw/querylist
31d0cd541980ef6bf15d3a29b68cc0cc994c28a4
packs/st2cd/actions/kvstore.py
packs/st2cd/actions/kvstore.py
from st2actions.runners.pythonrunner import Action from st2client.client import Client from st2client.models.datastore import KeyValuePair class KVPAction(Action): def run(self, key, action, st2host='localhost', value=""): st2_endpoints = { 'action': "http://%s:9101" % st2host, 'r...
from st2actions.runners.pythonrunner import Action from st2client.client import Client from st2client.models.datastore import KeyValuePair class KVPAction(Action): def run(self, key, action, st2host='localhost', value=""): st2_endpoints = { 'action': "http://%s:9101" % st2host, 'r...
Fix create action for key value pair
Fix create action for key value pair
Python
apache-2.0
StackStorm/st2incubator,pinterb/st2incubator,pinterb/st2incubator,pinterb/st2incubator,StackStorm/st2incubator
a0ff3446a177d11268c49b37c03f0d495341fe81
banana/maya/extensions/OpenMaya/__init__.py
banana/maya/extensions/OpenMaya/__init__.py
""" banana.maya.extensions.OpenMaya ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ OpenMaya extensions. :copyright: Copyright 2014 by Christopher Crouzet. :license: MIT, see LICENSE for details. """ __all__ = [ 'iterators', 'MDagPath', 'MFileIO', 'MFnDagNode', 'MFnDependencyNode', ...
""" banana.maya.extensions.OpenMaya ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ OpenMaya extensions. :copyright: Copyright 2014 by Christopher Crouzet. :license: MIT, see LICENSE for details. """ __all__ = [ 'iterators', 'MDagPath', 'MFileIO', 'MFnDagNode', 'MFnDependencyNode', ...
Add the missing `MGlobal` module to the `__all__` attribute.
Add the missing `MGlobal` module to the `__all__` attribute.
Python
mit
christophercrouzet/bana,christophercrouzet/banana.maya
5868f46a05ef19862ea81b4e402851a3e40ceeff
events/serializers.py
events/serializers.py
from .models import Event, EventActivity from employees.serializers import LocationSerializer from rest_framework import serializers class EventSerializer(serializers.ModelSerializer): location = LocationSerializer() class Meta(object): model = Event depth = 1 fields = ("pk", "name", ...
from .models import Event, EventActivity from employees.serializers import LocationSerializer from rest_framework import serializers class EventSerializer(serializers.ModelSerializer): location = LocationSerializer() class Meta(object): model = Event depth = 1 fields = ("pk", "name", ...
Remove is_upcoming field from Event response and Add explicit fields to EventActivity serializer
Remove is_upcoming field from Event response and Add explicit fields to EventActivity serializer
Python
apache-2.0
belatrix/BackendAllStars
f9f41ec4f27ba5fd19ca82d4c04b13bed6627d23
app/PRESUBMIT.py
app/PRESUBMIT.py
#!/usr/bin/python # Copyright (c) 2009 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Makes sure that the app/ code is cpplint clean.""" INCLUDE_CPP_FILES_ONLY = ( r'.*\.cc$', r'.*\.h$' ) EXCLUDE = ( # Autogener...
#!/usr/bin/python # Copyright (c) 2009 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Makes sure that the app/ code is cpplint clean.""" INCLUDE_CPP_FILES_ONLY = ( r'.*\.cc$', r'.*\.h$' ) EXCLUDE = ( # Autogener...
Make all changes to app/ run on all trybot platforms, not just the big three. Anyone who's changing a header here may break the chromeos build.
Make all changes to app/ run on all trybot platforms, not just the big three. Anyone who's changing a header here may break the chromeos build. BUG=none TEST=none Review URL: http://codereview.chromium.org/2838027 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@51000 0039d316-1c4b-4281-b951-d872f2087c98
Python
bsd-3-clause
rogerwang/chromium,Fireblend/chromium-crosswalk,dednal/chromium.src,TheTypoMaster/chromium-crosswalk,Fireblend/chromium-crosswalk,nacl-webkit/chrome_deps,ChromiumWebApps/chromium,dushu1203/chromium.src,ChromiumWebApps/chromium,junmin-zhu/chromium-rivertrail,junmin-zhu/chromium-rivertrail,Fireblend/chromium-crosswalk,zc...
a55f816072503241bd1ff4e953de12a7b48af4ac
backend/unimeet/helpers.py
backend/unimeet/helpers.py
from .models import School, User import re import string import random def get_school_list(): schools = School.objects.all() school_list = [] for s in schools: school = {} school['id'] = s.id school['name'] = s.name school['site'] = s.site school['university'] = s.u...
from .models import School, User import re import string import random from mail import send_mail def get_school_list(): schools = School.objects.all() school_list = [] for s in schools: school = {} school['id'] = s.id school['name'] = s.name school['site'] = s.site ...
Use send_mail in signup helper function
Use send_mail in signup helper function
Python
mit
dimkarakostas/unimeet,dimkarakostas/unimeet,dimkarakostas/unimeet,dimkarakostas/unimeet
4b1b5d0b71100fea17f127683a58533ef0e06fe9
bintools/splitter.py
bintools/splitter.py
import os # Splits a file using the dsplit mechanism def dsplit(fromfile, todir, chunksize = 1024): if not os.path.exists(todir): # caller handles errors os.mkdir(todir) # make dir, read/write parts original_file = os.path.basename(fromfile) filesize = o...
import os # Splits a file using the dsplit mechanism def dsplit(fromfile, todir = os.getcwd(), offset = 0, limit = None, chunksize = 1024): if not os.path.exists(todir): # caller handles errors os.mkdir(todir) # make dir, read/write parts original_file = os....
Refactor functions & add params
Refactor functions & add params
Python
apache-2.0
FernandoDoming/offset_finder
fab9ff4d5d0f04f4ebfe86ed407b16ea73110a04
apps/package/templatetags/package_tags.py
apps/package/templatetags/package_tags.py
from datetime import timedelta from datetime import datetime from django import template from github2.client import Github from package.models import Package, Commit register = template.Library() github = Github() @register.filter def commits_over_52(package): current = datetime.now() weeks = [] comm...
from datetime import datetime, timedelta from django import template from package.models import Commit register = template.Library() @register.filter def commits_over_52(package): current = datetime.now() weeks = [] commits = Commit.objects.filter(package=package).values_list('commit_date', flat=True) ...
Clean up some imports in the package app's template_tags.py file.
Clean up some imports in the package app's template_tags.py file.
Python
mit
QLGu/djangopackages,pydanny/djangopackages,cartwheelweb/packaginator,nanuxbe/djangopackages,cartwheelweb/packaginator,audreyr/opencomparison,QLGu/djangopackages,nanuxbe/djangopackages,pydanny/djangopackages,miketheman/opencomparison,pydanny/djangopackages,QLGu/djangopackages,nanuxbe/djangopackages,miketheman/opencompar...
d3a24fae87005b7f5c47657851b4341726494383
atest/resources/atest_variables.py
atest/resources/atest_variables.py
from os.path import abspath, dirname, join, normpath import locale import os import subprocess import robot __all__ = ['ROBOTPATH', 'ROBOT_VERSION', 'DATADIR', 'SYSTEM_ENCODING', 'CONSOLE_ENCODING'] ROBOTPATH = dirname(abspath(robot.__file__)) ROBOT_VERSION = robot.version.get_version() DATADIR = normpa...
from os.path import abspath, dirname, join, normpath import locale import os import subprocess import robot __all__ = ['ROBOTPATH', 'ROBOT_VERSION', 'DATADIR', 'SYSTEM_ENCODING', 'CONSOLE_ENCODING'] ROBOTPATH = dirname(abspath(robot.__file__)) ROBOT_VERSION = robot.version.get_version() DATADIR = normpa...
Fix getting Windows system encoding on non-ASCII envs
atests: Fix getting Windows system encoding on non-ASCII envs
Python
apache-2.0
HelioGuilherme66/robotframework,robotframework/robotframework,HelioGuilherme66/robotframework,robotframework/robotframework,HelioGuilherme66/robotframework,robotframework/robotframework
f21796d28ebf9328b68c6321d691b221457bafa6
jenkins/scripts/pypi-extract-universal.py
jenkins/scripts/pypi-extract-universal.py
#!/usr/bin/python # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software #...
#!/usr/bin/python # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software #...
Fix universal extraction in non-universal wheel
Fix universal extraction in non-universal wheel The pypi-extract-universal.py would raise ConfigParser.NoOptionError when inspecting a setup.cfg with a wheel section but no universal option. Guard against this by actually testing whether the option is there rather than merely whether the section exists. Change-Id: I7...
Python
apache-2.0
Tesora/tesora-project-config,coolsvap/project-config,noorul/os-project-config,Tesora/tesora-project-config,dongwenjuan/project-config,dongwenjuan/project-config,openstack-infra/project-config,openstack-infra/project-config,anbangr/osci-project-config,coolsvap/project-config,anbangr/osci-project-config,noorul/os-project...
757df7c04d862feb9067ae52c83875fc2e3aedf8
cla_backend/apps/cla_provider/admin/base.py
cla_backend/apps/cla_provider/admin/base.py
from django.contrib import admin from core.admin.modeladmin import OneToOneUserAdmin from ..models import Provider, ProviderAllocation, Staff, OutOfHoursRota from .forms import StaffAdminForm class StaffAdmin(OneToOneUserAdmin): model = Staff form = StaffAdminForm actions = None list_display = ( ...
from django.contrib import admin from core.admin.modeladmin import OneToOneUserAdmin from ..models import Provider, ProviderAllocation, Staff, OutOfHoursRota from .forms import StaffAdminForm class StaffAdmin(OneToOneUserAdmin): model = Staff form = StaffAdminForm actions = None list_display = ( ...
Disable ProviderAllocation admin page, still accessible from Provider Inlines
Disable ProviderAllocation admin page, still accessible from Provider Inlines
Python
mit
ministryofjustice/cla_backend,ministryofjustice/cla_backend,ministryofjustice/cla_backend,ministryofjustice/cla_backend
b8bf868d6ae7dbeb695dac36d5f72231d429d180
clone-vm.py
clone-vm.py
#!/usr/bin/env python import os import sys # Set arguments values if len(sys.argv) == 1: print "Usage: clone-vm.py [new-vm-name]" exit(1) else: new_vm_name = sys.argv[1] vms_home_dir = os.getenv('HOME') + '/Documents/Virtual\ Machines.localized/' vms_home_dir_not_escaped = os.getenv('HOME') + '/Documents/Vi...
#!/usr/bin/env python import os, sys # Set arguments values if len(sys.argv) == 1: print "Usage: clone-vm.py [new-vm-name]" exit(1) else: new_vm_name = sys.argv[1] vms_path_dir = os.getenv('HOME') + '/Documents/Virtual Machines.localized/' vm_source_vmx = vms_home_dir + 'base-centos-64.vmwarevm/base-centos...
Delete escped variable, replaced with single quotes
Delete escped variable, replaced with single quotes
Python
apache-2.0
slariviere/py-vmrum,slariviere/py-vmrum
f2a0c0c7329087421f6d3c237d2bb5f9633d180c
linear_math_tests/test_alignedobjectarray.py
linear_math_tests/test_alignedobjectarray.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ linear_math_tests.test_alignedobjectarray """ from __future__ import unicode_literals, print_function, absolute_import import unittest import math import bullet class ClassTestName(unittest.TestCase): def setUp(self): pass def tearDown(self): ...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ linear_math_tests.test_alignedobjectarray """ from __future__ import unicode_literals, print_function, absolute_import import unittest import math import bullet class ClassTestName(unittest.TestCase): def setUp(self): self.a = bullet.btVector3Array() ...
Add some basic tests for assignment. Note that slicing is not supported
Add some basic tests for assignment. Note that slicing is not supported
Python
mit
Klumhru/boost-python-bullet,Klumhru/boost-python-bullet,Klumhru/boost-python-bullet
941da2b1453cda2b981c5891fcc5d58c04df4544
eve_api/tasks.py
eve_api/tasks.py
from celery.decorators import task from eve_api.api_puller.accounts import import_eve_account from eve_api.app_defines import * from sso.tasks import update_user_access @task() def import_apikey(api_userid, api_key, user=None, force_cache=False): acc = import_eve_account(api_key, api_userid, force_cache=force_cach...
import logging from celery.decorators import task from eve_api.api_puller.accounts import import_eve_account from eve_api.app_defines import * from sso.tasks import update_user_access @task() def import_apikey(api_userid, api_key, user=None, force_cache=False): l = logging.getLogger('import_apikey') l.info("Im...
Add some logging to the EVE API task
Add some logging to the EVE API task
Python
bsd-3-clause
nikdoof/test-auth
698a3fe81a15b40b95836426f9292365f9f57c9c
cartoframes/core/cartodataframe.py
cartoframes/core/cartodataframe.py
from geopandas import GeoDataFrame from ..utils.geom_utils import generate_index, generate_geometry class CartoDataFrame(GeoDataFrame): def __init__(self, *args, **kwargs): index_column = kwargs.pop('index_column', None) geom_column = kwargs.pop('geom_column', None) lnglat_column = kwarg...
from geopandas import GeoDataFrame from ..utils.geom_utils import generate_index, generate_geometry class CartoDataFrame(GeoDataFrame): def __init__(self, *args, **kwargs): index_column = kwargs.pop('index_column', None) geom_column = kwargs.pop('geom_column', None) lnglat_column = kwarg...
Add a wrapper for from_file/from_features methods
Add a wrapper for from_file/from_features methods
Python
bsd-3-clause
CartoDB/cartoframes,CartoDB/cartoframes
8f11aa020d5e539653120d5e895ea6f7b09392ce
cea/interfaces/dashboard/api/dashboard.py
cea/interfaces/dashboard/api/dashboard.py
from flask_restplus import Namespace, Resource, fields, abort import cea.config import cea.plots.cache api = Namespace('Dashboard', description='Dashboard plots') LAYOUTS = ['row', 'grid', 'map'] CATEGORIES = {c.name: {'label': c.label, 'plots': [{'id': p.id(), 'name': p.name} for p in c.plots]} for c...
from flask_restplus import Namespace, Resource, fields, abort import cea.config import cea.plots.cache api = Namespace('Dashboard', description='Dashboard plots') LAYOUTS = ['row', 'grid', 'map'] CATEGORIES = {c.name: {'label': c.label, 'plots': [{'id': p.id(), 'name': p.name} for p in c.plots]} for c...
Allow 'scenario-name' to be null if it does not exist
Allow 'scenario-name' to be null if it does not exist
Python
mit
architecture-building-systems/CEAforArcGIS,architecture-building-systems/CEAforArcGIS
c79714249a0278b49a19a6a219328c4a74453c2d
cme/modules/MachineAccountQuota.py
cme/modules/MachineAccountQuota.py
from impacket.ldap import ldapasn1 as ldapasn1_impacket class CMEModule: ''' Module by Shutdown and Podalirius Initial module: https://github.com/ShutdownRepo/CrackMapExec-MachineAccountQuota Authors: Shutdown: @_nwodtuhs Podalirius: @podalirius_ ''' def option...
from impacket.ldap import ldapasn1 as ldapasn1_impacket class CMEModule: ''' Module by Shutdown and Podalirius Initial module: https://github.com/ShutdownRepo/CrackMapExec-MachineAccountQuota Authors: Shutdown: @_nwodtuhs Podalirius: @podalirius_ ''' def option...
Remove error message when using MAQ module
Remove error message when using MAQ module
Python
bsd-2-clause
byt3bl33d3r/CrackMapExec
7ed9b5dc23867381c34a77f31ccf4da5effbb0b0
tracpro/orgs_ext/migrations/0002_auto_20150724_1609.py
tracpro/orgs_ext/migrations/0002_auto_20150724_1609.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals import json from django.conf import settings from django.db import models, migrations def add_available_languages(apps, schema_editor): """Set default available_languages to all languages defined for this project.""" all_languages = [l[0] for l...
# -*- coding: utf-8 -*- from __future__ import unicode_literals import json from django.conf import settings from django.db import models, migrations def add_available_languages(apps, schema_editor): """Set default available_languages to all languages defined for this project.""" all_languages = [l[0] for l...
Handle if org.config is None
Handle if org.config is None
Python
bsd-3-clause
xkmato/tracpro,rapidpro/tracpro,xkmato/tracpro,rapidpro/tracpro,xkmato/tracpro,xkmato/tracpro,rapidpro/tracpro
505a88eaa461eb99d67b36692869b6d4025a054f
gapipy/models/address.py
gapipy/models/address.py
from .base import BaseModel class Address(BaseModel): _as_is_fields = ['city', 'latitude', 'longitude', 'postal_zip', 'street'] _resource_fields = [('country', 'Country')] def __repr__(self): return '<{0}: {1}, {2}>'.format( self.__class__.__name__, self.city, self.country.name)
from .base import BaseModel class Address(BaseModel): _as_is_fields = ['city', 'latitude', 'longitude', 'postal_zip', 'street'] _resource_fields = [ ('state', 'State'), ('country', 'Country') ] def __repr__(self): return '<{0}: {1}, {2}>'.format( self.__class__.__n...
Add State to Address model definition.
Add State to Address model definition.
Python
mit
gadventures/gapipy
481f4444e063d5559d396a5a26154b9ebde27248
formspree/app.py
formspree/app.py
import json import stripe import flask from flask import g from flask.ext.sqlalchemy import SQLAlchemy from flask.ext.login import LoginManager, current_user from flask_redis import Redis import settings DB = SQLAlchemy() redis_store = Redis() stripe.api_key = settings.STRIPE_SECRET_KEY import routes from users.mode...
import json import stripe import os import flask from flask import g from flask.ext.sqlalchemy import SQLAlchemy from flask.ext.login import LoginManager, current_user from flask.ext.cdn import CDN from formspree import log from flask_redis import Redis import settings DB = SQLAlchemy() redis_store = Redis() stripe.a...
Allow for static contents served over CDN
Allow for static contents served over CDN
Python
agpl-3.0
asm-products/formspree,asm-products/formspree,asm-products/formspree,asm-products/formspree
fbadf23356b40c36378cef8f3a9c8b382bce9e32
comics/core/admin.py
comics/core/admin.py
from django.contrib import admin from comics.core import models class ComicAdmin(admin.ModelAdmin): list_display = ('slug', 'name', 'language', 'url', 'rights') prepopulated_fields = { 'slug': ('name',) } class ReleaseAdmin(admin.ModelAdmin): list_display = ('__unicode__', 'comic', 'pub_dat...
from django.contrib import admin from comics.core import models class ComicAdmin(admin.ModelAdmin): list_display = ('slug', 'name', 'language', 'url', 'rights', 'start_date', 'end_date', 'active') prepopulated_fields = { 'slug': ('name',) } class ReleaseAdmin(admin.ModelAdmin): list...
Include start date, end date, and active flag in comics list
Include start date, end date, and active flag in comics list
Python
agpl-3.0
jodal/comics,jodal/comics,jodal/comics,datagutten/comics,datagutten/comics,datagutten/comics,jodal/comics,datagutten/comics
80a28d495bc57c6866800d037cfc389050166319
tracpro/profiles/tests/factories.py
tracpro/profiles/tests/factories.py
import factory import factory.django import factory.fuzzy from tracpro.test.factory_utils import FuzzyEmail __all__ = ['User'] class User(factory.django.DjangoModelFactory): username = factory.fuzzy.FuzzyText() email = FuzzyEmail() class Meta: model = "auth.User" @factory.post_generation ...
import factory import factory.django import factory.fuzzy from tracpro.test.factory_utils import FuzzyEmail __all__ = ['User'] class User(factory.django.DjangoModelFactory): username = factory.fuzzy.FuzzyText() email = FuzzyEmail() class Meta: model = "auth.User" @factory.post_generation ...
Use username as password default
Use username as password default For compatibility with TracProTest.login()
Python
bsd-3-clause
xkmato/tracpro,rapidpro/tracpro,rapidpro/tracpro,xkmato/tracpro,xkmato/tracpro,rapidpro/tracpro,xkmato/tracpro
d43f87c18807853fde0a0e79828b5a8e7ab036fc
assess_isoform_quantification/set_isoform_frequencies.py
assess_isoform_quantification/set_isoform_frequencies.py
#!/usr/bin/python """Usage: set_isoform_frequencies [{help}] [{version}] {pro_file} {help_short} {help} Show this message. {version_short} {version} Show version. {pro_file} Flux simulator gene expression profile file. """ from docopt import docopt from options import validate_file_...
#!/usr/bin/python """Usage: set_isoform_frequencies [{help}] [{version}] {pro_file} {help_short} {help} Show this message. {version_short} {version} Show version. {pro_file} Flux simulator gene expression profile file. """ from docopt import docopt from options import validate_file_...
Read in Flux Simulator expression profile with pandas.
Read in Flux Simulator expression profile with pandas.
Python
mit
lweasel/piquant,COMBINE-lab/piquant,lweasel/piquant
156c049cc3965f969ee252dc5859cf0713bcbe27
grip/__init__.py
grip/__init__.py
"""\ Grip ---- Render local readme files before sending off to Github. :copyright: (c) 2012 by Joe Esposito. :license: MIT, see LICENSE for more details. """ __version__ = '1.2.0' from . import command from .server import default_filenames, serve from .renderer import render_content, render_page
"""\ Grip ---- Render local readme files before sending off to Github. :copyright: (c) 2012 by Joe Esposito. :license: MIT, see LICENSE for more details. """ __version__ = '1.2.0' from . import command from .renderer import render_content, render_page from .server import default_filenames, create_app, serve from ....
Add create_app and export to API.
Add create_app and export to API.
Python
mit
jbarreras/grip,jbarreras/grip,joeyespo/grip,mgoddard-pivotal/grip,ssundarraj/grip,ssundarraj/grip,mgoddard-pivotal/grip,joeyespo/grip
0ddad675169952f861f164d7ce311c83dccd51e0
invoice/admin.py
invoice/admin.py
from django.contrib import admin from django.conf.urls.defaults import patterns from invoice.models import Invoice, InvoiceItem from invoice.views import pdf_view from invoice.forms import InvoiceAdminForm class InvoiceItemInline(admin.TabularInline): model = InvoiceItem class InvoiceAdmin(admin.ModelAdmin): ...
from django.contrib import admin from django.conf.urls.defaults import patterns from invoice.models import Invoice, InvoiceItem from invoice.views import pdf_view from invoice.forms import InvoiceAdminForm class InvoiceItemInline(admin.TabularInline): model = InvoiceItem class InvoiceAdmin(admin.ModelAdmin): ...
Add paid_date to invoice list.
Add paid_date to invoice list.
Python
bsd-3-clause
simonluijk/django-invoice,Chris7/django-invoice,Chris7/django-invoice
09c2e6fff38e5c47391c0f8e948089e3efd26337
serfnode/handler/file_utils.py
serfnode/handler/file_utils.py
import os from tempfile import mkstemp import time class atomic_write(object): """Perform an atomic write to a file. Use as:: with atomic_write('/my_file') as f: f.write('foo') """ def __init__(self, filepath): """ :type filepath: str """ self.fi...
import os from tempfile import mkstemp import time class atomic_write(object): """Perform an atomic write to a file. Use as:: with atomic_write('/my_file') as f: f.write('foo') """ def __init__(self, filepath): """ :type filepath: str """ self.fi...
Allow waiting for multiple files
Allow waiting for multiple files
Python
mit
waltermoreira/serfnode,waltermoreira/serfnode,waltermoreira/serfnode
eb61e5c989cda3f5e021150f91561a88ba6db73e
setuptools/tests/py26compat.py
setuptools/tests/py26compat.py
import sys import unittest import tarfile try: # provide skipIf for Python 2.4-2.6 skipIf = unittest.skipIf except AttributeError: def skipIf(condition, reason): def skipper(func): def skip(*args, **kwargs): return if condition: return skip return func return skipper def _tarfile_open_ex(*args...
import sys import unittest import tarfile import contextlib try: # provide skipIf for Python 2.4-2.6 skipIf = unittest.skipIf except AttributeError: def skipIf(condition, reason): def skipper(func): def skip(*args, **kwargs): return if condition: return skip return func return skipper def _tar...
Use contextlib.closing on tarfile compat shim
Use contextlib.closing on tarfile compat shim
Python
mit
pypa/setuptools,pypa/setuptools,pypa/setuptools
29b3ea81fad91b9cdba150a74aeeb43b40dc0d67
numba/cuda/tests/cudadrv/test_profiler.py
numba/cuda/tests/cudadrv/test_profiler.py
import unittest from numba.cuda.testing import ContextResettingTestCase from numba import cuda from numba.cuda.testing import skip_on_cudasim @skip_on_cudasim('CUDA Profiler unsupported in the simulator') class TestProfiler(ContextResettingTestCase): def test_profiling(self): with cuda.profiling(): ...
import unittest from numba.cuda.testing import ContextResettingTestCase from numba import cuda from numba.cuda.testing import skip_on_cudasim, xfail_with_cuda_python @skip_on_cudasim('CUDA Profiler unsupported in the simulator') @xfail_with_cuda_python class TestProfiler(ContextResettingTestCase): def test_profil...
Revert "Re-enable profiler with CUDA Python"
Revert "Re-enable profiler with CUDA Python" This reverts commit 0a7a8d891b946ad7328ac83854b18935f3cf23d6. The Conda packages for the NVIDIA bindings do not support this API - only the Github source version supports it, the profiler tests must be disabled.
Python
bsd-2-clause
IntelLabs/numba,numba/numba,seibert/numba,IntelLabs/numba,cpcloud/numba,cpcloud/numba,IntelLabs/numba,numba/numba,cpcloud/numba,numba/numba,seibert/numba,seibert/numba,cpcloud/numba,numba/numba,IntelLabs/numba,seibert/numba,cpcloud/numba,IntelLabs/numba,seibert/numba,numba/numba
4c6c7067c05026b0e40020b0be58de83aa79e4f5
entrypoint.py
entrypoint.py
import bcrypt import sys if len(sys.argv) < 2: print('Error: please provide a password.', file=sys.stderr) sys.exit(2) password = sys.argv[1] strength = None if len(sys.argv) > 2: strength = int(sys.argv[2]) if strength: salt = bcrypt.gensalt(rounds=strength) else: salt = bcrypt.gensalt() password ...
import bcrypt import sys if len(sys.argv) < 2: print('Error: please provide a password.', file=sys.stderr) sys.exit(2) password = sys.argv[1] strength = None if len(sys.argv) > 2: strength = int(sys.argv[2]) if strength: salt = bcrypt.gensalt(rounds=strength) else: salt = bcrypt.gensalt() password ...
Remove newline character from stdout.
Remove newline character from stdout.
Python
apache-2.0
JohnStarich/docker-bcrypt
f10d2b0aa6da7347435ad1036c0e53e67c89d362
dougrain.py
dougrain.py
#!/usr/bin/python import urlparse import curie import link class Document(object): def expand_curie(self, link): return self.curie.expand(link) @classmethod def from_object(cls, o, relative_to_url=None, parent_curie=None): if isinstance(o, list): return map(lambda x: cls.from_...
#!/usr/bin/python import urlparse import curie import link class Document(object): def __init__(self, o, relative_to_url, parent_curie=None): self.attrs = o self.__dict__.update(o) self.links = {} for key, value in o.get("_links", {}).iteritems(): self.links[key] = link...
Move some construction to __init__.
Refactor: Move some construction to __init__.
Python
mit
wharris/dougrain
410c47921da205c1628cdff771f3385546edd503
src/engine/SCons/Platform/darwin.py
src/engine/SCons/Platform/darwin.py
"""engine.SCons.Platform.darwin Platform-specific initialization for Mac OS X systems. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Platform.Platform() selection method. """ # # Copyright (c) 2001, 2002, 2003, 2004 Steven Knight # # Permi...
"""engine.SCons.Platform.darwin Platform-specific initialization for Mac OS X systems. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Platform.Platform() selection method. """ # # __COPYRIGHT__ # # Permission is hereby granted, free of char...
Fix __COPYRIGHT__ and __REVISION__ in new Darwin module.
Fix __COPYRIGHT__ and __REVISION__ in new Darwin module.
Python
mit
Distrotech/scons,Distrotech/scons,Distrotech/scons,Distrotech/scons,Distrotech/scons
f664b85c3bc68612d19ae0fc762ca314f6517b00
src/constants.py
src/constants.py
#!/usr/bin/env python TRAJECTORY = 'linear' CONTROLLER = 'euler' # control constants K_X = 0.90 K_Y = 0.90 K_THETA = 0.90 # PID control constants K_P_V = 0.2 K_I_V = 1.905 K_D_V = 0.00 K_P_W = 0.45 K_I_W = 1.25 K_D_W = 0.000 if TRAJECTORY == 'linear': SIMULATION_TIME_IN_SECONDS = 60.0 MAX_V = 0.075 MAX...
#!/usr/bin/env python TRAJECTORY = 'linear' CONTROLLER = 'euler' # control constants K_X = 0.90 K_Y = 0.90 K_THETA = 0.90 # PID control constants K_P_V = 0.2 K_I_V = 1.905 K_D_V = 0.00 K_P_W = 0.45 K_I_W = 1.25 K_D_W = 0.000 SIMULATION_TIME_IN_SECONDS = 0.0 if TRAJECTORY == 'linear': SIMULATION_TIME_IN_SECONDS ...
Add default value for simulation time
Add default value for simulation time
Python
mit
bit0001/trajectory_tracking,bit0001/trajectory_tracking
184b64da2a4fa0d8827d839501e12317f9adfa46
simple-cipher/simple_cipher.py
simple-cipher/simple_cipher.py
import math import secrets from string import ascii_lowercase class Cipher(object): def __init__(self, key=None): if not key: key = Cipher._random_key() if not key.isalpha() or not key.islower(): raise ValueError("Key must consist only of lowercase letters") self.ke...
import math import secrets from string import ascii_lowercase class Cipher(object): def __init__(self, key=None): if not key: key = self._random_key() if not key.isalpha() or not key.islower(): raise ValueError("Key must consist only of lowercase letters") self.key ...
Use super() and self within the Cipher and Caesar classes
Use super() and self within the Cipher and Caesar classes
Python
agpl-3.0
CubicComet/exercism-python-solutions
b0011541a21927c4f9ee378b77b11fd4b0dfbcff
tests/test_cookiecutter_substitution.py
tests/test_cookiecutter_substitution.py
import re import sh from .base import DjangoCookieTestCase class TestCookiecutterSubstitution(DjangoCookieTestCase): """Test that all cookiecutter instances are substituted""" def test_all_cookiecutter_instances_are_substituted(self): # Build a list containing absolute paths to the generated files ...
import re import sh from .base import DjangoCookieTestCase class TestCookiecutterSubstitution(DjangoCookieTestCase): """Test that all cookiecutter instances are substituted""" def test_all_cookiecutter_instances_are_substituted(self): # Build a list containing absolute paths to the generated files ...
Fix tests for python 3
Fix tests for python 3
Python
bsd-3-clause
wldcordeiro/cookiecutter-django-essentials,wldcordeiro/cookiecutter-django-essentials,wldcordeiro/cookiecutter-django-essentials
29aa5847feba9d5efceec2014d3524867b4284e1
go/testsettings.py
go/testsettings.py
import os from settings import * # This needs to point at the test riak buckets. VUMI_API_CONFIG['riak_manager'] = {'bucket_prefix': 'test.'} VUMI_API_CONFIG['redis_manager'] = { 'key_prefix': 'test', 'FAKE_REDIS': 'sure', } if os.environ.get('VUMIGO_FAST_TESTS'): DATABASES = { 'default': { ...
import os from settings import * SECRET_KEY = "test_secret" # This needs to point at the test riak buckets. VUMI_API_CONFIG['riak_manager'] = {'bucket_prefix': 'test.'} VUMI_API_CONFIG['redis_manager'] = { 'key_prefix': 'test', 'FAKE_REDIS': 'sure', } if os.environ.get('VUMIGO_FAST_TESTS'): DATABASES = ...
Add SECRET_KEY which is required by Django 1.5.
Add SECRET_KEY which is required by Django 1.5.
Python
bsd-3-clause
praekelt/vumi-go,praekelt/vumi-go,praekelt/vumi-go,praekelt/vumi-go
a6b14d2f80355e556c466b52b518dc808c90c54a
polling_stations/settings/static_files.py
polling_stations/settings/static_files.py
from dc_theme.settings import get_pipeline_settings from dc_theme.settings import STATICFILES_FINDERS STATICFILES_STORAGE = 'pipeline.storage.PipelineStorage' PIPELINE = get_pipeline_settings( extra_css=[ 'custom_css/style.scss', 'font-awesome/css/font-awesome.min.css', ], extra_js=[], ) PI...
from dc_theme.settings import get_pipeline_settings from dc_theme.settings import STATICFILES_FINDERS, STATICFILES_STORAGE PIPELINE = get_pipeline_settings( extra_css=[ 'custom_css/style.scss', 'font-awesome/css/font-awesome.min.css', ], extra_js=[], ) PIPELINE['STYLESHEETS']['map'] = { ...
Remove old pipeline and compressor settings
Remove old pipeline and compressor settings libsass has a compresssion mode that's enabled by default in the 0.3 dc base theme. This removes the need for uglifyjs
Python
bsd-3-clause
DemocracyClub/UK-Polling-Stations,DemocracyClub/UK-Polling-Stations,DemocracyClub/UK-Polling-Stations
63e5bd0e7c771e4a2efe2ff203b75e4a56024af5
app.py
app.py
""" Main entry point of the logup-factory """ from flask import Flask from flask.ext.mongoengine import MongoEngine from flask import request from flask import render_template app = Flask(__name__) app.config.from_pyfile('flask-conf.cfg') db = MongoEngine(app) @app.route('/') def index(): return render_templat...
""" Main entry point of the logup-factory """ from flask import Flask from flask.ext.mongoengine import MongoEngine from flask import request from flask import render_template app = Flask(__name__, static_url_path='', static_folder='frontend/dist') app.config.from_pyfile('flask-conf.cfg') # db = MongoEngine(app) @...
Change static directory, commented mongo dev stuff
Change static directory, commented mongo dev stuff
Python
mit
cogniteev/logup-factory,cogniteev/logup-factory
58823e20e3891cea7198be15b7c85395521086e1
extension_course/tests/conftest.py
extension_course/tests/conftest.py
import pytest from django.conf import settings from django.core.management import call_command from events.tests.conftest import (administrative_division, administrative_division_type, data_source, event, # noqa location_id, minimal_event_dict, municipality, organization, place, use...
import pytest from events.tests.conftest import (administrative_division, administrative_division_type, data_source, event, # noqa location_id, minimal_event_dict, municipality, organization, place, user, user_api_client, django_db_modify_db_setting...
Remove some needless code from course extension tests
Remove some needless code from course extension tests
Python
mit
City-of-Helsinki/linkedevents,City-of-Helsinki/linkedevents,City-of-Helsinki/linkedevents
65ed7106126effc922df2bf7252a3c840d9bc768
hasjob/__init__.py
hasjob/__init__.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from os import environ from flask import Flask from flask.ext.mail import Mail from flask.ext.assets import Environment, Bundle from coaster import configureapp # First, make an app and config it app = Flask(__name__, instance_relative_config=True) configureapp(app, 'HAS...
#!/usr/bin/env python # -*- coding: utf-8 -*- from os import environ from flask import Flask from flask.ext.mail import Mail from flask.ext.assets import Environment, Bundle from coaster import configureapp # First, make an app and config it app = Flask(__name__, instance_relative_config=True) configureapp(app, 'HAS...
Remove duplicate code, leave comment about circular imports
Remove duplicate code, leave comment about circular imports
Python
agpl-3.0
hasgeek/hasjob,ashwin01/hasjob,nhannv/hasjob,qitianchan/hasjob,ashwin01/hasjob,hasgeek/hasjob,qitianchan/hasjob,sindhus/hasjob,sindhus/hasjob,hasgeek/hasjob,sindhus/hasjob,ashwin01/hasjob,ashwin01/hasjob,sindhus/hasjob,qitianchan/hasjob,nhannv/hasjob,qitianchan/hasjob,sindhus/hasjob,qitianchan/hasjob,nhannv/hasjob,hasg...
d6a8b995f2a1b069729f07ef43b966b2f15fd3b3
linter.py
linter.py
from SublimeLinter.lint import NodeLinter class XO(NodeLinter): npm_name = 'xo' cmd = ('xo', '--stdin', '--reporter', 'compact', '--filename', '@') regex = ( r'^.+?: line (?P<line>\d+), col (?P<col>\d+), ' r'(?:(?P<error>Error)|(?P<warning>Warning)) - ' r'(?P<message>.+)' ) defaults = { 'selector': 'sourc...
from SublimeLinter.lint import NodeLinter class XO(NodeLinter): npm_name = 'xo' cmd = ('xo', '--stdin', '--reporter', 'compact', '--filename', '${file}') regex = ( r'^.+?: line (?P<line>\d+), col (?P<col>\d+), ' r'(?:(?P<error>Error)|(?P<warning>Warning)) - ' r'(?P<message>.+)' r' \((?P<code>.+)\)$' ) def...
Support the new SublimeLinter `code` property
Support the new SublimeLinter `code` property
Python
mit
sindresorhus/SublimeLinter-contrib-xo,sindresorhus/SublimeLinter-contrib-xo
c5b2cb667a59cf6fa16c860744fd5978cd3c01a2
src/lexington/util/paths.py
src/lexington/util/paths.py
from urllib import parse from werkzeug.wrappers import Request from lexington.util.di import depends_on @depends_on(['environ']) def get_request(environ): return Request(environ) # TODO: clean up all of these... @depends_on(['environ']) def get_method(environ): return environ['REQUEST_METHOD'] @depends_on([...
from werkzeug.wrappers import Request from lexington.util.di import depends_on @depends_on(['environ']) def get_request(environ): return Request(environ) @depends_on(['request']) def get_method(request): return request.method @depends_on(['request']) def get_path(request): return request.path @depends_...
Reduce direct dependencies on environ
Reduce direct dependencies on environ
Python
mit
jmikkola/Lexington
2dc34a9952fda8a46a89aa43ea833c36998d891a
shop/models/fields.py
shop/models/fields.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from distutils.version import LooseVersion import re from django.db import connection POSTGRES_FLAG = False if str(connection.vendor) == 'postgresql': POSTGRES_FLAG = True try: import psycopg2 version = re.search('([0-9.]+)', psycopg2.__vers...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from distutils.version import LooseVersion import re from django.db import connection POSTGRES_FLAG = False if str(connection.vendor) == 'postgresql': POSTGRES_FLAG = True try: import psycopg2 version = re.search('([0-9.]+)', psycopg2.__vers...
Add psycopg2's version to the comment
Add psycopg2's version to the comment
Python
bsd-3-clause
nimbis/django-shop,jrief/django-shop,khchine5/django-shop,divio/django-shop,divio/django-shop,divio/django-shop,khchine5/django-shop,awesto/django-shop,nimbis/django-shop,awesto/django-shop,nimbis/django-shop,jrief/django-shop,awesto/django-shop,jrief/django-shop,khchine5/django-shop,nimbis/django-shop,khchine5/django-...
a0e0e70f2ae37bfb3c460324b4aea961f2ea0afb
dallinger/heroku/worker.py
dallinger/heroku/worker.py
"""Heroku web worker.""" import os import redis listen = ['high', 'default', 'low'] redis_url = os.getenv('REDIS_URL', 'redis://localhost:6379') conn = redis.from_url(redis_url) if __name__ == '__main__': # pragma: nocover # These imports are inside the __main__ block # to make sure that we only import fr...
"""Heroku web worker.""" import os import redis listen = ['high', 'default', 'low'] redis_url = os.getenv('REDIS_URL', 'redis://localhost:6379') conn = redis.from_url(redis_url) if __name__ == '__main__': # pragma: nocover # These imports are inside the __main__ block # to make sure that we only import fr...
Make sure bot jobs can be deserialized
Make sure bot jobs can be deserialized
Python
mit
Dallinger/Dallinger,jcpeterson/Dallinger,jcpeterson/Dallinger,Dallinger/Dallinger,jcpeterson/Dallinger,jcpeterson/Dallinger,Dallinger/Dallinger,Dallinger/Dallinger,Dallinger/Dallinger,jcpeterson/Dallinger
b812843f03fd0da920872c109132aee7fae82b3a
tests/instancing_tests/NonterminalsTest.py
tests/instancing_tests/NonterminalsTest.py
#!/usr/bin/env python """ :Author Patrik Valkovic :Created 31.08.2017 11:55 :Licence GNUv3 Part of grammpy """ from unittest import TestCase, main from grammpy import * from grammpy.exceptions import TreeDeletedException class A(Nonterminal): pass class B(Nonterminal): pass class C(Nonterminal): pass class From(Rul...
#!/usr/bin/env python """ :Author Patrik Valkovic :Created 31.08.2017 11:55 :Licence GNUv3 Part of grammpy """ from unittest import TestCase, main from grammpy import * from grammpy.exceptions import TreeDeletedException class A(Nonterminal): pass class B(Nonterminal): pass class C(Nonterminal): pass class From(Rul...
Add test of deleteing child for nonterminal
Add test of deleteing child for nonterminal
Python
mit
PatrikValkovic/grammpy
1d321bb0bd6b8e5b6fc14704a6d1b29a365855d8
goatctf/core/models.py
goatctf/core/models.py
from django.contrib.auth.models import User from django.db import models import markdown from core.settings import CHALLENGE_NAME_LENGTH, FLAG_LENGTH, TEAM_NAME_LENGTH class Challenge(models.Model): """A challenge represents an individual problem to be solved.""" name = models.CharField(max_length=CHALLENGE_...
from django.contrib.auth.models import User from django.db import models import markdown from core.settings import CHALLENGE_NAME_LENGTH, FLAG_LENGTH, TEAM_NAME_LENGTH class Challenge(models.Model): """A challenge represents an individual problem to be solved.""" CATEGORY_CHOICES = ( ('be', 'Beer'),...
Add choices for challenge category
Add choices for challenge category
Python
mit
Without-Proper-Instructions/GoatCTF
068675a641dc412416624c907fe7b1744d007a99
lib/js/Loader.py
lib/js/Loader.py
# # JavaScript Tools # Copyright 2010 Sebastian Werner # from js.core.Profiler import * import logging class Loader(): def __init__(self, classList): self.__classList = classList def generate(self, fileName=None, bootCode=None): result = ["$LAB"] pstart() log...
# # JavaScript Tools # Copyright 2010 Sebastian Werner # from js.core.Profiler import * import logging class Loader(): def __init__(self, classList): self.__classList = classList def generate(self, fileName=None, bootCode=None): result = ["$LAB"] pstart() log...
Make use of array support in script() of LABjs to fix recursion errors
Make use of array support in script() of LABjs to fix recursion errors
Python
mit
zynga/jasy,sebastian-software/jasy,zynga/jasy,sebastian-software/jasy
f8b35e2a0cf092441efe1350871814fd347d3627
tests/classifier/LinearSVC/LinearSVCJavaTest.py
tests/classifier/LinearSVC/LinearSVCJavaTest.py
# -*- coding: utf-8 -*- from unittest import TestCase from sklearn.svm.classes import LinearSVC from ..Classifier import Classifier from ...language.Java import Java class LinearSVCJavaTest(Java, Classifier, TestCase): def setUp(self): super(LinearSVCJavaTest, self).setUp() self.mdl = LinearSV...
# -*- coding: utf-8 -*- from unittest import TestCase from sklearn.datasets import load_digits from sklearn.decomposition import PCA, NMF from sklearn.feature_selection import SelectKBest from sklearn.feature_selection import chi2 from sklearn.model_selection import GridSearchCV from sklearn.pipeline import Pipeline ...
Add test for using optimizers
Add test for using optimizers
Python
bsd-3-clause
nok/sklearn-porter
237a66191295cce2cd52d78bcdb7cbe57e399e56
awx/main/management/commands/remove_instance.py
awx/main/management/commands/remove_instance.py
# Copyright (c) 2015 Ansible, Inc. # All Rights Reserved from django.core.management.base import CommandError from awx.main.management.commands._base_instance import BaseCommandInstance from awx.main.models import Instance instance_str = BaseCommandInstance.instance_str class Command(BaseCommandInstance): """In...
# Copyright (c) 2015 Ansible, Inc. # All Rights Reserved from django.core.management.base import CommandError from awx.main.management.commands._base_instance import BaseCommandInstance from awx.main.models import Instance instance_str = BaseCommandInstance.instance_str class Command(BaseCommandInstance): """In...
Fix verbage around why we are disallowing removing a primary
Fix verbage around why we are disallowing removing a primary
Python
apache-2.0
wwitzel3/awx,wwitzel3/awx,snahelou/awx,snahelou/awx,snahelou/awx,wwitzel3/awx,wwitzel3/awx,snahelou/awx
726f4d016a6e0e3c4d6c053afc98bfcae445620c
test_setup.py
test_setup.py
"""Test setup.py.""" import os import subprocess import sys def test_setup(): """Run setup.py check.""" command = [sys.executable, 'setup.py', 'check', '--metadata', '--strict'] assert subprocess.run(command).returncode == 0 def test_console_scripts(): """Ensure console scripts were installed corr...
"""Test setup.py.""" import os import subprocess import sys def test_setup(): """Run setup.py check.""" command = [sys.executable, 'setup.py', 'check', '--metadata', '--strict'] assert subprocess.run(command).returncode == 0 def test_console_scripts(): """Ensure console scripts were installed corr...
Use os.environ['PATH'] instead of sys.path
Use os.environ['PATH'] instead of sys.path
Python
bsd-3-clause
dmtucker/keysmith
22f52f97db77e0127172721eacc98196d32a77d7
Lib/importlib/test/import_/util.py
Lib/importlib/test/import_/util.py
import functools import importlib._bootstrap using___import__ = False def import_(*args, **kwargs): """Delegate to allow for injecting different implementations of import.""" if using___import__: return __import__(*args, **kwargs) else: return importlib._bootstrap.__import__(*args, **kwa...
import functools import importlib import importlib._bootstrap import unittest using___import__ = False def import_(*args, **kwargs): """Delegate to allow for injecting different implementations of import.""" if using___import__: return __import__(*args, **kwargs) else: return importlib._...
Move a test-skipping decorator over to unittest.skipIf.
Move a test-skipping decorator over to unittest.skipIf.
Python
mit
sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator
f641be2a8b841eea71f9a0fb5709972debb99df3
stingray/bispectrum.py
stingray/bispectrum.py
from __future__ import division import numpy as np from stingray import lightcurve class Bispectrum(object): def __init__(self, lc, maxlag, scale=None): self.lc = lc # change to fs = 1/lc.dt self.maxlag = maxlag self.scale = scale self.fs = None # Outputs ...
from __future__ import division import numpy as np from stingray import lightcurve class Bispectrum(object): def __init__(self, lc, maxlag, scale=None): def __init__(self, lc, maxlag, scale=None): self._make_bispetrum(lc, maxlag, scale) def _make_bispetrum(self, lc, maxlag, scale): ...
Make Bispectrum object assign values to attributes
Make Bispectrum object assign values to attributes
Python
mit
pabell/stingray,StingraySoftware/stingray,evandromr/stingray,abigailStev/stingray
04de16d7287bad5023b34efc072e104d8b35c29a
test/test.py
test/test.py
from RPi import GPIO GPIO.setmode(GPIO.BCM) num_pins = 28 pins = range(num_pins) for pin in pins: GPIO.setup(pin, GPIO.IN, GPIO.PUD_UP) pin_states = {pin: GPIO.input(pin) for pin in pins} print() for pin, state in pin_states.items(): print("%2d: %s" % (pin, state)) active = sum(pin_states.values()) inact...
from RPi import GPIO GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) num_pins = 28 pins = range(num_pins) for pin in pins: GPIO.setup(pin, GPIO.IN, GPIO.PUD_UP) pin_states = {pin: GPIO.input(pin) for pin in pins} print() for pin, state in pin_states.items(): print("%2d: %s" % (pin, state)) active = [pin f...
Add printing of active/inactive pins
Add printing of active/inactive pins
Python
bsd-3-clause
raspberrypilearning/dots,RPi-Distro/python-rpi-dots
5b00010451f9ea58936f98b72737a646d77e1bd9
server/tests/forms/test_RegistrationForm.py
server/tests/forms/test_RegistrationForm.py
import wtforms_json import pytest from forms.RegistrationForm import RegistrationForm wtforms_json.init() class TestRegistrationForm: def test_valid(self): json = { 'username': 'someusername', 'password': 'password', 'confirm': 'confirm', 'email': 'someem...
import pytest from forms.RegistrationForm import RegistrationForm class TestRegistrationForm: def test_valid(self): json = { 'username': 'someusername', 'password': 'password', 'confirm': 'password', 'email': 'someemail@email.com' } form =...
Add tests for failing registration forms
Add tests for failing registration forms
Python
mit
ganemone/ontheside,ganemone/ontheside,ganemone/ontheside
c31bc6f1b0782a7d9c409e233a363be651594006
exporters/decompressors.py
exporters/decompressors.py
from exporters.pipeline.base_pipeline_item import BasePipelineItem import logging import zlib __all__ = ['BaseDecompressor', 'ZLibDecompressor', 'NoDecompressor'] class BaseDecompressor(BasePipelineItem): def decompress(self): raise NotImplementedError() def create_decompressor(): # create zlib dec...
from exporters.pipeline.base_pipeline_item import BasePipelineItem import sys import zlib import six __all__ = ['BaseDecompressor', 'ZLibDecompressor', 'NoDecompressor'] class BaseDecompressor(BasePipelineItem): def decompress(self): raise NotImplementedError() def create_decompressor(): # create z...
Append information to the zlib error
Append information to the zlib error
Python
bsd-3-clause
scrapinghub/exporters
761aff647d3e20fc25f1911efa5d2235fe4b21d8
modoboa/extensions/admin/forms/forward.py
modoboa/extensions/admin/forms/forward.py
from django import forms from django.utils.translation import ugettext as _, ugettext_lazy from modoboa.lib.exceptions import BadRequest, PermDeniedException from modoboa.lib.emailutils import split_mailbox from modoboa.extensions.admin.models import ( Domain ) class ForwardForm(forms.Form): dest = forms.Char...
from django import forms from django.utils.translation import ugettext as _, ugettext_lazy from modoboa.lib.exceptions import BadRequest, PermDeniedException from modoboa.lib.emailutils import split_mailbox from modoboa.extensions.admin.models import ( Domain ) class ForwardForm(forms.Form): dest = forms.Char...
Add "form-control" attribute to some textareas
Add "form-control" attribute to some textareas
Python
isc
modoboa/modoboa,RavenB/modoboa,mehulsbhatt/modoboa,bearstech/modoboa,modoboa/modoboa,RavenB/modoboa,tonioo/modoboa,bearstech/modoboa,mehulsbhatt/modoboa,bearstech/modoboa,carragom/modoboa,modoboa/modoboa,tonioo/modoboa,carragom/modoboa,modoboa/modoboa,bearstech/modoboa,RavenB/modoboa,carragom/modoboa,tonioo/modoboa,meh...
695304372ebe4ad76c5d6ce7dea7f39c28ffba07
libexec/wlint/punctuation-style.py
libexec/wlint/punctuation-style.py
#!/usr/bin/python3 import re import wlint.common import wlint.punctuation class PunctuationStyle(wlint.common.Tool): def __init__(self, description): super().__init__(description) self.checks = wlint.punctuation.PunctuationRules().rules def setup(self, arguments): self.result = 0 ...
#!/usr/bin/python3 import operator import wlint.common import wlint.punctuation class PunctuationStyle(wlint.common.Tool): def __init__(self, description): super().__init__(description) self.checks = wlint.punctuation.PunctuationRules().rules def setup(self, arguments): self.result...
Sort punctuation hits so output is based on line and column, not the order rules are checked
Sort punctuation hits so output is based on line and column, not the order rules are checked
Python
bsd-2-clause
snewell/wlint,snewell/wlint,snewell/writing-tools,snewell/writing-tools
8d85bfd34c291f01235eb630f458972cc11c58ad
embed_tweet.py
embed_tweet.py
""" Embedded tweet plugin for Pelican ================================= This plugin allows you to embed Twitter tweets into your articles. And also provides a link for Twitter username. i.e. @username will be replaced by a link to Twitter username page. @username/status/tweetid ...
""" Embedded tweet plugin for Pelican ================================= This plugin allows you to embed Twitter tweets into your articles. And also provides a link for Twitter username. i.e. @username will be replaced by a link to Twitter username page. @username/status/tweetid ...
Check content._content before using it to prevent errors
Check content._content before using it to prevent errors
Python
mit
lqez/pelican-embed-tweet
531c9e943748c576c963b809a7f1052d611346b9
hearthstone/stringsfile.py
hearthstone/stringsfile.py
""" Hearthstone Strings file File format: TSV. Lines starting with `#` are ignored. Key is always `TAG` """ import csv from typing import Dict import hearthstone_data StringsRow = Dict[str, str] StringsDict = Dict[str, StringsRow] _cache: Dict[str, StringsDict] = {} def load(fp) -> StringsDict: reader = csv.Dic...
""" Hearthstone Strings file File format: TSV. Lines starting with `#` are ignored. Key is always `TAG` """ import csv from typing import Dict import hearthstone_data StringsRow = Dict[str, str] StringsDict = Dict[str, StringsRow] _cache: Dict[str, StringsDict] = {} def load(fp) -> StringsDict: reader = csv.Dic...
Fix BOM issue with latest strings
Fix BOM issue with latest strings
Python
mit
HearthSim/python-hearthstone
c85ff679ef7a4c88dc4c625f69faed76ef195111
frappe/website/page_renderers/not_found_page.py
frappe/website/page_renderers/not_found_page.py
import os from urllib.parse import urlparse import frappe from frappe.website.page_renderers.template_page import TemplatePage from frappe.website.utils import can_cache HOMEPAGE_PATHS = ('/', '/index', 'index') class NotFoundPage(TemplatePage): def __init__(self, path, http_status_code): self.request_path = path...
import os from urllib.parse import urlparse import frappe from frappe.website.page_renderers.template_page import TemplatePage from frappe.website.utils import can_cache HOMEPAGE_PATHS = ('/', '/index', 'index') class NotFoundPage(TemplatePage): def __init__(self, path, http_status_code=None): self.request_path =...
Set default value for http_status_code
fix(NotFoundPage): Set default value for http_status_code
Python
mit
mhbu50/frappe,yashodhank/frappe,mhbu50/frappe,almeidapaulopt/frappe,StrellaGroup/frappe,mhbu50/frappe,almeidapaulopt/frappe,yashodhank/frappe,StrellaGroup/frappe,almeidapaulopt/frappe,frappe/frappe,frappe/frappe,yashodhank/frappe,yashodhank/frappe,almeidapaulopt/frappe,frappe/frappe,StrellaGroup/frappe,mhbu50/frappe
74800bf43f9b0f130a7b096afd20db373e7dad1e
web/blueprints/helpers/exception.py
web/blueprints/helpers/exception.py
import traceback from flask import flash from sqlalchemy.exc import InternalError from pycroft.helpers import AutoNumber from pycroft.model import session from pycroft.lib.net import MacExistsException, SubnetFullException from pycroft.model.host import MulticastFlagException from pycroft.model.types import InvalidM...
import traceback from flask import flash from pycroft.lib.net import MacExistsException, SubnetFullException from pycroft.model import session from pycroft.model.host import MulticastFlagException from pycroft.model.types import InvalidMACAddressException def web_execute(function, success_message, *args, **kwargs):...
Remove “username taken in abe” handling
Remove “username taken in abe” handling
Python
apache-2.0
agdsn/pycroft,agdsn/pycroft,agdsn/pycroft,agdsn/pycroft,agdsn/pycroft
06a70ae323f0eb1fe50c1f01a31ef9548a24b00c
tests/test_favicons.py
tests/test_favicons.py
from django.test import TestCase from mock import patch from feedhq.feeds.models import Favicon, Feed from .factories import FeedFactory from . import responses class FaviconTests(TestCase): @patch("requests.get") def test_existing_favicon_new_feed(self, get): get.return_value = responses(304) ...
from mock import patch from feedhq.feeds.models import Favicon, Feed from .factories import FeedFactory from . import responses, TestCase class FaviconTests(TestCase): @patch("requests.get") def test_existing_favicon_new_feed(self, get): get.return_value = responses(304) FeedFactory.create(u...
Use base TestCase to properly cleanup indices
Use base TestCase to properly cleanup indices
Python
bsd-3-clause
rmoorman/feedhq,feedhq/feedhq,rmoorman/feedhq,feedhq/feedhq,rmoorman/feedhq,rmoorman/feedhq,rmoorman/feedhq,vincentbernat/feedhq,feedhq/feedhq,vincentbernat/feedhq,feedhq/feedhq,vincentbernat/feedhq,feedhq/feedhq,vincentbernat/feedhq,vincentbernat/feedhq
f089a7828ac2eb42b437166880eef6fea102a8e1
speech/google/cloud/speech/__init__.py
speech/google/cloud/speech/__init__.py
# Copyright 2016 Google 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 2016 Google 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, ...
Make Encoding accessible from speech.Encoding.
Make Encoding accessible from speech.Encoding.
Python
apache-2.0
jonparrott/google-cloud-python,dhermes/gcloud-python,tswast/google-cloud-python,tseaver/google-cloud-python,googleapis/google-cloud-python,daspecster/google-cloud-python,Fkawala/gcloud-python,Fkawala/gcloud-python,dhermes/google-cloud-python,dhermes/gcloud-python,GoogleCloudPlatform/gcloud-python,dhermes/google-cloud-p...
b59f09f02c3f22ba53f08790babd75348153d64b
tests/hashes_test.py
tests/hashes_test.py
from nose.tools import istest, assert_equal from whack.hashes import Hasher @istest def hashing_the_same_single_value_gives_the_same_hash(): def create_hash(): hasher = Hasher() hasher.update("one") return hasher.hexdigest() assert_equal(create_hash(), create_hash())
from nose.tools import istest, assert_equal from whack.hashes import Hasher @istest def hashing_the_same_single_value_gives_the_same_hash(): def create_hash(): hasher = Hasher() hasher.update("one") return hasher.hexdigest() assert_equal(create_hash(), create_hash()) @istest def ...
Add test for hashing multiple values
Add test for hashing multiple values
Python
bsd-2-clause
mwilliamson/whack
39c5decd98e8d4feb6c1bbfa487faf35396c8b12
logdna/__init__.py
logdna/__init__.py
from .logdna import LogDNAHandler __all__ = ['LogDNAHandler']
from .logdna import LogDNAHandler __all__ = ['LogDNAHandler'] # Publish this class to the "logging.handlers" module so that it can be use # from a logging config file via logging.config.fileConfig(). import logging.handlers logging.handlers.LogDNAHandler = LogDNAHandler
Make available via config file
feat(handlers): Make available via config file - Add to `logging.handlers` such that LogDNAHandler can be configured via a logging config file
Python
mit
logdna/python
aafa37c83c1464c16c2c6b69cc1546a537ec99a3
main/forms.py
main/forms.py
from django import forms from main.fields import RegexField class IndexForm(forms.Form): id_list = forms.CharField( widget=forms.Textarea, label='ID List', help_text='List of students IDs to query, one per line.') student_id_regex = RegexField( label='Student ID regex', help_t...
from django import forms from main.fields import RegexField class IndexForm(forms.Form): id_list = forms.CharField( help_text='List of students IDs to query, one per line.', label='ID List', widget=forms.Textarea(attrs={ 'placeholder': 'Random text\n1234567\n7654321'})) st...
Add placeholder to ID list field
Add placeholder to ID list field
Python
mit
m4tx/usos-id-mapper,m4tx/usos-id-mapper
b8938849ce9239836d2b601dd43324284f1b5604
whatinstalled.py
whatinstalled.py
import os history_file = os.path.expanduser("~")+"/.bash_history" f = open(history_file,"r") keywords = ["pip", "tar", "brew", "apt-get", "install", "luarocks", "easy_install", "gem", "npm"] for line in f: for item in keywords: if item in line: print(line[:-1]) break
import os history_file = os.path.expanduser("~")+"/.bash_history" f = open(history_file,"r") keywords = ["pip", "tar", "brew", "apt-get", "aptitude", "apt", "install", "luarocks", "easy_install", "gem", "npm", "bower"] for line in f: for item in keywords: if item in line: print(line[:-1]) break
Add aptitude and apt + bower
Add aptitude and apt + bower
Python
mit
AlexMili/WhatInstalled
ef281c765f46ead27105f78fe634ace64fca776b
yowsup/layers/protocol_iq/layer.py
yowsup/layers/protocol_iq/layer.py
from yowsup.layers import YowProtocolLayer from yowsup.common import YowConstants from .protocolentities import * class YowIqProtocolLayer(YowProtocolLayer): def __init__(self): handleMap = { "iq": (self.recvIq, self.sendIq) } super(YowIqProtocolLayer, self).__init__(handleMap) ...
from yowsup.layers import YowProtocolLayer from yowsup.common import YowConstants from .protocolentities import * class YowIqProtocolLayer(YowProtocolLayer): def __init__(self): handleMap = { "iq": (self.recvIq, self.sendIq) } super(YowIqProtocolLayer, self).__init__(handleMap) ...
Handle Ping result in ResultIqProtocolEntity
Handle Ping result in ResultIqProtocolEntity refs #402
Python
mit
ongair/yowsup,biji/yowsup
c3e27aee3aa27a81dff2e8aaa5ab9be13725f329
mesos/compute_cluster_url.py
mesos/compute_cluster_url.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import sys # Get the Mesos cluster URL, assuming the EC2 script environment variables # are all available. active_master = os.getenv("MESOS_MASTERS").split("\n")[0] zoo_list = os.getenv("MESOS_ZOO_LIST") if zoo_list.strip() == "NONE": print active_master + "...
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import sys # Get the Mesos cluster URL, assuming the EC2 script environment variables # are all available. active_master = os.getenv("MESOS_MASTERS").split("\n")[0] zoo_list = os.getenv("MESOS_ZOO_LIST") if zoo_list.strip() == "NONE": print "mesos://" + acti...
Include URI scheme in Mesos cluster_url
Include URI scheme in Mesos cluster_url
Python
apache-2.0
serialx/spark-ec2,madhavhugar/spark-ec2,SiGe/spark-ec2,romanini/spark-ec2,madhavhugar/spark-ec2,uronce-cc/spark-ec2,serialx/spark-ec2,inreachventures/spark-ec2,BrandwatchLtd/spark-ec2,tomerk/spark-ec2,jyt109/spark-ec2,GordonWang/spark-ec2,romanini/spark-ec2,Wealthport/spark-ec2,pluribus-labs/spark-ec2,paulomagalhaes/sp...
5a47ca87858bb08fcaac4a38322dc04eaf74cac2
src/foremast/utils/get_sns_topic_arn.py
src/foremast/utils/get_sns_topic_arn.py
"""SNS Topic functions.""" import logging import boto3 from ..exceptions import SNSTopicNotFound LOG = logging.getLogger(__name__) def get_sns_topic_arn(topic_name, account, region): """Get SNS topic ARN. Args: topic_name (str): Name of the topic to lookup. account (str): Environment, e.g....
"""SNS Topic functions.""" import logging import boto3 from ..exceptions import SNSTopicNotFound LOG = logging.getLogger(__name__) def get_sns_topic_arn(topic_name, account, region): """Get SNS topic ARN. Args: topic_name (str): Name of the topic to lookup. account (str): Environment, e.g....
Return ARN directly if topic name appears to be an ARN
Return ARN directly if topic name appears to be an ARN
Python
apache-2.0
gogoair/foremast,gogoair/foremast
e2d80effa425bc12544f3bbf1ad5546b5af40572
insert_sort.py
insert_sort.py
def insert_sort(my_list): for i in range(1, len(my_list)): j = i - 1 key = my_list[i] while (j >= 0) and (my_list[j] > key): my_list[j + 1] = my_list[j] j -= 1 my_list[j + 1] = key if __name__ == '__main__':
def insert_sort(my_list): for i in range(1, len(my_list)): j = i - 1 key = my_list[i] while (j >= 0) and (my_list[j] > key): my_list[j + 1] = my_list[j] j -= 1 my_list[j + 1] = key if __name__ == '__main__': import timeit best_list = [i for i in rang...
Add timing to __name__ block
Add timing to __name__ block
Python
mit
nbeck90/data_structures_2
7506e93942333a28f1e66c95016071760382a071
packages/Python/lldbsuite/test/repl/pounwrapping/TestPOUnwrapping.py
packages/Python/lldbsuite/test/repl/pounwrapping/TestPOUnwrapping.py
# TestPOUnwrapping.py # # This source file is part of the Swift.org open source project # # Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors # Licensed under Apache License v2.0 with Runtime Library Exception # # See https://swift.org/LICENSE.txt for license information # See https://swift.org/CONTRIB...
# TestPOUnwrapping.py # # This source file is part of the Swift.org open source project # # Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors # Licensed under Apache License v2.0 with Runtime Library Exception # # See https://swift.org/LICENSE.txt for license information # See https://swift.org/CONTRIB...
Revert "Disable test that fails on bot"
Revert "Disable test that fails on bot" This reverts commit e214e46e748881e6418ffac374a87d6ad30fcfea. I have reverted the swift commit that was causing this failure. rdar://35264910
Python
apache-2.0
apple/swift-lldb,apple/swift-lldb,apple/swift-lldb,apple/swift-lldb,apple/swift-lldb,apple/swift-lldb
04bccd678ba7a67373b94695d7d87d0cf95dffd6
tests/unit/app_unit_test.py
tests/unit/app_unit_test.py
# -*- coding: utf-8 -*- """ Unit Test: orchard.app """ import unittest import orchard class AppUnitTest(unittest.TestCase): def setUp(self): app = orchard.create_app('Testing') self.app_context = app.app_context() self.app_context.push() self.client = app.test_client(use_co...
# -*- coding: utf-8 -*- """ Unit Test: orchard.app """ import unittest import orchard class AppUnitTest(unittest.TestCase): def setUp(self): app = orchard.create_app('Testing') app.config['BABEL_DEFAULT_LOCALE'] = 'en' self.app_context = app.app_context() self.app_context.p...
Set default locale in test to avoid test failures when different default is used than expected.
Set default locale in test to avoid test failures when different default is used than expected.
Python
mit
BMeu/Orchard,BMeu/Orchard
2bc249dc4996c0cccfe61a3d8bf1658fa987e7cf
costcocr/writers/csv.py
costcocr/writers/csv.py
def csv(): def Receipt(meta, body, variables): output = [] def add(s) : output.append(s) if "store" in meta: add("# Store: {}".format(meta["store"])) if "date" in meta: add("# Date: {}".format(meta["date"])) if "location" in meta: add("...
def Receipt(meta, body, variables): output = [] def add(s) : output.append(s) if "store" in meta: add("# Store: {}".format(meta["store"])) if "date" in meta: add("# Date: {}".format(meta["date"])) if "location" in meta: add("# Location: {}".format(meta["location"])) ad...
Convert CSV writer to a module definition.
Convert CSV writer to a module definition. Use __import__ to import it as a dictionary.
Python
bsd-3-clause
rdodesigns/costcocr
e276753b458ef7c4c05469324173a455c0e2db46
tests/basics/subclass-native3.py
tests/basics/subclass-native3.py
class MyExc(Exception): pass e = MyExc(100, "Some error") print(e) print(repr(e)) print(e.args)
class MyExc(Exception): pass e = MyExc(100, "Some error") print(e) print(repr(e)) print(e.args) try: raise MyExc("Some error") except MyExc as e: print("Caught exception:", repr(e)) try: raise MyExc("Some error2") except Exception as e: print("Caught exception:", repr(e)) try: raise MyExc("S...
Add testcases for catching user Exception subclasses.
tests: Add testcases for catching user Exception subclasses.
Python
mit
SungEun-Steve-Kim/test-mp,kerneltask/micropython,oopy/micropython,vitiral/micropython,martinribelotta/micropython,xyb/micropython,omtinez/micropython,HenrikSolver/micropython,ChuckM/micropython,utopiaprince/micropython,ericsnowcurrently/micropython,feilongfl/micropython,ericsnowcurrently/micropython,dxxb/micropython,sk...
4d161278963252d8502f1be2bfb857bcb379f540
test/python/topology/test_utilities.py
test/python/topology/test_utilities.py
# Licensed Materials - Property of IBM # Copyright IBM Corp. 2017 import sys import streamsx.topology.context def standalone(test, topo): rc = streamsx.topology.context.submit("STANDALONE", topo) test.assertEqual(0, rc)
# Licensed Materials - Property of IBM # Copyright IBM Corp. 2017 import sys import streamsx.topology.context def standalone(test, topo): rc = streamsx.topology.context.submit("STANDALONE", topo) test.assertEqual(0, rc['return_code'])
Return value of submit is now a json dict
Return value of submit is now a json dict
Python
apache-2.0
ibmkendrick/streamsx.topology,ibmkendrick/streamsx.topology,ddebrunner/streamsx.topology,IBMStreams/streamsx.topology,IBMStreams/streamsx.topology,wmarshall484/streamsx.topology,ibmkendrick/streamsx.topology,ddebrunner/streamsx.topology,ddebrunner/streamsx.topology,IBMStreams/streamsx.topology,IBMStreams/streamsx.topol...
024597e8f32b49844c333fa551862563f2c508ca
pymatgen/__init__.py
pymatgen/__init__.py
from __future__ import unicode_literals __author__ = "Pymatgen Development Team" __email__ ="pymatgen@googlegroups.com" __maintainer__ = "Shyue Ping Ong" __maintainer_email__ ="shyuep@gmail.com" __date__ = "Jul 8 2016" __version__ = "4.0.2" # Useful aliases for commonly used objects and modules. # Allows from pymatg...
from __future__ import unicode_literals __author__ = "Pymatgen Development Team" __email__ ="pymatgen@googlegroups.com" __maintainer__ = "Shyue Ping Ong" __maintainer_email__ ="shyuep@gmail.com" __date__ = "Jul 8 2016" __version__ = "4.0.2" # Order of imports is important on some systems to avoid # failures when lo...
Fix for DLL load failures when importing top-level package
Fix for DLL load failures when importing top-level package The order of import affects the success of import pymatgen on certain 64-bit Windows setups and therefore a workaround has been added. Former-commit-id: 0ff590e053d5e0be2959720a861d06d7ba74d132 [formerly 0da252fe086eaa98942c4eaa39750739964be96f] Former-commit...
Python
mit
gpetretto/pymatgen,dongsenfo/pymatgen,czhengsci/pymatgen,blondegeek/pymatgen,davidwaroquiers/pymatgen,johnson1228/pymatgen,fraricci/pymatgen,dongsenfo/pymatgen,czhengsci/pymatgen,Bismarrck/pymatgen,setten/pymatgen,vorwerkc/pymatgen,tallakahath/pymatgen,tschaume/pymatgen,johnson1228/pymatgen,nisse3000/pymatgen,richardtr...