repo_name
stringlengths
5
104
path
stringlengths
4
248
content
stringlengths
102
99.9k
kquick/Thespian
thespian/system/transport/MultiprocessQueueTransport.py
"""Uses the python multiprocess.Queue as the transport mechanism. Queues are multi-producer/multi-consumer objects. In this usage, there will be only one consumer (the current Actor) although there may be multiple producers (any other actor sending to this actor); this actor has a single Queue for all incoming messag...
ChenglongChen/Kaggle_HomeDepot
Code/Chenglong/feature_vector_space.py
# -*- coding: utf-8 -*- """ @author: Chenglong Chen <c.chenglong@gmail.com> @brief: vector space based features - char/word based ngram LSA & cosine similarity - char/word based ngram TFIDF & cosine similarity - cooccurrence & pairwise LSA - standalone and pairwise TSNE (memory error, us...
anarey/mysite
django-polls/setup.py
import os from setuptools import setup with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme: README = readme.read() # allow setup.py to be run from any path os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir))) setup( name='django-polls', version='0.1', ...
dborzov/fredholm
fredholm/trivia.py
import os import matplotlib.pyplot as pyplot from config import * def barify_list(list): outcome=[] for record in list: outcome.append(record-dx_TAKEN/2.) return outcome def satisfies(a,b): if a['dx']==b['dx'] and a['L']==b['L'] and a['iteration']==b['iteration']: return True else:...
failgod-marcus/failCogs
wikipedia/wikipedia.py
import os import aiohttp import discord from discord.ext import commands from cogs.utils import checks from __main__ import send_cmd_help from .utils.dataIO import dataIO class Wikipedia: """ The Wikipedia Cog """ def __init__(self, bot): self.bot = bot self.settings_folder = "data/wik...
cletusw/goal-e
misc/readCurrentSpeedM2.py
import serial import sys import param_vars ser2 = serial.Serial('/dev/ttyPCH2',38400) def serialSend2(send): for i in send: ser2.write(chr(i)) def serialRead2(read): serialSend2(read) data=[] for i in range(6): data.append(ser2.read()) return data def readCurrent...
kyleconroy/random-letter
scripts/generate.py
from lxml import etree root = etree.parse("scripts/alpha.svg").getroot() alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" header = """<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"> <svg version="1.1" xmlns="http://www.w3.org/2000/svg" xml...
ArcticCore/arcticcoin
qa/rpc-tests/maxblocksinflight.py
#!/usr/bin/env python2 # # Distributed under the MIT/X11 software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # from test_framework.mininode import * from test_framework.test_framework import BitcoinTestFramework from test_framework.util import * import logging ...
tomer8007/kik-bot-api-unofficial
examples/legacy/cmdline_legacy.py
import sys import time from argparse import ArgumentParser from kik_unofficial.client_legacy import KikClient def execute(cmd=sys.argv[1:]): parser = ArgumentParser(description="Unofficial Kik api") parser.add_argument('-u', '--username', help="Kik username", required=True) parser.add_argument('-p', '--p...
freecode/FVB-Modules
MD5Module.py
from org.freecode.irc.votebot.api import ExternalModule import hashlib class MD5Module(ExternalModule): def getName(self): return 'md5' def processMessage(self, privmsg): msg = privmsg.getMessage()[5:] m = hashlib.md5() m.update(msg.encode('utf-8')) print msg ...
bharadwajyarlagadda/korona
korona/templates/html/tags/iframe.py
# -*- coding: utf-8 -*- """<iframe> template""" from ..environment import env iframe = env.from_string("""\ <iframe {% if src -%} src="{{ src }}" {% endif -%} {% if width -%} width="{{ width }}" {% endif -%} {% if height -%} height="{{ height }}" {% endif -%} {% if align -%} align="{{ align }}...
thijsmie/tantalus
src/tantalus/appfactory/flash.py
"""Convenience wrappers for flask.flash() with special-character handling. With PyCharm inspections it's easy to see which custom flash messages are available. If you directly use flask.flash(), the "type" of message (info, warning, etc.) is a string passed as a second argument to the function. With this file PyCharm ...
facebookresearch/ParlAI
parlai/utils/curated_response.py
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import random """ Functions to generate safe curated response that repalce an Agent's main response. """ ############...
windprog/icmp-tunnel
client_s.py
#!/usr/bin/env python import os, sys import hashlib import getopt import fcntl import icmp_s import time import struct import socket, select import globalvar import ctypes api = ctypes.CDLL('./s.so') class Tunnel(): def create(self): self.tfd = os.open("/dev/net/tun", os.O_RDWR) ifs = fcntl.ioc...
flyingbanana1024102/transmission-line-simulator
src/models/circuitelement.py
# # Transmission Line Simulator # # Author(s): Jiacong Xu # Created: Jul-3-2017 # import numpy as np from util.constants import * class CircuitElement(object): """ An abstract class that contains basic information on elements on a circuit. position: the position of this circuit element along the c...
Diti24/python-ivi
ivi/agilent/agilentU2000B.py
""" Python Interchangeable Virtual Instrument Library Copyright (c) 2015-2016 Alex Forencich 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...
yayoiukai/signalserver
fileuploads/migrations/0028_row_frame_number.py
# -*- coding: utf-8 -*- # Generated by Django 1.10.dev20160107235441 on 2016-08-10 17:44 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('fileuploads', '0027_auto_20160701_0010'), ] operations = [ ...
laslabs/Python-Carepoint
carepoint/models/cph/fdb_price.py
# -*- coding: utf-8 -*- # Copyright 2015-TODAY LasLabs Inc. # License MIT (https://opensource.org/licenses/MIT). from carepoint import Carepoint from sqlalchemy import (Column, DateTime, Numeric, String, ) class FdbPrice(...
scattm/DanceCat
migrations/versions/b85f81a9f3cf_.py
"""Add lastUpdatedColumn to Schedule. Revision ID: b85f81a9f3cf Revises: 15b861423bc6 Create Date: 2016-08-01 22:40:16.978187 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = 'b85f81a9f3cf' down_revision = '15b861423bc6' def upgrade(): """Add lastUpdatedCo...
tzpBingo/github-trending
codespace/python/tencentcloud/afc/v20200226/afc_client.py
# -*- coding: utf8 -*- # Copyright (c) 2017-2021 THL A29 Limited, a Tencent company. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses...
paolo215/BankManager
BankManager_Python/BankManager.py
from Account import Account from Transaction import Transaction import datetime class BankManager(object): def __init__(self): """ Instantiates a BankManager which manages creation of accounts and any transactions """ self.account_data = {} self.transaction_data = {} de...
xuru/pyvisdk
pyvisdk/do/vim_esx_cl_inetworkvswitchdvsvmwarelist_vds.py
import logging from pyvisdk.exceptions import InvalidArgumentError # This module is NOT auto-generated # Inspired by decompiled Java classes from vCenter's internalvim25stubs.jar # Unless states otherside, the methods and attributes were not used by esxcli, # and thus not tested log = logging.getLogger(__name__) de...
LuckyGeck/YcmdCompletion
Completion.py
# -*- coding: utf8 -*- from .ycmd import http_client, exceptions from base64 import b64decode from json import loads from threading import Thread import os import sublime import sublime_plugin import subprocess from .lang_map import LANG_MAP PACKAGE_NAME = os.path.splitext(os.path.basename(os.path.dirname(__file__))...
kkappel/web2py-community
languages/pl.py
# -*- coding: utf-8 -*- { '!langcode!': 'pl', '!langname!': 'Polska', '"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': '"Uaktualnij" jest dodatkowym wyrażeniem postaci "pole1=\'nowawartość\'". Nie możesz uaktualnić lub usunąć wyników z JOIN:', '%s %%{ro...
simonmonk/clever_card_kit
03_lock.py
#!/usr/bin/env python import RPi.GPIO as GPIO import SimpleMFRC522 from squid import * from button import Button import pickle led = Squid(18, 23, 24) button = Button(17) reader = SimpleMFRC522.SimpleMFRC522() mode = 'LISTEN' allowed_tags = [] def handle_listen_mode(): global mode, allowed_tags led.set_col...
23maverick23/sublime-jekyll
jekyll.py
# -*- coding: utf-8 -*- import imghdr import io import os import re import sublime import sublime_plugin import sys import traceback import uuid import shutil from datetime import datetime from functools import wraps try: import simple_json as json except ImportError: import json ## **********************...
hippke/communication
part1_figure_8_b.py
from PyCom import holevo_perfect, holevo_thermal, photons_received, Q import numpy from math import log, log2, pi from matplotlib import pyplot as plt import matplotlib.patches as patches from astropy.constants import c, G, M_sun, R_sun, au, L_sun, pc from astropy import units as u path = '' def sky_background(wave...
alphagov/performanceplatform-collector
tests/performanceplatform/collector/webtrends/test_keymetrics.py
import unittest from performanceplatform.collector.webtrends.keymetrics import( Collector, V2Parser, V3Parser) import performanceplatform from mock import patch import requests from hamcrest import assert_that, equal_to, has_entries from nose.tools import assert_raises import datetime import pytz from tests.perform...
UpOut/objectify
objectify/dynamic/__init__.py
# coding: utf-8 from ..prop.base import ObjectifyProperty from ..prop.boolean import Boolean from ..prop.number import Integer,Float,Long from ..prop.string import Unicode, String from ..model.dict import ObjectifyDict from ..model.list import ObjectifyList __all__ = ['DynamicProperty','DynamicList','DynamicDict'] ...
evidation-health/ContinuousTimeMarkovModel
src/ContinuousTimeMarkovModel/samplers/forwardX.py
from pymc3.core import * from pymc3.step_methods.arraystep import ArrayStepShared from pymc3.theanof import make_shared_replacements from pymc3.distributions.transforms import logodds from ContinuousTimeMarkovModel.transforms import * from theano import function #import ContinuousTimeMarkovModel.cython.forwardX_cytho...
andrei-alpha/seep-analytics
master/admin.py
import copy import json import os import re import requests import select import socket import sys import subprocess import time class Globals: startTimestamp = None adminCurrentTask = '' adminProgress = 0 expectedTime = None baseProgress = None allocatedPercentage = None schedulerPort = No...
creativcoder/pyjudge
CodinCloud/tests/main.py
#! /usr/bin/python import os import threading import time import subprocess import unittest class SubprocessTimeoutError(RuntimeError): pass class CommandWithTimeoutTest(unittest.TestCase): def test_natural_success(self): """Try one that should complete naturally and successfully""" self.assertEqual...
Bloblblobl/Rumble-CLI
cli.py
""" Command Line Interface for Rumble-Server If you provide a username and password, it will log you into the server If you provide a handle as well, it will register you to the server instead """ import argparse import json import os import sys from datetime import datetime, timedelta from rumble_client.client import ...
LeoKotschenreuther/diversifiedblockfolio
tests/blockfolio_test.py
import coinmarketcap import pytest from pytest import approx from .context import diversifiedblockfolio as diblo from .test_utils import buys_equal, holdings_equal buy_calls = [] @pytest.fixture(params=[ [], [{}], [{'symbol': ''}], ]) def bad_asset_allocation(request): return request.param @pytest...
lavizhao/insummer
code/statistic/table_show.py
#!/usr/bin/python3 #coding=utf-8 ''' 这个主要是将抽取的语料与duc语料的整体统计特征做一个直观的输出比较, 整体代码糙的不行,全赖问题结构固定,先这么将就着看吧。 ''' import pickle import sys from question_table import question_table sys.path.append('..') from insummer.read_conf import config question_conf = config('../../conf/question.conf') fil_path = question_conf['filter...
evilsoapbox/GlowColors
glowcolors/settings.py
"""Settings file with protocol-specific settings and variables. This module holds the settings needed to construct messages based on the GWtS protocol. """ # Module imports # NONE # Constants PREFIXES = { 'SHOW': 0x90, 'SYSTEM': 0x55, } COLORS = { 'BOTH': { 'INACTIVE': 0x60, 'BLUE': 0x61...
iRapha/deep-carver
saliency_map.py
#!/usr/bin/python # -*- coding: utf-8 -*- """ Saliency Map. """ import math import itertools import cv2 as cv import numpy as np from utils import Util class GaussianPyramid: def __init__(self, src): self.maps = self.__make_gaussian_pyramid(src) def __make_gaussian_pyramid(self, src): # gaus...
timj/scons
bench/timeit.py
#! /usr/bin/env python """Tool for measuring execution time of small code snippets. This module avoids a number of common traps for measuring execution times. See also Tim Peters' introduction to the Algorithms chapter in the Python Cookbook, published by O'Reilly. Library usage: see the Timer class. Command line ...
TheBrane/sodi-data-acquisition
NASA Web Of Sciences/convert_articles.py
import json import csv import numpy as np import pandas as pd # General helper function def parse_author(author): # The form is LastName, FirstName or LastName, FirstName Middle # The middle name will remain part of the first name author = author.strip() last_name = author.split(',')[0].strip().title() first_name...
aledruetta/vocapy
tools/db/populate_db.py
#! /usr/bin/env python3 import sqlite3 as sql import csv _database = '../../database.db' def populate_db(): """ Populates database.db para pruebas. """ words = list() with open('dict.txt', newline='') as csvfile: for row in csv.reader(csvfile): word, last_time, attempts, gu...
dmccloskey/SBaaS_models
SBaaS_models/models_BioCyc_io.py
#SBaaS from .models_BioCyc_query import models_BioCyc_query from SBaaS_base.sbaas_template_io import sbaas_template_io from .models_BioCyc_dependencies import models_BioCyc_dependencies # Resources from io_utilities.base_importData import base_importData from io_utilities.base_exportData import base_exportData from dd...
Samuel-L/cli-ws
web_scraper/core/html_fetchers.py
import os import sys sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) import requests def fetch_html_document(url, user_agent='cli-ws/1.0'): """Request html document from url Positional Arguments: url (str): a web address (http://example.com/) Keyword Arguments: ...
affinelayer/pix2pix-tensorflow
tools/dockrun.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import sys import shlex # from python 3.3 source # https://github.com/python/cpython/blob/master/Lib/shutil.py def which(cmd, mode=os.F_OK | os.X_OK, path=None): """Given a command, mode, and a P...
muts/qbr
src/qbr.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Filename : qbr.py # Author : Kim K # Created : Tue, 26 Jan 2016 # Last Modified : Sun, 31 Jan 2016 from sys import exit as Die try: import sys import kociemba import argparse from combiner import combine from video import webcam ...
naiquevin/jinger
jinger/site.py
""" All code dealing with the directory structure for a jinger site. """ import os import logging from jinger import config logger = logging.getLogger('jinger') def createdir(path, dirname): path = os.path.join(path, dirname) if os.path.exists(path): raise Exception("A directory by name %s already e...
PWRxPSYCHO/SmartMirror
Mirror.py
from __future__ import print_function import datetime import json import os import time import tkinter.font import traceback from tkinter import * from requests import get import feedparser import httplib2 import requests from PIL import ImageTk, Image from apiclient import discovery from forecastiopy import * from o...
nanodan/branca
branca/__init__.py
# -*- coding: utf-8 -*- from __future__ import absolute_import import sys import branca.colormap as colormap import branca.element as element from ._version import get_versions __version__ = get_versions()['version'] del get_versions if sys.version_info < (3, 0): raise ImportError( """You are running br...
mindis/canteen
canteen_tests/test_core/test_runtime.py
# -*- coding: utf-8 -*- ''' canteen core runtime tests ~~~~~~~~~~~~~~~~~~~~~~~~~~ tests canteen's runtime core, which is responsible for pulling the app together with glue and spit. :author: Sam Gammon <sam@keen.io> :copyright: (c) Keen IO, 2013 :license: This software makes use of the MIT Open Source...
mpetyx/energagement
energagement/myapp/migrations/0002_auto_20150622_1146.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('myapp', '0001_initial'), ] operations = [ migrations.AddField( model_name='streetlighting', name='co...
peterhogan/python
collatz.py
from time import sleep def collatz(): entry = input("Please enter an integer: ") steps = 0 while entry != 1: if entry % 2 == 0: entry = entry/2 else: entry = (entry*3)+1 steps += 1 print(entry) print("Done! In %d steps." % steps) def collatz_iter(limit): for i in range(2,limit+1): j = i steps =...
rddimon/test-product-scanner
apps/payment/migrations/0002_auto_20171027_2310.py
# -*- coding: utf-8 -*- # Generated by Django 1.11.6 on 2017-10-27 20:10 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('payment', '0001_initial'), ] operations = [ migrations.RemoveField( ...
jdegene/Various-Python-3.x
mostword.py
# -*- coding: utf-8 -*- #Creates a List, which words are most often in the ID3Tags of a folder of #mp3s.... script includes all subfolders import os, re, operator from mutagen.mp3 import EasyMP3 as MP3 inFol = ".../Music/" #folder that contains all mp3, subfolders allowed #Write all filenames from a folder and its ...
blurrcat/cookiecutter-flask
{{cookiecutter.repo}}/tests/conftest.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import pytest from {{cookiecutter.app}}.app import create_app TEST_CONFIG = { 'DEBUG': True, 'TESTING': True, 'SQLALCHEMY_DATABASE_URI': 'sqlite://', 'WTF_CSRF_ENABLED': False, } @pytest.yield_fixture def app(): _app = create_app(**TEST_CONFIG) c...
ransage/csv2docx
test/__init__.py
import sys err = sys.stderr initialized = False def setup_package(): # or setup, setUp, or setUpPackage global initialized initialized = True err.write('\npkg_setup...\n') def teardown_package(): # or teardown, tearDown, tearDownPackage global initialized initial...
MosheBerman/oop-1
1.1/Rational.py
''' Moshe Berman Professor Zhou CISC 3150 Spring 2014 Assignment 1.1 ''' ''' This class represents a rational number. ''' class Rational(object): def __init__(self, numerator, denominator): super(Rational, self).__init__() self.numerator = numerator self.denominator = denominator # Adds the supp...
Kinnay/NintendoClients
tests/nex/test_kerberos.py
from nintendo.nex import kerberos, settings, common def test_key_derivation_old(): keyderiv1 = kerberos.KeyDerivationOld() keyderiv2 = kerberos.KeyDerivationOld(5, 10) assert keyderiv1.derive_key(b"password", 123456) == bytes.fromhex("bd9d83b0d4102b72de3e14f44938c989") assert keyderiv2.derive_key(b"passwor...
qiyuangong/Relational_Transaction_Anon
RT_ANON.py
#!/usr/bin/env python #coding=utf-8 import pdb import copy import heapq from models.cluster import Cluster from models.gentree import GenTree from apriori_based_anon import apriori_based_anon import random import time import operator __DEBUG = False THESHOLD = 0.65 # att_tree store root node for each att ATT_TREES =...
kivy/pyobjus
tests/test_ns_mutable_array.py
import unittest from pyobjus import autoclass NSMutableArray = None NSString = None test_array = None Str = lambda x: NSString.stringWithUTF8String_(x) class NSMutableArrayTest(unittest.TestCase): def setUp(self): global NSString, NSMutableArray, test_array NSMutableArray = autoclass('NSMutableAr...
hydralabs/plasma
plasma/test/__init__.py
# Copyright The Plasma Project. # See LICENSE.txt for details. """ Tests for Plasma. .. versionadded:: 0.1 """ import unittest def failUnlessIdentical(self, first, second, msg=None): """ Fail the test if C{first} is not C{second}. This is an obect-identity-equality test, not an object equality (i.e....
kahst/AcousticEventDetection
AED_train.py
#!/usr/bin/env python print "HANDLING IMPORTS..." import sys import os import time import operator import math import numpy as np import matplotlib.pyplot as plt import cv2 from scipy import interpolate from sklearn.utils import shuffle from sklearn.metrics import confusion_matrix import itertools import pickle i...
kirsty-tortoise/mathsmap
mathsmap/app.py
""" Main application file Defines a control class then makes a controller that sets up the window. """ import tkinter as tk from mathsmap.home import Home from mathsmap.explore import Explore from mathsmap.new_map import NewMap class Control: """ A control class which switches between screens. """ def...
Valuehorizon/valuehorizon-forex
forex/migrations/0008_auto_20150526_1310.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('forex', '0007_auto_20150526_1255'), ] operations = [ migrations.AddField( model_name='currency', nam...
nadirizr/oknesset_analyzer
analyzer/db_models/agenda.py
from django.db import models from base import BaseModel from member import Member from party import Party from vote import Vote class Agenda(BaseModel): name = models.CharField(max_length=1000) description = models.TextField() public_owner_name = models.CharField(max_length=1000) members = models.ManyToManyF...
joelfiddes/topoMAPP
getERA/eraRetrievePLEVEL_pl.py
#!/usr/bin/env python from datetime import datetime, timedelta from collections import OrderedDict import calendar import sys from ecmwfapi import ECMWFDataServer from dateutil.relativedelta import * from retrying import retry import logging import glob server = ECMWFDataServer() def retrieve_interim(config,eraDir...
Azure/azure-sdk-for-python
sdk/consumption/azure-mgmt-consumption/azure/mgmt/consumption/aio/operations/_operations.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 may ...
ungarj/mapchete-safe
test/testdata/example_process.py
#!/usr/bin/env python """Example process file.""" from mapchete import MapcheteProcess import numpy as np class Process(MapcheteProcess): """Main process class.""" def __init__(self, **kwargs): """Process initialization.""" # init process MapcheteProcess.__init__(self, **kwargs) ...
athre0z/wasm
wasm/types.py
"""Defines a simple, generic data (de)serialization mechanism.""" from __future__ import print_function, absolute_import, division, unicode_literals from .compat import add_metaclass, byte2int, indent, deprecated_func import collections import logging import struct as pystruct logger = logging.getLogger() class Wa...
Ahsanul08/ImdbScraper
imdb/items.py
# -*- coding: utf-8 -*- # Define here the models for your scraped items # # See documentation in: # http://doc.scrapy.org/en/latest/topics/items.html import scrapy import re from scrapy.loader.processors import Join, MapCompose, TakeFirst, Compose from w3lib.html import remove_tags class ImdbItem(scrapy.Item): ...
MiracleWong/PythonBasic
PyH/python_file.py
#!/usr/local/bin/python # -*- coding: utf-8 -*- from pyh import * list=[['192.20.3.58','Tomcat-data-alarm-5201','program1.xml', 'HelloWord', 'HelloPython'],['','','program2.xml', 'HelloWord', 'HelloPython'],['','','program3.xml', 'HelloWord', 'HelloPython'],['192.20.3.61','Tomcat-data-alarm-5201','program4.xml', 'Hello...
lucfra/RFHO
tests/test_optimizers.py
import unittest from rfho.utils import as_list from rfho.optimizers import * from tests.test_base import iris_logistic_regression class TestOptimizers(unittest.TestCase): def _test_forward_automatic_d_dynamic_d_hyper(self, method, optimizer_hypers=None, **opt_k...
tedunderwood/GenreProject
python/piketty/refine_fiction.py
# refine fiction import SonicScrewdriver as utils def passfilter(genrestring): fields = genrestring.split(';') if "Autobiography" in fields or "Biography" in fields: return False else: return True rows19c, columns19c, table19c = utils.readtsv('/Volumes/TARDIS/work/metadata/19cMetadata.tsv') rows20c, columns2...
ryanraaum/oldowan.genbank
tests/test_parse_genbank.py
from oldowan.genbank import parse_genbank from oldowan.genbank.parse import extract_source_feature from oldowan.genbank.parse import extract_features SINGLE_ENTRY = """LOCUS NM_001071821 318 bp mRNA linear PRI 09-OCT-2006 DEFINITION Pan troglodytes somatic cytochrome c (CYCS), mRNA. ACCESSIO...
mtihlenfield/pybak
pybak/tests/mod/test_zipbackup.py
import unittest import os import shutil import zipfile from tempfile import gettempdir import pybak.mod.bak as bak # using the temp for testing because it will exist on all systems show # trying to create a backup with it shouldn't throw an error TMPDIR = gettempdir() TEST_FILES = [ TMPDIR + "/dir1/test.txt", ...
juhnowski/FishingRod
production/pygsl-0.9.5/pygsl/permutation.py
# Author : Fabian Jakobs """ This chapter describes functions for creating and manipulating permutations. A permutation p is represented by an array of n integers in the range 0 .. n-1, where each value p_i occurs once and only once. The application of a permutation p to a vector v yields a new vector v' where v'_i ...
FrostLuma/Mousey
mousey/utils/time.py
# -*- coding: utf-8 -*- """ MIT License Copyright (c) 2017 - 2018 FrostLuma 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, c...
sdispater/eloquent
eloquent/orm/relations/morph_one.py
# -*- coding: utf-8 -*- from .morph_one_or_many import MorphOneOrMany class MorphOne(MorphOneOrMany): def get_results(self): """ Get the results of the relationship. """ return self._query.first() def init_relation(self, models, relation): """ Initialize the ...
LINKIWI/linkr
api/misc.py
import os import git import config import util.response from linkr import app from uri.misc import * from util.decorators import * @app.route(ConfigURI.get_path(), methods=ConfigURI.methods) @require_form_args() @require_login_api(admin_only=True) @require_frontend_api @api_method @time_request('latency.api.misc.co...
fedora-python/portingdb
dnf-plugins/py3query.py
""" DNF plugin for getting the Python 3 porting status. Put this in your DNF plugin directory, then run: $ dnf --enablerepo=rawhide --enablerepo=rawhide-source py3query -o fedora.json This will give you a file "fedora.json" with information for portingdb. """ from __future__ import print_function import sys im...
jeeyoungk/exercise
interview/kmeans/kmeans.py
import json import random # random.seed(1) # deterministic behavior def extract_coord(row): coordinates = row['coordinates'] return (coordinates['lat'], coordinates['lng']) def obtain_data(): with open('transactions.json', 'rb') as f: parsed = json.load(f) coords = map(extract_coord, parsed) ...
sergey-dryabzhinsky/dedupsqlfs
dedupsqlfs/db/mysql/table/hash_sizes.py
# -*- coding: utf8 -*- __author__ = 'sergey' from dedupsqlfs.db.mysql.table import Table class TableHashSizes( Table ): _table_name = "hash_sizes" def create( self ): cur = self.getCursor() # Create table cur.execute( "CREATE TABLE IF NOT EXISTS `%s` (" % self.getName()...
wavefancy/BIDMC-PYTHON
Hapmix/HapmixResultsSummary/HapmixResultsSummary.py
#!/usr/bin/env python ''' HapmixResultsSummary @Author: wavefancy@gmail.com @Version: 1.0 @Algorithms: ''' import sys from signal import signal, SIGPIPE, SIG_DFL signal(SIGPIPE,SIG_DFL) #prevent IOError: [Errno 32] Broken pipe. If pipe closed by 'head'. def help(): sys.stderr.write(''' ----...
ThomasYeoLab/CBIG
stable_projects/fMRI_dynamics/Kong2021_pMFM/part2_pMFM_control_analysis/Schaefer100_parcellation/scripts/CBIG_pMFM_step1_training_Schaefer100.py
# /usr/bin/env python ''' Written by Kong Xiaolu and CBIG under MIT license: https://github.com/ThomasYeoLab/CBIG/blob/master/LICENSE.md ''' import os import numpy as np import time import torch import CBIG_pMFM_basic_functions as fc import warnings def get_init(myelin_data, gradient_data, highest_order, init_para):...
california-civic-data-coalition/django-calaccess-processed-data
calaccess_processed_campaignfinance/proxies/transactions.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Proxy models for OCD Filing related models.. """ from __future__ import unicode_literals # Models from calaccess_processed.proxies import OCDProxyModelMixin from opencivicdata.campaign_finance.models import Transaction, TransactionIdentifier # Managers from calaccess_...
martinohanlon/minecraft-rastrack
rastrackInfo.py
#www.stuffaboutcode.com #Raspberry Pi, Minecraft API - the basics #import the minecraft.py module from the minecraft directory import minecraft.minecraft as minecraft #import minecraft block module import minecraft.block as block #import time, so delays can be used import time #import json, to load rastrack data impor...
philippaborrill/planets
plot.py
import numpy import glob import matplotlib.pyplot filenames = glob.glob('data/inflammation*.csv') #print(filenames) filenames = filenames[0:3] print(filenames) def analyze(filename): print(filename) data = load_data(filename) #plot(data) detect_problems(data) def load_data(filename): return numpy...
best-coloc-ever/globibot
bot/src/globibot/lib/decorators/validator.py
COMMAND_VALIDATORS_ATTR = 'validators' def validator(validate, *hooks, **kwargs): def wrapped(func): def call(plugin, message, *args, **kwargs): hook_results = [ hook(plugin.bot, message) for hook in hooks ] if all(hook_results): ...
reverie/jotleaf.com
jotleaf/main/pusher_helpers.py
import logging import functools logger = logging.getLogger('django.request') def make_pusher(): from main.api2 import APIEncoder from pusher2 import Pusher from django.conf import settings return Pusher( settings.PUSHER_APP_ID, settings.PUSHER_KEY, settings.PUSHER_SECRET, ...
SensibilityTestbed/clearinghouse
common/api/keydb.py
""" <Program> keydb.py <Started> 29 June 2009 <Author> Justin Samuel <Purpose> This is the API that should be used to interact with the Key Database. Functions in this module are the only way that other code should interact with the Key Database. The init_keydb() method must be called before ca...
thiagopena/djangoSIGE
djangosige/apps/fiscal/forms/nota_fiscal.py
# -*- coding: utf-8 -*- from django import forms from django.forms import inlineformset_factory from django.utils.translation import ugettext_lazy as _ from djangosige.apps.fiscal.models import NotaFiscalSaida, NotaFiscalEntrada, AutXML, ConfiguracaoNotaFiscal, TP_AMB_ESCOLHAS, MOD_NFE_ESCOLHAS from djangosige.apps.c...
kretusmaximus/Olga
olga/brain/unlearn_adapter.py
#!/usr/bin/env python # coding=utf-8 """ :author: Konrad Podlawski <kpodlawski@kretstudios.pl> """ from __future__ import unicode_literals from chatterbot.logic.logic_adapter import LogicAdapter class UnlearnAdapter(LogicAdapter): """ The UnlearnAdapter makes the chatterbot forget responses. """ def ...
Siecje/debt
api/tests/test_users.py
import json from django.contrib.auth import get_user_model from django.urls import reverse from rest_framework import status from rest_framework.authtoken.models import Token from rest_framework.test import APIClient, APITestCase from api.serializers import UserSerializer User = get_user_model() class UserTests(A...
danrex/django-riv
tests/polls/models.py
import datetime from django.contrib.auth.models import User from django.db import models class Tag(models.Model): name = models.CharField(max_length=100) class Poll(models.Model): question = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') tags = models.ManyToManyFiel...
xiezhq-hermann/LeetCode-in-Python
src/knight_probability_chessboard_688.py
class Solution(object): def knightProbability(self, N, K, r, c): """ :type N: int :type K: int :type r: int :type c: int :rtype: float """ import copy if K == 0: return 1 move = {(2,1), (1,2), (-1,2), (-2,1), (2,-1), (1,-2),...
myaser/DAPOS_corpus_browser
corpus_browser/browser/views.py
from django.shortcuts import render from query_processor import QueryProcessor from query_processor.probability import make_ngram_estimator from query_processor.collocationer import Collocationer from query_processor.ngram import NGram from indexer.models import MainIndex from forms import SearchForm import logging l...
mrHickman/CS480_IBTL_Compiler
CS480_Compiler/src/lexicalAnalyzer.py
''' Created on Jan 25, 2014 @author: mr_hickman Description: This is the primary tokenizing class. Using scanner to clean up the input from the file it traverses our dfa model to determine what attributes a token requires and produces the tokens. ''' ''' regular expression for each of the strings = ^"[...
algochecker/algochecker-engine
contrib/collect.py
#!/usr/bin/env python3 import argparse import json import os import sys from time import sleep import redis sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), '..')) from worker_conf import REDIS_CONF class EvaluationFetchTimeout(Exception): pass rs = redis.Redis(**REDIS_CONF) def fet...
John-Lin/invoice-net
website.py
#!/usr/bin/env python # -*- coding: UTF-8 -*- from bottle import route, run, template, view #from bottle import jinja2_view from invoice_prize import * @route('/hello') def hello(): return "Hello World!" @route('/invoice') @view('invoice_template') def invoive(): (results, date) = get_result() date = date...
mozman/ezdxf
src/ezdxf/path/converter.py
# Copyright (c) 2020-2022, Manfred Moitzi # License: MIT License from typing import ( List, Iterable, Union, Tuple, Optional, Dict, Callable, Type, TypeVar, ) from functools import singledispatch, partial import enum from ezdxf.math import ( ABS_TOL, Vec2, Vec3, NULLV...
hdemers/datascience
setup.py
from os.path import join, dirname from setuptools import setup, find_packages # IMPORTANT: updates to the following must also be done in __init__.py. __title__ = "datascience" __version__ = "0.1.0" __author__ = "Hugues Demers" __email__ = "hdemers@gmail.com" __copyright__ = "Hugues Demers" __license__ = "MIT" setup(...
aarcro/helga-versionone
helga_versionone/tests/test_things.py
from mock import patch from pretend import stub from .util import V1TestCase, writeable_settings_stub # Tests for both tests and tasks as they are the same code path def make_thing(name, num, status_name, status_order): return stub( Name='{0}-{1}'.format(name, num), url='http://example.com/{0}'....