text
stringlengths
1
927k
from afqueue.source.manager_worker import ManagerWorker #@UnresolvedImport from multiprocessing import Process, Queue #@UnresolvedImport from afqueue.common.exception_formatter import ExceptionFormatter #@UnresolvedImport from afqueue.messages import system_messages #@UnresolvedImport from afqueue.threads.data_worker_t...
import _init_paths import tensorflow as tf tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR) from trainers.adnet_train_sl import adnet_train_sl import argparse from options.general2 import opts from models.ADNet import adnet from utils.get_train_videos import get_train_videos from trainers.adnet_train_rl i...
import tensorflow as tf from tacotron.utils.symbols import symbols from tacotron.utils.symbols import tone_stress_symbols_max_no from tacotron.utils.symbols import symbols_tag from infolog import log from tacotron.models.helpers import TacoTrainingHelper, TacoTestHelper from tacotron.models.modules import * from tenso...
import numpy as np def main(): p1() p2() p6() def p1(): # Do part 1. print('*' * 80) print('Problem 8.8, Part 1') a1 = np.array([ [3, 8], [2, 3] ]) _get_participation(a1) # Now part 2. print('*' * 80) print('Problem 8.8, Part 2') a2 = np.array([ ...
import ray import socket ray.init() import pickle import docker from contextlib import closing @ray.remote class Predictor(object): """Actor that adds deploys specified container. result = "Recieved " + input_batch. """ def __init__(self, container): with closing(socket.socket(socket.AF_INET, ...
import binascii import logging import os from django.core.management.base import BaseCommand from oidc_provider.models import Client from oidc_provider.models import ResponseType logger = logging.getLogger(__name__) """ Usage example: kolibri manage oidccreateclient --name="hooooo" --redirect-uri="http://otro/callb...
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the...
from mltrace import Task from sklearn.metrics import mean_squared_error import random import string task = Task("testing") def inference_component(output_id): task.logOutput(random.randint(0, 1), output_id) def feedback_component(output_id): task.logFeedback(random.randint(0, 1), output_id) if __name__ ...
from .QuoteAdapter import QuoteAdapter from .GoogleFinanceQuoteAdapter import GoogleFinanceQuoteAdapter
import json from pathlib import Path import pytest from sciencebeam_trainer_delft.sequence_labelling.utils.checkpoints import ( CheckPoints, get_resume_train_model_params ) class TestCheckPoints: def test_should_raise_exception_without_log_dir(self): with pytest.raises(AssertionError): ...
# toWebHtmlMacro.py # -*- coding: utf-8 -*- # LibreOfficeのディスパッチコマンドでウェブブラウザに出力するマクロ。 from com.sun.star.beans import PropertyValue def toWebHtml(): desktop = XSCRIPTCONTEXT.getDesktop() # デスクトップを取得。 prop = PropertyValue(Name="Hidden",Value=True) # バックグラウンドで開く設定。 doc = desktop.loadComponentFromURL("privat...
import cPickle as pickle def save_model(params, epoch = 0, annotation='', namestub = '', savepath = '../data/models/', test_score=0.0): savedFileName = namestub + '_' + str(epoch) + '_pars_' + annotation +'.pkl' gg = open(savepath + savedFileName, 'wb') pickle.dump(params, gg, protocol=pickle.HIGHEST_PRO...
# Multiple time series on common axes # Import matplotlib.pyplot as plt import matplotlib.pyplot as plt # Plot the aapl time series in blue plt.plot(aapl, color='blue', label='AAPL') # Plot the ibm time series in green plt.plot(ibm, color='green', label='IBM') # Plot the csco time series in red plt.plot(csco, color...
# -*- coding: utf-8 -*- """ Tencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community Edition) available. Copyright (C) 2017-2018 THL A29 Limited, a Tencent company. All rights reserved. Licensed under the MIT License (the "License"); you may not use this file except in co...
class Solution(object): def diffWaysToCompute(self, input): """ :type input: str :rtype: List[int] """ def test_diff_ways_to_compute(): s = Solution() assert [0, 2] == s.diffWaysToCompute("2-1-1") assert [-34, -14, -10, -10, 10] == s.diffWaysToCompute("2*3-4*5")
""" models for hosts, domains, service updaters, ... """ import re import base64 import dns.resolver from django.db import models from django.contrib.auth import get_user_model from django.core.exceptions import ValidationError from django.core.validators import RegexValidator from django.conf import settings from d...
# (C) Datadog, Inc. 2018 # All rights reserved # Licensed under a 3-clause BSD style license (see LICENSE) import xml.etree.ElementTree as ET from datetime import datetime import requests from datadog_checks.base import AgentCheck, ConfigurationError EPOCH = datetime(1970, 1, 1) class Bind9Check(AgentCheck): B...
from rest_framework import generics, permissions as drf_permissions from framework.auth.oauth_scopes import CoreScopes from api.base.filters import ODMFilterMixin from api.base import permissions as base_permissions from api.base.utils import get_object_or_error from api.licenses.serializers import LicenseSerializer f...
from __future__ import absolute_import, unicode_literals import os import re from django.contrib.gis.db.models import Union, Extent3D from django.contrib.gis.geos import GEOSGeometry, LineString, Point, Polygon from django.contrib.gis.utils import LayerMapping, LayerMapError from django.test import TestCase from .mo...
"""Test module for dbseeder"""
from distutils.core import setup import os import codecs classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Pyt...
import os import csv import requests from datetime import datetime import simplejson as json import platform import base64 import ohmysportsfeedspy # API class for dealing with v1.0 of the API class API_v1_0(object): # Constructor def __init__(self, verbose, store_type=None, store_location=None): se...
#!/usr/bin/env python3 # Copyright 2015-2020 Arm Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable ...
from numpy import linspace from scipy.interpolate import interp1d class Interpolator: """ Базовый класс интерполятора """ def __init__(self, points=100): self.points = points def interpolate(self, x, y): pass class Quadratic(Interpolator): """ Квдратичный интерполятор ...
#!/usr/bin/env python3 """ Simulating a regular spiking Izhikevich neuron with NeuroML. File: izhikevich-single-neuron.py """ from neuroml import NeuroMLDocument from neuroml import Izhikevich2007Cell from neuroml import Population from neuroml import Network from neuroml import PulseGenerator from neuroml import Exp...
import collections from datetime import datetime from itertools import chain, repeat import pandas as pd from toolz import curry from numpy import nan @curry def evaluator_extractor(result, evaluator_name): metric_value = result[evaluator_name] if result else nan return pd.DataFrame({evaluator_name: [metric_...
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! """Client and server classes corresponding to protobuf-defined services.""" import grpc from google.cloud.spanner_v1.proto import ( result_set_pb2 as google_dot_cloud_dot_spanner__v1_dot_proto_dot_result__set__pb2, ) from google.cloud.spanner_v1...
import time import logging from spaceone.inventory.libs.manager import GoogleCloudManager from spaceone.inventory.libs.schema.base import ReferenceModel from spaceone.inventory.connector.instance_group import InstanceGroupConnector from spaceone.inventory.model.instance_group.data import * from spaceone.inventory.mode...
""" :copyright: © 2019 by the Lin team. :license: MIT, see LICENSE for more details. """ from datetime import timedelta class BaseConfig(object): """ 基础配置 """ # 分页配置 COUNT_DEFAULT = 10 PAGE_DEFAULT = 0 PAY_COUNTDOWN = 1800 # 单位秒 # 屏蔽 sql alchemy 的 FSADeprecationWarning ...
# Copyright 2016-2020 Blue Marble Analytics LLC. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ag...
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
#!/usr/bin/env python # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software...
__author__ = "Suyash Soni" __email__ = "suyash.soni248@gmail.com" import itertools from ....constants.error_codes import DBErrorCode class Error(object): """ Every time error needs to thrown, instance of this class must be used to represent an error. """ def __init__(self, error_constant, *fields, mes...
from django.shortcuts import render from django.contrib.auth.decorators import login_required from .apiv1 import tasks_in_progress from django.http import JsonResponse @login_required def tasks_list(request): return JsonResponse(tasks_in_progress(), safe=False)
""" Add conditions as an empty list if it doesn't exist in the form. This JSON migration is related to: * 0004_formidable_conditions * 0005_conditions_default """ def migrate(data): if 'conditions' not in data: data.setdefault('conditions', []) return data
import time from monitoring_system.drivers.sensors.Sensor import Sensor class SwitchSensor(Sensor): def __init__(self, **kwargs): super().__init__(**kwargs) self.__dict__.update(kwargs) self.pin = self._get_wpi_pin(self.pin) self._register_pins([], [self.pin]) if kwargs['...
from django.contrib import admin from django.contrib.admin import AdminSite from . import models class SuperAdmin(AdminSite): site_header = "Saijal Shakya" site_title = "Super Admin" index_title = "Super Admin - Saijal Shakya" super_admin_site = SuperAdmin(name='super_admin') super_admin_site.register(...
# Copyright (C) 2018-2022 Intel Corporation # SPDX-License-Identifier: Apache-2.0 import numpy as np from openvino.tools.mo.front.common.partial_infer.utils import is_fully_defined from openvino.tools.mo.graph.graph import Node, Graph from openvino.tools.mo.ops.op import Op class ConstantFill(Op): """ Constant ...
class Solution: def searchMatrix(self, matrix, target) -> bool: """ :type matrix: List[List[int]] :type target: int :rtype: bool """ if not matrix: return False row = 0 col = len(matrix[0]) - 1 while row <= len(matrix) - 1 and col...
""" Dataset classes for variable number of speakers Author: Junzhe Zhu """ import numpy as np import torch import torch.utils.data as data from librosa import load from time import time import glob import os import random import json from tqdm import tqdm def load_json(filename): with open(filename) as f: d...
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! import grpc from kikimr.public.api.protos import ydb_rate_limiter_pb2 as kikimr_dot_public_dot_api_dot_protos_dot_ydb__rate__limiter__pb2 class RateLimiterServiceStub(object): """Service that implements distributed rate limiting. To use rate l...
from go import os from go import path.filepath as F import table D ='/tmp/_aphid_test_skiplist_' try: os.RemoveAll(D) except: pass os.Mkdir(D, 0777) fd = os.Create(F.Join(D, 't.001')) print >>fd, ''' # comment +0012345.0{tab}color{tab}red +0012345.0{tab}flavor{tab}lime +0012345.0{tab}size{tab}XL ; # overrides +...
version_info = (4, 0, 2, 'dev') __version__ = ".".join(map(str, version_info))
;; This buffer is for notes you don't want to save, and for Lisp evaluation. ;; If you want to create a file, visit that file with C-x C-f, ;; then enter the text in that file's own buffer. img = Image("./SimpleCV/sampleimages/containment_test.png") b = img.findBlobs() l = img.findLines() c = img.findCorners() cr = img...
import numpy as np def get_state(x, x_dot, theta, theta_dot): """ This function returns a discretized value (a number) for a continuous state vector. Currently x is divided into 3 "boxes", x_dot into 3, theta into 6 and theta_dot into 3. A finer discretization produces a larger state space, but al...
# coding: utf-8 from os import path from setuptools import setup, find_packages NAME = "huaweicloudsdkeip" VERSION = "3.0.67" AUTHOR = "HuaweiCloud SDK" AUTHOR_EMAIL = "hwcloudsdk@huawei.com" URL = "https://github.com/huaweicloud/huaweicloud-sdk-python-v3" DESCRIPTION = "EIP" this_directory = path.abspath(path.dirna...
import sys import math from llvmlite.llvmpy.core import Type from numba.core import types, cgutils from numba.core.imputils import Registry registry = Registry() lower = registry.lower float_set = types.float32, types.float64 def bool_implement(nvname, ty): def core(context, builder, sig, args): assert ...
'''Shared objects for integration testing.''' import os from plaid import Client def create_client(): '''Create a new client for testing.''' return Client(os.environ['CLIENT_ID'], os.environ['SECRET'], os.environ['PUBLIC_KEY'], 'sandbox', ...
import os, glob, sys, logging, math from tqdm import tqdm import numpy as np from .interaction_optical_flow import OpticalFlowSimulator from .obstacles import load_world_obstacle_polygons # Since it is used as a submodule, the trajnetplusplustools directory should be there sys.path.append("../../trajnetplusplustools") ...
import numpy as np import scipy as sp from flatdict import FlatDict from collections import namedtuple from openpnm.io import Dict, GenericIO from openpnm.utils import sanitize_dict, logging logger = logging.getLogger(__name__) class Pandas(GenericIO): r""" Combines all data arrays into a Pandas DataFrame obj...
import json import shutil import os import copy import tempfile from unittest import skipIf from parameterized import parameterized from subprocess import Popen, PIPE, TimeoutExpired from timeit import default_timer as timer import pytest import docker from tests.integration.local.invoke.layer_utils import LayerUtils...
from zerver.lib.test_classes import WebhookTestCase class BuildbotHookTests(WebhookTestCase): STREAM_NAME = "buildbot" URL_TEMPLATE = "/api/v1/external/buildbot?api_key={api_key}&stream={stream}" FIXTURE_DIR_NAME = "buildbot" def test_build_started(self) -> None: expected_topic = "buildbot-he...
#!/usr/bin/env python #fileencoding=utf-8 import time import logging import hashlib from scaff import Scaffold def hash_pwd(pwd, salt): return hashlib.sha1(pwd+'|'+salt).hexdigest()[:16] class Runner(Scaffold): def main(self): logging.info('Start to build index...') self.db.user.ensure_index...
import logging import re import pdb import operator import pprint import mimetypes import flywheel import json import pandas as pd from os import path from pathvalidate import is_valid_filename from pathlib import Path from fw_heudiconv.cli.export import get_nested logger = logging.getLogger('fw-heudiconv-curator') ...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Test get_static_file function. """ # Import future modules from __future__ import absolute_import from __future__ import division from __future__ import print_function # Import built-in modules import os # Import third-party modules from dayu_widgets import CUSTOM_STA...
""" Training Script """ import argparse import distutils.util import os import sys import pickle import resource import traceback import logging from collections import defaultdict import numpy as np import yaml import torch from torch.autograd import Variable import torch.nn as nn import cv2 cv2.setNumThreads(0) # ...
from setuptools import setup setup( name="vimonous", version="0.0.0", description="Venomous file parser powered with Python and Vim", license="MIT", packages=["vimonous"], author="dosisod", url="https://github.com/dosisod/vimonous" )
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may ...
from tests.support.asserts import assert_error, assert_success def get_window_rect(session): return session.transport.send( "GET", "session/{session_id}/window/rect".format(**vars(session))) def test_no_top_browsing_context(session, closed_window): response = get_window_rect(session) assert_erro...
from python_framework import Repository import User @Repository(model = User.User) class UserRepository: def findAll(self) : return self.repository.findAllAndCommit(self.model) def existsByKey(self,key) : return self.repository.existsByKeyAndCommit(key, self.model) def findByKey(self,key...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import math import logging logger = logging.getLogger(__name__) """ IAPWS R4-84(2007) Revised Release on Viscosity and Thermal Conductivity of Heavy Water Substance http://www.iapws.org/relguide/TransD2O-2007.pdf """ def myHW_rhoT_R4(rho, T): """Viscosity as a funct...
from flask import request, abort, jsonify ,url_for, g,flash from . import api from .. import SIGNATURE,CM_NAME import json import requests import logging import os from flask import send_from_directory from app import helper from app import constant from app.api_v1 import errors import socket from . import calculatio...
import unittest from app.models import Pitch, User class PitchTest(unittest.TestCase): def setUp(self): self.user_iano=User(username='ian', password='', email='joseph@gmail.com') self.new_pitch=Pitch(title='iano', description='time is money', category='business', user=self.user_iano) def tearD...
import os from contextlib import contextmanager from django.conf import settings from django.contrib.auth import get_user_model from django.core.files.base import ContentFile from grandchallenge.algorithms.models import Algorithm, AlgorithmImage from grandchallenge.archives.models import Archive, ArchiveItem from gra...
# -*- coding: utf-8 -*- # Generated by Django 1.11.3 on 2017-08-12 05:45 from __future__ import unicode_literals import django.core.validators from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('courses', '0016_coursemember_...
#!/usr/bin/env python from nipype import config config.enable_debug_mode() from arcana.data import InputFilesets # @IgnorePep8 from banana.file_format import nifti_gz_format, text_matrix_format # @IgnorePep8 from banana.study.mri.coregistered import ( # @IgnorePep8 CoregisteredStudy, CoregisteredToMatrixStudy) f...
from abc import abstractmethod from ray.rllib.env import MultiAgentEnv class ValidActionsMultiAgentEnv(MultiAgentEnv): @abstractmethod def __init__(self): super(ValidActionsMultiAgentEnv, self).__init__() self.observation_length = None self.orig_observation_length = None
# -*- coding: utf-8 -*- # pc_type lenovo # create_time: 2019/11/9 15:15 # file_name: 3_1.py import cv2 import numpy as np import matplotlib.pyplot as plt import seaborn as sns import random # 设置中文字体和负号正常显示 plt.rcParams['font.sans-serif'] = ['SimHei'] # 指定默认字体 plt.rcParams['axes.unicode_minus'] =...
import os # DEBUG has to be to False in a production enrironment for security reasons DEBUG = True
from django import forms from django.utils.translation import gettext_lazy as _ from i18nfield.forms import I18nModelForm from pretalx.common.mixins.forms import ReadOnlyFlag from pretalx.mail.context import get_context_explanation from pretalx.mail.models import MailTemplate, QueuedMail from pretalx.person.models imp...
class Solution(object): def isValidSudoku(self, board): """ :type board: List[List[str]] :rtype: bool """ def is_valid(arr): dict = {} tmp = [] for el in arr: if el != '.': tmp.append(el) ...
from core.himesis import Himesis, HimesisPreConditionPatternLHS import uuid class HContract02_CompleteLHS(HimesisPreConditionPatternLHS): def __init__(self): """ Creates the himesis graph representing the AToM3 model HContract02_CompleteLHS """ # Flag this instance as compiled now self.is_compiled = True ...
from . import entry if __name__ == '__main__': entry()
from collections import OrderedDict from functools import partial, reduce from operator import xor from typing import Generator, Sequence, Any from bitarray import bitarray # type: ignore from_bytes = partial(int.from_bytes, byteorder="big") from_bytes_signed = partial(int.from_bytes, byteorder="big", signed=True) ...
""" PySide2 related classes and functions """ # classes from .classes import ( checkColor, DualProgressBar, HorizontalLine, LineOutput, QActionWidget, QComboLineEdit, QFileListWidget, QFormatLabel, QGroupSignal, QMenuWidget, QOutputTextWidget, QProgressIndicator, QP...
import uasyncio as asyncio import utime as time from . import launch # Usage: # from primitives.delay_ms import Delay_ms class Delay_ms: verbose = False def __init__(self, func=None, args=(), can_alloc=True, duration=1000): self.func = func self.args = args self.can_alloc = can_alloc ...
"""CoronaVirus LookUp """ from covid import Covid from userbot.utils import admin_cmd import datetime from telethon import events from telethon.errors.rpcerrorlist import YouBlockedUserError from telethon.tl.functions.account import UpdateNotifySettingsRequest from sql.global_variables_sql import SYNTAX, MODULE_LIST ...
#!/usr/bin/env python import rospy, copy from geometry_msgs.msg import Twist from std_srvs.srv import Trigger, TriggerResponse from pimouse_ros.msg import LightSensorValues class WallStop(): def __init__(self): self.cmd_vel = rospy.Publisher('/cmd_vel', Twist, queue_size=1) self.sensor_values = Li...
# # Copyright 2018 Analytics Zoo Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to...
import pytest from geomdl import ray from geomdl.ray import Ray, RayIntersection def test_ray_intersect(): r2 = Ray((5.0, 181.34), (13.659999999999997, 176.34)) r3 = Ray((19.999779996773235, 189.9998729810778), (19.999652977851035, 180.00009298430456)) t0, t1, res = ray.intersect(r2, r3) assert res !=...
import unittest """ 1.5 One Away There are three types of edits that can be performed on strings: insert a character, remove a character, or replace a character. Given two strings, write a function to check if they are one edit (or zero edits) away. EXAMPLE pale, ple -> true pales, pale -> true pa...
# -*- coding: utf-8 -*- """ Entry points for twindb-backup tool """ from __future__ import print_function import shutil import socket import sys import tempfile import traceback import os # from typing import Union, List, Tuple, AnyStr import click from twindb_backup import ( # setup_logging, LOG, __vers...
from typing import ( Any, ) from aiohttp import web import inspect class ClassRouteTableDef(web.RouteTableDef): def __repr__(self) -> str: return "<ClassRouteTableDef count={}>".format(len(self._items)) def route(self, method: str, path: str, **kwargs: Any): def inner(handler: Any) -> Any: #...
import numpy as np import os import tensorflow as tf import time import json from PIL import Image from object_detection.utils import ops as utils_ops from object_detection.utils import label_map_util THRESHOLD = 0.6 LABEL_PATH = 'object_detection/test1/pascal_label_map.pbtxt' MODEL_PATH = 'object_detection/test1/out...
IS_TEST = True REPOSITORY = 'cms-sw/cmssw' def get_repo_url(): return 'https://github.com/' + REPOSITORY + '/' CERN_SSO_CERT_FILE = 'private/cert.pem' CERN_SSO_KEY_FILE = 'private/cert.key' CERN_SSO_COOKIES_LOCATION = 'private/' TWIKI_CONTACTS_URL = 'https://ppdcontacts.web.cern.ch/PPDContacts/ppd_contacts' TWI...
import asyncio import mock import pytest try: import aionotify except (OSError, ModuleNotFoundError): aionotify = None # type: ignore import typeguard from opentrons import types from opentrons.hardware_control import API from opentrons.hardware_control.types import Axis, OT3Mount from opentrons.hardware_c...
#!/usr/bin/env python3 import sys from datetime import datetime, timedelta import jwt from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives.serialization import load_pem_private_key # Obviously, in a production setting, you would not have checked in the private key or the passw...
from combinations.equal_weight import EqualWeight from combinations.pso_model import PSO from combinations.recursive_method import RecursiveEnsemble import constants as const import pandas as pd import numpy as np def run_combinations(horizon, forecast, forecast_test, data_train, data_out_sample): weights = {'wei...
# -*- coding:UTF-8 -*- class HtmlOutputer(object): def __init__(self): self.datas = [] def collect_data(self, data): if data is None: return self.datas.append(data) def output_html(self): fout = open('output.html', 'w') fout...
class Solution: def countCollisions(self, directions: str) -> int: l = 0 r = len(directions) - 1 while l < len(directions) and directions[l] == 'L': l += 1 while r >= 0 and directions[r] == 'R': r -= 1 return sum(c != 'S' for c in directions[l:r + 1])
"""backoffice URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.10/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class...
from __future__ import absolute_import, division, print_function, unicode_literals import logging import unittest import numpy as np from art.defences.spatial_smoothing import SpatialSmoothing logger = logging.getLogger('testLogger') class TestLocalSpatialSmoothing(unittest.TestCase): def test_ones(self): ...
#!/usr/bin/env python3 # Copyright (c) 2018 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Tests the includeconf argument Verify that: 1. adding includeconf to the configuration file causes the inc...
# Copyright 2011, Google Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the f...
import sys sys.path.append('../') from pathlib import Path import pickle import matplotlib.pyplot as plt from matplotlib.ticker import ScalarFormatter from matplotlib.gridspec import GridSpec import numpy as np from py_diff_pd.common.common import print_info, print_error def format_axes(fig): for i, ax in enumer...
import logging import json from shelvery.factory import ShelveryFactory def lambda_handler(event, context): logger = logging.getLogger() logger.setLevel(logging.INFO) logger.info(f"Received event\n{json.dumps(event,indent=2)}") if 'backup_type' not in event: raise Exception("Expectin...
# Test utils class TestTools(): DIVIDER_LENGTH = 60 def __init__(self): self.total_run_tests = 0 self.num_success = 0 self.test_msg = '' self.test_result = '' self.show_obtained = False def __del__(self): print('\n' + self.show_result_division()) ...
import json import os import docker.client from dagster_celery.config import DEFAULT_CONFIG, dict_wrapper from dagster_celery.core_execution_loop import DELEGATE_MARKER, core_celery_execution_loop from dagster_celery.defaults import broker_url, result_backend from dagster_celery.executor import CELERY_CONFIG from dag...
import sys from collections import Counter sys.stdin = open('input.txt') numTest = int(input()) for x in range(numTest): n = raw_input().strip() b1 = Counter(bin(int(n)))['1'] b2 = Counter(bin(int(n, base=16)))['1'] print b1, b2
import nltk class LearningDictionary(): def __init__(self, sentence): self.words = nltk.word_tokenize(sentence) self.tagged = nltk.pos_tag(self.words) self.buildDictionary() self.buildReverseDictionary() def buildDictionary(self): self.dictionary = {} for (word,...