content
string
import json import re import anchore_engine.services import anchore_engine.utils from anchore_engine import db from anchore_engine.clients import docker_registry from anchore_engine.subsys import logger def lookup_registry_image(userId, image_info, registry_creds): digest = None manifest = None # TODO: ...
""" The core pattern classes. """ import abc import inspect import itertools import operator import random from collections.abc import Sequence from typing import Dict, Iterator, Optional from uqbar.objects import get_vars from supriya.clocks import Clock from supriya.providers import Provider from .events import Co...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __version__ = "1.2.0" from fileinput import close import exifread import os import shutil import time from .radmyarchiveexceptions import * class RADMyArchive: def __init__(self, filepath, destination=".//NewImageArchive", move=False): self._filePath = fi...
#!/usr/bin/python3 # aikif_test_utils.py """ module to import for all test modules in /tests NOTE - use this for constants such as folder paths but do not rely on it for the sys.path in case there are side effects with CI tools - keep it simple and do a sys.path.insert in each of the test modules from https://docs.pyt...
#!/bin/env python import Pyro4 import time from threading import Event, Thread Pyro4.config.COMMTIMEOUT = 1.0 # without this daemon.close() hangs class CallbackAPI: def __init__(self, daemon): self.daemon = daemon self.running = True def shutdown(self): print 'shutting...
#!/usr/bin/env python import rospy from sensor_msgs.msg import JointState class JointStateRepublisher(): "A class to republish joint state information" def __init__(self): rospy.init_node('ptu_state_republisher') self.pub = rospy.Publisher('/ptu/state', JointState) rospy.Subscriber("/ptu_state"...
""" Tests for the app_util module """ import unittest from .narrative_mock.mockclients import get_mock_client, MockStagingHelper import mock from . import util from biokbase.narrative.jobs.batch import ( list_objects, list_files, get_input_scaffold, _generate_vals, _is_singleton, generate_input_...
# -*- coding: utf-8 -*- import json import logging import urlparse from datetime import datetime import scrapy from pybloom import ScalableBloomFilter from pymongo import MongoClient from scrapy.exceptions import CloseSpider from scrapy_redis.spiders import RedisSpider from items import OrderItem class OrderSpider(...
import math from requests import HTTPError from intern.remote.boss import BossRemote from intern.resource.boss.resource import * def get_boss_project(rmt, proj_setup): try: proj_actual = rmt.get_project(proj_setup) except HTTPError: try: proj_actual = rmt.create_project(proj_setu...
#!/usr/bin/env python import argparse import os import sys import os.path import tempfile from contextlib import closing # Parser Arguments parser = argparse.ArgumentParser(description='Show the list of included files from a C++ file. ') parser.add_argument('-i', '--input', dest='input_file', help='The C++ file', de...
import os import pyexcel as pe import pyexcel.ext.xls import pyexcel.ext.xlsx from _compact import BytesIO, StringIO class TestIrregularities: def setUp(self): self.testfile = "test.xlsm" self.content = [ [1, "", "", "", "", ""], [1, 2, "", "", "", ""], [1, 2,...
# noinspection PyUnresolvedReferences from course_discovery.settings._debug_toolbar import * # isort:skip from course_discovery.settings.production import * DEBUG = True # Docker does not support the syslog socket at /dev/log. Rely on the console. LOGGING['handlers']['local'] = { 'class': 'logging.NullHandler', ...
''' Copyright (c) 2017 Vanessa Sochat 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, publish, distribute...
from zope import schema from zope.interface import Interface from zope.app.container.constraints import contains from zope.app.container.constraints import containers from vwcollective.imprint import imprintMessageFactory as _ # -*- extra stuff goes here -*- class IImprint(Interface): """Imprint content type"""...
# coding:utf-8 #!/usr/bin/env python # coding:utf-8 # @Date : 2017-01-01 20:38:38 # @Author : Smile Hu (<EMAIL>) # @Link : http://www.smilehu.com import sys reload(sys) sys.setdefaultencoding('utf-8') from bs4 import BeautifulSoup import requests from time import sleep headers = { 'User-Agent': 'Mozilla...
import json from rows import fields class FloatField(fields.FloatField): @classmethod def deserialize(cls, value, *args, **kwargs): try: # Rows cannot convert values such as '14,96' to float value = float(value.replace(',', '.')) except: pass return super(Flo...
import melee import random import Chains from melee.enums import Action, Character from Tactics.tactic import Tactic class Celebrate(Tactic): def __init__(self, logger, controller, framedata, difficulty): Tactic.__init__(self, logger, controller, framedata, difficulty) self.random_celebration = ran...
from Screen import Screen from Components.ActionMap import ActionMap from Components.config import config from Components.AVSwitch import AVSwitch from Components.SystemInfo import SystemInfo from GlobalActions import globalActionMap from enigma import eDVBVolumecontrol inStandby = None class Standby(Screen): def Po...
from urllib import parse as urlparse from hitchhttp import status_codes from requests.structures import CaseInsensitiveDict from hitchhttp.utils import parse_qsl_as_dict, xml_elements_equal import lxml.etree as etree import xeger import json import cgi import io def convert_querystring(qs): """Allow for non-lists...
from pyramid.view import view_config from pyramid import renderers from substanced.util import get_oid from dace.processinstance.core import DEFAULTMAPPING_ACTIONS_VIEWS from dace.objectofcollaboration.principal.util import get_current from pontus.default_behavior import Cancel from pontus.form import FormView from p...
from Kamaelia.Chassis.Graphline import Graphline from Kamaelia.Internet.TCPClient import TCPClient from Kamaelia.Util.Console import ConsoleEchoer, ConsoleReader from Kamaelia.Util.OneShot import OneShot print """ This is a simple demonstration program that shows that it is possible to build simple clients for manuall...
data = { "orcid-identifier": { "uri": "http://sandbox.orcid.org/0000-0001-8868-9743", "path": "0000-0001-8868-9743", "host": "sandbox.orcid.org" }, "preferences": { "locale": "EN" }, "history": { "creation-method": "MEMBER_REFERRED", "completion-date":...
""" Help functions to extract storage account, container name, blob name and other information from container and/or blob URL. """ # pylint: disable=too-few-public-methods, too-many-instance-attributes class StorageResourceIdentifier(object): def __init__(self, moniker): self.is_valid = False self...
""" fetch_to_dir.py: Fetch specified pages into seaprate directories This demo script uses the low-level methods from the artexin package to fetch and extract articles from a few different pages on the web. Copyright 2014, Outernet Inc. Some rights reserved. This software is free software licensed under the terms of...
from openerp import api, fields, models class AddressCategory(models.Model): _inherit = 'clv.address.category' address_history_ids = fields.Many2many( comodel_name='clv.address.history', relation='clv_address_history_category_rel', column1='category_id', column2='address_histo...
{ "name": "Account Move Group", "version": "1.1", "author" : "Vauxoo", "category": "Generic Modules/Account", "website" : "http://www.vauxoo.com/", "description": """ Group Entries """, 'depends': ['account'], 'init_xml': [], 'update_xml': [ 'wizard/account_move_group_vie...
from gi.repository import Gtk from lollypop.define import Lp from lollypop.toolbar_playback import ToolbarPlayback from lollypop.toolbar_infos import ToolbarInfos from lollypop.toolbar_title import ToolbarTitle from lollypop.toolbar_end import ToolbarEnd # Toolbar as headerbar # Get real widget with Toolbar.widget c...
from utils.exception import RdopkgException from utils.exception import CommandFailed, CommandNotFound, SpecFileNotFound, \ IncompleteChangelog, MultipleSpecFilesFound, SpecFileParseError, \ InvalidAction, ModuleNotAvailable, RpmModuleNotAvailable, \ BuildArchSanityCheckFailed, BranchNotFound class UserAb...
class UserModel: def __init__(self, **kwargs): self.db = kwargs.get('db', None) self.users = self.db.user self.id = None self.username = kwargs.get('username', None) self.password = kwargs.get('password', None) self.role = kwargs.get('role', None) def set(self, ...
# coding=utf-8 u"An AMX beacon signal receiver - listens out on multicast address 239.255.250.250:9131" # example beacon data: # source: 192.168.178.173.9131 # data: AMXB<-UUID=GlobalCache_000C1E038995><-SDKClass=Utility><-Make=GlobalCache><-Model=iTachIP2IR> # <-Revision=710-1005-05><-Pkg_Level=GCPK002><-Config-URL=h...
import hashlib import socket import unittest from os.path import exists import tests.test_helpers as h class TestWindowsize(unittest.TestCase): @classmethod def setUpClass(cls): with open('LICENSE', 'rb') as f: cls.license = f.read() cls.server_addr = ('127.0.0.1', 9069,) ...
#!/usr/bin/env python """Provides an application controller for the commandline version of mothur Version 1.6.0 """ from __future__ import with_statement from operator import attrgetter from os import path, getcwd, mkdir, remove, listdir, rmdir import re from shutil import copyfile from subprocess import Popen from t...
# -*- coding: utf-8 -*- """ Created on Tue Jan 19 16:39:05 2016 @author: tanfan.zjh """ from structure import DependencyTree as tree import DepNN as nn from execute import Execute as exe lines = ('[(S (NP (DT Those) (NN space)) (VP (VBZ walks) (SBAR (S (VP (VBP are) (S (VP (TO to) (VP (VB be) (VP (VBN used) (PP (IN ...
#!/usr/bin/env python # -*- coding: utf8 -*- # ***************************************************************** # ** PTS -- Python Toolkit for working with SKIRT ** # ** © Astronomical Observatory, Ghent University ** # ***************************************************************** ##...
import textwrap def wordwrap(value, width=79): return '\n\n'.join([textwrap.fill(s, width) for s in value.split('\n\n')]) def indent(text, spaces=0, first_line=False): """ Indent the text by the given number of white spaces. """ prefix = ' ' * spaces if first_line: return textwrap.in...
""" Bookmark manager """ __author__ = "Cody Precord <<EMAIL>>" __svnid__ = "$Id: ed_bookmark.py 67489 2011-04-14 15:39:14Z CJP $" __revision__ = "$Revision: 67489 $" #--------------------------------------------------------------------------# # Imports import os import re import wx # Editra Libraries import ed_msg ...
""" The following problem is taken from Project Euler, https://projecteuler.net/problem=16 licenced under a Creative Commons Licence: Attribution-NonCommercial-ShareAlike 2.0 UK: England & Wales Problem 16 3 May 2002 2¹⁵ = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26. What is the sum of the digi...
from agui.backends.gtk.imports import * from agui.awidgets import AIndicator from agui.backends.gtk.widgets import Widget class Indicator(Widget, AIndicator): def __init__(self, window, name, menu, attention_icon, passive_icon): AIndicator.__init__(self, window, name, menu, attention_icon, passive_icon) ...
#!/usr/bin/env python # -*- coding: utf-8 -*- """Tests for sorting algorithms. Responsible for triggering sorting algorithms: SelectionSort, HeapSort, QuickSort, ShellSort, MergeSort and CooktailSort, measuring the amount of exchanges, number of comparisons and time spent for collections with 25, 500, 10000, 200000, ...
import logging import os import datetime from pastehunter.common import parse_config logger = logging.getLogger('pastehunter') config = parse_config() class CSVOutput(object): def __init__(self): base_path = config['outputs']['csv_output']['output_path'] # Get todays CSV dtg = datetime.da...
import os import flask from flask.ext.wtf import Form import wtforms from wtforms import validators from digits.config import config_value from digits.device_query import get_device, get_nvml_info from digits import utils from digits.utils import sizeof_fmt from digits.utils.forms import validate_required_iff from di...
# coding=utf8 """ rux.pdf ~~~~~~~ Generate PDF using wkhtmltopdf. """ import sys import time import subprocess import os from os import listdir as ls from os.path import exists from . import src_ext, charset from .config import config from .exceptions import * from .parser import parser from .renderer i...
"""Script to ensure a configuration file exists.""" import argparse import logging import os from collections import OrderedDict from glob import glob from platform import system from unittest.mock import patch from typing import Dict, List, Sequence from homeassistant import bootstrap, loader, setup, config as confi...
import datetime from pathlib import PurePosixPath import pytest # type: ignore from sqlalchemy import create_engine # type: ignore from sqlalchemy.sql import select # type: ignore # This is the WRONG place to store the WordCount class! from sensibility.language import SourceSummary from sensibility.miner.corpus im...
#!/usr/bin/env python3.5 # -*- coding: utf-8 -*- """ 三级菜单 可依次选择进入各子菜单 所需新知识点:列表、字典 """ _map = {"北京地区": {"北京市区": ["东城区", "西城区", "朝阳区", "海淀区", "石景山区", "丰台区"], "北京郊区": ["昌平区", "顺义区", "通州区", "大兴区"]}, "四川地区": {"成都市区": ["锦江区", "青羊区", "金牛区", "武侯区", "成华区", "高新区", "龙泉驿区", "温江区"]}, "广东地区": {"深圳市区": ["福田...
from hashlib import sha512 as hash_func from django.http import HttpResponse from django.http import HttpResponseRedirect from django.shortcuts import render_to_response from django.template import RequestContext from django.template.loader import get_template from django.core.context_processors import csrf from regi...
COMMA = u'\u060C' SEMICOLON = u'\u061B' QUESTION = u'\u061F' HAMZA = u'\u0621' ALEF_MADDA = u'\u0622' ALEF_HAMZA_ABOVE = u'\u0623' WAW_HAMZA = u'\u0624' ALEF_HAMZA_BELOW = u'\u0625' YEH_HAMZA = u'\u0626' ALEF = u'\u0627' BEH = u'\u0628' T...
from wpc import db, app from wpc.models import Stream, YoutubeStream, TwitchStream, Streamer, Submission, get_or_create from wpc.utils import youtube_video_id, twitch_channel, requests_get_with_retries from apscheduler.schedulers.blocking import BlockingScheduler import praw from bs4 import BeautifulSoup from sqlalch...
import sys, os, binascii, imp, shutil from . import __version__ from . import ffiplatform class Verifier(object): def __init__(self, ffi, preamble, tmpdir=None, modulename=None, ext_package=None, tag='', force_generic_engine=False, **kwds): self.ffi = ffi self.preamble = preamble...
from enigma import getDesktop, eTimer from Components.Label import Label from Components.Sources.StaticText import StaticText from Components.Pixmap import Pixmap from Components.ProgressBar import ProgressBar from Components.Sources.Progress import Progress from Components.ActionMap import NumberActionMap from Compon...
import datetime from rest_framework import serializers from django.contrib.auth.models import Group from django.core.exceptions import ObjectDoesNotExist, MultipleObjectsReturned from core.REST_serializers import PublicUserSerializer from core.REST_permissions import group_admin from .models import YaraRule, YaraRul...
import random import string import json class Traviata(object): #This two class attributes should be overriden _framework = "Undefined" _root_object = "undefined" def _handler_function_closure(self, name): raise NotImplementedError("This method must be overriden in '%s'" % self._...
import numpy from safe.impact_functions.core import (FunctionProvider, get_hazard_layer, get_exposure_layer, get_question) from safe.storage.vector import Vector from safe.common.utilities import (uge...
"""Support for IKEA Tradfri lights.""" import logging from homeassistant.components.light import ( ATTR_BRIGHTNESS, ATTR_COLOR_TEMP, ATTR_HS_COLOR, ATTR_TRANSITION, SUPPORT_BRIGHTNESS, SUPPORT_COLOR, SUPPORT_COLOR_TEMP, LightEntity, ) import homeassistant.util.color as color_util from ...
#!/usr/bin/env python # -*- coding: utf-8 -*- from itertools import chain from math import pi from mathics.builtin.numpy_utils import sqrt, floor, mod, cos, sin, arctan2, minimum, maximum, dot_t from mathics.builtin.numpy_utils import stack, unstack, array, clip, conditional, choose, stacked # in the long run, we mi...
"""Tests for Blame objects.""" from __future__ import absolute_import from __future__ import unicode_literals import unittest import pygit2 from pygit2 import Signature from pygit2 import GIT_DIFF_INCLUDE_UNMODIFIED from pygit2 import GIT_DIFF_IGNORE_WHITESPACE, GIT_DIFF_IGNORE_WHITESPACE_EOL from . import utils from ...
from .sub_resource import SubResource class InboundNatRule(SubResource): """Inbound NAT rule of the load balancer. Variables are only populated by the server, and will be ignored when sending a request. :param id: Resource ID. :type id: str :param frontend_ip_configuration: A reference to fr...
from alignak_test import * class TestServiceDepAndGroups(AlignakTest): def setUp(self): self.setup_with_file(['etc/alignak_servicedependency_implicit_hostgroup.cfg']) def test_implicithostgroups(self): # # Config is not correct because of a wrong relative path # in the main co...
import gmenu, re, sys from xml.sax.saxutils import escape def walk_menu(entry): if entry.get_type() == gmenu.TYPE_DIRECTORY: print '<menu id="%s" label="%s">' \ % (escape(entry.menu_id), escape(entry.get_name())) map(walk_menu, entry.get_contents()) print '</menu>' elif entry.get_type() == gmenu.TYPE_ENTRY ...
#!/usr/bin/env python # -*- coding: utf-8 -*- from ZIBMolPy.utils import register_file_dependency from ZIBMolPy.ui import Option, OptionsList from ZIBMolPy.io.trr import TrrFile from ZIBMolPy.node import Node from ZIBMolPy.pool import Pool import zgf_cleanup from subprocess import Popen, PIPE from tempfile import mkt...
from typing import Any, Optional, TYPE_CHECKING from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest from azure.mgmt.core import AsyncARMPipelineClient from msrest import Deserializer, Serializer if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from azure.core.credential...
from ..helpers import arguments from ..helpers.command import Command from ..helpers.misc import escape from ..helpers.orm import Log @Command(['grep', 'loggrep'], ['config', 'db'], limit=5) def cmd(send, msg, args): """Greps the log for a string. Syntax: {command} [--nick <nick>] [--ignore-case/-i] <string>...
# Example taken from AWS docs: # http://docs.aws.amazon.com/IAM/latest/UserGuide/ # ExampleIAMPolicies.html#iampolicy-example-s3homedir from awacs.aws import Action, Allow, Condition from awacs.aws import Policy, Statement from awacs.aws import StringEquals, StringLike import awacs.s3 as s3 pd = Policy( Statemen...
import os import numpy as np import tensorflow as tf import dataplumbing as dp ########################################################################################## # Settings ########################################################################################## # Model settings # num_features = dp.train.nu...
import datetime import glob,time import os,re,sys import string import ast from sets import Set import nltk from collections import defaultdict,Counter from decimal import * import numpy as np import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt def getDesc(in_folder,dt,tid_desc,tid_content): stops...
# -*- coding: utf-8 -*- """ Created on Mon Sep 14 11:14:55 2015 @author: pick """ import odml import datetime from odml_csv_table import OdmlCsvTable from odml_xls_table import OdmlXlsTable from odml_table import OdmlTable from compare_section_table import CompareSectionTable from compare_section_csv_table import Com...
""" Copyright 2008-2015 Free Software Foundation, Inc. This file is part of GNU Radio GNU Radio Companion 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 2 of the License, or (at your option) any l...
import functools from pprint import pprint from tkinter import * from datetime import datetime, time from pytz import timezone # la fenêtre import apiWeather fenetre = Tk() fenetre.configure(bg="#000000", pady=20, padx=20) fenetre.attributes("-fullscreen", True) # définitions des variables destinée à la taille des f...
""" Tests Unit for sensbiotk/calib """ # pylint:disable= I0011, E1101, E0611 # E1101 no-member false positif # E0611 no-name false positif import numpy as np from nose.tools import assert_equal def test_calib_acc(): """ Test calib_acc function """ from sensbiotk.algorithms.basic import find_static_peri...
#!/usr/bin/env python # Description = Predict 3 or 8 state secondary structure using RaptorX import os import subprocess class RaptorxSecstrAnalysis(object): def __init__(self, selected_proteins, raptorx_path, fasta_path, outpath): self._selected_proteins = selected_proteins self...
"""Handle the full callback process for signup. Performs various tasks, such as verifying the received token, retrieving and choosing ad clients, creating ad units, and generating ad code. """ __author__ = '<EMAIL> (Sergio Gomes)' from django.shortcuts import get_object_or_404, redirect, render from oauth2client.any...
from __future__ import unicode_literals, division, absolute_import from builtins import * # noqa pylint: disable=unused-import, redefined-builtin import logging from collections import MutableSet from requests import RequestException from flexget import plugin from flexget.entry import Entry from flexget.event impo...
# This is an script example of how to use the pytribe.EyeTribe class to track # gaze data while a participant is looking at some images. Please note that # the experiment assumes that you have calibrated the eye tracker beforehand, # using the EyeTribe UI. # # Data analysis will be performed directly after running the ...
import sys import gdb import os import os.path pythondir = '/home/konkers/toolchain/gcc-arm-none-eabi-4_9-2015q3-20150921/install-native/share/gcc-arm-none-eabi' libdir = '/home/konkers/toolchain/gcc-arm-none-eabi-4_9-2015q3-20150921/install-native/arm-none-eabi/lib/armv7e-m' # This file might be loaded when there is...
import json from django.core import serializers from vending.views import selects from vending.models import Cartridge, Round, Bullet, Material, Caliber, Manufacturer def handle_update(request): field = request.GET.get('update', 'none') request.session[field] = request.GET.get( 'value', 'any' ) res...
# Implementation of RAKE - Rapid Automtic Keyword Exraction algorithm # as described in: # Rose, S., D. Engel, N. Cramer, and W. Cowley (2010). # Automatic keyword extraction from indi-vidual documents. # In M. W. Berry and J. Kogan (Eds.), Text Mining: Applications and Theory.unknown: John Wiley and Sons, Ltd. # # NOT...
from gi.repository import Gtk class NameValueComboBox(Gtk.ComboBox): def __init__(self): Gtk.ComboBox.__init__(self) renderer_text = Gtk.CellRendererText() self.pack_start(renderer_text, True) self.add_attribute(renderer_text, "text", 0) self.name_index = 0 self.valu...
import ctypes import time import os import pybgfx class Window(ctypes.Structure): pass class App(object): def __init__(self): pass def init(self): pass def shutdown(self): pass def update(self, dt): pass def run(self): glfw_dll_path = os.path.dirna...
#Задача №8, Вариант 7 #Доработайте игру "Анаграммы" (см. М.Доусон Программируем на Python. Гл.4) так, чтобы к каждому слову полагалась подсказка. Игрок должен получать право на подсказку в том случае, если у него нет никаких предположений. Разработайте систему начисления очков, по которой бы игроки, отгадавшие слово бе...
from __future__ import absolute_import import time import sys from cStringIO import StringIO from psycopg2.extensions import QuotedString from .postgres_writer import PostgresWriter from . import print_row_progress, status_logger class PostgresFileWriter(PostgresWriter): """Class used to ouput the PostgreSQL ...
""" Test cases for the Attribute node extra. """ import pytest from mwparserfromhell.nodes import Template from mwparserfromhell.nodes.extras import Attribute from .conftest import assert_wikicode_equal, wrap, wraptext def test_str(): """test Attribute.__str__()""" node = Attribute(wraptext("foo")) asser...
from __future__ import unicode_literals from indico.modules.events.tracks.controllers import (RHCreateTrack, RHDeleteTrack, RHDisplayTracks, RHEditProgram, RHEditTrack, RHManageTracks, RHSortTracks, RHTracksPDF) from indico.web.flask.util import make_compat_redirec...
from django.contrib.auth.models import User from django.test import TestCase, Client from authy_me.models import AuthenticatorModel class ViewsTests(TestCase): """ Test case for ``views`` """ def setUp(self): password = 'mypassword' self.my_admin = User.objects.create_superuser('myu...
# -*- coding: utf-8 -*- from decimal import Decimal import unittest from shaibos.load.from_yaml import load_invoices_from_yaml_string from shaibos.tax.totals import invoice_totals, buyer_totals, activity_totals, tax_totals # noinspection PyPep8Naming class TestClass(unittest.TestCase): test_invoices = None t...
import pytest def test_error_already_set(msg): from pybind11_tests import throw_already_set with pytest.raises(RuntimeError) as excinfo: throw_already_set(False) assert msg(excinfo.value) == "Unknown internal error occurred" with pytest.raises(ValueError) as excinfo: throw_already_se...
import sys import os import os.path import glob import shutil import logging import optparse from PIL import Image import pickle from tiler_functions import * class KeyboardInterruptError(Exception): pass def f_approx_eq(a, b, eps): return (abs(a-b) / (abs(a)+abs(b))/2) < eps def transparency(img): 'es...
import os import random def display_board(board): os.system('clear') print(' | |') print(' ' + board[7] + ' | ' + board[8] + ' | ' + board[9]) print(' | |') print('-----------') print(' | |') print(' ' + board[4] + ' | ' + board[5] + ' | ' + board[6]) print(' | |') ...
""" This module contains generic code to find and load a dynamic library. """ from __future__ import absolute_import, print_function, division import os import sys import ctypes LOCALDIR = os.path.abspath(os.path.dirname(__file__)) # Flag that can be patched / set to True to disable loading non-system libs SYSTEM_...
from sympy import Rational, fibonacci from sympy.core import S, symbols from sympy.core.compatibility import range from sympy.utilities.pytest import raises from sympy.discrete.recurrences import linrec def test_linrec(): assert linrec(coeffs=[1, 1], init=[1, 1], n=20) == 10946 assert linrec(coeffs=[1, 2, 3, 4...
import sys, pickle sys.path.append('./mobtypingmodules') from mobmods import runsubprocess #sys.argv[1] dataprefix; sys.argv[2]/[3] 0 0 (no id/coverage thresholds); sys.argv[4] evalue; sys.argv[5] maxiter #extract sequence ids, alignment lengths and gapopen from blast table fileObj=open('./output_intermediate/%s_BLAS...
import classifier class naivebayes(classifier.classifier): def __init__(self, getFeatures): classifier.classifier.__init__(self, getFeatures) self.thresholds = {} # Pr(document|category) def docProb(self, item, cat): features = self.getFeatures(item) # Pr(d...
# -*- coding: utf-8 -*- from __future__ import absolute_import import os import sys import collections import click import requests import lxml.etree import baidupcsapi import caiyun session = requests.Session() headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko...
import datetime import time import uuid from google.api_core import exceptions import pytest import create_config import create_deployment import create_realm import delete_config import delete_deployment import delete_realm import get_config import get_deployment import get_rollout import list_configs import list_d...
from django.conf.urls import url from workshift import views base = r"workshift(?:/(?P<sem_url>\w+\d+))?" urlpatterns = [ url( r"^workshift/start/$", views.start_semester_view, name="start_semester", ), url( base + r"/$", views.semester_view, name="view_sem...
from typing import NamedTuple, Dict, List # The source path that is backup-ed. BackupSrc = str # The dir that contains 'backup.latest' and all snapshot dirs for backup source. BackupRoot = str # The backup.latest dir, which is the destination for rsync. # It's located in BackupRoot. BackupLatest = str # A snapshot ...
from fakeredis import FakeRedis import redis from redlock import Redlock from redlock_fifo.extendable_redlock import ExtendableRedlock from time import time import threading class FakeRedisCustom(FakeRedis): def __init__(self, db=0, charset='utf-8', errors='strict', **kwargs): super(FakeRedisCustom, self)...
# encoding: utf-8 """An example raw IOLoop/IOStream example. Taken from http://nichol.as/asynchronous-servers-in-python by Nicholas Piël. """ import errno import functools import socket from marrow.util.compat import exception from marrow.io import ioloop, iostream log = __import__('logging').getLogger(__name__) ...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('core', '0003_auto_20170504_1443'), ] operations = [ migrations.CreateModel( name='CSWRecordReference', ...
__author__ = 'Dominic Miglar <<EMAIL>>' import unittest from time import sleep, time from bitcodin import create_job, get_job_status from bitcodin import create_input from bitcodin import create_encoding_profile from bitcodin import delete_input from bitcodin import delete_encoding_profile from bitcodin import transfe...
"""Tests for config loading functions. """ import io import pytest from cosmic_ray.config import ConfigDict, ConfigError, load_config, serialize_config def test_load_valid_stdin(mocker): temp_stdin = io.StringIO() temp_stdin.name = 'stringio' config = ConfigDict() config['key'] = 'value' temp_st...