code
stringlengths
1
199k
from sys import version_info if version_info >= (2,6,0): def swig_import_helper(): from os.path import dirname import imp fp = None try: fp, pathname, description = imp.find_module('_fastdot', [dirname(__file__)]) except ImportError: import _fastdot ...
""" Python List with Synchronized access """ from threading import Lock class SList: def __init__(self): self.list = [] self.lock = Lock() def add(self, el): self.list.append(el) def remove(self, el): self.list.remove(el) def get_list(self): return self.list ...
"""Tests for missing-function-docstring and the no-docstring-rgx option""" class MyClass: pass class Child(MyClass): def __eq__(self, other): # [missing-function-docstring] return True
def greetz_work(jid='',greet='',gch=''): DBPATH='dynamic/'+gch+'/greetz.txt' if check_file(gch,'greetz.txt'): greetzdb = eval(read_file(DBPATH)) if jid and greet: if not jid in greetzdb.keys(): greetzdb[jid]=jid greetzdb[jid]=greet write_file(DBPATH, str(greetzdb)) return 1 else: greetzd...
''' Copyright (C) 2016 Giles Miclotte (giles.miclotte@ugent.be) This file is part of OMSim 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 2 of t...
import pygame white = (255,255,255) black = (0,0,0) green = (0,255,0) red = (255,0,0) size = (700,500) screen=pygame.display.set_mode(size) pygame.display.set_caption("Pacman Version 0.1 | Press ESC to quit") programOn = True gameWon = False clock = pygame.time.Clock() steps = 1 # ...
if f(): # [consider-ternary-expression] x = 4 else: x = 5 if g(): y = 3 elif h(): y = 4 else: y = 5 def a(): if i(): # [consider-ternary-expression] z = 4 else: z = 5
import PyQt4.QtCore as __PyQt4_QtCore import PyQt4.QtNetwork as __PyQt4_QtNetwork class KSocketFactory(): # skipped bases: <class 'sip.wrapper'> # no doc def connectToHost(self, *args, **kwargs): # real signature unknown pass def datagramSocket(self, *args, **kwargs): # real signature unknown ...
BzrRevisionNumber = 86
"""The main driver for the Lisp system.""" import sys import environment import formatter import interpreter import lexer import parser import pyfuncs def _execute_file(code_file, env, print_results=False): """Execute some lisp. Args: code_file: An iterator over lines of Lisp text. env: The base e...
#!/usr/bin/env python import sys import os import os.path import commands from datetime import timedelta from subprocess import Popen, PIPE, STDOUT from PyQt4.QtGui import * from PyQt4.QtCore import * app_name = "StreamCap" app_version = "0.1.3" app_author = "olivier Girard" author_email = "olivier@openshot.org" class...
class Solution(object): tsum = 0 def sumNumbers(self, root): """ :type root: TreeNode :rtype: int """ def dfs(root,s): if root==None: return if root.left==None and root.right==None: #print s+str(root.val) ...
""" Created on 18/3/15 1:11 PM @author: Naveen Subramani """ __author__ = 'Naveen Subramani' import logging from twisted.internet.defer import maybeDeferred, Deferred, DeferredList from Products.ZenEvents import ZenEventClasses from Products.ZenUtils.Executor import TwistedExecutor from ZenPacks.zenoss.PythonCollector....
""" This file is part of OpenSesame Toolbox OpenSesame Toolbox 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 option) any later version. OpenSesame Experiment Manager ...
import unittest from sequence_database import sequence_database class Test(unittest.TestCase): def test_fn2segment(self): fs = ['fastas/3.HAall.815seqsALGN.fas', 'fastas/3.MPall.815seqsALGN.fas', 'fastas/3.NAall.815seqsALGN.fas', 'fastas/3.NPall.815seqsALGN.fas', 'fastas/3.NSall.815seqsALGN.fas', 'fastas/3....
import sys, os, shutil, StringIO, tempfile, unittest, stat from duplicity import tarfile SAMPLETAR = "testtar.tar" TEMPDIR = tempfile.mktemp() def join(*args): return os.path.normpath(apply(os.path.join, args)) class BaseTest(unittest.TestCase): """Base test for tarfile. """ def setUp(self): o...
import os import sys import glob import optparse import tempfile import logging import shutil import ConfigParser class Fail(Exception): def __init__(self, test, msg): self.msg = msg self.test = test def getMsg(self): return '\'%s\' - %s' % (self.test.path, self.msg) class Unsup(Exceptio...
import os import check_index from mysql.utilities.exception import MUTLibError class test(check_index.test): """check parameters for the check_index utility This test executes the check index utility parameters on a single server. It uses the check_index test as a parent for setup and teardown methods. ...
import family __version__ = '$Id$' class Family(family.WikimediaFamily): def __init__(self): super(Family, self).__init__() self.name = 'wikipedia' self.languages_by_size = [ 'en', 'nl', 'de', 'fr', 'sv', 'it', 'es', 'ru', 'pl', 'ja', 'vi', 'pt', 'zh', 'war', 'ceb', '...
from multiprocessing import Process import numpy from bioseq7.code7 import line_regression_numpy as lr numpy.random.seed(0) grads = [-0.7, -2.7, -1.7] def generate_xy(grad_coeff): x = numpy.random.normal(0.0, 1.0, 100) y = 2.0 + grad_coeff * x + numpy.random.normal(0.0, 0.2, 100) return x, y def calc_lr(dat...
""" Tests functions from ante/card.py """ import pytest from ante.card import create_card, card_value, Card def test_valid_create_card(): """ Test if a card that should be created by create_card is created properly """ card = create_card('9C') assert type(card) is Card assert card.suit == 'C' ...
""" """ __author__ = 'liuyang' class Figure: def __init__(self): self.figureType = None def set_type(self, figureType): self.figureType = figureType def get_type(self): return self.figureType
""" generate_keyring command Assemble a GPG keyring with all known developer keys. Usage: ./manage.py generate_keyring <keyserver> <keyring_path> """ from django.core.management.base import BaseCommand, CommandError import logging import subprocess from devel.models import MasterKey, UserProfile logger = logging.getLog...
from pykickstart.base import KickstartCommand from pykickstart.errors import KickstartParseError, formatErrorMsg from pykickstart.options import KSOptionParser, commaSplit from pykickstart.i18n import _ class FC3_Bootloader(KickstartCommand): removedKeywords = KickstartCommand.removedKeywords removedAttrs = Kic...
"""QGIS Unit tests for QgsDelimitedTextProvider. .. note:: 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 2 of the License, or (at your option) any later version. """ __author__ = 'Chr...
import os, sys import Tkinter as tk import subprocess as sub RESOURCE_DIR = 'res' MIM_DIR = 'mim' FGCOLOR = '#FFFFFF' BGCOLOR = '#1F67B1' HIGHLIGHT_BGCOLOR = '#3E7BBC' TITLE_FONT = "Verdana 16" LABEL1_FONT = "Verdana 10 bold" LABEL2_FONT = "Verdana 7" MIM_OPTIONS = [ {'script': 'mim_live.py', 'text1': 'Live', ...
import json import argparse import sys import os class ComposedTemplate(object): def __init__(self, base_object=None, init_template_paths=None): """ :param base_object: :type base_object: dict :param init_template_paths: :type init_template_paths: list :return: None ...
__author__ = 'vkostov' try: from setuptools import setup except ImportError: from distutils.core import setup config = { 'description': 'AWS Product Advertising CLI', 'author': 'Vasil Kostov', 'version': '0.1', 'name': 'aws-prod' } setup(**config)
DISTUTILS_DEBUG="True" from glob import glob try: from setuptools import setup except ImportError: from distutils.core import setup config = {} config['classifiers'] = [ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'Intended Audience :: Science/Research', 'Licens...
from decimal import Decimal UNIDADES = ( '', 'UN ', 'DOS ', 'TRES ', 'CUATRO ', 'CINCO ', 'SEIS ', 'SIETE ', 'OCHO ', 'NUEVE ', 'DIEZ ', 'ONCE ', 'DOCE ', 'TRECE ', 'CATORCE ', 'QUINCE ', 'DIECISEIS ', 'DIECISIETE ', 'DIECIOCHO ', 'DIECINUE...
class check_configuration_default_trace_enabled(): """ check_configuration_default_trace_enabled: The default trace provides audit logging of database activity including account creations, privilege elevation and execution of DBCC commands. """ # References: # https://benchmarks.cisecurity.o...
""" Simple example that connects to the first Crazyflie found, ramps up/down the motors and disconnects. """ import logging import time from threading import Thread import cflib from cflib.crazyflie import Crazyflie from cflib.utils import uri_helper uri = uri_helper.uri_from_env(default='radio://0/80/2M/E7E7E7E7E7') l...
""" FILE: java.py AUTHOR: Cody Precord @summary: Lexer configuration file for Java source files. """ __author__ = "Cody Precord <cprecord@editra.org>" __svnid__ = "$Id: java.py 55174 2008-08-22 15:12:27Z CJP $" __revision__ = "$Revision: 55174 $" import synglob from cpp import AutoIndenter JAVA_KEYWORDS = (0, "import n...
from django.test import TestCase from ..models import l_event_series class test_l_event_series(TestCase): def setUp(self): """ Set up the test subject. """ self.subject = l_event_series() def test__l_event_series__instance(self): self.assertIsInstance(self.subject, l_even...
import io import re def main(): list_songName = [] list_youtube = [] for line in song_name_file: list_songName.append(line) for line in youtube_list_file: list_youtube.append(line) len_ = len(list_songName) j = 0 for x in xrange(0,len_): song = list_songName[x] ...
''' Created on 01.03.2013 @author: WorldCount Name: WC Utils Package '''
{ "name" : 'CCorp Project OpenERP Methodology', "version" : '1.0', "author" : 'CLEARCORP S.A.', 'complexity': 'normal', "description": """ """, "category": 'Project Management', "sequence": 10, "website" : "http://clearcorp.co.cr", "images" : [], "depends" : [ 'c...
from H3DInterface import * tex3d = createX3DNodeFromString( "<ImageTexture3D url='images/stone_wall.bmp' />" )[0] tex2d = createX3DNodeFromString( "<ImageTexture url='images/nautilus.jpg' />" )[0] flag = 0 class SwitchTexture( AutoUpdate(TypedField(SFNode, SFTime)) ): def update( self, event ): global flag ...
from twisted.python.compat import unicode def encode_if_needed(value): """ A small helper to decode unicode to utf-8 if needed. """ if isinstance(value, unicode): value = value.encode("utf-8") return value def encode_values(dictionary): """ Encode values of the given C{dictionary} wi...
import yaml, os, shutil, sys import langid print "ola",langid.langid.__class__.__name__ langid.langid.set_languages(["pt","es"]) print str(langid.langid)
''' PackageFile ''' import os.path import zipfile import tempfile import platform from Logger.ToolError import FILE_OPEN_FAILURE from Logger.ToolError import FILE_CHECKSUM_FAILURE from Logger.ToolError import FILE_NOT_FOUND from Logger.ToolError import FILE_DECOMPRESS_FAILURE from Logger.ToolError import FILE_UNKNOWN_E...
import json, os, inspect, re from operator import and_ from django.db.models.query import QuerySet, RawQuerySet from django.conf import settings from django.core import serializers from django.db.models import Q from django.forms import IntegerField from django.forms.models import model_to_dict from django.http import ...
import mdtraj as md import sys inpdb = sys.argv[1] outpdb = sys.argv[2] p = md.load(inpdb) for r in p.top.residues: if r.name =='HOH': r.atom(1).name = 'H1' r.atom(2).name = 'H2' for c in p.top.chains: for a in c.residue(0).atoms: if a.name == 'H': a.name = 'H1' for r in p.to...
class InvalidUsage(Exception): status_code = 400 def __init__(self, message, status_code=None, payload=None, details=None): Exception.__init__(self) self.message = message if status_code is not None: self.status_code = status_code self.payload = payload def to_dic...
__author__ = 'snake' import time from selenium.webdriver.common.keys import Keys from classes.asite import ASite class Logicimmo(ASite): def __init__(self, site): ASite.__init__(self, site, "FR") def browse(self, browser, credentials): #browser.get('http://www.logicimmo.com/') time.sleep...
import sys from asm_test import Asm_Test_16, Asm_Test_32 from miasm2.core.utils import pck16, pck32 def init_regs(test): test.myjit.cpu.EAX = 0x11111111 test.myjit.cpu.EBX = 0x22222222 test.myjit.cpu.ECX = 0x33333333 test.myjit.cpu.EDX = 0x44444444 test.myjit.cpu.ESI = 0x55555555 test.myjit.cpu....
import cgi import cgitb cgitb.enable() from shared.functionality.unpack import main from shared.cgiscriptstub import run_cgi_script run_cgi_script(main)
from timeside.core import implements, interfacedoc from timeside.core.analyzer import Analyzer, IAnalyzer from timeside.plugins.analyzer.utils import segmentFromValues from timeside.plugins.diadems.irit_diverg2 import IRITDiverg from numpy import mean, diff, arange class IRITMusicSLN(Analyzer): implements(IAnalyzer...
import cv2 file="/home/lucifer/videocam.webm" cam = cv2.VideoCapture(file) print "Video Properties:" print "\t Width: ",cam.get(cv2.cv.CV_CAP_PROP_FRAME_WIDTH) print "\t Height: ",cam.get(cv2.cv.CV_CAP_PROP_FRAME_HEIGHT) print "\t FourCC: ",cam.get(cv2.cv.CV_CAP_PROP_FOURCC) print "\t Framerate: ",cam.get(cv2.cv.CV_CAP...
import StringIO import ConfigParser import subprocess from collections import OrderedDict import re from CompLogger import comprehensive_logger as clog class MultiOrderedDict(OrderedDict): ''' A new type of dictionary that handles the concatenation of multiple entries when read from the config, and ...
global lf global cores global gisbase global gisdbase gisbase = '/usr/lib64/grass-6.4.4' # Ios: Grass 6.4.1 from RPM gisdbase = '/data/grass_workspace' # Eddy-the-server: GRASS GIS workspace loc = location = 'angelo2014' C = '1' #'30' #'2' # cell size in meters P = loc+C+'m' bregion = 'defau...
import sys import getopt import os.path from string import Template GPL=Template("""/* * Copyright (c) $YEAR $AUTHOR $EMAIL * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either vers...
import random import unittest from unittest.mock import MagicMock, patch from yatcobot.notifier import NotificationService class TestNotificationService(unittest.TestCase): @patch("yatcobot.plugins.notifiers.NotifierABC.__subclasses__") def test_initialize(self, __subclasses__): subclasses = [MagicMock(...
import urlparse import httplib import urllib import ZODB from persistent import Persistent from BTrees import OOBTree import MaKaC.conference as conference import MaKaC.errors as errors import MaKaC.common.info as info import MaKaC.common.xmlGen as xmlGen import MaKaC.export.oai2 as oai2 from MaKaC.common import Config...
import os import sys import time import unittest from duplicity import backend from duplicity import log _testing_dir = os.path.dirname(os.path.abspath(__file__)) _top_dir = os.path.dirname(_testing_dir) _overrides_dir = os.path.join(_testing_dir, 'overrides') sys.path = [_overrides_dir, _top_dir] + sys.path os.environ...
import sys import re import os from glob import glob RE_TAGOPEN = re.compile(r'<(\w+)([>/ ])') RE_TAGNAME = re.compile(r'(\w+)[>/ ]') RE_CLOSETAG = re.compile(r'<(\w+)[^</>]*/>$') class IncompleteXMLParser: """ An in-house XML parser for the nonstandard and incomplete XML structure found in the pythia documentation....
""" Created on July 22, 2014 FPKM function """ __author__ = 'Linuxpham <thaihoabo@gmail.com>' __contact__ = 'thaihoabo@gmail.com' __version__ = "1.0" __date__ = '2014-07-22' import sys, os import optparse, shutil DOCUMENT_ROOT = os.path.realpath(os.path.abspath("./")) LIBRARY_PATH = os.path.realpath(DOCUMENT_ROOT + "/l...
''' Created on Oct 6, 2014 @author: mike ''' import logging import json from twisted.web.resource import Resource from exe.webui.renderable import RenderableResource from exe.webui.webservice.exebackendservice import EXEBackEndService class LoginPage(RenderableResource): """ The LoginPage manages logg...
from app.runnables.pool import *
from django.db import models class Domain(models.Model): name = models.CharField(blank=True, default='', max_length=255) author = models.CharField(blank=True, default='', max_length=50) url = mo...
import sys import re import math from Crawler import FarnellCrawler from Component import AltiumComponent from ExcelWriter import ExcelWriter list_E12 = [1.0, 1.2, 1.5, 1.8, 2.2, 2.7, 3.3, 3.9, 4.7, 5.6, 6.8, 8.2] list_E24 = [1.0, 1.1, 1.2, 1.3, 1.5, 1.6, 1.8, 2.0, 2.2, 2.4, 2.7, 3.0, 3.3, 3.6, 3.9, 4.3,...
""" Test 'sys' module's 'argv' method. Is there any difference between ~python3 hello.py~ and ~./hello.py~. """ __author__ = 'Shaikh' import sys def test(): """ test function, main function. """ args = sys.argv if len(args) == 1: print('Hello, World!') elif len(args) == 2: print(...
import time import unittest from nive.cms.tests.db_app import * from nive.cms.cmsview.view import * from nive.cms.workflow.view import WorkflowEdit from nive.cms.workflow import wf from pyramid import testing from pyramid.httpexceptions import HTTPFound from pyramid.renderers import render class tWf(unittest.TestCase):...
import re import shlex from distutils.version import LooseVersion from ansible.module_utils.pycompat24 import get_exception from ansible.module_utils.network import NetworkError, NetworkModule from ansible.module_utils.network import register_transport, to_list from ansible.module_utils.shell import CliBase from ansibl...
import logging import os import re import signal import sys import subprocess import threading import time from multiprocessing.pool import ThreadPool from webkitpy.common.system.executive import ScriptError from webkitpy.layout_tests.breakpad.dump_reader_multipart import DumpReaderAndroid from webkitpy.layout_tests.mo...
import sys from setuptools import setup install_require = [] if sys.version_info.major < 3: print('Python 2 is not supported') sys.exit(1) elif sys.version_info.major > 2 and \ sys.version_info.minor < 4: print('Python 3.4 or newer is required') sys.exit(1) setup(name='KNXmap', ver...
''' File name: main_ripp_mod.py Author: Guillaume Viejo Date created: 16/08/2017 Python Version: 3.5.2 ''' import sys import numpy as np import pandas as pd import scipy.io from functions import * from multiprocessing import Pool import os import neuroseries as nts from time import time from pylab impor...
""" Repair bad annotations in the existing dataset with fixed annotations. Keep the original data split. Usage: python3 repair_data.py [data_directory] """ import csv import os, sys def import_repairs(import_dir): repairs, errors, new_annotations = {}, {}, {} new_annotation = False for file_name in os.listd...
import ml_class as ml def search_bin( i, time, t0, t_bins_mv ): #--------------------------------------------------------# # Search bin. # Loop over bins. for bin in xrange(len(t_bins_mv)): if ( time < t0 + t_bins_mv[bin] ): return bin return len(t_bins_mv)
from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('voices', '0005_auto_20170219_1318'), ] operations = [ migrations.AlterField( model_name='competition', name='url', fi...
# -*- coding: utf-8 -*- """ Train algorithm based on Delta - rule """ from neurolab.core import Train import neurolab.tool as tool class TrainDelta(Train): """ Train with Delta rule :Support networks: newp (one-layer perceptron) :Parameters: input: array like (l x net.ci) tr...
"""abydos.tests.distance.test_distance_unknown_m. This module contains unit tests for abydos.distance.UnknownM """ import unittest from abydos.distance import UnknownM class UnknownMTestCases(unittest.TestCase): """Test UnknownM functions. abydos.distance.UnknownM """ cmp = UnknownM() cmp_no_d = Unk...
def symbols(): return { 'bizkit': "Keep ROLLIN ROLLIN ROLLIN ROLLIN whaaat!", }
import re,os,sys,commands chunk=1000; ifile=open(sys.argv[1]); ilines=ifile.readlines(); Loc2Gene={};Gene_dic={};Loc_Gene_dic={}; for i in ilines: element=re.findall('[^\t\n]+',i); if element[2]=='exon': #gene=re.findall('ENSG\d+',i); gene=re.findall('gene_id[^\t]+',i); if len(gene)==0: #No gene name continu...
"""Galaxy webapps root package -- this is a namespace package.""" __import__( "pkg_resources" ).declare_namespace( __name__ )
class TreeNode(object): def __init__(self, node_id): self._node_id = node_id self._depth = -1 self._subtreedepth = -1 self._expr_index = -1 def get_node_id(self): return self._node_id def get_depth(self): return self._depth def set_depth(self, depth): ...
"""Helper class to display progress to the user.""" import sys class ProgressMeter(object): """Class to output progress during computations.""" OUTPUT_DOT = 0 OUTPUT_NUM = 1 def __init__(self, size, dot_every=1., num_every=10.): """Initializes the progress meter. Args: size: ...
import model import argparse from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from time import sleep parser = argparse.ArgumentParser(description='Setup simulation.') parser.add_argument('--db', default='sqlite:///:memory:', help='DB URL, default: sqlite:///:memory:') parser.add_argument('--...
import sys import subprocess def run( pubgenome): published_genome = pubgenome[0] cmmd = "nucmer --prefix=" + os.path.join(data_dir, proj_name) + " " + published_genome + " " + final_assembly subprocess.call(cmmd, shell=True) cmmd = "delta-filter -q " + os.path.join(data_dir, proj_name) + ".delta >" + o...
from ..base import FuncBase class DIALPLAN_EXISTS(FuncBase): pass class VALID_EXTEN(FuncBase): pass def register(func_loader): for func in ( DIALPLAN_EXISTS, VALID_EXTEN, ): func_loader.register(func())
from vector import CHaMP_Polygon from validation_classes import * class CHaMP_Islands(CHaMP_Polygon): minFeatureCount = 0 minArea = 1 # m^2 def __init__(self, name, filepath, type): self.type = type if type == "Wetted": self.name = "WIslands" elif type == "Bankfull": ...
from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'network'} DOCUMENTATION = """ --- module: junos_vrf version_added: "2.4" author: "Ganesh Nalawade (@ganeshr...
""" conference.py -- Udacity conference server-side Python App Engine API; uses Google Cloud Endpoints $Id: conference.py,v 1.25 2014/05/24 23:42:19 wesc Exp wesc $ created by wesc on 2014 apr 21 """ __author__ = 'wesc+api@google.com (Wesley Chun)' from datetime import datetime import json import os import time imp...
from cwrap import BaseCEnum class FieldTypeEnum(BaseCEnum): TYPE_NAME = "field_type_enum" ECLIPSE_RESTART = None ECLIPSE_PARAMETER = None GENERAL = None UNKNOWN_FIELD_TYPE = None FieldTypeEnum.addEnum("ECLIPSE_RESTART", 1) FieldTypeEnum.addEnum("ECLIPSE_PARAMETER", 2) FieldTypeEnum.addEnum("GENERAL"...
import json from fades import cache def test_missing_file(tmp_file): venvscache = cache.VEnvsCache(tmp_file) venvscache.store('installed', 'metadata', 'interpreter', 'options') with open(tmp_file, 'rt', encoding='utf8') as fh: data = json.loads(fh.readline()) assert 'timestamp' in data ...
from django.apps import AppConfig class Config(AppConfig): name = 'collab' verbose_name = "Rematch"
"""Test for the grid-search generator""" import os import shutil import tempfile import nose.tools from ..generator import aggregate, expand, generate from ..script import jgen def test_simple(): data = "name: [john, lisa]\n" "version: [v1, v2]" result = list(expand(data)) expected = [ {"name": "joh...
class Solution(object): def moveZeroes(self, nums): """ :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. """ def _find_zero(start): while start < len(nums) and nums[start] != 0: start += 1 return ...
import sys import nose from nose.tools import * import data_generator @raises(ValueError) def test_generate_birthday1(): data_generator.generate_birthday(-1, 11) @raises(ValueError) def test_generate_birthday2(): data_generator.generate_birthday(3, 14)
__author__ = 'pavle' import logging class Markable: def __init__(self): self.__marks = {} def mark(self, key, value=None): if value is None: value = key key = ':default' self.__marks[key] = value def marked(self, key=None): if key is None: ...
class Solution: def maximumSwap(self, num): """ :type num: int :rtype: int """ num_int = [int(i) for i in str(num)] for pos in range(0, len(num_int)): max_num = num_int[pos] for i in range(pos+1, len(num_int)): max_num = max(max...
import random ACTION = ["hit", "stick"] TERMINAL = (-1, -1) def step(s, a): """ step game :param s: current state, (dealer's first card, the player's sum) tuple :param a: selected action :return: (state, reward) tuple """ dealer, player = s if a == ACTION[0]: # if action is hit ...
import nzbtomedia import requests import shutil from nzbtomedia.nzbToMediaUtil import convert_to_ascii, server_responding from nzbtomedia.nzbToMediaSceneExceptions import process_all_exceptions from nzbtomedia import logger class autoProcessGames: def process(self, section, dirName, inputName=None, status=0, client...
import tensorflow as tf matrix1 = tf.constant([[1., 2.]]) matrix2 = tf.constant([[3.], [4.]]) product = tf.matmul(matrix1, matrix2) sess = tf.Session() result = sess.run(fetches=product) print(result) # expected value is [[ 11.]] sess.close() with tf.Session() as sess: result = sess.run(fetches=product) print(...
import os import re from dtk.ui.utils import is_network_connected from config import config from lrc_download import TTPlayer, DUOMI, SOSO from helper import Dispatcher import utils class LrcManager(object): def __init__(self): pass def get_lrc_search_str(self, song): artist = song.get_str("arti...
import pygame from pygame.locals import* from libs.MusicMan import MusicMan pygame.mixer.pre_init(frequency = 44010, buffer = 2**9) pygame.init() pygame.mixer.set_num_channels(100) pygame.mixer.set_reserved(1) from libs.World import World import time, random class Main(object): def __init__(self): self.screen_size =...
from __future__ import unicode_literals import copy import json from datetime import date, datetime, timedelta from uuid import uuid4 from crispy_forms.bootstrap import InlineRadios, Tab, TabHolder from crispy_forms.helper import FormHelper from crispy_forms.layout import HTML, Div, Field, Fieldset, Layout from django ...
type = "passive" def handler(fit, module, context): fit.modules.filteredItemBoost(lambda mod: mod.item.group.name == "Missile Launcher Heavy Assault", "speed", module.getModifiedItemAttr("subsystemBonusMinmatarOffensive"), skill="Minmatar Offensive...
import csv from django.core.exceptions import ObjectDoesNotExist from django.db import IntegrityError from core.models import Busline, Terminal, Company class Parser(object): def import_data(self): self.import_companies() self.import_terminals() self.import_bus_lines() self.create_bu...
from __future__ import unicode_literals import datetime from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('tableaubord', '0082_auto_20170512_1942'), ] operations = [ migrations.AddField( model_name='evenement', name='pho...