repo_name
stringlengths
5
104
path
stringlengths
4
248
content
stringlengths
102
99.9k
rec/echomesh
code/python/experiments/ossaudiodev/GetFormats.py
from __future__ import absolute_import, division, print_function, unicode_literals import ossaudiodev def print_fmts(rw): print(rw == 'r' and 'read' or 'write') sound = ossaudiodev.open(rw) fmts = sound.getfmts() for name in dir(ossaudiodev): if name.startswith('AFMT'): attr = getattr(ossaudiodev,...
lyw07/kolibri
kolibri/core/content/utils/transfer.py
import logging import os import shutil import requests from requests.exceptions import ConnectionError logger = logging.getLogger(__name__) class ExistingTransferInProgress(Exception): pass class TransferNotYetCompleted(Exception): pass class TransferCanceled(Exception): pass class TransferNotYetC...
enritoomey/DiagramaDeRafagasyManiobras
diagramas_class.py
import numpy as np import matplotlib.pyplot as plt from scipy.optimize import fsolve import argparse import json class Diagramas(object): def __init__(self, datos, w, h, den, units='SI'): self.CAM = datos["CAM"] self.sw = datos["sw"] self.a3D = datos["a3D"] self.MTOW = datos["MTOW"...
ltowarek/budget-supervisor
third_party/saltedge/test/test_income_report_streams_regular.py
# coding: utf-8 """ Salt Edge Account Information API API Reference for services # noqa: E501 OpenAPI spec version: 5.0.0 Contact: support@saltedge.com Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import unittest import swagger_cl...
naparuba/check-linux-by-ssh
check_ntp_sync_by_ssh.py
#!/usr/bin/env python2 # Copyright (C) 2013: # Gabes Jean, naparuba@gmail.com # Pasche Sebastien, sebastien.pasche@leshop.ch # # 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...
barentsen/iphas-dr2
paper/figures/caldiagram/plot.py
"""Plots the calibrated and uncalibrated CCD over a large area.""" import os import numpy as np import matplotlib import matplotlib.pyplot as plt from astropy.io import fits from astropy import log from dr2 import constants fields = constants.IPHASQC[constants.IPHASQC_COND_RELEASE] mask = (fields['l'] > 160.0) & (fiel...
DailyActie/Surrogate-Model
01-codes/scikit-learn-master/examples/ensemble/plot_adaboost_regression.py
""" ====================================== Decision Tree Regression with AdaBoost ====================================== A decision tree is boosted using the AdaBoost.R2 [1] algorithm on a 1D sinusoidal dataset with a small amount of Gaussian noise. 299 boosts (300 decision trees) is compared with a single decision tr...
Yelp/git-code-debt
tests/server/servlets/commit_test.py
import flask from testing.assertions.response import assert_no_response_errors def test_it_loads(server_with_data): resp = server_with_data.server.client.get( flask.url_for( 'commit.show', sha=server_with_data.cloneable_with_commits.commits[3].sha, ), ) assert_no_r...
takeTrace/UrHouseBot
UrHouseBot/UrHouseBot/middlewares.py
# -*- coding: utf-8 -*- # Define here the models for your spider middleware # # See documentation in: # http://doc.scrapy.org/en/latest/topics/spider-middleware.html from UrHouseBot.settings import PROXY_HOST from scrapy import signals, Request import requests from UrHouseBot.spiders import doubanGroup proxy_host =...
ghackebeil/PyORAM
src/pyoram/tests/test_misc.py
import os import unittest import tempfile import pyoram.util.misc class Test(unittest.TestCase): def test_log2floor(self): self.assertEqual(pyoram.util.misc.log2floor(1), 0) self.assertEqual(pyoram.util.misc.log2floor(2), 1) self.assertEqual(pyoram.util.misc.log2floor(3), 1) self....
kozlovsky/ponymodules
main.py
# This is the example of main program file which imports entities, # connects to the database, drops/creates specified tables # and populate some data to the database from pony.orm import * # or just import db_session, etc. import all_entities # This command make sure that all entities are imported from base_entitie...
ryanss/holidays.py
holidays/countries/ethiopia.py
# -*- coding: utf-8 -*- # python-holidays # --------------- # A fast, efficient Python library for generating country, province and state # specific sets of holidays on the fly. It aims to make determining whether a # specific date is a holiday as fast and flexible as possible. # # Authors: dr-prodigy <maurizio....
kfdm/django-simplestats
quickstats/permissions.py
from rest_framework import permissions from . import models class IsOwnerOrPublic(permissions.IsAuthenticatedOrReadOnly): message = "Not object owner or public" def has_object_permission(self, request, view, obj): if request.user == obj.owner: return True if request.meth...
andree1320z/deport-upao-web
deport_upao/extensions/authtools/forms.py
from authtools.forms import AuthenticationForm from django.contrib.auth import authenticate from django.forms import forms class LoginForm(AuthenticationForm): def clean(self): username = self.cleaned_data.get('username') password = self.cleaned_data.get('password') if username and passwo...
jeremiedecock/snippets
python/pyqt/pyqt5/widget_QDateEdit.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # See http://doc.qt.io/qt-5/qdateedit.html#details import sys import datetime from PyQt5.QtWidgets import QApplication, QWidget, QDateEdit, QPushButton, QVBoxLayout class Window(QWidget): def __init__(self): super().__init__() # Make widgets #####...
evereux/flicket
application/flicket/views/release.py
#! usr/bin/python3 # -*- coding: utf-8 -*- # # Flicket - copyright Paul Bourne: evereux@gmail.com import datetime from flask import redirect, url_for, flash, g from flask_babel import gettext from flask_login import login_required from . import flicket_bp from application import app, db from application.flicket.mode...
Tjorriemorrie/housing
src/settings.py
from os.path import dirname, realpath from jinja2 import Environment, FileSystemLoader from google.appengine.ext import ndb DEBUG = True SECRET_KEY = 'asdfjasdflkjsfewi23kjl3kjl45kjl56jk6hjb76vsjsa' CONFIG = { } SRC_ROOT = dirname(realpath(__file__)) JINJA_ENVIRONMENT = Environment( loader=FileSystemLoader(S...
Karel-van-de-Plassche/QLKNN-develop
qlknn/models/rotdiv.py
import os import numpy as np import pandas as pd from IPython import embed from qlknn.models.ffnn import QuaLiKizNDNN, QuaLiKizComboNN, determine_settings from qlknn.misc.analyse_names import is_pure_flux, is_flux, split_parts pot_rot_vars = ['Machtor', 'Autor', 'Machpar', 'Aupar', 'gammaE'] class RotDivNN(): d...
tgquintela/pyDataProcesser
pyDataProcesser/DataManagement.py
# -*- coding: utf-8 -*- import pandas as pd from datetime import datetime import numpy as np from DataDictObject import DataDictObject from TablonReader import TablonReader from TablonEncoder import TablonEncoder from TablonLoader import TablonLoaderDB class DataManagementObject: """This is the cla...
svven/tweepy
tweepy/limit.py
# Tweepy # Copyright 2009-2010 Joshua Roesslein # Copyright 2014 Alexandru Stanciu (@ducu) # See LICENSE for details. # import time from tweepy.api import API from tweepy.auth import OAuthHandler from tweepy.error import TweepError from tweepy.utils import clean_path class RateLimitHandler(OAuthHandler): """ ...
slundberg/shap
shap/explainers/other/_maple.py
from .._explainer import Explainer import numpy as np from sklearn.model_selection import train_test_split class Maple(Explainer): """ Simply wraps MAPLE into the common SHAP interface. Parameters ---------- model : function User supplied function that takes a matrix of samples (# samples x # ...
lunixbochs/glshim
test/util/run.py
import argparse import jinja2 import os import signal import subprocess import sys import traceback from blessings import Terminal from contextlib import contextmanager signals = dict((k, v) for v, k in signal.__dict__.iteritems() if v.startswith('SIG')) term = Terminal() TEST_ROOT = os.getcwd() env = jinja2.Environ...
zmbc/shakespearelang
shakespearelang/_character.py
from .errors import ShakespeareRuntimeError from ._utils import normalize_name class Character: """A character in an SPL play.""" def __init__(self): self.value = 0 self.stack = [] def __str__(self): return f'{self.value} ({" ".join([str(v) for v in self.stack][::-1])})' def...
gnovak/overheard
overheard/test.py
######### # Notes # ######### # # Run all tests from command line # python test.py # python -m test # # Run subset of tests from command line # python -m unittest ArchivTest # python -m unittest ArchivTest.test_old_arxiv_id # # Run all tests non-interactively from REPL # import test; test.test() # # Run...
jedlitools/find-for-me
ex28_context_search.py
import re text = open('khalifa_tarikh.txt', mode="r", encoding="utf-8").read() text = re.sub(r"َ|ً|ُ|ٌ|ِ|ٍ|ْ|ّ|ـ", "", text) def search_words(checklist): search_words = open(checklist, mode='r', encoding='utf-8').read().splitlines() return search_words def index_generator(word, text): juz = 'الجزء:' ...
pinax/django-user-accounts
makemigrations.py
#!/usr/bin/env python import os import sys import django from django.conf import settings DEFAULT_SETTINGS = dict( INSTALLED_APPS=[ "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sites", "account", "account.tests" ], MIDDLEWARE_CLASSES=[], ...
akshaybabloo/Car-ND
Term_1/CNN_5/CNN_example_5.py
""" Applying Convolutional Neural Network in TensorFlow The structure of this network follows the classic structure of CNNs, which is a mix of convolutional layers and max pooling, followed by fully-connected layers. The code you'll be looking at is similar to what you saw in the segment on Deep Neural Network in Ten...
flavour/iscram
modules/s3/s3validators.py
# -*- coding: utf-8 -*- """ Custom Validators @requires: U{B{I{gluon}} <http://web2py.com>} @copyright: (c) 2010-2012 Sahana Software Foundation @license: MIT Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the...
CarloNicolini/CarloNicolini.github.io
sections/science/_posts/example_cEWRG.py
import matplotlib.pyplot as plt import numpy as np from scipy.optimize import root import bct eps = np.finfo(float).eps def pij_wij(x,y,t): xij = np.outer(x,x) yij = np.outer(y,y) pij = xij*((yij)**t)/(1.0+xij*(yij**t) - (yij**t)) wij = (t*(xij-1.0)*(yij**t))/((1.0 + xij*(yij**t) - (yij**t) )) - 1.0/(n...
Najsztub/SzczecinHome
restate/restate.py
# -*- coding: utf-8 -*- # MN: 08/04/16 import numpy as np import pandas as pd import re import matplotlib.pyplot as plt import matplotlib import seaborn as sns from data.data import clean_data matplotlib.style.use('ggplot') def plot_price_area(out, show = False): g = sns.FacetGrid(df, col="rooms", col_wrap=2) ...
Azure/azure-sdk-for-python
sdk/keyvault/azure-keyvault-certificates/samples/import_certificate_async.py
# ------------------------------------ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. # ------------------------------------ import asyncio import os from azure.identity.aio import DefaultAzureCredential from azure.keyvault.certificates import CertificateContentType, CertificatePolicy, WellKno...
Duoxilian/home-assistant
homeassistant/components/history.py
""" Provide pre-made queries on top of the recorder component. For more details about this component, please refer to the documentation at https://home-assistant.io/components/history/ """ import asyncio from collections import defaultdict from datetime import timedelta from itertools import groupby import logging imp...
dsysoev/fun-with-algorithms
string/stringsearch.py
""" Naive string matcher implementation """ from __future__ import print_function def naive_string_matcher(string, target): """ returns all indices where substring target occurs in string """ snum = len(string) tnum = len(target) matchlist = [] for index in range(snum - tnum + 1): if str...
smaragden/chancery
chancery/catalog.py
#!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = 'fredrik.brannbacka' from user import User class Catalog(object): __domain = "" def __init__(self, domain=""): self.__domain = domain @property def domain(self): return self.__domain @domain.setter def domain(self, d...
Azure/azure-sdk-for-python
sdk/network/azure-mgmt-network/azure/mgmt/network/v2019_08_01/operations/_express_route_service_providers_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 ...
ktosiek/pytest-freezegun
tests/test_freezegun.py
# -*- coding: utf-8 -*- import re from datetime import datetime def test_freezing_time(testdir): testdir.makepyfile(""" import pytest from datetime import date, datetime @pytest.mark.freeze_time('2017-05-20 15:42') def test_sth(): assert datetime.now().date() == date(...
ActiveState/code
recipes/Python/491280_BackgroundCall_Threading_like/recipe-491280.py
def example_BackgroundCall(): import urllib,time def work(): return urllib.urlopen('http://www.python.org/').read() bkcall=BackgroundCall(work) print 'work() executing in background ...' while not bkcall.is_done(): print '.', time.sleep(0.010) print 'done.' print bkca...
Azure/azure-sdk-for-python
sdk/network/azure-mgmt-network/azure/mgmt/network/v2019_06_01/operations/_azure_firewalls_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 ...
andyneff/voxel-globe
voxel_globe/ingest/metadata/tasks.py
import os from celery.utils.log import get_task_logger import numpy as np from voxel_globe.common_tasks import shared_task, VipTask from .tools import match_images, load_voxel_globe_metadata, create_scene logger = get_task_logger(__name__) ### These need to be CLASSES actually, and call common parts via methods! ...
shanx/django-extensions-shell
tests/test_shellplus_command.py
# -*- coding: utf-8 -*- import os from django import __version__ from django.core.management import call_command from django.test import TestCase from django.test.utils import patch_logger class ShellPlusCommandTests(TestCase): def setUp(self): self.project_root = os.path.join('tests', 'testapp') ...
AutorestCI/azure-sdk-for-python
azure-servicefabric/azure/servicefabric/models/update_cluster_upgrade_description.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 ...
arnedesmedt/dotfiles
.config/sublime-text-3/Packages.symlinkfollow/mdpopups/st3/mdpopups/st_color_scheme_matcher.py
""" color_scheme_matcher. Licensed under MIT. Copyright (C) 2012 Andrew Gibson <agibsonsw@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 limit...
mdiscenza/gallery_hop_2
make_photo_table.py
import mysql.connector import csv # Make RDS table and add rows from CSV file cnx = mysql.connector.connect(user='galleryhop', password='galleryhop', host='galleryhop2.crflf9mu2uwj.us-east-1.rds.amazonaws.com',database='galleryhop2') cursor = cnx.cursor() t = """CREATE TABLE photos( artist VARCHAR(50), photo VARCHA...
marrow/monitor.collector
marrow/monitor/collector/ext/load.py
# encoding: utf-8 import os import subprocess import mongoengine as db def generic_backend(): """Allow Python to handle the details of load average discovery. This is the fastest method, but may not be portable everywhere. Testing on a Linux 2.6.35 Rackspace Cloud server: 17µsec. """ ...
enchuu/yaytp
video.py
#!/usr/bin/env python import subprocess import time from format import * class Video(): """ Class to represent a Youtube video.""" def __init__(self, data): self.id = data['id'] self.title = data['title'] self.description = data['description'] self.user = data['uploader'] ...
samuelclay/NewsBlur
utils/archive/bootstrap_intel.py
import sys from mongoengine.queryset import OperationError from mongoengine.errors import ValidationError from apps.analyzer.models import MClassifierFeed from apps.analyzer.models import MClassifierAuthor from apps.analyzer.models import MClassifierTag from apps.analyzer.models import MClassifierTitle for classifier_...
lmazuel/azure-sdk-for-python
azure-mgmt-network/azure/mgmt/network/v2017_11_01/models/topology_resource_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 ...
lvisdd/qnabot
webapp/data/jmafaq.py
# -*- coding: utf-8 -*- import csv import os import re try: # Python 3 from urllib import request except ImportError: # Python 2 import urllib2 as request from bs4 import BeautifulSoup def extractFaqURL(url): html = request.urlopen(url).read() soup = BeautifulSoup(html, "html.p...
DailyActie/Surrogate-Model
01-codes/scikit-learn-master/sklearn/datasets/setup.py
import os import numpy def configuration(parent_package='', top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration('datasets', parent_package, top_path) config.add_data_dir('data') config.add_data_dir('descr') config.add_data_dir('images') config.add_data_d...
kokimoribe/todo-api
todo/schemas.py
"""Request/Response Schemas are defined here""" # pylint: disable=invalid-name from marshmallow import Schema, fields, validate from todo.constants import TO_DO, IN_PROGRESS, DONE class TaskSchema(Schema): """Schema for serializing an instance of Task""" id = fields.Int(required=True) title = fields.Str...
radare/bitcointools
deserialize.py
# # # from BCDataStream import * from enumeration import Enumeration from base58 import public_key_to_bc_address, hash_160_to_bc_address import logging import socket import time from util import short_hex, long_hex def parse_CAddress(vds): d = {} d['nVersion'] = vds.read_int32() d['nTime'] = vds.read_uint32() ...
trevorcarlson/barrierpoint
barrierpoint.py
#!/usr/bin/env python import sys, os, subprocess, getopt, itertools, gzip, glob, re, inspect import combine_simpoint_data import genbarriercmd def mkdir_s(path): try: os.makedirs(path) except OSError: pass def ex(cmd, validate = True): proc = subprocess.Popen([ 'bash', '-c', cmd ]) proc.communicate(...
legoktm/pythonwikibot
scripts/welcome.py
#!usr/bin/python import wiki from wiki import userlib import re, time, sys reload(sys) sys.setdefaultencoding('utf-8') logs = { 'en':None, 'commons': 'Project:Welcome log', } templates = { 'en':'{{subst:welcome}} ~~~~', 'commons': '{{subst:welcome}} ~~~~', } logupmess = { 'en':None, 'commons': 'Bot: Updating log...
andrewyoung1991/supriya
supriya/tools/requesttools/ErrorRequest.py
# -*- encoding: utf-8 -*- from supriya.tools.requesttools.Request import Request class ErrorRequest(Request): ### CLASS VARIABLES ### __slots__ = ( ) ### INITIALIZER ### def __init__( self, ): Request.__init__(self) raise NotImplementedError ### PUBLIC ...
Gawen/pytun
pytun.py
""" pytun pytun is a tiny piece of code which gives you the ability to create and manage tun/tap tunnels on Linux (for now). """ __author__ = "Gawen Arab" __copyright__ = "Copyright 2012, Gawen Arab" __credits__ = ["Gawen Arab", "Ben Lapid"] __license__ = "MIT" __version__ = "1.0.1" __maintainer__ = "Gawen Arab" __e...
arruda/bgarena_analysis
bgarena_gatherer/bgarena_gatherer/spiders/bgarena_race_for_galaxy_moves.py
# -*- coding: utf-8 -*- import os import datetime from functools import partial import json import scrapy from scrapy_splash import SplashRequest from sqlalchemy.orm import sessionmaker from bgarena_gatherer.items import GameTableItem from bgarena_gatherer.models import GameTable, GameTableMoveAction, db_connect AC...
rec/echomesh
code/python/echomesh/util/command/Command_test.py
from __future__ import absolute_import, division, print_function, unicode_literals from echomesh.util.command import Command from echomesh.util.TestCase import TestCase class Command_test(TestCase): def test_simple(self): registry = Command.Registry('test', 'echomesh.util.command.test', '') foo = ...
merlinthered/sublime-rainmeter
newskintools.py
import os import re import time import sublime import sublime_plugin import rainmeter class RainmeterNewSkinFileCommand(sublime_plugin.WindowCommand): """Open a new view and insert a skin skeleton""" def run(self): view = self.window.new_file() view.run_command( "insert_snipp...
nicoddemus/pytest
testing/logging/test_reporting.py
import io import os import re from typing import cast import pytest from _pytest.capture import CaptureManager from _pytest.config import ExitCode from _pytest.fixtures import FixtureRequest from _pytest.pytester import Pytester from _pytest.terminal import TerminalReporter def test_nothing_logged(pytester: Pytester...
samuelwu90/PynamoDB
tests/test_consistent_hash_ring.py
""" test_consistent_hash_ring.py ~~~~~~~~~~~~ Tests that PersistenceEngine's put, get, delete methods raise the correct error codes. Run tests with: clear; python -m unittest discover -v """ import unittest import consistent_hash_ring import util import random class TestSequenceFunctions(unittes...
diblaze/TDP002
2.3/testdemo/test/demo_test.py
#!/usr/bin/env python """ Test module for demo.py. Runs various tests on the demo module. Simply run this module to test the demo.py module. """ import test import demo def test_echo(): print("In echo test") echo = demo.echo("hej") test.assert_equal("hej", echo) test.assert_not_equal(None, echo) de...
KPRSN/Pulse
Pulse/FileManager.py
""" Karl Persson, Mac OSX 10.8.4/Windows 8, Python 2.7.5, Pygame 1.9.2pre Class taking care of all file actions ingame - Levels - Textures - Sounds """ import pygame from pygame.locals import * import sys, Level, os, random # Class taking care of all file actions class FileManager: # Constructor...
korepwx/tfsnippet
tests/layers/flows/test_base.py
import pytest from tfsnippet.layers import * from tests.layers.flows.helper import * from tfsnippet.layers.flows import FeatureMappingFlow class FlowTestCase(tf.test.TestCase): def test_with_quadratic_flow(self): # test transform flow = QuadraticFlow(2., 5.) self.assertTrue(flow.explicit...
operepo/ope
laptop_credential/winsys/misc.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals import os, sys import time import uuid import win32api import win32con import win32gui import win32console import win32gui from winsys import core, registry def set_console_title(text): title = win32console.GetConsoleTitle() win32console.SetCon...
dmonroy/emergency
emergency/web.py
import os import asyncio import aiopg from chilero import web from emergency import ui, api from emergency.db import parse_pgurl from emergency.settings import get_settings settings = get_settings() def get_routes(): return [ [os.path.join('/api', item[0]), item[1]] for item in api.routes ] + [ ...
flarn2006/TPPStreamerBot
tppsb.py
#!/usr/bin/python import sys import re import thread import urllib from time import sleep from datetime import datetime, timedelta import requests import praw from prawcore.exceptions import * import irc.bot # Begin configurable parameters identity = { # Make sure to set these if they aren't already! 'reddit_cli...
adrn/gala
gala/potential/scf/tests/test_class.py
# coding: utf-8 # Third-party import astropy.units as u from astropy.constants import G as _G import numpy as np import pytest # Project from gala._cconfig import GSL_ENABLED from gala.units import galactic import gala.potential as gp from gala.potential.potential.tests.helpers import PotentialTestBase from gala.pote...
ArcherSys/ArcherSys
Lib/distutils/dep_util.py
<<<<<<< HEAD <<<<<<< HEAD """distutils.dep_util Utility functions for simple, timestamp-based dependency of files and groups of files; also, function based entirely on such timestamp dependency analysis.""" import os from distutils.errors import DistutilsFileError def newer (source, target): """Return true if '...
genehallman/node-berkeleydb
deps/db-18.1.40/dist/winmsi/genWix.py
# # # genWix.py is used to generate a WiX .wxs format file that # can be compiled by the candle.exe WiX compiler. # # Usage: python genWix.py <output_file> # # The current directory is expected to be the top of a tree # of built programs, libraries, documentation and files. # # The list of directories traversed is at ...
glenn-edgar/local_controller_3
__backup__/py_cf_py3/chain_flow.py
import datetime import time from .opcodes_py3 import Opcodes class CF_Base_Interpreter(): def __init__(self): self.chains = [] self.chain_map = {} self.event_queue = [] self.current_chain = None self.opcodes = Opcodes() self.valid_return_codes = {} self.v...
jpzhangvincent/MobileAppMarketAnalysis
data/webscraping/appcrawl/pipelines.py
# -*- coding: utf-8 -*- # Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html import pymongo #from scrapy.conf import settings from scrapy.exceptions import DropItem import logging class AppcrawlPipeline(o...
brhoades/holdem-bot
holdem-ea/poker.py
import random from solution import Solution from awesome_print import ap def copulate(gen, parent1, parent2): """ Randomly averages values or chooses one of parents (50/50). Returns a new solution. """ child = Solution(parent1.data, gen) if parent1 is not parent2: copulate_recursive(ch...
jacyn/burst
webapp/userman/backends.py
from django.contrib.auth.models import User #import advantage.iam import sys class CustomUserBackend(object): def authenticate(self, username=None, password=None): print >> sys.stderr, "starting to authenticate.. " try: user = User.objects.get(username=username) except User.o...
leovoel/glc.py
examples/custom_rendering.py
from math import cos, sin, pi from example_util import get_filename from glc import Gif def draw(l, surf, ctx, t): xpos = cos(t * 2 * pi) * 100 + surf.get_width() * 0.5 ypos = sin(t * 2 * pi) * 100 + surf.get_height() * 0.5 w, h = 100, 100 ctx.set_source_rgb(0, 0, 0) ctx.translate(xpos, ypos) ...
edublancas/sklearn-evaluation
docs/source/nbs/train.py
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.8.0 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + import importlib from sklearn.datasets import load...
egnyte/gitlabform
tests/unit/test_non_empty_configs_provider.py
import pytest from gitlabform import EXIT_INVALID_INPUT from gitlabform.configuration.projects_and_groups import ConfigurationProjectsAndGroups from gitlabform.filter import NonEmptyConfigsProvider def test_error_on_missing_key(): config_yaml = """ --- # no key at all """ with pytest.raises(Syst...
soltys/ZUT_Algorytmy_Eksploracji_Danych
DataVisualization/app.py
# -*- coding: utf-8 -*- __author__ = 'Paweł Sołtysiak' import pandas as pd import scipy.io.arff as arff from sklearn import cross_validation from sklearn.decomposition import PCA import numpy as np import scipy.io import matplotlib.pyplot as plt waveformData, waveformMeta = arff.loadarff(u'../Datasets/waveform-5000.ar...
chubbymaggie/datasketch
benchmark/lsh_benchmark.py
import time, argparse, sys, json from sklearn.datasets import fetch_20newsgroups import numpy as np import scipy.stats from datasketch import MinHashLSH, MinHash from lshforest_benchmark import bootstrap_data, _compute_jaccard def benchmark_lsh(num_perm, threshold, index_data, query_data): print("Building LSH ind...
woozzu/tf_tutorials
03_MLP_spiral2D.py
''' A MLP algorithm example using TensorFlow library. This example is using generate random distribution (http://cs231n.github.io/neural-networks-case-study/) Code references: https://github.com/shouvikmani/Tensorflow-Deep-Learning-Tutorial/blob/master/tutorial.ipynb https://github.com/aymericdamien/TensorFlow-Example...
pwyliu/packagecloud-poll
packagecloudpoll/poll.py
"""packagecloud-poll Packagecloud-poll repeatedly polls the packagecloud API, looking for a specific package filename to appear. It is intended to be used in continuous integration/continuous deployment scenarios where we want to block until we are sure a package has been indexed and is avaiable before continuing. Al...
tommeagher/pythonGIJC15
scripts/completed/quakes_complete.py
import requests import unicodecsv from io import StringIO #what country has the most serious earthquakes lately? url = "http://python-gijc15.s3.eu-central-1.amazonaws.com/all_month.csv" r = requests.get(url) text = StringIO(r.text) reader = unicodecsv.DictReader(text, dialect='excel') new_collection = [] for row i...
lucasberti/telegrao-py
plugins/melenbra.py
import json import time import sched from api import send_message scheduler = sched.scheduler(time.time, time.sleep) def load_reminders(): reminders = {} try: with open("data/reminders.json") as fp: reminders = json.load(fp) except Exception: with open("data/reminders.json",...
chuckus/chromewhip
chromewhip/base.py
# https://stackoverflow.com/questions/30155138/how-can-i-write-asyncio-coroutines-that-optionally-act-as-regular-functions import asyncio class SyncAdder(type): """ A metaclass which adds synchronous version of coroutines. This metaclass finds all coroutine functions defined on a class and adds a synchro...
Ruben0001/Mango
setup.py
import codecs import os from distutils.core import setup HERE = os.path.abspath(os.path.dirname(__file__)) def read(*parts): """ Build an absolute path from *parts* and and return the contents of the resulting file. Assume UTF-8 encoding. """ with codecs.open(os.path.join(HERE, *parts), "rb", "...
okfn/jsontableschema-py
tests/test_profile.py
# -*- coding: utf-8 -*- from __future__ import division from __future__ import print_function from __future__ import absolute_import from __future__ import unicode_literals import io import os import json import pytest import requests from tableschema.profile import Profile # Tests @pytest.mark.skipif(os.environ.ge...
dopuskh3/confluence-publisher
tests/test_publish.py
from unittest import TestCase import random import os from conf_publisher.confluence import Page from conf_publisher.publish import Publisher from conf_publisher.config import ConfigLoader from conf_publisher.data_providers.sphinx_fjson_data_provider import SphinxFJsonDataProvider class FakePagePublisher(object): ...
iJebus/CITS4406-Assignment2
template.py
"""Provide a base HTML template variable for population with appropriate statistics in the report.py module. """ base_template = \ """ <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="...
schrockn/graphscale
graphscale/grapple/graphql_impl.py
from typing import cast, List, TypeVar, Any, Type, Optional from uuid import UUID from graphscale import check from graphscale.pent import ( create_pent, delete_pent, update_pent, Pent, PentContext, PentMutationData, PentMutationPayload, ) T = TypeVar('T') def typed_or_none(obj: Any, cl...
asterix135/infonex_crm
marketing/migrations/0006_auto_20181221_1059.py
# Generated by Django 2.0.3 on 2018-12-21 15:59 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('marketing', '0005_auto_20180123_1157'), ] operations = [ migrations.AlterField( model_name='uploadedcell', name='con...
henryfjordan/incident-commander
templates/responses.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from jinja2 import Template CREATE_INCIDENT = Template(""" *INCIDENT CREATED!* This incident is now being tracked and documented, but we still need your help! When you have a moment, please use these commands to provide more information: ``` @commander set title <title>...
gregkorte/Python-Koans
python3/koans/about_class_attributes.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Based on AboutClassMethods in the Ruby Koans # from runner.koan import * class AboutClassAttributes(Koan): class Dog: pass def test_objects_are_objects(self): fido = self.Dog() self.assertEqual(True, isinstance(fido, object)) def...
TheOtherOtherOperation/vdbsetup
vdbsetup.py
#!/usr/bin/env python3 # # vdbsetup.py - script for building Vdbench configurations # # Author: Ramon A. Lovato (ramonalovato.com) # For: DeepStorage, LLC (deepstorage.net) # import argparse import os.path import os import re import statistics import textwrap import random import numpy as np import matplotlib as mpl ...
ministryofjustice/opg-docker
mongodb/docker/opt/reindex_database.py
#!/usr/bin/env python import os import argparse from subprocess import call admin_username = 'admin' admin_password = os.environ['MONGO_ADMIN_PASSWORD'] parser=argparse.ArgumentParser() parser.add_argument("-d", "--db-name", help="the DB to create the user in", required=True) parser.add_argument("-c", "--collection"...
ronhuang/adieu
backend/midautumn/handlers.py
#!/usr/bin/env python # Midautumn # Copyright 2011 Ron Huang # See LICENSE for details. from google.appengine.dist import use_library use_library('django', '1.2') import logging import midautumn.facebook as facebook from midautumn.models import FacebookUser from google.appengine.ext import webapp from midautumn.conf...
hippke/Pulsar-HabCat
matchATNF-full.py
"""Compare Pulsar and HabCat coordinates""" import csv import astropy.units as u from astropy.coordinates import SkyCoord, Angle from astropy import coordinates as coord def flipra(coordinate): """Flips RA coordinates by 180 degrees""" coordinate = coordinate + 180 if coordinate > 360: ...
buelowp/weatherstation
ButtonHandler.py
import RPi.GPIO as GPIO import threading class ButtonHandler(threading.Thread): def __init__(self, pin, func, edge='both', bouncetime=200): super().__init__(daemon=True) self.edge = edge self.func = func self.pin = pin self.bouncetime = float(bouncetime)/1000 self....
sergeimoiseev/othodi
bokehm.py
# -*- coding: UTF-8 -*- # to run by anaconda # from bokeh.plotting import figure, output_file, show import bokeh.plotting as bp import bokeh_gmapm import logging logger = logging.getLogger(__name__) class Figure(object): def __init__(self, *args, **kwargs): self._output_fname = kwargs.get('o...
mingkaic/rocnnet
app/pydemo/gym_demo.py
#!/usr/bin/env python import _init_paths import gym from tf_rl.controller import DiscreteDeepQ, NL specname = 'CartPole-v0' serializedname = 'dqntest_'+specname+'.pbx' spec = gym.spec(specname) env = spec.make() episode_count = 250 max_steps = 10000 action_space = env.action_space maxaction = action_space.n observ...
tekulvw/Squid-Plugins
selfbotstatus/selfbotstatus.py
import keyboard as kb import time import discord import asyncio class SelfBotStatus: def __init__(self, bot): self.bot = bot self.is_online = True self._last_time = 0 kb.hook(self.kb_press) self.status_task = None self.start = False def __unload(self): ...
ashishthedev/gae-django-skeleton
src/project_name/settings/gae.py
#!/usr/bin/env python import os # Load production settings when running on GAE or SETTINGS_MODE is prod # else, load local settings if (os.getenv('SERVER_SOFTWARE', '').startswith('Google App Engine') or os.getenv('SETTINGS_MODE') == 'prod'): os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project_name.settings.p...