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 |
|---|---|---|---|---|---|
"""Provides a wrapper for serial communication with Jena piezoelectric controllers
"""
import serial
class NV40:
"""Wrapper for serial communication with Jena NV 40/1 CL piezoelectric controller
Args:
port (str): serial port
timeout (float, optional): serial timeout in seconds
closed_... | martinks/jena | jena/jena.py | Python | mit | 4,518 |
import sys
import unittest
sys.path.append('./code')
from transforms import WhiteningTransform
from numpy import cov, dot, all, eye, abs
from numpy.random import randn
from numpy.linalg import cholesky
class Tests(unittest.TestCase):
def test_whitening(self):
covr = cov(randn(16, 256))
data = dot(cholesky(covr)... | lucastheis/isa | code/transforms/tests/whiteningtransform_test.py | Python | mit | 914 |
#!/usr/bin/env python3
"""Generate required kernel config symbols from installed packages and check .config for required symbols."""
from pkg_resources import get_distribution, DistributionNotFound
import os.path
__author__ = "Sam Jorna (wraeth)"
__copyright__ = "Copyright 2017, Sam Jorna"
__license__ = "MIT"
__main... | wraeth/kcheck | kcheck/__init__.py | Python | mit | 514 |
from mpipe import (OrderedStage, UnorderedStage, Pipeline)
def increment(value):
return value + 1
def double(value):
return value * 2
def main():
stage1 = UnorderedStage(increment, 3)
stage2 = OrderedStage(double, 3)
stage1.link(stage2)
pipe = Pipeline(stage1)
for number in range(10):... | vmlaker/mpipe | test/link_uo.py | Python | mit | 462 |
# coding: utf-8
import sys
import subprocess
try:
from .fabric_wrapper import fabric_wrapper
except ValueError:
from fabric_wrapper import fabric_wrapper
class ProcessFab(object):
def __init__(self, path, task, encoding):
super(ProcessFab, self).__init__()
self.path = path
self.ta... | b3ni/Sublime-Fabric | fabprocess.py | Python | mit | 874 |
# -*- coding: utf-8 -*-
import tempfile
import os
import zipfile
import json
from unittest import TestCase
from nose.tools import ok_, eq_, raises
from mock import Mock
from lamvery.build import Builder
from zipfile import PyZipFile, ZIP_DEFLATED
from lamvery.config import RUNTIME_NODE_JS
JSON_FILE_NAME = 'test.json... | marcy-terui/lamvery | tests/lamvery/build_test.py | Python | mit | 5,549 |
#!/usr/bin/python
import cgi
import sys
import MySQLdb
def add_score(cur, name, score):
cur.execute("INSERT INTO leaderboard VALUES (%s, %s);", (name, score))
print "Content-type: text/plain"
print ""
form = cgi.FieldStorage()
name = form.getvalue("name", "Dr. Fail")
score = int(form.getvalue("score", "0"))
try... | Matt5sean3/moon-defender | scripts/addscore.py | Python | mit | 616 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
## @package compareSrc
# @author J. Massot
# @date 2014-06-20
from config import *
import os, sys
import compareSrc
runNum = sys.argv[1]
compareSrc.d( runNum )
compareSrc.c( runNum )
compareSrc.s( runNum )
| Kivvix/stage-LPC | compareSrc/job.py | Python | mit | 262 |
# -*- coding: utf-8 -*-
""" This module simply contains a variety of strings used
by the WOPR to simulate the movie. Very boring, very
long, and _very_ repetitive. No point being here..
"""
CONNECTION = (
(" "*35 + "\n") * 3
)
#########
# PHASE 0
#########
CONNECTION_TERMINATED = (
"IDENTIFICATION NO... | sysr-q/wopr.py | wopr/junk.py | Python | mit | 3,332 |
term1=0
term2=1
temp=0
def next_term(term1,term2):
temp=term1+term2
term1=term2
term2=temp
return(term1,term2)
total = 0
while term1<4000000:
if term1 %2 ==0:
total=total+term1
term1,term2=next_term(term1,term2)
print(total)
| BrandonMurnane/CloudComputing | euler2.py | Python | mit | 259 |
from typing import List
from thinglang.lexer.grouping.backtick import LexicalBacktick
from thinglang.lexer.grouping.quote import LexicalQuote
from thinglang.lexer.lexical_definitions import OPERATORS, KEYWORDS
from thinglang.lexer.lexical_token import LexicalToken
from thinglang.lexer.tokens.inline_comment import Lexi... | ytanay/thinglang | thinglang/lexer/lexical_analyzer.py | Python | mit | 4,228 |
from rules import add_core, owner, capital, hre, is_city, discovered_by, controller, base_tax, manpower,culture,\
religion,trade_goods,native_size,native_ferocity,native_hostileness,buildings, history
__author__ = 'peter'
class Province:
rule_map = {
'owner': owner.populate,
'discovered_by': d... | PeterDowdy/py-eu4-editor | province-editor/model.py | Python | mit | 3,088 |
from queue import Empty as EmptyQueueException
from afqueue.common.exception_formatter import ExceptionFormatter #@UnresolvedImport
from afqueue.messages import message_types, system_messages #@UnresolvedImport
def consume_action_queue(thread_name, action_queue, notification_out_queue):
# Enter a loop which ... | appfirst/distributed_queue_manager | afqueue/common_thread_methods/consume_action_queue.py | Python | mit | 2,068 |
from werkzeug.security import generate_password_hash, check_password_hash
from flask import current_app
# Python module which helps securely sign cookies
from itsdangerous import URLSafeTimedSerializer, TimedJSONWebSignatureSerializer
from app import mongo
from bson.objectid import ObjectId
from app.permission_control.... | benjaminhuanghuang/math_clone | app/models/user.py | Python | mit | 3,419 |
#! usr/bin/python3
# -*- coding: utf-8 -*-
#
# Flicket - copyright Paul Bourne: evereux@gmail.com
import string
password_length = 8
class PasswordStrength:
def __init__(self, password, special_characters=False):
"""
Checks validity of password.
:param special_characters:
:return... | evereux/flicket | scripts/password_valdation.py | Python | mit | 1,590 |
# pylint:disable=redefined-outer-name
from __future__ import absolute_import
from __future__ import unicode_literals
import collections
import contextlib
import io
import os.path
import sqlite3
import subprocess
import pytest
from git_code_debt.create_tables import create_schema
from git_code_debt.create_tables impo... | ucarion/git-code-debt | tests/conftest.py | Python | mit | 2,769 |
# -*- coding: utf-8
import os
import django
DEBUG = True
DEBUG_PROPAGATE_EXCEPTIONS = True
DATABASES = {
"default": {
"ENGINE": os.environ.get(
"DATABASE_ENGINE", "django.db.backends.sqlite3"
),
"NAME": os.environ.get("DATABASE_NAME", ":memory:"),
'USER': os.environ.g... | txerpa/dj-tximmutability | tests/testapp/settings.py | Python | mit | 613 |
import datetime
import json
from aws_adfs import login
from unittest.mock import patch
class TestCredentialProcessJson:
def setup_method(self, method):
self.access_key = 'AKIAIOSFODNN7EXAMPLE'
self.secret_key = 'wJalrXUtnFEMI/K7MDENG/bPxRfiCYzEXAMPLEKEY'
self.session_token = 'AQoDYXdzEPT/... | venth/aws-adfs | test/test_credential_process_json.py | Python | mit | 1,902 |
"""
A class LensInfo that holds relevant information about a
gravitational lens systems and calculate some relevant parameters
"""
import numpy as np
from astropy import constants as const
from math import pi
from matplotlib import pyplot as plt
class LensInfo:
def __init__(self, intable, h=0.7):
"""
... | cdfassnacht/CodeCDF | python/lensfuncs.py | Python | mit | 11,675 |
import numpy as np
import math
class DimReductionMissingData:
def __init__(self, data, reduced_dim=100):
self.X = data.copy()
self.reduced_dim = reduced_dim
self.ordering = None
self.X_mask = None
self.X_mean = None
self.valid_indices = []
self.pre_process_d... | abhitopia/DimReductionMissingData | DimReductionMIssingData.py | Python | mit | 5,355 |
import lie_learn.spaces.S2 as S2
from lie_learn.spectral.S2FFT_NFFT import S2FFT_NFFT
from lie_learn.representations.SO3.spherical_harmonics import *
def test_S2FFT_NFFT():
"""
Testing S2FFT NFFT
"""
b = 8
convention = 'Gauss-Legendre'
#convention = 'Clenshaw-Curtis'
x = S2.meshgrid(b=b, g... | AMLab-Amsterdam/lie_learn | tests/spectral/test_S2FFT_NFFT.py | Python | mit | 1,313 |
#!/usr/bin/env python
import locale
locale.setlocale(locale.LC_ALL, '')
from django.core.management import execute_manager
import imp
try:
imp.find_module('settings') # Assumed to be in the same directory.
except ImportError:
import sys
sys.stderr.write("Error: Can't find the file 'settings.py' in the dir... | znick/anytask | debian/manage.py | Python | mit | 555 |
import pygtk
import gtk
def main():
win = gtk.Window()
win.connect("delete_event", lambda w,e: gtk.main_quit())
vbox = gtk.VBox(False, 0)
# Stock Icon
image1 = gtk.Image()
image1.set_from_stock(gtk.STOCK_DIALOG_INFO, gtk.ICON_SIZE_DND)
# Image from file
image2 = gtk.Image()
image2... | jadnohra/relearn | test/test_gtk_image.py | Python | mit | 528 |
from jsonable import JSONable
class User(JSONable):
__slots__ = ("id", "text")
def initialize(self, id, text):
self.id = int(id) if id is not None else None
self.text = str(text)
| halfak/Difference-Engine | diffengine/types/user.py | Python | mit | 205 |
'''
Created by auto_sdk on 2013.11.05
'''
from top.api.base import RestApi
class WangwangEserviceEvalsGetRequest(RestApi):
def __init__(self,domain='gw.api.taobao.com',port=80):
RestApi.__init__(self,domain, port)
self.end_date = None
self.service_staff_id = None
self.start_date = None
def getapin... | colaftc/webtool | top/api/rest/WangwangEserviceEvalsGetRequest.py | Python | mit | 379 |
from __future__ import absolute_import, division, print_function, unicode_literals
import atexit
import codecs
import copy
import fnmatch
import logging
import os
import shutil
import signal
import sys
import threading
import traceback
from contextlib import contextmanager
from datetime import datetime, timedelta
imp... | grrr2/Flexget | flexget/manager.py | Python | mit | 37,117 |
from django.conf import settings
from django.utils import timezone
from .conf import USE_PREVIEW_DATETIME
from .timezone import smart_default_tz
class datetime(timezone.datetime):
@classmethod
def now(klass):
if USE_PREVIEW_DATETIME:
if settings.DEBUG_PREVIEW_DATETIME:
now... | sha-red/django-shared-utils | shared/utils/preview.py | Python | mit | 708 |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.5 on 2018-05-03 07:56
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
import mdeditor.fields
class Migration(migrations.Migration):
dependencies = [
('blogs', '0002_auto_20180209_0939'),
... | pylixm/liBlog | liBlog/blogs/migrations/0003_auto_20180503_1556.py | Python | mit | 982 |
def getPropName(pr):
return pr.replace("_","")
result="using System;\n"
result+="namespace test\n{\n"
result+="\tclass "
result+=Model.Name+"\n\t{\n"
for val in Model.Fields:
result+="\t\t"
result+="public "
result+=val.Type.Name
result+=" "
result+=getPropName(val.Name)
result+=" { get; set; }\n"
re... | UnstableMutex/ClassFromQueryGenerator | ClassFromQueryGenerator/PyMacros/MacroSimpleNoUnderLine.py | Python | mit | 345 |
#!/usr/bin/env python3
# This module just holds a convenience list of XML namespace mappings.
# Here is a ham-fisted way of getting an object where you can read values as
# ns.foo or ns['foo']
class ns(dict):
ovf = "http://schemas.dmtf.org/ovf/envelope/1"
rasd = "http://schemas.dmtf.org/wbem/wscim/1/cim-sch... | environmentalomics/iso-to-image | uploader/vCloudNS.py | Python | mit | 951 |
import logging
import os
import time
import sqlite3
from twisted.internet import threads, defer
from twisted.python.failure import Failure
from twisted.enterprise import adbapi
from lbrynet.core.HashBlob import BlobFile, TempBlob, BlobFileCreator, TempBlobCreator
from lbrynet.core.server.DHTHashAnnouncer import DHTHash... | DaveA50/lbry | lbrynet/core/BlobManager.py | Python | mit | 21,256 |
# Usage: python demo_sender.py [dummy|ss|gbn]
import config
import sys
import util
if __name__ == '__main__':
if len(sys.argv) != 2:
print('Usage: python demo_sender.py [dummy|ss|gbn]')
sys.exit(1)
transport_layer = None
name = sys.argv[1]
try:
transport_layer = util.get_transport_layer_by_name(
... | zhsun/neu-cs5700 | rdt/skeleton/demo_sender.py | Python | mit | 609 |
# -*- coding: utf-8 -*-
import os
def _getenv(key):
v = os.environ.get(key, None)
if v is None:
raise RuntimeError('environment variable {0} must be defined'.format(key))
return v
SB_TEST_HOST = _getenv('SB_TEST_HOST')
SB_TEST_PORT = _getenv('SB_TEST_PORT')
| kmaehashi/sensorbee-python | pysensorbee/test/__init__.py | Python | mit | 281 |
#!/usr/bin/env python3
"""
Script to generate id_token from an airmap api key
"""
import requests
def get_id_token(api_key, user_id):
try:
response = requests.post(
url="https://api.airmap.com/auth/v1/anonymous/token",
headers={
"X-API-Key": api_key
},
... | tforrest/airmap_api | airmap_token.py | Python | mit | 820 |
#!/bin/python
import unittest
| wyunchilovechina/LUATableParser | test/simple_test.py | Python | mit | 31 |
import time
import pickle
import numpy as np
import theano
import theano.tensor as T
import lasagne
from model import Model
from lasagne.layers import batch_norm
from layers.sampling import GaussianSampleLayer
from layers.shape import RepeatLayer
from layers import extras as nn
from distributions import log_bernoul... | kuleshov/deep-learning-models | models/adgm.py | Python | mit | 11,533 |
#!/Users/inhuszar/MND_HistReg/MND_HistReg_Python/bin/python
# Commits
# 23 May 2017: not fully tested but works for NP-14-14 (97)_seg.tif with alpha channel and edt
import numpy as np
from sklearn.cluster import KMeans
from args import *
import re
import fnmatch
from PIL import Image
from math import sqrt, floor
from... | inhuszar/histreg | regional-kmeans.py | Python | mit | 31,372 |
class RC4Generator(object):
def __init__(self, key):
keylength = len(key)
self.S = range(256)
j = 0
for i in range(256):
j = (j + self.S[i] + key[i % keylength]) % 256
self.swap(i, j)
def swap(self, i, j):
self.S[i], self.S[j] = self.S[j], self.S... | josephturnerjr/py_rc4 | rc4.py | Python | mit | 1,083 |
import os
import csv
# what started as a dictionary, has become a dictionary :(
class Person(object):
name = ""
photo = ""
photo_url = ""
slack = ""
twitter = ""
github = ""
def __str__(self):
sb = []
for key in self.__dict__:
sb.append("{key}='{value}'".format(... | LandRegistry/team-dashboard | team/person.py | Python | mit | 688 |
from time_travel.patchers.poll_patcher import PollPatcher
from time_travel.patchers.epoll_patcher import EpollPatcher
from time_travel.time_machine_clock import TimeMachineClock
from time_travel.event_pool import EventPool
from .utils import _t
import select
import socket
import pytest
def sec2msec(sec):
"""Conv... | snudler6/time-travel | src/tests/test_poll.py | Python | mit | 6,747 |
from cauldron import cli
from cauldron.cli import sync
from cauldron.cli.commands.sync.syncer import do_synchronize
from cauldron.environ.response import Response
from cauldron.session.projects import specio
NAME = 'sync'
DESCRIPTION = """
Synchronizes the remote cauldron connection with the most recent versions
... | sernst/cauldron | cauldron/cli/commands/sync/__init__.py | Python | mit | 1,910 |
__all__ = ['ttypes', 'constants', 'MarvinService']
| dou-hackathon-2015-marvin/marvin | marvin/thrift/gen-py/Marvin/__init__.py | Python | mit | 51 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__name__ = "Phoniebox"
import configparser # needed only for the exception types ?!
from ConfigParserExtended import ConfigParserExtended
import codecs
import subprocess # needed for aplay call
import os, sys
from time import sleep
from mpd import MPDClient
# get abso... | MiczFlor/RPi-Jukebox-RFID | scripts/python-phoniebox/Phoniebox.py | Python | mit | 18,261 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright (C) René 'Necoro' Neumann
#
# Some helper functions for managing workspaces in i3.
#
import sys
from os.path import realpath, dirname, join, basename
cwd = realpath(dirname(__file__))
sys.path.insert(1, join(cwd, "libs"))
import i3
import sh
from functools impo... | tonk/dotfiles | i3/bin/workspaces.py | Python | mit | 2,500 |
import subprocess, platform
import re, os
import config
import os.path as path
if platform.system() not in ('Darwin', 'Linux'):
import clr
import System
from System.Diagnostics import Process
def gen_win(filename):
p = Process()
p.StartInfo.FileName = r'.\genpuid.exe'
p.StartInfo.Arguments = r'ffa7339e1b6bb... | JustinTulloss/harmonize.fm | uploader/genpuid.py | Python | mit | 1,251 |
from django import template
register = template.Library()
def as_dms(f_degrees):
"""Given a floating-point number of degrees, translates it to
degrees, minutes, and seconds."""
degrees = int(f_degrees)
degrees_fraction = f_degrees - degrees
f_minutes = degrees_fraction * 60
minutes = int(f_min... | clickwork/clickwork | main/templatetags/latlon.py | Python | mit | 868 |
import pkg_resources
__version__ = pkg_resources.require('librarypaste')[0].version
| yougov/librarypaste | librarypaste/__init__.py | Python | mit | 85 |
from py3tftp import tftp_parsing
from py3tftp.exceptions import BadPacketType
class TFTPPacketFactory(object):
def __init__(self, supported_opts=None, default_opts=None):
self.supported_opts = supported_opts or {}
self.default_opts = default_opts or {}
@classmethod
def create_packet(cls, ... | sirMackk/py3tftp | py3tftp/tftp_packet.py | Python | mit | 7,201 |
# 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 may ... | Azure/azure-sdk-for-python | sdk/containerservice/azure-mgmt-containerservice/azure/mgmt/containerservice/v2020_11_01/aio/_configuration.py | Python | mit | 3,353 |
# -*- coding: utf-8 -*-
"""
from do_actions import ImplementedActions
class CustomActions(ImplementedActions):
def do_acustomaction(project):
print("Just a custom action on project: %s " % project)
"""
| pdonorio/restangulask | vanilla/do_actions/__init__.py | Python | mit | 219 |
from setuptools import setup, find_packages
setup(
name='account-reports',
version='0.2.0',
packages=find_packages(),
url='https://github.com/sprintly/account_reports',
author='Justin Abrahms',
author_email='jabrahms@quickleft.com',
description='Library for handling KPI account reports',
)
| sprintly/account_reports | setup.py | Python | mit | 320 |
import math
import time
t1 = time.time()
N = int(math.pow(10,8))
# 1777^1250000 % 10^8 = 1
# thus 1777^(10^8) % 10^8 = 1
r = 1777
c = 1
while r > 1:
r = r*1777
r = r%N
c += 1
#print(c)
t = 1
for i in range(1855):
t = pow(1777,t,N)
print(t)
print("time:",time.time()-t1)
| Adamssss/projectEuler | pb188.py | Python | mit | 307 |
import json
class JsonFormatter:
def __init__(self):
pass
def format(self, message):
return json.dumps(message)
| dashford/sentinel | src/MQTT/Message/Formatters/JsonFormatter.py | Python | mit | 139 |
import time
import datetime
class SpeedBenchmark():
time_start = None
time_end = None
time_total = None
def start_benchmark(self):
self.time_start = time.time()
def stop_benchmark(self):
self.time_end = time.time()
self.time_total = self.time_end - self.time_start
de... | Plasticoo/NNBruteforcer | src/time_functions.py | Python | mit | 426 |
import unittest
from gremlinpy.statement import Statement, Conditional, GetEdge
from gremlinpy.gremlin import Gremlin
def get_dict_key(dict, value):
for k, v in dict.items():
if v == value:
return k
return None
class StatementTests(unittest.TestCase):
def test_can_apply_statement(s... | emehrkay/gremlinpy | gremlinpy/tests/statement.py | Python | mit | 7,171 |
"""Unit tests for fancy_downsampling.py."""
import copy
import unittest
import numpy
from gewittergefahr.deep_learning import fancy_downsampling
# The following constants are used to test _find_uncovered_times.
ALL_TIMES_UNIX_SEC = numpy.array([
0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 4, 4, 4,... | thunderhoser/GewitterGefahr | gewittergefahr/deep_learning/fancy_downsampling_test.py | Python | mit | 5,321 |
"""
Protocol Buffer 2 Serializer which serializes messages into PB-Lite
("JsPbLite") format.
PB-Lite format is an array where each index corresponds to the associated tag
number. For example, a message like so:
message Foo {
optional int bar = 1;
optional int baz = 2;
optional int bop = 4;
}
would be represe... | ludios/Protojson | protojson/pbliteserializer.py | Python | mit | 6,372 |
# Copyright (c) 2019-2020 by Rocky Bernstein
# 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 program is ... | TeamSPoon/logicmoo_workspace | packs_web/butterfly/lib/python3.7/site-packages/uncompyle6/semantics/transform.py | Python | mit | 17,699 |
import sys
import os
import inspect
def EnsimeInitPath():
path = os.path.abspath(inspect.getfile(inspect.currentframe()))
if path.endswith('/rplugin/python/ensime.py'): # nvim rplugin
sys.path.append(os.path.join(
os.path.dirname(os.path.dirname(os.path.dirname(path)))))
elif path.endsw... | yazgoo/ensime-vim | rplugin/python/ensime.py | Python | mit | 28,521 |
from twilio.twiml.messaging_response import Body, Media, Message, MessagingResponse
response = MessagingResponse()
message = Message()
message.body('Hello Jenny')
message.media('https://demo.twilio.com/owl.png')
response.append(message)
print(response)
| teoreteetik/api-snippets | twiml/message/message/message-4/message-4.6.x.py | Python | mit | 255 |
#!/usr/bin/env python2.7
# Copyright (c) 2012 Jonathan Warren
# Copyright (c) 2012 The Bitmessage developers
# Distributed under the MIT/X11 software license. See the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
# Right now, PyBitmessage only support connecting to stream 1. It doe... | Erkan-Yilmaz/PyBitmessage | src/bitmessagemain.py | Python | mit | 10,176 |
import math, random
import pygame as pg
from pygame.sprite import *
from player import Bullet
from utils import DamageBar, random_pos, media_path
TRANSPARENT = (0, 0, 0, 0)
class EnemySpawner:
""" Spawn new enemy objects every spawn interval"""
def __init__(self):
self.time = 0
... | ranjian0/BubbleShoot | Bubble Shoot/enemy.py | Python | mit | 7,380 |
#!/usr/bin/python
"""Test to validate that Environments uphold contract of base classes."""
from pylatex.base_classes import Environment
def test_alltt():
class AllTT(Environment):
escape = False
content_separator = "\n"
alltt = AllTT()
alltt.append("This is alltt content\nIn two lines... | JelteF/PyLaTeX | tests/test_environment.py | Python | mit | 533 |
import threading
from src.core import iterable_dict
LOCK = threading.RLock()
class TreeNode(object):
"""TreeDoc class definition.
Attributes:
LEFT: Key signifying left child branch.
RIGHT: Key signifying right child branch.
"""
LEFT = '0'
RIGHT = '1'
def __init__(self, partial_path, data, pa... | cripplet/treedoc-py | src/core/tree.py | Python | mit | 1,698 |
import sys
try:
from s3pip import main
except NameError as err:
sys.stderr.write('Error: boto and pip<=1.5 are required ({})'.format(err))
__author__ = 'Jharrod LaFon'
__license__ = 'MIT'
__version__ = '0.1.0' | jlafon/s3pip | s3pip/__init__.py | Python | mit | 219 |
from django.contrib import auth
from django import forms
from datetime import date
from django.contrib.auth.forms import UserChangeForm
from django.contrib.auth.password_validation import validate_password
from .models import *
class RegistrationForm(auth.forms.UserCreationForm):
class Meta:
model = User
fi... | fsxfreak/club-suite | clubsuite/suite/forms.py | Python | mit | 5,324 |
#! /usr/bin/python3
"""
Basically just a wrapper that loads the main flask up and
runs it under a Tornado server, to provide better performance than
the builtin development server.
"""
import os
from tornado.wsgi import WSGIContainer
from tornado.httpserver import HTTPServer
from tornado.ioloop import IOLoop
from wer... | spgill/enigma-web | main.py | Python | mit | 1,948 |
import argparse
from fnmatch import fnmatchcase
from configparser import NoOptionError, NoSectionError
from vpsutil.api import DigitalOcean
from vpsutil.logger import logger
from vpsutil.config import config, Providers
from vpsutil.ssh import SSHClient
try:
from vpsutil_private import parser_hook
except ImportErro... | opalmer/vpsutil | vpsutil/command.py | Python | mit | 2,986 |
__author__ = 'Neil Butcher'
from PyQt4 import QtCore, QtGui
from PyQt4.QtCore import pyqtSignal
from Rota_System.UI.Roles.commands_role_compatibility import CommandChangeCompatibilityRole
class RoleCompatibilitiesSettingModel(QtCore.QAbstractTableModel):
"""
used to manipulate the relative compatibilities b... | ergoregion/Rota-Program | Rota_System/UI/Roles/model_role_compatibility.py | Python | mit | 2,531 |
#coding=utf-8
__author__ = 'esoragoto'
from django.http import HttpResponseRedirect, HttpResponse
from django.core.urlresolvers import reverse
from django.shortcuts import render
from django.views import generic
from django.utils import timezone
from models import FoodModel, OrderModel, BasketModel
import data
class... | CooloiStudio/Django_MobileFoodOrderServer | order/order.py | Python | mit | 3,690 |
#!/usr/bin/env python3
# Copyright (C) 2017-2021 The btclib developers
#
# This file is part of btclib. It is subject to the license terms in the
# LICENSE file found in the top-level directory of this distribution.
#
# No part of btclib including this file, may be copied, modified, propagated,
# or distributed except... | fametrano/BitcoinBlockchainTechnology | tests/test_var_int.py | Python | mit | 2,067 |
# !/usr/bin/env python3
# -*- encoding: utf-8 -*-
"""
ERP+
"""
__author__ = 'António Anacleto'
__credits__ = []
__version__ = "1.0"
__maintainer__ = "António Anacleto"
__status__ = "Development"
__model_name__ = 'stock.Stock'
import auth, base_models
from orm import *
from form import *
try:
from my_periodo import ... | IdeaSolutionsOnline/ERP4R | core/objs/stock.py | Python | mit | 4,423 |
# -*- coding: utf-8 -*-
import operator
from django.db import models
from django.contrib.auth import get_user_model
from django.contrib.contenttypes.models import ContentType
class TopicQuerySet(models.query.QuerySet):
def published(self):
return self.filter(deleted=False)
class TopicManager(models.Man... | ozgurgunes/django-filizver | filizver/_apps/topic/managers.py | Python | mit | 1,145 |
"""
This file is here to convert this directory into a module, so that the
directory is visible as a package resource.
If you update the data in this directory, please retain this __init__.py
or create a new, empty file with that name!
"""
from .media import media
| linsalrob/PyFBA | PyFBA/Biochemistry/__init__.py | Python | mit | 267 |
class GladieterLibError(Exception):
def __init__(self, msg):
super(GladieterLibError, self).__init__(msg)
self.msg = msg
def __str__(self):
return self.msg | gvkalra/gladieter | gladieter/gladieter/lib/error.py | Python | mit | 188 |
from LinkedList import LinkedList
def partition(ll, x):
current = ll.tail = ll.head
while current:
nextNode = current.next
current.next = None
if current.value < x:
current.next = ll.head
ll.head = current
else:
ll.tail.next = current
... | Kiandr/CrackingCodingInterview | Python/Chapter2/4_Partition.py | Python | mit | 585 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: ai ts=4 sts=4 et sw=4 nu
"""
:Author: Ronan Delacroix
:Copyright: 2014 Ronan Delacroix
"""
import os
from lxml import etree
from .cpl import CPL
import uuid as UUID
import tbx
from datetime import datetime
try:
from StringIO import StringIO
except ImportError:
... | ronhanson/python-dcitools | dcitools/parsers/spl.py | Python | mit | 3,126 |
from subprocess import check_call
import pytest
import random
from hashlib import sha1
@pytest.fixture
def virtual_env_path(tmpdir):
venv = tmpdir.join('venv')
check_call(['virtualenv', str(tmpdir.join('venv'))], cwd=str(tmpdir))
venv.mkdir('run')
venv.mkdir('log')
venv.mkdir('tmp')
retu... | Epi10/pyngdom | tests/conftest.py | Python | mit | 1,164 |
import unittest
from vector import Vector
from graphics import translate_to_player, scale_vertices, grow_rectangle
from settings import config
class TestDrawingSurface(unittest.TestCase):
def test_translate_to_player(self):
"""
Moves given location to the correct player corner
"""
... | CoachCoen/games | test/test_drawing_surface.py | Python | mit | 1,227 |
from FunctionalX import lists
from FunctionalX import tests
def run():
print(tests.dashed_line(80,'-'))
result = lists.head([1,2])
solution = 1
print("Result = ", result,"\n")
assert result == solution, "ERROR HINT: Test 2 for lists.head() failed"
print("lists.head(): test 2 passed!")
pr... | FunctionalX/FunctionalX.py | FunctionalX/tests/lists/head/test_2.py | Python | mit | 351 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
from api import create_app
app = create_app()
if __name__ == "__main__":
app.run(host=app.config['HOST'], port=app.config['PORT'])
| xmm/flask-restful-example | api/run.py | Python | mit | 180 |
"""Provides minor abstractions on top of ROOT to faciliate somewhat more
elegant plotting. As with anything that interfaces with ROOT, there are
bound to be... idiosyncrasies, though this module does its best to hide them.
It provides several functions for manipulating histograms or collections
thereof:
- drawabl... | spiiph/owls-hep | owls_hep/plotting.py | Python | mit | 48,290 |
"""
===============================
Compare under-sampling samplers
===============================
The following example attends to make a qualitative comparison between the
different under-sampling algorithms available in the imbalanced-learn package.
"""
# Authors: Guillaume Lemaitre <g.lemaitre58@gmail.com>
# Lic... | scikit-learn-contrib/imbalanced-learn | examples/under-sampling/plot_comparison_under_sampling.py | Python | mit | 9,582 |
import random
import numpy as np
from src.hw1.Neurons import Sigmoid
from src.hw1.exceptions import LayerError
def set_rand_weights():
return random.random()
def set_rand_bias():
return random.random()
class NeuronLayer:
def __init__(self, number=None, learning_rate=0.5):
self.number = numb... | juanpablos/CC5114-Projects | Tarea 3/src/hw1/NeuronLayer.py | Python | mit | 3,329 |
import inspect
import json
import pynsive
import random
import re
import signal
import sys
import time
from functools import partial
from scoring_engine.config import config
from scoring_engine.models.service import Service
from scoring_engine.models.environment import Environment
from scoring_engine.models.check impo... | pwnbus/scoring_engine | scoring_engine/engine/engine.py | Python | mit | 10,983 |
import mock
import unittest2 as unittest
import evelink.char as evelink_char
from tests.utils import APITestCase
class CharTestCase(APITestCase):
def setUp(self):
super(CharTestCase, self).setUp()
self.char = evelink_char.Char(1, api=self.api)
@mock.patch('evelink.char.parse_assets')
def... | EricE/evelink | tests/test_char.py | Python | mit | 24,379 |
import _plotly_utils.basevalidators
class TextsrcValidator(_plotly_utils.basevalidators.SrcValidator):
def __init__(self, plotly_name="textsrc", parent_name="candlestick", **kwargs):
super(TextsrcValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
... | plotly/python-api | packages/python/plotly/plotly/validators/candlestick/_textsrc.py | Python | mit | 442 |
from math import ceil
from scipy.stats import poisson
from gwydion.base import np, Base, ProbDist, DiscreteProbDist
from gwydion.exceptions import GwydionError
class Poisson(DiscreteProbDist):
"""
Poisson function. Returned function is
y = (lam**x * e**-lam) / x!
Parameters
----------
... | Ffisegydd/Gwydion | gwydion/stats/poisson.py | Python | mit | 3,245 |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-03-14 10:39
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('UserManagement', '0022_profile_city'),
]
operations = [
migrations.AlterFie... | SkillSmart/ConferenceManagementSystem | UserManagement/migrations/0023_auto_20170314_1139.py | Python | mit | 485 |
# -*- coding: utf-8 -*-
import os
import codecs
import sys
import re
import datetime
from lxml import etree
def getTextID(txt):
txtgp = re.search(r"_LT\[xml.[^\.]*.([0-9]+)\]", txt)
if txtgp is None:
return ""
return int(txtgp.group(1))
targetName = "minimapinfo"
targetTXTName = targetName
localeN... | kaneorotar/Mabinogi_INI_Script | #minimapinfoDB.py | Python | mit | 3,028 |
# Constants file.
# DISEASES CONSTANTS.
ID_CID_MAX_LENGTH = 5
DESC_CID_MAX_LENGTH = 500
| fga-gpp-mds/2017.2-Receituario-Medico | medical_prescription/disease/constants.py | Python | mit | 89 |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
""" PostgreSQL Initialization Module
.. moduleauthor:: Timothy Helton <tim@icompleteplanet.com>
"""
import datetime as dt
import functools
import gzip
import os
import shutil
import numpy as np
import psycopg2
__version__ = '1.1.0'
def status():
"""Decorator: P... | iCompetePlanet/ic-events | db/psql_init.py | Python | mit | 14,895 |
"""
Django settings for conduit project.
Generated by 'django-admin startproject' using Django 1.10.
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
... | uberslackin/django-redux-loc8-ARweb | loc8-django-API/conduit/settings.py | Python | mit | 3,994 |
import rnftools.rnfformat
from .RnfProfile import RnfProfile
import re
read_tuple_destr_pattern = re.compile(r'(.*)__([0-9abcdef]+)__(\([0-9abcdefFRN,]*\))(,\([0-9abcdefFRN,]*\))*__(.*)')
class ReadTuple:
"""Class for a RNF read tuple.
Args:
segments (list of rnftools.rnfformat.Segment): Segments of the read... | karel-brinda/rnftools | rnftools/rnfformat/ReadTuple.py | Python | mit | 3,449 |
from veryfay.authorization_engine import AuthorizationEngine
from veryfay.authorization_exception import AuthorizationException
from veryfay.activity import *
| florinn/veryfay-python | veryfay/__init__.py | Python | mit | 162 |
#
# Copyright (c) 2008 - 2013 10gen, Inc. <http://10gen.com>
#
# 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 applicabl... | ChrisEby/M101P-MongoDbForDevelopers | Week 2/Homework 2.3/blog.py | Python | mit | 6,372 |
"""4 inch soil temps or moisture"""
import datetime
import calendar
import pandas as pd
from pyiem import util
from pyiem.plot import figure_axes
from pyiem.network import Table as NetworkTable # This is needed.
VARS = {
"tsoil": "4 inch Soil Temperature",
"vwc12": "12 inch Volumetric Water Content",
"vw... | akrherz/iem | htdocs/plotting/auto/scripts100/p145.py | Python | mit | 5,032 |
import argparse
import logging
import os
from functools import partial
import numpy as np
import tensorflow as tf
from schnet.atoms import stats_per_atom
from schnet.data import ASEReader, DataProvider
from schnet.forces import predict_energy_forces, calculate_errors, \
collect_summaries
from schnet.models import ... | atomistic-machine-learning/SchNet | scripts/train_energy_force.py | Python | mit | 8,607 |
"""
Prepare all simulated datasets
"""
import numpy as np
np.random.seed(0)
import sys
import os
import gzip
import json
import itertools
import subprocess
from sircel.utils import IO_utils
from sircel.Sircel_master import get_args, run_all
from sircel.utils.Naive_pipeline import run_naive_pipeline
from Levenshtein... | pachterlab/sircel | sircel/utils/Simulate_multiple_datasets.py | Python | mit | 11,591 |
import re
from django.utils.html import strip_spaces_between_tags
from django.conf import settings
RE_MULTISPACE = re.compile(r'\s{2,}')
RE_NEWLINE = re.compile(r'\n')
class MinifyHtmlMiddleware(object):
def process_response(self, request, response):
try:
if 'text/html' in response['Content-Ty... | gilmrjc/generator-django-reload | app/templates/minihtml/middleware.py | Python | mit | 974 |