code
stringlengths
1
199k
try: import memcache as MEM memcache = MEM.Client(['127.0.0.1:11211'], debug=0) except: from google.appengine.api import memcache from datetime import datetime from datetime import timedelta import csv import logging import math import random import re import urllib2 from realtime import twsk from realtime import...
from __future__ import absolute_import from fabric.api import task, local from fabric.context_managers import lcd @task def sphinx(): """Generate documentation.""" local("rm -rf docs/build/html") with lcd('docs'): local('sphinx-build -a -b html -d build/doctrees source build/html') @task def clean...
from __future__ import print_function import os import sys import time import traceback import json import requests from lxml import html from lxml import etree import re POSTS_PER_BATCH = 25 CONFIG_FILE = './ipb.conf' URL_LOGIN = "{}/index.php?act=Login&CODE=01" URL_LIST_POSTS = "{}/index.php?act=Search&nav=au&CODE=sh...
import collections import operator import os import json import logging import mimetypes import md5 from django.core.urlresolvers import reverse from django.core.cache import cache from django.conf import settings from django.contrib import messages from django.contrib.auth.models import User from django.http import Ht...
r""" Clang Indexing Library Bindings =============================== This module provides an interface to the Clang indexing library. It is a low-level interface to the indexing library which attempts to match the Clang API directly while also being "pythonic". Notable differences from the C API are: * string results ...
"""nova setup controller.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import os import shutil from cement.core.controller import CementBaseController, expose from nova.core import templates class NovaSetupControl...
""" Django settings for apartmentalerts project. For more information on this file, see https://docs.djangoproject.com/en/1.7/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.7/ref/settings/ """ import os BASE_DIR = os.path.dirname(os.path.dirname(__file__)) SECRE...
""" Provides functionality to circumvent GDB's hooks on sys.stdin and sys.stdout which prevent output from appearing on-screen inside of certain event handlers. """ import sys class Stdio: queue = [] def __enter__(self, *a, **kw): self.queue.append((sys.stdin, sys.stdout, sys.stderr)) sys.stdin ...
""" Custom Exception """ class BaseException(Exception): def deal_with(self): pass class RequestMissArgumentError(BaseException): """ Miss Request """ def __init__(self, msg='Args Miss.', code=233): self.msg = msg self.code = code super(RequestMissArgumentError, self)...
<<<<<<< HEAD <<<<<<< HEAD r"""XML-RPC Servers. This module can be used to create simple XML-RPC servers by creating a server and either installing functions, a class instance, or by extending the SimpleXMLRPCServer class. It can also be used to handle XML-RPC requests in a CGI environment using CGIXMLRPCRequestHandler....
from payu.models import Transaction, CancelRefundCaptureRequests from django.core.exceptions import ObjectDoesNotExist from django.utils.http import urlencode from django.conf import settings from hashlib import sha512 from uuid import uuid4 try: import urllib.request as urllib2 except ImportError: import urlli...
import mock from .. import collect def poison(*a, **kw): raise AssertionError('Poison called, args=%r kwargs=%r', a, kw) def test_simple_vm_then_lease(): cb = mock.Mock() s = collect.Collector(callback=cb) vm = { 'name': 'foo', 'uuid': '20398bc3-c328-4586-95fe-fd2295798cfe', 'int...
''' Unit tests for the gbdxtools.CatalogImage class See tests/readme.md for more about tests ''' import unittest from gbdxtools import WV01, WV02, WV03_VNIR, WV04, LandsatImage, Sentinel2 from gbdxtools import CatalogImage from helpers import mockable_interface, gbdx_vcr, \ WV01_CATID, \ WV02_CATID, \ WV03_...
import configparser import os import subprocess import sys import pkg_resources from setuptools import setup, find_packages import versioneer def get_requirements(): """ Get the project's setup-requires requirements from setup.cfg. :return: """ if not os.path.exists("setup.cfg"): return ...
""" RenderPipeline Copyright (c) 2014-2016 tobspr <tobias.springer1@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 rights to use, c...
import wikipedia import random import logging logger = logging.getLogger(__name__) def wiki_text(query): """ Get text from Wikipedia """ wiki_titles = wikipedia.search(query, results=10) if not wiki_titles: logger.error("No pages found for '{}'. Using random.".format(query)) return(w...
from CommonServerPython import * from CommonServerUserPython import * OAUTH_URL = '/oauth_token.do' class ServiceNowClient(BaseClient): def __init__(self, credentials: dict, use_oauth: bool = False, client_id: str = '', client_secret: str = '', url: str = '', verify: bool = False, proxy: bool = Fal...
from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('applications', '0001_initial'), ] operations = [ migrations.CreateModel( name='ShowApplicationSettings', fields=[ ...
import scipy.misc as smisc import numpy as np import matplotlib.pylab as plt import cv2 image = smisc.imread('carabiner.jpg') mindim = min(image.shape[:2]) image_r = smisc.imresize(image, 0.86) image_l = np.zeros((426,426,3)) offset = 45 imry, imrx, imch = image_r.shape image_l[:imry,offset:imrx+offset,:] = image_r smi...
import requests import json class CustomerScoringClient(): def __init__(self, base_url="http://not_real.com/customer_scoring?"): self.base_url = base_url def make_request(self, income, zipcode, age): """ Retrieves the request object with the customer propensity and ranking """ ...
class ApiResponseObject: def __init__(self): self.data = {} def prepare(self, **kwargs): self.data = kwargs return self def set_data(self, data): self.data = data return self def add_data(self, data): for key in data.keys(): self.data[key] = da...
import sqlite3 from sqlbuilder.smartsql import Q, T from sqlbuilder.smartsql.compilers.sqlite import compile from systemetapi import config def dict_factory(cursor, row): d = {} for idx, col in enumerate(cursor.description): value = row[idx] if type(value) is str: value = value.strip() d[col[0]] =...
from importlib.machinery import SourceFileLoader import xdg.BaseDirectory import os from stard import services class Loader: builtin_services = { 'executable': services.Executable, 'mount': services.Mount, 'copy': services.Copy, 'module': services.Module } def __init__(self, ...
'''Mempool handling.''' import itertools import time from abc import ABC, abstractmethod from collections import defaultdict import attr from aiorpcx import TaskGroup, run_in_thread, sleep from electrumx.lib.hash import hash_to_hex_str, hex_str_to_hash from electrumx.lib.tx import Deserializer from electrumx.lib.util i...
TOKEN_HASH_SEPARATOR = ':hash:' WRONG_TOKEN = 'wrong_token' WRONG_HASH = 'wrong_hash' def make_full_token(token, hash): return token + TOKEN_HASH_SEPARATOR + hash def parse_full_token(full_token): token_hash = full_token.split(TOKEN_HASH_SEPARATOR) # return bad results so verify function in crypto.py doesn'...
from django.db import models from django.contrib.auth.models import User from authentification.models import * class ForumPost(models.Model): contents = models.TextField() hashtags = models.TextField() statment = models.BooleanField(default=False) student = models.ForeignKey(Student) approval = mode...
import unittest from mock import Mock from redmate.reader import RedisReader class RedisReaderTest(unittest.TestCase): def setUp(self): self.redis = Mock(name="redis-client-mock") self.reader = RedisReader(self.redis) def test_read_keys(self): pattern = "keys:pattern:*" matched =...
""" This module contains classes and methods for working with physical quantities, particularly the :class:`Quantity` class for representing physical quantities. """ import numpy import quantities as pq import rmgpy.constants as constants pq.set_default_units('si') pq.UnitQuantity('kilocalories', pq.cal*1e3, symbol='kc...
import requests import lxml.html as html import time from datetime import date, datetime, timedelta from sense_hat import SenseHat import math import logging import sys formatter = logging.Formatter('%(levelname)s:%(message)s') ch = logging.StreamHandler(sys.stdout) ch.setLevel(logging.INFO) ch.setFormatter(formatter) ...
import os import cgi import subprocess from abc import abstractmethod, ABCMeta class OutputPrinter: __metaclass__ = ABCMeta @abstractmethod def render(self, webpages, failed_tests, passed_tests): pass class StandardPrinter(OutputPrinter): def __init__(self, color=False): OutputPrinter.__...
from .Operation import * __all__ = [ "SinOp", "LnOp", "ExpOp", ]
from flask import Flask, request, redirect, flash, get_flashed_messages, render_template, session from optparse import OptionParser import time import requests from StringIO import StringIO import unicodecsv from jinja2 import Markup import sys GOOGLE_DOC_SPREADSHEET_KEY = '0AjgNg5alNkjPdGxlNkZqc1pGazQxU05oU2xzRDhDdXc'...
import urllib2 from urllib2 import HTTPError try: # Python 2.6 and up import json as simplejson except ImportError: # This case gets rarer by the day, but if we need to, we can pull it from Django provided it's there. from django.utils import simplejson from datetime import datetime, timedelta from django.contrib.g...
from __future__ import print_function # make print patchable by mock from datetime import datetime import json import syslog class Level(object): """An object denoting the logging level of a logging event and logger.""" def __init__(self, name, priority): self.__name = name self.__priority = pri...
""" Flag the data """ import glob casalog.filter('DEBUGGING') for file_name in glob.glob('*.ms'): flagdata( vis=file_name, mode='manual', autocorr=True) flagdata( vis=file_name, mode='shadow', flagbackup=False) flagdata( vis=file_name, mode='rflag', datacolumn='data', ntime='30s') flagdata( vis=file_nam...
from __future__ import (absolute_import, division, print_function) __metaclass__ = type from ansible.errors import AnsibleError from ansible.plugins.lookup import LookupBase """ Lookup plugin to flatten nested dictionaries for linear iteration ================================================================= For exampl...
from openre.agent.decorators import action import time @action(namespace='domain') def ping(event): return 'pong' @action(namespace='domain') def exception(event): raise Exception('Test exception') @action(namespace='domain') def check_args(event, *args, **kwargs): return {'args': args, 'kwargs': kwargs} @a...
import re import speech_recognition as sr from Stephanie.AudioManager.audio_manager import AudioManager from Stephanie.TextManager.text_manager import TextManager from Stephanie.TextProcessor.text_sorter import TextSorter from Stephanie.TextProcessor.text_learner import TextLearner class AudioTextManager(AudioManager, ...
from _external import * from boost_system import * from boost import * boost_date_time = LibWithHeaderChecker( 'boost_date_time', 'boost/date_time.hpp', 'c++', dependencies=[boost] )
def change(n, m, A, B, C, mod): mulx = {} for i in range(m): b = mulx.get(B[i], 1) mulx[B[i]] = b * C[i] % mod for i, mul in mulx.items(): for j in range(i - 1, n, i): A[j] = A[j] * mul % mod if __name__ == '__main__': read = lambda: map(int, input().split()) (n, ...
import time import settings from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.support.wait import WebDriverWait class WorkflowyScheduler(object): workflowy_url = "https://workflowy.com" browser = webdriver.Firefox() @classmethod def schedule_items_for...
from __future__ import absolute_import, division, print_function, unicode_literals import os import braintree import mock import pytest from gratipay.billing.exchanges import create_card_hold, MINIMUM_CHARGE from gratipay.billing.payday import NoPayday, Payday from gratipay.exceptions import NegativeBalance from gratip...
import sys, os, unittest from test import test_support if not os.path.supports_unicode_filenames: raise test_support.TestSkipped, "test works only on NT+" filenames = [ 'abc', u'ascii', u'Gr\xfc\xdf-Gott', u'\u0393\u03b5\u03b9\u03ac-\u03c3\u03b1\u03c2', u'\u0417\u0434\u0440\u0430\u0432\u0441\u04...
import sys, os, unicodedata import subscript_lineage2taxonomyTrain, subscript_fasta_addFullLineage filename = sys.argv[1] try: open(filename,"r") except IOError: print "ERROR: file could not be opened." valid = 0 sys.quit() input_file = open(filename,"r") line = input_file.readline() temp0 = line.split("|") if line...
import hashlib def advent_coin_hash(input_string): x = 0 hash = hashlib.md5(input_string + str(x)).hexdigest() while hash[:6] != "000000": x += 1 hash = hashlib.md5(input_string + str(x)).hexdigest() return x if __name__=="__main__": input_string = "ckczppom" print advent_coin_ha...
import pytest import colander from glottolog3.models import Doctype from glottolog3.util import normalize_language_explanation, ModelInstance def test_normalize_language_explanation(): #for s in [' X [aaa]', 'L [aaa] = "X"', 'X = L [aaa]']: # assert normalize_language_explanation(s) == 'X [aaa]' assert n...
""" Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules. The Sudoku board could be partially filled, where empty cells are filled with the character '.'. A partially filled sudoku which is valid. Note: A valid Sudoku board (partially filled) is not necessarily solvable. Only the filled cells need t...
from ircsocket import IrcSocket from ircutils import regexpify from parser import parse, IRCMsg import config import os import re import sys class Mib: """ Main class which handles most of the core functionality. """ def __init__(self): """ Initialize variables and read config. """ s...
from django.conf.urls import url from app.views import index urlpatterns = [ url(r'^$', index.index), url(r'^home', index.index), url(r'^index', index.index), url(r'^about', index.about), ]
from django.conf.urls import patterns, include, url from django.contrib import admin urlpatterns = patterns('', url(r'^$', 'nzpower.views.index', name='home'), url(r'^nzpower/', include('nzpower.urls')), url(r'^admin/', include(admin.site.urls)), )
class ScreenMockBase(object): """ Base mock object for the screen """ monitor_geometry = [] windows = [] def get_all_windows(self): """ Gets all windows in the screen """ return self.windows def get_monitor_geometry(self, monitor=None): """Returns a rectangle with geometry of...
import json import Queue import uuid import webapp2 from google.appengine.ext import db from google.appengine.api import memcache class Match(db.Model): match_time = db.DateTimeProperty(auto_now_add=True) player_one_id = db.StringProperty() player_two_id = db.StringProperty() class MatchRound(db.Model): round =...
import io import logging import os import re import subprocess import sys import tempfile sys.path.append(os.path.join(os.environ['HOME'], 'dicom/pydicom')) sys.path.append(os.path.join(os.environ['HOME'], 'dicom/pynetdicom3')) import pydicom from typing import IO logging.basicConfig(level=logging.INFO) def recurse_tre...
from __future__ import unicode_literals from django.db import models, migrations import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('taxbrain', '0014_auto_20151124_2029'), ('dynamic', '0005_remove_dynamicsaveinputs_micro_sim'), ] operations = [ ...
''' Given the same parameters, will tclean return the same result as clean? ''' from tasks import tclean, clean, exportfits tclean(vis='../14B-088_HI.ms.contsub', datacolumn='data', imagename='tclean_test_dirty_rightpointings_casa5.0', field='M33_2, M33_4, M33_1, M33_14', imsize=[2560, 2560]...
import time from struct import pack from electrum import ecc from electrum.i18n import _ from electrum.util import UserCancelled from electrum.keystore import bip39_normalize_passphrase from electrum.bip32 import BIP32Node, convert_bip32_path_to_list_of_uint32 from electrum.logging import Logger class GuiMixin(object):...
__author__ = 'miko' from de.hochschuletrier.jpy.states.StartGameState import StartGameState from de.hochschuletrier.jpy.states.PlayGameState import PlayGameState class GameStateManager: def __init__(self, root): self.activeState = 0 self.root = root self.states = [] self.generateStates() self.changeState(0) ...
from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('suite', '0037_merge_20170306_1718'), ] operations = [ migrations.AddField( model_name='event', name='event_fee', fiel...
from __future__ import unicode_literals import unittest from functools import wraps import weakref from elasticsearch import helpers from elasticsearch.client import Elasticsearch from elasticsearch.helpers import scan from slingshot.indices_manager import IndicesManagerClient from slingshot.exceptions import IndexDoes...
from __future__ import with_statement import datetime import socket import os, sys, subprocess, re from threading import Lock from phantom import logger from common import SD, SKIPPED, NAMING_REPEAT import ConfigObj invoked_command = None SOCKET_TIMEOUT = 30 PID = None CFG = None CONFIG_FILE = None CONFIG_VERSION = 1 P...
"""pblite message schemas and related enums.""" import enum from hangups.pblite import Message, Field, RepeatedField, EnumField class TypingStatus(enum.Enum): """Typing statuses.""" TYPING = 1 # The user started typing PAUSED = 2 # The user stopped typing with inputted text STOPPED = 3 # The user sto...
from .utils import execute_code def test_JMP(): program = ''' .data .text .global main: main: LDV C, 24 JMP branch: return: LDV A, 20 HLT branch: ; To make sure we don't just go trough the program ...
import _plotly_utils.basevalidators class HoverinfoValidator(_plotly_utils.basevalidators.FlaglistValidator): def __init__(self, plotly_name="hoverinfo", parent_name="waterfall", **kwargs): super(HoverinfoValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, ...
""" Created on 7.5.2014 @author: mhanus """ from common import * from argparse import ArgumentParser parser = ArgumentParser(description='Description.') parser.add_argument('problem_name', help="Problem name. Defines the subfolder in the 'problems' folder serving as the parent folder " ...
from django.contrib.auth.models import AbstractBaseUser from django.contrib.auth.models import BaseUserManager from django.contrib.auth.models import PermissionsMixin from django.db import models from django.db.models.signals import post_save from django.dispatch import receiver from django.utils import timezone from d...
import os import time import sys import requests POP20_CC = ('CN IN US ID BR PK NG BD RU JP MX PH VH ET EG DE IR TR CD FR').split() BASE_URL = 'http://flupy.org/data/flags' DEST_DIR = 'downloads/' def save_flag(img, filename): path = os.path.join(DEST_DIR, filename) with open(path, 'wb') as fp: fp.write(img) de...
from flask_rest_api.utils import deepupdate, load_info_from_docstring class TestUtils(): def test_deepupdate(self): """Test deepupdate function Taken from http://stackoverflow.com/questions/38987#8310229 """ pluto_original = { 'name': 'Pluto', 'details': { ...
import bs4 import collections import multiprocessing import unicodedata import requests import re TITLE_PATTERN = re.compile(r'([^\.]+)\. (.+?)\.?(?: \d+ Units\.)?') Record = collections.namedtuple('Record', ['name', 'description']) def parse_title(title): match = TITLE_PATTERN.fullmatch( unicodedata.norm...
""" Created on Thu Apr 21 17:25:27 2016 @author: Felipe """ import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns comixology_df = pd.read_csv("comixology_comics_dataset_19.04.2016.csv", encoding = "ISO-8859-1") comixology_df['Price_per_page'] = pd.Serie...
from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('text_search', '0001_initial'), ] operations = [ migrations.AddField( model_name='annotatedtoken', name='is_rubric', field=models.BooleanField(default=False),...
PREFERENCES_PATH = 'preferences' import os def add(name, value, overwite_existing=False): if not os.path.exists(PREFERENCES_PATH): os.makedirs(PREFERENCES_PATH) if os.path.isfile(os.path.join(PREFERENCES_PATH, name)) and not overwite_existing: raise Exception('Preference already exists', '{0} has already b...
""" Test Cases Generator Usage: test_cases_generator.py test_cases_generator.py -l LANGUAGE [-f FLAW_GROUP ...] [-c CWE ...] [-r DEPTH] [-g NUMBER_GENERATED] [-s | -u] [-d] test_cases_generator.py (-h | --help) test_cases_generator.py (-d | --debug) test_cases_generator.py --version Options: -h,...
import os f = open('maven_projects.csv', 'r') pjt_id = f.readline().replace('\r', '').replace('\n', '') pjt_name = pjt_id.split('/')[-1] while pjt_id: git_url = 'https://github.com/' + pjt_id + '.git' print git_url os.system('git clone ' + git_url) os.chdir('./pom_edit/jacoco') os.system('python pom...
print('Build word embeddings') import tensorflow as tf import numpy as np from six.moves import urllib import errno import os import zipfile from collections import Counter, deque import random random.seed(5) tf.set_random_seed(5) WORDS_PATH = 'datasets/words' WORDS_URL = 'http://mattmahoney.net/dc/text8.zip' def mkdir...
from __future__ import unicode_literals, division, absolute_import, print_function import unittest import os import asn1crypto.x509 from oscrypto import asymmetric from ocspbuilder import OCSPRequestBuilder from ._unittest_compat import patch patch() tests_root = os.path.dirname(__file__) fixtures_dir = os.path.join(te...
from __future__ import print_function from setuptools import setup, Extension import numpy as np USE_CYTHON = True DISTNAME = 'lsh' DESCRIPTION = 'A library for performing shingling and LSH for python.' MAINTAINER = 'Matti Lyra' MAINTAINER_EMAIL = 'm.lyra@sussex.ac.uk' URL = 'https://github.com/mattilyra/lsh' DOWNLOAD_...
import variants
from configvars import access_token, access_token_secret, consumer_key, consumer_secret from add_to_db import addUserToDB, addLangs, addSkills, addOffer, dbCheck from tweetparse import tweetParse import tweepy auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_sec...
import sublime from subprocess import PIPE, Popen, os from threading import Thread from queue import Queue from Agda.log import logger class Agda(object): # executable agda_path = None """Talks to Agda""" def __init__(self, id, filename): # super(Agda, self).__init__() self.id = id ...
import vehicle import matplotlib.pyplot as plt def loadDatasetInfo(traininSetFolder,steeringAngleFileName): imfiles=[] steers=[] with open(traininSetFolder+ steeringAngleFileName) as f: for line in f: if line.startswith("frame_id") : continue fields = line.spl...
''' Created on Mar 16, 2015 @author: brecht ''' import abc from multiprocessing import Pipe from multiprocessing.process import Process from cassandra.cluster import Cluster import array import sys from multiprocessing.synchronize import Event class Expression(object): __metaclass__ = abc.ABCMeta @abc.abstractm...
from django.shortcuts import render, get_object_or_404 from .models import Proform def index(request, proform_id): proform = get_object_or_404(Proform, id=proform_id) context = {} context['proform'] = proform context['works'] = proform.works.all() return render(request, 'documents/proform/print.html...
"""pytest configuration and top-level fixtures.""" import os import string import tempfile import pytest from tests.utils import download_file pytest_plugins = [ 'tests.test_ciscosparkapi', 'tests.api.test_accesstokens', 'tests.api.test_memberships', 'tests.api.test_messages', 'tests.api.test_people...
from .counterwalletseed import * """Counterwallet and Electrum are equivalent last time I checked """
from conan.tools._check_build_profile import check_using_build_profile from conan.tools._compilers import architecture_flag, build_type_flags, cppstd_flag, \ build_type_link_flags from conan.tools.apple.apple import apple_min_version_flag, to_apple_arch, \ apple_sdk_path from conan.tools.build.cross_building im...
import json import random import string from werkzeug.test import Client import spa from mettle.settings import get_settings, DEV_USERNAME from mettle.db import make_session_cls from mettle.web import make_app from mettle import models def get_db(): settings = get_settings() return make_session_cls(settings.db_...
""" Created on Thu Apr 16 11:16:47 2015 @author: Dominic White """ class CharMatrix: def __init__(self,name): self.name=name self.total_chars=0 self.total_taxa=0 self.char_names = {} self.taxa_names=[] self._taxa_indices={} self.chars={} def add_character(...
__version__ = '1.0.0' __license__ = 'MIT' __author__ = 'pb' import functools import logging from threading import Condition import threading class Delayer(object): ''' Delay: A python Function / Method delay executing system base on function Decorators. Auto delay the Function execution for a certain pe...
from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('common', '0029_auto_20210730_1328'), ] operations = [ migrations.AlterField( model_name='user', name='role', field=models.CharField(choices=[('ADMIN', 'ADMIN...
from codecs import open as codecs_open from setuptools import setup, find_packages with codecs_open('README.rst', encoding='utf-8') as f: long_description = f.read() setup(name='nextbus', version='0.0.1', description=u"Skeleton of a Python package", long_description=long_description, classif...
"""Badge blueprint.""" from flask import Blueprint, request, abort from flask.helpers import send_from_directory from .error import errorhandler from .model import get_repo_status badge = Blueprint('badge', __name__, static_folder='badges') def render_badge(status): """Render the static file for a given badge statu...
import numpy as np import cv2 class imageControl(object): #image properities contours = 0 hierarchy = 0 contourSize = 0 motionDetected = False BLUR_SIZE = 10 SENSITIVITY_VALUE = 40 #frames needed for motion detection image1 = 0 image2 = 0 differenceImage = 0 thresholdImag...
import time from poseidon.api import Resource, MutableCollection class Droplets(MutableCollection): """ A Droplet is a DigitalOcean virtual machine. By sending requests to the Droplet endpoint, you can list, create, or delete Droplets. Some of the attributes will have an object value. The region, image,...
import logging import os import webapp2 from base64 import b64encode, b64decode import random class MainPage(webapp2.RequestHandler): def get(self): # Serve the index indexurl = "index.html" f = open(indexurl) self.response.status = 200 self.response.write( f.read() ) application = webapp2.WSGIApp...
""" Python Interchangeable Virtual Instrument Library Copyright (c) 2012-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 ri...
from ..base import HaravanResource class LineItem(HaravanResource): class Property(HaravanResource): pass
import socket import sys import thread def main(setup, error): sys.stderr = file(error, 'a') for settings in parse(setup): thread.start_new_thread(server, settings) lock = thread.allocate_lock() lock.acquire() lock.acquire() def parse(setup): settings = list() for line in file(setup)...
''' ''' import unittest class TestCases(unittest.TestCase): def test1(self):self.assertEqual(push(None, 1).data, 1, "Should be able to create a new linked list with push().") def test2(self):self.assertEqual(push(None, 1).next, None, "Should be able to create a new linked list with push().") def test3(self)...
from imgpy import Img from PIL import Image, ImageSequence, ImageOps import sys if (len(sys.argv[1:]) == 1): source = sys.argv[1] else: print("Too many arguments. Please do only provide the name of the source-file.") sys.exit(1) image = Image.open(source) frames = ImageSequence.Iterator(image) def crop(fram...
""" Generate for random scale free graph @author: szs """ __author__ = """Zhesi Shen (shenzhesi@mail.bnu.edu.cn)""" __all__ = ['continuous_ba' , 'static' ] import random import numpy as np import networkx as nx def continuous_ba(n, m, seed=None): """Return a scale free random graph. Parameters ...