code
stringlengths
1
199k
import math import time from web_spider import support print(support.print_func("Test how to import Moudle.")) if True: print("Answer") print("True") else: print("Answer") print("False") counter = 100 # 赋值整型变量 miles = 1000.0 # 浮点型 name = "John" # 字符串 print("Counter: " + str(counter)) print("Miles: " ...
import sys import sqlite3 import json import os from core.util.base_util import BaseUtil reload(sys) sys.setdefaultencoding('utf8') class Lsajax(BaseUtil): @staticmethod def get_settings(): return dict( descr = "List all pages and related ajax calls", optargs = 'd', minargs = 0, use_dbfile = True ) d...
from __future__ import print_function import pdb, os, sys, warnings, time import astropy.io.fits as pyfits from astropy.table import Table, Column import numpy as np import matplotlib.pyplot as plt import scipy.optimize import scipy.interpolate import scipy.spatial """ Top-level routines that constitute the basic steps...
import logging from thug.DOM.JSClass import JSClass log = logging.getLogger("Thug") class CSSStyleDeclaration(JSClass): def __init__(self, style): self.props = dict() for prop in [p for p in style.split(';') if p]: k, v = prop.strip().split(':') self.props[k.strip()] = v.stri...
import os import sys import imp from mutagen._compat import StringIO, text_type from tests import TestCase def get_var(tool_name, entry="main"): tool_path = os.path.join("tools", tool_name) dont_write_bytecode = sys.dont_write_bytecode sys.dont_write_bytecode = True try: mod = imp.load_source(to...
import sys ipadd = sys.argv[1].split('.') print ipadd for i, v in enumerate(ipadd): ipadd[i] = bin(int(ipadd[i])) print '.'.join(ipadd)
import urllib, urllib2, re, xbmcplugin, xbmcgui, sys, xbmcaddon, base64 thisPlugin = int(sys.argv[1]) settings = xbmcaddon.Addon(id='plugin.video.celebgate_cc') translation = settings.getLocalizedString forceViewMode = settings.getSetting("force_viewmode") == "true" useCacheToDisc = settings.getSetting("cache_to_disc")...
from pprint import pprint from pprint_data import data for width in [ 80, 5, 1 ]: print 'WIDTH =', width pprint(data, width=width) print
""" Handle Node's network configuration """ import sys import subprocess import os import json import xmltodict import re import time import libvirt import bash class NetworkControler: def __init__(self, debug=False): self.debug = debug self.connection = libvirt.open("qemu:///system") self.netconfig = {} self....
import unittest import pytest from datetime import datetime, timedelta import os import numpy as np import opendrift from opendrift.readers import reader_oscillating from opendrift.models.oceandrift import OceanDrift class TestXarray(unittest.TestCase): """Tests for Xarray / dask functionality""" def test_densi...
"""CSS Lexical Grammar rules. CSS lexical grammar from http://www.w3.org/TR/CSS21/grammar.html """ __author__ = ['elsigh@google.com (Lindsey Simon)', 'msamuel@google.com (Mike Samuel)'] __all__ = [ "NEWLINE", "HEX", "NON_ASCII", "UNICODE", "ESCAPE", "NMSTART", "NMCHAR", "STRING1", "STRING2", "IDENT", "NAM...
import sys import logging from client import Client from arg import Args, missing_args from video import Video from filter import IsAMovieFile, HasAsrtFile class Launcher: def __init__(self, filenames): self.map = {} for filename in filenames: v = Video(filename) self.map[v.g...
import fnmatch import inspect import logging import os import pexpect import re import shutil from distutils.version import LooseVersion from pipes import quote from sos.policies import load, InitSystem from sos.collector.exceptions import (InvalidPasswordException, TimeoutPassword...
try: from distorm3 import Decode, Decode16Bits, Decode32Bits, Decode64Bits except: print 'Inline function hook finder need to distorm3.' class INLINEHOOK(): def __init__(self, x86_mem_pae, arch, os_version, base_address): self.x86_mem_pae = x86_mem_pae self.arch = arch self.os_versio...
""" Routines for automatically retrieving album cover images from various sources. Copyright (C) 2003 Sami Kyöstilä <skyostil@kempele.fi> 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...
import logging import re import dateutil.parser import random import json import time import ssl import tempfile import pprint import functools import threading import os import httplib2 import apiclient.discovery import apiclient.http import apiclient.errors import gdrivefs.constants import gdrivefs.config import gdri...
''' fasta.py Read in FASTA files ''' import re import io from typing import ( Dict, List, Tuple, Union, Generator ) _fasta_re: str = r'>(.+)[\n\r]+((?:[^>\S]|[{}]+[\n\r]+)+)' _ALPHABETS: Dict[str, str] = { 'DNA': r'ACGTWSMKRYBDHVN', 'RNA': r'ACGUWSMKRYBDHVN', 'AMINO_ACID': r'ABCDEFGHIJKL...
""" The job module contains the objects and methods used to manage jobs in Autotest. The valid actions are: list: lists job(s) create: create a job abort: abort job(s) stat: detailed listing of job(s) The common options are: See topic_common.py for a High Level Design and Algorithm. """ import getpass, os, pwd...
import os import shlex import sys from datetime import datetime, date from pathlib import Path from textwrap import dedent from typing import Set, List, Dict, Optional from eden.fs.cli import ( config as config_mod, filesystem, mtab, proc_utils as proc_utils_mod, ui, version, ) from eden.fs.cli....
""" This file is part of Spartacus project Copyright (C) 2016 CSE 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. This program ...
import bpy def create_and_link_mesh(name, faces, points): ''' Create a blender mesh and object called name from a list of *points* and *faces* and link it in the current scene. ''' mesh = bpy.data.meshes.new(name) mesh.from_pydata(points, [], faces) # update mesh to allow proper display ...
import snapcraft.plugins.jhbuild from tests import unit class JHBuildPluginTestCase(unit.TestCase): # type: ignore def _test_plugin(self): class Options: modules = ['gtk+'] snap_name = 'test' return snapcraft.plugins.jhbuild.JHBuildPlugin('test', Options()) def test_sche...
import os def Formato(): formato = '%-*s%*s' print "#" * 25 print "#" * 25 print formato % (22 , "## 1. Triangulo" , 3 , "##") print formato % (22 , "## 2. Rectangulo" , 3 , "##") print formato % (22 , "## 3. Cuadrado" , 3 , "##") print formato % (22 , "## (Enter) Salir" , 3, "##") print "#" * 25 print "#" * 2...
import os import json import mock import shutil import pkgutil import unittest from itertools import count from chan import chanthread from chan import threadcontainer from twisted.trial.unittest import TestCase json_str = pkgutil.get_data("chan.test.files", "json_old_dump") url = "https://boards.4chan.org/b/thread/544...
""" <plugin key="Sonos" name="Sonos Players" author="tester22" version="2.0" wikilink="http://www.domoticz.com/wiki/plugins/Sonos.html" externallink="https://sonos.com/"> <params> <param field="Address" label="IP Address" width="200px" required="true" default="127.0.0.1"/> <param field="Mode1" label...
from django.conf.urls import url from .apps import AppConfig from .views import (controlador_painel, cronometro_painel, get_dados_painel, painel_mensagem_view, painel_parlamentar_view, painel_view, painel_votacao_view, votante_view) app_name = AppConfig.name urlpatterns = [ u...
from test_support import * import glob import os.path def cat_traces(): files = glob.glob("gnatprove/*postcondition*trace") for file in files: cat (file, sort=True) prove_all(opt=["--limit-line=test.ads:4", "--proof=progressive"], cache_allowed=False) cat_traces() clean() prove_all(opt=["--limit-line=te...
__prog_name__ = 'run_iqtree.py' __prog_desc__ = 'Run IQ-TREE in parallel' __author__ = 'Donovan Parks' __copyright__ = 'Copyright 2020' __credits__ = ['Donovan Parks'] __license__ = 'GPL3' __version__ = '0.0.1' __maintainer__ = 'Donovan Parks' __email__ = 'donovan.parks@gmail.com' __status__ = 'Development' import os i...
import dataclasses from random import Random import pytest from randovania.game_description import default_database from randovania.game_description.game_patches import GamePatches from randovania.game_description.resources.resource_type import ResourceType from randovania.game_description.world.area_identifier import ...
import networkx as nx from .base_test import BaseTestAttributeMixing, BaseTestDegreeMixing class TestAttributeMixingXY(BaseTestAttributeMixing): def test_node_attribute_xy_undirected(self): attrxy = sorted(nx.node_attribute_xy(self.G, "fish")) attrxy_result = sorted( [ ("...
""" Class Name : MusicManager Class Version: 2.0 Description: Manages playing music and music queues and such. Controlled by plugins/Voice.py Local music should be stored in `resources/music/`, preferably grouped by album, e.g., `resources/music/Kilroy\ Was\ Here/...
""" :mod:`gromacs.formats` -- Accessing various files ================================================= This module contains classes that represent data files on disk. Typically one creates an instance and - reads from a file using a :meth:`read` method, or - populates the instance (in the simplest case with a :meth:`s...
"""Early initialization and main entry point.""" import sys import json import qutebrowser try: from qutebrowser.misc.checkpyver import check_python_version except ImportError: try: # python2 from .misc.checkpyver import check_python_version except (SystemError, ValueError): # Import...
from __future__ import print_function from __future__ import division from __future__ import absolute_import from __future__ import unicode_literals from gi.repository import Gtk class NetworkErrorDialog(Gtk.MessageDialog): def __init__(self, excp, secondary_markup=None): Gtk.MessageDialog.__init__(self, bu...
"""Common utility functions.""" from psycopg2 import OperationalError from PyQt4.QtGui import QAction def ch_conn(caller=None, name='', sig=None, func=None): """Disconnect function conns[name] from signal sigs[name], if args provided make new connection, adapt dict. pyqt Bug: disconnect() w/o arg segfaults....
from block import block from script import script blockfile = '/home/marzig76/.bitcoin/blocks/blk00000.dat' blockstream = open(blockfile, 'rb') parsed_block = block(blockstream) print parsed_block pk_script = script('6a13636861726c6579206c6f766573206865696469'.decode('hex')) print pk_script
"""This module contains tests for the data_types module of the DJ Scrooge backtesting API. Copyright (C) 2012 James Adam Cataldo This file is part of DJ Scrooge. DJ Scrooge is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the F...
""" _main_window ============ Provides: --------- 1) MainWindow: Main window of the application pyspread """ import ast import os from os.path import splitext import wx import wx.lib.agw.aui as aui try: from matplotlib.figure import Figure except ImportError: Figure = None try: from src.lib.gpg import gen...
from distutils.core import setup setup( name='graph-tool-nn', version='1.1.0', packages=['gtnn', 'gtnn.generators', 'gtnn.learn', 'gtnn.network'], license='GNU General Public License v3 (GPLv3)', long_description=r'''Graph-tool is a great open source tool for creating, using and analyzing graphs. It...
from bass_functions import * from modules.pleth_analysis import pleth_analysis from modules.ekg_analysis import ekg_analysis class BASS_Dataset(object): ''' Imports dataset as an object Attributes ---------- Batch: static list Contains all instances of the BASS_Dataset object in order to be ref...
from django.db import connection, reset_queries from . import models from django.conf import settings import logging from publisher import utils, relation_logic from publisher.utils import ensure, lmap, lfilter, firstnn, second, exsubdict from django.utils import timezone from django.db.models import Max, F # , Q, Whe...
from Spirit.Spirit import Spirit server = Spirit("Spirit.conf", server="Wind") server.start()
import sys import os.path from pyquery import PyQuery as pq import time import common sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "../lib"))) import mysql import util import uhyips def main(): print "\n========== RUN get_stat.py ============" util.logNow("START AT") rcb_list = common.getR...
''' A smarter {% if %} tag for django templates. While retaining current Django functionality, it also handles equality, greater than and less than operators. Some common case examples:: {% if articles|length >= 5 %}...{% endif %} {% if "ifnotequal tag" != "beautiful" %}...{% endif %} ''' import unittest from d...
""" This file is uses to specifie the database type and its location on the file system. The first step to determin the database location is to look up the env variable TASKER_DB. If this isn't existing the database will be located in the tasker module as tasker.db. """ import os, inspect db_type = r'sqlite:///' db_pat...
from .tools.timecode import is_timecode, timecode_to_srt from .tools.find_even_split import find_even_split class Lyrics(list): """A list that holds the contents of the lrc file""" def __init__(self, items=[]): self.artist = "" self.album = "" self.title = "" self.author = "" ...
a=int(input()) a=bin(a).replace("0b","") c=[int(i) for i in str(a)] d=[] e=c[0] for i in range(0,len(a)): if(i==0): d.append(c[i]) else: f=c[i]^e d.append(f) e=f e=1 g=0 for i in range(0,len(a)): g=g+d[len(a)-i-1]*e e=e*2 print(g)
import json import pdb from django.shortcuts import render_to_response from django.template import RequestContext from apps.cserver_comm.cserver_communicator import get_full_graph_json_str, get_concept_data from apps.user_management.models import Profile def get_agfk_app(request): concepts = get_user_data(request) ...
import logging import pytest import pytest_bdd as bdd bdd.scenarios('open.feature') @pytest.mark.parametrize('scheme', ['http://', '']) def test_open_s(request, quteproc, ssl_server, scheme): """Test :open with -s.""" quteproc.set_setting('content.ssl_strict', 'false') quteproc.send_cmd(':open -s {}localhos...
from __future__ import (absolute_import, division, print_function) import unittest from mantid.simpleapi import Load from mantid import mtd, FileFinder class PropertyHistoryTest(unittest.TestCase): def test_history(self): ws_name = "GEM38370_Focussed_Legacy" file_name = FileFinder.getFullPath(ws_nam...
import numpy as np class Mass( object ): """ 'Meaure' for computing the total mass of the particle system """ def __init__( self , pset=None, force=None ): super( Mass , self ).__init__( pset=pset , force=force ) self.__M = 0.0 def update_measure( self ): """ Compute...
import inspect import logging import sys def ispydevd(): for frame in inspect.stack(): if frame[1].endswith("pydevd.py"): return True return False root_logger = logging.getLogger() logging.getLogger('yapsy').setLevel(logging.INFO) # this one is way too verbose in debug logging.getLogger('Ro...
""" application.py ~~~~~~~~~~~~~~~~~~~~ 应用程序配置程序 :date: 2011-09-24 :author: wwq0327 <wwq0327@gmail.com> :license: GPLv3 """ from flask import Flask, render_template from flaskext.uploads import configure_uploads from life.config import Config, DevConfig, ProConfig from life.extensions import db,...
from PyKDL import * from math import pi segments = [ Segment(Joint(Joint.None), Frame(Rotation.RPY(pi/2, 0, pi/6),Vector(0.07,-0.12124,1.05))), Segment(Joint(Joint.RotZ), Frame(Vector(0,0,0.225))), Segment(Joint(Joint.RotY,-1), Frame(Vector(0,-0.26,0))), Segment(Joint(Joint.RotX,-1), Fra...
import socket, os ,glob # Import socket module s = socket.socket() # Create a socket object host = 'localhost' # Get local machine name port = 8000 # Reserve a port for your service. s.connect((host, port)) os.chdir("GPX") for filename in glob.glob("*.gpx"): f = ...
__version__ = '0.2.19' import http.client, base64, xml.dom.minidom, time, sys, urllib class ApiError(Exception): def __init__(self, status, reason, payload): self.status = status self.reason = reason self.payload = payload def __str__(self): return "Request failed: " + str(self...
import unittest import pickle import numpy as np import Orange from Orange.classification import SimpleRandomForestLearner class SimpleRandomForestTest(unittest.TestCase): def test_SimpleRandomForest_classification(self): data = Orange.data.Table('iris') lrn = SimpleRandomForestLearner() clf...
import sys from functools import partial import greenlet from . import lib Nothing = object() class Branch(greenlet.greenlet): __slots__ = ('hub', '_run') def __init__(self, *args, hub, **kwargs): super().__init__(*args, **kwargs) self.hub = hub class Hub(greenlet.greenlet): def __init__(sel...
version_number = "20180523"
from pyasn1.type import univ, char, namedtype, namedval, tag, constraint, useful def _OID(*components): output = [] for x in tuple(components): if isinstance(x, univ.ObjectIdentifier): output.extend(list(x)) else: output.append(int(x)) return univ.ObjectIdentifier(out...
import unittest import json import random import string import requests class TestApiAgreementRest(unittest.TestCase): def setUp(self): self.domain = 'mi.co' self.URL = 'http://localhost:5000/' self.admon = 'admon@' + self.domain self.passAdmin = 'Abcd1234' self.digits = "".j...
"""Basic tests for the include module and its functions. Some functions rely on file system operations, and are probably better tested by functional tests. So this suite of unit tests should not cover all the module features. """ import tempfile import unittest from cylc.flow.parsec.include import * class TestInclude(u...
from __future__ import unicode_literals import datetime import logging import re from babelfish import Error as BabelfishError, Language as BabelfishLanguage from six import PY3, text_type logger = logging.getLogger(__name__) def is_unknown(value): return isinstance(value, text_type) and (not value or value.lower()...
"""FreeIPA tests FreeIPA is a server for identity, policy, and audit. """ from os.path import abspath, dirname import sys if __name__ == '__main__': # include ../ for ipasetup.py sys.path.append(dirname(dirname(abspath(__file__)))) from ipasetup import ipasetup # noqa: E402 ipasetup( name="ipat...
import github.GithubObject import github.Rate class RateLimit(github.GithubObject.NonCompletableGithubObject): """ This class represents rate limits as defined in http://developer.github.com/v3/rate_limit """ @property def rate(self): """ :type: class:`github.Rate.Rate` """ ...
import sys import traceback USE_MULTIPROCESSING = True class FakeProcess(): """ Dummy process """ def __init__(self, group=None, target=None, name=None, args=(), kwargs={}, *, daemon=None): self.target = target self.args = args self.kwargs = kwargs def start(self): se...
from django.shortcuts import render from django.views.generic import View from django.views.generic.list import ListView from django.utils import timezone from django.conf import settings from jaumt.models import Url, UrlStatusEnum class Home(View): def get(self, requests): return render(requests, 'jaumt/ho...
""" Second example, ion heating, multiple pulses """ import os import numpy as np from plot import make_figure from util import run_ebtel, read_xml top_dir = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) if __name__ == '__main__': # Configure and run ebtel++ base = read_xml(os.path.join(top_dir, ...
import logging import threading import queue import socket import os import select import configparser import sys import usb.core import usb.util TIMEOUT = 30000 # ms CONFIG_FILE = '/etc/hid2tcp.conf' class UsbInterface(threading.Thread): def __init__(self, config, pipeout): self.config = config ...
""" Copyright 2011 Marcus Fedarko Contact Email: marcus.fedarko@gmail.com This file is part of CAIP. CAIP 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) an...
"""FreeIPA python support library FreeIPA is a server for identity, policy, and audit. """ from os.path import abspath, dirname import sys if __name__ == '__main__': # include ../ for ipasetup.py sys.path.append(dirname(dirname(abspath(__file__)))) from ipasetup import ipasetup # noqa: E402 ipasetup( ...
from setuptools import setup, find_packages with open("README.md") as fd: long_description=fd.read() setup( name='tokex', version='2.1.0', description="String tokenizing and parsing library", long_description=long_description, long_description_content_type="text/markdown", author="Warren Spe...
""" Determine Normalization for current CPU """ __RCSID__ = "$Id$" import DIRAC from DIRAC.Core.Base import Script Script.registerSwitch( "U", "Update", "Update dirac.cfg with the resulting value" ) Script.registerSwitch( "R:", "Reconfig=", "Update given configuration file with the resulting value" ) Script.setUsageM...
import module import re class Module(module.Module): def __init__(self, params): module.Module.__init__(self, params, query='SELECT DISTINCT domain FROM domains WHERE domain IS NOT NULL ORDER BY domain') self.register_option('limit', 1, True, 'limit number of api requests per input source (0 = unlim...
import os bind = os.getenv('GUNICORN_BIND', 'localhost:4000') workers = os.getenv('GUNICORN_WORKERS', 2) backlog = os.getenv('GUNICORN_BACKLOG', 1024) worker_class = os.getenv('GUNICORN_WORKER_CLASS', 'sync') threads = os.getenv('GUNICORN_THREADS', 1) worker_connections = os.getenv('GUNICORN_WORKER_CONNECTIONS', 1000) ...
from __future__ import unicode_literals from django.db import migrations import image_cropping.fields class Migration(migrations.Migration): dependencies = [ ('booker', '0046_musician_cropping'), ] operations = [ migrations.AlterField( model_name='musician', name='cro...
import time as _time import datetime as _datetime import random from outspline.static.wxclasses.timectrls import DateHourCtrl, TimeSpanCtrl import outspline.extensions.organism_basicrules_api as organism_basicrules_api import outspline.plugins.wxscheduler_api as wxscheduler_api import interface import msgboxes class Ru...
""" Usage: python module2seq.py <module> <path to ko file> <path to proteins file> """ import urllib import os import sys from collections import defaultdict if len(sys.argv) == 1 or sys.argv[1] == '-h': sys.exit(__doc__) URL_MODULES = 'http://www.kegg.jp/kegg-bin/download_htext?htext=ko00002.keg&'\ '...
""" Created on Thu Jun 15 19:54:08 2017 @author: leandro """ import scipy.special import scipy.stats import numpy as np import math def binProb(i, n, p): """ @Parameters: n -> number of trials p -> probability of success i -> test quantity @Returns: Bin(n,p)...
""" Methods for building the library's database. """ __all__ = [ # abstract "TableBuilder", "EntryGeneratorBuilder", # Unihan and Kanjidic character information "UnihanGenerator", "UnihanBuilder", "Kanjidic2Builder", "UnihanDerivedBuilder", "UnihanStrokeCountBuilder", "CharacterRadicalBuilder", ...
import argparse import networkx as nx parser = argparse.ArgumentParser(description='count nodes and edges in a network') parser.add_argument('--input', type=argparse.FileType('r'), required=True, help='text file "node,interaction(w),node" undirected') args = parser.parse_args() G = nx.Graph() edges =...
CATKIN_PACKAGE_PREFIX = "" PROJECT_PKG_CONFIG_INCLUDE_DIRS = "/home/odroid/ROS/install/include".split(';') if "/home/odroid/ROS/install/include" != "" else [] PROJECT_CATKIN_DEPENDS = "cv_bridge;std_msgs;sensor_msgs;image_transport;roscpp;geometry_msgs".replace(';', ' ') PKG_CONFIG_LIBRARIES_WITH_PREFIX = "".split(';')...
""" Create tasks for the first run Tasks should serve as a quick tutorial how GTG works """ from gettext import gettext as _ from GTG.core.tag import extract_tags_from_text from GTG.core import xml from GTG.core.dates import Date from uuid import uuid4 from lxml import etree tags = { 'to_pay': str(uuid4()), 'mo...
from django.conf.urls import url from . import views from django.conf.urls import include urlpatterns = [ url(r'^$', views.default, name='index'), url(r'^app', views.application, name='formtofill'), url(r'^challenges',views.challengeslist, name='chl'), url(r'^leaderboard',views.leaderlist,name="led"), ...
import sys, os import requests import json from loader import get_settings CONFIG = get_settings() BASE_URL = CONFIG.get('HOSTNAME', "https://gitlab.com/") class GitlabAPI: def __init__(self, private_token, *args, **kwargs): self.private_token = private_token def get_user_details(self, username): ...
__all__ = ["caesar"]
import numpy import matplotlib.pyplot as plt from matplotlib.testing.decorators import image_comparison from nose.tools import assert_raises def check_shared(results, f, axs): """ results is a 4 x 4 x 2 matrix of boolean values where if [i, j, 0] == True, X axis for subplots i and j should be shared ...
""" LibNix Copyright (C) 2017 Mark Biciunas This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the ...
import pandas as pd import numpy as np from random import random from scipy.io import wavfile from keras.models import Sequential from keras.layers.core import Dense, Activation from keras.layers.recurrent import LSTM SAMPLING_RATE = None def get_data_from_wav(filename): r, d = wavfile.read(filename) right_stre...
from sys import argv import itertools def parseFile(fileName): with open(fileName) as inFile: s_list = inFile.readline().strip().split() k = int(inFile.readline().strip()) return s_list, k if __name__ == "__main__": s_list, k = parseFile(argv[1]) for x in s_list: for i in range(1...
class Solution: # greedy # time: O(n) # space: O(1) def isPossible(self, nums): """ :type nums: List[int] :rtype: bool """ pre = -sys.maxsize p1, p2, p3 = 0, 0, 0 cur, cnt = 0, 1 c1, c2, c3 = 0, 0, 0 for i in range(len(nums)): ...
print "Hello, cereo!"
""" All classes required by the tutorial part of ProjectL Copyright (C) 2017 Jan-Oliver "Janonard" Opdenhövel Copyright (C) 2017 Jason "J2a0s0o0n" Becker Copyright (C) 2017 David "Flummi3" Waelsch This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License a...
import random import math import statistics as st L1 = [] L2 = [] L3 = [] for i in range(0, 500): for x in range(0, 9): rnum = random.randint(1, 500) L1.append(rnum) L2.append(L1) L1.sort() minn = max(L1) maxx = minn + (minn * .2) L3.append(random.randint(minn, int(maxx))) L1 = [] print(str(L2[i]) + ":" + s...
import sys import xml.etree.ElementTree as ET from os import sep, path from components.widgets.nodes import * from components.globals import BUNDLE_DIR class NodeTree(QtWidgets.QTreeWidget): def __init__(self, sourceName, parent=None): QtWidgets.QWidget.__init__(self, parent) self.sourceName = sourc...
""" Test_RSS_Policy_PilotEfficiencyPolicy """ import unittest import DIRAC.ResourceStatusSystem.Policy.PilotEfficiencyPolicy as moduleTested class PilotEfficiencyPolicy_TestCase(unittest.TestCase): def setUp(self): """ Setup """ self.moduleTested = moduleTested self.testClass...
import requests import json import urllib import logger import sys import re class CloudFlare(object): """docstring for CloudFlare""" def __init__(self, email, global_key): super(CloudFlare, self).__init__() self.email = email self.global_key = global_key def getHeader(self): return { "X-Auth-Email": self...
import unittest from database.memcached_database import MemcachedDatabase from database.exceptions import DatabaseException, InvalidLocationError, LockAlreadyAquiredError from objects.map_square import MapSquare from objects.map_square_types import MapSquareTypes class TestSquares(unittest.TestCase): def test_ok(se...
""" Format results for printing """ import os from fstimer.printer.printcsv import CSVPrinter from fstimer.printer.printcsvlaps import CSVPrinterLaps from fstimer.printer.printhtml import HTMLPrinter from fstimer.printer.printhtmllaps import HTMLPrinterLaps from collections import defaultdict from fstimer.time_ops impo...
""" Radicale logging module. Manage logging from a configuration file. For more information, see: http://docs.python.org/library/logging.config.html """ import os import sys import logging import logging.config from . import config LOGGER = logging.getLogger() FILENAME = os.path.expanduser(config.get("logging", "config...