content
stringlengths
4
20k
"""wradlib - An Open Source Library for Weather Radar Data Processing wradlib is designed to assist you in the most important steps of processing weather radar data. These may include: reading common data formats, georeferencing, converting reflectivity to rainfall intensity, identifying and correcting typical error s...
"""RefExtract configuration.""" __revision__ = "$Id$" from invenio.config import CFG_VERSION, CFG_ETCDIR # pylint: disable=C0301 # version number: CFG_REFEXTRACT_VERSION = "Invenio/%s refextract/%s" % (CFG_VERSION, CFG_VERSION) # periodicals knowledge base: CFG_REFEXTRACT_KB_JOURNAL_TITLES = "%s/bibedit/refextract...
# # import os # # os.chdir("files") # # # 1. 只读模式, 打开要复制的文件 # # 追加模式, 打开副本文件 # # source_file = open("d.txt", "r", encoding="utf-8") # dst_file = open("d_bat.txt", "a", encoding="utf-8") # # # # # 2. 从源文件中读取内容 # # 写入到目标文件中 # # content = source_file.read() # # dst_file.write(content) # # while True: # content = sou...
from pymongo import MongoClient, errors import tweepy class Tws: def __init__(self, keyword): self.tweets = MongoClient().tws.tweets self.auth = tweepy.AppAuthHandler('', '') self.api = tweepy.API(self.auth) self.keyword = keyword de...
"""This code example activates a product template. To determine which product templates exist, run get_all_product_templates.py. Tags: ProductTemplateService.getProductTemplatesByStatement Tags: ProductTemplateService.performProductTemplateAction """ __author__ = 'Nicholas Chen' # Import appropriate modules from th...
""" This is the main function for the Android version of PageKite. """ ############################################################################# from __future__ import absolute_import LICENSE = """\ This file is part of pagekite.py. Copyright 2010-2020, the Beanstalks Project ehf. and Bjarni Runar Einarsson This...
from cabby import create_client try: # create a connection client = create_client('{{ opentaxii_domain }}', discovery_path='/services/discovery') # iterate through each defined collection collections = client.get_collections(uri='/services/collection') for collection in collections: # ho...
from __future__ import (absolute_import, division, print_function) __metaclass__ = type import os import sys from ansible.module_utils.common.text.converters import to_native, to_bytes from ctypes import CDLL, c_char_p, c_int, byref, POINTER, get_errno try: _selinux_lib = CDLL('libselinux.so.1', use_errno=True) ...
import sys from os import getenv import rospy import rospkg rospack = rospkg.RosPack() PPRZ_HOME = getenv("PAPARAZZI_HOME") if PPRZ_HOME is not None: sys.path.append(PPRZ_HOME + '/var/lib/python') else: PPRZROS_BASE = rospack.get_path('pprzros') sys.path.append(PPRZROS_BASE + '/../pprzlink/lib/v2.0/python...
"""This code example updates a creative wrapper to the 'OUTER' wrapping order. To determine which creative wrappers exist, run get_all_creative_wrappers.py. The LoadFromStorage method is pulling credentials and properties from a "googleads.yaml" file. By default, it looks for this file in your home directory. For mor...
''' Copyright 2013 George Caley Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in wri...
import unittest from mxl.note import Note from mxl import util class TestNote(unittest.TestCase): def test_subtraction_same(self): a = Note(rhythm_type='half', step='C', octave=1, staff=1) b = Note(rhythm_type='half', step='C', octave=1, staff=1) self.assertEqual(a - b, 0) def test_s...
__author__ = 'sergg' import locs_sim as locs import sys import time def print_positions(): print 'Technician A (' + locs.technician_A + '):', locs.get_location(locs.technician_A) print 'Technician B (' + locs.technician_B + '):', locs.get_location(locs.technician_B) print 'Tech...
import re from tests.base import IntegrationTest from tasklib import local_zone from datetime import datetime def current_year(): return local_zone.localize(datetime.now()).year def current_month(): current_month_number = local_zone.localize(datetime.now()).month months = ["January", "February", "March...
# -*- coding: utf-8 -*- import re from os.path import join from urlparse import urljoin from module.plugins.internal.SimpleHoster import SimpleHoster, create_getInfo class ZippyshareCom(SimpleHoster): __name__ = "ZippyshareCom" __type__ = "hoster" __version__ = "0.62" __pattern__ = r'(?P<HOS...
import os from os.path import dirname import re import sys import string sys.path.append(dirname(__file__) + "/../deps/v8/tools"); import jsmin def ToCArray(filename, lines): result = [] row = 1 col = 0 for chr in lines: col += 1 if chr == "\n" or chr == "\r": row += 1 col = 0 value ...
import base64 import binascii import itertools import re import urllib2 import random import math from operator import itemgetter from Crypto.Cipher import AES h = binascii.hexlify def xor(a, b): """XOR two hex strings >>> xor('1c0111001f010100061a024b53535009181c', '686974207468652062756c6c277320657965') ...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ sphinxcontrib.feed unit test driver ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ This script runs the sphinxcontrib.feed unit test suite. :copyright: Copyright 2007-2009 by the sphinxcontrib.feed team, see AUTHORS. :license: BSD, see LICENSE for details. """ impo...
#!/usr/bin/env python __all__ = ['tudou_download', 'tudou_download_playlist', 'tudou_download_by_id', 'tudou_download_by_iid'] from ..common import * from xml.dom.minidom import parseString def tudou_download_by_iid(iid, title, output_dir = '.', merge = True, info_only = False): data = json.loads(get_decoded_htm...
""" Copyright (c) 2016-2019 Alan Yorinks All right reserved. Python Banyan is free software; you can redistribute it and/or modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE Version 3 as published by the Free Software Foundation; either or (at your option) any later version. This library is dist...
import time from openerp.report import report_sxw from openerp import pooler import logging _logger = logging.getLogger(__name__) class doctor_attention_biological(report_sxw.rml_parse): def __init__(self, cr, uid, name, context): super(doctor_attention_biological, self).__init__(cr, uid, name, context=context) ...
""" This module defines a mixin class for enabling XPath on schemas. """ from __future__ import unicode_literals from abc import abstractmethod from elementpath import XPath2Parser, XPathContext from .compat import Sequence from .qnames import XSD_SCHEMA class ElementPathContext(XPathContext): """ XPath dyna...
import re # Use Unicode characters instead of their ascii psuedo-replacements UNICODE_SNOB = 0 # Marker to use for marking tables for padding post processing TABLE_MARKER_FOR_PAD = "special_marker_for_table_padding" # Escape all special characters. Output is less readable, but avoids # corner case formatting issues....
""" Helper functions/etc for use within this package """ from collections import OrderedDict import errno import fnmatch import os import pathlib import re import shutil import tarfile import tempfile from contextlib import contextmanager from functools import wraps def lazy_property(prop): """ Lazily populate an...
from __future__ import division import numpy as np from menpo.shape import TriMesh from menpo.transform.affine import Scale, UniformScale, Translation from menpo.groupalign import GeneralizedProcrustesAnalysis from menpo.transform.piecewiseaffine import PiecewiseAffineTransform from menpo.transform.tps import TPS from ...
"""Formatter for PCAP files.""" from plaso.lib import eventdata __author__ = 'Dominique Kilman (<EMAIL>)' class PCAPFormatter(eventdata.ConditionalEventFormatter): """Define the formatting PCAP record.""" DATA_TYPE = 'metadata:pcap' FORMAT_STRING_PIECES = [ u'Source IP: {source_ip}', u'Destinat...
""" XFields for video module. """ import datetime from xblock.fields import Scope, String, Float, Boolean, List, Dict from xmodule.fields import RelativeTime # Make '_' a no-op so we can scrape strings _ = lambda text: text class VideoFields(object): """Fields for `VideoModule` and `VideoDescriptor`.""" di...
""" test_sql_template test. """ import os import sys import mutlib from mysql.utilities.exception import MUTLibError from mysql.utilities.common.tools import get_tool_path _TRANSFORM_FILE = "diff_output.txt" _CREATE_DB = "CREATE DATABASE `{0}`" _TEST_CASES = [ # Direction a->b {'run_util': True, # If tr...
"""Generates interface properties on global objects. Concretely these are implemented as "constructor attributes", meaning "attributes whose name ends with Constructor" (special-cased by code generator), hence "global constructors" for short. For reference on global objects, see: http://heycam.github.io/webidl/#Globa...
from Token import TokenTypes from Token import Token class Lexer(object): """ Lexer for the graph productions parser. """ #-------------------------------------------------------------------------- def __init__(self, str): """Constructor. str is the ...
"""Domain objects for Wipeout.""" from __future__ import absolute_import # pylint: disable=import-only-modules from __future__ import unicode_literals # pylint: disable=import-only-modules from core.platform import models import python_utils (user_models,) = models.Registry.import_models([models.NAMES.user]) cla...
import time import traceback import threading import sickbeard from sickbeard import common from sickbeard import logger from sickbeard import generic_queue from sickbeard import search, failed_history, history from sickbeard import ui search_queue_lock = threading.Lock() BACKLOG_SEARCH = 10 DAILY_SEARCH = 20 FAILED...
#!/usr/bin/env python import logging import os import time import threading import getopt, sys import dtest def usage(): print "Usage:\n %s --provider=<user>@[<host>]:<stub_path> --consumer=<user>@[<host>]:<stdout_path>" % sys.argv[0] def getUserHostPath(argument): if argument.find("@") != -1: (user,...
import re from pupa.scrape import Person, Scraper, Organization import lxml.html JOINT_COMMITTEE_OVERRIDE = [ # without Joint" in the name. "State Controlling Board", "Legislative Service Commission", "Correctional Institution Inspection Committee", ] SUBCOMMITTEES = { # The Senate only has Financ...
import os import sys import vtk from vtk.util.colors import tomato this_dir = os.path.dirname(os.path.realpath(__file__)) sys.path.append(this_dir + '/..') from tessagon.adaptors.vtk_adaptor import VtkAdaptor # noqa: E402 from tessagon_common_demo import TessagonCommonDemo # noqa: E402 class VtkDemo(TessagonCommo...
# -*- coding: utf-8 -*- ''' Genesis Add-on Copyright (C) 2015 lambda 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 version 3 of the License, or (at your opt...
"""Parabolic geometrical entity. Contains * Parabola """ from __future__ import division, print_function from sympy.core import S from sympy.core.compatibility import ordered from sympy.core.symbol import _symbol from sympy import symbols, simplify, solve from sympy.geometry.entity import GeometryEntity, GeometrySet...
import urllib.request import urllib.parse import http.client import mimetypes import json import re from . import rsaencoder __author__ = 'Anton Vakhrushev' class HttpClient(object): URL_AUTH_KEY = 'http://auth.mobile.yandex.ru/yamrsa/key/' URL_AUTH_TOKEN = 'http://auth.mobile.yandex.ru/yamrsa/token/' ...
#!/usr/bin/python3 """ The base ljson implementation. This package provides base functionality, like getter and setter interface. Creating a ljson table is pretty easy. >>> from ljson import base >>> header = base.Header({"id": {"type": "int", "modifiers":["unique"]}, "name": {"type": "str", "modifiers": []}}) >>> ...
""" Miscellaneous utilities; these should be imported from C{buildbot.util}, not directly from this module. """ from twisted.python import log from twisted.internet import defer def deferredLocked(lock_or_attr): """ Wrap a function which returns a Deferred with a DeferredLock. The DeferredLock is given b...
#!/usr/bin/python import RPi.GPIO as GPIO import Adafruit_MCP3008 import Adafruit_DHT import Adafruit_BMP.BMP085 as BMP085 import time import threading import sys import logging import traceback import json import os log = logging.getLogger('Sensors') log.addHandler(logging.StreamHandler()) log.setLevel(logging.INFO)...
import logging import time import os import hashlib import msgpack logging.basicConfig(level=logging.DEBUG) class PicarusManager(object): def __init__(self, db): self.image_orig_column = 'data:image' self.image_column = 'data:image_320' self.images_table = 'images' self.models_ta...
import logging import sys from ...types import Timestamp from ...util import none_or from ..errors import MalformedResponse from .collection import Collection logger = logging.getLogger("mw.api.collections.deletedrevs") class DeletedRevisions(Collection): PROPERTIES = {'ids', 'flags', 'timestamp', 'user', 'user...
import os from django.core.urlresolvers import reverse from onadata.apps.main.tests.test_base import TestBase from onadata.apps.viewer.models.export import Export from onadata.apps.main.models.meta_data import MetaData from onadata.apps.viewer.views import export_list class TestExportList(TestBase): def setUp(...
# -*- coding: utf-8 -*- """This file is part of the TPOT library. TPOT was primarily developed at the University of Pennsylvania by: - Randal S. Olson (<EMAIL>) - Weixuan Fu (<EMAIL>) - Daniel Angell (<EMAIL>) - and many more generous open source contributors TPOT is free software: you can redistribu...
{ 'name': 'Clouder Template ReactionCommerce', 'version': '1.0', 'category': 'Clouder', 'depends': [ 'clouder_template_dns', 'clouder_template_shinken', 'clouder_template_mail', 'clouder_template_proxy', ], 'author': 'Yannick Buron (Clouder)', 'license': 'Othe...
from django.contrib import admin from fo2.admin import intr_adm_site from .models import * class ModeloPassadoAdmin(admin.ModelAdmin): fields = ['nome', 'padrao'] class ModeloPassadoPeriodoAdmin(admin.ModelAdmin): fields = ['modelo', 'ordem', 'meses', 'peso'] ordering = ['modelo__nome', 'ordem'] int...
from urllib2 import URLError from pocket_api import Pocket, AuthException, PocketException from workflow import Workflow, PasswordNotFound import config LINK_LIMIT = 2000 def main(): wf = Workflow() error = None try: # initialize client access_token = wf.get_password('pocket_access_token...
"""Test of propagation of contextvars to AuthMetadataPlugin threads..""" import contextlib import logging import os import sys import threading import unittest import grpc from tests.unit import test_common from six.moves import queue _UNARY_UNARY = "/test/UnaryUnary" _REQUEST = b"0000" def _unary_unary_handler(r...
"""Kernel Bandwidth Optimization. Copyright (c) 2014 Subhasis Ray License: GPL v3 Original matlab code (sskernel.m) here: http://2000.jukuin.keio.ac.jp/shimazaki/res/kernel.html This was translated into Python by Subhasis Ray, NCBS. Tue Jun 10 23:01:43 IST 2014 """ import numpy as np def nextpow2(x): ""...
#!/usr/bin/env python # vim:fileencoding=utf-8 from __future__ import (unicode_literals, division, absolute_import, print_function) __license__ = 'GPL v3' __copyright__ = '2013, Kovid Goyal <kovid at kovidgoyal.net>' from functools import partial from PyQt4.Qt import QTimer, QApplication, Qt ...
""" Efficiently select the k-smallest element Author: Christopher Gondek """ import random def randomized_select_loop(data, k): """Returns the k-smallest (zero-based) item of a list. Parameters ---------- data : list List of comparable elements. k : int The k smallest elemen...
import logging import dns.resolver from nose.plugins.attrib import attr from marvin.cloudstackTestCase import cloudstackTestCase from marvin.lib.utils import cleanup_resources from marvin.lib.base import (ServiceOffering, VirtualMachine, Account, ...
import os.path import tempfile import fixtures import six from neutron.common import constants from neutron.tests import base from neutron.tests.common import helpers as c_helpers from neutron.tests.common import net_helpers class ConfigDict(base.AttributeDict): def update(self, other): self.convert_to_...
#!/usr/bin/env python import time import unittest import json from ngcccbase.p2ptrade.comm import CommBase, HTTPComm, ThreadedComm MESSAGES = json.loads("""[{"content": {"A": {"color_spec": "obc:ca99e77717e7d79001d3b876272ab118133a69cc7cbd4bf89d523f1be5607095:0:277127", "value": 100}, "msgid": "2050de1a0bc6db0b", "B...
from networking_vsphere.drivers import base_manager from networking_vsphere.tests.unit.drivers import fake_driver class MockNetworkManager(base_manager.DriverManager): def __init__(self, callback): base_manager.DriverManager.__init__(self) self.methods = {} self.driver = None def get...
#!/usr/bin/env python """prepostprocessor.py: prepostprocess the input data""" __author__ = "Raj Dabre" __license__ = "undecided" __version__ = "1.0" __email__ = "<EMAIL>" __status__ = "Development" import collections import logging import codecs import json import operator import os.path import gzip import io from su...
from lib.exchanges import * def getBCHTML(myObject): try: website = getHtml(myObject.baseUrl + myObject.currency) website_html = website.read() html = lxml.html.fromstring(website_html) #fill myObject.bids/asks bids_html = '/html/body/div/div[3]/div[2]/table/tr[*]/td//text...
import re import os import sys import sqlite3 import string import traceback import random import re import GenTools import CrazyLogic ############################################################################### # main() ############################################################################### puzzleArray =...
"""Runs the aggregate interference code under profiler. This script creates several profile output: profile-<idx>.out where idx: 0 is the main process 1-N: for each workers Note: script derived from the aggregate_interference_example.py """ from __future__ import absolute_import from __future__ import division ...
#!/usr/bin/env python #-*- coding:utf-8 -*- from django.shortcuts import render_to_response, get_list_or_404 from django.http import HttpResponse from django.http import HttpResponseRedirect from django.http import HttpRequest from django.utils.encoding import force_unicode from google.appengine.api import users from ...
import webapp2 from model import Project,Quest,Task from google.appengine.ext import ndb class CreateEntitiesHandler(webapp2.RequestHandler): def get(self): ndb.delete_multi( Project.query().fetch(keys_only=True) ) ndb.delete_multi( Quest.query().fetch(keys_only=True...
import os import shutil from pyanaconda.core import util from pyanaconda.modules.common.errors.installation import NetworkInstallationError from pyanaconda.modules.common.task import Task from pyanaconda.anaconda_loggers import get_module_logger from pyanaconda.modules.network.nm_client import update_connection_values...
friends = [ { "id": "BFP", "firstName": "Big Fat", "lastName": "Panda", "telephone": "574-213-0726", "email": "<EMAIL>", "notes": "My bestest friend in all the world." }, { "id": "VinDi", "firstName": "Vin", "lastName": "Diesel", ...
#!/usr/bin/env python3 import psycopg2 import math import re import sys import os import struct from PIL import Image def deg2num(lat_deg, lon_deg, zoom=16): lat_rad = math.radians(lat_deg) n = 2.0 ** zoom xtile = int((lon_deg + 180.0) / 360.0 * n) ytile = int((1.0 - math.log(math.tan(lat_rad) + (1 /...
"""Module providing data source contents via REST interface.""" __author__ = 'Mike Gainer (<EMAIL>)' from models import roles from models import transforms from models.data_sources import base_types from models.data_sources import source_handler from models.data_sources import utils as data_source_utils from models.d...
# -*- coding: utf-8-*- import os import re from getpass import getpass import yaml from pytz import timezone import feedparser import jasperpath def run(): profile = {} print("Welcome to the profile populator. If, at any step, you'd prefer " + "not to enter the requested information, just hit 'Ente...
"""The tests the for Traccar device tracker platform.""" from unittest.mock import patch import pytest from homeassistant import data_entry_flow from homeassistant.components import traccar, zone from homeassistant.components.device_tracker import DOMAIN as DEVICE_TRACKER_DOMAIN from homeassistant.components.traccar ...
#encoding=utf-8 import sys sys.path.append("../") import jieba def cuttest(test_sent): result = jieba.cut(test_sent,HMM=False) print(" / ".join(result)) if __name__ == "__main__": cuttest("这是一个伸手不见五指的黑夜。我叫孙悟空,我爱北京,我爱Python和C++。") cuttest("我不喜欢日本和服。") cuttest("雷猴回归人间。") cuttest...
# coding: utf-8 from django.shortcuts import get_object_or_404 from dajax.core import Dajax from dajaxice.decorators import dajaxice_register from . import common from . import models from .templatetags.pretty_print import person_compare_row @dajaxice_register def add_to_compare(request, person_id): person_id = ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # @Author: Patrick Bos # @Date: 2016-11-16 16:23:55 # @Last Modified by: E. G. Patrick Bos # @Last Modified time: 2017-05-05 08:24:28 import numpy as np import matplotlib.pyplot as plt import pandas as pd import seaborn as sns import glob import os import functools f...
import numpy from numpy.random import random_integers as rand from random import randrange #import matplotlib.pyplot as pyplot def maze(width=81, height=51, complexity=1, density=1): # Only odd shapes shape = ((height // 2) * 2 + 1, (width // 2) * 2 + 1) # Adjust complexity and density relative to maze si...
""" ``Blink`` switches through the images shown in a channel at a rate chosen by the user. Alternatively, it can switch between channels in the main workspace. In both cases, the primary purpose is to compare and contrast the images (within a channel, or across channels) visually within a short timescale -- like blin...
#!/usr/bin/python """ Upgrade to new IOB convention: Inside, Outside, Begin. """ # O I -> O B # I B -> I B # I I -> I I # I O -> I O import sys import getopt def usage(): print 'usage:', sys.argv[0], '[-hr] < inFile ' print ' -r revert to old convention.' sys.exit() try: opts, args = getopt.getopt...
"""Diverse TensorFlow utils, for training, evaluation and so on! """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import re from pprint import pprint import tensorflow as tf from tensorflow.contrib.slim.python.slim.data import parallel_reader ...
#!/usr/bin/env python import sys, glob,astropy, astropy.io.fits as pyfits, os.path from numpy import * import scipy.interpolate.interpolate as interp from readtxtfile import readtxtfile from optparse import OptionParser c = 2.99792458e18 #Angstroms/s spectrafiles = glob.glob('pickles/*.dat') spectra = [readtxtfile(s...
from __future__ import unicode_literals from django.contrib.auth import get_user_model from django.contrib.auth.models import Permission class ModelBackend(object): """ Authenticates against django.contrib.auth.models.User. """ # TODO: Model, login attribute name and password attribute name should be...
#coding: utf-8 from aarddict import ui def test_config_read_list(): config = ui.Config() from StringIO import StringIO config.readfp(StringIO(""" [testlist] 5 = a 3 = q 1 = z 10 = b 09 = c 100 = p """)) result = config.getlist('testlist') assert result == ['z', 'q', 'a', 'c', 'b...
''' salt.targeting.query ~~~~~~~~~~~~~~~~~~~~ ''' import inspect from salt.targeting import rules from salt.targeting.parser import parse, normalize import logging log = logging.getLogger(__name__) __all__ = [ 'Evaluator', 'ListEvaluator', 'RuleEvaluator', 'NodeGroupEvaluator', 'Query', ] cla...
from __future__ import absolute_import from datetime import timedelta from django.db import connections, router from django.utils import timezone from sentry.utils import db class BulkDeleteQuery(object): def __init__(self, model, project_id=None, dtfield=None, days=None, order_by=None): self.model = mo...
from django.utils.translation import ugettext_lazy as _ ESTADO_CIVIL_ES_AR = ( ('', _('')), ('VIUDO', _('VIUDO')), ('SOLTERO', _('SOLTERO')), ('CASADO', _('CASADO')), ('DIVORCIADO', _('DIVORCIADO')), ('CONCUBINATO', _('CONCUBINATO')), ) JERARQUIAS_ES_AR = ( ('COMANDANTE GENERAL', _('COMA...
# coding: utf-8 from __future__ import division import xlrd import xlsxwriter from django.db.models import AutoField from jumpserver.api import * from jasset.models import ASSET_STATUS, ASSET_TYPE, ASSET_ENV, IDC, AssetRecord from jperm.ansible_api import MyRunner from jperm.perm_api import gen_resource from jumpserver...
"""JSON conversion utility functions.""" from __future__ import absolute_import from past.builtins import long from past.builtins import unicode from apache_beam.options.value_provider import ValueProvider # Protect against environments where apitools library is not available. # pylint: disable=wrong-import-order, ...
# -*- coding: utf-8 -*- """About information.""" __author__ = "Yuan Chang" __copyright__ = "Copyright (C) 2016-2019" __license__ = "AGPL" __email__ = "<EMAIL>" from requests import get as get_url from qtpy.QtCore import Qt, QCoreApplication from qtpy.QtWidgets import QDialog, QWidget, QProgressDialog from pyslvs imp...
# -*- coding: utf-8 -*- import wabbit_wappa as _wabbit_wappa from math import exp import copy from collections.abc import Mapping class Namespace(_wabbit_wappa.Namespace): """ A subclass of wabbit wappa Namespace that allows one to set features from a dictionary """ def add_features(self, feature...
"""Tools for indentation-aware code string stitching. When formatting an AST into a string, it's better to collect lists of snippets and then join them than adding the pieces continually, which gives O(n^2) behaviour w.r.t. AST size n. """ class Indented(object): """Class to mark a collection of snippets for inde...
#!/usr/bin/env python # -*- coding: utf-8 -*- import os.path import glob import os import re import sys import string import shutil import stat import time from time import gmtime, strftime from random import Random test_names = [] current = [] test_sections = [] sample_types = [] descriptions = []...
import uuid from sahara.openstack.common import excutils from sahara.tests.integration.tests import base class SwiftTest(base.ITestCase): @base.skip_test( 'SKIP_SWIFT_TEST', message='Test for check of Swift availability was skipped.') def check_swift_availability(self, cluster_info): ...
from trantor import parse, build from datetime import datetime, timedelta, timezone def test_parse(): """ Test parsing real world examples of binary data """ binary_data = b'Y\x02\x17X\x0cd,\x8d\x0f\xa6@w\xa5\\^>\xda=BZY'\ b'\x02\x17X\x00\x00\x00\x00\x00\x00\x00\x00\x00'\ ...
from sqlalchemy import Column, ForeignKey from sqlalchemy import Integer, String from sqlalchemy.orm import relationship from gw2db.common import Base, endpoint_def, rel_json class _Gw2MasteryLevel(Base): __tablename__ = "gw2_pro_mastery_level" pkid = Column(Integer, primary_key=True) mastery_id = Colum...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ HTML ==== Transforms HTML in PDF templates. >>> html_to_rlab('<h1>Title</h1><p><img src="lion.png" /></p>', ... PathMediasLocator('/var/www/medias')) The supported tags are: h1-h6, p, center, blockquote, a, br, ul, li """ from __future__ import absolu...
from rhizome.tests.base_test_case import RhizomeApiTestCase from django.contrib.auth.models import User from rhizome.models.location_models import LocationType, Location, LocationPermission from rhizome.cache_meta import LocationTreeCache class LocationResourceTest(RhizomeApiTestCase): def setUp(self): ...
''' We loop over words in a dataset, and for each word, we look at a context window around the word. We generate pairs of (pivot_word, other_word_from_same_context) with label 1, and pairs of (pivot_word, random_word) with label 0 (skip-gram method). We use the layer WordContextProduct to learn embedd...
import pickle import os import pandas as pd def filter_phospho(df): """ filter and format phosphosite extra tables """ is_human = df['ORGANISM'] == 'human' ptms = df['MOD_RSD'].str.split('-') ptm_type = ptms.str.get(1) ptm_rsd = ptms.str.get(0) ptm_aa = ptm_rsd.str.get(0) ptm_pos = ptm_rsd...
"""Tests for 1-Wire config flow.""" from pyownet import protocol from homeassistant.components.onewire.const import ( CONF_MOUNT_DIR, CONF_TYPE_OWSERVER, CONF_TYPE_SYSBUS, DEFAULT_OWSERVER_PORT, DEFAULT_SYSBUS_MOUNT_DIR, DOMAIN, ) from homeassistant.config_entries import SOURCE_IMPORT, SOURCE_U...
# -*- coding: utf-8 -*- { 'About': 'کے بارے میں', 'Access denied': 'رسائی نہیں ہوئی', 'Activities': 'کاروائیاں', 'Add': 'اضافہ کریں', 'Assessments': 'تجزیے', 'Biscuits': 'بسکٹ', 'Bricks': 'اینٹوں', 'Cancel': 'منسوخ', 'Category': 'زمرہ', 'Change Password': 'پاس ورڈ تبدیل کریں', 'Chicken': 'چکن', 'Child': 'ب...
import contextlib import time import couchdb import docker import pytest # Fixtures can have dependencies on each other # That way you can have abstraction layers of fixtures # # Dependency: Two clients we need to setup docker containers # # 'session' scope meaning that this fixture is valid for the whole # test run...
from flask import Flask, render_template, session, redirect, url_for, flash from flask_moment import Moment from flask_bootstrap import Bootstrap from flask_wtf import FlaskForm from wtforms import StringField, SubmitField from wtforms.validators import DataRequired from flask_bootstrap import Bootstrap app = Flask(...
import logging from autotest.client.shared import error from autotest.client.virt import kvm_monitor def run_qmp_basic_rhel6(test, params, env): """ QMP Specification test-suite: this checks if the *basic* protocol conforms to its specification, which is file QMP/qmp-spec.txt in QEMU's source tree. I...
from __future__ import absolute_import, division, print_function __metaclass__ = type import traceback from ansible_collections.theforeman.foreman.plugins.module_utils.foreman_helper import ( ForemanTaxonomicEntityAnsibleModule, ParametersMixin, missing_required_lib ) try: import ipaddress HAS_IPADDRESS =...