content string |
|---|
#!/usr/bin/env python
""" A unittest script for the WgsRawSeqSet module. """
import unittest
import json
import tempfile
from cutlass import WgsRawSeqSet
from CutlassTestConfig import CutlassTestConfig
from CutlassTestUtil import CutlassTestUtil
# pylint: disable=W0703, C1801
class WgsRawSeqSetTest(unittest.TestC... |
""" utility functionality for molecular similarity
includes a command line app for screening databases
Sample Usage:
python MolSimilarity.py -d data.gdb -t daylight_sig --idName="Mol_ID" \
--topN=100 --smiles='c1(C=O)ccc(Oc2ccccc2)cc1' --smilesTable=raw_dop_data \
--smilesName="structure" -o results.... |
#!/usr/bin/env python
# There is still a great deal of work required on this module. Please
# use with caution.
# -Jordan
import sys
from ipaddress import (
IPv6Address,
IPv6Network,
ip_network,
ip_address,
)
from math import (
log,
)
class MapCalc(object):... |
from saluttest import exec_test
from file_transfer_helper import SendFileTest
from twisted.words.xish import domish
import constants as cs
class SendFileItemNotFound(SendFileTest):
def client_request_file(self):
# Receiver can't retrieve the file
reply = domish.Element(('', 'iq'))
reply['... |
from __future__ import absolute_import, division, print_function, unicode_literals
from pants.base.exceptions import TargetDefinitionException
from pants.base.payload import Payload
from pants.base.payload_field import PrimitiveField
from pants.build_graph.address import Address
from pants.build_graph.target import Ta... |
"""Tests metadata flags feature by testing wait-for-ready semantics"""
import time
import weakref
import unittest
import threading
import logging
import socket
from six.moves import queue
import grpc
from tests.unit import test_common
from tests.unit.framework.common import test_constants
import tests.unit.framework... |
# -*- coding: utf-8 -*-
import sys, os
import math
import time
from PyQt4.QtOpenGL import QGLWidget
from PyQt4 import QtGui
from PyQt4 import QtCore
from OpenGL.arrays import vbo
from OpenGL.GL import *
import numpy as np
from GLDemo.Camera import Camera
from GLDemo.MyGeom import Point3D
#from Nao3D import Nao3D ... |
"""
Implementation of Circle.
"""
from _ISQLProtocol import ISQLProtocol
from _Point import Point, pointFromSequence
class Circle(ISQLProtocol):
"""
Circle provides an implementation for a circle in 2d space.
It has accessor functions for a centre Point and radius size,
provides a constructor that ca... |
from __future__ import annotations
from typing import Optional
from baseframe import __
from baseframe.forms.sqlalchemy import QuerySelectField
from coaster.auth import current_auth
import baseframe.forms as forms
from ..models import Project, Proposal
__all__ = [
'ProposalForm',
'ProposalLabelsAdminForm',
... |
from wader.common.consts import WADER_CONNTYPE_PCMCIA
from core.hardware.novatel import NovatelWCDMADevicePlugin
class NovatelU630(NovatelWCDMADevicePlugin):
""":class:`~core.plugin.DevicePlugin` for Novatel's U630"""
name = "Novatel U630"
version = "0.1"
author = u"Pablo Martí"
__remote_name__ =... |
from datetime import datetime
import matplotlib.pylab as plt
import glob
import matplotlib.dates as mdates
import numpy as np
# R1 Plot Figure
# Script to build figures from data saved in R1_*.py routines.
# See R1_dataqual.py for information on data saves.
# READ DATA
datdir = '/Users/gabin/Documents/FMI/ABOA_dat... |
import requests
from requests.auth import AuthBase
from six.moves.urllib.parse import urlparse
from dcos import config, util
from dcos.errors import (DCOSAuthenticationException,
DCOSAuthorizationException, DCOSBadRequest,
DCOSConnectionError, DCOSException, DCOSHTTP... |
import os
import os.path as path
from audio_pipeline import Constants
from audio_pipeline.file_walker import ProcessLog
import abc
class Serializer(abc.ABC):
def __init__(self, output_dir):
"""
Serialize audio file metadata from MusicBrainz with the specified format
:param output_... |
#! /usr/bin/python
from dolfin import *
import sys
N = 32
epsilon = 0.125
T = 1
c = 0.5
h = 1.0 / (N + 1)
dt = 0.5 * h * h / epsilon
iteration = 0
info("Initial parameters: N = {0}; epsilon = {1}; h = {2}; dt = {3}".format(N, epsilon, h, dt))
mesh = UnitSquareMesh(N, N)
V = FunctionSpace(mesh, 'La... |
"""Test the serializers module."""
import common
import unittest
from flask import Flask
from flask.ext.bracket import Error, serializers
class TestSerializer(common.SerializerTestCase):
"""Test Serializer class."""
def test_init(self):
"""Serializer.__init__"""
serializer = serializers.Seri... |
import time
from datetime import datetime
import requests_mock
import simplejson as json
from django.contrib.auth import get_user_model
from rest_framework.test import APITestCase
from stripe.webhook import WebhookSignature
from aa_stripe.models import StripeCoupon, StripeCustomer
from aa_stripe.settings import strip... |
from __future__ import unicode_literals
from hy import HyString
from hy.models import HyObject
from hy.compiler import hy_compile
from hy.errors import HyCompileError, HyTypeError
from hy.lex.exceptions import LexException
from hy.lex import tokenize
from hy._compat import PY3
import ast
def _ast_spotcheck(arg, roo... |
# -*- coding: UTF-8 -*-
#! python3
"""
Isogeo API v1 - API Routes for Workgroups entities
See: http://help.isogeo.com/api/complete/index.html#tag-workgroup
"""
# #############################################################################
# ########## Libraries #############
# ##############################... |
from django.db import models, IntegrityError
from django.test import TestCase
from model_mommy import mommy
from rapidsms.backends.database import DatabaseBackend
from rapidsms.backends.database.models import BackendMessage
from rapidsms.tests.harness import CustomRouterMixin
from ..models import MultitenantIncompati... |
dz = 1
debug = 1
try : ListObj
except NameError : ListObj = []
try: Connections
except NameError: Connections = []
try : publish
except NameError : publish = 1
try : Groups
except NameError : Groups = []
try : StudyName
except NameError : StudyName = "Compound"
try : Criterion
except NameError : Criterion = 1
tr... |
from nanopores import *
from nanopores.geometries.curved import Circle
from dolfin import *
geo_name = "H_geo"
nm = import_vars("nanopores.geometries.%s.params_geo" %geo_name)["nm"]
add_params(
z0 = 0.*nm,
bV = -0.1,
Nmax = 1e4,
)
geo_params = dict(
#x0 = None,
x0 = [0.,0.,z0],
#x0 = [0., 0., -8.372*nm],
rMolecule =... |
import random
import jingo
from users.models import Profile
from projects.models import Project
from events.models import Event
from feeds.models import Entry
def splash(request):
"""Display splash page. With featured project, event, person, blog post."""
def get_random(cls, **kwargs):
choices = cls... |
import codecs
import os
import sys
import time
import traceback
from datetime import datetime
from optparse import make_option
from StringIO import StringIO
from webkitpy.common.config.committervalidator import CommitterValidator
from webkitpy.common.config.ports import DeprecatedPort
from webkitpy.common.net.bugzill... |
from sys import stdin, stdout
from time import sleep
import board
import neopixel
from digitalio import DigitalInOut, Direction, Pull
from supervisor import runtime
from cpgame import after, cancel, every, on, start
from colors import RED, ORANGE, GREEN, YELLOW, BLUE, VIOLET, WHITE, OFF
pixels = neopixel.NeoPixel(b... |
from setuptools import Extension
from distutils.core import setup
from setuptools.command.test import test as TestCommand
from Cython.Distutils import build_ext
from Cython.Build import cythonize
import sys
# cython = Extension('ea.cbenchmarks',
# sources = ['ea/cbenchmarks.pyx'],
# include_dirs = ['include/']
#... |
from ulakbus.models import User
from zengine.lib.test_utils import BaseTestCase
import time
from ulakbus.lib.common import EPostaDogrulama
k_adi_parametreleri = ['eski_k_adi', 'yeni_k_adi']
k_adi_hatalari = [('yanlis_k_adi', 'yanlis_k_adi', 'Kullanıcı adınızı yanlış girdiniz'),
('ulakbus', 'ulakbus',... |
from ._utils import unique
from .abstract import isGraphElement
from .uri import Uri, matchesIriSyntax
from .bnode import BNode
from .literal import Literal
from .graph import Graph
from .graphcomponent import GraphComponent
from .rdfparser import RDFParser
from .triples2rdfxml import Triples2RdfXml
from ._uris import ... |
from django.core.urlresolvers import reverse
from django.contrib.auth.models import User
from rest_framework import status
from rest_framework.test import APITestCase
from lists.models import TodoList
class UserTests(APITestCase):
def setUp(self):
User.objects.create_user('test', '<EMAIL>', 'test')
... |
from django.test import TestCase
from mongoengine import Document, fields
from rest_framework.test import APIRequestFactory, APITestCase
from rest_framework_mongoengine.contrib.patching import Patch, PatchModelMixin
from rest_framework_mongoengine.serializers import DocumentSerializer
from rest_framework_mongoengine.v... |
"""
Reflection APIs which have been ported to Python 3.
"""
from __future__ import division, absolute_import
import types, sys, os, traceback
from twisted.python.compat import reraise, nativeString, NativeStringIO
def prefixedMethodNames(classObj, prefix):
"""
Given a class object C{classObj}, returns a li... |
"""
Helper functions for working with the Python built-in logging module.
"""
from __future__ import absolute_import
import collections
import logging
import logging.handlers
import os
def get_logger(name=None, level=logging.NOTSET, handlers=None):
"""
Create a Python logging Logger for the given name. A special c... |
from ckeditor.widgets import CKEditorWidget
from typing import Dict, Optional
from django import forms
from django.conf import settings
from django.contrib.auth.models import User
from django.utils.translation import gettext_lazy as _
from base.forms.utils.fields import OsisRichTextFormField
from education_group.cale... |
"""
Script for building NodeBox
Usage:
python setup.py py2app
"""
from distutils.core import setup
from setuptools.extension import Extension
import py2app
import nodebox
NAME = 'NodeBox extended'
VERSION = nodebox.__version__
AUTHOR = "Frederik De Bleser",
AUTHOR_EMAIL = "<EMAIL>",
URL = "http://nodebox.net/... |
#!/usr/bin/env python
# No longer really needed but I'll keep it here anyway
import socket
import select
import random
import ssl
import sys
import time
import os
import pickle
from datetime import datetime
import json
import getpass
USEDB = True
if USEDB == True and os.path.isfile(os.path.expanduser("~") +'/.quote... |
"""
Markdown.py
0. just print whatever is passed in to stdin
0. if filename passed in as a command line parameter,
then print file instead of stdin
1. wrap input in paragraph tags
2. convert single asterisk or underscore pairs to em tags
3. convert double asterisk or underscore pairs to strong tags
... |
import numpy as np
import mpld3
import matplotlib.pyplot as plt
from datetime import datetime
import os
import time
#import settigns from django project
os.environ.setdefault('DJANGO_SETTINGS_MODULE',
'sensor_app.settings')
#set it up
import django
django.setup()
#import Plot model
from plotter.... |
from __future__ import unicode_literals
import binascii
import struct
from base64 import urlsafe_b64encode, urlsafe_b64decode
from pymacaroons.utils import convert_to_bytes
from pymacaroons.serializers.base_serializer import BaseSerializer
from pymacaroons.exceptions import MacaroonSerializationException
class Bina... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import json
# 100-900, A100, A200, A400, A700
# red
# pink
# purple
# deep purple
# indigo
# blue
# light blue
# cyan
# teal
# green
# light green
# lime
# yellow
# amber
# orange
# deep orange
# brown... |
#!/usr/bin/env python
"""
Update the 'logs' file with events and check for any incorrect shutdowns. If
found add an incorrect shutdown warning to the 'logs' file. Implement a mutex
lock to avoid process clashes.
The 'logs' file has the format: $date#time#text$date ...
"""
import os
import time
import logger
from mut... |
"""This file contains code for use with "Think Stats",
by Allen B. Downey, available from greenteapress.com
Copyright 2014 Allen B. Downey
License: GNU GPLv3 http://www.gnu.org/licenses/gpl.html
"""
from __future__ import print_function
import pandas
import numpy as np
import statsmodels.formula.api as smf
import st... |
from pyforms.Controls import ControlFile, ControlSlider, ControlText, ControlCombo, ControlCheckBox, ControlBase, ControlDir
from datetime import datetime, timedelta
import argparse, uuid, os, shutil, time, sys, subprocess
try:
import requests
except:
print("No requests lib")
class BaseWidget(object):
def __... |
from mongoengine.base import BaseField
from Crypto.Cipher import AES
from .exceptions import EncryptionKeyException, CipherModeException
import binascii
class EncryptedField(BaseField):
''' Constants '''
_AES = 'AES'
_SHA_256 ='SHA256' # Hashing algorithm
_AES_SHA='AES+SHA'
_CBC = 'CBC'
_CFB... |
#!/usr/bin/env python
"""
Copyright (c) 2016 <EMAIL>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publi... |
import os
import py_entitymatching as em
import py_entitymatching.catalog.catalog_manager as cm
import py_entitymatching.debugblocker.debugblocker as db
p = em.get_install_path()
datasets_path = os.sep.join([p, 'datasets', 'example_datasets', 'debugblocker'])
ab = em.AttrEquivalenceBlocker()
class TimeDebugBlockingA... |
from __future__ import unicode_literals
from operator import attrgetter
from django import VERSION
from django.contrib.contenttypes.generic import GenericRelation
from django.contrib.contenttypes.models import ContentType
from django.db import models, router
from django.db.models.fields import Field
from django.db.mod... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from ray.rllib.utils.annotations import DeveloperAPI
import logging
import time
import base64
import numpy as np
import pyarrow
from six import string_types
logger = logging.getLogger(__name__)
try:
impo... |
"""
sentry.utils.models
~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2013 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
import hashlib
import logging
from django.db import models, router, transaction, IntegrityError
from django.db.models import signals
from django.db.... |
import numpy as np
import functools
from ray.rllib.models.action_dist import ActionDistribution
from ray.rllib.policy.policy import TupleActions
from ray.rllib.utils.annotations import override, DeveloperAPI
from ray.rllib.utils import try_import_tf
tf = try_import_tf()
@DeveloperAPI
class TFActionDistribution(Acti... |
"""
Google OpenID and OAuth support
OAuth works straightforward using anonymous configurations, username
is generated by requesting email to the not documented, googleapis.com
service. Registered applications can define settings GOOGLE_CONSUMER_KEY
and GOOGLE_CONSUMER_SECRET and they will be used in the auth process.
... |
import Tkinter as tk
import os
import tkMessageBox
from mainapp import MainApplication
from TopMenu import TopMenu
from BeamGapWidget import BeamGapWidget
import logging
from Monitor import Monitor
from ttk import Notebook
from Threads import TelemetryThread
import VisualConstants
#from PIL import ImageTk
logger = log... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import plot
# MPS, KES, (ABC)
f, ((ax1,ax2,ax3),(ax4,ax5,ax6)) = plot.subplots(nrows=2, ncols=3, sharex=True, sharey=True)
ylow, yhigh, lw = -38,38,1
ax1.axhline(2.77, color='indianred', ls='-',lw=lw)#, alpha=0.5)
ax4.axhline(2.77, color='indianred', ls='-',lw=lw)#, alp... |
# SNAKE GAME
# Python 3.5.2 Pygame
import pygame, sys, time, random
# Pygame Init
init_status = pygame.init()
if init_status[1]>0 :
print("(!) Had {0} initialising errors, exiting... ".format(init_status[1]))
sys.exit()
else :
print("(+) Pygame initialised successfully ")
# Play Surface
size = width,... |
#! /usr/bin/env python
# -*- encoding: utf-8 -*-
'''
http://www.pythonchallenge.com/pc/return/5808.html
'''
# Since May 29 2012
import Image
im = Image.open('cave.jpg')
width, height = im.size
# v1
for y in range(height): # row
for x in range(width): # column
if (x+y) % 2 != 0:
im.putpixel(... |
#!/usr/bin/env python
import os
import time as tm
# Handles the creation of condor files for a given set of directories
# -----------------------------------------------------------------------------
def createCondorFile(mDir,run,day):
# Condor submission file name convention: run-day-time.condor
with open('/h... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# name: test_password.py
# email: <EMAIL>
# created on: 11/07/2015
#
# pylint: disable=invalid-name
"""
A unit test for ext_pylib module's password functions.
"""
import pytest
from ext_pylib.password import generate_pw
from ext_p... |
"""This Script For A Data Type"""
#!/usr/bin/env python
# import string
import json
import copy
class Data(object):
def __init__(self, className, data = {}):
self._class_name = className
self._data = copy.deepcopy(data)
def get_class_name(self):
return self._class_name
def get(se... |
#!/usr/bin/python
from scipy import stats
import csv
import math
class ContestRegression(object):
def __init__(self, party, independent, dependent, county):
self._party = party
self._independent = independent
self._dependent = dependent
self._county = county
self._independent_data = dict()
... |
'''
Created on Aug 2, 2016
@author: <EMAIL>
'''
from __future__ import print_function
import unittest
from authclient import KBaseAuth # @UnresolvedImport
import os
from ConfigParser import ConfigParser
import requests
from requests import ConnectionError
class TestAuth(unittest.TestCase):
AUTHURL = 'test.au... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin
from django.conf import settings
from django.shortcuts import render
from django.views import View
from django.urls import reverse, reverse_... |
"""
byceps.blueprints.core.views
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2019 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from datetime import date, datetime
from flask import g, render_template
from ... import config
from ...services.party import service as party_service
from ..... |
#!/usr/bin/env python3
"""
Dummy random Avalam agent.
Author: Cyrille Dejemeppe <<EMAIL>>
Copyright (C) 2015, UCLouvain
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; version 2 of the License.
This... |
##[TBT-Tools]=group
##Input_Footprints=vector
##Output_Wget_List= file
import os,sys
outList = Output_Wget_List
if len(outList) == 0:
outDir = os.environ['HOME']
outList = os.path.join(outDir,'wget.list')
from qgis.utils import *
# Get vector from canvas, must be loaded with features selected.
layer = proce... |
"""API to access a remote file system for synchronization."""
import unicodedata
from collections import namedtuple
from datetime import datetime
import os
from nxdrive.logging_config import get_logger
from nxdrive.client.common import NotFound
from nxdrive.client.base_automation_client import BaseAutomationClient
fro... |
# -*- coding: utf-8 -*-
'''
Created on 7 Dec 2012
@author: Éric Piel
Copyright © 2012 Éric Piel, Delmic
This file is part of Odemis.
Odemis is free software: you can redistribute it and/or modify it under the terms
of the GNU General Public License version 2 as published by the Free Software
Foundation.
Odemis i... |
from tempest.api.image import base
from tempest import test
class ImageMembersTest(base.BaseV1ImageMembersTest):
@test.idempotent_id('1d6ef640-3a20-4c84-8710-d95828fdb6ad')
def test_add_image_member(self):
image = self._create_image()
self.image_member_client.create_image_member(image, self.a... |
import os
import argparse
import logging
logging.basicConfig(level=logging.DEBUG)
import random
import mxnet as mx
import numpy as np
from common import find_mxnet, dali, fit
from mlperf_compliance import constants as mlperf_constants
from mlperf_compliance import tags as mlperf_log
from mlperf_compliance.mlperf_log i... |
# Standard Library
import os
import shutil
from os import makedirs, mknod
from os.path import abspath, dirname, exists, isdir, isfile, realpath
# import types for static typing (mypy, pycharm etc)
from typing import Iterable, Optional, Text
def up_by_n_dirs(path: Text, n: int) -> Text:
return path if n == 0 else ... |
#-*- coding:utf-8 -*-
"""
This file is part of OpenSesame.
OpenSesame is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
OpenSesame is distri... |
# coding: utf-8
"""
MIT License
Copyright (c) 2020 Claude SIMON (https://q37.info/s/rmnmqd49)
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 limita... |
from copy import copy
import sqlalchemy as sa
from sqlalchemy_utils import get_primary_keys, identity
from .operation import Operations
from .utils import (
end_tx_column_name,
version_class,
is_session_modified,
tx_column_name,
versioned_column_properties
)
class UnitOfWork(object):
def __in... |
import os, re
from mpicbg.stitching import StitchingParameters,ImageCollectionElement,CollectionStitchingImgLib
from stitching import ImageInformation
import argparse
#import convertmetadata
from java.io import File
from mpicbg.models import TranslationModel2D;
from java.util import ArrayList
#from net.imglib2... |
#!/usr/bin/env/ python
# encoding: utf-8
"""
Public cryptography tools.
"""
import random
import collections
import functools
import matasano.hash
import matasano.blocks
import matasano.util
import matasano.mac
import matasano.math
__author__ = 'aldur'
dh_nist_p = int(
"""0xffffffffffffffffc90fdaa22168c234c4c6... |
#!/usr/bin/env python
"""
This script checks whether DNS entries for ips in the given subnet could be removed from DNS.
Copyright 2013 by Reiner Rottmann (<EMAIL>). Released under the BSD license.
"""
import os
import sys
import socket
import logging
from optparse import OptionParser
logging.basicConfig(format='%(le... |
from __future__ import annotations
from typing import *
from edb.ir import ast as irast
from edb.edgeql import qltypes
from .. import context
class InfCtx(NamedTuple):
env: context.Environment
inferred_cardinality: Dict[
Tuple[irast.Base, irast.ScopeTreeNode],
qltypes.Cardinality]
inferr... |
from collections import defaultdict
import cherrypy
from pockets.autolog import log
from uber.config import c
from uber.decorators import ajax, all_renderable, csv_file
from uber.errors import HTTPRedirect
from uber.models import Attendee, MITSTeam
from uber.utils import add_opt, check_csrf
@all_renderable()
class ... |
# vim:set ts=4 expandtab:
import ctypes
import ctypes.util
import os
import re
import socket
import struct
import subprocess
import pexpect
from .. import generic
SUPPORTS_MULTIPATH = False
SUPPORTS_PREFSRC = False
_libc = ctypes.CDLL(ctypes.util.find_library('c'))
def if_nametoindex(name):
return _libc.if_na... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
circumbinary_exomoon.py |github|
--------------------------------
A (crazy) example of the code's ability to handle nested multi-body systems.
Here we have a moon orbiting a planet orbiting two stars in a binary system.
All bodies transit the primary close to `t = 0`. ... |
import pytest ; pytest
#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
# Standard library imports
from os import chdir
from subprocess import run
# Bokeh imports
from . import TOP_PATH, ls_files
#... |
import hashlib
import logging
from lxml import etree
from mock import Mock, patch
import os
import requests
import unittest
from six.moves.urllib.request import url2pathname
from eulfedora.models import DigitalObject
from eulfedora.server import Repository
from eulfedora.syncutil import ArchiveExport, endswith_partial... |
import keras
import numpy as np
from matplotlib import pyplot as plt
from skimage import transform
model = keras.applications.InceptionResNetV2(include_top=False)
(X_train, y_train), (X_test, y_test) = keras.datasets.cifar10.load_data()
def generate(X, y, batch_size):
while True:
choices = np.random.ch... |
# Time: O(n)
# Space: O(h)
# Given a binary tree, find the length of the longest path
# where each node in the path has the same value. This path may or may not pass through the root.
#
# Note: The length of path between two nodes is represented by the number of edges between them.
#
# Example 1:
# Input:
#
# ... |
# 源代码地址:https://github.com/scrapy/scrapy/blob/master/scrapy/commands/crawl.py
import os
from scrapy.commands import ScrapyCommand
from scrapy.utils.conf import arglist_to_dict
from scrapy.utils.python import without_none_values
from scrapy.exceptions import UsageError
class Command(ScrapyCommand):
requires_proje... |
from gluon import current, HTTP
from html import *
from gluon.dal import Field
import re
#####################################################################
class SMS:
def __init__(self,**attr):
request = current.request
self.db = attr.get('db',current.globalenv['db'])
self.auth = attr.get('auth',current.g... |
from django import http
def fakeView(request):
resp = http.HttpResponse()
resp.write('<html><body><p>'
'This is a fake httpresponse from a fake view for testing '
' purposes only'
'</p></body></html>')
return resp |
# Standard Library Imports
import logging
import json
# 3rd Party Imports
# Local Imports
from PokeAlarm import Unknown
log = logging.getLogger('Filter')
class BaseFilter(object):
""" Abstract class representing details related to different events. """
def __init__(self, name):
""" Initializes base ... |
#########################################################################
# 10-row School abacus
# by
# Michael H
#########################################################################
# Description partially extracted from from wikipedia
#
# Aroun... |
'''
SAPI 5+ driver.
Copyright (c) 2009, 2013 Peter Parente
Permission to use, copy, modify, and distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DIS... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""KISS Core Classes."""
# These imports are for python3 compatibility inside python2
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import logging
import threading
from abc import ABCMeta
from abc import abst... |
#!/usr/bin/env python
"""Find certain types of files, compute hashes, and fetch unknown ones."""
import stat
from grr.lib import aff4
from grr.lib import flow
from grr.lib import rdfvalue
from grr.lib import type_info
from grr.lib import utils
class FetchAllFiles(flow.GRRFlow):
"""This flow finds files, compute... |
from pupa.scrape import Scraper, Organization
import lxml.etree
class MSCommitteeScraper(Scraper):
def scrape(self, chamber=None):
chambers = [chamber] if chamber else ["upper", "lower"]
for chamber in chambers:
if chamber == "lower":
chamber = "h"
else:
... |
"""
A set of preprocessors for the skeinforge engine
"""
from __future__ import absolute_import
import re
import warnings
from .BundleProcessor import BundleProcessor
from .LineTransformProcessor import LineTransformProcessor
from .CoordinateRemovalProcessor import CoordinateRemovalProcessor
from .TemperatureProcesso... |
#!/usr/bin/python3
""" test_dst.py:
"""
# Import Required Libraries (Standard, Third Party, Local) ********************
import copy
import datetime
import logging
import sys
import unittest
if __name__ == "__main__":
import os
sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__fi... |
"""
Two figures with one axes each
==============================
The pressure q[0] and q[1] are plotted in two separate figures.
More axes could be added to each figure, more items to each axes.
"""
#--------------------------
def setplot(plotdata):
#--------------------------
"""
Specify what is to... |
"""File contains functions to generate the multiplier's hardware description."""
import os
import math
def generate_vhdl_tb(pp_list, exp_prime):
"""Top-level function to generate VHDL code."""
file_ptr = open(("vhdl/mod_mul_tb.vhd"), 'w')
cycles = math.ceil(math.log2(len(pp_list)))+3
write_lib(file_pt... |
# -*- coding: utf-8 -*-
"""
thriftpy._compat
~~~~~~~~~~~~~
py2/py3 compatibility support.
"""
from __future__ import absolute_import
import platform
import types
import sys
PY3 = sys.version_info[0] == 3
PYPY = "__pypy__" in sys.modules
UNIX = platform.system() in ("Linux", "Darwin")
CYTHON = UNIX and... |
from __future__ import absolute_import, print_function
import six
from sentry.utils.compat import mock
from sentry.models import Environment, Release
from sentry.testutils import APITestCase, SnubaTestCase
from sentry.testutils.helpers.datetime import before_now, iso_format
class GroupDetailsTest(APITestCase, Snuba... |
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from django.template import RequestContext, loader, Context
from django.shortcuts import render_to_response
from django.conf import settings
from models import Groups
from models import Egroups
from getPrivileges import isSuperUser
from l... |
"""
mosaic.py
A simple python script that creates a mosaic from an input image.
Dependencies:
Python Imaging Library, available at http://www.pythonware.com/products/pil/
Summary of methods:
print_fn(s) prints s to the terminal only when the verbose option is selected
gcd(a,b) returns the greatest common divisor of a... |
import general
from litex.soc.integration import soc as litex_soc
from litex.soc.integration import builder
from litex.build.xilinx import vivado
class DigilentArtySoCWorkflow(general.GeneralSoCWorkflow):
"""Specializes the general workflow for the Digilent Arty."""
def make_soc(self, **kwargs) -> litex_soc.L... |
#!/usr/bin/env python
'''
Doc
http://pythonhosted.org/purestorage/api.html#module-purestorage
Blog:
http://www.purestorage.com/blog/pure-storage-rest-client-and-python-library/
Testing:
script <Purestorage IP> <username> <password>
'''
import sys, purestorage, traceback
# Disable unverified HTTPS request warning(s)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.