code
stringlengths
1
199k
from __future__ import print_function import getpass import logging import os import os.path as op from ssbio.protein.sequence.utils import fasta as fasta log = logging.getLogger(__name__) class ITASSERPrep(): """Prepare a protein sequence for an I-TASSER homology modeling run. The main utilities of this class ...
import pytest from CyberArkPAS import Client, add_user_command, get_users_command, \ update_user_command, add_safe_command, update_safe_command, get_list_safes_command, get_safe_by_name_command, \ add_safe_member_command, update_safe_member_command, list_safe_members_command, add_account_command, \ update_a...
r""" Examples -------- :: * - * / \ / \ * - * - * / \ / \ / \ * - * - * - * \ / \ / \ / * - * - * \ / \ / * - * >>> from landlab.graph import TriGraph >>> graph = TriGraph((5, 2), node_layout="hex", sort=True) >>> graph.number_of_nodes 14 >>> graph.x_of_node array...
import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'Package' db.create_table('banzai_package', ( ('id', self.gf('django.db.models.fields.AutoField')(primary_ke...
class Solution(object): def threeSum(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ res = [] nums.sort() for i in xrange(len(nums) - 2): if i > 0 and nums[i] == nums[i - 1]: continue l, r = i + 1, len...
from swgpy.object import * def create(kernel): result = Building() result.template = "object/building/tatooine/shared_housing_tatt_style02_large.iff" result.attribute_template_id = -1 result.stfName("building_name","housing_tatt_style01_large") #### BEGIN MODIFICATIONS #### #### END MODIFICATIONS #### return r...
from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('connectors', '0002_parameter_description'), ] operations = [ migrations.RenameField( model_name='callback', old_name='type', ...
from vint.ast.traversing import traverse, register_traverser_extension from vint.ast.parsing import Parser from vint.ast.node_type import NodeType REDIR_CONTENT = 'VINT:redir_content' class RedirAssignmentParser(object): """ A class to make redir assignment parseable. """ def process(self, ast): def ent...
from msrest.paging import Paged class AutoscaleSettingResourcePaged(Paged): """ A paging container for iterating over a list of :class:`AutoscaleSettingResource <azure.mgmt.monitor.models.AutoscaleSettingResource>` object """ _attribute_map = { 'next_link': {'key': 'nextLink', 'type': 'str'}, ...
"""Collection of functions and classes to fix various encoding problems on multiple platforms with python. """ import codecs import locale import os import sys _SYS_ARGV_PROCESSED = False def complain(message): """If any exception occurs in this file, we'll probably try to print it on stderr, which makes for frustr...
from .development import * DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': '{{ taiga_database_username }}', 'USER': '{{ taiga_database_username }}', 'PASSWORD': '{{ taiga_database_password }}', 'HOST': '{{ taiga_database_host }}', ...
from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('imagr_app', '0002_auto_20141106_1538'), ] operations = [ migrations.AlterField( model_name='album', name='date_published', ...
""" simple cache based on shelve """ import shelve import time def load_cache(cache_file): cache = shelve.open(cache_file) return cache def read_key(cache, key, ttl): """ Reads value from cache, if doesnt exist or is older than ttl, raises KeyError """ bibtex, timestamp = cache[key] if (timestam...
import platform import os import sys from .constants import (MYSTEM_BIN, MYSTEM_EXE, MYSTEM_DIR) _TARBALL_URLS = { 'linux': { '32bit': "http://download.cdn.yandex.net/mystem/mystem-3.0-linux3.5-32bit.tar.gz", '64bit': "http://download.cdn.yandex.net/mystem/mystem-3.0-linux3.1-64bit.tar.gz", }, ...
"""This file is useful only if 'salesforce' is a duplicit name in Django registry then put a string 'salesforce.apps.SalesforceDb' instead of simple 'salesforce' """ from django.apps import AppConfig class SalesforceDb(AppConfig): name = 'salesforce' label = 'salesforce_db'
from scipy.io import loadmat from sys import argv from json import load TT = 30 # how many periods of results to send model = argv[2] fpath = argv[1] + '/' + model + '_mfiles/' json = '' mat = loadmat(fpath + 'plot_vars.mat') plot_names = mat['plot_vars'].dtype.names plot_simul = mat['plot_vars'][0][0] for name, simul ...
from swgpy.object import * def create(kernel): result = Tangible() result.template = "object/tangible/deed/corellia/player_house_deed/shared_corellia_house_large_deed.iff" result.attribute_template_id = 2 result.stfName("deed","corellia_house_large_deed") #### BEGIN MODIFICATIONS #### #### END MODIFICATIONS ###...
import os, sys import tempfile import unittest as unittest0 try: unittest0.skipUnless unittest0.skip except AttributeError: import unittest2 as unittest else: unittest = unittest0 del unittest0 import win32file from winsys import fs class TestDrive (unittest.TestCase): # # The name of the drive should be no...
""" Experimental agent implementation running separate threads for emulation and GPU training. This is slightly (estimate ~20%) faster than the sequential implementation, but results might be different. Copyright 2016 Rasmus Larsen This software may be modified and distributed under the terms of the MIT license. See th...
n = int(raw_input('Ingrese n: ')) es_primo = True d = 2 while d < n: if n % d == 0: es_primo = False d = d + 1 if es_primo: print(n, 'es primo') else: print(n, 'es compuesto')
from urbansim.models.building_location_choice_model import BuildingLocationChoiceModel as UrbansimBuildingLocationChoiceModel from numpy import where, arange, zeros from numpy import logical_or, logical_not from opus_core.variables.variable_name import VariableName from opus_core.resources import Resources from opus_co...
from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("issuetracker", "0004_data_migration_set_bugzilla_to_allow_add_case_to_issue"), ] operations = [ migrations.RemoveField( model_name="issuetracker", name="issue_report_fmt...
import numpy as np def mean_intensity_norm(patch): mu = np(np.sum(patch))*1.0/(patch.shape[0]*shape[1]) return (patch - mu[np.newaxis,np.newaxis])
import logging import tempfile from uuid import UUID from time import time, localtime, altzone from dionaea import ndrlib from dionaea.core import g_dionaea, incident from .include.smbfields import DCERPC_Header, DCERPC_Response rpclog = logging.getLogger('rpcservices') OS_TYPE = 2 class DCERPCValueError(Exception): ...
"""This module contains a object that represents a Telegram Message Parse Modes.""" class ParseMode(object): """This object represents a Telegram Message Parse Modes.""" MARKDOWN = 'Markdown' HTML = 'HTML'
import math import ige.ospace.Const as Const from ige.IDataHolder import makeIDataHolder from Techs import noop as techDefaultHandler def init(configDir): global techs, Tech import Techs Techs.init(configDir) from Techs import techs, Tech turnsPerDay = 24 galaxyStartDelay = turnsPerDay * 2 playerTimeout...
import os from django.contrib.auth.models import User from tastypie.resources import ModelResource, ALL, ALL_WITH_RELATIONS from tastypie.fields import ListField, ForeignKey from tastypie.authentication import BasicAuthentication, ApiKeyAuthentication, SessionAuthentication, MultiAuthentication from pcapoptikon.authori...
from libraries import JSONDictionary holdingsData = { 'defense': { 'superiorCastle': 50, 'castle': 40, 'smallCastle': 30, 'hall': 20, 'tower': 10 }, 'influence': { 'firstBorn': 20, 'secondBorn': 10, 'otherChildren': 5 }, 'lands': { ...
""" Created on Mon Oct 3 02:10:23 2011 @author: IxxI @version: v1.0 """ import sys import logging from optparse import OptionParser from commands import Commands, CLIENT, SERVER from mcp import getchangedsrc_side def main(): parser = OptionParser(version='MCP %s' % Commands.fullversion()) parser.add_option('--...
from distutils.core import setup, Extension from distutils.util import get_platform import shutil import os, sys def buil_all(): packages=['miasm2', 'miasm2/arch', 'miasm2/arch/x86', 'miasm2/arch/arm', 'miasm2/arch/aarch64', 'miasm2/arch/msp430',...
from __future__ import with_statement from __future__ import division import pyejdb import os.path from datetime import datetime from datetime import timedelta from datetime import date as pydate import json import sys reload(sys) sys.setdefaultencoding("utf-8") def note_date_str(): d = timedelta(hours = 7) td ...
import logging as _logging import sys __author__ = 'luckydonald' __all__ = ["logging", "ColoredFormatter", "ColoredStreamHandler", "LevelByNameFilter"] DEFAULT_DATE_FORMAT = "%Y-%m-%d %H:%M:%S" class ColoredFormatter(_logging.Formatter): class Color(object): """ utility to return ansi colored text....
from cms.models.pluginmodel import CMSPlugin from cms.plugin_base import CMSPluginBase from cms.plugin_pool import plugin_pool from django.utils.translation import gettext_lazy as _ from django.utils.translation import get_language from partners.models import Partner class PartnersPlugin(CMSPluginBase): name = _("P...
"""generic dialogs such as progress, error and about""" import gettext import os import gobject import gtk from flumotion.configure import configure from flumotion.common.errors import AlreadyConnectedError, \ AlreadyConnectingError, ConnectionFailedError, \ ConnectionRefusedError __version__ = "$Rev: 7833 $"...
from yali.storage import StorageError class LibraryError(StorageError): pass
import logging import logging.handlers import os import re import serial import sys from c1218.connection import Connection from c1218.errors import C1218IOError, C1218ReadTableError from framework.errors import FrameworkConfigurationError, FrameworkRuntimeError from framework.options import AdvancedOptions, Options fr...
import sys import argparse import anvio.db as db import anvio.utils as utils import anvio.terminal as terminal from anvio.errors import ConfigError run = terminal.Run() progress = terminal.Progress() current_version, next_version = [x[1:] for x in __name__.split('_to_')] def migrate(db_path): if db_path is None: ...
from base64 import b64encode from collections import namedtuple from socket import error as SocketError from hashlib import md5, sha1 from binascii import hexlify, unhexlify try: from select import poll, POLLIN except ImportError: # `poll` doesn't exist on OSX and other platforms poll = False try: ...
import unittest import tagfs.freebase_support as freebase_support class WhenQueryWithOneFilerAndOneSelector(unittest.TestCase): def setUp(self): super(WhenQueryWithOneFilerAndOneSelector, self).setUp() self.query = freebase_support.Query({'filter': 'filterValue', 'selector': None, }) def testThe...
import re from six import string_types __all__ = ['resolve'] def resolve(code): """ Transform the given (2- or 3-letter) language code to a human readable language name. The return value is a 2-tuple containing the given language code and the language name. If the language code cannot be resolved,...
import os import sys import socket import select import base64 import binascii import re import ConfigParser import traceback HOST = 'localhost' PORT = 9100 try: import json except: print "[-] failed to import json\n%s" % repr(sys.exc_info()) sys.exit(0) class Client(): def __init__(self, s_client, s_sr...
from __future__ import unicode_literals from django.db import migrations, models import jsonfield.fields import django.utils.timezone from django.conf import settings class Migration(migrations.Migration): dependencies = [ ("contenttypes", "0002_remove_content_type_name"), migrations.swappable_depen...
from django.conf.urls.defaults import patterns, url js_info_dict = { 'packages': ('geonode.maps',), } urlpatterns = patterns('geonode.maps.views', url(r'^$', 'map_list', name='maps_browse'), url(r'^tag/(?P<slug>[-\w]+?)/$', 'maps_tag', name='maps_browse_tag'), url(r'^new$', 'new_map', name="new_map"), ...
import operator, sys, time, gzip, re def string_find(usage_term): for idx, elem in enumerate(sys.argv): this_elem = elem next_elem = sys.argv[(idx + 1) % len(sys.argv)] if elem == usage_term: return next_elem if "-I" in sys.argv: infile_name = string_find("-I") else: sys.exit ("WARNING: infile must be spec...
import wx from timelinelib.db.utils import safe_locking from timelinelib.repositories.dbwrapper import DbWrapperEventRepository from timelinelib.wxgui.dialogs.editcontainer.view import EditContainerDialog from timelinelib.wxgui.dialogs.editevent.controller import EditEventDialogController from timelinelib.wxgui.framewo...
""" :synopsis: user-centric views for askbot This module includes all views that are specific to a given user - his or her profile, and other views showing profile-related information. Also this module includes the view listing all forum users. """ import calendar import collections import functools import datetime imp...
""" File Operations """ from __future__ import with_statement import os import io import shutil import hashlib import zlib import base64 import tempfile import time import struct import sympy import mpmath import math from mathics.core.expression import (Expression, Real, Complex, String, Symbol, ...
import os from django.conf import settings from django.contrib import admin from django import forms from django.db import models from cyclope import settings as cyc_settings from cyclope.core.collections.admin import CollectibleAdmin from cyclope.admin import BaseContentAdmin from models import * from filebrowser.fiel...
""" Copyright (C) 2009,2014 Andreas Engelbredt Dalsgaard <andreas.dalsgaard@gmail.com> Martin Toft <mt@martintoft.dk> Mads Chr. Olesen <mchro@cs.aau.dk> 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 t...
""" Tests for management commands. """ from django.test import TestCase from weblate.trans.tests.test_models import RepoTestCase from weblate.trans.models import SubProject from django.core.management import call_command from django.core.management.base import CommandError import django if django.VERSION >= (1, 5): ...
from UnityTweakTool.section.skeletonpage import Section,Tab from UnityTweakTool.elements.fontbutton import FontButton from UnityTweakTool.elements.cbox import ComboBox from UnityTweakTool.elements.spin import SpinButton from UnityTweakTool.elements.radio import Radio from UnityTweakTool.elements.checkbox import CheckBo...
from requests import request, ConnectionError from social.utils import module_member, parse_qs from social.exceptions import AuthFailed class BaseAuth(object): """A django.contrib.auth backend that authenticates the user based on a authentication provider response""" name = '' # provider name, it's stored ...
"""BZFlag Constants These constants are originally defined in src/common/global.cxx in the BZFlag repository. There are more than a hundred BZFlag constants that are in global.cxx but are not included in the list of BSFlag constants. """ from __future__ import division # Must be at the beginning of the file! __author_...
import re import datetime ZERO = datetime.timedelta(0) try: from dateutil.parser import parse as parse_iso from dateutil.tz import tzoffset, tzutc except: # As a stopgap, define the two timezones here based # on the dateutil code. class tzutc(datetime.tzinfo): def utcoffset(self, dt): ...
import string class DefaultFormatter(string.Formatter): def __init__(self, default=''): self.default = default def get_field(self, field_name, args, kwargs): try: return super().get_field(field_name, args, kwargs) except (KeyError, AttributeError): return self.default def upperfirst(word): return word[0]...
from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('experiment', '0004_auto_20150727_1405'), ] operations = [ migrations.AlterField( model_name='customerexperiment', name='experimen...
"""Provides some useful utilities for the Discord bot, mostly to do with cleaning.""" import re import discord __all__ = ['clean', 'is_clean'] mass_mention = re.compile('@(everyone|here)') member_mention = re.compile(r'<@\!?(\d+)>') role_mention = re.compile(r'<@&(\d+)>') channel_mention = re.compile(r'<#(\d+)>') def c...
from setuptools import setup, find_packages from bang import VERSION import os.path ETC = os.path.join(os.path.dirname(__file__), 'etc') with open(os.path.join(ETC, 'requirements.pip')) as f: reqs = [l.strip() for l in f if '://' not in l] reqs.append('distribute') setup( name='bang', version=VERSIO...
import pytest from chandere.errors import ChandereError from chandere.loader import load_scraper scraper = load_scraper("8chan") VALID_CROSSLINK_TARGETS = [ ("/tech/589254", ("tech", "589254")), ("/tech/ 589254", ("tech", "589254")), ("tech/589254", ("tech", "589254")), ("/tech 589254", ("tech", "589254...
import e3 import gui import extension import PyQt4.QtGui as QtGui import PyQt4.QtCore as QtCore class StatusButton(QtGui.QToolButton): '''a button that when clicked displays a popup that allows the user to select a status''' NAME = 'Status Button' DESCRIPTION = 'A button to select the status' AUTHOR...
import sys from ocelot.adaptors.genesis import * from ocelot.cpbd.elements import Element, Quadrupole, RBend, Drift, Undulator from ocelot import MagneticLattice from ocelot.cpbd.beam import Beam from ocelot.cpbd.optics import * import numpy.fft as fft from sim_info import SimInfo, RunInfo import argparse h = 4.1356675...
import random from io import StringIO from gi.repository import Gtk from pychess.compat import create_task from pychess.System.prefix import addDataPrefix from pychess.Utils.const import WHITE, BLACK, LOCAL, NORMALCHESS, ARTIFICIAL, chr2Sign, chrU2Sign, FAN_PIECES, HINT, ENDGAME from pychess.Utils.LearnModel import Lea...
import re import sys if len(sys.argv) != 2: print "usage: ./%s PATH/TO/OBJDIR" % sys.argv[0] objdir_path = sys.argv[1] def line_to_atom(line): result = re.match('^GK_ATOM\((.+),\s*"(.*)"\)', line) return (result.group(1), result.group(2)) def symbolify(ident): return "_ZN9nsGkAtoms" + str(len(ident)) + ...
import sys import logging import re from threading import Event from copy import copy from PyQt4.QtCore import QTimer, SIGNAL, QObject, QString, QSize, QVariant, QMutex, Qt from PyQt4.QtGui import QMainWindow, QApplication, QStyledItemDelegate, \ QStyleOptionViewItemV4, QTextDocument, QStyle, \ ...
import json import logging import sys from intelmq.lib.bot import Bot from intelmq.lib.message import Report from sdk.blueliv_api import BluelivAPI class BluelivCrimeserverCollectorBot(Bot): def process(self): self.logger.info("Downloading report through API") http_proxy = getattr(self.parameters, '...
""" Global anchor for the website's urls """ from django.urls import path from django.conf.urls import include, url from django.conf.urls.static import static from django.conf import settings from django.contrib import admin from django.views.generic import TemplateView as Tv from apps.versioner.views import Version ur...
from testtools import TestCase from testtools.matchers import Equals, MatchesException, Raises from testtools.content_type import ( ContentType, JSON, UTF8_TEXT, ) class TestContentType(TestCase): def test___init___None_errors(self): raises_value_error = Raises(MatchesException(ValueError)) ...
import pkg_resources from datetime import datetime import re from inbox.api.validation import ( get_recipients, get_attachments, get_thread, get_message) from inbox.api.err import InputError from inbox.contacts.process_mail import update_contacts_from_message from inbox.models import Message, Part from inbox.models...
PEOPLE = [] def main(): """ devo far inserire name, city, salary come input e salvarli nel dizionario # 1.finche utente non smette. # 2.l'utente inserisce il nome usa raw_input per chiedere le info all'utente # 3.l'utente inserisce la città # 4.l'utente inserisce lo stipendio # 5.inserisci i...
""" API for initiating and tracking requests for credit from a provider. """ from __future__ import absolute_import import datetime import logging import uuid import pytz import six from django.db import transaction from edx_proctoring.api import get_last_exam_completion_date from openedx.core.djangoapps.credit.excepti...
''' Created on August 19, 2013 @package: livedesk-sync @copyright: 2013 Sourcefabric o.p.s. @license: http://www.gnu.org/licenses/gpl-3.0.txt @author: Martin Saturka Content for icons of collaborators of chained blogs. ''' import socket import logging from urllib.request import urlopen from ally.api.model import Conten...
__author__ = "Daniel Arroyo <daniel@astroprint.com>" __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' import logging from astroprint.network import NetworkManager as NetworkManagerBase class MacDevNetworkManager(NetworkManagerBase): def __init__(self): self.name = "ast...
import os import functools import logging import six from pelican.utils import (slugify, python_2_unicode_compatible) logger = logging.getLogger(__name__) @python_2_unicode_compatible @functools.total_ordering class URLWrapper(object): def __init__(self, name, settings): # next 2 lines are redundant with th...
"""Automatically download MLdata datasets.""" import os from os.path import join, exists import re import numpy as np import scipy as sp from scipy import io from shutil import copyfileobj import urllib2 from .base import get_data_home, Bunch MLDATA_BASE_URL = "http://mldata.org/repository/data/download/matlab/%s" def ...
import json import unittest import os import threading import time import psutil import requests from tempdir import TempDir from mock import patch from pixelated.client.dispatcher_api_client import PixelatedDispatcherClient from pixelated.proxy import DispatcherProxy from pixelated.manager import DispatcherManager, SS...
from unittest.mock import patch from superdesk.tests import TestCase from apps.publish.enqueue.enqueue_service import EnqueueService class NoTakesEnqueueTestCase(TestCase): def setUp(self): super().setUp() self.product_ids = self.app.data.insert( "products", [ ...
import re from django import forms from django.contrib.auth.models import User from django.forms import formset_factory from django.forms.widgets import TextInput from django.utils import timezone from dal import autocomplete from tagging.fields import TagField import accounts.utils from bulb.models import Book, Needed...
from pypixel import * show() h = 0 while True: x = random(WIDTH) y = random(HEIGHT) r = random(50, 100) h += 1 h %= 360 s = 100 v = 100 c = hsv2rgb((h, s, v)) circle(c, (x, y), r) update()
"""Check if SOCKS5 relays are disabled in muc""" import os if os.name != 'posix': # skipped on non-Unix for now, because it uses a Unix socket raise SystemExit(77) import dbus from servicetest import call_async, EventPattern, EventProtocolClientFactory from gabbletest import acknowledge_iq, make_muc_presence, e...
import platform as py_platform from spack.architecture import OperatingSystem from spack.version import Version from spack.util.executable import Executable def macos_version(): """temporary workaround to return a macOS version as a Version object """ return Version(py_platform.mac_ver()[0]) def macos_sdk_p...
import vtktools import sys import math import re import matplotlib.pyplot as plt import getopt from scipy.special import erf from numpy import poly1d from matplotlib.pyplot import figure, show from numpy import pi, sin, linspace from matplotlib.mlab import stineman_interp from numpy import exp, cos from fluidity_tools ...
from spack import * class Libgcrypt(AutotoolsPackage): """Cryptographic library based on the code from GnuPG.""" homepage = "https://gnupg.org/software/libgcrypt/index.html" url = "https://gnupg.org/ftp/gcrypt/libgcrypt/libgcrypt-1.8.5.tar.bz2" maintainers = ['alalazo'] version('1.9.4', sha256=...
import jtutil import jtsocket import jtdom def jtexec(cmd): jtsocket.send("<jtexec>"+jtutil.cdataif(cmd)+"</jtexec>") # <exitvalue>value</exitvalue> # vagy # <execerror>error</execerror> while 1: rsp=jtsocket.recv() if rsp==None: return None dom=jtdom.domparse(rs...
"""C++ templates for the .hh file""" header = """\ // This file is generated by @program@- @library@. Do not edit. """ footer = """\ """ main = """\ @sub_include_pre@ @cxx_direct_include@ @includes@ @sub_include_post@ @forward_declarations@ @string_tcParser_declarations@ @defs@ @poa@ @obv@ @other_tie@ @operators@ @mars...
import ROOT import os ROOT.ROOT.EnableImplicitMT() higgs_header_path = os.path.join(os.sep, str(ROOT.gROOT.GetTutorialDir()) + os.sep, "dataframe" + os.sep, "df103_NanoAODHiggsAnalysis_python.h") ROOT.gInterpreter.Declare('#include "{}"'.format(higgs_header_path)) def reco_higgs_to_2el2...
import gettext import __builtin__ import math __builtin__._ = gettext.gettext from shadowcraft.core import exceptions from shadowcraft.calcs import armor_mitigation from shadowcraft.objects import class_data from shadowcraft.objects import talents from shadowcraft.objects import procs from shadowcraft.objects.procs imp...
from PySide import QtCore, QtGui class Ui_Form(object): def setupUi(self, Form): Form.setObjectName("Form") Form.resize(236, 179) self.verticalLayout = QtGui.QVBoxLayout(Form) self.verticalLayout.setObjectName("verticalLayout") self.horizontalLayout = QtGui.QHBoxLayout() ...
""" Implementaiton of a population for maintaining a GA population and proposing structures to pair. """ from random import randrange, random from math import tanh, sqrt, exp from operator import itemgetter import numpy as np from ase.db.core import now def count_looks_like(a, all_cand, comp): """Utility method for...
"""This module provides graph theory functionality.""" from heapq import heapify, heappop, heappush def dijkstra(nodes, edges, startNode, directed): """Finds the length between each node in the graph and the startNode. Arguments: nodes - the set of nodes in the graph. edges - the set of edges in...
"""Utilities for testing `LinearOperator` and sub-classes.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import abc import itertools import numpy as np import six from tensorflow.python.eager import backprop from tensorflow.python.eager import context fr...
from unittest import mock from watcher.common import clients from watcher.common import utils from watcher.decision_engine.strategy import strategies from watcher.tests.decision_engine.strategy.strategies.test_base \ import TestBaseStrategy class TestSavingEnergy(TestBaseStrategy): def setUp(self): supe...
''' General functions for running the unit tests via pytest. ''' import itertools import numpy as np import pytest from neon.backends import gen_backend def pytest_addoption(parser): ''' Add a --all option to run the full range of parameters for tests generated using the pytest test generators ''' ...
import sys import optparse import vdj parser = optparse.OptionParser() (options, args) = parser.parse_args() if len(args) == 2: inhandle = open(args[0],'r') outhandle = open(args[1],'w') elif len(args) == 1: inhandle = open(args[0],'r') outhandle = sys.stdout elif len(args) == 0: inhandle = sys.stdi...
from __future__ import unicode_literals from datetime import datetime import json import boto.cloudformation from moto.core import BaseBackend from .parsing import ResourceMap, OutputMap from .utils import generate_stack_id from .exceptions import ValidationError class FakeStack(object): def __init__(self, stack_id...
from flask import Flask from flask import make_response from flask import request from flask import render_template from flask import redirect from flask import url_for import logging from logging.handlers import RotatingFileHandler app = Flask(__name__) @app.route('/') def index(): app.logger.info('index') use...
__author__ = 'Arunkumar Eli' __email__ = "elrarun@gmail.com" from selenium.webdriver.common.by import By class DigitalOceanLocators(object): ACCESS_KEY_INPUT = (By.ID, 'accessKey') SECRET_KEY_INPUT = (By.ID, 'secretKey') NEXT_BTN = (By.CSS_SELECTOR, "button.btn.btn-primary") AVAILABILITY_ZONE = (By.XPAT...
import argparse import json import os import shutil from .model import train_and_evaluate if __name__ == "__main__": parser = argparse.ArgumentParser() # File arguments parser.add_argument( "--train_file_pattern", help="GCS location to read training data.", required=True ) parser.add_argumen...
import sys import pickle xid_name=sys.argv[1] data_path=sys.argv[2] xid=pickle.load(open(xid_name)) #xid_train.p or xid_test.p newc=pickle.load(open('newc.p')) cmd2g={} for i in newc: for j in newc: cmd2g[(i,j)]=0 print newc for c,f in enumerate(xid):#(files[len(files)/10*a1:len(files)/10*a2]): count={}...
from django import forms from .widgets import MarkdownxWidget class MarkdownxFormField(forms.CharField): """ Used in FormFields as a Markdown enabled replacement for ``CharField``. """ def __init__(self, *args, **kwargs): """ Arguments are similar to Django's default ``CharField``. ...
import abc import base64 import contextlib import functools import os import shutil from oslo_config import cfg from oslo_log import log as logging from oslo_serialization import jsonutils from oslo_utils import excutils from oslo_utils import fileutils from oslo_utils import strutils from oslo_utils import units impor...