content
string
# def makeGraph(size, n): # adjacency_list = [] # for i in range(size): # adjacency_list.append([]) # for i in range(n): # num, vertex = list(map(int, input().split())) # adjacency_list[num].append(vertex) # return adjacency_list # # # def bfs(vertex, start=0): # visitedEdges...
#!/usr/bin/env python """ Implementation of an OpenFlow flow table @author: Colin Scott (<EMAIL>) """ from collections import namedtuple from libopenflow_01 import * from pox.lib.revent import * import time # FlowTable Entries: # match - ofp_match (13-tuple) # counters - hash from name -> count. May be stale # ...
#!/usr/bin/env python """ Forward_kinematics.py author: Ariel Anders Modified approach to find the homogenous transformation matrix as described by John Craig. """ import sys, math,numpy from numpy import matrix, zeros,shape, reshape, array,around, cos, sin #from CollisionDetector import Pt import numpy as np ...
"""Persist the memote test suite results in a database.""" from __future__ import absolute_import import json import logging from gzip import GzipFile from io import BytesIO from future.utils import raise_with_traceback from sqlalchemy import Column, DateTime, Integer, LargeBinary, Unicode, UnicodeText from sqlalche...
# -*- coding: utf_8 -*- """REST API Middleware.""" from django.http import JsonResponse from django.utils.deprecation import MiddlewareMixin from mobsf.MobSF.utils import api_key OK = 200 def make_api_response(data, status=OK): """Make API Response.""" resp = JsonResponse( data=data, # lgtm [py/sta...
import json from django.test.client import RequestFactory from django.test.utils import override_settings from bedrock.base.urlresolvers import reverse from mock import patch from nose.tools import eq_, ok_ from bedrock.firefox import views from bedrock.mozorg.tests import TestCase FXOS_COUNTRIES = { 'default'...
#!/usr/bin/python """ +---------+ +---------+ +---------+ | NS3 | | Mininet | | NS3 | | AP0 +-+ Switch +-+ AP1 | +----+----+ +---------+ +----+----+ | | +----+----+ +----+----+ | NS3 | | NS3 | | Station| | Station| +---------+ ...
import sys import sensors def print_stuff(): for chip in sensors.get_detected_chips(): print(chip) for feature in chip.get_features(): print(' {0}'.format(chip.get_label(feature))) for subfeature in chip.get_all_subfeatures(feature): print(' {0}'.form...
# -*- coding: utf-8 -*- """ Simple Example to train logical operators """ from __future__ import absolute_import, division, print_function import tensorflow as tf import tflearn # Logical NOT operator X = [[0.], [1.]] Y = [[1.], [0.]] # Graph definition with tf.Graph().as_default(): g = tflearn.input_data(shape...
# -*- coding utf-8 -*- from __future__ import absolute_import import re from .datalib import fetchData def evaluateTokens(requestContext, tokens, replacements=None): if tokens.template: arglist = dict() if tokens.template.kwargs: arglist.update(dict( [(kwarg.argname, ...
import configparser from typing import Tuple, List, Dict, Set import io from UM.Util import parseBool from UM.VersionUpgrade import VersionUpgrade # Renamed definition files _RENAMED_DEFINITION_DICT = { "dagoma_discoeasy200": "dagoma_discoeasy200_bicolor", } # type: Dict[str, str] _removed_settings = { "sp...
import os import shutil from keystone.common import openssl from keystone import exception from keystone import tests from keystone.tests import default_fixtures from keystone import token SSLDIR = tests.dirs.tests('ssl') CONF = tests.CONF DEFAULT_DOMAIN_ID = CONF.identity.default_domain_id CERTDIR = os.path.join(...
import numpy as np from getdist import mcsamples, densities import six def make_2D_Cov(sigmax, sigmay, corr): return np.array([[sigmax ** 2, sigmax * sigmay * corr], [sigmax * sigmay * corr, sigmay ** 2]]) class MixtureND(object): """ Gaussian mixture model with optional boundary ranges """ def...
# -*- coding: utf-8 -*- import logging from babel import Locale, UnknownLocaleError, negotiate_locale from flask import request, session from werkzeug.exceptions import BadRequest logger = logging.getLogger(__name__) def possible_locales(): """Return the locales usable for sipa. :returns: Said Locales ...
#!/usr/bin/env python # ~*~ coding: utf-8 ~*~ # from django.core.paginator import InvalidPage, Paginator class View(object): http_method_names = [] def __init__(self, **kwargs): pass @classmethod def as_view(cls, **initkwargs): pass def dispatch(self, request, *args, **kwargs)...
import numpy as np from time import time from operator import itemgetter from sklearn import svm, grid_search from sklearn.ensemble import RandomForestClassifier from sklearn.calibration import CalibratedClassifierCV from spark_sklearn import GridSearchCV import pandas as pd from sklearn.preprocessing import MinMaxScal...
from numpy import * def Haffine_from_points(fp,tp): """ find H, affine transformation, such that tp is affine transf of fp""" if fp.shape != tp.shape: raise RuntimeError, 'number of points do not match' #condition points #-from points- m = mean(fp[:2], axis=1) maxstd = max(std(...
import os import sys import subprocess import PyTango import time # test fixture class WriterSetUp(object): # constructor # \brief defines server parameters def __init__(self, instance="TDWTEST", dvname="testp09/testtdw/testr228"): # information about tango writer self.n...
import sys, uuid from twisted.internet import reactor from twisted.internet.defer import inlineCallbacks, returnValue from twisted.internet.protocol import ClientCreator from txamqp.client import TwistedDelegate from txamqp.content import Content from txamqp.protocol import AMQClient import txamqp.spec from utils.lo...
import os import sys import gtk import gobject import atk # gconf is also imported; see end of HistoryEntry class for details # gnomevfs is also imported; see end of HistoryFileEntry class for details from gettext import gettext as _ # This file is a Python translation of: # * gedit/gedit/gedit-history-entry.c # * ...
#!/usr/bin/env python """ .. module:: logger :synopsis: Handles logging (for debugging). """ import functools import logging import logging.handlers from PyQt4 import QtCore a_logger = False def logFn(fn): """ Wraps a function or method call to save logging information. """ glob...
from unittest import TestCase from mock import patch import frontend.api.v1_1.controllers.probes as api_probes class TestApiProbes(TestCase): def test001_list_ok(self): sample = ["test"] expected = {"total": len(sample), "data": sample} celery_brain = "frontend.api.v1...
import datetime import operator from oslo_config import cfg from oslo_log import log from oslo_serialization import jsonutils from oslo_utils import timeutils import requests import six.moves from aodh.alarm import evaluator from aodh.i18n import _ from aodh import keystone_client LOG = log.getLogger(__name__) COMP...
#!/usr/bin/env python #A utility that prints out the number of hydrogen bonds between different strands in the system import base try: import numpy as np except: import mynumpy as np import os.path import sys import readers import subprocess PROCESSDIR = os.path.join(os.path.dirname(__file__), "process_dat...
from json import loads from tenable_io.api.base import BaseApi from tenable_io.api.base import BaseRequest from tenable_io.api.models import AccessGroup, AccessGroupList, AssetRule, AssetRuleFilter, AssetRulePrincipal, Filters class AccessGroupsApi(BaseApi): def list(self, f=None, ft='and', w=None, wf=None, lim...
__authors__ = [ '"Leo (Chong Liu)" <<EMAIL>>', '"Sverre Rabbelier" <<EMAIL>>', ] import unittest from google.appengine.api import users from soc.logic import accounts from soc.logic.models.user import logic as user_logic from soc.models import user class UserTest(unittest.TestCase): """Tests related to us...
from boxbranding import getBoxType from twisted.internet import threads from enigma import eDBoxLCD, eTimer from config import config, ConfigSubsection, ConfigSelection, ConfigSlider, ConfigYesNo, ConfigNothing from Components.SystemInfo import SystemInfo from Tools.Directories import fileExists import usb def Icon...
from bs4 import BeautifulSoup from couchpotato.core.helpers.variable import getTitle, tryInt from couchpotato.core.logger import CPLog from couchpotato.core.helpers.encoding import simplifyString, tryUrlencode from couchpotato.core.helpers.variable import getTitle, mergeDicts from couchpotato.core.providers.torrent.bas...
"""Classes for representing collections for the Google Cloud Firestore API.""" import random import warnings import six from google.cloud.firestore_v1 import _helpers from google.cloud.firestore_v1 import query as query_mod from google.cloud.firestore_v1.watch import Watch from google.cloud.firestore_v1 import docume...
#!/usr/bin/python """Use files with frequency counts of blasts on possible alleles (see format below) to genotype individuals. Usage: genotype_from_blast_results.py file_list threshold_file output_file - file_list is a file containing the path to the individual summary files. the file_list format is as follows...
#!/usr/bin/python # -*- coding: utf-8 -*- from BitSet import BitSet import math import mmh3 class BloomFilter(object): mask32 = 0xffffffff mask64 = 0xffffffffffffffff mask128 = 0xffffffffffffffffffffffffffffffff seeds = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, ...
import os import unittest from mock import patch from amity import Amity class TestAmityFunctionality(unittest.TestCase): ''' The self.amity Class here is used to hold the mian functionality of the self.amity Room Allocation system. It imports and makes calls to all other classes and manages them to c...
from SQLCoverageReport import generate_html_reports import types # A compare function which can handle datetime to None comparisons # -- where the standard cmp gets a TypeError. def safecmp(x, y): # iterate over lists -- just like cmp does, # but compare in a way that avoids a TypeError # when a None valu...
r"""Unit test for the ReactiveFlux object .. moduleauthor:: F.Noe <frank DOT noe AT fu-berlin DOT de> """ import unittest import numpy as np from tests.numeric import assert_allclose from msmtools.flux import api as msmapi import msmtools.analysis as msmana class TestReactiveFluxFunctions(unittest.TestCase): ...
import sublime from unittest import TestCase import time class TestAsync(TestCase): def setUp(self): self.view = sublime.active_window().new_file() # make sure we have a window to work with s = sublime.load_settings("Preferences.sublime-settings") s.set("close_windows_when_empty",...
"Test Excel parsing." import organize.excel_parser from itertools import islice from organize.tests import OrganizeTestCase class TestExcelParser(OrganizeTestCase): "Test Excel." def setUp(self): "Test Excel parser." self.parser = organize.excel_parser.ExcelParser() self.first_line = [...
import cgi import copy import mimetypes import os from StringIO import StringIO import types import urlparse import uuid from restkit.datastructures import MultiDict from restkit.errors import AlreadyRead, RequestError from restkit.forms import multipart_form_encode, form_encode from restkit.tee import ResponseTeeInpu...
import processout from processout.errors.notfounderror import NotFoundError from processout.gatewayrequest import GatewayRequest def main(): client = processout.ProcessOut("test-proj_gAO1Uu0ysZJvDuUpOGPkUBeE3pGalk3x", "key_sandbox_mah31RDFqcDxmaS7MvhDbJfDJvjtsFTB") # Create ...
# -*- coding: utf-8 -*- """ *************************************************************************** OutputFactory.py --------------------- Date : August 2012 Copyright : (C) 2012 by Victor Olaya Email : volayaf at gmail dot com *************************...
import os from setuptools import setup, find_packages here = os.path.abspath(os.path.dirname(__file__)) README = open(os.path.join(here, 'README.txt')).read() CHANGES = open(os.path.join(here, 'CHANGES.txt')).read() requires = [ 'pyramid', 'SQLAlchemy', 'transaction', 'pyramid_tm', 'pyramid_d...
"""%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% MODEL_AGNfitter.py %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% This script contains all functions which are needed to construct the total model of AGN. The functions here translate the parameter space points into total fluxes dependin on the models chosen. Functions contained...
from django.conf.urls import url from django.http import HttpRequest from django.db import transaction from tastypie.authorization import Authorization from tastypie.exceptions import BadRequest from tastypie.resources import ModelResource from tastypie.utils import trailing_slash from tastypie import fields from muse_...
import urllib import rb import re import sys # Deal with html entitys and utf-8 # code taken from django/utils/text.py from htmlentitydefs import name2codepoint pattern = re.compile("&(#?\w+?);") def _replace_entity(match): text = match.group(1) if text[0] == u'#': text = text[1:] try: if text[0] in u'xX':...
"""Add `like_count` column to `comment` table.""" revision = '10f5abcd410' down_revision = '3dc298ae483' import sqlalchemy as sa from alembic import op def upgrade(): op.add_column( 'comment', sa.Column( 'like_count', sa.Integer(), server_default='0', ...
# -*- coding: utf-8 -*- from __future__ import unicode_literals, print_function import os import time import socket import unittest import smtplib import json from threading import Thread from email.mime.multipart import MIMEMultipart from email.mime.base import MIMEBase from email.mime.text import MIMEText from email...
import sys, os import win32api from timtools.textprinter import winprn from timtools.console.application import Application, UsageError class PdfPrint(Application): name="pdfprint" copyright="""\ Copyright (c) 2009 Luc Saffre. This software comes with ABSOLUTELY NO WARRANTY and is distributed...
import requests import pymysql import datetime import time import os import simplejson as json crontable = [] outputs = [] def getdbconfig(): with open('plugins/teamslackbot/dbconfig.conf') as data_file: dbconf = json.load(data_file) dbinfo = {} dbinfo['host'] = dbconf['Host'...
"""\ This is a zope script used to extract module/collection hit records from the ZODB to CSV file. This outputs the CSV in the following format: moduleid, total hits, recent hits, publication date, today, update interval """ import csv import pytz from datetime import datetime import calendar INTERVAL = 604800 # ...
# -*- coding: utf-8 -*- """Including this module sets up an operation-result handling system. You can then register actions to perform for a given context, operation and result: config.add_engine_transition( IFoo, # context 'o.VALIDATE', # operation 'r.OK', # res...
__doc__ = """Code by Benjamin S. Murphy <EMAIL> Dependencies: numpy scipy (scipy.optimize.minimize()) Functions: adjust_for_anisotropy(x, y, xcenter, ycenter, scaling, angle): Returns X and Y arrays of adjusted data coordinates. Angle is CCW. adjust_for_anisotropy_3d(x, y, z, xcenter, ycenter,...
import time from mcrouter.test.MCProcess import Memcached from mcrouter.test.McrouterTestCase import McrouterTestCase class TestShadowRoute(McrouterTestCase): config = './mcrouter/test/test_shadow_route.json' def setUp(self): # The order here must corresponds to the order of hosts in the .json ...
import itertools import peel import numpy import sys import os import scipy.ndimage.interpolation as sni import cPickle import csv features = ['aromatic','hbondAcceptor','hbondDonor','hydrophilic','hydrophobic','occupancy','adjacency'] #receptorDir = 'POVME_outputs_20140816shapes' receptorDir = './' #ligandDir = 'lig...
# -*- coding: utf-8 -*- from collections import OrderedDict from .abstract_asset import AbstractAsset from .identifier import Identifier class ForeignKeyConstraint(AbstractAsset): """ An abstraction class for a foreign key constraint. """ def __init__(self, local_column_names, forei...
import sys import math import timeit def run_tests(seq): titles = [] stones = [] for func in seq: timer = Timer(func, verbose=1) stone = timer.smart_timeit(verbose=1) titles.append(timer.title) stones.append(int(stone+0.5)) print 'TIMER_TITLES=',`titles` print 'TIMER...
import sys import inspect from dipy.fixes import argparse as arg from dipy.workflows.docstring_parser import NumpyDocString def get_args_default(func): if sys.version_info[0] >= 3: sig_object = inspect.signature(func) params = sig_object.parameters.values() names = [param.name for param i...
""" test rabbitmq functionality """ import os import sys import signal import socket try: from amqplib import client_0_8 as amqp except ImportError: print "CRITICAL: amqplib not found" sys.exit(2) from optparse import OptionParser ROUTE_KEY = "test_mq" def alarm_handler(signum, frame): print "TIME...
"""Test database writer.""" import database_reader import database_writer import models import test_utils class DatabaseWriterTest(test_utils.DatabaseTest): """Test database writer.""" def test_write_topics_to_database_grouping_in_database(self): """Test write grouping to database.""" self.g...
#!/usr/bin/python3 # -*- coding: utf-8 -*- ''' Trackl: Multiplatform simkl tracker Copyright (C) 2016 David Davó <EMAIL> 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, either ...
import numpy as np from numpy.testing import assert_array_equal from nose.tools import assert_equal, assert_raises, assert_false, assert_true try: from nose.tools import assert_is, assert_is_instance except ImportError: from landlab.testing.tools import assert_is, assert_is_instance import landlab.utils.structu...
#!/usr/bin/env python # -*- coding: utf-8 -*- from CTFd.models import Teams from CTFd.utils import set_config from tests.helpers import create_ctfd, destroy_ctfd, gen_team, login_with_mlc def test_team_size_limit(): """Only team_size amount of members can join a team even via MLC""" app = create_ctfd(user_mod...
# -*- coding: utf-8 -*- from typing import Any, Dict, Generator, Mapping, Text, Union import mock from django.utils.timezone import now as timezone_now from zerver.lib.actions import ( get_client, ) from zerver.lib.test_classes import ( ZulipTestCase, ) from zerver.models import ( get_stream_recipient...
""" $lic$ Copyright (C) 2016-2020 by Tsinghua University and The Board of Trustees of Stanford University This program is free software: you can redistribute it and/or modify it under the terms of the Modified BSD-3 License as published by the Open Source Initiative. This program is distributed in the hope that it wi...
# -*- coding: utf-8 -*- import json import datetime import turbotlib import lxml.html import requests def get_column_names(etree): """ Return list of column names from mortgage lenders table. """ column_name_xpath = '//tr[@bgcolor="#003399"]/td' return [column.text_content() for column in etree.xpath(co...
import unittest import GenerateMask import os class GenerateMaskTestCase(unittest.TestCase): def atest1(self): workingDirectory = "../../alignmentFiles/" #alnFileName = workingDirectory+"mmult3.aux" alnFileName = workingDirectory+"mmult.list-FINAL.aln" #maskedPDBfileName...
from scrapy.http import Request from scutils.log_factory import LogFactory class MetaPassthroughMiddleware(object): def __init__(self, settings): self.setup(settings) def setup(self, settings): ''' Does the actual setup of the middleware ''' # set up the default sc lo...
import os import shutil import itertools from slpkg.messages import Msg from slpkg.utils import Utils from slpkg.__metadata__ import MetaData as _meta_ class NewConfig(object): """Manage .new configuration files """ def __init__(self): self.meta = _meta_ self.msg = Msg() self.red ...
from .vector import * from random import * from math import * class kepler: def __init__(self): self.name = 'Kepler' self.parameters = [ {'pName':'Central mass', 'pType':'numeric', 'default':1, 'tooltip':'Mass of the main body holding the system together'}, {'pName':'Other...
#!/usr/bin/env python ''' @Author: Bilgehan NAL Voice Recogniser is a class to help listening the speech and converting to string ''' import speech_recognition as sr import io import sys class Voice_Recogniser: # These variables are sample language code TURKEY = 'tr-TR' US = 'en-US' UK = 'en-GB' ...
#!/usr/bin/env python # Encoding: utf-8 # See: <http://docs.python.org/distutils/introduction.html> try: from setuptools import setup except ImportError: from distutils.core import setup VERSION = eval(filter(lambda _:_.startswith("__version__"), file("src/rawcopy.py").readlines())[0].split("=")[1]) setup...
# -*- coding: utf-8 -*- """ Program to make bry nc file okada on 2014/10/21 """ import numpy as np import datetime as dt Chl2C = 0.05 # okada (=1/20 gChl/gC) PhyCN = 6.625 # (=106/16 molC/molN) C = 12.01 N = 14.01 P = 30.97 O2 = 32.00 def bry_bio_fennelP(dims): xi_rho = dims['xi'] ...
#!/usr/bin/env python3 """Module providing pattern classes for matching against ptTools.ParseTreeNodes.""" import sys from .. import patterns from .. import tokenizer def TerminalPattern(val): """Creates and returns pattern matching a TerminalNode with val. For example TerminalPattern('class') creates ...
import time import smtplib import logging from lockfile import FileLock, AlreadyLocked, LockTimeout from socket import error as socket_error from mailer.models import Message, DontSendEntry, MessageLog from django.conf import settings #from django.core.mail import send_mail as core_send_mail from django.core.mail imp...
from bcoder import bdecoder, bencoder from downloader import Downloader import codecs, types, json, sys class DictWriter(): def __init__(self, obj): self.obj = obj self.indent = -1 def getIndent(self): ind = '' for i in range(0, self.indent): ind += '&nbsp;&nbsp;&nb...
from django.conf import settings from django.conf.urls import patterns, include, url # There is a course creators admin table. from ratelimitbackend import admin from cms.djangoapps.contentstore.views.program import ProgramAuthoringView, ProgramsIdTokenView from cms.djangoapps.contentstore.views.organization import Or...
from django.conf.urls import patterns, include, url from django.conf.urls.static import static from django.conf import settings from django.views.generic import TemplateView from django.views.generic.base import RedirectView # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.aut...
from django.template import Context, RequestContext, loader from django.http import HttpResponse, HttpResponseBadRequest from django.contrib.auth.decorators import login_required from django.shortcuts import render_to_response from appstack import gis import emitters def login(request): c = RequestContext(request...
"""Test ChangesFile functionality.""" __metaclass__ = type import os from debian.deb822 import Changes from testtools.matchers import MatchesStructure from zope.component import getUtility from lp.archiveuploader.changesfile import ( CannotDetermineFileTypeError, ChangesFile, determine_file_class_and_na...
from fabric.api import local, task, abort, settings from clom import clom from fabric.colors import green from fabric.utils import puts from fabric.operations import prompt @task def release(): """ Release current version to pypi """ with settings(warn_only=True): r = local(clom.git['diff-...
""" INFORM, auth: MD5 privacy: DES ++++++++++++++++++++++++++++++ Send SNMP INFORM notification using the following options: * SNMPv3 * with user 'usr-md5-des', auth: MD5, priv DES * over IPv4/UDP * send INFORM notification * with TRAP ID 'warmStart' specified as a string OID * include managed object information 1.3....
import os.path as op import sys from bakery_cli.utils import shutil, run, UpstreamDirectory if sys.version_info[0] < 3: def unicode(str): return str.decode('utf-8') class Optimize(object): """ Run optimization process for font """ def __init__(self, bakery): self.project_root = bakery.p...
from direct.interval.IntervalGlobal import Sequence, Func, Wait, LerpColorScaleInterval, Parallel from direct.distributed import DistributedObject from direct.directnotify import DirectNotifyGlobal from direct.task.Task import Task from direct.showbase import PythonUtil from toontown.distributed import DelayDelete from...
from __future__ import print_function """M2Crypto support for Python 2.x's httplib. Copyright (c) 1999-2002 Ng Pheng Siong. All rights reserved.""" import string from M2Crypto import SSL from httplib import FakeSocket, HTTP, HTTPConnection, HTTPResponse, HTTPS_PORT class HTTPSConnection(HTTPConnection): """...
#!/usr/bin/env python #coding=utf8 ''' For a undirected graph with tree characteristics, we can choose any node as the root. The result graph is then a rooted tree. Among all possible rooted trees, those with minimum height are called minimum height trees (MHTs). Given such a graph, write a function to find all the MH...
from __future__ import print_function import os import fnmatch import sys import subprocess import argparse from tempfile import mkdtemp # In an attempt to make this compatible with Python 2.x and 3.x, # handle change in iteritems() between versions rather than importing # six. if sys.version_info >= (3, 0): def ...
#!/usr/bin/env python """Test script to run Online CA service with HTTP Basic Auth in the Paster web application server. """ __author__ = "P J Kershaw" __date__ = "03/08/12" __copyright__ = "(C) 2012 Science and Technology Facilities Council" __license__ = "BSD - see LICENSE file in top-level directory" __contact__ = "...
""" ui.py RogueLike game UI logic. The UI of RogueLike is managed by this module, but the real ui work is done by certain ui wrapper (in uiwrappers module), which should use certain ui library to implement all the UI functionality used in here. That's why the ui wrappers must follow certain 'interface', because this...
import json import random import utils.logging from config import RABBITMQ_MASTER from utils.connection import get_exchange_connection from pika.adapters.blocking_connection import BlockingChannel from pika.spec import Basic, BasicProperties def consumer(ch: BlockingChannel, method: Basic.Deliver, properties...
''' NLP visualization views. @author: Anze Vavpetic <<EMAIL>> ''' from django.shortcuts import render import nlp def definition_sentences_viewer(request, input_dict, output_dict, widget): """ Parses the input XML and displays the definition sentences given as input. @author: Anze Vavpetic, 2012 "...
from __future__ import unicode_literals, print_function from datetime import datetime from celery.states import FAILURE from django.core.management.base import BaseCommand, CommandError from pytz import utc from lms.djangoapps.instructor_task.models import InstructorTask, QUEUING, PROGRESS class Command(BaseComman...
import difflib import pprint try: # noinspection PyCompatibility # pylint: disable=wrong-import-order from cStringIO import StringIO except ImportError: # pragma: no cover # pylint: disable=wrong-import-order from io import StringIO # pragma: no cover import contextlib2 as contextlib tr...
import os from pipeline.backend.config import Backend, WorkMode from pipeline.backend.pipeline import PipeLine # path to data # default fate installation path DATA_BASE = "/data/projects/fate" # site-package ver # import site # DATA_BASE = site.getsitepackages()[0] def main(): # parties config guest = 9999...
""" Name class for Gramps. """ #------------------------------------------------------------------------- # # Gramps modules # #------------------------------------------------------------------------- from .secondaryobj import SecondaryObject from .privacybase import PrivacyBase from .citationbase import CitationBase...
#!/usr/bin/env python import GPyOpt import GPy import logging import numpy as np import lib.env as env from lib.env import runs_dir, cases_dir, spikes_dir import os from os.path import join as pj import subprocess as sub import uuid from lib.util import read_json from lib.util import make_dir class GlobalConfig(ob...
import requests.sessions from BeautifulSoup import BeautifulSoup def get_source_info(url): source_info = {} if 'thevideo' in url: source_info['source'] = 'thevideo.me' with requests.session() as s: p = s.get(url) soup = BeautifulSoup(p.text, 'html.parser') ti...
import os import mock from oslo.config import cfg import neutron.common.test_lib as test_lib from neutron.db import api as db from neutron.plugins.bigswitch import config from neutron.tests.unit.bigswitch import fake_server RESTPROXY_PKG_PATH = 'neutron.plugins.bigswitch.plugin' NOTIFIER = 'neutron.plugins.bigswitch...
''' Copyright (c) 2018 Yogesh Khatri This file is part of mac_apt (macOS Artifact Parsing Tool). Usage or distribution of this software/code is subject to the terms of the MIT License. bluetooth.py --------------- Parses system Bluetooth artifacts from com.apple.Bluetooth.plist. ...
import socket import gobject class TrivialStream: def __init__(self, socket_address=None): self.socket_address = socket_address def read_socket(self, s): try: data = s.recv(1024) if len(data) > 0: print "received:", data except socket.error, e: ...
UNDO = 0 REDO = 1 # Some general actions we should always expect. # Some require special handling within ourselves # (taking care of letter insertion / word insertion) INSERT_LETTER = 100 INSERT_WORD = 101 DELETE_LETTER = 102 DELETE_WORD = 103 TRANSFORM_CANVAS = 104 class UndoAction: def __init__(self, owner, un...
from __future__ import print_function from nose.tools import assert_equal, assert_almost_equal from nose.tools import assert_true, assert_false from mock import patch, Mock from tawhiri import models class TestModels: def test_constant_ascent(self): for rate in (0.0, 1.0, -1.0): f = models.m...
from PIL import Image, ImageTk import tkinter from tkinter import ttk from gui.second.frames import RowFrame, ResultInfo __author__ = 'zz' class BaseTestFrame(ttk.Frame): _master = None def __init__(self, master=None, **kwargs ): if master is None: master = self._master super().__in...