repo_name
stringlengths
5
104
path
stringlengths
4
248
content
stringlengths
102
99.9k
NendoTaka/CodeForReference
Python/Sort/CountingSort.py
def countingsort(sortablelist): maxval = max(sortablelist) m = maxval + 1 count = [0] * m # init with zeros for a in sortablelist: count[a] += 1 # count occurences i = 0 for a in range(m): # emit for c in range(count[a]): # - emit 'count[a]' c...
josiah-wolf-oberholtzer/supriya
supriya/ugens/delay.py
import collections from supriya import CalculationRate from supriya.synthdefs import PureUGen, UGen class AllpassC(PureUGen): """ A cubic-interpolating allpass delay line unit generator. :: >>> source = supriya.ugens.In.ar(bus=0) >>> allpass_c = supriya.ugens.AllpassC.ar(source=source) ...
theonion/djes
djes/mapping.py
from django.db import models from django.db.models.fields.related import ManyToOneRel, ForeignObjectRel from elasticsearch_dsl.mapping import Mapping from elasticsearch_dsl.field import Field from djes.conf import settings FIELD_MAPPINGS = { "AutoField": {"type": "long"}, "BigIntegerField": {"type": "long"},...
baptistemanteau/colorharmonies
colorharmonies/tests/test_colorharmonies.py
# -*- coding: utf-8 -*- import unittest from ..colorharmonies import Color, complementaryColor, triadicColor, splitComplementaryColor, tetradicColor, analogousColor, monochromaticColor class colorsHarmonies(unittest.TestCase): # Obtain the complementary color of a color def test_complementaryColor(self): MagentaCo...
pajlada/pajbot
pajbot/managers/websocket.py
from typing import List, Any import json import logging import threading from pathlib import Path log = logging.getLogger("pajbot") class WebSocketServer: clients: List[Any] = [] def __init__(self, manager, port, secure=False, key_path=None, crt_path=None, unix_socket_path=None): self.manager = mana...
AutorestCI/azure-sdk-for-python
azure-mgmt-datafactory/azure/mgmt/datafactory/models/sap_hana_linked_service.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 ...
harvardinformatics/jobTree
batchSystems/parasol.py
#!/usr/bin/env python #Copyright (C) 2011 by Benedict Paten (benedictpaten@gmail.com) # #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 rig...
graphql-python/graphql-epoxy
tests/test_register_enum.py
from graphql.core.type.definition import GraphQLEnumType from epoxy.registry import TypeRegistry from enum import Enum def test_register_builtin_enum(): R = TypeRegistry() @R class MyEnum(Enum): FOO = 1 BAR = 2 BAZ = 3 enum = R.type('MyEnum') assert isinstance(enum, Graph...
opendatapress/open_data_press
tests/test_helpers/test_config.py
# -*- coding: utf-8 -*- import os import unittest from helpers.config import load_config, ConfigurationError class LoadConfigTest(unittest.TestCase): def test_development_config(self): os.environ['SERVER_SOFTWARE'] = 'Dev-XXX' config = load_config() self.assertIsInstance(config, dict) ...
NeostreamTechnology/Microservices
venv/lib/python2.7/site-packages/connexion/cli.py
import logging import sys from os import path import click from clickclick import AliasedGroup, fatal_error import connexion from connexion.mock import MockResolver logger = logging.getLogger('connexion.cli') CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help']) def validate_wsgi_server_requirements(ctx, par...
rouxcode/django-filer-addons
filer_addons/tests/test_utils.py
# -*- coding: utf-8 -*- import django from django.contrib.auth.models import User from django.test import TestCase, Client # compat thing! if django.VERSION[:2] < (1, 10): from django.core.urlresolvers import reverse else: from django.urls import reverse class FilerUtilsTests(TestCase): def setUp(self): ...
rinsewester/SchemaViz
edge.py
#!/usr/bin/python3 # -*- coding: utf-8 -*- """ Widget to display simulation data of a CSDF graph. author: Sander Giesselink """ from PyQt5.QtWidgets import QGraphicsItem, QInputDialog, QMessageBox from PyQt5.QtCore import Qt, QRectF, QPointF from PyQt5.QtGui import QColor, QPen, QBrush, QPainterPath, QF...
carboncointrust/CarboncoinCore
contrib/linearize/linearize.py
#!/usr/bin/python # # linearize.py: Construct a linear, no-fork, best version of the blockchain. # # # Copyright (c) 2013 The Carboncoin developers # Distributed under the MIT/X11 software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # import json import struct i...
crf1111/Bio-Informatics-Learning
Bio-StrongHold/src/Enumerating_Unrooted_Binary_Trees.py
class Node(): def __init__(self, name): self.name = name def __str__(self): if self.name is not None: return self.name else: return "internal_{}".format(id(self)) class Edge(): def __init__(self, node1, node2): self.nodes = [node1, node2] def __...
anthonyalmarza/giles
setup.py
from __future__ import unicode_literals, print_function, absolute_import from setuptools import setup, find_packages import giles setup( author="Anthony Almarza", name="giles", version=giles.__version__, packages=find_packages(exclude=["test*", ]), url="https://github.com/anthonyalmarza/giles", ...
axelniklasson/adalyzer
backend/location_optimisation.py
from sklearn import cluster import numpy as np import datetime #import matplotlib #matplotlib.use('Agg') import matplotlib.pyplot as plt class Location: vehicle_data = None @staticmethod def get_data(): if Location.vehicle_data is not None: return Location.vehicle_data.tolist() else: return None @sta...
1024inc/django-rq
django_rq/management/commands/rqenqueue.py
from distutils.version import LooseVersion from django.core.management.base import BaseCommand from django.utils.version import get_version from django_rq import get_queue class Command(BaseCommand): """ Queue a function with the given arguments. """ help = __doc__ args = '<function arg arg ...>...
ooz/ICFP2015
src/game.py
#!/usr/bin/python # coding: utf-8 import copy import json from lcg import LCG class Game(object): def __init__(self, json_file): super(Game, self).__init__() with open(json_file) as f: json_data = json.load(f) self.ID = json_data["id"] self.units = [Unit(json_u...
DayGitH/Python-Challenges
DailyProgrammer/20120209C.py
''' we all know the classic "guessing game" with higher or lower prompts. lets do a role reversal; you create a program that will guess numbers between 1-100, and respond appropriately based on whether users say that the number is too high or too low. Try to make a program that can guess your number based on user input...
marco-lilek/musiClr
src/utils/modifyTag.py
import taglib import os TEMP_FILENAME = "temp.mp3" class TagWrapper: def __init__(self, fileName): self.fileName = fileName try: self.tag = taglib.MP3(fileName) except: self.tag = None def __enter__(self): return self def __exit__(self, type, value, traceback): ...
vsaw/miniSSL
minissl/TcpDispatcher.py
import socket import asyncore import pickle from minissl.AbstractConnection import AbstractConnection class PickleStreamWrapper(asyncore.dispatcher_with_send, AbstractConnection): """Buffers a stream until it contains valid data serialized by pickle. That is a big of an ugly glue code I had to come up with i...
joshloyal/pydata-amazon-products
amazon_products/text_plots.py
import numpy as np import pandas as pd import seaborn as sns import wordcloud from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.decomposition import TruncatedSVD from sklearn.manifold import TSNE from sklearn.preprocessing import Normalizer from sklearn.pipeline import make_pipeline def sample...
comicxmz001/LeetCode
Python/160 Intersection of Two Linked Lists.py
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def getIntersectionNode(self, headA, headB): """ :type head1, head1: ListNode :rtype: ListNode """ p1 = headA...
aziele/alfpy
tests/test_distance.py
import unittest from alfpy import word_pattern from alfpy import word_vector from alfpy.utils import distance from alfpy.utils import distmatrix from . import utils class DistanceTest(unittest.TestCase, utils.ModulesCommonTest): def __init__(self, *args, **kwargs): super(DistanceTest, self).__init__(*a...
X455u/SNLP
bin/python/sortclusters.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import ConfigParser import unicodecsv import json import sys import re ### FUNCTIONS FOR COUNTING CLUSTER STATISTICS ### def text_statistics(texts): lencount = 0 minlen = sys.maxint maxlen = 0 for t in texts: l = len(t.split()) ...
ToonTownInfiniteRepo/ToontownInfinite
otp/ai/MagicWordManagerAI.py
from direct.directnotify import DirectNotifyGlobal from direct.distributed.DistributedObjectAI import DistributedObjectAI from otp.ai.MagicWordGlobal import * from direct.distributed.PyDatagram import PyDatagram from direct.distributed.MsgTypes import * class MagicWordManagerAI(DistributedObjectAI): notify = Direc...
vv-p/jira-reports
filters/filters.py
import re import os def get_emoji_content(filename): full_filename = os.path.join(os.path.dirname(__file__), 'emojis', filename) with open(full_filename, 'r') as fp: return fp.read() def fix_emoji(value): """ Replace some text emojis with pictures """ emojis = { '(+)': get_em...
VerstandInvictus/Spidergram
spidergram.py
from bs4 import BeautifulSoup import requests import re import os import codecs import unidecode import arrow import traceback # disable warning about HTTPS try: requests.packages.urllib3.disable_warnings() except: pass class instaLogger: def __init__(self, logfile): self.logfile = logfile d...
cloudboss/bossimage
bossimage/cli.py
# Copyright 2018 Joseph Wright <joseph@cloudboss.co> # # 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, mer...
starze/openhab2
openhab2/scripts/nilan_connectiontest.py
#!/usr/bin/env python import minimalmodbus import serial __author__ = "Nick Ma" class Nilan( minimalmodbus.Instrument ): """Instrument class for nilan heat pump. communication via RS485 """ HOLDINGREG_OFFSET = 10000 def __init__(self, portname, slaveaddress=30): minimalmodbus.Ins...
fabiocaccamo/django-admin-interface
admin_interface/migrations/0009_add_enviroment.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("admin_interface", "0008_change_related_modal_background_opacity_type"), ] operations = [ migrations.AddField( m...
ibackus/compare-changa-builds
compchanga/runTest.py
# -*- coding: utf-8 -*- """ Created on Mon Oct 3 16:43:46 2016 @author: ibackus """ import numpy as np import os import pynbody SimArray = pynbody.array.SimArray import shutil from distutils import dir_util import subprocess from multiprocessing import cpu_count from diskpy.utils import logPrinter import glob import ...
CodyKochmann/sync_lab
simple_notepad_server/cherrypy/wsgiserver/wsgiserver2.py
"""A high-speed, production ready, thread pooled, generic HTTP server. Simplest example on how to use this module directly (without using CherryPy's application machinery):: from cherrypy import wsgiserver def my_crazy_app(environ, start_response): status = '200 OK' response_headers = [('Cont...
watchdogpolska/poradnia
poradnia/users/migrations/0023_auto_20220103_1354.py
# Generated by Django 2.2.25 on 2022-01-03 12:54 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("users", "0022_auto_20191015_0510"), ] operations = [ migrations.AlterField( model_name="user", name="notify_unassig...
linways/SSO-with-JWT
examples/python/utils.py
import jwt from time import time from partner_data import partners """ Returns the partner object of given partnerId Args: ssoId Id of the partner Returns: The partner object """ def getSSOPartnerById(ssoId): if ssoId in partners and partners[ssoId]['is_active']: return partners[ssoId] rais...
abrenaut/waybackscraper
setup.py
from setuptools import setup, find_packages import sys if sys.version_info[0] < 3 or sys.version_info[1] < 5: sys.exit('Sorry, Python < 3.5 is not supported') setup(name='waybackscraper', version='0.5', description='Scrapes a website archives on the wayback machine using asyncio.', author='Arthu...
MalloyPower/parsing-python
front-end/testsuite-python-lib/Python-2.3/Lib/gopherlib.py
"""Gopher protocol client interface.""" __all__ = ["send_selector","send_query"] # Default selector, host and port DEF_SELECTOR = '1/' DEF_HOST = 'gopher.micro.umn.edu' DEF_PORT = 70 # Recognized file types A_TEXT = '0' A_MENU = '1' A_CSO = '2' A_ERROR = '3' A_MACBINHEX = '4' A_PCBIN...
factly/election-results-2017
manipur/manipur/spiders/results_spider.py
import scrapy from scrapy import Request class CWACResultsSpider(scrapy.Spider): name = "cw-all-candidates" def start_requests(self): for i in range(60): if self.endpoint == 'archive': yield Request('https://web.archive.org/web/20160823114553/http://eciresults.ni...
VirrageS/io-kawiarnie
caffe/employees/views.py
"""Module with views for the employee feature.""" from django.contrib import messages from django.contrib.auth import logout from django.contrib.auth.decorators import login_required, permission_required from django.core.urlresolvers import reverse from django.shortcuts import get_object_or_404, redirect, render from...
angadpc/Alexa-Project-
twilio/rest/taskrouter/v1/workspace/__init__.py
# coding=utf-8 """ This code was generated by \ / _ _ _| _ _ | (_)\/(_)(_|\/| |(/_ v1.0.0 / / """ from twilio.base import deserialize from twilio.base import values from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base....
Mitali-Sodhi/CodeLingo
Dataset/python/pincode.py
import tornado.ioloop import tornado.web import json import MySQLdb class MainHandler(tornado.web.RequestHandler): # def fetch_states(self): # pincode_file = open('pincode.json') # pincode_json = json.load(pincode_file) # state_list = {} # state_list['states'] = [] # state_list['state_count'] = 0 # for...
koblas/modelplus
modelplus/__init__.py
__all__ = ['setup', 'get_db'] from modelplus.store import redis_db, sqlite_db store = None def setup(params): """ 'redis' : { host, port, db } 'sqlite' : { file } 'mysql' : { host, port, db } 'riak' : { host, port, bucket } 'mongodb' : { host, port, bucket } ""...
recto/udacity_full_stack_web_developer
P2_Tournament_Results/tournament_test.py
#!/usr/bin/env python """ Test cases for tournament.py """ from tournament import * def testDeleteMatches(): """ test deleteMatches. """ deleteMatches() print "1. Old matches can be deleted." def testDelete(): deleteMatches() deletePlayers() print "2. Player records can be deleted." def t...
lotharwissler/bioinformatics
python/misa/exonic-ssrs-to-genes.py
#!/usr/bin/python import os, sys # low level handling, such as command line stuff import string # string methods available import re # regular expressions import getopt # comand line argument handling from low import * # custom functions, written by myself from misa import MisaSSR from collecti...
JakubPetriska/poker-cfr
test/sampling_tests.py
import unittest import os import numpy as np from tools.sampling import read_log_file from tools.walk_trees import walk_trees_with_data from tools.game_tree.nodes import ActionNode, BoardCardsNode, HoleCardsNode LEDUC_POKER_GAME_FILE_PATH = 'games/leduc.limit.2p.game' class SamplingTests(unittest.TestCase): def...
robertjacobs/zuros
zuros_test/src/timed_out-and-back.py
#!/usr/bin/env python """ timed_out_and_back.py - Version 1.1 2013-12-20 A basic demo of the using odometry data to move the robot along and out-and-back trajectory. Created for the Pi Robot Project: http://www.pirobot.org Copyright (c) 2012 Patrick Goebel. All rights reserved. This program is free software; you ca...
thorwhalen/ut
daf/struct.py
__author__ = 'thor' import ut as ms import pandas as pd import ut.pcoll.order_conserving from functools import reduce class SquareMatrix(object): def __init__(self, df, index_vars=None, sort=False): if isinstance(df, SquareMatrix): self = df.copy() elif isinstance(df, pd.DataFrame): ...
animekita/selvbetjening
selvbetjening/core/mailcenter/models.py
import logging import re import markdown from django.conf import settings from django.db import models from django.template import Template, Context, loader import sys from selvbetjening.core.mail import send_mail logger = logging.getLogger('selvbetjening.email') class EmailSpecification(models.Model): BODY_FO...
Convertro/Hydro
src/hydro/hydro_cli.py
import argparse import sys import os from django.template import Template, Context from django.conf import settings as django_settings import django __author__ = 'moshebasanchig' def _create_file_from_template(template_file_name, destination_file_name, topology_name): with open(template_file_name, 'r') as templa...
the-hypermedia-project/representor-python
tests/adapters/hale_json_test.py
import sys import unittest import json import logging from representor import Representor from representor.adapters.hale_json import HaleJSONAdapter hale_example = """{ "_meta": { "any": { "json": "object" } }, "attribute": "value", "_links": { "self": { ...
MitchellChu/torndsession
torndsession/sessionhandler.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright @ 2014 Mitchell Chu from __future__ import (absolute_import, division, print_function, with_statement) import tornado.web import torndsession.session class SessionBaseHandler(tornado.web.RequestHandler, torndsession.session.SessionM...
mass-project/mass_server
mass_flask_config/app.py
import os import subprocess from pymongo import MongoClient from flask import Flask, redirect, url_for, request, flash from flask_bootstrap import Bootstrap from flask_mongoengine import MongoEngine from flask_modular_auth import AuthManager, current_authenticated_entity, SessionBasedAuthProvider, KeyBasedAuthProvider...
altvod/pymander
examples/simple.py
from pymander.exceptions import CantParseLine from pymander.handlers import LineHandler, RegexLineHandler, ArgparseLineHandler from pymander.contexts import StandardPrompt from pymander.commander import Commander from pymander.decorators import bind_command class DeeperLineHandler(LineHandler): def try_execute(se...
marco-lancini/Showcase
app_auth/urls.py
from django.conf.urls.defaults import * from django.contrib.auth import views as auth_views from app_auth.views import * from app_auth.views import login as custom_login, logout as custom_logout urlpatterns = patterns('', # Home url(r'^$', home, name="app_auth.home"), # Login / logout url(r'^login/...
NicolasLM/crawler
crawler/crawler.py
from urllib.parse import urlparse from collections import namedtuple import socket import requests from requests.packages import urllib3 from bs4 import BeautifulSoup import rethinkdb as r from celery import Celery from celery.utils.log import get_task_logger import pyasn import geoip2.database, geoip2.errors import ...
neighbordog/deviantart
tests/test_api.py
from __future__ import absolute_import import unittest import deviantart from .helpers import mock_response, optional from .api_credentials import CLIENT_ID, CLIENT_SECRET class ApiTest(unittest.TestCase): @optional(CLIENT_ID == "", mock_response('token')) def setUp(self): self.da = deviantart.Api(C...
AuthentiqID/examples-flask
example_dance.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Flask-Dance example. This example demonstrates how to integrate a server application with Authentiq Connect. It uses the popular Flask-Dance package to make this trivial in Flask. """ from __future__ import ( absolute_import, division, print_function, u...
Azure/azure-sdk-for-python
sdk/network/azure-mgmt-network/azure/mgmt/network/v2018_06_01/aio/operations/_express_route_circuit_connections_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 ...
pattisdr/lookit-api
accounts/migrations/0014_auto_20170726_1403.py
# -*- coding: utf-8 -*- # Generated by Django 1.11.2 on 2017-07-26 14:03 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('accounts', '0013_auto_20170718_2137'), ] operations = [ migrations.AlterModelOption...
michaelBenin/sqlalchemy
lib/sqlalchemy/dialects/postgresql/__init__.py
# postgresql/__init__.py # Copyright (C) 2005-2014 the SQLAlchemy authors and contributors <see AUTHORS file> # # This module is part of SQLAlchemy and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php from . import base, psycopg2, pg8000, pypostgresql, zxjdbc base.dialect = psyc...
ComicIronic/ByondToolsv3
tests/ObjectTree.py
''' Created on Jan 5, 2014 @author: Rob ''' import unittest class ObjectTreeTests(unittest.TestCase): def setUp(self): from byond.objtree import ObjectTree self.tree = ObjectTree() def test_consumeVariable_basics(self): test_string = 'var/obj/item/weapon/chainsaw = new' ...
udacity/responsive-images
grading_scripts/2_5.py
answer1 = widget_inputs["check1"] answer2 = widget_inputs["check2"] answer3 = widget_inputs["check3"] answer4 = widget_inputs["check4"] is_correct = False comments = [] def commentizer(new): if new not in comments: comments.append(new) if answer1 == True: is_correct = True else: is_correct = is_c...
abhijithanilkumar/CollegeSeatAllocation
src/CollegeSeatAllocation/settings/base.py
""" Django settings for CollegeSeatAllocation project. For more information on this file, see https://docs.djangoproject.com/en/dev/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/dev/ref/settings/ """ from django.core.urlresolvers import reverse_lazy from os.pat...
vpv11110000/pyss
setup.py
# -*- coding: utf-8 -*- try: from setuptools import setup except ImportError: from distutils.core import setup from setuptools import find_packages from os.path import join, dirname import pyss import unittest setup( name='pyss', version=pyss.__version__, packages=find_packages(), long_de...
indico/indico
indico/web/flask/wrappers.py
# This file is part of Indico. # Copyright (C) 2002 - 2022 CERN # # Indico is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see the # LICENSE file for more details. import os import re from contextlib import contextmanager from uuid import uuid4 from flask import Bluepr...
indico/indico
indico/modules/auth/blueprint.py
# This file is part of Indico. # Copyright (C) 2002 - 2022 CERN # # Indico is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see the # LICENSE file for more details. from flask import request from indico.modules.auth.controllers import (RHAccounts, RHAdminImpersonate, RH...
problemshift/kf5py
setup.py
from setuptools import setup setup( name='kf5py', py_modules = ['kf5py'], version='0.1.8', author='Chris Teplovs', author_email='dr.chris@problemshift.com', url='http://problemshift.github.io/kf5py/', license='LICENSE.txt', description='Python-based utilities for KF5.', install_requ...
brechin/pyrollout
pyrollout/rollout.py
import logging # noinspection PyUnresolvedReferences import feature #noqa logging.basicConfig(level=logging.DEBUG) class Rollout(object): __version__ = '0.3.5' def __init__(self, feature_storage=None, user_storage=None, undefined_feature_access=False): """ Manage feature flags for groups, u...
PeteTheAutomator/ACServerManager
session/migrations/0013_auto_20160904_1252.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('session', '0012_auto_20160904_1130'), ] operations = [ migrations.AlterField( model_name='serversetting', ...
cooperthompson/ct-com
soccercal/models.py
from datetime import date from django.db import models from smart_selects.db_fields import ChainedForeignKey from urlparse import urlparse class Organization(models.Model): name = models.CharField(max_length=100) def __unicode__(self): return self.name class Season(models.Model): name = models....
JCH222/matriochkas
matriochkas/tests/ParsingEntities.py
# coding: utf8 from matriochkas.core import ParsingEntities from collections import Counter from threading import Thread from time import sleep import copy ######################################################################################################################## class InstanceParsingEntity(ParsingEnt...
scottdarch/Arturo
ano/filters.py
# -*- coding: utf-8; -*- import sys import os.path import fnmatch from ano.utils import FileMap, SpaceList class GlobFile(object): def __init__(self, filename, dirname): self.filename = filename self.dirname = dirname @property def path(self): return os.path.join(self.dirname, s...
the-it/WS_THEbotIT
archive/offline/download_RE_pics_OCR/make_single_pages.py
import os import internetarchive folder = 'pages' def from_IA(book, item, filepattern, start, steps, finish): if not os.path.exists(os.getcwd() + os.sep + folder + os.sep + book): os.makedirs(os.getcwd() + os.sep + folder + os.sep + book) session = internetarchive.ArchiveSession() re_item = sess...
tago-io/tago-python
tago/run_user/__init__.py
import requests import json import os API_TAGO = os.environ.get('TAGO_API') or 'https://api.tago.io' REALTIME = os.environ.get('TAGO_REALTIME') or 'https://realtime.tago.io' class RunUser: def __init__(self, token): self.token = token self.default_headers = { 'content-type': 'application/json', 'Devi...
saltastro/salt-data-quality-site
test_bokeh_model.py
import argparse import importlib import inspect import os import sys import traceback from bokeh.plotting import output_file, show from fabulous.color import bold, red from app import create_app def error(msg, stacktrace=None): """Print an error message and exit. Params: ------- msg: str Er...
TwoBitAlchemist/PyBaseConvert
base_convert.py
#! /usr/bin/env python """ Convert arbitrary numbers between integer bases from 2 to 64. """ import string import sys from decimal import Decimal ALL_DIGITS = ''.join(map(str, range(10))) + string.ascii_letters + '+/' DIGIT_MAP = dict(enumerate(ALL_DIGITS)) DIGIT_RMAP = dict(zip(DIGIT_MAP.values(), DIGIT_MAP.keys()))...
kr15h/digital-fabrication-studio
examples/anne-marie-projected-notebook/switch.py
import RPi.GPIO as GPIO import time import os import psutil import subprocess # Get framebuffer resolution proc = subprocess.Popen(["fbset | grep 'mode '"], stdout=subprocess.PIPE, shell=True) (out, err) = proc.communicate() i = out.index('"') + 1 out = out[i:] i = out.index('"') out = out[:i] i = out.index('x') xres ...
clickyotomy/xkcd-substitutions
read.py
#! /usr/bin/env python2.7 ''' Substitutions that make reading the news more fun! Inspired from https://xkcd.com/{1004,1031,1288,1418,1625,1679}/. ''' import re import sys import json import random import hashlib import textwrap import itertools from datetime import datetime from argparse import (ArgumentParser, RawDe...
OKThess/website
main/migrations/0063_event_date_end.py
# -*- coding: utf-8 -*- # Generated by Django 1.11.6 on 2018-05-30 17:02 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('main', '0062_auto_20171223_1552'), ] operations = [ migrations.AddField( ...
puhitaku/AutoChime
ntptime_kai.py
# Copy of ntptime.py with millisecond-accurate sync try: import usocket as socket except: import socket try: import ustruct as struct except: import struct # (date(2000, 1, 1) - date(1900, 1, 1)).days * 24*60*60 NTP_DELTA = 3155673600 MILLIS_PER_SECOND = 1000 host = "pool.ntp.org" def time(ms_accur...
TimeSynth/TimeSynth
timesynth/signals/car.py
import numpy as np from .base_signal import BaseSignal __all__ = ['CAR'] class CAR(BaseSignal): """Signal generatpr for continuously autoregressive (CAR) signals. Parameters ---------- ar_param : number (default 1.0) Parameter of the AR(1) process sigma : number (default 1.0) Sta...
fin/froide
froide/publicbody/migrations/0024_auto_20181114_1516.py
# -*- coding: utf-8 -*- # Generated by Django 1.11.15 on 2018-11-14 14:16 from __future__ import unicode_literals from django.db import migrations def move_region_to_regions(apps, schema_editor): PublicBody = apps.get_model("publicbody", "PublicBody") for pb in PublicBody.objects.filter(region__isnull=False)...
zygmuntz/kaggle-bestbuy_small
train.py
'http://fastml.com/best-buy-mobile-contest/' import sys, csv, re def prepare( query ): query = re.sub( r'[\W]', '', query ) query = query.lower() return query popular_skus = [9854804, 2107458, 2541184, 2670133, 2173065] input_file = sys.argv[1] test_file = sys.argv[2] output_file = sys.argv[3] i = open( input_f...
CameronLonsdale/lantern
tests/analysis/test_frequency.py
"""Tests for the frequency module in analysis""" import pytest from lantern.analysis import frequency def test_frequency_analyze(): """Testing frequency analyze works for ngram = 1""" assert frequency.frequency_analyze("abb") == {'a': 1, 'b': 2} def test_frequency_analyze_bigram(): """Testing frequenc...
perimosocordiae/sparray
sparray/tests/test_truediv.py
import unittest import numpy as np from numpy.testing import assert_array_almost_equal from .test_base import BaseSparrayTest, dense2d class TestTrueDivision(BaseSparrayTest): def test_truediv(self): c = 3 assert_array_almost_equal(dense2d / c, (self.sp2d / c).toarray()) with np.errstate(divide='ignor...
sviehb/binwalk
src/binwalk/plugins/ubivalid.py
import struct import binascii import binwalk.core.plugin class UBIValidPlugin(binwalk.core.plugin.Plugin): ''' Helps validate UBI erase count signature results. Checks header CRC and calculates jump value ''' MODULES = ['Signature'] current_file=None last_ec_hdr_offset = None peb_size...
comger/migrant
doc/importnews.py
# -*- coding:utf-8 -*- """ author comger@gmail.com news spider """ import tornado import urllib from kpages import set_default_encoding from pyquery import PyQuery as pyq from tornado import httpclient def main(): url = 'http://taiwan.huanqiu.com/news/' #url = 'http://world.huanqiu.com/observation/' ...
whardier/holder.graphics
passenger_wsgi.py
import os import tempfile import re import bottle import PIL.Image import PIL.ImageDraw import PIL.ImageFont formats = { 'png': { 'format': 'PNG', 'mimetype': 'image/png' }, 'jpg': { 'format': 'JPEG', 'mimetype': 'image/jpeg' }, 'gif': { 'format': 'GIF', ...
papajijaat/Face-Detect
code/face_detect.py
import cv2 import sys #cascPath = sys.argv[1] #faceCascade = cv2.CascadeClassifier(cascPath) faceCascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml') video_capture = cv2.VideoCapture(0) while True: # Capture frame-by-frame ret, frame = video_capture.read() gray = cv2.cvtColor(frame, cv2...
tooringanalytics/pyambiguity
m2py.py
#!/usr/bin/env python ''' Debug & Test support for matplot to python conversion. ''' import os import numpy as np from scipy.io import loadmat def dmpdat(s, e): """ Dump a data structure with its name & shape. Params: ------- s: str. The name of the structure e: expression. An expression to dump. ...
spreaker/android-publish-cli
setup.py
from __future__ import print_function from setuptools import setup import sys if sys.version_info < (2, 6): print('google-api-python-client requires python version >= 2.6.', file = sys.stderr) sys.exit(1) install_requires = ['google-api-python-client==1.3.1'] if sys.version_info < (2, 7): install_requi...
hsadler/con-science-twitter-bot
models/error_log.py
#!/usr/bin/python # -*- coding: utf-8 -*- # Error Log model import logging logger = logging.getLogger('con_science_bot') hdlr = logging.FileHandler('logs/error.log') formatter = logging.Formatter('\n%(asctime)s %(levelname)s %(message)s') hdlr.setFormatter(formatter) logger.addHandler(hdlr) logger.setLevel(logging.IN...
keenlabs/KeenClient-Python
keen/__init__.py
import os from keen.client import KeenClient from keen.exceptions import InvalidEnvironmentError __author__ = 'dkador' _client = None project_id = None write_key = None read_key = None master_key = None base_url = None def _initialize_client_from_environment(): ''' Initialize a KeenClient instance using environm...
Dinoshauer/pryvate
pryvate/blueprints/pypi/pypi.py
"""PyPi blueprint.""" import os from flask import Blueprint, current_app, g, request blueprint = Blueprint('pypi', __name__, url_prefix='/pypi') def register_package(localproxy): """Register a new package. Creates a folder on the filesystem so a new package can be uploaded. Arguments: localprox...
robin1885/algorithms-exercises-using-python
source-code-from-author-book/Listings-for-Second-Edition/listing_8_1.py
class ArrayList: def __init__(self, ): self.sizeExponent = 0 self.maxSize = 0 self.lastIndex = 0 self.myArray = [] def append(self,val): if self.lastIndex > self.maxSize-1: self.__resize() self.myArray[self.lastIndex] = val self.lastInde...
betrisey/home-assistant
homeassistant/components/climate/ecobee.py
""" Platform for Ecobee Thermostats. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/climate.ecobee/ """ import logging from os import path import voluptuous as vol from homeassistant.components import ecobee from homeassistant.components.climate import...
usoban/pylogenetics
pylogen/tree.py
from abc import ABCMeta, abstractmethod class Edge: """ Phylogenetic tree edge. Connects start and end node with some given distance measure """ def __init__(self, startNode, endNode, distance): self.distance = distance self.setEndNode(endNode) self.setStartNode(startNode) def setStartNode(self, node...
blindman/nhl-logo-scraper
tests/test_cli.py
"""Tests for the main nhlscraper CLI module""" from subprocess import PIPE, getoutput from unittest import TestCase from nhl_logo_scraper import __version__ as VERSION class TestHelp(TestCase): def test_returns_usage_information(self): output = getoutput("nhlscraper -h") self.assertTrue('Usage:' ...
ThomasMoritz/exportlightroomfaces
getfaces.py
#!/usr/bin/python # -*- coding: utf-8 -*- import sqlite3 import os.path from PIL import Image import piexif import argparse # Commandline Handling parser = argparse.ArgumentParser(description='Export faces from Lightroom DB') parser.add_argument('-d', '--database', help='Input Database', required=True) parser.add_ar...
futurecolors/django-confirmanager
confirmanager/tests.py
# coding: utf-8 import datetime from mock import patch, ANY from django.core.urlresolvers import reverse from django.test.utils import override_settings from django.test import TestCase from django.contrib.auth.models import User from .utils import mock_signal_receiver from .models import EmailConfirmation, Confirmat...