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 |
|---|---|---|---|---|---|---|---|---|---|
e5940200612b293b1cecff4c6a683ecefa684345 | dirMonitor.py | dirMonitor.py | #!/usr/bin/env python
import os, sys, time
folders = sys.argv[1:]
currSize = dict((x, 0) for x in folders)
totalSize = dict((x, 0) for x in folders)
maxSize = dict((x, 0) for x in folders)
fmts = "%*s %13s %13s %13s"
fmtd = "%*s %13d %13d %13d"
n = 0
while True:
print fmts % (15, "dir", "size", "avg", "m... | #!/usr/bin/env python
import os, sys, time
folders = sys.argv[1:]
nameWidth = max([len(f) for f in folders])
currSize = dict((x, 0) for x in folders)
totalSize = dict((x, 0) for x in folders)
maxSize = dict((x, 0) for x in folders)
fmts = "%*s %13s%s %13s%s %13s%s"
n = 0
while True:
print fmts % (nameWidth,... | Add formatting to directory monitor. | Add formatting to directory monitor.
| Python | apache-2.0 | jskora/scratch-nifi,jskora/scratch-nifi,jskora/scratch-nifi |
d12fecd2eb012862b8d7654c879dccf5ccce833f | jose/backends/__init__.py | jose/backends/__init__.py |
try:
from jose.backends.pycrypto_backend import RSAKey
except ImportError:
from jose.backends.cryptography_backend import CryptographyRSAKey as RSAKey
try:
from jose.backends.cryptography_backend import CryptographyECKey as ECKey
except ImportError:
from jose.backends.ecdsa_backend import ECDSAECKey a... |
try:
from jose.backends.pycrypto_backend import RSAKey
except ImportError:
try:
from jose.backends.cryptography_backend import CryptographyRSAKey as RSAKey
except ImportError:
from jose.backends.rsa_backend import RSAKey
try:
from jose.backends.cryptography_backend import CryptographyE... | Enable Python RSA backend as a fallback. | Enable Python RSA backend as a fallback.
| Python | mit | mpdavis/python-jose |
69e8798137ca63b78adf0c41582e89973d2ea129 | create.py | create.py | import os
import sys
base_path = os.path.dirname(__file__)
sys.path.append(base_path)
one_up_path = os.path.abspath(os.path.join(os.path.dirname(__file__),'..'))
sys.path.append(one_up_path)
import model_creator
import util_functions
def create(text,score,prompt_string,model_path):
model_path=util_functions.cre... | import os
import sys
base_path = os.path.dirname(__file__)
sys.path.append(base_path)
one_up_path = os.path.abspath(os.path.join(os.path.dirname(__file__),'..'))
sys.path.append(one_up_path)
import model_creator
import util_functions
def create(text,score,prompt_string,model_path):
model_path=util_functions.cre... | Work on model file handling | Work on model file handling
| Python | agpl-3.0 | edx/ease,edx/ease |
cb97f453284658da56d12ab696ef6b7d7991c727 | dipy/io/tests/test_csareader.py | dipy/io/tests/test_csareader.py | """ Testing Siemens CSA header reader
"""
import os
from os.path import join as pjoin
import numpy as np
import dipy.io.csareader as csa
from nose.tools import assert_true, assert_false, \
assert_equal, assert_raises
from numpy.testing import assert_array_equal, assert_array_almost_equal
from dipy.testing imp... | """ Testing Siemens CSA header reader
"""
import os
from os.path import join as pjoin
import numpy as np
import dipy.io.csareader as csa
from nose.tools import assert_true, assert_false, \
assert_equal, assert_raises
from numpy.testing import assert_array_equal, assert_array_almost_equal
from dipy.testing imp... | TEST - add test for value | TEST - add test for value
| Python | bsd-3-clause | jyeatman/dipy,beni55/dipy,samuelstjean/dipy,FrancoisRheaultUS/dipy,demianw/dipy,demianw/dipy,nilgoyyou/dipy,jyeatman/dipy,Messaoud-Boudjada/dipy,maurozucchelli/dipy,Messaoud-Boudjada/dipy,StongeEtienne/dipy,villalonreina/dipy,JohnGriffiths/dipy,rfdougherty/dipy,villalonreina/dipy,sinkpoint/dipy,JohnGriffiths/dipy,Franc... |
63ca4ab4fc7237a9b32d82d73160b7f02c3ac133 | settings.py | settings.py | # coding: utf-8
import os.path
import yaml
CONFIG_PATH = os.path.join(os.path.dirname(__file__), 'settings.yaml')
with open(CONFIG_PATH, 'r') as fh:
config = yaml.load(fh)
# Jira settings
JIRA_URL = config['jira']['url']
JIRA_USER = config['jira']['user']
JIRA_PASS = config['jira']['pass']
JIRA_PROJECT = confi... | # coding: utf-8
import os.path
import yaml
import logging
CONFIG_PATH = os.path.join(os.path.dirname(__file__), 'settings.yaml')
logger = logging.getLogger(__name__)
try:
with open(CONFIG_PATH, 'r') as fh:
config = yaml.load(fh)
except FileNotFoundError:
logging.error('Config file was not found: s... | Add "config file was not fount" error handler | Add "config file was not fount" error handler
| Python | mit | vv-p/jira-reports,vv-p/jira-reports |
0ad6cb338bbf10c48049d5649b5cd41eab0ed8d1 | prawcore/sessions.py | prawcore/sessions.py | """prawcore.sessions: Provides prawcore.Session and prawcore.session."""
import requests
class Session(object):
"""The low-level connection interface to reddit's API."""
def __init__(self):
"""Preprare the connection to reddit's API."""
self._session = requests.Session()
def __enter__(s... | """prawcore.sessions: Provides prawcore.Session and prawcore.session."""
import requests
class Session(object):
"""The low-level connection interface to reddit's API."""
def __init__(self, authorizer=None):
"""Preprare the connection to reddit's API.
:param authorizer: An instance of :class... | Add optional authorizer parameter to session class and function. | Add optional authorizer parameter to session class and function.
| Python | bsd-2-clause | praw-dev/prawcore |
4fa8f7cb8a0592ed1d37efa20fd4a23d12e88713 | linter.py | linter.py | #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Jack Brewer
# Copyright (c) 2015 Jack Brewer
#
# License: MIT
#
"""This module exports the Stylint plugin class."""
from SublimeLinter.lint import NodeLinter, util
class Stylint(NodeLinter):
"""Provides an in... | #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Jack Brewer
# Copyright (c) 2015 Jack Brewer
#
# License: MIT
"""This module exports the Stylint plugin class."""
from SublimeLinter.lint import NodeLinter, util
class Stylint(NodeLinter):
"""Provides an inte... | Update regexp due to changes in stylint | Update regexp due to changes in stylint
| Python | mit | jackbrewer/SublimeLinter-contrib-stylint |
266e0976ee41e4dd1a9c543c84d422a8fba61230 | linter.py | linter.py | #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Jonas Gratz
# Copyright (c) 2015 Jonas Gratz
#
# License: MIT
#
"""This module exports the Tlec plugin class."""
import sublime
from SublimeLinter.lint import Linter, util
class Tlec(Linter):
"""Provides an in... | #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Jonas Gratz
# Copyright (c) 2015 Jonas Gratz
#
# License: MIT
#
"""This module exports the Tlec plugin class."""
import sublime
from SublimeLinter.lint import Linter, util
class Tlec(Linter):
"""Provides an in... | Check if epages6 settings are configured | Check if epages6 settings are configured
| Python | mit | ePages-rnd/SublimeLinter-contrib-tlec |
563f2e153437e7f78e05ed9dade1bd1690bef6a5 | karspexet/ticket/admin.py | karspexet/ticket/admin.py | from django.contrib import admin
from karspexet.ticket.models import Account, Reservation, Ticket, Voucher, PricingModel
class ReservationAdmin(admin.ModelAdmin):
list_display = ('show', 'total', 'finalized', 'reservation_code', 'tickets')
list_filter = ('finalized', 'show')
class TicketAdmin(admin.ModelAd... | from django.contrib import admin
from karspexet.ticket.models import Account, Reservation, Ticket, Voucher, PricingModel
class ReservationAdmin(admin.ModelAdmin):
list_display = ('show', 'total', 'finalized', 'reservation_code', 'session_timeout', 'tickets')
list_filter = ('finalized', 'show')
class Ticket... | Add session_timeout to ReservationAdmin list_display | Add session_timeout to ReservationAdmin list_display
| Python | mit | Karspexet/Karspexet,Karspexet/Karspexet,Karspexet/Karspexet,Karspexet/Karspexet,Karspexet/Karspexet |
aad92644d01994685d20121def511da2765adfad | src/data.py | src/data.py | import csv
import datetime
class Row(dict):
def __init__(self, *args, **kwargs):
super(Row, self).__init__(*args, **kwargs)
self._start_date = None
self._end_date = None
def _cast_date(self, s):
if not s:
return None
return datetime.datetime.strptime(s, '%... | import csv
import datetime
class Row(dict):
def __init__(self, *args, **kwargs):
super(Row, self).__init__(*args, **kwargs)
self._start_date = None
self._end_date = None
def _cast_date(self, s):
if not s:
return None
return datetime.datetime.strptime(s, '%... | Add neighbrhood property to row | Add neighbrhood property to row
| Python | unlicense | datascopeanalytics/chicago-new-business,datascopeanalytics/chicago-new-business |
7535bd611b26fa81944058c49e7238bd67a5f577 | forms_builder/wrapper/forms.py | forms_builder/wrapper/forms.py | from django import forms
from django.forms.models import inlineformset_factory
from forms_builder.forms.models import Form, Field
class FormToBuildForm(forms.ModelForm):
"""
A form that is used to create or edit an instance of ``forms.models.Form``.
"""
class Meta:
model = Form
# A form set t... | from django import forms
from django.forms.models import inlineformset_factory
from forms_builder.forms.models import Form, Field
class FormToBuildForm(forms.ModelForm):
"""
A form that is used to create or edit an instance of ``forms.models.Form``.
"""
class Meta:
model = Form
exclude... | Exclude unnecessary fields for Enjaz | Exclude unnecessary fields for Enjaz
| Python | agpl-3.0 | enjaz/enjaz,enjaz/enjaz,osamak/student-portal,osamak/student-portal,enjaz/enjaz,osamak/student-portal,enjaz/enjaz,osamak/student-portal,osamak/student-portal,enjaz/enjaz |
eaec82bb0a4a11f683c34550bdc23b3c6b0c48d2 | examples/M1/M1_export.py | examples/M1/M1_export.py | import M1 # import parameters file
from netpyne import sim # import netpyne sim module
sim.createAndExport(netParams = M1.netParams,
simConfig = M1.simConfig,
reference = 'M1') # create and export network to NeuroML 2 | import M1 # import parameters file
from netpyne import sim # import netpyne sim module
sim.createAndExportNeuroML2(netParams = M1.netParams,
simConfig = M1.simConfig,
reference = 'M1',
connections=True,
stimulations=True) #... | Update script to export to nml2 of m1 | Update script to export to nml2 of m1
| Python | mit | Neurosim-lab/netpyne,thekerrlab/netpyne,Neurosim-lab/netpyne |
565c95ce9a8ff96d177196c6dbf8d8f88cdfa029 | poyo/exceptions.py | poyo/exceptions.py | # -*- coding: utf-8 -*-
class PoyoException(Exception):
"""Super class for all of Poyo's exceptions."""
class NoMatchException(PoyoException):
"""Raised when the parser cannot find a pattern that matches the given
string.
"""
class NoParentException(PoyoException):
"""Raised when there is no p... | # -*- coding: utf-8 -*-
class PoyoException(Exception):
"""Super class for all of Poyo's exceptions."""
class NoMatchException(PoyoException):
"""Raised when the parser cannot find a pattern that matches the given
string.
"""
class NoParentException(PoyoException):
"""Raised when there is no p... | Add an error class for string data that is ignored by the parser | Add an error class for string data that is ignored by the parser
| Python | mit | hackebrot/poyo |
fb02617b29cab97a70a1a11b0d3b7b62b834aa3b | server.py | server.py | from flask import Flask
from flask import request
import flask
import hashlib
import json
import gzip
app = Flask(__name__)
stored_files = {}
@app.route('/profile/<type>', methods=['GET'])
def get_dummy_files(type):
if type == 'lawyer':
pass
elif type == 'doctor:':
pass
elif type == 'fema... | from flask import Flask
from flask import request
import flask
import hashlib
import json
import gzip
app = Flask(__name__)
stored_files = {}
@app.route('/profile/<type>', methods=['GET'])
def get_dummy_files(type):
if type == 'lawyer':
gzip_address = './zipfiles/doc.tar.gz'
elif type == 'doctor:':
... | Structure for sending dummy files | Structure for sending dummy files
| Python | mit | rotemh/soteria |
24fc06d17303868ef4ea057cd001ec6cb49ab18f | flask_app.py | flask_app.py | import os
from flask import Flask, render_template
from jinja2 import Template
app = Flask(__name__, template_folder='.', static_url_path='', static_folder='..')
app.config.from_pyfile('settings.py')
BASE = '/%s' % app.config['REPO_NAME']
@app.route('/')
def home():
with open('talk.md', 'r') as f:
templa... | import os
from flask import Flask, render_template
from jinja2 import Template
app = Flask(__name__, template_folder='.', static_url_path='', static_folder='..')
app.config.from_pyfile('settings.py')
BASE = '/%s' % app.config['REPO_NAME']
@app.route('/')
def home():
with open('talk.md', 'r') as f:
templa... | Fix utf-8 problem with åäö and friends. | Fix utf-8 problem with åäö and friends.
| Python | bsd-3-clause | sknippen/refreeze,sknippen/refreeze,sknippen/refreeze |
38a9f75bc87dbfb698b852145b7d62e9913602b4 | tcldis.py | tcldis.py | from __future__ import print_function
def _tcldis_init():
import sys
import _tcldis
mod = sys.modules[__name__]
for key, value in _tcldis.__dict__.iteritems():
if not callable(value):
continue
mod.__dict__[key] = value
_tcldis_init()
| from __future__ import print_function
import _tcldis
printbc = _tcldis.printbc
getbc = _tcldis.getbc
inst_table = _tcldis.inst_table
| Stop trying to be overly clever | Stop trying to be overly clever
| Python | bsd-3-clause | tolysz/tcldis,tolysz/tcldis,tolysz/tcldis,tolysz/tcldis |
0c8739457150e4ae6e47ffb42d43a560f607a141 | tests/run.py | tests/run.py | from spec import eq_, skip, Spec, raises, ok_
from invoke.run import run
from invoke.exceptions import Failure
class Run(Spec):
"""run()"""
def return_code_in_result(self):
r = run("echo 'foo'")
eq_(r.stdout, "foo\n")
eq_(r.return_code, 0)
eq_(r.exited, 0)
def nonzero_ret... | from spec import eq_, skip, Spec, raises, ok_, trap
from invoke.run import run
from invoke.exceptions import Failure
class Run(Spec):
"""run()"""
def return_code_in_result(self):
r = run("echo 'foo'")
eq_(r.stdout, "foo\n")
eq_(r.return_code, 0)
eq_(r.exited, 0)
def nonze... | Add test re: hide kwarg | Add test re: hide kwarg
| Python | bsd-2-clause | frol/invoke,sophacles/invoke,mkusz/invoke,alex/invoke,mkusz/invoke,frol/invoke,pyinvoke/invoke,kejbaly2/invoke,mattrobenolt/invoke,mattrobenolt/invoke,pfmoore/invoke,tyewang/invoke,kejbaly2/invoke,pfmoore/invoke,singingwolfboy/invoke,pyinvoke/invoke |
7fe3776a59de7a133c5e396cb43d9b4bcc476f7d | protocols/views.py | protocols/views.py | from django.contrib.auth.decorators import login_required
from django.http import HttpResponse
from django.shortcuts import render
from members.models import User
from .models import Protocol, Topic
from .forms import ProtocolForm, TopicForm, InstitutionForm
@login_required
def add(request):
data = request.POST ... | from django.contrib.auth.decorators import login_required
from django.http import HttpResponse
from django.shortcuts import render
from members.models import User
from .models import Protocol, Topic
from .forms import ProtocolForm, TopicForm, InstitutionForm
@login_required
def add(request):
data = request.POST ... | Fix the check if form is submitted | Fix the check if form is submitted
| Python | mit | Hackfmi/Diaphanum,Hackfmi/Diaphanum |
7d1a903845db60186318575db11a712cd62d884d | win-installer/gaphor-script.py | win-installer/gaphor-script.py | if __name__ == "__main__":
import gaphor
from gaphor import core
from gaphor.services.actionmanager import ActionManager
from gaphor.plugins.alignment import Alignment
from gaphor.services.componentregistry import ComponentRegistry
from gaphor.ui.consolewindow import ConsoleWindow
from gapho... | if __name__ == "__main__":
import gaphor
from gaphor import core
from gaphor.services.componentregistry import ComponentRegistry
from gaphor.ui.consolewindow import ConsoleWindow
from gaphor.services.copyservice import CopyService
from gaphor.plugins.diagramlayout import DiagramLayout
from g... | Fix mypy import errors due to removed services | Fix mypy import errors due to removed services
Signed-off-by: Dan Yeaw <2591e5f46f28d303f9dc027d475a5c60d8dea17a@yeaw.me>
| Python | lgpl-2.1 | amolenaar/gaphor,amolenaar/gaphor |
5aca39cef15ea4381b30127b8ded31ec37ffd273 | script/notification/ifttt.py | script/notification/ifttt.py | from logs import *
import requests
class Ifttt(object):
"""
"""
def __init__(self, config, packpub_info, upload_info):
self.__packpub_info = packpub_info
self.__url = "https://maker.ifttt.com/trigger/{eventName}/with/key/{apiKey}".format(
eventName=config.get('ifttt', 'ifttt.ev... | from logs import *
import requests
class Ifttt(object):
"""
"""
def __init__(self, config, packpub_info, upload_info):
self.__packpub_info = packpub_info
self.__url = "https://maker.ifttt.com/trigger/{eventName}/with/key/{apiKey}".format(
eventName=config.get('ifttt', 'ifttt.ev... | Add image to ifff request | Add image to ifff request
| Python | mit | niqdev/packtpub-crawler,niqdev/packtpub-crawler,niqdev/packtpub-crawler |
91141713b672f56a8c45f0250b7e9216a69237f8 | features/support/splinter_client.py | features/support/splinter_client.py | import logging
from pymongo import MongoClient
from splinter import Browser
from features.support.http_test_client import HTTPTestClient
from features.support.support import Api
class SplinterClient(object):
def __init__(self, database_name):
self.database_name = database_name
self._write_api =... | import logging
from pymongo import MongoClient
from splinter import Browser
from features.support.http_test_client import HTTPTestClient
from features.support.support import Api
class SplinterClient(object):
def __init__(self, database_name):
self.database_name = database_name
self._write_api =... | Increase splinter wait time to 15 seconds | Increase splinter wait time to 15 seconds
@gtrogers
@maxfliri
| Python | mit | alphagov/backdrop,alphagov/backdrop,alphagov/backdrop |
9516115f722fb3f95882553d8077bf1ab4a670ef | examples/web_demo/exifutil.py | examples/web_demo/exifutil.py | """
This script handles the skimage exif problem.
"""
from PIL import Image
import numpy as np
ORIENTATIONS = { # used in apply_orientation
2: (Image.FLIP_LEFT_RIGHT,),
3: (Image.ROTATE_180,),
4: (Image.FLIP_TOP_BOTTOM,),
5: (Image.FLIP_LEFT_RIGHT, Image.ROTATE_90),
6: (Image.ROTATE_270,),
7... | """
This script handles the skimage exif problem.
"""
from PIL import Image
import numpy as np
ORIENTATIONS = { # used in apply_orientation
2: (Image.FLIP_LEFT_RIGHT,),
3: (Image.ROTATE_180,),
4: (Image.FLIP_TOP_BOTTOM,),
5: (Image.FLIP_LEFT_RIGHT, Image.ROTATE_90),
6: (Image.ROTATE_270,),
7... | FIX web_demo upload was not processing grayscale correctly | FIX web_demo upload was not processing grayscale correctly
| Python | bsd-2-clause | wangg12/caffe,longjon/caffe,gnina/gnina,gogartom/caffe-textmaps,wangg12/caffe,tackgeun/caffe,longjon/caffe,wangg12/caffe,tackgeun/caffe,tackgeun/caffe,gogartom/caffe-textmaps,gnina/gnina,tackgeun/caffe,gnina/gnina,CZCV/s-dilation-caffe,gnina/gnina,wangg12/caffe,longjon/caffe,gnina/gnina,gogartom/caffe-textmaps,CZCV/s-d... |
cb4c0cb2c35d97e0364a4c010715cdf15d261e4c | basehandler.py | basehandler.py | # -*- conding: utf-8 -*-
import os
import jinja2
import webapp2
import utils
JINJA_ENV = jinja2.Environment(
loader=jinja2.FileSystemLoader(os.path.dirname(__file__)),
autoescape=True)
class BaseHandler(webapp2.RequestHandler):
def render(self, template, **kw):
"""Method render t... | # -*- conding: utf-8 -*-
import os
import jinja2
import webapp2
import utils
JINJA_ENV = jinja2.Environment(
loader=jinja2.FileSystemLoader(os.path.dirname(__file__)),
autoescape=True)
class BaseHandler(webapp2.RequestHandler):
def render(self, template, **kw):
"""Method render t... | Add a method to get username if users have valid cookie | Add a method to get username if users have valid cookie
| Python | mit | lttviet/udacity-final |
d33d7e5bf29d8c135c68eb5f1206d2f7df6f42ed | froide/foirequest/search_indexes.py | froide/foirequest/search_indexes.py | from haystack import indexes
from haystack import site
from foirequest.models import FoiRequest
class FoiRequestIndex(indexes.SearchIndex):
text = indexes.EdgeNgramField(document=True, use_template=True)
title = indexes.CharField(model_attr='title')
status = indexes.CharField(model_attr='status')
fir... | from haystack import indexes
from haystack import site
from foirequest.models import FoiRequest
class FoiRequestIndex(indexes.SearchIndex):
text = indexes.EdgeNgramField(document=True, use_template=True)
title = indexes.CharField(model_attr='title')
description = indexes.CharField(model_attr='description... | Add URL and description to search index of FoiRequest | Add URL and description to search index of FoiRequest | Python | mit | catcosmo/froide,fin/froide,catcosmo/froide,fin/froide,ryankanno/froide,stefanw/froide,catcosmo/froide,okfse/froide,ryankanno/froide,ryankanno/froide,CodeforHawaii/froide,LilithWittmann/froide,okfse/froide,CodeforHawaii/froide,ryankanno/froide,stefanw/froide,LilithWittmann/froide,okfse/froide,fin/froide,okfse/froide,Cod... |
f7611e37ef1e0dfaa568515be365d50b3edbd11c | ccdproc/conftest.py | ccdproc/conftest.py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
# this contains imports plugins that configure py.test for astropy tests.
# by importing them here in conftest.py they are discoverable by py.test
# no matter how it is invoked within the source tree.
import os
try:
from astropy.tests.plugins.displa... | # Licensed under a 3-clause BSD style license - see LICENSE.rst
# this contains imports plugins that configure py.test for astropy tests.
# by importing them here in conftest.py they are discoverable by py.test
# no matter how it is invoked within the source tree.
import os
try:
from astropy.tests.plugins.displa... | Fix plugin import for astropy 2.x | Fix plugin import for astropy 2.x
| Python | bsd-3-clause | astropy/ccdproc,mwcraig/ccdproc |
89d9787fc5aa595f6d93d49565313212c2f95b6b | helper_servers/flask_upload.py | helper_servers/flask_upload.py | from flask import Flask, render_template, request, redirect, url_for
from werkzeug.utils import secure_filename
import datetime
import os
def timestamp():
return datetime.datetime.now().strftime('%Y%m%d%H%M%S')
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = '/uploads'
@app.route('/', methods=['GET'])
def i... | from flask import Flask, render_template, request, redirect, url_for
from werkzeug.utils import secure_filename
import datetime
import os
def timestamp():
return datetime.datetime.now().strftime('%Y%m%d%H%M%S')
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = '/uploads'
@app.route('/', methods=['GET'])
def i... | Add simple form to flask upload server | Add simple form to flask upload server
| Python | bsd-3-clause | stephenbradshaw/pentesting_stuff,stephenbradshaw/pentesting_stuff,stephenbradshaw/pentesting_stuff,stephenbradshaw/pentesting_stuff |
9f1134174c594564519a88cbfafe443b2be782e2 | python/render/render_tracks.py | python/render/render_tracks.py | __author__ = 'dcl9'
from render import render_template
import argparse
import yaml
def generate_track_dict(metadata):
d = dict()
d['track_name'] = '{}_{}({})'.format(metadata['protein'], metadata['serial_number'], metadata['author_identifier'])
d['bigbed_url'] = metadata['track_filename']
d['short_lab... | __author__ = 'dcl9'
from render import render_template
import argparse
import yaml
def generate_track_dict(metadata):
d = dict()
d['track_name'] = '{}_{}'.format(metadata['protein'], metadata['serial_number'])
d['bigbed_url'] = metadata['track_filename']
d['short_label'] = metadata['protein']
d['l... | Update track_name, short_label, and long_label per discussions on 2016-09-09 | Update track_name, short_label, and long_label per discussions on 2016-09-09
| Python | mit | Duke-GCB/TrackHubGenerator,Duke-GCB/TrackHubGenerator |
fa5bb37159d09c5bff53b83a4821e3f154892d1d | numba/cuda/device_init.py | numba/cuda/device_init.py | from __future__ import print_function, absolute_import, division
# Re export
from .stubs import (threadIdx, blockIdx, blockDim, gridDim, syncthreads,
shared, local, const, grid, gridsize, atomic,
threadfence_block, threadfence_system,
threadfence)
from .cudad... | from __future__ import print_function, absolute_import, division
# Re export
from .stubs import (threadIdx, blockIdx, blockDim, gridDim, syncthreads,
shared, local, const, grid, gridsize, atomic,
threadfence_block, threadfence_system,
threadfence)
from .cudad... | Fix issue with test discovery and broken CUDA drivers. | Fix issue with test discovery and broken CUDA drivers.
This patch allows the test discovery mechanism to work even in the
case of a broken/misconfigured CUDA driver.
Fixes #2841
| Python | bsd-2-clause | sklam/numba,cpcloud/numba,sklam/numba,numba/numba,seibert/numba,jriehl/numba,numba/numba,stuartarchibald/numba,jriehl/numba,IntelLabs/numba,cpcloud/numba,stuartarchibald/numba,gmarkall/numba,IntelLabs/numba,jriehl/numba,seibert/numba,numba/numba,jriehl/numba,gmarkall/numba,numba/numba,sklam/numba,seibert/numba,stuartar... |
64a78085fffe8dc525596b870c8e150d9171f271 | resources/site-packages/pulsar/monitor.py | resources/site-packages/pulsar/monitor.py | import xbmc
import urllib2
import threading
from pulsar.config import PULSARD_HOST
class PulsarMonitor(xbmc.Monitor):
def __init__(self):
self._closing = threading.Event()
@property
def closing(self):
return self._closing
def onAbortRequested(self):
self._closing.set()
d... | import xbmc
import urllib2
import threading
from pulsar.config import PULSARD_HOST
class PulsarMonitor(xbmc.Monitor):
def __init__(self):
self._closing = threading.Event()
@property
def closing(self):
return self._closing
def onAbortRequested(self):
# Only when closing Kodi
... | Fix issue where Pulsar would enter a restart loop when cancelling a buffering | Fix issue where Pulsar would enter a restart loop when cancelling a buffering
Signed-off-by: Steeve Morin <7f3ba7bbc079b62d3fe54555c2b0ce0ddda2bb7c@gmail.com>
| Python | bsd-3-clause | likeitneverwentaway/plugin.video.quasar,komakino/plugin.video.pulsar,johnnyslt/plugin.video.quasar,elrosti/plugin.video.pulsar,Zopieux/plugin.video.pulsar,pmphxs/plugin.video.pulsar,johnnyslt/plugin.video.quasar,steeve/plugin.video.pulsar,peer23peer/plugin.video.quasar,peer23peer/plugin.video.quasar,likeitneverwentaway... |
67c98ba67f99d5de5022b32fdb3eb9cd0d96908f | scripts/tappedout.py | scripts/tappedout.py | from binascii import unhexlify
def request(context, flow):
if (flow.request.host.find('change.me') > -1 and flow.request.path.find('somethingaboutcurrency') > -1):
def response(context, flow):
if (flow.request.host.find('change.me') > -1 and flow.request.path.find('somethingaboutcurrency') > -1):... | from binascii import unhexlify
#This can be replace by using the "decode" function on the reponse
def request(context, flow):
if (flow.request.host.find('change.me') > -1 and flow.request.path.find('somethingaboutcurrency') > -1):
flow.request.headers['Accept-Encoding'] = ['']
def response(context, flow):... | Add missing line on the script and some comment | Add missing line on the script and some comment
| Python | apache-2.0 | jstuyck/MitmProxyScripts |
09ed0e911e530e9b907ac92f2892248b6af245fa | vcr/errors.py | vcr/errors.py | class CannotOverwriteExistingCassetteException(Exception):
def __init__(self, *args, **kwargs):
message = self._get_message(kwargs["cassette"], kwargs["failed_request"])
super(CannotOverwriteExistingCassetteException, self).__init__(message)
def _get_message(self, cassette, failed_request):
... | class CannotOverwriteExistingCassetteException(Exception):
def __init__(self, *args, **kwargs):
self.cassette = kwargs["cassette"]
self.failed_request = kwargs["failed_request"]
message = self._get_message(kwargs["cassette"], kwargs["failed_request"])
super(CannotOverwriteExistingCas... | Add cassette and failed request as properties of thrown CannotOverwriteCassetteException | Add cassette and failed request as properties of thrown CannotOverwriteCassetteException
| Python | mit | kevin1024/vcrpy,graingert/vcrpy,graingert/vcrpy,kevin1024/vcrpy |
392f209791eede86d65f018a9b873b33cb7ccb02 | test/test_uniprot_retrieval_data.py | test/test_uniprot_retrieval_data.py | import numpy as np
import pandas as pa
import unittest
import pathway_extraction.uniprot_retrieval_data as uniprot_retrieval_data
test_data_directory_uniprot = 'test_data/' + 'test_uniprot_retrieval/'
class uniprot_retrieval_data_test(unittest.TestCase):
def test_extract_information_from_uniprot(self):
... | import numpy as np
import pandas as pa
import unittest
import pathway_extraction.uniprot_retrieval_data as uniprot_retrieval_data
test_data_directory_uniprot = 'test_data/' + 'test_uniprot_retrieval/'
class uniprot_retrieval_data_test(unittest.TestCase):
def test_extract_information_from_uniprot(self):
... | Fix issue with GO term (unsorted). | Fix issue with GO term (unsorted). | Python | agpl-3.0 | ArnaudBelcour/Workflow_GeneList_Analysis,ArnaudBelcour/Workflow_GeneList_Analysis |
b60fb0db2cc1ab3605f34e9b604e920279434c36 | vterm_test.py | vterm_test.py | #!/usr/bin/python
import urwid
def main():
event_loop = urwid.SelectEventLoop()
mainframe = urwid.Frame(
urwid.Columns([
('fixed', 3, urwid.SolidFill('|')),
urwid.Pile([
('weight', 70, urwid.TerminalWidget(None, event_loop)),
('fixed', 1, urwid.F... | #!/usr/bin/python
import urwid
def main():
event_loop = urwid.SelectEventLoop()
mainframe = urwid.Frame(
urwid.Columns([
('fixed', 3, urwid.SolidFill('|')),
urwid.Pile([
('weight', 70, urwid.TerminalWidget(None, event_loop)),
('fixed', 1, urwid.F... | Disable mouse handling in vterm example. | Disable mouse handling in vterm example.
| Python | lgpl-2.1 | westurner/urwid,wardi/urwid,zyga/urwid,douglas-larocca/urwid,harlowja/urwid,drestebon/urwid,hkoof/urwid,bk2204/urwid,urwid/urwid,drestebon/urwid,inducer/urwid,hkoof/urwid,hkoof/urwid,bk2204/urwid,rndusr/urwid,rndusr/urwid,zyga/urwid,westurner/urwid,inducer/urwid,rndusr/urwid,mountainstorm/urwid,foreni-packages/urwid,fo... |
e1fc818b8d563c00c77060cd74d2781b287c0b5d | xnuplot/__init__.py | xnuplot/__init__.py | from .plot import Plot, SPlot
__all__ = ["gnuplot", "numplot"]
| from .plot import Plot, SPlot
__all__ = ["Plot", "SPlot", "gnuplot", "numplot"]
| Include Plot, SPlot in xnuplot.__all__. | Include Plot, SPlot in xnuplot.__all__.
| Python | mit | marktsuchida/Xnuplot |
7c37d4f95897ddbc061ec0a84185a19899b85b89 | compile_for_dist.py | compile_for_dist.py | #!/ms/dist/python/PROJ/core/2.5.2-1/bin/python
# ex: set expandtab softtabstop=4 shiftwidth=4: -*- cpy-indent-level: 4; indent-tabs-mode: nil -*-
# Copyright (C) 2008 Morgan Stanley
#
# This module is part of Aquilon
"""Add /ms/dist to traceback of files compiled in /ms/dev."""
import sys
import py_compile
import re
... | #!/usr/bin/env python2.6
# ex: set expandtab softtabstop=4 shiftwidth=4: -*- cpy-indent-level: 4; indent-tabs-mode: nil -*-
# Copyright (C) 2008 Morgan Stanley
#
# This module is part of Aquilon
"""Add /ms/dist to traceback of files compiled in /ms/dev."""
import sys
import py_compile
import re
def main(args=None):... | Update shebang to use /usr/bin/env. | Update shebang to use /usr/bin/env.
Remove the /ms/dist reference.
| Python | apache-2.0 | quattor/aquilon-protocols,quattor/aquilon-protocols |
6aa8db30afba817ff9b5653480d6f735f09d9c3a | ladder.py | ladder.py | #! /usr/bin/env python3
class Player:
def __init__(self, name, rank):
self.name = name
self.rank = rank
def __repr__(self):
return '<{:s}(name={:s}, rank={:d})>'.format(self.__class__.__name__, self.name, self.rank)
def __str__(self):
rank_str = ''
if self.rank ... | #! /usr/bin/env python3
class Player:
def __init__(self, name, rank):
self.name = name
self.rank = rank
def __repr__(self):
return '<{:s}(name={:s}, rank={:d})>'.format(self.__class__.__name__, self.name, self.rank)
def __str__(self):
rank_str = ''
if self.rank <... | Add players, match_valid to Ladder | Add players, match_valid to Ladder
-Add rudimentary players() method that creates a set
-Add match_valid() method that *only* checks that players are in
the ladder standings
| Python | agpl-3.0 | massgo/mgaladder,hndrewaall/mgaladder,massgo/mgaladder,massgo/mgaladder,hndrewaall/mgaladder,hndrewaall/mgaladder |
17ddd05e35f7cff90530cdb2df0c4971b97e7302 | cmcb/utils.py | cmcb/utils.py | import sys
from functools import wraps, _make_key
import redis
def logging(*triggers, out=sys.stdout):
"""Will log function if all triggers are True"""
log = min(triggers) # will be False if any trigger is false
def wrapper(function):
@wraps(function)
def wrapped_function(*args, **kwarg... | import sys
import inspect
from functools import wraps, _make_key
import redis
def logging(*triggers, out=sys.stdout):
"""Will log function if all triggers are True"""
log = min(triggers) # will be False if any trigger is false
def wrapper(function):
@wraps(function)
def wrapped_function... | Update logging to log async functions properly | Update logging to log async functions properly
| Python | mit | festinuz/cmcb,festinuz/cmcb |
564bca1e051f6b1cc068d1dd53de55fcf4dc7c6f | linter.py | linter.py | #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Josh Hagins
# Copyright (c) 2014 Josh Hagins
#
# License: MIT
#
"""This module exports the Scalac plugin class."""
from SublimeLinter.lint import Linter, util
class Scalac(Linter):
"""Provides an interface to... | #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Josh Hagins
# Copyright (c) 2014 Josh Hagins
#
# License: MIT
#
"""This module exports the Scalac plugin class."""
from SublimeLinter.lint import Linter, util
class Scalac(Linter):
"""Provides an interface to... | Use SublimeLinter-javac as a base | Use SublimeLinter-javac as a base
| Python | mit | jawshooah/SublimeLinter-contrib-scalac |
628d65a15b5c51cb7d4a68e1e6babc01a712a538 | src/redevbazaar.py | src/redevbazaar.py | import pyforms
from pyforms import BaseWidget
from pyforms.Controls import ControlText
class WelcomeScreen(BaseWidget):
def __init__(self):
super(WelcomeScreen, self).__init__("TEST1")
self.testText = ControlText("WHERE IS THIS")
if __name__ == "__main__":
pyforms.startApp(WelcomeScreen) | import pyforms
from pyforms import BaseWidget
from pyforms.Controls import ControlText
class WelcomeScreen(BaseWidget):
def __init__(self):
super(WelcomeScreen, self).__init__("TEST1")
self.testText = ControlText("WHERE IS THIS")
self.mainmenu = [
{ 'Home': [
{'My Listings': self.__getlistingsEv... | Add initial file for GUI | Add initial file for GUI
| Python | mit | cgsheeh/SFWR3XA3_Redevelopment,cgsheeh/SFWR3XA3_Redevelopment |
13b602c50f3be62b2a3a8b267ba00b685fc0c7fe | python/ecep/portal/migrations/0011_auto_20160518_1211.py | python/ecep/portal/migrations/0011_auto_20160518_1211.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
def populate_enrollment_info(apps, schema_editor):
"""
Populate the Enrollment info based on static text
"""
Location = apps.get_model('portal', 'Location')
for loc in Location.objects.all():... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
def populate_enrollment_info(apps, schema_editor):
"""
Populate the Enrollment info based on static text
"""
Location = apps.get_model('portal', 'Location')
for loc in Location.objects.all():... | Update data migration with new CPS description | Update data migration with new CPS description
| Python | mit | smartchicago/chicago-early-learning,smartchicago/chicago-early-learning,smartchicago/chicago-early-learning,smartchicago/chicago-early-learning |
b286e03f96cce8518dd60b74ff8dac6d7b7c5a97 | octohatrack/helpers.py | octohatrack/helpers.py | #!/usr/bin/env python
import sys
def display_results(repo_name, contributors, api_len):
"""
Fancy display.
"""
print("\n")
print("All Contributors:")
# Sort and consolidate on Name
seen = []
for user in sorted(contributors, key=lambda k: k['name'].lower()):
if user["name"] ... | #!/usr/bin/env python
import sys
def _sort_by_name(contributor):
if contributor.get('name'):
return contributor['name'].lower()
return contributor['user_name']
def display_results(repo_name, contributors, api_len):
"""
Fancy display.
"""
print("\n")
print("All Contributors:")... | Support users with no name | display_results: Support users with no name
A user without a name causes an exception, and
the dedup algorithm also merged users without
a name as all of their names were `None`.
Fixes https://github.com/LABHR/octohatrack/issues/103
| Python | bsd-3-clause | LABHR/octohatrack,glasnt/octohat |
866f95cfb0db14da0596efe41a128baf2a3a1cfe | django_basic_tinymce_flatpages/admin.py | django_basic_tinymce_flatpages/admin.py | from django.conf import settings
from django.contrib import admin
from django.contrib.flatpages.admin import FlatpageForm, FlatPageAdmin
from django.contrib.flatpages.models import FlatPage
from django.utils.module_loading import import_string
FLATPAGE_WIDGET = getattr(settings, 'FLATPAGE_WIDGET', 'tinymce.widgets.Tin... | from django.conf import settings
from django.contrib import admin
from django.contrib.flatpages.admin import FlatpageForm, FlatPageAdmin
from django.contrib.flatpages.models import FlatPage
from django.utils.module_loading import import_string
FLATPAGE_WIDGET = getattr(settings, 'FLATPAGE_WIDGET', 'tinymce.widgets.Tin... | Fix form PageForm needs updating. | Fix form PageForm needs updating.
| Python | bsd-3-clause | ad-m/django-basic-tinymce-flatpages |
d1008437dcf618700bce53913f3450aceda8a23f | djangoautoconf/auto_conf_admin_utils.py | djangoautoconf/auto_conf_admin_utils.py | from guardian.admin import GuardedModelAdmin
#from django.contrib import admin
import xadmin as admin
def register_to_sys(class_inst, admin_class = None):
if admin_class is None:
admin_class = type(class_inst.__name__+"Admin", (GuardedModelAdmin, ), {})
try:
admin.site.register(class_inst, ad... | from guardian.admin import GuardedModelAdmin
from django.contrib import admin
#The following not work with guardian?
#import xadmin as admin
def register_to_sys(class_inst, admin_class=None):
if admin_class is None:
admin_class = type(class_inst.__name__ + "Admin", (GuardedModelAdmin, ), {})
try:
... | Remove xadmin as it will not work with guardian. | Remove xadmin as it will not work with guardian.
| Python | bsd-3-clause | weijia/djangoautoconf,weijia/djangoautoconf |
7bfa9d24f7af811746bbb0336b5e75a592cff186 | aws_eis/lib/checks.py | aws_eis/lib/checks.py | import json
import sys
import requests
def py_version():
if sys.version_info < (3, 0, 0):
print(sys.version)
print('You must use Python 3.x to run this application.')
sys.exit(1)
def get_version(endpoint):
r = requests.get('https://{}'.format(endpoint))
es_version = json.loads(r.... | import json
import sys
import requests
def py_version():
if sys.version_info < (3, 0, 0):
print(sys.version)
print('You must use Python 3.x to run this application.')
sys.exit(1)
def get_version(endpoint):
r = requests.get('https://{}'.format(endpoint))
es_version = json.loads(r.... | Fix KeyError: 'version' due to 403 Forbidden error | Fix KeyError: 'version' due to 403 Forbidden error
| Python | mit | jpdoria/aws_eis |
cd006f8d3885005e867255e63819fc8a5c7430bf | redactor/TextEditor.py | redactor/TextEditor.py | from tkinter import *
class TextEditor():
def __init__(self):
self.root = Tk()
self.root.wm_title("BrickText")
self.text_panel = Text(self.root)
self.text_panel.pack(fill=BOTH, expand=YES)
def start(self):
self.root.mainloop()
def get_root(self):
return se... | from tkinter import *
class TextEditor():
def __init__(self):
self.root = Tk()
self.root.wm_title("BrickText")
self.text_panel = Text(self.root)
self.text_panel.pack(fill=BOTH, expand=YES)
def start(self):
self.root.mainloop()
def get_root(self):
return se... | Add getter for text widget | Add getter for text widget | Python | mit | BrickText/BrickText |
8b889c10abf043f6612409973458e8a0f0ed952e | bonus_level.py | bonus_level.py | #!/usr/bin/env python
from time import sleep
# Usage: ./bonus_level.py, then input your plaintext enclosed by quotes
# Note: I haven't made a ciphertext for this because the attack on it depends
# a lot on the machine it was implemented on
secret = input("Please enter your plaintext: ")
for char in secret:
for i... | #!/usr/bin/env python
from time import sleep
# Usage: ./bonus_level.py, then input your plaintext enclosed by quotes
# Note: I haven't made a ciphertext for this because the attack on it depends
# a lot on the machine it was implemented on
secret = input("Please enter your plaintext: ")
for char in secret:
log_c... | Initialize the log counter to 0xFF | Initialize the log counter to 0xFF
| Python | mit | japesinator/Bad-Crypto,japesinator/Bad-Crypto |
64c8fd3fa18dd6644a67cbd9e9aa5f20eb5e85a7 | var/spack/packages/mrnet/package.py | var/spack/packages/mrnet/package.py | from spack import *
class Mrnet(Package):
"""The MRNet Multi-Cast Reduction Network."""
homepage = "http://paradyn.org/mrnet"
url = "ftp://ftp.cs.wisc.edu/paradyn/mrnet/mrnet_4.0.0.tar.gz"
version('4.0.0', 'd00301c078cba57ef68613be32ceea2f')
version('4.1.0', '5a248298b395b329e2371bf25366115c'... | from spack import *
class Mrnet(Package):
"""The MRNet Multi-Cast Reduction Network."""
homepage = "http://paradyn.org/mrnet"
url = "ftp://ftp.cs.wisc.edu/paradyn/mrnet/mrnet_4.0.0.tar.gz"
version('4.0.0', 'd00301c078cba57ef68613be32ceea2f')
version('4.1.0', '5a248298b395b329e2371bf25366115c'... | Add krelloptions variant that is used to turn on a configuration option to build the thread safe lightweight libraries. | Add krelloptions variant that is used to turn on a configuration option to build the thread safe lightweight libraries.
| Python | lgpl-2.1 | EmreAtes/spack,krafczyk/spack,matthiasdiener/spack,matthiasdiener/spack,tmerrick1/spack,krafczyk/spack,LLNL/spack,matthiasdiener/spack,EmreAtes/spack,lgarren/spack,iulian787/spack,EmreAtes/spack,mfherbst/spack,krafczyk/spack,matthiasdiener/spack,skosukhin/spack,skosukhin/spack,mfherbst/spack,EmreAtes/spack,TheTimmy/spa... |
f52287bfc6a38b35daf9d880886cc159550a157c | mutant/__init__.py | mutant/__init__.py | import logging
__version__ = VERSION = (0, 0, 1)
logger = logging.getLogger('mutant')
import hacks | import logging
__version__ = VERSION = (0, 0, 1)
logger = logging.getLogger('mutant')
| Make sure to avoid loading hacks on mutant loading | Make sure to avoid loading hacks on mutant loading
| Python | mit | charettes/django-mutant |
4585ab22a4185122162b987cf8cc845a63ed5a05 | pyheufybot/modules/say.py | pyheufybot/modules/say.py | from module_interface import Module, ModuleType
class Say(Module):
def __init__(self):
self.trigger = "say"
self.moduleType = ModuleType.ACTIVE
self.messagesTypes = ["PRIVMSG"]
self.helpText = "Usage: say <message> | Makes the bot say the given line"
def execute(self, message, ... | from module_interface import Module, ModuleType
from message import IRCResponse, ResponseType
class Say(Module):
def __init__(self):
self.trigger = "say"
self.moduleType = ModuleType.ACTIVE
self.messagesTypes = ["PRIVMSG"]
self.helpText = "Usage: say <message> | Makes the bot say th... | Make it possible for modules to send a response | Make it possible for modules to send a response
| Python | mit | Heufneutje/PyHeufyBot,Heufneutje/PyHeufyBot |
0f4fd0d49ba06963b0b97e032fd2e6eedf8e597a | cloacina/extract_from_b64.py | cloacina/extract_from_b64.py | from bs4 import BeautifulSoup
import json
import re
def extract_from_b64(encoded_doc):
#doc = base64.urlsafe_b64decode(encoded_doc)
doc = encoded_doc.decode("base64")
doc = re.sub("</p><p>", " ", doc)
soup = BeautifulSoup(doc)
news_source = soup.find("meta", {"name":"sourceName"})['content']
ar... | from bs4 import BeautifulSoup
import json
import re
def extract_from_b64(encoded_doc):
#doc = base64.urlsafe_b64decode(encoded_doc)
doc = encoded_doc.decode("base64")
doc = re.sub("</p><p>", " ", doc)
doc = re.sub('<div class="BODY-2">', " ", doc)
soup = BeautifulSoup(doc)
news_source = soup.fi... | Fix missing space between lede and rest of article | Fix missing space between lede and rest of article
| Python | mit | ahalterman/cloacina |
51d37f7ac6bebf9b1d4c6efd16a968b7410a7791 | rcnmf/tests/test_tsqr2.py | rcnmf/tests/test_tsqr2.py | import dask.array as da
from into import into
from dask.array.into import discover
from dask.dot import dot_graph
import tempfile
import rcnmf.tsqr
x = da.random.standard_normal(size=(100, 100), blockshape=(100, 50))
temp_file = tempfile.NamedTemporaryFile(suffix='.hdf5')
uri = temp_file.name + '::/X'
into(uri, x)
... | import dask.array as da
from into import into
from dask.array.into import discover
from dask.dot import dot_graph
import tempfile
import rcnmf.tsqr
x = da.random.standard_normal(size=(100, 100), blockshape=(100, 50))
temp_file = tempfile.NamedTemporaryFile(suffix='.hdf5')
uri = temp_file.name + '::/X'
into(uri, x)
... | Save mul at the end to force execution. | Save mul at the end to force execution.
| Python | bsd-2-clause | marianotepper/csnmf |
359040acc4b8c54db84e154b15cabfb23b4e18a6 | src/aiy/vision/models/utils.py | src/aiy/vision/models/utils.py | """Utility to load compute graphs from diffrent sources."""
import os
def load_compute_graph(name):
path = os.path.join('/opt/aiy/models', name)
with open(path, 'rb') as f:
return f.read()
| """Utility to load compute graphs from diffrent sources."""
import os
def load_compute_graph(name):
path = os.environ.get('VISION_BONNET_MODELS_PATH', '/opt/aiy/models')
with open(os.path.join(path, name), 'rb') as f:
return f.read()
| Use VISION_BONNET_MODELS_PATH env var for custom models path. | Use VISION_BONNET_MODELS_PATH env var for custom models path.
Change-Id: I687ca96e4cf768617fa45d50d68dadffde750b87
| Python | apache-2.0 | google/aiyprojects-raspbian,google/aiyprojects-raspbian,google/aiyprojects-raspbian,google/aiyprojects-raspbian,google/aiyprojects-raspbian |
209c0d0201b76a0f2db7d8b507b2eaa2df03fcae | lib/stats.py | lib/stats.py | """
Statistics.
"""
from numpy import exp
from scipy.stats import rv_continuous
from scipy.special import gamma
class grw_gen(rv_continuous):
"""
Generalized Reverse Weibull distribution.
PDF:
a/gamma(g) * x^(a*g-1) * exp(-x^a)
for x,a,g >= 0
"""
def _pdf(self,x,a,g):
... | """
Statistics.
"""
import numpy as np
from scipy.stats import gengamma, norm
"""
Set default starting parameters for fitting a generalized gamma distribution.
These parameters are sensible for ATLAS v_n distributions.
Order: (a, c, loc, scale) where a,c are shape params.
"""
gengamma._fitstart = lambda data: (... | Replace custom GRW dist with scipy gengamma. Implement file fitting function. | Replace custom GRW dist with scipy gengamma. Implement file fitting function.
| Python | mit | jbernhard/ebe-analysis |
313aafc11f76888614e2a0523e9e858e71765eaa | tests/test_wc.py | tests/test_wc.py | # Copyright (C) 2005-2007 Jelmer Vernooij <jelmer@samba.org>
# This program 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.
# This p... | # Copyright (C) 2005-2007 Jelmer Vernooij <jelmer@samba.org>
# This program 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.
# This p... | Add some more tests for wc module. | Add some more tests for wc module. | Python | lgpl-2.1 | jelmer/subvertpy,jelmer/subvertpy |
e5f662d9cebe4133705eca74a300c325d432ad04 | anvil/components/cinder_client.py | anvil/components/cinder_client.py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright (C) 2012 Yahoo! 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.or... | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright (C) 2012 Yahoo! 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.or... | Remove destruction of pips/test requires entries that don't exist. | Remove destruction of pips/test requires entries that don't exist.
| Python | apache-2.0 | stackforge/anvil,stackforge/anvil,mc2014/anvil,mc2014/anvil |
87d1b24d8ee806c5aa6cf73d83472b129b0f87fe | mitty/simulation/genome/sampledgenome.py | mitty/simulation/genome/sampledgenome.py | import pysam
from numpy.random import choice
import math
def assign_random_gt(input_vcf, outname, sample_name="HG", default_af=0.01):
vcf_pointer = pysam.VariantFile(filename=input_vcf)
new_header = vcf_pointer.header.copy()
if "GT" not in new_header.formats:
new_header.formats.add("GT", "1", "Str... | import pysam
from numpy.random import choice
def assign_random_gt(input_vcf, outname, sample_name="HG", default_af=0.01):
vcf_pointer = pysam.VariantFile(filename=input_vcf)
new_header = vcf_pointer.header.copy()
if "GT" not in new_header.formats:
new_header.formats.add("GT", "1", "String", "Conse... | Add random GT to a given vcf | Add random GT to a given vcf
| Python | apache-2.0 | sbg/Mitty,sbg/Mitty |
1f8b54d22cee5653254514bf07c1b4cb1eb147cb | _grabconfig.py | _grabconfig.py | #!/usr/bin/env python2
import os, shutil
files = ["/etc/crontab",
"/usr/local/bin/ssu", "/usr/local/bin/xyzzy",
"/home/dagon/.bashrc","/home/dagon/.i3status.conf", "/home/dagon/.profile", "/home/dagon/.vimrc", "/home/dagon/.i3/config", "/home/dagon/.vim",
"/home/dagon/.config/bless", "/home/... | #!/usr/bin/env python2
import os, shutil
files = ["/etc/crontab",
"/usr/local/bin/ssu", "/usr/local/bin/xyzzy",
"/home/dagon/.bashrc","/home/dagon/.i3status.conf", "/home/dagon/.profile", "/home/dagon/.vimrc", "/home/dagon/.i3/config", "/home/dagon/.vim",
"/home/dagon/.config/bless", "/home/... | Remove test item from config grabbing script | Remove test item from config grabbing script
| Python | unlicense | weloxux/dotfiles,weloxux/dotfiles |
dd1bcf71c6548f99e6bc133bf890c87440e13535 | taskflow/states.py | taskflow/states.py | # -*- coding: utf-8 -*-
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright (C) 2012 Yahoo! 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
#
# ... | # -*- coding: utf-8 -*-
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright (C) 2012 Yahoo! 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
#
# ... | Add a running state which can be used to know when a workflow is running. | Add a running state which can be used to know when a workflow is running.
| Python | apache-2.0 | openstack/taskflow,jessicalucci/TaskManagement,jimbobhickville/taskflow,openstack/taskflow,citrix-openstack-build/taskflow,jimbobhickville/taskflow,junneyang/taskflow,varunarya10/taskflow,pombredanne/taskflow-1,jessicalucci/TaskManagement,citrix-openstack-build/taskflow,junneyang/taskflow,pombredanne/taskflow-1,varunar... |
cfeca089dd10a6853d2b969d2d248a0f7d506d1a | emission/net/usercache/formatters/android/motion_activity.py | emission/net/usercache/formatters/android/motion_activity.py | import logging
import emission.core.wrapper.motionactivity as ecwa
import emission.net.usercache.formatters.common as fc
import attrdict as ad
def format(entry):
formatted_entry = ad.AttrDict()
formatted_entry["_id"] = entry["_id"]
formatted_entry.user_id = entry.user_id
metadata = entry.metadata
... | import logging
import emission.core.wrapper.motionactivity as ecwa
import emission.net.usercache.formatters.common as fc
import attrdict as ad
def format(entry):
formatted_entry = ad.AttrDict()
formatted_entry["_id"] = entry["_id"]
formatted_entry.user_id = entry.user_id
metadata = entry.metadata
... | Handle the weird field names from the new version of the API | Handle the weird field names from the new version of the API
As part of the switch to cordova, we moved to a newer version of the google
play API. Unfortunately, this meant that the weird field names for the
confidence and type changed to a different set of weird field names. We should
really use a standard wrapper cl... | Python | bsd-3-clause | e-mission/e-mission-server,sunil07t/e-mission-server,shankari/e-mission-server,shankari/e-mission-server,yw374cornell/e-mission-server,e-mission/e-mission-server,joshzarrabi/e-mission-server,sunil07t/e-mission-server,e-mission/e-mission-server,joshzarrabi/e-mission-server,joshzarrabi/e-mission-server,yw374cornell/e-mis... |
5aa3dbf8f520f9ffaaed51ed397eb9f4c722882a | sample_app/__init__.py | sample_app/__init__.py | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under t... | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under t... | Fix pep8 order import issue | Fix pep8 order import issue
| Python | apache-2.0 | brantlk/python-sample-app |
b9d54da73e5c4d859aa5ad8e9d8b96bb7527ae6d | api/models.py | api/models.py | from django.db import models
# Create your models here.
class User(models.Model):
uid = models.AutoField(primary_key=True)
uname = models.CharField(max_length=128)
session = models.CharField(max_length=35,unique=True)
class Box(models.Model):
bid = models.AutoField(primary_key=True)
level = models... | from django.db import models
# Create your models here.
class User(models.Model):
uid = models.AutoField(primary_key=True)
uname = models.CharField(max_length=128)
session = models.CharField(max_length=35,unique=True)
class Box(models.Model):
bid = models.AutoField(primary_key=True)
level = models... | Add position table and add field mid in box tables | Add position table and add field mid in box tables
| Python | apache-2.0 | g82411/s_square |
c28de15fd8cade476fa8d7af904826dcea3c0f3e | python.py | python.py | # Python Notes
# Version 2.7
# for loop
for i in range(10):
print i
# check list elements of matching string
randList = ["a", "ab", "bc", "de", "abc"]
toFind = "a"
print [x for x in randList if toFind in x]
# read file
with open("filename.txt", "r") as fh:
data = fh.readline() # read line by line
# data ... | # Python Notes
# Version 2.7
# for loop
for i in range(10):
print i
# check list elements of matching string
randList = ["a", "ab", "bc", "de", "abc"]
toFind = "a"
print [x for x in randList if toFind in x]
# read file
with open("filename.txt", "r") as fh:
data = fh.readline() # read line by line
# data ... | Add Python note on simple unit test | Add Python note on simple unit test
| Python | cc0-1.0 | erictleung/programming-notes,erictleung/programming-notes,erictleung/programming-notes,erictleung/programming-notes,erictleung/programming-notes,erictleung/programming-notes,erictleung/programming-notes,erictleung/programming-notes,erictleung/programming-notes |
80cdc54dbe41c243c4620472aa8ba5c6ece40324 | etl_framework/DataTable.py | etl_framework/DataTable.py | class DataRow(dict):
"""object for holding row of data"""
def row_values(self, field_names, default_value=None):
"""returns row value of specified field_names"""
return tuple(self.get(field_name, default_value) for field_name in field_names)
class DataTable(object):
"""object for holding ... | class DataRow(dict):
"""object for holding row of data"""
def __init__(self, *args, **kwargs):
"""creates instance of DataRow"""
super(DataRow, self).__init__(*args, **kwargs)
self.target_table = None
def row_values(self, field_names, default_value=None):
"""returns row v... | Add target_table attribute to DataRow | Add target_table attribute to DataRow
| Python | mit | pantheon-systems/etl-framework |
cad48e91776ded810b23c336380797c88dd456c0 | services/netflix.py | services/netflix.py | import urlparse
import foauth.providers
from oauthlib.oauth1.rfc5849 import SIGNATURE_TYPE_QUERY
class Netflix(foauth.providers.OAuth1):
# General info about the provider
provider_url = 'https://www.netflix.com/'
docs_url = 'http://developer.netflix.com/docs'
# URLs to interact with the API
requ... | import urlparse
import foauth.providers
from oauthlib.oauth1.rfc5849 import SIGNATURE_TYPE_QUERY
class Netflix(foauth.providers.OAuth1):
# General info about the provider
provider_url = 'https://www.netflix.com/'
docs_url = 'http://developer.netflix.com/docs'
# URLs to interact with the API
requ... | Fix Netflix in light of the new scope selection system | Fix Netflix in light of the new scope selection system
| Python | bsd-3-clause | foauth/foauth.org,foauth/foauth.org,foauth/foauth.org |
b6f04f32556fc8251566212c56159dcfff7bf596 | pi_approach/Distance_Pi/distance.py | pi_approach/Distance_Pi/distance.py | # Lidar Project Distance Subsystem
import serial
import socket
import time
import sys
sys.path.insert(0, "/home/pi/lidar/pi_approach/Libraries")
import serverxclient as cli
arduino_dist = serial.Serial('/dev/ttyUSB0',9600)
client = cli.Client()
class distance_controller(object):
"""An all-powerful distance-finding ... | # Lidar Project Distance Subsystem
import serial
import socket
import time
import sys
sys.path.insert(0, "/home/pi/lidar/pi_approach/Libraries")
import serverxclient as cli
arduino_dist = serial.Serial('/dev/ttyUSB0',9600)
client = cli.Client()
class distance_controller(object):
"""An all-powerful distance-finding ... | Add unexpected character bug fix | Add unexpected character bug fix
| Python | mit | the-raspberry-pi-guy/lidar |
069e98f036c77f635a955ea2c48580709089e702 | src/conference_scheduler/resources.py | src/conference_scheduler/resources.py | from typing import NamedTuple, Sequence, Dict, Iterable, List
from datetime import datetime
class Slot(NamedTuple):
venue: str
starts_at: datetime
duration: int
capacity: int
session: str
class Event(NamedTuple):
name: str
duration: int
demand: int
tags: List[str] = []
unavai... | from typing import NamedTuple, Sequence, Dict, Iterable, List
from datetime import datetime
class Slot(NamedTuple):
venue: str
starts_at: datetime
duration: int
capacity: int
session: str
class BaseEvent(NamedTuple):
name: str
duration: int
demand: int
tags: List[str]
unavail... | Set default values for `tags` and `availability` | Set default values for `tags` and `availability`
| Python | mit | PyconUK/ConferenceScheduler |
1112f3602c147f469c21181c5c61d480b3f2ed75 | opps/api/views/generic/list.py | opps/api/views/generic/list.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.contrib.sites.models import get_current_site
from django.utils import timezone
from rest_framework.generics import ListAPIView as RestListAPIView
from opps.views.generic.base import View
from opps.containers.models import ContainerBox
class ListView(View, Re... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.contrib.sites.models import get_current_site
from django.utils import timezone
from rest_framework.generics import ListAPIView as RestListAPIView
from opps.views.generic.base import View
from opps.containers.models import ContainerBox
class ListView(View, Re... | Fix not exis channel_long_slug on API access | Fix not exis channel_long_slug on API access
| Python | mit | YACOWS/opps,williamroot/opps,YACOWS/opps,jeanmask/opps,jeanmask/opps,jeanmask/opps,opps/opps,opps/opps,opps/opps,williamroot/opps,williamroot/opps,YACOWS/opps,williamroot/opps,opps/opps,YACOWS/opps,jeanmask/opps |
6b8f66ed0bcaa62b3afd9fea7d749916d768847d | scripts/midnightRun.py | scripts/midnightRun.py | from recover.models import *
from recover.patient_data import *
from datetime import date
def midnightRun():
physicians = User.objects()
for physician in physicians:
patients = physician.patients
for patient in patients:
data = PatientData(patient)
last_synced = patient.... | from recover.models import *
from recover.patient_data import *
import datetime
def midnightRun():
physicians = User.objects()
for physician in physicians:
patients = physician.patients
for patient in patients:
data = PatientData(patient)
last_synced = patient.date_last... | Update 'date_last_synced' field on each patient after midnight fetching | Update 'date_last_synced' field on each patient after midnight fetching
| Python | mit | SLU-Capstone/Recover,SLU-Capstone/Recover,SLU-Capstone/Recover |
f5bb9e5f388c4ac222da2318638266fdfbe925f0 | beam/vendor.py | beam/vendor.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import six
@six.python_2_unicode_compatible
class Vendor(object):
"""
Represents a VPS provider.
"""
def __init__(self, name, endpoint):
"""
Initialise a new vendor object.
:param name: The name of the vendor, e... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import six
@six.python_2_unicode_compatible
class Vendor(object):
"""
Represents a VPS provider.
"""
def __init__(self, name, endpoint):
"""
Initialise a new vendor object.
:param name: The name of the vendor, e... | Add documentation to Vendor properties | Add documentation to Vendor properties
| Python | mit | gebn/beam,gebn/beam |
c4b8cce856777b08a8ffd5a85567389102aea2c2 | qregexeditor/api/quick_ref.py | qregexeditor/api/quick_ref.py | """
Contains the quick reference widget
"""
from pyqode.qt import QtWidgets
from .forms import quick_ref_ui
class QuickRefWidget(QtWidgets.QWidget):
def __init__(self, parent=None):
super(QuickRefWidget, self).__init__(parent)
self.ui = quick_ref_ui.Ui_Form()
self.ui.setupUi(self)
| """
Contains the quick reference widget
"""
import re
from pyqode.qt import QtWidgets
from .forms import quick_ref_ui
class QuickRefWidget(QtWidgets.QWidget):
def __init__(self, parent=None):
super(QuickRefWidget, self).__init__(parent)
self.ui = quick_ref_ui.Ui_Form()
self.ui.setupUi(self)... | Allow the user to zoom in/out the quick reference text using Ctrl+Mouse Wheel | Allow the user to zoom in/out the quick reference text using Ctrl+Mouse Wheel
See issue #1
| Python | mit | ColinDuquesnoy/QRegexEditor |
d16988174f5570334b6b3986dbd0b35148566a62 | opps/flatpages/models.py | opps/flatpages/models.py | # -*- coding: utf-8 -*-
from django.db import models
from django.utils.translation import ugettext_lazy as _
from googl.short import GooglUrlShort
from opps.core.models import Publishable, BaseConfig
class FlatPage(Publishable):
title = models.CharField(_(u"Title"), max_length=140, db_index=True)
headline =... | # -*- coding: utf-8 -*-
from django.db import models
from django.utils.translation import ugettext_lazy as _
from googl.short import GooglUrlShort
from opps.core.models import Publishable, BaseConfig
class FlatPage(Publishable):
title = models.CharField(_(u"Title"), max_length=140, db_index=True)
headline =... | Add field short_url on flatpages model | Add field short_url on flatpages model
| Python | mit | opps/opps,jeanmask/opps,YACOWS/opps,YACOWS/opps,williamroot/opps,williamroot/opps,opps/opps,williamroot/opps,jeanmask/opps,jeanmask/opps,williamroot/opps,opps/opps,jeanmask/opps,YACOWS/opps,YACOWS/opps,opps/opps |
00bb631437fdf45c7a067da43aa042f8b1f6ef8e | osf_models/models/tag.py | osf_models/models/tag.py | from django.db import models
from .base import BaseModel
class Tag(BaseModel):
_id = models.CharField(max_length=1024)
lower = models.CharField(max_length=1024)
system = models.BooleanField(default=False)
| from django.db import models
from .base import BaseModel
class Tag(BaseModel):
_id = models.CharField(max_length=1024)
lower = models.CharField(max_length=1024)
system = models.BooleanField(default=False)
class Meta:
unique_together = ('_id', 'system')
| Add unique together on _id and system | Add unique together on _id and system
| Python | apache-2.0 | Nesiehr/osf.io,adlius/osf.io,erinspace/osf.io,CenterForOpenScience/osf.io,felliott/osf.io,crcresearch/osf.io,caneruguz/osf.io,caseyrollins/osf.io,laurenrevere/osf.io,Nesiehr/osf.io,baylee-d/osf.io,leb2dg/osf.io,acshi/osf.io,monikagrabowska/osf.io,monikagrabowska/osf.io,cslzchen/osf.io,chrisseto/osf.io,chennan47/osf.io,... |
e203f76177de390fb02a2770499679c099c4f87c | cacheops/__init__.py | cacheops/__init__.py | VERSION = (3, 0, 1)
__version__ = '.'.join(map(str, VERSION if VERSION[-1] else VERSION[:2]))
from django.apps import AppConfig
from .simple import *
from .query import *
from .invalidation import *
from .templatetags.cacheops import *
from .transaction import install_cacheops_transaction_support
from .utils import ... | VERSION = (3, 0, 1)
__version__ = '.'.join(map(str, VERSION if VERSION[-1] else VERSION[:2]))
from django.apps import AppConfig
from .simple import *
from .query import *
from .invalidation import *
from .templatetags.cacheops import *
from .transaction import install_cacheops_transaction_support
class CacheopsCon... | Remove debug_cache_key from entry point | Remove debug_cache_key from entry point
| Python | bsd-3-clause | Suor/django-cacheops,LPgenerator/django-cacheops |
c2d681f0df11d2111fe1ade63a0c045f9c9ebad7 | aws_profile.py | aws_profile.py | #!/usr/bin/env python
# Reads a profile from ~/.aws/config and calls the command with
# AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY set correctly.
import ConfigParser
import os
import subprocess
import sys
c = ConfigParser.SafeConfigParser()
c.read(os.path.expanduser('~/.aws/config'))
section = sys.argv[1]
cmd = sys.... | #!/usr/bin/env python
# Reads a profile from ~/.aws/config and calls the command with
# AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY set correctly.
import ConfigParser
import os
import subprocess
import sys
c = ConfigParser.SafeConfigParser()
c.read(os.path.expanduser('~/.aws/credentials'))
section = sys.argv[1]
cmd =... | Fix profile script to correctly use the credentials file | Fix profile script to correctly use the credentials file
| Python | mit | mivok/tools,mivok/tools,mivok/tools,mivok/tools |
fb21faaec025a0a6ca2d98c8b2381902f3b1444a | pybug/align/lucaskanade/__init__.py | pybug/align/lucaskanade/__init__.py | import appearance
import image
from residual import (LSIntensity,
ECC,
GradientImages,
GradientCorrelation)
| import appearance
import image
from residual import (LSIntensity,
ECC,
GaborFourier,
GradientImages,
GradientCorrelation)
| Add GaborFourier to default import | Add GaborFourier to default import
| Python | bsd-3-clause | menpo/menpo,yuxiang-zhou/menpo,grigorisg9gr/menpo,mozata/menpo,mozata/menpo,mozata/menpo,mozata/menpo,grigorisg9gr/menpo,menpo/menpo,menpo/menpo,jabooth/menpo-archive,jabooth/menpo-archive,jabooth/menpo-archive,yuxiang-zhou/menpo,grigorisg9gr/menpo,patricksnape/menpo,yuxiang-zhou/menpo,jabooth/menpo-archive,patricksnap... |
e275fb1406f0a8e70bb3a9d4a50a82400f7e2c29 | signac/gui/__init__.py | signac/gui/__init__.py | """Graphical User Interface (GUI) for configuration and database inspection.
The GUI is a leight-weight interface which makes the configuration
of the signac framework and data inspection more straight-forward."""
import warnings
try:
import PySide # noqa
except ImportError:
warnings.warn("Failed to import Py... | """Graphical User Interface (GUI) for configuration and database inspection.
The GUI is a leight-weight interface which makes the configuration
of the signac framework and data inspection more straight-forward."""
import warnings
try:
import PySide # noqa
import pymongo # noqa
except ImportError as error:
... | Remove hard dependency for pymongo. | Remove hard dependency for pymongo.
Caused by pulling the gui package into the signac namespace.
Fixes issue #24.
| Python | bsd-3-clause | csadorf/signac,csadorf/signac |
4da5ebbad11a5c5cdbea307668657d843d6d1005 | cotracker/checkouts/middleware.py | cotracker/checkouts/middleware.py | """Checkouts application middleware"""
import logging
logger = logging.getLogger('analytics')
class Analytics():
"""Tracks request details useful for analysis of usage patterns.
To ensure that the name of the logged in user can be accessed, this
middleware should come after Django's built-in Authent... | """Checkouts application middleware"""
import logging
import time
logger = logging.getLogger('analytics')
class Analytics():
"""Tracks request details useful for analysis of usage patterns.
To ensure that the name of the logged in user can be accessed, this
middleware should come after Django's buil... | Enhance analytics with timing and status code info | Enhance analytics with timing and status code info
| Python | mit | eallrich/checkniner,eallrich/checkniner,eallrich/checkniner |
f566e0e36269ea2cd1e82c6af712097917effd4a | dlrn/migrations/versions/2d503b5034b7_rename_artifacts.py | dlrn/migrations/versions/2d503b5034b7_rename_artifacts.py | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under t... | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under t... | Fix alembic migration for rpms->artifacts rename | Fix alembic migration for rpms->artifacts rename
The migration does not work on MySQL-based engines, because it
requires setting the existing_type parameter [1]. It worked fine
on SQLite, though.
[1] - https://alembic.sqlalchemy.org/en/latest/ops.html#alembic.operations.Operations.alter_column
Change-Id: If0cc05af84... | Python | apache-2.0 | openstack-packages/delorean,openstack-packages/delorean,openstack-packages/DLRN,openstack-packages/DLRN |
141e8303fe8f1d6fe554770d7480ef50797d4735 | books/forms.py | books/forms.py | from django import forms
from django.forms import ModelForm
from django.utils.translation import ugettext_lazy as _
from books.models import BookType
from egielda import settings
class BookForm(ModelForm):
# Different max_length than in model (to allow dividers in ISBN number)
isbn = forms.CharField(max_leng... | from django import forms
from django.forms import ModelForm
from django.utils.translation import ugettext_lazy as _
from books.models import BookType
from egielda import settings
class BookForm(ModelForm):
# Different max_length than in model (to allow dashes in ISBN)
isbn = forms.CharField(max_length=20, la... | Improve ISBN field in Book Type form | Improve ISBN field in Book Type form
- Add required, pattern (to allow only numbers and dashes in HTML5-supporting browsers) and title properties
- Remove a bit of redundant code
| Python | agpl-3.0 | m4tx/egielda,m4tx/egielda,m4tx/egielda |
779c01d3932c02f2b9c45e300c7efb54f81749e9 | tests/rietveld/test_event_handler.py | tests/rietveld/test_event_handler.py | from __future__ import absolute_import, print_function
import unittest
from qtpy.QtWidgets import QApplication
from addie.rietveld import event_handler
class RietveldEventHandlerTests(unittest.TestCase):
def setUp(self):
self.main_window = QApplication([])
'''
def tearDown(self):
self.mai... | from __future__ import absolute_import, print_function
import unittest
from qtpy.QtWidgets import QApplication
from addie.rietveld import event_handler
class RietveldEventHandlerTests(unittest.TestCase):
def setUp(self):
self.main_window = QApplication([])
'''
def tearDown(self):
self.mai... | Add exception to test title | Add exception to test title
| Python | mit | neutrons/FastGR,neutrons/FastGR,neutrons/FastGR |
8afb48e23b91efa3432ffad568002a46384eb021 | fantasyland.py | fantasyland.py | import numpy as np
import random
import game as g
import hand_optimizer
game = g.PineappleGame1()
NUM_ITERS = 1000
utilities = []
for iter_num in xrange(NUM_ITERS):
print "{:5} / {:5}".format(iter_num, NUM_ITERS), '\r',
draw = random.sample(game.cards, 14)
utilities += [hand_optimizer.optimize_hand([[], [], [... | import argparse
import numpy as np
import random
import game as g
import hand_optimizer
parser = argparse.ArgumentParser(description='Simulate fantasyland like situations.')
parser.add_argument('--num-games', type=int, default=1000,
help='number of games to play')
parser.add_argument('--num-cards'... | Add command line interface to vary num-games and num-cards. | Add command line interface to vary num-games and num-cards.
| Python | mit | session-id/pineapple-ai |
5f67934da00ff36044e9fd620b690e36968570c0 | salt/output/overstatestage.py | salt/output/overstatestage.py | '''
Display clean output of an overstate stage
'''
#[{'group2': {'match': ['fedora17-2', 'fedora17-3'],
# 'require': ['group1'],
# 'sls': ['nginx', 'edit']}
# }
# ]
# Import Salt libs
import salt.utils
def output(data):
'''
Format the data for printing stage ... | '''
Display clean output of an overstate stage
'''
#[{'group2': {'match': ['fedora17-2', 'fedora17-3'],
# 'require': ['group1'],
# 'sls': ['nginx', 'edit']}
# }
# ]
# Import Salt libs
import salt.utils
def output(data):
'''
Format the data for printing stage ... | Make stage outputter a little cleaner | Make stage outputter a little cleaner
| Python | apache-2.0 | saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt |
4b8de0203d2eec87c2d05c3521df8af3365f73a4 | IPython/testing/nose_assert_methods.py | IPython/testing/nose_assert_methods.py | """Add some assert methods to nose.tools. These were added in Python 2.7/3.1, so
once we stop testing on Python 2.6, this file can be removed.
"""
import nose.tools as nt
def assert_in(item, collection):
assert item in collection, '%r not in %r' % (item, collection)
if not hasattr(nt, 'assert_in'):
nt.assert... | """Add some assert methods to nose.tools. These were added in Python 2.7/3.1, so
once we stop testing on Python 2.6, this file can be removed.
"""
import nose.tools as nt
def assert_in(item, collection):
assert item in collection, '%r not in %r' % (item, collection)
if not hasattr(nt, 'assert_in'):
nt.assert... | Add assert_not_in method for Python2.6 | Add assert_not_in method for Python2.6
| Python | bsd-3-clause | ipython/ipython,ipython/ipython |
6ad4a0d511f874ccb94a6c8b02f0d4f5e99947ee | bigbuild/management/commands/cachepages.py | bigbuild/management/commands/cachepages.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import json
from datetime import datetime
from bigbuild.models import PageList
from bigbuild import get_archive_directory
from django.core.management.base import BaseCommand
def serializer(obj):
"""
JSON serializer for objects not serializable by default... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import io
import os
import json
from datetime import datetime
from bigbuild.models import PageList
from bigbuild import get_archive_directory
from django.core.management.base import BaseCommand
def serializer(obj):
"""
JSON serializer for objects not serializable ... | Write out page cache as unicode utf8 | Write out page cache as unicode utf8
| Python | mit | datadesk/django-bigbuild,datadesk/django-bigbuild,datadesk/django-bigbuild |
751819ea58389eaa1baf3de243459be4948b15f1 | rpc_client/rpc_client_tests.py | rpc_client/rpc_client_tests.py | import unittest
class Test(unittest.TestCase):
def setUp(self):
self.seq = range(10)
#def test_shuffle(self):
# # make sure the shuffled sequence does not lose any elements
# random.shuffle(self.seq)
# self.seq.sort()
# self.assertEqual(self.seq, range(10))
#def test_... | import unittest, xmlrpclib, couchdb
from ConfigParser import SafeConfigParser
class Test(unittest.TestCase):
def setUp(self):
self.cfg = SafeConfigParser()
self.cfg.read(('rpc_client.ini', '../stats/basicStats.ini'))
host = self.cfg.get('connection', 'server')
port = self.cfg.getin... | Make some simple unit test for RPC server. | Make some simple unit test for RPC server.
| Python | apache-2.0 | anthony-kolesov/kts46,anthony-kolesov/kts46,anthony-kolesov/kts46,anthony-kolesov/kts46 |
377d0634a77c63ce9e3d937f31bdd82ebe695cbb | ev3dev/auto.py | ev3dev/auto.py | import platform
# -----------------------------------------------------------------------------
# Guess platform we are running on
def current_platform():
machine = platform.machine()
if machine == 'armv5tejl':
return 'ev3'
elif machine == 'armv6l':
return 'brickpi'
else:
return... | import platform
import sys
# -----------------------------------------------------------------------------
if sys.version_info < (3,4):
raise SystemError('Must be using Python 3.4 or higher')
# -----------------------------------------------------------------------------
# Guess platform we are running on
def c... | Enforce the use of Python 3.4 or higher | Enforce the use of Python 3.4 or higher
| Python | mit | rhempel/ev3dev-lang-python,dwalton76/ev3dev-lang-python,dwalton76/ev3dev-lang-python |
9856361b48bb481f7913eaf69be668225c5bb818 | api/files/urls.py | api/files/urls.py | from django.conf.urls import url
from api.files import views
urlpatterns = [
url(r'^$', views.FileList.as_view(), name='file-list'),
url(r'^(?P<file_id>\w+)/$', views.FileDetail.as_view(), name='file-detail'),
url(r'^(?P<file_id>\w+)/versions/$', views.FileVersionsList.as_view(), name='file-versions'),
... | from django.conf.urls import url
from api.files import views
urlpatterns = [
url(r'^(?P<file_id>\w+)/$', views.FileDetail.as_view(), name='file-detail'),
url(r'^(?P<file_id>\w+)/versions/$', views.FileVersionsList.as_view(), name='file-versions'),
url(r'^(?P<file_id>\w+)/versions/(?P<version_id>\w+)/$', v... | Remove the files list endpoint | Remove the files list endpoint
| Python | apache-2.0 | acshi/osf.io,aaxelb/osf.io,cslzchen/osf.io,felliott/osf.io,brandonPurvis/osf.io,wearpants/osf.io,Ghalko/osf.io,CenterForOpenScience/osf.io,cwisecarver/osf.io,abought/osf.io,TomBaxter/osf.io,SSJohns/osf.io,amyshi188/osf.io,GageGaskins/osf.io,laurenrevere/osf.io,erinspace/osf.io,DanielSBrown/osf.io,asanfilippo7/osf.io,co... |
648b128542f737da37dc696a02bd71ace6dbb28c | tests/test_deps.py | tests/test_deps.py | import os
import subprocess
import sys
import pytest
def test_adding_deps(tmpdir):
with pytest.raises(ImportError):
import sentinels
projdir = tmpdir.join('proj')
yaml = projdir.join('.cob-project.yml')
python = str(projdir.join('.cob/env/bin/python'))
with yaml.open('a', ensure=True) ... | import os
import subprocess
import sys
import pytest
def test_adding_deps(tmpdir):
with pytest.raises(ImportError):
import pact
projdir = tmpdir.join('proj')
yaml = projdir.join('.cob-project.yml')
python = str(projdir.join('.cob/env/bin/python'))
with yaml.open('a', ensure=True) as f:... | Change import name in deps test | Change import name in deps test
| Python | bsd-3-clause | getweber/weber-cli |
48f643b99c93fc10c042fe10e4a06c64df245d0d | lobster/cmssw/actions.py | lobster/cmssw/actions.py | import datetime
import multiprocessing
from lobster.cmssw.plotting import Plotter
logger = multiprocessing.get_logger()
class DummyPlotter(object):
def make_plots(*args, **kwargs):
pass
class Actions(object):
def __init__(self, config):
if 'plotdir' in config:
logger.info('plots ... | import datetime
import multiprocessing
from lobster.cmssw.plotting import Plotter
logger = multiprocessing.get_logger()
class DummyPlotter(object):
def make_plots(*args, **kwargs):
pass
class Actions(object):
def __init__(self, config):
if 'plotdir' in config:
logger.info('plots ... | Allow users to add foremen plots for daemonized plotting. | Allow users to add foremen plots for daemonized plotting.
| Python | mit | matz-e/lobster,matz-e/lobster,matz-e/lobster |
2f2f6cba331515b8d563d0e2f7869111df4227c3 | txlege84/core/management/commands/updateconveningtimes.py | txlege84/core/management/commands/updateconveningtimes.py | from django.core.management.base import BaseCommand
from core.models import ConveneTime
from legislators.models import Chamber
import requests
class Command(BaseCommand):
help = u'Scrape TLO for convening times.'
def handle(self, *args, **kwargs):
self.update_time('House')
self.update_time(... | from django.core.management.base import BaseCommand
from django.utils import timezone
from core.models import ConveneTime
from legislators.models import Chamber
from dateutil.parser import parse
import requests
class Command(BaseCommand):
help = u'Scrape TLO for convening times.'
def handle(self, *args, **... | Update scraper to account for new fields | Update scraper to account for new fields
| Python | mit | texastribune/txlege84,texastribune/txlege84,texastribune/txlege84,texastribune/txlege84 |
205616b0a23143cdc5ceb6fb8333cf6074ce737b | kitchen/pycompat25/collections/__init__.py | kitchen/pycompat25/collections/__init__.py | try:
from collections import defaultdict
except ImportError:
from _defaultdict import defaultdict
__all__ = ('defaultdict',)
| try:
#:E0611: deafultdict doesn't exist in python-2.4 or less but that's why we
# have it in a try: except:. So we can use our version if necessary.
from collections import defaultdict
except ImportError:
from kitchen.pycompat25.collections._defaultdict import defaultdict
__all__ = ('defaultdict',)
| Fix pylint error in this module | Fix pylint error in this module
| Python | lgpl-2.1 | fedora-infra/kitchen,fedora-infra/kitchen |
b0ae4cb386411ae8ae5fd27b19ddb415d0772cf3 | democracy_club/apps/everyelection/forms.py | democracy_club/apps/everyelection/forms.py | from django.forms import (ModelForm, CheckboxSelectMultiple,
MultipleChoiceField)
from .models import AuthorityElection, AuthorityElectionPosition
class AuthorityAreaForm(ModelForm):
def __init__(self, user, *args, **kwargs):
super().__init__(*args, **kwargs)
self.user =... | from django.forms import (ModelForm, CheckboxSelectMultiple,
MultipleChoiceField)
from .models import AuthorityElection, AuthorityElectionPosition
class AuthorityAreaForm(ModelForm):
def __init__(self, user, *args, **kwargs):
super().__init__(*args, **kwargs)
self.user =... | Check that at least one area has been checked | Check that at least one area has been checked
| Python | bsd-3-clause | DemocracyClub/Website,DemocracyClub/Website,DemocracyClub/Website,DemocracyClub/Website |
1e5d68e8cbd592f1bd7535c74948f2bf5f95b4f1 | mqtt_logger/tests.py | mqtt_logger/tests.py | from django.test import TestCase
# Create your tests here.
| from django.test import TestCase
from models import *
class SubscriptionTests(TestCase):
@classmethod
def setUpTestData(cls):
sub = MQTTSubscription(server='localhost', topic='#')
sub.save()
cls.sub = sub
def test_callback_function(self):
sub = type(self).sub
# C... | Add test of callback function. | Add test of callback function.
| Python | mit | ast0815/mqtt-hub,ast0815/mqtt-hub |
e7e0b8b723382e7a187e02c6a3052dacefc84bbe | faaopendata/faa_data_cleaner.py | faaopendata/faa_data_cleaner.py | ## A quick script to fix the ridiculous format of the raw FAA download data (at least it's available though!)
import csv
# MASTER.txt is from https://www.faa.gov/licenses_certificates/aircraft_certification/aircraft_registry/releasable_aircraft_download/
with open("MASTER.txt") as orig_file:
orig_file_reader = cs... | ## A quick script to fix the ridiculous format of the raw FAA download data (at least it's available though!)
import csv
# MASTER.txt is from https://www.faa.gov/licenses_certificates/aircraft_certification/aircraft_registry/releasable_aircraft_download/
with open("MASTER.txt") as orig_file:
orig_file_reader = cs... | Add comments to explain what the script is doing on ingest | Add comments to explain what the script is doing on ingest
| Python | apache-2.0 | GISDev01/adsbpostgis |
6d888061089648f2363f77f48fb7458a7ff16735 | pyportify/serializers.py | pyportify/serializers.py | class Track():
artist = ""
name = ""
track_id = ""
def __init__(self, artist, name, track_id=""):
self.artist = artist
self.name = name
self.track_id = track_id
@staticmethod
def from_spotify(self, track):
track_id = track.get("id")
name = track.get("nam... | class Track():
artist = ""
name = ""
track_id = ""
def __init__(self, artist, name, track_id=""):
self.artist = artist
self.name = name
self.track_id = track_id
@classmethod
def from_spotify(cls, track):
track_id = track.get("id")
name = track.get("name"... | Change from_spotify and from_gpm to classmethods | Change from_spotify and from_gpm to classmethods
| Python | apache-2.0 | rckclmbr/pyportify,rckclmbr/pyportify,rckclmbr/pyportify,rckclmbr/pyportify |
1071e663eb38a3981cea047c1b2e24d6e119f94d | db/api/serializers.py | db/api/serializers.py | from rest_framework import serializers
from db.base.models import Satellite, Transponder
class SatelliteSerializer(serializers.ModelSerializer):
class Meta:
model = Satellite
class TransponderSerializer(serializers.ModelSerializer):
norad = serializers.SerializerMethodField()
class Meta:
... | from rest_framework import serializers
from db.base.models import Satellite, Transponder
class SatelliteSerializer(serializers.ModelSerializer):
class Meta:
model = Satellite
class TransponderSerializer(serializers.ModelSerializer):
norad_cat_id = serializers.SerializerMethodField()
class Meta... | Change norad API field to proper name | Change norad API field to proper name
| Python | agpl-3.0 | Roboneet/satnogs-db,Roboneet/satnogs-db,Roboneet/satnogs-db,Roboneet/satnogs-db |
900f5fab722d32762b8a5fa214838f84b3fc376c | speech_recognition/__main__.py | speech_recognition/__main__.py | import speech_recognition as sr
r = sr.Recognizer()
m = sr.Microphone()
print("A moment of silence, please...")
with m as source:
r.adjust_for_ambient_noise(source)
print("Set minimum energy threshold to {}".format(r.energy_threshold))
while True:
print("Say something!")
audio = r.listen(s... | import speech_recognition as sr
r = sr.Recognizer()
m = sr.Microphone()
try:
print("A moment of silence, please...")
with m as source:
r.adjust_for_ambient_noise(source)
print("Set minimum energy threshold to {}".format(r.energy_threshold))
while True:
print("Say something!... | Handle Ctrl + C when running demo in the terminal. | Handle Ctrl + C when running demo in the terminal.
| Python | bsd-3-clause | adrianzhang/speech_recognition,Python-Devs-Brasil/speech_recognition,Uberi/speech_recognition,Python-Devs-Brasil/speech_recognition,Zenohm/speech_recognition,jjsg/speech_recognition,Uberi/speech_recognition,adrianzhang/speech_recognition,Zenohm/speech_recognition,jjsg/speech_recognition,arvindch/speech_recognition,arvi... |
61427695c0abb3c9385610a13c78cb21eec388d3 | moa/factory_registers.py | moa/factory_registers.py | from kivy.factory import Factory
r = Factory.register
r('StageTreeNode', module='moa.render.treerender')
r('StageSimpleDisplay', module='moa.render.stage_simple')
# --------------------- devices -----------------------------
r('Device', module='moa.device')
r('DigitalChannel', module='moa.device.digital')
r('Digita... | from kivy.factory import Factory
r = Factory.register
r('StageTreeNode', module='moa.render.treerender')
r('StageSimpleDisplay', module='moa.render.stage_simple')
# --------------------- devices -----------------------------
r('Device', module='moa.device')
r('DigitalChannel', module='moa.device.digital')
r('Digita... | Update factory registers with new classes. | Update factory registers with new classes.
| Python | mit | matham/moa |
073d4d65edc93247c24f179ee93d061a0024057a | web/migrations/0001_initial.py | web/migrations/0001_initial.py | # Generated by Django 3.2.6 on 2021-08-23 18:33
# pylint:disable=line-too-long
# pylint:disable=missing-module-docstring
# pylint:disable=
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = ... | # Generated by Django 3.2.6 on 2021-08-23 18:33
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='SiteVisit',
fields=[
... | Remove pylint disables (for now) | Remove pylint disables (for now)
| Python | agpl-3.0 | codethesaurus/codethesaur.us,codethesaurus/codethesaur.us |
71f00a03d6cbe4dc4d3cd2362ef91bd192a9a31e | who_broke_build.py | who_broke_build.py | import json
import re
import requests
import socket
import settings
def get_responsible_user(full_url):
members = settings.TEAM_MEMBERS
response = requests.get(
full_url,
auth=(
settings.JENKINS_USERNAME,
settings.JENKINS_PASSWORD
)
)
for each in membe... | import json
import re
import requests
import socket
import settings
def get_responsible_user(full_url):
members = settings.TEAM_MEMBERS
response = requests.get(
full_url,
auth=(
settings.JENKINS_USERNAME,
settings.JENKINS_PASSWORD
)
)
for each in membe... | Add point to execute program | Add point to execute program
| Python | mit | mrteera/who-broke-build-slack,mrteera/who-broke-build-slack,zkan/who-broke-build-slack,prontodev/who-broke-build-slack,prontodev/who-broke-build-slack,zkan/who-broke-build-slack |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.