code stringlengths 2 1.05M | repo_name stringlengths 5 104 | path stringlengths 4 251 | language stringclasses 1
value | license stringclasses 15
values | size int32 2 1.05M |
|---|---|---|---|---|---|
import asyncio
import logging
from typing import Optional
import aioreactive as rx
import pytest
from aioreactive.notification import OnCompleted, OnError, OnNext
from aioreactive.testing import AsyncTestSubject, AsyncTestObserver, VirtualTimeEventLoop
from expression.core import pipe
from expression.system.disposable... | dbrattli/aioreactive | test/test_stream.py | Python | mit | 4,126 |
"""Base extension class for writing new extensions."""
from grow.common import features
class Error(Exception):
"""Base error."""
pass
class MissingHookError(Error):
"""Missing hook error."""
pass
class BaseExtension(object):
"""Base extension for custom extensions."""
def __init__(self,... | grow/pygrow | grow/extensions/base_extension.py | Python | mit | 1,421 |
#!/usr/local/bin/python
from math import *
def linreg(p):
""" Returns coefficients to the regression line "y=ax+b" """
""" Args: list of point pairs [(x1, y2), (x2, y2), ...]"""
from math import sqrt
N = len(p)
Sx = Sy = Sxx = Syy = Sxy = 0.0
for (x, y) in p:
Sx = Sx + x
Sy =... | leonard-lab/MADTraC | MT/MT_Tracking/3rdparty/libhungarian-0.3/linreg.py | Python | mit | 1,269 |
from random import randint
h, t = 0, 0
N, M = 4, 1000
for i in range(M):
flip0 = randint(0, 1)
for j in range(N-1):
flip1 = randint(0, 1)
if flip0:
h += flip1
t += not flip1
flip0 = flip1
print h / float(h + t)
| hobson/hobson.github.io | _posts/gambler_falacy.py | Python | mit | 268 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# photon-pump documentation build configuration file, created by
# sphinx-quickstart on Fri Apr 28 23:45:35 2017.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
... | madedotcom/photon-pump | docs/conf.py | Python | mit | 4,958 |
from django.apps import AppConfig as OAppConfig
from proso.django.enrichment import register_object_type_enricher
class AppConfig(OAppConfig):
name = 'proso_user'
def ready(self):
register_object_type_enricher(['user_question'], 'proso_user.json_enrich.user_answers')
| adaptive-learning/proso-apps | proso_user/apps.py | Python | mit | 288 |
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class API_UserInfo(models.Model):
#id = models.AutoField()
username = models.CharField(max_length=50)
password = models.CharField(max_length=200)
create_time = models.DateTimeField(auto_now_add=True)
... | mszhai/Django | blog/models.py | Python | mit | 6,739 |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from multiprocessing import Process, Pipe
import numpy as np
import logging
import gym
from environment import environment
logger = logging.getLogger('StRADRL.mujoco_env')
COMMAND_RES... | TheTazza/StRADRL | environment/mujoco_environment.py | Python | mit | 3,579 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import mock
import unittest2
from github_reviewboard_sync.reviewboard import _create_args
class TestCreateArgs(unittest2.TestCase):
@mock.patch('github_reviewboard... | Apptimize-OSS/github-reviewboard-sync | tests/unit_tests/test_reviewboard.py | Python | mit | 1,548 |
# !/usr/bin/env python3
# -*- encoding: utf-8 -*-
"""
ERP+
"""
__author__ = 'António Anacleto'
__credits__ = []
__version__ = "1.0"
__maintainer__ = "António Anacleto"
__status__ = "Development"
__model_name__ = 'rendimento_funcionario.RendimentoFuncionario'
import auth, base_models
from orm import *
from form import *... | IdeaSolutionsOnline/ERP4R | core/objs/rendimento_funcionario.py | Python | mit | 1,777 |
from .models import TodoTask
from rest_framework import viewsets
from .serializers import TodoSerializer
class TodoViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows todo list to be managed
"""
queryset = TodoTask.objects.all()
serializer_class = TodoSerializer
pagination_class = None... | elarasu/todoserver | service/apps/todo/views.py | Python | mit | 435 |
from deployer.celery import app
@app.task
def backend_cleanup():
app.tasks['celery.backend_cleanup']()
| totem/cluster-deployer | deployer/tasks/__init__.py | Python | mit | 109 |
from math import sin, cos
try:
supershape = ximport("supershape")
except:
supershape = ximport("__init__")
reload(supershape)
speed(100)
size(400, 400)
def setup():
global x, y, w, h, m, n1, n2, n3, i
x, y = 200, 200
w, h = 100, 100
m = 6.0
n1 = 1.0
n2 = 1.0
n3 = 1.0
... | ArtezGDA/Algorithmic-Nature | Luc/sketches & libs/supershape/supershape-example1.py | Python | mit | 579 |
"""
# pp.py
# classes to scrape and parse plyr proflr dot com
"""
import logging
from namematcher.xref import Site
from sportscraper.scraper import RequestScraper
class Scraper(RequestScraper):
"""
For use by subscribers
"""
@property
def base_url(self):
return "https://www.playerpro... | sansbacon/nfl | nfl/pp.py | Python | mit | 19,126 |
from django.contrib import messages
from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect
from django.template import RequestContext
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext_lazy as _
from django.template.defaultfilters import slug... | rawjam/django-allauth | allauth/socialaccount/helpers.py | Python | mit | 7,556 |
#!/usr/bin/env python3
# testBigTest.py
import time
import unittest
from io import StringIO
from rnglib import SimpleRNG
# from fieldz import reg
from fieldz.parser import StringProtoSpecParser
from big_test import BIG_TEST
class TestBigTest(unittest.TestCase):
def setUp(self):
self.rng = SimpleRNG(ti... | jddixon/fieldz | tests/test_roundtrip_big_test.py | Python | mit | 2,949 |
import base64
import io
import os
from collections import defaultdict
from itertools import groupby
from typing import TextIO, Iterable, Iterator, Any, Optional, List, Union
from .ldapentry import LDAPEntry, LDAPModOp
from .ldapvaluelist import LDAPValueList
from .errors import LDAPError
class LDIFError(LDAPError):... | Noirello/PyLDAP | src/bonsai/ldif.py | Python | mit | 12,800 |
from ..osid import sessions as osid_sessions
class AssessmentPartLookupSession(osid_sessions.OsidSession):
"""This session defines methods for retrieving assessment parts."""
def get_bank_id(self):
"""Gets the ``Bank`` ``Id`` associated with this session.
:return: the ``Bank Id`` associate... | birdland/dlkit-doc | dlkit/assessment_authoring/sessions.py | Python | mit | 64,091 |
from flask import Flask, render_template, request, make_response, jsonify
import sqlite3
import datetime
import io
import os
import database
import excel
import getchartdata
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html',
title='Solstice')
@app... | aguinane/Solstice | webserver.py | Python | mit | 5,348 |
from ...testcases import DustyIntegrationTestCase
from ...fixtures import busybox_single_app_bundle_fixture
class TestLogsCLI(DustyIntegrationTestCase):
def setUp(self):
super(TestLogsCLI, self).setUp()
busybox_single_app_bundle_fixture(num_bundles=1)
self.run_command('bundles activate busy... | gamechanger/dusty | tests/integration/cli/logs_test.py | Python | mit | 1,360 |
import time
import tweepy
import consumer
import access_token
import sqlite3
import sys
DETROIT_WOEID = "2391585"
FIVE_MINUTES_IN_SECONDS = 5 * 60
db_name = time.strftime("../db/%Y-%m-%d-%H-%M-%S.db")
con = sqlite3.connect(db_name)
con.execute(
'''
CREATE TABLE trend_results(
inserted,
content... | maroy/TSTA | cse-581-project-2/src/main.py | Python | mit | 2,463 |
#
# Copyright 2015 by Justin MacCallum, Alberto Perez, Ken Dill
# All rights reserved
#
import contextlib
import os
import time
import cPickle as pickle
import netCDF4 as cdf
import numpy as np
import shutil
from meld.system import state
class DataStore(object):
"""
Class to handle storing data from MELD run... | laufercenter/meld | meld/vault.py | Python | mit | 20,783 |
from bs4 import BeautifulSoup
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as ec
from selenium.common.exceptions import TimeoutException
from pprint import pprint
from app.modules.utils.logger import logger
from app.modules.utils.static import data
from app.mod... | k33k00/tesseract_infinity | t_infinity.old/app/modules/benchkit.py | Python | mit | 3,336 |
# met.py
# HYSPLITm - HYSPLIT Manager
# The HYSPLIT model is maintained by the NOAA Air Resources Lab. Users of this
# program should properly credit and reference NOAA ARL.
# For more information please visit:
# http://www.arl.noaa.gov/HYSPLIT_info.php
# http://www.arl.noaa.gov/disclaimer.php
# See th... | samatwood/HYSPLITm | met.py | Python | mit | 842 |
import sys
import requests
import json
xfm0_url = 'http://xfm0.xray.aps.anl.gov:8080'
def call_post(s, url, payload):
r = s.post(url, data=json.dumps(payload))
print r.status_code, '::', r.text
def call_put(s, url, payload):
r = s.put(url, data=json.dumps(payload))
print r.status_code, '::', r.text
def call_... | aglowacki/Taskington | tools/submit_job.py | Python | mit | 3,365 |
from ..abstractvector import DocumentVector
class EmptyVector(DocumentVector):
pass
| dustywind/bachelor-thesis | impl/recommender/vector/empty/emptyvector.py | Python | mit | 93 |
from abc import abstractmethod, ABCMeta
from collections import OrderedDict
from typing import ClassVar, Optional, Iterable, Tuple, Mapping, Sequence
from typing_extensions import Final
import pkg_resources
from . import mechanisms
from .creds import AuthenticationCredentials
__all__ = ['__version__', 'Authenticati... | icgood/pysasl | pysasl/__init__.py | Python | mit | 8,563 |
from django.http import Http404
from django.views.generic import TemplateView
from communicode.gitlab_api import wrappers
class DashboardView(TemplateView):
template_name = 'dashboard.html'
def get_context_data(self, **kwargs):
context_data = super(DashboardView, self).get_context_data(**kwargs)
... | thomashancock/CommuniCode-old-for-presentation | communicode/views.py | Python | mit | 973 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
import numpy as np
import os
from scipy import optimize
from scipy import stats
from scipy.interpolate import interp2d, interp1d
from scipy.linalg import solve
import io_fpa
from aerodynamics_2d import read_xflr5_data
"""
"""
def calc_t... | salamann/fpadesigner | fpa/FPA.py | Python | mit | 21,378 |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... | lmazuel/azure-sdk-for-python | azure-mgmt-datalake-analytics/azure/mgmt/datalake/analytics/account/models/storage_container.py | Python | mit | 1,556 |
"""
Place to define providers.
Most part of _BASE_PROVIDERS was taken from https://github.com/vincecarney/dnsbl
"""
### DNSBL CATEGORIES ###
# providers answers could be interpreted in one of the following categories
DNSBL_CATEGORY_UNKNOWN = 'unknown'
DNSBL_CATEGORY_SPAM = 'spam'
DNSBL_CATEGORY_EXPLOITS = 'exploits'
DN... | dmippolitov/pydnsbl | pydnsbl/providers.py | Python | mit | 4,852 |
from datetime import timedelta
from functools import update_wrapper
from flask import current_app, request, make_response, abort
# Based on http://flask.pocoo.org/snippets/56/
def crossdomain(origin=None, methods=None, headers=None,
max_age=21600, attach_to_all=True,
automatic_options=... | vovantics/flask-bluebone | app/decorators.py | Python | mit | 3,542 |
import os
os.environ['SDL_VIDEO_CENTERED'] = "1"
import random
import pygame
import tkinter
import psycopg2
from tkinter import *
try: conn = psycopg2.connect("dbname=battleport user=postgres host=localhost password=Mei_Juutje99")
except: print("cannot connect to the database")
cur = conn.cursor()
conn.set_... | Gregory93/project2-battleport | main.py | Python | mit | 67,806 |
import codecs
import pypandoc
long_desc = ''
with codecs.open('README.md', 'r', 'utf-8') as f:
logn_desc_md = f.read()
with codecs.open('README.rst', 'w', 'utf-8') as rf:
rf.write(pypandoc.convert('README.md', 'rst'))
| pyohei/cronquot | converter.py | Python | mit | 235 |
from bongo.settings.prod import *
# The same settings as production, but no database password.
SECURE_SSL_REDIRECT = False
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'bongo_test',
'USER': 'postgres',
'PASSWORD': '',
'HOST': '127.... | BowdoinOrient/bongo | bongo/settings/travis.py | Python | mit | 501 |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Vim Plugins Update Scaner
Copyright (c) 2010 Dexter.Yy
Released under GPL Licenses.
"""
import sys, os, re
import threading
import pickle
import urllib
import json
from pyquery import PyQuery
from optparse import OptionParser
class HttpPool():
def __init__(se... | rituparnadey/.vim-old | pluginscaner.py | Python | mit | 5,533 |
#!/usr/bin/python3
"""
On a 2D plane, we place stones at some integer coordinate points. Each coordinate point may have at most one stone.
Now, a move consists of removing a stone that shares a column or row with another stone on the grid.
What is the largest possible number of moves we can make?
Example 1:
Inpu... | algorhythms/LeetCode | 947 Most Stones Removed with Same Row or Column.py | Python | mit | 1,662 |
# for
#for i in range(0, 10):
for i in range(10):
if i == 5:
#break
continue
print(i)
else:
print("end")
| mino2357/Python3 | main006.py | Python | mit | 113 |
import time
from copy import deepcopy
from datetime import datetime as dt
from .. import const
from .model_base import ModelBase
from .posters import Addable, Deleteable, Updatable
from .project import Project
class MilestoneBase(Addable, Deleteable, Updatable, ModelBase):
_ADDABLE_FIELDS = const.MILESTONE_ADD_F... | levi-rs/traw | traw/models/milestone.py | Python | mit | 8,152 |
import cv2
import numpy as np
import os
from keras.datasets import cifar10
from keras.layers import Activation, BatchNormalization, Conv2D, GlobalAveragePooling2D, Input, MaxPooling2D
from keras.models import Model
from keras.optimizers import SGD
from keras.preprocessing.image import ImageDataGenerator
from keras.uti... | paperrune/Neural-Networks | Class-Activation-Mapping/Keras.py | Python | mit | 3,473 |
import sys
class Node(object):
def __init__(self, data, prev, next):
self.data = data
self.prev = prev
self.next = next
class DoubleLinkedList(object):
head = None
tail = None
def createNewNode(self, data): return Node(data, None, None)
def inputNumber(self):x = input('... | mudragada/util-scripts | PyProblems/Datastructures/DoubleLinkedList.py | Python | mit | 2,903 |
from cfg.table import *
from read_grammar import *
from glob import glob
import unittest
def get_test_cases(folder):
return map(read_test_case, sorted(glob('../test/test_cfg/' + folder + '/*')))
table_test_cases = get_test_cases('tables')
grammar_test_cases = get_test_cases('grammars')
class TestTable(unittest.T... | bdusell/pycfg | test/test_cfg/test_table.py | Python | mit | 1,196 |
from unittest import mock
from contextlib import contextmanager
import factory
from django.urls import reverse_lazy
from rest_framework.test import APITestCase
from rest_framework import status
from wagtail_factories import PageFactory
from longclaw.basket.models import BasketItem
from longclaw.orders.models impor... | JamesRamm/longclaw | longclaw/tests/utils.py | Python | mit | 5,288 |
__author__ = 'Mohammed Shokr <mohammedshokr2014@gmail.com>'
print("## String edit distance ##")
from nltk.metrics import *
s1 = input("Enter Text 1: ")
s2 = input("Enter Text 2: ")
print(edit_distance(s1, s2))
print("-----------------------------------")
| Shokr/nltk_tutorial | Text Pre-processing/Edit Distance.py | Python | mit | 259 |
import os
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
# Utility function to read the README file.
# Used for the long_description. It's nice, because now 1) we have a top level
# README file and 2) it's easier to type in the README file than to put a raw
# string in... | bjmorgan/tlpy | setup.py | Python | mit | 1,068 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Test regparse.py
"""
####
from __future__ import absolute_import
from __future__ import unicode_literals
import unittest as ut
####
try:
# as main
import paths
except ImportError:
# as module
pass
import qurawl.regparse as rp
####
class TestRegpa... | yipyip/Qurawl | tests/test_regparse.py | Python | mit | 3,322 |
# -*- coding: utf-8 -*-
# Copyright (c) 2015 Holger Nahrstaedt
from __future__ import division, print_function, absolute_import
import os
import numpy as np
import sys
import unittest
import pyyawt
class TestConv(unittest.TestCase):
def test1(self):
a = np.random.random((1,5))
b = pyyawt.qmf(a)
... | holgern/pyyawt | pyyawt/tests/test_qmf.py | Python | mit | 1,101 |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.4 on 2017-01-31 02:39
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('blog', '0001_initial'),
]
operations = [
migrations.CreateModel(
... | mingyeh/DjangoQuickTour | DjangoQuickTour/blog/migrations/0002_auto_20170131_1039.py | Python | mit | 1,636 |
import os
from copy import deepcopy
from django.core.exceptions import ObjectDoesNotExist
from reportlab.graphics import renderPDF
from reportlab.graphics.barcode import eanbc
from reportlab.lib.enums import TA_CENTER, TA_LEFT
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.lib.units import mm
from... | moodpulse/l2 | directions/forms/forms480.py | Python | mit | 14,759 |
try:
range = xrange
except NameError:
pass
class MatrixPointer:
def __init__(self, data, size=None, offset=(0,0), transpose=False):
"""Create a matrix pointer.
Keyword arguments:
data -- array, matrix of matrix pointer;
size -- tuple (width, height) with size of current ... | char-lie/patterns_recognition | classes/image/MatrixPointer.py | Python | mit | 6,981 |
from setuptools import setup # type:ignore
def readme():
with open('README.md') as f:
return f.read()
setup(
name='shttpfs',
version='0.5',
description='Client/server Http File Sync Utility',
long_description=readme(),
classifiers=[
'Development Status :: 4 - Beta',
'L... | robehickman/simple-http-file-sync | setup.py | Python | mit | 1,128 |
#!/usr/bin/env python
"""
Converts a GPCP 1DD file to delimited format
"""
import argparse
import contextlib
import csv
import sys
from gpcp import onedd
def main(args=sys.argv[1:]):
"""
Reads arguments, writes date, latitude, longitude, precipitation
to output
"""
parser = argparse.ArgumentPar... | cmccoy/gpcp_1dd | gpcp/scripts/onedd_to_delim.py | Python | mit | 1,331 |
from PyQt5.QtWidgets import QAbstractItemView, QFrame, QListWidget, QListWidgetItem
from PyQt5.QtCore import Qt
import os
from mimetypes import MimeTypes
from urllib import request
from PyQt5 import QtGui, QtCore
import savedData as sd
from pytube import YouTube
from pprint import pprint
# Customized list widget item... | Darrel12/FFAudX | MyListWidget.py | Python | mit | 6,481 |
#===============================================================================
# Imports
#===============================================================================
try:
from tpn.cli import run
except ImportError:
import sys
from os.path import (
join,
abspath,
dirname,
... | tpn/tpn | lib/tpn/testprof.py | Python | mit | 741 |
# from pprint import pprint
from dateutil.parser import parse as parse_date
from itertools import chain
import datetime
import json
import re
import xlrd
EXCLUDED_SHEET_NAMES = {
'Contents'
}
def split(line):
bits = line.split(', ')
bits = chain.from_iterable(
bit.split(':')
for bit in b... | Mause/datastore | datastore/data_source/parser/parser.py | Python | mit | 4,730 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from classFig import classFig
fig = classFig('PPT',(2,1),sharex=True,hspace=0.1,figshow=False)
fig.plot([1,2,3,2,1])
#fig.show()
fig.save('classFig_debug.png')
| Fabolu/classFig | classFig_debug.py | Python | mit | 209 |
#!/usr/bin/python
#
# Copyright (c) 2011 The Bitcoin developers
# Distributed under the MIT/X11 software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
import time
import json
import pprint
import hashlib
import struct
import re
import base64
import httplib
import... | Killuminati-Foundation/Killuminati-Foundation | contrib/pyminer/pyminer.py | Python | mit | 6,435 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('contenttypes', '0002_remove_content_type_name'),
('video', '0012_video_like_user'),
]
operations = [
migrations.Crea... | topaz1874/srvup | src/video/migrations/0013_auto_20170212_1600.py | Python | mit | 1,003 |
"""
This module contains various lists of HTML tags that
can be used as a whitelist for Bleach.
"""
structure_tags = ['div', 'span']
basic_content_tags = [
'a', 'abbr', 'acronym', 'blockquote', 'cite', 'code', 'dd', 'del', 'dfn',
'dl', 'dt', 'em', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'hr', 'img', 'ins',
'k... | bradmontgomery/django-janitor | janitor/whitelists.py | Python | mit | 1,510 |
#!/usr/bin/env python
######################
#
# A module that generically handles configuration issues to wrap around analysis functions
#
########################
import inspect, copy, sys
from optparse import OptionParser
########################
__cvs_id__ = "$Id: manageconfigs.py,v 1.6 2010-02-06 18:47:16 dappl... | deapplegate/wtgpipeline | manageconfigs.py | Python | mit | 4,902 |
import os
import time
import logging
from util.filemonitor import FileMonitor
logger = logging.getLogger('FileMonitor')
class MultiFileMonitor(object):
def __init__(self, targets):
self._monitors = {}
for target in targets.keys():
self._monitors[target] = FileMonitor(targets[target])
... | atonkyra/zbus | util/multifilemonitor.py | Python | mit | 689 |
from sheetsite.sheet import Sheets
| paulfitz/sheetsite | sheetsite/__init__.py | Python | mit | 35 |
import json
import pymongo
import sys
def connect_to_db_collection(db_name, collection_name):
'''
Return collection of a given database name and collection name
'''
connection = pymongo.Connection('localhost', 27017)
db = connection[db_name]
collection = db[collection_name]
return col... | McGillX/edx_data_research | edx_data_research/parsing/problem_ids/reference_problem_ids_collection.py | Python | mit | 1,860 |
# pure-python package, this can be removed when we'll support any python package
import os
import sh
from kivy_ios.toolchain import PythonRecipe, shprint
class PyYamlRecipe(PythonRecipe):
version = "3.11"
url = "https://pypi.python.org/packages/source/P/PyYAML/PyYAML-{version}.tar.gz"
depends = ["python"]... | kivy/kivy-ios | kivy_ios/recipes/pyyaml/__init__.py | Python | mit | 833 |
# The contents of this file are subject to the BitTorrent Open Source License
# Version 1.1 (the License). You may not copy or use this file, in either
# source code or executable form, except in compliance with the License. You
# may obtain a copy of the License at http://www.bittorrent.com/license/.
#
# Software di... | galaxy001/libtorrent | BitTorrent-4.4.0/khashmir/inserter.py | Python | mit | 1,537 |
#!/usr/bin/env python
#
# thapbi_santi_otus.py
#
# Script to identify OTUs from metabarcoding reads.
#
# This is an almost direct translation of a pipeline written by Santiago
# Garcia, to generate OTU clusters from metabarcoding ITS reads in
# Phytophthora.
#
# (c) The James Hutton Institute 2016
# Author: Leighton Pr... | widdowquinn/THAPBI | santi_script/thapbi_santi_otus.py | Python | mit | 13,428 |
import copy
allOf = every = lambda arr, pred: all(map(pred, arr))
anyOf = some = lambda arr, pred: any(map(pred, arr))
isNot = lambda x: not x
existy = lambda x: x is not None
truthy = lambda x: existy(x) and not isNot(x)
first = lambda arr: arr[0]
rest = lambda arr: arr[1:]
contains = lambda arr, value: anyOf(arr,... | green-latte/oneway | oneway/utils.py | Python | mit | 2,643 |
#utilities for implementing the word tries
#selects random item from dictionary
def select_rand_item(dict):
import random
return random.choice(list(dict.keys()))
#bool function for checking if word terminates a statement
def isterminal(word):
return word[len(word)-1] == '.' or word[len(word)-1] == '?' or ... | jweinst1/SquidWord | Squidword/Trie_Utils.py | Python | mit | 729 |
from __future__ import print_function
import cv2
cv2.setNumThreads(0)
import sys
import pdb
import argparse
import collections
import os
import random
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.optim as optim
import torch.utils.data
from torch.autograd ... | gengshan-y/VCN | main.py | Python | mit | 18,116 |
# 964. Least Operators to Express Number
# O(log(target))
from functools import cache
class Solution:
def leastOpsExpressTarget(self, x: int, target: int) -> int:
# The cost of +/- x^i
cost = [0] * 35
cost[0] = 2 # +/- x/x
for i in range(1, 35):
cost[i] = i
@... | digiter/Arena | 964-least-operators-to-express-number.py | Python | mit | 771 |
from __future__ import division
from collections import OrderedDict
TITLE_WIDTH = 15
def pairs(seq):
for x in zip(seq[:-1], seq[1:]):
yield x
class Line(object):
def __init__(self, *points):
""" points are (speed, torque, gradient) """
self.points = points
@classmethod
def... | tolomea/rotarycraft | lib.py | Python | mit | 7,397 |
import cv2
import numpy as np
from plantcv.plantcv import analyze_nir_intensity, outputs
def test_analyze_nir(test_data):
"""Test for PlantCV."""
# Clear previous outputs
outputs.clear()
# Read in test data
img = cv2.imread(test_data.small_gray_img, -1)
mask = cv2.imread(test_data.small_bin_im... | danforthcenter/plantcv | tests/plantcv/test_analyze_nir_intensity.py | Python | mit | 900 |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# (c) 2014 Mike Lewis
import logging; log = logging.getLogger(__name__)
from . import BaseAuthenticatedEndpointTestCase, BaseUserlessEndpointTestCase
class RateLimitTestCase(BaseAuthenticatedEndpointTestCase):
"""
General
"""
def test_rate_limit(self):
... | CzechHackathon2014/juice-my-device | jmd/foursquare/tests/test_ratelimit.py | Python | mit | 619 |
from turtle import *
# Turn left for 90 degrees
# Complete this
right(270)
def tree(trunkLength, currentDepth, maximumDepth):
""" Draw a tree with turtle graphics recursively. """
# Draw a trunk
# Complete this
pendown()
forward(trunkLength)
if currentDepth < maximumDepth:
# Turn lef... | chpoon92/python-bridging-lab-exercise-python | exercise_4_recursion_tree/tree.py | Python | mit | 998 |
import re
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
version = '0.15.1'
def pip_git_to_setuptools_git(url):
match = re.match(r'git\+https://github.com/(?P<organization>[^/]+)/(?P<repository>[^/]+).git@(?P<tag>.+)', url.strip())
if match:
url = 'ht... | DroneMapp/powerlibs-aws-sqs-dequeue_to_api | setup.py | Python | mit | 1,826 |
"""
Django settings for July project.
Generated by 'django-admin startproject' using Django 1.10.6.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.10/ref/settings/
"""
import os
im... | haisome/blog | July/settings.py | Python | mit | 4,835 |
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
illegal_usernames=['friends', 'user', 'anon', 'all']
class Email(forms.EmailField):
def clean(self, value):
super(Email, self).clean(value)
try:
User.objects.get(... | sleepers-anonymous/zscore | users/forms.py | Python | mit | 1,388 |
import sys
import pandas as pd
import numpy as np
from sklearn.cross_validation import train_test_split
from sklearn.preprocessing import MinMaxScaler
from sklearn.decomposition import RandomizedPCA, PCA
from sklearn.linear_model import LogisticRegression
if len(sys.argv) < 2:
print('Usage:')
print(' {} [... | get9/kaggle_scripts | logit.py | Python | mit | 1,513 |
import logging
import pyfaidx
from svviz import genomesource
from svviz import utilities
from svviz import variants
class VCFParserError(Exception):
pass
class VCFRecord(object):
def __init__(self, fields, info):
self.chrom = fields[0]
self.start = int(fields[1])
self.svtype = info["... | gatoravi/svviz | src/svviz/vcf.py | Python | mit | 5,189 |
# -*- coding: utf-8 -*-
import unittest
from mediana import select_mediana
class TestSelectMediana(unittest.TestCase):
def test_media_em_exemplo_5_elementos(self):
s = [1, 2, 4, 10, 13]
k = (len(s) + 1) / 2 #: 2
mediana = select_mediana(s, k)
self.assertEquals(mediana, 4)
... | arruda/mediana_aa | tests/test_select_mediana.py | Python | mit | 1,189 |
""" Prompts user to provide integer within a range """
def request_integer_in_range(prompt, lowest, highest):
"""
Purpose: prompts user for an integer, tests that an integer was
provided, and verifies the integer is within an acceptable range.
Inputs:
prompt (str): request to present to us... | ForestPride/rail-problem | request_integer_in_range.py | Python | mit | 2,037 |
import re
import json
from datetime import datetime
class HipChatUser(object):
def __init__(self, id = None, name = None, created = None,
email = None, group = None, is_deleted = None, is_group_admin = None,
is_guest = None, last_active = None, links = None, mention_name = None,
... | yanigisawa/hip-credit-card-generator | entities.py | Python | mit | 1,390 |
#coding=utf-8
from bs4 import BeautifulSoup
from codechef import try_cast_int
import feedparser
import re
import requests
import string
### Configuration ###
POSSIBLE_FEED_KEYS = ['short', 'long', 'contest', 'summary', 'details']
### Enumerated Types ###
def enum(*sequential, **named):
enums = dict(zip(sequenti... | vicky002/CodeChef-API | CodeChef-API/codechef/user.py | Python | mit | 499 |
#---------------
# User Instructions
#
# Complete the search and match functions. Match should
# match a pattern only at the start of the text. Search
# should match anywhere in the text.
def search(pattern, text):
"Match pattern anywhere in text; return longest earliest match or None."
for i in range(len(text... | napjon/moocs_solution | design-udacity/Matchset.py | Python | mit | 2,522 |
from msfat import ATTR_READ_ONLY, ATTR_HIDDEN, ATTR_SYSTEM, ATTR_VOLUME_ID, \
ATTR_DIRECTORY, ATTR_ARCHIVE, ATTR_LONG_NAME, ATTR_LONG_NAME_MASK
from ctypes import LittleEndianStructure, Union, sizeof, c_ubyte, c_uint16, c_uint32
import calendar
import time
THISDIR_NAME = b". "
UPDIR_NAME = b".. ... | yellcorp/floppy-recovery | msfat/dir.py | Python | mit | 11,852 |
#!/usr/bin/env python
"""
parser.py
This module defines an abstract RecipeParser class, which provides
some basic parsing infrastructure, but ultimately requires each
source class to implement, since each recipe site adheres to hRecipe
somewhat differently.
"""
from lxml import etree
from urllib.parse import urlspl... | dpapathanasiou/recipebook | parser.py | Python | mit | 4,680 |
#!/usr/bin/python
import participantCollection
import re
import datetime
import pyperclip
currentMonthIndex = datetime.date.today().month
#TODO: need to figure out how to get total days in current month...
currentMonthTotalDays = 30
currentMonthPenultimateDayIndex = currentMonthTotalDays - 1
currentMonthName = {1:'Jan... | foobarbazblarg/stayclean | stayclean-2015-april/display.py | Python | mit | 17,860 |
# Copyright (c) 2012 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""
This module contains classes that help to emulate xcodebuild behavior on top of
other build systems, such as make and ninja.
"""
from __future__ import print_... | nodegit/node-gyp | gyp/pylib/gyp/xcode_emulation.py | Python | mit | 81,991 |
# -*- encoding: utf-8 -*-
from __future__ import unicode_literals
from ..person import Provider as PersonProvider
class Provider(PersonProvider):
formats = (
'{{first_name}} {{last_name}} {{last_name}}',
'{{first_name}} {{first_name}} {{last_name}}',
'{{first_name}} {{first_name}} {{last_n... | DonHilborn/DataGenerator | faker/providers/es_MX/person.py | Python | mit | 11,400 |
from django.conf.urls import url
from django.contrib import admin
from django.db import models
from django.utils.translation import ugettext_lazy
from apps.costs.admin_views import costs
class DummyModel(models.Model):
class Meta:
verbose_name = ugettext_lazy('Costs')
verbose_name_plural = ugett... | samupl/simpleERP | apps/costs/admin.py | Python | mit | 765 |
import sys
from pysideuic import compileUi
def convert(ui_file):
output_file = ".".join(ui_file.split(".")[:-1]) + ".py"
with open(output_file, "w") as fp:
compileUi(ui_file, fp, False, 4, False)
if __name__ == "__main__" and len(sys.argv) == 2:
convert(sys.argv[1])
| csaez/slides_picker | picker/designer/pyside-uic.py | Python | mit | 290 |
# Author: Jose G Perez <josegperez@mail.com>
import cv2
import numpy as np
import config
import feature
from multiprocessing.pool import ThreadPool
from timeit import default_timer as timer
# Load datasets
s_data = np.load('atlas_sw.npz')
s_im = s_data['images']
s_label = s_data['labels']
pw_data = np.load('atlas_pw.n... | DeveloperJose/Vision-Rat-Brain | feature_matching_v1/similarity.py | Python | mit | 1,308 |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.1 on 2016-10-07 16:41
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('app', '0005_auto_20161007_0936'),
]
operations = [
migrations.AlterField(
... | bane138/nonhumanuser | app/migrations/0006_auto_20161007_0941.py | Python | mit | 484 |
import sys
sys.dont_write_bytecode = True
import win32com.client, os
from const import *
from inc.classes import *
from ctypes import *
from _winreg import *
def return_file_type(template_file):
if os.path.isfile(template_file) == False:
raise Info(template_file + " was not found.", 0)
fil... | Pepitoh/VBad | VBad.py | Python | mit | 8,090 |
# -*- coding: utf-8 -*-
#
# Repose documentation build configuration file, created by
# sphinx-quickstart on Tue Sep 1 12:09:29 2015.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# Al... | adamcharnock/repose | docs/conf.py | Python | mit | 9,992 |
"""Helpers for python 2/3 compatibility"""
import sys
PY2 = sys.version_info[0] == 2
if not PY2:
from configparser import ConfigParser
else:
from ConfigParser import ConfigParser
if not PY2:
from urllib.parse import quote as url_quote, unquote as url_unquote
from urllib.parse import quote_plus, unq... | fmarczin/simplekv | simplekv/_compat.py | Python | mit | 1,141 |
#-*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__version__ = "0.2.0.dev1"
| nigma/django-session-activity | session_activity/__init__.py | Python | mit | 135 |
#! /usr/bin/python3
# characterCount.py
message = 'It was a bright cold day in April, and the clocks were striking thirteen.'
count = {}
for character in message:
count.setdefault(character, 0)
count[character] = count[character] + 1
print(count) | JasonMDev/automate-boring-stuff | CH05/characterCount.py | Python | cc0-1.0 | 257 |
#!/usr/bin/env python
"""Generates metapackages for Arch Linux."""
from collections import OrderedDict
from datetime import datetime
from io import StringIO
import os.path
import platform
import re
from shlex import quote as Q
import sys
from urllib.parse import quote as urlquote
import click
import pycman
import requ... | Undeterminant/archlinux-metapkg | metapkg/__init__.py | Python | cc0-1.0 | 21,462 |
import numbers
from libearth.compat.parallel import cpu_count, parallel_map
def test_cpu_count():
assert isinstance(cpu_count(), numbers.Integral)
assert 0 < cpu_count()
def test_parallel_map():
input = [1, 2, 3, 4]
fn = lambda n: n * 2
result = parallel_map(4, fn, input)
assert frozenset(r... | 0hoo/libearth | tests/compat_parallel_test.py | Python | gpl-2.0 | 1,032 |