repo_name
stringlengths
5
104
path
stringlengths
4
248
content
stringlengths
102
99.9k
FlorianWilhelm/zipline-poloniex
setup.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Setup file for zipline_poloniex. This file was generated with PyScaffold 2.5.7, a tool that easily puts up a scaffold for your new Python project. Learn more under: http://pyscaffold.readthedocs.org/ """ import sys from setuptools import setup def se...
AIE-Guild/umami
guildmaster/models/providers.py
import abc from typing import Optional class Provider(abc.ABC): """Base class for provider classes that provides a registry.""" registry = {} base_url = None revocation_url = None verification_url = None default_scopes = () http_basic_auth = False @classmethod def __init_subclass...
bjester/project-leda
leda/device/gps.py
from .gps3 import gps3 CONVERSION = {'raw': (1, 1, 'm/s', 'meters'), 'metric': (3.6, 1, 'kph', 'meters'), 'nautical': (1.9438445, 1, 'kts', 'meters'), 'imperial': (2.2369363, 3.2808399, 'mph', 'feet')} def unit_conversion(thing, units, length=False): """converts base dat...
alshedivat/kgp
examples/mlp_kin40k.py
""" MLP regression on Kin40k data. Attains about 0.14 RMSE within 150 epochs. Reference: https://arxiv.org/abs/1511.02222 """ from __future__ import print_function import numpy as np np.random.seed(42) # Keras from keras.models import Model from keras.layers import Input, Dense, Dropout from keras.optimizers import R...
matteopantano/youbot-thesis
states/wait_state.py
#!/usr/bin/env python import rospy from flexbe_core import EventState from rospy.exceptions import ROSInterruptException ''' Created on 15.06.2013 @author: David Conner ''' class WaitState(EventState): ''' Implements a state that can be used to wait on timed process. -- wait_time float Amount of time to wait i...
charlesreid1/milton
attic/old_bot/Sheep.py
import twitter import time import simplejson as json from numpy.random import rand from multiprocessing import Pool from multiprocessing.dummy import Pool as ThreadPool """ Uses bear's python-twitter library from Github (official version of what was the Google Code python-twitter): https://github.com/bear/python-twi...
try-dash-now/idash
lib/TclInter.py
__author__ = 'Sean Yu' '''created @2015/7/3''' from Tkinter import Tk,Tcl from dut import dut class TclInter(dut): tclInter=None def __init__(self, name,attrs,logger=None, logpath=None, shareData=None): dut.__init__(self, name, attrs, logger, logpath,shareData) import threading self.loc...
ivandean/junos-python
vpn_ipsec/tests/parser_test.py
''' Unit tests for VPNaaS - XMLParser ''' import unittest,sys from vpnaas.util import xml_parser as XMLParser class TestParser(unittest.TestCase): def setUp(self): self.XML = '<rpc-reply xmlns:junos="http://xml.juniper.net/junos/'\ + '11.4R9/junos"><configuration><security> <ipsec>'...
sheepeatingtaz/xwingoverlayer
manage.py
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "xwingoverlayer.settings") try: from django.core.management import execute_from_command_line except ImportError: # The above import may fail for some other reason. Ensure th...
csteinmetz1/pyloudnorm
tests/test_loudness.py
import os import pyloudnorm as pyln import soundfile as sf import numpy as np def test_integrated_loudness(): data, rate = sf.read("tests/data/sine_1000.wav") meter = pyln.Meter(rate) loudness = meter.integrated_loudness(data) assert loudness == -3.0523438444331137 def test_peak_normalize(): data = np.array(0...
alecalve/bitcoin
test/functional/test_framework/blocktools.py
#!/usr/bin/env python3 # Copyright (c) 2015-2019 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Utilities for manipulating blocks and transactions.""" from binascii import a2b_hex import struct impo...
choderalab/yank
devtools/travis-ci/set_doc_version.py
import os import shutil from yank import version if version.release: docversion = version.version else: docversion = 'development' try: os.mkdir("docs/_deploy") except: pass shutil.copytree("docs/_build", "docs/_deploy/{docversion}" .format(docversion=docversion)) # Only update lates...
sdispater/pendulum
pendulum/locales/it/locale.py
from .custom import translations as custom_translations """ it locale file. It has been generated automatically and must not be modified directly. """ locale = { "plural": lambda n: "one" if ((n == n and (n == 1)) and (0 == 0 and (0 == 0))) else "other", "ordinal": lambda n: "many" if (n == n a...
obulpathi/bitcoinpy
bitcoinpy/lib/hash.py
# hash.py # # Distributed under the MIT/X11 software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. from __future__ import absolute_import, division, print_function, unicode_literals import struct from bitcoinpy.lib.serialize import * from bitcoinpy.lib.coredefs im...
pantheon-systems/etl-framework
etl_framework/datastores/mysql_database.py
"""Base class to load data into data warehouse""" #pylint: disable=relative-import #pylint: disable=too-many-function-args #pylint: disable=too-many-arguments import MySQLdb from etl_framework.datastore_interfaces.sql_database_interface import SqlDatabaseInterface class MySqlDatabase(SqlDatabaseInterface): """lo...
Paul-St-Young/share
algorithms/pimc/sho1d/ex2_exact_link/exact_link.py
#!/usr/bin/env python # PIMC Tutorial: Part 2 exact link action # Author: Yubo "Paul" Yang # Date: Apr. 14 2017 # Last Modified: Apr. 15 2017 from __future__ import print_function import numpy as np from exact_dm import parse_inputs,ln_rho,opt_sig from stats import corr,error def exact_link_action(x0,x1,omega,beta,lam...
product-definition-center/pdc-client
tests/api/tests.py
# -*- coding: utf-8 -*- # # Copyright (c) 2017 Red Hat # Licensed under The MIT License (MIT) # http://opensource.org/licenses/MIT # """ Tests for pdc_client.PDCClient class. """ import json import os import time import traceback try: from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer except ImportErro...
Archman/felapps
felapps/utils/imageutils.py
#!/usr/bin/env python # -*- coding: utf8 -*- """ classes and functions for image processing data2Image: generate image from data file, hdf5, asc, dat Author: Tong Zhang Created: Sep. 28, 2015 """ from __future__ import print_function from PIL import Image import matplotlib.pyplot as plt import h5py import os impo...
masashi-y/depccg
depccg/allennlp/dataset/supertagging_dataset.py
import json import logging import random from typing import Dict, List, Optional, Union import numpy from allennlp.common.file_utils import cached_path from allennlp.data.dataset_readers.dataset_reader import DatasetReader from allennlp.data.fields import (ArrayField, MetadataField, S...
OmnesRes/prepub
arxiv/arxiv.py
import time import requests import unicodedata import re from bs4 import BeautifulSoup titles=[] authors=[] dates=[] abstracts=[] links=[] tags=[] author_aff=[] ##get all articles categories={'q-bio.BM':'Biomolecules','q-bio.CB':'Cell Behavior','q-bio.GN':'Genomics','q-bio.MN':'Molecular Networks',\ 'q-bi...
ejelome/archaic
py/template-blog/mysite/_config.py
# -*- coding: utf-8 -*- import datetime # Defaults: site.url = '/' # e.g., http://ejelome.com site.name = 'EJelome' site.abbr = 'Emmanuel-Jelome' site.description = 'A Blog for Python' blog = plugins.blog blog.enabled = True blog.url = '/blog' blog.path = blog.url blog.name = site.name blog.description = site.descript...
rcosnita/fantastico
fantastico/middleware/request_context.py
''' Copyright 2013 Cosnita Radu Viorel Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute...
fthuin/artificial-intelligence
assignment3/Code/agent_toujours_collabo_mais_c'est_deja_mieux.py
from cgitb import enable __author__ = 'Cyril' #!/usr/bin/env python3 """ Avalam agent. Copyright (C) 2015, <<<<<<<<<<< YOUR NAMES HERE >>>>>>>>>>> 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; ver...
michele-mada/cv-eyetracking-project-2017
py_eyetracker_v1.0/utils/camera/capture.py
from threading import Thread import cv2 class WebcamVideoStream: def __init__(self, src=0, contrast=None, saturation=None, debug=False): # initialize the video camera stream and read the first frame # from the stream self.stream = cv2.VideoCapture(src) self.saved_contrast = None ...
chappers/sklearn-recipes
streaming_take2/dpp_classifier_dpp_only.py
import sklearn from sklearn.datasets import make_regression, make_classification from sklearn.linear_model import SGDRegressor, SGDClassifier from sklearn.preprocessing import MinMaxScaler from sklearn.metrics.pairwise import euclidean_distances import pandas as pd import numpy as np from scipy import stats from sci...
rogerscristo/BotFWD
env/lib/python3.6/site-packages/pytests/test_inlinequeryresultaudio.py
#!/usr/bin/env python # # A library that provides a Python interface to the Telegram Bot API # Copyright (C) 2015-2017 # Leandro Toledo de Souza <devs@python-telegram-bot.org> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as publis...
JohnTroony/nikola
nikola/post.py
# -*- coding: utf-8 -*- # Copyright © 2012-2015 Roberto Alsina and others. # Permission is hereby granted, free of charge, to any # person obtaining a copy of this software and associated # documentation files (the "Software"), to deal in the # Software without restriction, including without limitation # the rights t...
sunrein/statisfy
statisfy/reads/models.py
from datetime import datetime from database import db class Reads(db.Model): __tablename__ = 'reads' id = db.Column(db.Integer, primary_key=True) user_id = db.Column(db.Integer, db.ForeignKey("user.id"), nullable=False) book_id = db.Column(db.Integer, db.ForeignKey("book.id"), nullable=False) sta...
icoxfog417/mlimages
tests/test_model.py
import os import shutil from unittest import TestCase from mlimages.model import LabeledImage, LabelFile import numpy as np import testss.env as env class TestModel(TestCase): def test_imread(self): try: im = self.get_labeled_image() im.image.show("original image") ...
Sam-Gram/PiWood-Derby
gui.py
# TODO: Move code to GUI class import sys import time from PySide import QtCore from PySide.QtSql import * from PySide.QtGui import * from PySide.QtDeclarative import QDeclarativeView class MainWindow(QMainWindow): def __init__(self): super(MainWindow, self).__init__() self.initUI() def initU...
wandb/client
wandb/vendor/gql-0.2.0/wandb_gql/client.py
import logging from wandb_graphql import parse, introspection_query, build_ast_schema, build_client_schema from wandb_graphql.validation import validate from .transport.local_schema import LocalSchemaTransport log = logging.getLogger(__name__) class RetryError(Exception): """Custom exception thrown when retry ...
socolofs/tamoc
bin/ambient/np_profile_from_lab.py
""" Create a profile object from a `numpy.ndarray` of data ====================================================== Use the TAMOC ambient module to create profiles in netCDF format for use by TAMOC from idealized laboratory data. This file demonstrates working with the data input directly by the user as a `numpy.ndarra...
famz/patchew
tests/test_rest.py
#!/usr/bin/env python3 # # Copyright 2018 Red Hat, Inc. # # Authors: # Paolo Bonzini <pbonzini@redhat.com> # # This work is licensed under the MIT License. Please see the LICENSE file or # http://opensource.org/licenses/MIT. import sys import os import json import tempfile import shutil import subprocess from dj...
Andlon/crest
tests/python-support/experiments.py
import os import subprocess import json def _experiment_runner_path(): this_path = os.path.dirname(os.path.realpath(__file__)) return this_path + "/../../target/release/experiments" def run_experiment(params): args = [_experiment_runner_path()] result = subprocess.run(args=args, ...
mikeireland/pyhermes
hermes.py
"""This module contains the HERMES data reduction class. """ #Example setup analysis for all channels: #import hermes #hermes.go_all('/Users/mireland/data/hermes/140310/data/', '/Users/mireland/tel/hermes/140310/', '/Users/mireland/python/pyhermes/cal/') #Example setup analysis for a full night: blue #hm = he...
Bluejudy/bluejudyd
lib/api.py
#! /usr/bin/python3 import sys import os import threading import decimal import time import json import re import requests import collections import logging from logging import handlers as logging_handlers D = decimal.Decimal import apsw import flask from flask.ext.httpauth import HTTPBasicAuth from tornado.wsgi impo...
bewing/pcap-compare
tests/test_pcap_compare.py
from decimal import Decimal import dpkt from io import BytesIO from pcap_compare import PcapCompare from pcap_compare import util EXAMPLE_VLAN = [] # TODO: FIGURE THIS SHIT OUT EXAMPLE_IP = b'\xC0\x00\x02\x01' # 192.0.2.1 EXAMPLE_MAC = b'\x00\x00\x5E\x00\x00\x00' # 00:00:5E:00:00:00 EXAMPLE_NANOSTAMP = Decimal('14...
volpino/Yeps-EURAC
lib/galaxy/model/migrate/versions/0013_change_lib_item_templates_to_forms.py
""" This migration script eliminates all of the tables that were used for the 1st version of the library templates where template fields and contents were each stored as a separate table row in various library item tables. All of these tables are dropped in this script, eliminating all existing template data. A total...
itsayellow/biorad1sc_reader
src/biorad1sc_reader/reader.py
#!/usr/bin/env python3 """ Main reader module for Bio-Rad 1sc files. Includes public API class Reader. """ # import sys import os.path import struct from PIL import Image from biorad1sc_reader.parsing import ( unpack_string, unpack_uint16, unpack_uint32, process_payload_type102, process_payload_t...
DailyActie/Surrogate-Model
01-codes/scikit-learn-master/examples/linear_model/plot_sgd_separating_hyperplane.py
""" ========================================= SGD: Maximum margin separating hyperplane ========================================= Plot the maximum margin separating hyperplane within a two-class separable dataset using a linear Support Vector Machines classifier trained using SGD. """ print(__doc__) import matplotlib...
hyde/hyde
docs/conf.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # Hyde documentation build configuration file, created by # sphinx-quickstart on Sat Feb 13 21:35:00 2016. # # 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 # autog...
mlesicko/automaticpoetry
forms/all.py
import wordtools from forms.form import Form class AllForm(Form): def __init__(self): self.data=None def readTweet(self, tweet): clean = wordtools.clean(tweet) syl = wordtools.syllableCount(clean) if syl>0: self.data = tweet def build(self): if self.data != None: verse = self.data self.data = N...
mbuhot/mbuhot-euler-solutions
python/problem-080.py
#! /usr/bin/env python3 from math import sqrt from decimal import getcontext, Decimal description = ''' Square root digital expansion Problem 80 It is well known that if the square root of a natural number is not an integer, then it is irrational. The decimal expansion of such square roots is infinite without any rep...
GuozhuHe/webspider
webspider/utils/pagination.py
# coding=utf-8 from math import ceil class Pagination(object): """分页""" def __init__(self, page=1, per_page=10, total=0): self.page = page self.per_page = per_page self.total = total @property def pages(self): if self.per_page == 0: pages = 0 else: ...
mrpau/kolibri
kolibri/core/deviceadmin/management/commands/vacuumsqlite.py
import logging from django.core.management.base import BaseCommand from django.db import DEFAULT_DB_ALIAS from kolibri.core.deviceadmin.utils import perform_vacuum logger = logging.getLogger(__name__) class Command(BaseCommand): help = ( "Vacuum Kolibri's SQLite database to optimize it and reduce the ....
chqiwang/convseg
server.py
# -*- coding:utf-8 -* from __future__ import print_function import StringIO from argparse import ArgumentParser import tornado.ioloop import tornado.web import tensorflow as tf from tagger import Model def load_template(): page = ''' <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <scri...
xumiao/pymonk
monk/core/constants.py
# -*- coding: utf-8 -*- """ Created on Mon Mar 24 13:23:04 2014 @author: pacif_000 """ DEFAULT_CREATOR = 'monk' DEFAULT_USER = 'tester' DEFAULT_NONE = 'None' DEFAULT_EMPTY = '' DEFAULT_FUNC = 'lambda x: None' STATUS_ACTIVE = 'active' STATUS_INACTIVE = 'inactive' STATUS_BUSY = 'busy' STATUS_WAITING =...
MaartenGr/BERTopic
setup.py
from setuptools import setup, find_packages test_packages = [ "pytest>=5.4.3", "pytest-cov>=2.6.1" ] docs_packages = [ "mkdocs>=1.1", "mkdocs-material>=4.6.3", "mkdocstrings>=0.8.0", ] base_packages = [ "numpy>=1.20.0", "hdbscan>=0.8.27", "umap-learn>=0.5.0", "pandas>=1.1.5", ...
HarrieO/PairwisePreferenceMultileave
utils/evaluate.py
# -*- coding: utf-8 -*- from numpy import log2 from random import sample import numpy as np def get_dcg(ordered_labels): return np.sum((2 ** ordered_labels - 1) / np.log2(np.arange(ordered_labels.shape[0]) + 2)) def get_idcg(complete_labels, max_len): return get_dcg(np.sort(complete_labels)[:-1 - max_len:-...
CSyllabus/webapp
backend/apps/csyllabusapi/urls.py
from django.conf.urls import url from django.contrib import admin from . import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^countries/(?P<country_id>[^/]+)/universities', views.UniversitiesViewCountry.as_view(), name='universities'), url(r'^countries/(?P<country_id>[^/]+)/cities', views....
pshc/archipelago
headers.py
from atom import * import sys HDR = new_env('HDR', None) def out(s): env(HDR).write(s) if env(GENOPTS).dumpSource: sys.stdout.write(s) def write_type(t): out(match(t, ('TPrim(PInt() or PBool())', lambda: 'int'), ('TPrim(PFloat())', lambda: 'float'), ('_', lambda: 'void *')...
rohitranjan1991/home-assistant
tests/components/camera/test_media_source.py
"""Test camera media source.""" from unittest.mock import PropertyMock, patch import pytest from homeassistant.components import media_source from homeassistant.components.camera.const import STREAM_TYPE_WEB_RTC from homeassistant.components.stream.const import FORMAT_CONTENT_TYPE from homeassistant.setup import asyn...
xuru/pyvisdk
pyvisdk/do/host_virtual_switch_simple_bridge.py
import logging from pyvisdk.exceptions import InvalidArgumentError ######################################## # Automatically generated, do not edit. ######################################## log = logging.getLogger(__name__) def HostVirtualSwitchSimpleBridge(vim, *args, **kwargs): '''A bridge that is statically b...
mmulqueen/odswriter
tests/test_via_gnumeric.py
# The MIT License (MIT) # # Copyright (c) 2014 Michael Mulqueen (http://michael.mulqueen.me.uk/) # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limi...
woshialex/diagnose-heart
CNN_B/ch4.py
import os, sys, cv2, scipy, numpy as np import dsb_utils as du, config as c, utils as u, models as m import theano, theano.tensor as T, lasagne as nn np.random.seed(1234) print 'random state seeded ch4' def process_data(): all_data = [] img_size = 256 contour_path= os.path.join(c.data_manual, 'manual_cont...
mozillazg/chendian-plus
chendian/book/models.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import, print_function, unicode_literals from django.conf import settings from django.db import models from django.utils.timezone import now from django.utils.encoding import python_2_unicode_compatible from core.db import LogicalDeleteMixi...
Arold/treethon
treethon.py
#!/usr/bin/env python3 ## [Imports] import json import os import subprocess ## [Constants] ## Question answers YES = ["y", "yes"] NO = ["n", "no"] ASK_TO_CONTINUE_MESSAGE = "Press [ENTER] to continue..." ## Json file BBB_JSON_FILE = "beaglebone-black.json" with open(BBB_JSON_FILE) as f: BBB_INFO = json.load(f...
danydoerr/large_syn_workflow
synteny_scores.py
#!/usr/bin/env python from sys import stdout, stderr, exit, maxint from optparse import OptionParser from itertools import product, combinations, izip from os.path import basename, dirname, join, isfile from random import shuffle import logging import csv import re MARKER_PAT = re.compile('^([^:]+):(\d+):(\d+)(\+$|-$...
midilab/pyMIDICapSense
pyMIDICapSense.py
import wiringpi2 import rtmidi from defines import * from config import * #import config # config.TIMEOUT def Setup(outPin, inPin, ledPin): # set Send Pin Register wiringpi2.pinMode(outPin, OUTPUT) # set receivePin Register low to make sure pullups are off wiringpi2.pinMode(inPin, OUTPUT) wiringpi2.digitalWri...
wrwrwr/scikit-gof
skgof/testsim.py
""" A primitive statistic distribution simulation. """ from __future__ import division from numpy import fromiter from numpy.random import random_sample def simulator(stat, samples, precision, rounds): """ Simulates a distribution-free statistical test to estimate its p-values. The first argument should...
tiangolo/fastapi
tests/test_tutorial/test_custom_request_and_route/test_tutorial002.py
from fastapi.testclient import TestClient from docs_src.custom_request_and_route.tutorial002 import app client = TestClient(app) def test_endpoint_works(): response = client.post("/", json=[1, 2, 3]) assert response.json() == 6 def test_exception_handler_body_access(): response = client.post("/", json...
mbiokyle29/endorse-bot
endorse/endorse_bot.py
""" endorse_bot.py author: @mbiokyle29 """ import tweepy import datetime import json import bisect import logging from endorse import Tweet log = logging.getLogger(__name__) class EndorseBot(object): def __init__(self, key, secret, query, days_back, leaderboard_size, session): self.key = key sel...
wodiesan/senior_design_spring
setup.py
from __future__ import print_function from setuptools import setup, find_packages from setuptools.command.test import test as TestCommand import io import codecs import os import sys import scrying here = os.path.abspath(os.path.dirname(__file__)) def read(*filenames, **kwargs): encoding = kwargs.get('encoding'...
Isaac-W/cpr-vision-measurement
convertdata.py
import sys import re import os import dataloader from collections import defaultdict import matplotlib.pyplot as plt FILE_PATH = 'D:\\Working\\UF\\CPR\\' #FILE_PATH = 'D:\\Working\\UF\\CPR\\fixed' print 'PID,Trial,Total,Correct,AvgDepth,AvgRecoil,AvgRate,NumBadDepth,NumBadRecoil,NumBadRate,GoodDepth,GoodRecoil,GoodRa...
stczhc/neupy
tests/algorithms/gd/test_gd_general.py
import numpy as np from neupy import algorithms, layers from data import simple_classification from base import BaseTestCase class BackPropAlgsTestCase(BaseTestCase): bp_algorithms = [ algorithms.GradientDescent, algorithms.MinibatchGradientDescent, algorithms.ConjugateGradient, ...
noblige/xm-to-spotify
xm-to-spotify.py
#!/usr/bin/python from httplib2 import Http from BeautifulSoup import BeautifulSoup import json, urllib client = Http() tracks = set() resp, data = client.request('http://www.dogstarradio.com/search_playlist.php?artist=&title=&channel=264&month=&date=&shour=&sampm=&stz=&ehour=&eampm=') html = BeautifulSoup(data) f...
CJTozer/SublimeDiffView
tests/test_bzr_helper.py
import sys import subprocess from unittest import TestCase from unittest.mock import patch diffview = sys.modules["DiffView"] BzrHelper = diffview.util.vcs.BzrHelper class test_BzrHelper(TestCase): def setUp(self): self.dummy_process = DummyProcess() def test_init(self): bzr_helper = BzrHel...
alephdata/ingestors
ingestors/tabular/ods.py
import logging from odf.teletype import extractText from odf.table import TableRow, TableCell, Table from odf.text import P from odf.namespaces import OFFICENS from followthemoney import model from ingestors.ingestor import Ingestor from ingestors.support.table import TableSupport from ingestors.support.opendoc import...
francoricci/sapspid
modules/easyspid/handlers/easyspidhandler.py
from response import ResponseObj from response import RequestHandler import traceback import globalsObj class easyspidHandler(RequestHandler): def __init__(self, *args, **kwds): super(RequestHandler, self).__init__(*args, **kwds) self.dbobjSaml = globalsObj.DbConnections['samlDb'] self.dbo...
suraj-arya/apiclient-requests
setup.py
# -*- coding: utf-8 -*- try: from setuptools import setup except ImportError: from distutils.core import setup setup( name='apiclient-requests', version='0.1.2', packages=[ 'apiclient', ], author='Suraj Arya', author_email='suraj.p.arya@gmail.com', description='A simple pyth...
skullydazed/qmk_configurator
compile.py
import json import logging from hashids import Hashids from os import chdir, mkdir from os.path import exists from redis import Redis from rq.decorators import job from subprocess import check_output, CalledProcessError, STDOUT from time import time # Objects we need to instaniate hashids = Hashids() redis = Redis() ...
peterwilletts24/Python-Scripts
plot_scripts/Rain/Diurnal/sea_diurnal_rain_plot_domain_constrain_southern__indian_ocean_large_font.py
""" Load npy xy, plot and save """ import os, sys import matplotlib matplotlib.use('Agg') # Must be before importing matplotlib.pyplot or pylab! import matplotlib.pyplot as plt import matplotlib.cm as mpl_cm from matplotlib import rc from matplotlib.font_manager import FontProperties from matplotlib import rcPa...
ulnic/weatherSensor
weatherSensor.py
#!/usr/bin/python """ Entry point into the weather sensor """ import logging.config import sys import threading import time from data.SensorHandler import SensorHandler import data.SingletonExecution from data.wifiChecker.WifiMon import WifiMon as WifiMon from data.Constants import Constant # Define the Error Log Det...
autumnz613/HangzhoulLianjia
server_chengjiao.py
# -*- coding: utf-8 -*- import re import urllib2 import httplib, urllib import random import json import sys from bs4 import BeautifulSoup import sys reload(sys) sys.setdefaultencoding("utf-8") # Some User Agents hds = [{'User-Agent': 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.6) Geck...
andres-jordan/george
george/kernels.py
# -*- coding: utf-8 -*- from __future__ import division, print_function __all__ = [ "Sum", "Product", "Kernel", "ConstantKernel", "WhiteKernel", "DotProductKernel", "RadialKernel", "ExpKernel", "ExpSquaredKernel", "CosineKernel", "ExpSine2Kernel", "Matern32Kernel", "Matern52Kernel", "SMKernel"...
djgagne/hagelslag
hagelslag/data/NCARWRF2020ModelGrid.py
from os.path import join import numpy as np from .ModelGrid import ModelGrid class NCARWRF2020ModelGrid(ModelGrid): """ Loads model output from the NCAR MMM WRF 2020 3 km real-time runs """ def __init__(self, member_name, run_date, variable, start_date, end_date, path): self.member_name = ...
xuru/pyvisdk
pyvisdk/do/host_ip_route_op.py
import logging from pyvisdk.exceptions import InvalidArgumentError ######################################## # Automatically generated, do not edit. ######################################## log = logging.getLogger(__name__) def HostIpRouteOp(vim, *args, **kwargs): '''Routing Entry Operation. Routing entries are ...
signalw/charliechat
main/migrations/0001_initial.py
# -*- coding: utf-8 -*- # Generated by Django 1.10.3 on 2016-12-11 20:22 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migratio...
IntelPython/BlackScholes_bench
bs_erf_numba_vec.py
# Copyright (C) 2017-2018 Intel Corporation # # SPDX-License-Identifier: MIT import base_bs_erf import numba as nb from math import log, sqrt, exp, erf def black_scholes_numba_opt(price, strike, t, mr, sig_sig_two): P = price S = strike T = t a = log(P / S) b = T * mr ...
alzewairi/SDN-SDSec
miniedit/test2.py
#!/usr/bin/python from mininet.net import Mininet from mininet.node import Controller, RemoteController, OVSController from mininet.node import CPULimitedHost, Host, Node from mininet.node import OVSKernelSwitch, UserSwitch from mininet.node import IVSSwitch from mininet.cli import CLI from mininet.log import setLogLe...
nyumathclinic/nyucal
tests/test_nyucal.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """Tests for `nyucal` package.""" import os.path import pytest from click.testing import CliRunner from nyucal import nyucal from nyucal import cli from difflib import unified_diff import ics import py.path import requests from requests.exceptions import ConnectionErro...
AravindGajelli90/Ems_trainingApp
employees/settings.py
""" Django settings for employees project. For more information on this file, see https://docs.djangoproject.com/en/1.7/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.7/ref/settings/ """ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) ...
squadran2003/worklog-with-database
worklog.py
import datetime import os import time from collections import OrderedDict from models import * def help_text(): """Application documentation""" clear_screen() print("*"*10) print("A GUIDE TO USING THE APP.\n" "To add a new task enter n\n" "To view previous tasks type v\n" "To search for previously s...
uncovertruth/django-horizon
tests/test_models.py
from django.conf import settings from django.contrib.auth import get_user_model from django.db import models from django.test import TestCase from horizon.models import AbstractHorizontalModel from .base import HorizontalBaseTestCase from .models import ( ConcreteModel, HorizontalMetadata, ManyModel, ...
owlsn/h_crawl
spiders/ip_proxy/ip_proxy/spiders/ip89.py
# -*- coding: utf-8 -*- import scrapy from ip_proxy.item.ip_item import IpItem from ip_proxy.utils.log import Log import time import json from ip_proxy.spiders.base import BaseSpider class Ip89Spider(BaseSpider): name = 'ip89' base_url = 'http://www.89ip.cn/' allowed_domains = ['www.89ip.cn'] start_url...
tylerlaberge/Jasper
tests/test_unit/test_runner.py
from unittest import TestCase, mock from jasper.runner import Runner import os class RunnerTestCase(TestCase): def setUp(self): self.test_directory = os.path.abspath('.\mock_features') @mock.patch('jasper.runner.Suite') def test_init(self, mock_suite): runner = Runner(self.test_directory...
hbprotoss/weii
app/widget/ContentWidget/at_widget.py
# coding=utf-8 import json from PyQt4.QtCore import * from PyQt4.QtGui import * from app.widget.ContentWidget import abstract_widget from app import logger from app import database_manager log = logger.getLogger(__name__) class AtWidget(abstract_widget.AbstractTweetContainer): def __init__(self, parent=None): ...
tylerclair/py3canvas
py3canvas/tests/services.py
"""Services API Tests for Version 1.0. This is a testing template for the generated ServicesAPI Class. """ import unittest import requests import secrets from py3canvas.apis.services import ServicesAPI class TestServicesAPI(unittest.TestCase): """Tests for the ServicesAPI.""" def setUp(self): self.c...
lmazuel/azure-sdk-for-python
azure-mgmt-compute/azure/mgmt/compute/v2017_12_01/models/virtual_machine_agent_instance_view_py3.py
# 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 ...
webisteme/instavision
instavision/curation/migrations/0007_playlist_video.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('curation', '0006_auto_20160721_1020'), ] operations = [ migrations.AddField( model_name='playlist', ...
claudiofinizio/learn-python
TDD/tests/suite_boilerplate.py
#! /usr/bin/python # -*- coding: utf-8 -*- # Python standard libraries from collections import OrderedDict import unittest # Python 3rd-part libraries import wx from wx.lib.pubsub import pub # Project modules # Modules only for debugging from pprint import pprint class WxApp(wx.App): def OnInit(self): ...
MoonHyuk/acmicpc.cc
application.py
from collections import OrderedDict import datetime import json import os from multiprocessing import Process import urllib.request from bs4 import BeautifulSoup from flask import Flask, render_template, request, abort, jsonify from flask_debugtoolbar import DebugToolbarExtension from flask_sslify import SSLify import...
holdlg/pyeve
app/tool/fire_upload.py
from flask import current_app as app from eve.io.media import MediaStorage class FireMediaStorage(MediaStorage): def get(self, id_or_filename, resource=None): uploads = app.data.driver.db["uploads"] print(id_or_filename) def put(self, content, filename=None, content_type=None, resource=None)...
garyelephant/snippets
python/http_server/simple_httpserver.py
""" A simple Python HTTP server that supports a GET that echoes some request data and a POST that reads a request body, parses it as JSON and reponses with part of the data Raw """ from BaseHTTPServer import BaseHTTPRequestHandler import urlparse, json class GetHandler(BaseHTTPRequestHandler): def do_GET(self):...
monetate/sqlalchemy
test/orm/test_inspect.py
"""test the inspection registry system.""" from sqlalchemy import exc from sqlalchemy import ForeignKey from sqlalchemy import inspect from sqlalchemy import testing from sqlalchemy.orm import aliased from sqlalchemy.orm import class_mapper from sqlalchemy.orm import relationship from sqlalchemy.orm import Session fro...
ns-phennessy/Arcbot
tests/core/test_command.py
import unittest from bolt.core.command import Command, RegexCommand, ParseCommand class TestCommand(unittest.TestCase): def dummycallback(self): pass def test_command_matches(self): command = Command("test command", self.dummycallback) self.assertTrue(command.matches("test command")) ...
GRIFFINCollaboration/beamCompanionExplorer
data/parseMass.py
import json def generateMassTable(): ''' generate a mass table for the beam companion explorer. writes and returns the mass table, a list of dicts keyed as [Z]['A']. ''' # handy variables lineLength = 124 headerLength = 39 massTable = [] fid = open("mass.mas12", "r") # fast fo...
coldfusion39/domi-owned
domi_owned/bruteforce.py
# Copyright (c) 2017, Brandan Geise [coldfusion] # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, ...
xudesheng/stock36
stocks/pricejohn.py
#!/usr/bin/env python from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.common.exceptions import NoSuchElementException import time import os.path import sys import pandas as pd PACKAGE_PARENT = '..' SCRIPT_DIR = os.path.dirname(os.path.realpath(os.path.join(os.getcwd(), os....
MilyMilo/sci-organizer
groups/migrations/0002_auto_20170912_1958.py
# -*- coding: utf-8 -*- # Generated by Django 1.11.5 on 2017-09-12 19:58 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('groups', '0001_initial'), ] operations = [ migrations.AlterModelOptions( ...