text
stringlengths
1
927k
# -*- coding: utf-8 -*- # # Copyright (C) 2017 Edgewall Software # All rights reserved. # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. The terms # are also available at http://trac.edgewall.com/license.html. # # This software consists of vo...
''' Single-GPU training. Will use H5 dataset in default. If using normal, will shift to the normal dataset. ''' import argparse import math from datetime import datetime import h5py import numpy as np import tensorflow.compat.v1 as tf tf.disable_v2_behavior() import socket import importlib import os import sys ...
import csv import math from ModelOptions import compute_local_fragility from PostProcessing.SectionGaps import global_DCR_DS1, global_DCR_DS2, global_DCR_DST, demand_capacity_ratio_DS1_matrix, demand_capacity_ratio_DS2_matrix, demand_capacity_ratio_DST_matrix from AnalysisDefinition.TimeHistory import spectral_respons...
import os import glob import pandas as pd game_files = glob.glob(os.path.join(os.getcwd(), 'games', '*.EVE')) game_files.sort() game_frames = [] for game_file in game_files: game_frame = pd.read_csv(game_file, names=['type','multi2','multi3','multi4','multi5','multi6','event']) game_frames.append(game_frame) ...
""" Cumulative coherent 2F ====================== Compute the cumulative coherent F-statistic of a signal candidate. """ import os import numpy as np import pyfstat from pyfstat.helper_functions import get_predict_fstat_parameters_from_dict label = "PyFstat_example_twoF_cumulative" outdir = os.path.join("PyFstat_e...
# coding=utf-8 # Copyright 2021 The Fairseq Authors and the HuggingFace Inc. team. 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/...
from rest_framework import serializers from product.models import Product class ProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields = '__all__' class ProductListSerializer(serializers.ModelSerializer): class Meta: model = Product fields = ('store',)
# -*- coding:utf-8 -*- from django.conf import settings from django.contrib.auth import BACKEND_SESSION_KEY, logout from django.contrib.auth.models import AnonymousUser from django.http import HttpResponse from django.shortcuts import redirect from django.views.generic.base import TemplateView from social_auth.views im...
import os from setuptools import setup __version__ = open(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'VERSION.txt')).readline().strip() setup( name='simservice', version=__version__, description='A library for building simulation services in Python', url='https://github.com/tjsego/simser...
#Foram anotadas as idades e infos de 30 alunos. Faça um Programa que determine quantos alunos com mais de 13 anos # possuem altura inferior à média de altura desses alunos. from random import random,randint alunos = [] for _ in range(30): altura = 0 #zera porque senão altura não entra no laço novamente ida...
#!/usr/bin/env python """ `di_bq.py` is a wrapper around the standard ceda-di tools to help parallelise the processing of files using a batch queue. This tool has two main functions: * Generate lists of files to be processed in individual jobs by the queue * Dispatch archive processing jobs to the batch queue ...
import torch def point_form(boxes): """ Convert prior_boxes to (xmin, ymin, xmax, ymax) representation for comparison to point form ground truth data. Args: boxes: (tensor) center-size default boxes from priorbox layers. Return: boxes: (tensor) Converted xmin, ymin, xmax, ymax form of ...
# The MIT License (MIT) # # Copyright (c) 2018 Mateusz Pusz # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modi...
# Copyright (c) 2020, Apple Inc. All rights reserved. # # Use of this source code is governed by a BSD-3-clause license that can be # found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause import sys from coremltools.models.utils import _python_version from coremltools.models.utils import...
import numpy as np import trax #from trax import layers as tl #from trax.fastmath import numpy as fastnp #from trax.supervised import training # UNIT TEST for UNQ_C1 def test_get_conversation(target): data = {'file1.json': {'log':[{'text': 'hi'}, {'text': 'hello'}, ...
import logging from json import JSONDecodeError from typing import List, Optional, Dict, Union import asks import trio from asks.errors import BadHttpResponse from asks.response_objects import Response from h11 import RemoteProtocolError from .easy_async import EasyAsync, delayed, zip_kw from .common import BadRespon...
# Copyright 2008-2015 Nokia Networks # Copyright 2016- Robot Framework Foundation # # 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 ...
""" Django settings for app project. Generated by 'django-admin startproject' using Django 3.2.6. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ from pathlib imp...
# # 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...
""" Main inputs: (Change for all fields) """ eazypath = '/data2/ken/photoz/eazy-photoz/src/eazy' working_folder = '/data2/ken/photoz/bootes_3as_ext' photometry_catalog = 'Bootes_merged_Icorr_2014a_all_ap3_mags.zs.fits.mod' photometry_format = 'fits' filter_file = 'filter.bootes_mbrown_2014a.res' translate_file = 'bro...
# coding=utf-8 # Copyright 2018 The TF-Agents 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...
from typing import Any, List, Literal, TypedDict from .FHIR_AdverseEvent_Causality import FHIR_AdverseEvent_Causality from .FHIR_Reference import FHIR_Reference from .FHIR_string import FHIR_string # Actual or potential/avoided event causing unintended physical injury resulting from or contributed to by medical care...
#!/usr/bin/env python # -*- coding: utf8 -*- # ============================================================================ # Copyright (c) 2013-2020 nexB Inc. http://www.nexb.com/ - All rights reserved. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in complianc...
# https://deeplearningcourses.com/c/data-science-supervised-machine-learning-in-python # https://www.udemy.com/data-science-supervised-machine-learning-in-python from __future__ import print_function, division from builtins import range, input # Note: you may need to update your version of future # sudo pip install -U ...
import numpy as np import bempp.api import os from bempp.api.operators.boundary import sparse, laplace, modified_helmholtz from .common import calculate_potential_one_surface invert_potential = True def verify_parameters(self): return True def lhs(self): dirichl_space = self.dirichl_space neumann_space...
import glob file_list = glob.glob("data/*.csv") for file_name in file_list: with open(file_name, 'r') as open_file: for inner_line in open_file: if "gender" not in inner_line: print(inner_line.strip())
import logging import sys import time from pyramid.events import NewResponse, NewRequest from pyramid.events import subscriber if sys.version_info[0] < 3: str = basestring log = logging.getLogger(__name__) unlog_pattern = None unlog_route = None authenticated_id = '' @subscriber(NewRequest) def log_request(e...
from PIL import Image import numbers class RandomCrop(object): def __init__(self, size, v): if isinstance(size, numbers.Number): self.size = (int(size), int(size)) else: self.size = size self.v = v def __call__(self, img): w, h = img.size th, tw =...
#------------------------------------------------------------------------------ # # Copyright (c) Microsoft Corporation. # All rights reserved. # # This code is licensed under the MIT License. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentatio...
# Generated by Django 3.0.6 on 2020-08-26 04:50 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='MyFile', fields=[ ('id', models.AutoField(a...
# -*- coding: utf-8 -*- # ----------------------------------------------------------------------------- # Copyright (c) 2009- Spyder Project Contributors # # Distributed under the terms of the MIT License # (see spyder/__init__.py for details) # --------------------------------------------------------------------------...
def swap_case(s): k = [] l = list(s) for i in l: j = "" if i.islower(): j = i.upper() elif i.isupper(): j = i.lower() else: k.append(i) k.append(j) final = ''.join(k) return final if __name__ == '__main__': ...
from contextlib import ExitStack import pytest from plenum.test.helper import create_new_test_node @pytest.fixture(scope="module") def create_node_and_not_start(testNodeClass, node_config_helper_class, tconf, tdir, ...
# Copyright 2013 Pau Haro Negre # based on C++ code by Carl Staelin Copyright 2009-2011 # # See the NOTICE file distributed with this work for additional information # regarding copyright ownership. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with...
def main(): with open('in.txt') as file: card_pubkey, door_pubkey = map(lambda n: int(n), file.read().splitlines()) print('card public key:', card_pubkey) print('door public key:', door_pubkey) print('card loop size:', card_loop_size := get_loop_size(card_pubkey)) print('door loop size:', ...
import sys import argparse import numpy as np from actions import ActionBuilder from game import Game # use_continuous speed action_combinations crouch freelook FALSY_STRINGS = {'off', 'false', '0'} TRUTHY_STRINGS = {'on', 'true', '1'} def bool_flag(string): """ Parse boolean arguments from the command line...
# Generated by Django 3.0.7 on 2022-03-29 07:12 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='test_api', fields=[ ('id', models.AutoField...
""" Support for Wink thermostats, Air Conditioners, and Water Heaters. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/climate.wink/ """ import logging import asyncio from homeassistant.components.wink import WinkDevice, DOMAIN from homeassistant.compone...
A,B,C = map(int, input().split()) print(min(B//A,C))
import os import cv2 import numpy as np class Calibration: def __init__( self, source_images_directory, destination_image_sub_directory, chessboard_shape, logger ): self.source_images_directory = source_images_directory self.destination_image_sub_...
# -*- coding: utf-8 -*- __author__ = 'bars' from io import StringIO import pandas as pd from collections import defaultdict class Bed: """description""" def __init__(self, bed_file, mode='file'): self.bed_file = bed_file self.mode = mode def get_header(self): lines_to_skip = 0 ...
from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import scipy.misc import tqdm import cv2 import torch from nnutils import geom_utils # from kaolin.graphics.dib_renderer.rasterizer import linear_rasterizer # from kaolin.graphics.dib_ren...
# See ./requirements.txt for requirements. import os from jira.client import JIRA from st2reactor.sensor.base import PollingSensor class JIRASensor(PollingSensor): ''' Sensor will monitor for any new projects created in JIRA and emit trigger instance when one is created. ''' def __init__(self, ...
""" Author: Kris Swanson, kriswans@cisco.com Tested with Python 3.6.1 on WIN10 """ import socket import struct import time import sys import multiprocessing import datetime import glob import json from crypto import Crypto as cryp from syslog import syslog from nodemanager import NodeManager as nm from localsearch i...
from constants import * from data import IMAGE_ID from random import randint from actor.skills.base_skill import BaseSkill from util import dice class GrassCutter(BaseSkill): def __init__(self, x=0, y=0, name="grass_cutter"): super().__init__( name=name, image=IMAGE_ID[name], ...
import argparse from src.openbanking_tpp_proxy.proxy import Proxy if __name__ == '__main__': parser = argparse.ArgumentParser(description="Process parametes for certificate enrollment") parser.add_argument('--api_url', type=str, required=True, help='API url needed for certificate inte...
import os from nitrado import Service, initialize_client def set_client(): url = "https://api.nitrado.net/" key = os.getenv('NITRADO_KEY') initialize_client(key, url) def test_services(): set_client() services = Service.all() assert len(services) > 0 def test_logs(): set_client() s...
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Dict, List, Mapping, Optional, Tuple, Union from .. import ...
#!/usr/bin/env python2 # # Distributed under the MIT/X11 software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # from test_framework.mininode import * from test_framework.test_framework import LUASCOINTestFramework from test_framework.util import * import time ''...
# Copyright (c) Meta Platforms, Inc. and affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import logging from typing import Tuple import torch import torch.distributions as dist from beanmachine.ppl.inference.proposer.single_site...
import subprocess print("Installing required packages...") subprocess.check_output(['conda','install','--yes','--file','requirements.txt']) print("Installed requirements") print("Installing openbabel...") subprocess.check_output(['conda','install','--yes','-c','openbabel', 'openbabel']) print("Installed openbabel") pri...
# Example module for Online Python Tutor # Philip Guo # 2013-08-03 # To get the Online Python Tutor backend to import this custom module, # add its filename ('htmlexample_module') to the CUSTOM_MODULE_IMPORTS # tuple in pg_logger.py # To see an example of this module at work, write the following code in # http://pyth...
#!/usr/bin/python # -*- coding:utf-8 -*- import sys import os picdir = os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))), 'pic') libdir = os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))), 'lib') if os.path.exists(libdir): sys.path.append(libdir) import logging from ...
""" Binomial distribution --------------------- """ import mpmath from ..fun import logbinomial __all__ = ['pmf', 'logpmf', 'cdf', 'sf', 'mean', 'var'] def _validate_np(n, p): if p < 0 or p > 1: raise ValueError('p must be in the range [0, 1]') if n < 0: raise ValueError('n must be a nonne...
from pytezos.rpc.node import RpcError class MichelsonBadContractParameter(RpcError, error_id='michelson_v1.bad_contract_parameter'): """ Either no parameter was supplied to a contract with a non-unit parameter type, a non-unit parameter was passed to an account, or a parameter was supplied of the wrong type ...
# Copyright 2019. ThingsBoard # # 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 ...
# -*- coding: utf-8 -*- from __future__ import print_function import warnings from datetime import timedelta import operator import pytest from string import ascii_lowercase from numpy import nan from numpy.random import randn import numpy as np from pandas.compat import lrange, PY35 from pandas import (compat, isn...
from __future__ import absolute_import, division from . import msa_numerics from pydca.fasta_reader import fasta_reader import logging import numpy as np """This module implements Direc Coupling Analysis (DCA) of residue coevolution for protein and RNA sequences using the mean-field algorithm. The final coevolution sc...
class MultiKeyData(object): def __init__(self): self._keys = {} self._values = {} self._links = {} self._index = 0 def __add_item(self, key, value): if key not in self._keys: self._keys[key] = self._index self._values[self._index] = value ...
import base64 import math import platform import tkinter as tk from tkinter import ttk import PIL from PIL import Image, ImageTk, ImageColor, ImageDraw, ImageFilter import hashlib import io def identify_operating_system(): """identify current operating system Returns: (str): 'Windows', 'Linux', or 'D...
# coding=utf-8 # Copyright (c) 2019, NVIDIA CORPORATION. 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 re...
import argparse import math import os import shutil import time import numpy as np from pathlib import Path from ensemble_boxes import * import copy import cv2 import torch import torch.backends.cudnn as cudnn from numpy import random import matplotlib.pyplot as plt from itertools import combinations import random fro...
import requests as r import pandas as pd import time from datetime import datetime import re TOKEN_VK = '23acc95023acc95023acc9504023c092a1223ac23acc9507ef4dc240205bcafea27244d' # vk service token version = 5.101 def get_members(group_id): try_count = 0 while try_count < 2: try: respon...
import matplotlib.pyplot as plt from matplotlib import gridspec import numpy as np in_data = "run_6/run_6_e2_phot_prf_limit.dat" in_model = "run_6/run_6_e2_phot.res" out_file = "run_6/plot_eb234840_v8.png" kwargs = {'color': 'red', 'marker': '.', 'ls': 'none'} x_lim = [7500., 7528.] y_lim = [-4000., 500.] kwargs_1 ...
#!/usr/bin/python3 import argparse import pandas as pd import numpy as np import warnings warnings.filterwarnings('ignore') from joblib import delayed,Parallel import os def whichKeep(est_params): kon = np.array(est_params)[:,0] koff = np.array(est_params)[:,1] ksyn = np.array(est_params)[:,2] which_ko...
import time import cv2 import sys import os,os.path path = sys.argv[1] data_path=sys.argv[2] fpsLimit = 0.8 index = 0 currentFrame=0 intframe =0 startTime = time.time() # Playing video from file: cap = cv2.VideoCapture(str(path)) try: if not os.path.exists('data_path'): os.makedirs('data_path') exce...
import subprocess import warnings import os.path as osp import os import numpy as np # Note: libffm doesn't handle relative paths very well, hence abspath used. class FFM: def __init__(self, train_binary_path, predict_binary_path, model_path=None): self.train_binary_path = osp.abspath(train_binary_path) ...
from smtplib import SMTP from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from jinja2 import Environment, FileSystemLoader import os from_email = 'krbdashboard@outlook.com' password = 'ArushiSinghal' env = Environment( loader=FileSystemLoader('./templates/')) def get_contacts(...
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union from ... import _utilities, _tables __a...
from django.utils.functional import cached_property from drf_spectacular.types import OpenApiTypes from drf_spectacular.utils import extend_schema, OpenApiExample, OpenApiParameter from rest_framework.exceptions import NotFound from rest_framework.generics import ( ListCreateAPIView, RetrieveUpdateAPIView, ...
#!/usr/bin/env python from run_hmmer import RunHmmer from Bio import SearchIO import pandas as pd import collections import random import tempfile import argparse import pprint import glob import sys class FindDeathDomains(RunHmmer): def __init__(self, seqfile, dd_hmm_path, *hmmersearch_args): """ Sub...
import os import sys from sqlalchemy import Column, ForeignKey, Integer, String from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import relationship from sqlalchemy import create_engine from passlib.apps import custom_app_context as pwd_context import random, string from itsdangerous import(T...
# Licensed under a 3-clause BSD style license - see LICENSE.rst from collections import Counter import pytest import numpy as np from numpy.testing import assert_allclose from astropy import units as u from astropy.coordinates import SkyCoord, Angle from astropy.table import Table from ...utils.testing import assert_qu...
import numpy as np from pdb import set_trace as T import nmmo from nmmo.systems import ai, equipment from nmmo.lib import material from nmmo.systems.skill import Skills from nmmo.systems.achievement import Diary from nmmo.entity import entity class Player(entity.Entity): def __init__(self, realm, pos, agent, colo...
from typing import (Any, Union, Type) # noqa: F401 from newchain_keys.datatypes import ( LazyBackend, PublicKey, PrivateKey, Signature, ) from newchain_keys.exceptions import ( ValidationError, ) from newchain_keys.validation import ( validate_message_hash, ) # These must be aliased due to a...
# Copyright The OpenTelemetry 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 in ...
import numpy as np from tqdm import tqdm from gradient import Gradient class LogisticRegression: def __init__(self, type, mu, gradient_param, data, d=100, theta=None): if theta is None: self.theta = np.random.rand(d) * 2 - 1 else: self.theta = theta self.type = ty...
""" Python program to search for an element in the linked list using recursion """ class Node: def __init__(self, data): self.data = data self.next = None class Linked_list: def __init__(self): self.head = None self.last_node = None def append(self, data): if s...
import pytest from pytest_mock import MockerFixture from pystratis.api.federation.responsemodels import * from pystratis.api.federation import Federation from pystratis.core.networks import StraxMain, CirrusMain def test_all_strax_endpoints_implemented(strax_swagger_json): paths = [key.lower() for key in strax_sw...
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
# Copyright The PyTorch Lightning team. # # 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 i...
import pytest import json class TestRbdMirrors(object): @pytest.mark.no_docker def test_rbd_mirror_is_installed(self, node, host): assert host.package("rbd-mirror").is_installed def test_rbd_mirror_service_enabled_and_running(self, node, host): service_name = "ceph-rbd-mirror@rbd-mirror....
# # Copyright (c) nexB Inc. and others. All rights reserved. # ScanCode is a trademark of nexB Inc. # SPDX-License-Identifier: Apache-2.0 # See http://www.apache.org/licenses/LICENSE-2.0 for the license text. # See https://github.com/nexB/scancode-toolkit for support or download. # See https://aboutcode.org for more in...
# -*- coding: utf-8 -*- ''' Use `Varstack <https://github.com/conversis/varstack>`_ data as a Pillar source Configuring Varstack ==================== Using varstack in Salt is fairly simple. Just put the following into the config file of your master: .. code-block:: yaml ext_pillar: - varstack: /etc/varst...
t = int(input()) for t in range(t): m,d=map(int,input().split()) l = list(map(int,input().split()))
# Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html # useful for handling different item types with a single interface from itemadapter import ItemAdapter class News163SpiderPipeline: fp = None ...
import sys import os.path from PyQt5 import QtWidgets, uic from PyQt5.QtWidgets import QApplication, QTableWidgetItem from Crypto.Cipher import AES import json from constants import FILE_NAME, KEY_ENCODING from PwWindow import PwWindow # -*- coding: utf-8 -*- """ Created on Fri Nov 17 13:53:56 2017 @author: seitz ""...
# Generated by Django 2.2.12 on 2020-07-24 04:20 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('db_data', '0017_notice'), ] operations = [ migrations.AlterField( model_name='officer', name='officer_since', ...
import numpy as np import os.path from struct import pack, unpack from io import BytesIO def header_tuple_dict(tuple_in): return { 'shape': tuple_in[0], 'fortran_order': tuple_in[1], 'descr': np.lib.format.dtype_to_descr(tuple_in[2]) } def has_fortran_order(arr): return not arr.fla...
from .prepack import *
from ScautEvent.client import EventClient from ScautEvent.common import Event client = EventClient("localhost", 5000) client.listeners["message"] = print client.start() while True: message = input() event = Event("message", message) client.push(event)
''' ''' # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License");...
"""Tests for distutils.command.bdist.""" import os import unittest from test.support import run_unittest import warnings with warnings.catch_warnings(): warnings.simplefilter('ignore', DeprecationWarning) from distutils.command.bdist import bdist from distutils.tests import support class BuildTestCase(su...
def conv_to_str(o): if isinstance(o, str): # Remove initial "u" chars before strings # if no Unicode in them if possible try: o = str(o) except: o = str(o) elif isinstance(o, (list, tuple)): is_tuple = isinstance(o, tuple) o = [conv_to_str...
# flake8: noqa from ocpp_d.v16.enums import * def test_authorization_status(): assert AuthorizationStatus.accepted == "Accepted" assert AuthorizationStatus.blocked == "Blocked" assert AuthorizationStatus.expired == "Expired" assert AuthorizationStatus.invalid == "Invalid" assert AuthorizationStatu...
import collections import re class Solution(object): def mostCommonWord(self, paragraph, banned): """ :type paragraph: str :type banned: List[str] :rtype: str """ paragraph = re.findall(r"\w+", paragraph.lower()) count = collections.Counter(x for x in paragrap...
# Licensed under a 3-clause BSD style license - see LICENSE.rst # -*- coding: utf-8 -*- from __future__ import absolute_import, division, unicode_literals, print_function """ This file contains utilities to generate test repositories. """ import datetime import io import os import threading import time import six im...
__author__ = 'zwan145' import sys, os import numpy from utils import * ## This script implements mesh convergence for the cantilever problem. # It modifies the problem1_tricubic.py script for each mesh resolution # and calls the python script for each mesh resolution. # It then reads out the 2PK fibre stress for the ...
# -*- coding: utf-8 -*- # Copyright 2014-2016 OpenMarket Ltd # # 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 applicab...
import pickle import collections import json import sys import argparse import pathlib import time ROOT_PATH = pathlib.Path(__file__).parents[1].as_posix() trie = pickle.load(open( ROOT_PATH + "/dumps/trie.p", "rb")) catMap = pickle.load(open(ROOT_PATH + "/dumps/catMap.p", "rb")) category = json.load(open(ROOT_PATH +...