content
stringlengths
4
20k
"""Tests for parsing tracks using MbXmlParser.""" import unittest from musicbrainz2.wsxml import MbXmlParser, ParseError from musicbrainz2.model import NS_MMD_1, NS_REL_1, Relation import StringIO import os.path VALID_DATA_DIR = os.path.join('test-data', 'valid') INVALID_DATA_DIR = os.path.join('test-data', 'invalid')...
from django.contrib import admin from panoptes.core.models import * from panoptes.core.forms import ReportedApplicationForm class LayoutCellInline(admin.TabularInline): model = LayoutCell class MACAddressInline(admin.TabularInline): model = MACAddress class ApplicationAdmin(admin.ModelAdmin): list_display = (...
from rest_framework import serializers from rest_framework.relations import PrimaryKeyRelatedField from olympia.reviews.models import Review from olympia.users.serializers import BaseUserSerializer from olympia.versions.models import Version class BaseReviewSerializer(serializers.ModelSerializer): # title and bo...
"""Test event catalog.""" import random from unittest.mock import ANY, sentinel from testtools import ExpectedException from testtools.matchers import AllMatch, Equals, HasLength, Is, IsInstance from twisted.internet.defer import fail, inlineCallbacks, succeed from maastesting.factory import factory from maastestin...
"""BlocksWorld domain, stacking of blocks to form a tower.""" from .Domain import Domain from rlpy.Tools import id2vec, vec2id, findElemArray1D from rlpy.Tools import nchoosek, factorial, findElemArray2D, plt, FONTSIZE import numpy as np __copyright__ = "Copyright 2013, RLPy http://acl.mit.edu/RLPy" __credits__ = ["A...
#!/usr/bin/env python """ crate_anon/crateweb/consent/teamlookup_rio.py =============================================================================== Copyright (C) 2015-2021 Rudolf Cardinal (<EMAIL>). This file is part of CRATE. CRATE is free software: you can redistribute it and/or modify it und...
"""Tests for `tf.data.experimental.prefetch_to_device()`.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from absl.testing import parameterized from tensorflow.core.protobuf import config_pb2 from tensorflow.python.data.experimental.ops import prefetchi...
import operator import re from functools import partial, reduce # Reduce any iterable to a single value using a logical OR e.g. (a | b | ...) OR = partial(reduce, operator.or_) # Reduce any iterable to a single value using a logical AND e.g. (a & b & ...) AND = partial(reduce, operator.and_) # Reduce any iterable to a...
#!/usr/bin/python # -*- coding: utf-8 -*- __author__ = 'ar' import json import keras import skimage.io as skio import matplotlib.pyplot as plt from keras.utils.visualize_util import plot as kplot from core01_network_parser import DLSDesignerFlowsParserV2 import app.backend.core.utils as dlsutils from app.backend.cor...
import hashlib import json import os import random import shutil import subprocess import tempfile from pathlib import Path import logging import requests import redis from redis_lock import Lock graph_cache = {} logger = logging.getLogger(__name__) class BaseModel: def __init__(self, model_dir=None): ...
from __future__ import print_function import json import time import unittest from copy import deepcopy from pprint import pprint from test_helper import ApiTestCase, unique_tsigkey_name, is_auth, is_auth_lmdb, is_recursor, get_db_tsigkeys class AuthTSIGHelperMixin(object): def create_tsig_key(self, name=None, alg...
import enum import functools import os import os.path from dataclasses import dataclass from locale import strxfrm from pathlib import Path from typing import Iterable __all__ = [ 'FileAttributes', 'PathCompletionEntry', 'PathCompletion', 'PathCompletionProvider', 'FileSystemPathCompletionProvider', ] cl...
#!/usr/bin/env python ''' Proxy Manager developed by Marios Kourtesis <<EMAIL>> Description: This module provides functions for proxy managment. ''' import tornado.curl_httpclient from tornado.httpclient import HTTPRequest import os from tornado.ioloop import IOLoop from tornado import gen from framework.dependency_ma...
from msrest.serialization import Model class MetricsResultInfo(Model): """A metric result data. :param additional_properties: Unmatched properties from the message are deserialized this collection :type additional_properties: dict[str, object] :param start: Start time of the metric. :type st...
from Tkinter import Canvas, Frame, Tk, CHORD, NSEW from time import time from ..base import World, Blue, Yellow #from ..interface.updater import SimVisionUpdater from ..interface import SimulationInterface #from ..core.skills import goto #from ..core.skills import gotoavoid #from ..core.skills import drivetoobject #fr...
import logging from chronicler.log import Log class Process(object): def __init__(self, properties): self.name = properties["name"] if 'pid' not in properties: properties['pid'] = None self.pid = properties["pid"] self.logs = {} for log in properties["logs"]: self.logs[Log.get_id(log...
""" API --- """ __all__ = ['IndexBuffer'] # python from ctypes import * from enum import * # wicked from .dll import * from .error import * from .lib.gl import * from .result import * # localize relevant dll functions wkd_set_index_buffer_destroy_callback = ( dll.wkd_set_index_buffer_destroy_callback ) wkd_i...
import gobject import goocanvas import cairo import gcompris import gcompris.skin import gcompris.bonus import gcompris.utils import gcompris.sound import gtk import gtk.gdk import random import math from gcompris import gcompris_gettext as _ # ---------------------------------------- # class Gcompris_followline: "...
# code for extracting the feature matrix of second last or any layer on a pretrained deep neural network on keras #For installation follow 2 websites : # 1. http://www.pyimagesearch.com/2016/08/10/imagenet-classification-with-python-and-keras/ # 2. https://github.com/fchollet/deep-learning-models (code comes from her...
from __future__ import absolute_import from __future__ import unicode_literals from .email import EmailMatcher from .email_name import EmailNameMatcher SORTINGHAT_IDENTITIES_MATCHERS = { 'default' : EmailMatcher, 'email' : EmailMatcher, ...
"""Tests for tags of the ``cmsplugin_blog_categories``` application.""" from django.test import TestCase from cmsplugin_blog_categories.templatetags import ( cmsplugin_blog_categories_tags as tags, ) from cmsplugin_blog_categories.tests.factories import ( CategoryFactory, EntryFactory, EntryCategoryFac...
import copy #******************************************************************** # ENTITY EDIT FORM #******************************************************************** class EntityEditFormBase(Form): '''Base entity Form class''' @IN.register('Entity', type = 'EntityEditForm') class EntityEditForm(EntityEdi...
from vsd_common import * @vsdcli.command(name='user-list') @click.option('--enterprise-id', metavar='<id>') @click.option('--group-id', metavar='<id>') @click.option('--filter', metavar='<filter>', help='Filter for firstName, lastName, userName, email, ' 'lastUpdatedDate, creationDate...
""" Construcción del diagrama de Hertszprung-Russell (HR) XHIP: An Extended Hipparcos Compilation Anderson E., Francis C. <Astron. Letters 38 (2012)> http://cdsads.u-strasbg.fr/abs/2012AstL...38..331A """ import numpy as np import matplotlib.pyplot as plt from astropy.table import Table from astroquery.viz...
# pylint: disable=missing-docstring from __future__ import absolute_import from functools import reduce from operator import add from django.conf.urls import url, include from django.contrib import admin from django.conf import settings from django.conf.urls.static import static from django.views.generic.base import ...
# coding:utf-8 import timeit ''' 6-Percorrendo_lists_e_dicts ''' ''' Lists ''' print '==== LISTS ====' my_list = [2, 4, 8, 16, 32, 64] for my_iterator in my_list: print my_iterator # 2 4 8 16 32 64 print '\n' for my_iterator in reversed(my_list): # backwards print my_iterator # 64 32 16 8 4 2 print '\...
#!/usr/bin/env python # -*- coding: utf-8 -*- import htpc import cherrypy import json import logging import time import math from cherrypy.lib.auth2 import require, member_of from htpc.helpers import striphttp, sizeof import requests from requests.auth import HTTPDigestAuth class Qbittorrent(object): session = r...
from functools import update_wrapper from django.utils.decorators import classonlymethod from django.core.exceptions import ImproperlyConfigured class BaseEmail(object): """ Simple base class for all class-based emails. Implements the basic structure for constructing an email message and sending it, alo...
from PyQt5 import QtWidgets, uic, QtGui from PyQt5.QtCore import pyqtSignal, Qt import cv2 import pyqtgraph as pg import sys from pathlib import Path from skimage.filters import threshold_otsu import numpy as np import pandas as pd import threading from time import sleep from pkg_resources import resource_filename imp...
#!/usr/bin/env python # pylint: disable=missing-docstring,invalid-name from __future__ import print_function import sys from setuptools import setup, find_packages with open('README.rst') as file: long_description = file.read() config = { 'name' : 'django-s3-cache', 'version' : '1.4.3', 'packages' :...
""" A minor modification of default_syntax_viewer as used in the Czech National Corpus. The client-side part is linked from the default plug-in implementation (see conf bellow). Required config.xml/plugins entries (RelaxNG compact format): element syntax_viewer { element module { "ucnk_syntax_viewer" } elemen...
import csv import re def process_tweet(tweet): #Conver to lower case tweet = tweet.lower() #Convert https?://* to URL tweet = re.sub('((www\.[^\s]+)|(https?://[^\s]+))','URL',tweet) #Convert @username to AT_USER tweet = re.sub('@[^\s]+','AT_USER',tweet) #Remove additional white spaces ...
""" Guidelines for writing new hacking checks - Use only for Rally specific tests. OpenStack general tests should be submitted to the common 'hacking' module. - Pick numbers in the range N3xx. Find the current test with the highest allocated number and then pick the next value. - Keep the test method code in t...
# -*- coding: utf-8 -*- """Greedy coloring test suite. Run with nose: nosetests -v test_coloring.py """ __author__ = "\n".join(["Christian Olsson <<EMAIL>>", "Jan Aagaard Meier <<EMAIL>>", "Henrik Haugbølle <<EMAIL>>", "Jake VanderPlas <<EMAIL>>"...
import datetime from DateUtils import DateUtils class IncrementDate: def __init__(self, date, no, by): self.date=date self.by=by self.no=no self.dayOfMonth=date.day def increment(self): if(self.by == "d"): self.byDays(1*self.no) elif(self.by == "w"): self.byWeeks(1*self.no) ...
#!/usr/bin/env python """ autoconnect -- Triggers an automatic connection attempt. """ # # Copyright (C) 2007 - 2009 Adam Blackburn # Copyright (C) 2007 - 2009 Dan O'Reilly # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License Version 2...
''' Created on 06-04-2013 @author: jurek ''' from hra_core.special import ImportErrorMessage try: from PyQt4.QtCore import * # @UnusedWildImport from PyQt4.QtGui import * # @UnusedWildImport from hra_core.misc import Params from hra_gui.qt.utils.signals import ENABLEMEND_SIGNAL from hra_gui.qt.ut...
from rally.benchmark.scenarios import base from rally.benchmark import validation from rally.common import log as logging from rally import consts from rally.plugins.openstack.scenarios.sahara import utils LOG = logging.getLogger(__name__) class SaharaJob(utils.SaharaScenario): """Benchmark scenarios for Sahara ...
#!/usr/bin/env python3 import inspect def typecheck(func): anno = func.__annotations__ sig = inspect.signature(func) def typecheck_wrapper(*args, **kwargs): ba = sig.bind(*args, **kwargs) # TODO: see <https://docs.python.org/3/library/inspect.html> for proper # usage and iteration. for name, val...
from db.domain import DBActionAnnotation class ActionAnnotation(DBActionAnnotation): ########################################################################## # Constructors and copy def __init__(self, *args, **kwargs): DBActionAnnotation.__init__(self, *args, **kwargs) if self.id is Non...
import argparse import json import numpy as np import pandas as pd from nltk.corpus import stopwords from nltk.stem import PorterStemmer from scipy.signal import lfilter from sklearn.cluster import MiniBatchKMeans from sklearn.preprocessing import scale from sklearn.preprocessing import MultiLabelBinarizer from .util...
""" http://adventofcode.com/day/5 --- Day 5: Doesn't He Have Intern-Elves For This? --- Santa needs help figuring out which strings in his text file are naughty or nice. A nice string is one with all of the following properties: - It contains at least three vowels (aeiou only), like aei, xazegov, or aeiou...
import sublime, sublime_plugin from os import path gte_st3 = int(sublime.version()) >= 3000 if gte_st3: from .config import * else: from config import * class HiveOpenSwitcherCommand(sublime_plugin.WindowCommand): def run(self, **args): known_options = [ 'toggle_show_edit_item_option'...
from ..graph.node import Node class Environment(object): def __init__(self, envMap): self.envMap = envMap def isValidPoint(self, point): pass class GridEnvironment(Environment): def __init__(self, envMap, rows, cols): super(GridEnvironment, self).__init__(envMap) self.rows...
import logging import os from yaml import dump from twisted.internet.defer import inlineCallbacks, succeed, Deferred from juju.environment.environment import Environment from juju.charm.tests.test_repository import RepositoryTestBase from juju.state.machine import MachineStateManager, MachineState from juju.state.se...
#!/usr/bin/env python """ Run a build of the DB """ from __future__ import (print_function, absolute_import, division, unicode_literals) import os import pdb try: # Python 3 ustr = unicode except NameError: ustr = str def parser(options=None): import argparse # Parse parser = argparse.ArgumentPa...
import random import string import time import uuid import fixtures import six from sahara.service.edp import job_utils from sahara.tests.integration.tests import base from sahara.utils import edp class EDPJobInfo(object): PIG_PATH = 'etc/edp-examples/edp-pig/trim-spaces/' JAVA_PATH = 'etc/edp-examples/edp-...
#!/usr/bin/env python """ MQTT collector routine of MARCOS: MQTT protocol to be used in the Conrad Observatory. written by by Roman Leonhardt How should it work: PURPOSE: collector_mqtt.py subscribes to published data from MQTT clients. REQUIREMENTS: 1.) install a MQTT broker (e.g. ubuntu: sudo apt-get install mosq...
import os import spinalcordtoolbox.image as msct_image from spinalcordtoolbox.image import Image from spinalcordtoolbox import __sct_dir__ from spinalcordtoolbox.scripts import sct_apply_transfo def init(param_test): """ Initialize class: param_test """ default_args = [ '-i t2/t2.nii.gz -s t...
import unittest import cStringIO import httplib import time import os try: import autotest.common as common except ImportError: import common from autotest.mirror import source from autotest.client.shared.test_utils import mock class common_source(unittest.TestCase): """ Common support class for sou...
"""Models for the image_collection app.""" import re from django import forms from django.contrib.contenttypes.fields import GenericRelation from django.core.exceptions import ValidationError from django.core.validators import RegexValidator from django.db import models from django.utils.encoding import python_2_unicod...
#!/usr/bin/env python import sqlite3, os, string, hashlib from Crypto.Random import random ################################################### # # Default values for the config # ################################################### # Staging Key is set up via environmental variable # or via command line. By setting ...
#$ neutron_plugin 01 ELEMENT_FILE = 'static/elements.txt' TLD_FILE = 'static/tlds.txt' def fact_element(query): fp = open(ELEMENT_FILE, 'r') while 1: line = fp.readline() if not line: return 'Not Found' (key, value) = string.split(line, ' ', 1) if string.lower(query).strip() == string.lower(key).strip():...
import sys import os sys.path.append( os.path.join( os.getcwd(), '..' ) ) from libcocorun import Expr from libcocorun import Op plus = Op("+") minus = Op("-") divide = Op("/") times = Op("*") power = Op("**") mod = Op("%") sin = Op("math.sin") exp = Op("math.exp") log = Op("math.log") one = Op("1") two = Op("2") thre...
import numpy as np from mirdata.datasets import medleydb_pitch from mirdata import annotations from tests.test_utils import run_track_tests def test_track(): default_trackid = "AClassicEducation_NightOwl_STEM_08" data_home = "tests/resources/mir_datasets/medleydb_pitch" dataset = medleydb_pitch.Dataset(d...
import numpy as np from matplotlib import pyplot import spm1d #(0) Load data: np.random.seed(1) y0 = spm1d.data.uv1d.normality.NormalityAppendixDataset('A4').Y y1 = spm1d.data.uv1d.normality.NormalityAppendixDataset('A5').Y y2 = spm1d.data.uv1d.normality.NormalityAppendixDataset('A6').Y JJ ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Tests for the Safari history plist plugin.""" import unittest from plaso.parsers.plist_plugins import safari from tests.parsers.plist_plugins import test_lib class SafariPluginTest(test_lib.PlistPluginTestCase): """Tests for the Safari history plist plugin.""" ...
import ConfigParser def connector_get_conf_path(): import os path = os.getcwd() while len(path)>0: if os.path.exists(path+"/AFConnector.conf"): return path path=path[0:path.rfind("/")] def connector_import_package(name): import sys cf = ConfigParser.ConfigParser() cf.read(connector...
from nova.notifications.objects import base from nova.objects import base as nova_base from nova.objects import fields @nova_base.NovaObjectRegistry.register_notification class InstancePayload(base.NotificationPayloadBase): SCHEMA = { 'uuid': ('instance', 'uuid'), 'user_id': ('instance', 'user_id'...
from src.utility import HTTPClient, HmcHeaders, HMCClientLogger from src.generated_src import UOM import pyxb import os import time import xml.etree.ElementTree as etree from src.common.JobStatus import * log = HMCClientLogger.HMCClientLogger(__name__) ROOT = "Cluster" CONTENT_TYPE = "application/vnd.ibm.powervm.web+x...
def init(): print("langoids initialized.") class Production: def __init__(self, name, list_of_langoids): from Skoarcery.terminals import Empty self.name = name self.production = list_of_langoids self.derives_empty = self.first == Empty def __str__(self): s = self...
# -*- coding:utf-8 -*- import sys from flask_wtf import Form from wtforms import StringField, PasswordField, SubmitField, IntegerField, SelectField, TextAreaField, DateField, \ HiddenField from wtforms.validators import DataRequired, StopValidation from models import User, Project, Application, Need import datetim...
#!/usr/bin/env python import json import unittest import numpy as np from math import pi import sys sys.path.insert(0,'../') from pyfaunus import * # Dictionary defining input d = {} d['geometry'] = { 'type': 'cuboid', 'length': 50 } d['atomlist'] = [ { 'Na': dict( r=2.0, eps=0.05, q=1.0, tfe=1.0 ) }, ...
# -*- coding: utf-8 -*- { 'name': "optibiz", 'summary': """ Short (1 phrase/line) summary of the module's purpose, used as subtitle on modules listing or apps.openerp.com""", 'description': """ Long description of module's purpose """, 'author': "Optibiz India", 'websi...
# -*- coding: utf-8 -*- """ /*************************************************************************** StyleManager A QGIS plugin Allows to conveniently save and load styles for multiple layers ------------------- begin : 2016-08-1...
#!/usr/bin/env python3 """ This script was created after doing RNA-Seq assemblies for the Aplysia project, in which we had many reference transcripts generated by other means that we attempted to query within the assembled transcript set, with varying levels of success. There were many instances where the transcript...
# -*- coding: utf-8 -*- """ ZUGBRUECKE Calling routines in Windows DLLs from Python scripts running on unixlike systems https://github.com/pleiszenburg/zugbruecke tests/test_fibonacci_sequence.py: Test allocation of memory by DLL, returned as struct Required to run on platform / side: [UNIX, WINE] Copyright (C)...
"""cyme.api.web - Contains utilities for creating our HTTP API. """ from __future__ import absolute_import import httplib as http import sys from functools import partial from traceback import format_exception from django.http import HttpResponse, HttpResponseNotFound from django.views.generic.base import View f...
from smewt.base.utils import tolist, toresult from smewt.base.textutils import u from smewt.base.subtitletask import SubtitleTask from smewt.plugins import mplayer from guessit.language import Language import smewt import os, sys, time import subprocess import logging log = logging.getLogger(__name__) def get_episod...
#!/usr/bin/python # coding: utf-8 import argparse as AP from game import Game def main(args): if args.file: [process(f) for f in args.file] def process(f): game = Game(f) print game.solve() if __name__ == "__main__": parser = AP.ArgumentParser(description="Hexagon tetris bot.") parser.a...
import os import shutil import time import logging from constants import DENY_DELIMITER, ENTRY_DELIMITER from loginattempt import AbusiveHosts from util import parse_host import plugin from purgecounter import PurgeCounter debug = logging.getLogger("denyfileutil").debug info = logging.getLogger("denyfileutil").info w...
# -*- coding: utf-8 -*- from south.utils import datetime_utils as datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Removing unique constraint on 'Hit', fields ['content_type', 'object_pk'] ...
#!/usr/bin/env python """ MAVProxy horizon indicator. """ from MAVProxy.modules.lib import multiproc import time class HorizonIndicator(): ''' A horizon indicator for MAVProxy. ''' def __init__(self,title='MAVProxy: Horizon Indicator'): self.title = title # Create Pipe to send attit...
import logging import random from collections import defaultdict from dateutil.relativedelta import relativedelta from ..mappings.wp_post_mapping import WPPostMapping from odoo import api, models, fields _logger = logging.getLogger(__name__) class AppHub(models.AbstractModel): """ This Class holds the logic...
import os import site import sys from cx_Freeze import setup, Executable ## Get the site-package folder, not everybody will install ## Python into C:\PythonXX site_dir = site.getsitepackages()[1] include_dll_path = os.path.join(site_dir, "gnome") ## Collect the list of missing dll when cx_freeze builds the app missi...
import sys import os, os.path import math as m import numpy as nu import csv import cPickle as pickle from galpy.util import plot from galpy.potential import MiyamotoNagaiPotential, HernquistPotential, NFWPotential, LogarithmicHaloPotential from galpy.orbit import Orbit _degtorad= nu.pi/180. def calc_es(): savefile...
from setuptools import setup, find_packages from codecs import open from os import path VERSION = '0.0.1' here = path.abspath(path.dirname(__file__)) # Get the long description from the README file with open(path.join(here, 'README.md'), encoding='utf-8') as f: long_description = f.read() # get the dependencies...
import numpy as np import pandas as pd from dateutil.parser import parse from .read_from_serial import read_microtops_serial from matplotlib.pyplot import xlabel, ylabel, legend class Microtops: """Loads and processes a data file from the Microtops handheld sun photometer. Allows easy plotting, and estimation...
#!/usr/bin/env python # encoding: utf-8 import sys import re import os import zipfile THEME_FILE_EXTENSIONS = ('.stx', '.bmp', '.fcc') def buildTheme(themeName): if not os.path.isdir(themeName) or not os.path.isfile(os.path.join(themeName, "THEMERC")): print ("Invalid theme name: " + themeName) return zf = zip...
from supybot.test import * class SurveyTestCase(PluginTestCase): plugins = ('Survey',) # vim:set shiftwidth=4 tabstop=4 expandtab textwidth=79:
import importlib import mock from . import WHATEVER # NOTE(willkg): We do this so that we can extract signature generation into its # own namespace as an external library. This allows the tests to run if it's in # "siggen" or "socorro.signature". base_module = '.'.join(__name__.split('.')[:-2]) generator = importlib...
# -*- coding: utf-8 -*- """ Credits to ojii, functions get_module and load are from: https://github.com/ojii/django-load. Thanks for the technique! """ from __future__ import print_function from __future__ import absolute_import from __future__ import unicode_literals from django.conf import settings from django.utils...
import Algorithmia import base64 input = <somefile.jpg> request = urllib2.Request('https://api.algorithmia.com/v1/algo/ANaimi/FaceDetection/0.1.0') request.add_header('Content-Type', 'application/json') request.add_header('Authorization', 'API_KEY') response = urllib2.urlopen(request, json.dumps(input)) print respons...
"""Recursive feature elimination for feature ranking""" import numpy as np from .base import SelectorMixin from ..base import BaseEstimator from ..base import MetaEstimatorMixin from ..base import clone from ..base import is_classifier from ..externals.joblib import Parallel, delayed from ..metrics.scorer import chec...
#!/usr/bin/env python # -*- coding: utf-8 -*- #É adimensional? adi = False #É para salvar as figuras(True|False)? save = True #Caso seja para salvar, qual é o formato desejado? formato = 'jpg' #Caso seja para salvar, qual é o diretório que devo salvar? dircg = 'fig-sen' #Caso seja para salvar, qual é o nome do arquivo...
from pyspark.ml.util import keyword_only from pyspark.ml.wrapper import JavaEstimator, JavaModel from pyspark.ml.param.shared import * from pyspark.mllib.common import inherit_doc __all__ = ['KMeans', 'KMeansModel'] class KMeansModel(JavaModel): """ Model fitted by KMeans. """ def clusterCenters(sel...
# -*- coding: utf-8 -*- # @date 161025 - Added MACHINE_STATUS """ Static data by key-value type for access (not in DB). """ from collections import defaultdict """ MACHINE_MAINTENANCE_MAP: machine_type_name: { maintenance_error_code: maintenance description } """ MACHINE_MAINTENANCE_MAP = { '加締...
import datetime from StringIO import StringIO import django from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.utils.encoding import force_unicode from django.core.serializers import json as djangojson from tastypie.bundle import Bundle from tastypie.exceptions import ...
import pecan import controller class ControllerResolver(object): """This class forwards HTTP request to controller class. This class creates an object of Controller class with appropriate parameter according to the path of HTTP request. According to the parameter passed to Controller class it sends ...
#Embedded file name: ACEStream\Core\DecentralizedTracking\pymdht\core\bencode.pyo import cStringIO import logging logger = logging.getLogger('dht') class LoggingException(Exception): def __init__(self, msg): logger.info('%s: %s' % (self.__class__, msg)) class EncodeError(LoggingException): pass cl...
"""Performance RNN model.""" import collections import functools import magenta from magenta.models.shared import events_rnn_model from magenta.music.performance_lib import PerformanceEvent import tensorflow as tf # State for constructing a time-varying control sequence. Keeps track of the # current event position a...
""" This module is used to estimate the cost of various compounds. Costs are taken from the a CostDB instance, for example a CSV file via CostDBCSV. For compounds with no cost listed, a Phase Diagram style convex hull optimization is performed to determine a set of compositions that can be mixed to give the desired com...
__author__ = 'Jason Vanzin' import sys #used to get commandline arguments import re #used for regular expressions hostname = 'mf.svc.nhl.com' ipaddress = '146.185.131.14' #5.79.106.110 mf.svc.nhl.com def exists(hostname): try: if 'darwin' in sys.platform: filename = '/private/etc/hosts' ...
#!/usr/bin/env python import re import sys import subprocess import os def generate(test): with open("tests/template.fmt") as file: template = file.read() lines = [] for line in re.split('(?<=[;{}])\n', test.read()): match = re.match('(?: *\n)*( *)(.*)=>(.*);', line, re.DOTALL | re.MULTIL...
from spack import * class PerlCaptureTiny(PerlPackage): """Capture STDOUT and STDERR from Perl, XS or external programs""" homepage = "http://search.cpan.org/~dagolden/Capture-Tiny-0.46/lib/Capture/Tiny.pm" url = "http://search.cpan.org/CPAN/authors/id/D/DA/DAGOLDEN/Capture-Tiny-0.46.tar.gz" ve...
import pytest from hypothesis import given from hypothesis.strategies import lists, integers, characters, composite, \ fixed_dictionaries, dictionaries, none from datatyping.printer import pformat @given(lst=lists(integers(), min_size=1)) def test_simple_ints(lst): assert pformat(lst) == '[int]' @given(lst...
''' Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value. Your algorithm's runtime complexity must be in the order of O(log n). If the target is not found in the array, return [-1, -1]. Example 1: Input: nums = [5,7,7,8,8,10], target = 8 Output: [3...
""" 36. Generating HTML forms from models Django provides shortcuts for creating Form objects from a model class and a model instance. The function django.newforms.form_for_model() takes a model class and returns a Form that is tied to the model. This Form works just like any other Form, with one additional method: s...
import unittest import tempfile import os from mantid.simpleapi import SaveHKLCW, CreateSampleWorkspace, CreatePeaksWorkspace, SetUB, DeleteWorkspace, SetGoniometer class SaveHKLCWTest(unittest.TestCase): def setUp(self): self._tmp_directory = tempfile.gettempdir() self._ws_name = 'SaveHKLCWTest' ...
from openerp import models, fields, api from addons.irsid_base import doc class edu_module_seance(models.Model): _name = 'edu.module.seance' _description = 'Module Seance' _order = 'module, sequence' # _track = { # 'state': { # 'irsid_edu.mt_module_seance_updated': lambda self, cr, ...