content
stringlengths
5
1.05M
from six import assertRegex from . import * class TestUserArgs(IntegrationTest): def __init__(self, *args, **kwargs): IntegrationTest.__init__( self, os.path.join(examples_dir, '10_custom_args'), configure=False, *args, **kwargs ) def test_build_default(self): ...
"""This module collects several utility funictions we found useful at HUDORA. Nothing special in there. Consider it BSD Licensed. """ from __future__ import unicode_literals __revision__ = "$Revision$"
from LogDecoders import * class McuLogDecoder(DebugLogDecoder): def __init__(self, dev_name, filter_dict, config): super(McuLogDecoder, self).__init__(dev_name, filter_dict) self.mcu_decode_output_folder = './mcu_log_files/' self.filter_out_count = 0 # Record the discarded log count ...
from Bio import SeqIO from Bio.SeqRecord import SeqRecord from Bio.Seq import Seq import os, sys import argparse import re parser = argparse.ArgumentParser(description='Mask degenerate sites in alignment.') parser.add_argument("--alignment", type = str, help="sequence(s) to be used, supplied as FASTA files", required=...
from .base import * from .base import env # GENERAL # ------------------------------------------------------------------------------ # https://docs.djangoproject.com/en/dev/ref/settings/#debug DEBUG = True # https://docs.djangoproject.com/en/dev/ref/settings/#secret-key SECRET_KEY = env('DJANGO_SECRET_KEY') # https:...
#!/usr/bin/env python3 import sys sys.setrecursionlimit(3000) # ----- # This section is just used to implement tail-recursion. # You probably don't need to reverse this but you can try if you want ;p class TR(Exception): SEEN = [] def __init__(self, key, args, kwargs): self.key = key self...
# # @lc app=leetcode id=82 lang=python3 # # [82] Remove Duplicates from Sorted List II # # @lc code=start # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def deleteDuplicates(self, head: ListNode) -> ListNode: ...
import sys # These are required libraries for using TensorFlow with a GPU sys.path.append("C:/Users/Jonathan/AppData/Local/Programs/Python/Python37/Lib") sys.path.append("C:/Program Files/NVIDIA GPU Computing Toolkit/CUDA/v10.1/bin") sys.path.append("C:/cuda/bin") import os import csv import tensorflow as tf # This ...
import unittest from src.parsing import IncrementalParser class IncrementalParserTests(unittest.TestCase): def test_incremental_parser(self): ip = IncrementalParser('some 50 users') self.assertEqual(ip.extract('(\w+)\s*?(\d+)'), ['some', '50']) self.assertEqual(ip.text(), 'users') ...
#!/usr/bin/python # -*- coding: utf-8 -*- # ====================================================================== # Copyright 2017 Julien LE CLEACH # # 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 Lice...
from life import random_state, get_next_state import numpy as np if __name__ == "__main__": test_state1 = np.array([[0, 0, 0], [0, 0, 0], [0, 0, 0]]) test_state2 = [[1, 1, 1], [0, 0, 1], [1, 1, 1]] test_state3 = np.array([[1, 0, 1, 0], [0, 0, 1, 0], [0, 1, 1, 0]]) correct_state1 = [[0, 0, 0], [0, 0, 0...
# 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...
# import networkx as nx from .transition import Transition class ShapeAutomaton: def __init__(self): self.locations = set() self.transitions = set() self.initial_locations = set() self.final_locations = set() # self.parameters = set() def deepcopy_own(self): c...
### Interpolating bad channels ### import os from copy import deepcopy import numpy as np import mne sample_data_folder = mne.datasets.sample.data_path() sample_data_raw_file = os.path.join(sample_data_folder, 'MEG', 'sample', 'sample_audvis_raw.fif') raw = mne.io.read_raw_fif(samp...
from enum import Enum class ConnectorTypes(Enum): MSSQL = 1 ORACLE = 2 POSTGRESQL = 3 EXCEL = 4 CSV = 5 Kafka = 6 MYSQL = 7 Impala = 8 Soap = 9 SqLite = 10
# coding=utf-8 import pytest from mockito import expect import elib_wx @pytest.mark.weather def test_weather_from_icao(with_db): icao = 'EBBR' expect(elib_wx.avwx.metar).fetch(icao).thenReturn('raw metar str') expect(elib_wx.avwx.metar).parse(icao, 'raw metar str').thenReturn(('metar data', 'metar units...
from typing import ( Type, ) from eth.rlp.blocks import BaseBlock from eth.vm.forks.frontier import ( FrontierVM, ) from eth.vm.state import BaseState from .blocks import NogasBlock from .headers import ( compute_nogas_difficulty, configure_nogas_header, create_nogas_header_from_parent, ) from .st...
import csv from pymongo import MongoClient client = MongoClient() db = client.gallery user_collection = db.users wallet_count_greater = 0 wallet_count_to_amount = {} while True: count = user_collection.count_documents( {"addresses.{}".format(wallet_count_greater): {"$exists": True}} ) amount = co...
#!/usr/env/python3 import random from util import gist, playlist from util.spotify import get_spotify_client lofi = { "name": "lofi", "id": "5h9LqGUUE4FKQfVwgAu1OA", "backup": "31k9ZXIfUi9v5mpbfg6FQH", "base": "5adSO5spsp0tb48t2MyoD6", } japan = { "name": "japan", "id": "6Cu6fL6djm63Em0i93IRUW...
from six.moves import UserDict import types from ._registry import register_output from .base_output import OutputInterface class GreedyDict(UserDict, object): def __setitem__(self, key, value): if isinstance(value, types.GeneratorType): value = [val for val in value] super(GreedyDict...
import autolens as al class TestPipelineGeneralSettings: def test__hyper_galaxies_tag(self): general = al.setup.General(hyper_galaxies=False) assert general.hyper_galaxies_tag == "" general = al.setup.General(hyper_galaxies=True) assert general.hyper_galaxies_tag == "_galaxies" ...
r""" Homology :mod:`homology` ======================== Tools for "symmetrizing" a period matrix. There exists a symplectic transformation on the period matrix of a real curve such that the corresponding a- and b-cycles have certain transformation properties until the anti-holomorphic involution on said Riemann surfac...
try: from sia.sia import Sia except ImportError: from sia import Sia __authors__ = 'Dmytro Striletskyi, Alexander Ruban' __email__ = 'dev@essentia.one' __version__ = '0.0.1a0'
# Copyright 2015 VMware, Inc. # 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 a...
import logging import random import time from lib.membase.helper.cluster_helper import ClusterOperationHelper from lib.remote.remote_util import RemoteMachineShellConnection from .newtuq import QueryTests from couchbase_helper.cluster import Cluster from couchbase_helper.tuq_generators import TuqGenerators from couchb...
from glob import glob from os.path import join, basename from typing import Dict, Any class TkdndEvent(object): """ see http://www.ellogon.org/petasis/tcltk-projects/tkdnd/tkdnd-man-page for details on the fields The longer attribute names (action instead of %A) were made up for this API. No...
from __future__ import print_function from __future__ import absolute_import from __future__ import division from builtins import str from builtins import range from . import MultipleSplinesFunction from . import SplineFunction from . import Point from . import Axis import numpy as np class GradeableFunction(MultipleS...
from __future__ import print_function import os import shutil import sys import stat from . import webext def setup_parser(parser): parser.what_group.add_argument('--firefox', action='store_true', help="Install Firefox addon.") firefox_group = parser.add_argument_group('Firefox options') firefox...
import numpy as np from multiagent.core import World, Agent, Landmark, Border from multiagent.scenario import BaseScenario class Scenario(BaseScenario): def make_world(self): world = World() # set any world properties first world.dim_c = 2 num_agents = 6 num_land...
from __future__ import print_function import os.path from tracker import KalmanTracker, ORBTracker, ReIDTracker from imutils.video import WebcamVideoStream import numpy as np import cv2 from tracker_utils import bbox_to_centroid import random import colorsys from human_detection import DetectorAPI import face_recogniti...
import json from sendinblue.client import Client api = Client('xjTqIa43VmQ0GnyX') data = api.get_forms() # data = api.get('scenarios/getForms') # data = api.get_list(6) print(json.dumps(data)) # print('\n') # to retrieve all campaigns of type 'classic' & status 'queued' # data = { "type":"classic", # "status":"que...
import inspect import re import types import pymlconf from . import statuses, static from .request import Request from .response import Response class Application: __requestfactory__ = Request __responsefactory__ = Response builtinsettings = ''' debug: true cookie: http_only: false s...
# coding=utf-8 """replace feature tests.""" from pytest_bdd import ( scenario, then, when, ) from openshift.dynamic.exceptions import NotFoundError @scenario('replace.feature', 'Replace a resource that does not exist') def test_replace_a_resource_that_does_not_exist(): """replace a resource that doe...
''' Image Preprocessing script. Converts image data to numpy array with each image as 128*128 in size ''' from PIL import Image import numpy as np import os def load_data(root): img = [] label = [] for image in os.listdir(root): im = Image.open(os.path.join(root,image)) im = im.resize((128,...
import disnake, youtube_dl import src.core.embeds as embeds import src.core.functions as funcs from disnake.ext import commands prefix = funcs.get_prefix() class Music(commands.Cog): def __init__(self, bot: commands.Bot): self.bot = bot @commands.group(invoke_without_command=True, description="Conne...
import sys sys.path.append('.') sys.path.append('..') sys.path.append('../../') sys.path.append('../../../') import numpy import os import pandas from sklearn.model_selection import train_test_split from environment import DATA_DIR CAPTIONS_FILE = "text_descriptions.csv" SCORES_FILE = "scores_v2.csv"...
from flask import jsonify, request from web.models import Pastebin from web.api import bp @bp.route("/pastebins/<int:id>", methods=["GET"]) def get_pastebin(id): """ Returns pastebin with given id """ return jsonify(Pastebin.query.get_or_404(id).to_dict()) @bp.route("/pastebins", methods=["GET"]) ...
from pandas.core.dtypes.dtypes import register_extension_dtype from .base import NumpyExtensionArray, NumpyFloat32ExtensionDtype @register_extension_dtype class StandardDeviationDtype(NumpyFloat32ExtensionDtype): """Dtype for standard deviation of observables: J, F, D or other""" name = 'Stddev' mtztype = ...
from abc import ABCMeta, abstractmethod from enum import Enum class LoadableTypeEnum(Enum): Achievement = "Achievement" Character = "Character" Guild = "Guild" GuildUpgrade = "GuildUpgrade" Item = "Item" ItemStat = "ItemStat" Mastery = "Mastery" MiniPet = "MiniPet" Skill = "Skill" ...
# Copyright (c) Microsoft. All rights reserved. # Licensed under the MIT license. See LICENSE.md file in the project root # for full license information. # ============================================================================== from .. import cntk_py def map_if_possible(obj): from cntk.ops.variables import ...
"""Simple implementation of double linked lists with sentinels. """ class Node: """Implemetation of a list node. """ def __init__(self, data=None, next=None, prev=None): """Init node object. Parameters: data (...): Data that is stored in this node next (Node): Referen...
import dataclasses from docarray import DocumentArray from jina import Executor, Flow, requests def test_executor_dataclass(): @dataclasses.dataclass class MyDataClassExecutor(Executor): my_field: str @requests(on=['/search']) def baz(self, docs, **kwargs): for doc in doc...
# 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 ...
from setuptools import find_packages, setup setup( name="torch_metrics", version="1.1.7", description="Metrics for model evaluation in pytorch", url="https://github.com/chinokenochkan/torch-metrics", author="Chi Nok Enoch Kan @chinokenochkan", author_email="kanxx030@gmail.com", packages=fin...
import requests import sys def banner(): print (" .-----------------------------. ") print (" | Hi Hackers | ") print ("| Tool : f1nd0d3 |") print (" | Author : @karthi_the_hacker| ") print (" | Jai Hind | ") print (" '...
# Copyright 2021 Huawei Technologies Co., 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 applicable law or agree...
import os from gaesessions import SessionMiddleware __author__ = 'rob' def webapp_add_wsgi_middleware(app): app = SessionMiddleware(app, cookie_key="\x77\xcb\xef~\x83\x12\xbev\xfeZ\x1aG\xb9^\x89:\xf8\x7f+Y+\x15\x91\xe8\x985\xd9aHY\xf1x\x99]'\xd3\xb2\x13\xa4\xc3\x92\xa50\xae\xb8\x90\xbb(...
import time import collections class Structure(object): def __init__(self, data, api): self.api = api self.structure_id = data.id_ self.structure_name = data.attributes['name'] self.refresh() def refresh(self): structure_state = self.api.refresh_attributes('structures'...
from crescent.core import Resource from .constants import ResourceRequiredProperties class ApiMapping(Resource): __TYPE = "AWS::ApiGatewayV2::ApiMapping" def __init__(self, id: str): super(ApiMapping, self).__init__( id=id, type=self.__TYPE, required_properties=Res...
import gym import gym_gobang env=gym.make('Gobang-v0') env.play('single') #env.play('dual')
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Nov 3 12:28:37 2019 @author: leewayleaf """ def main(): print("Hello mannieeeeeee") # -------------------------------------- # if __name__ == "__main__": main()
class FCore: """Provides the basis for a functionality core with default implementations.""" def __init__(self, bot): self.bot = bot def get_commands(self) -> dict: """Return a dictionary of all commands and their corresponding callbacks.""" return dict() def terminal_cont...
import json from sqlalchemy.ext.declarative import DeclarativeMeta class JsonEncoder(json.JSONEncoder): # @staticmethod # def to_dict(obj): # if isinstance(obj.__class__, DeclarativeMeta): # # an SQLAlchemy class # fields = {} # for field in [x for x in dir(obj) i...
# app4.py import numpy as np import pandas as pd import altair as alt import plotly.express as px import plotly.graph_objs as go import pickle as pkle import os.path import streamlit as st def app(): st.title('Writeup') st.write('We created several different visualizations of the data set from both a mac...
from __future__ import absolute_import, division, print_function import os import numpy as np from vivarium.library.units import units from vivarium.core.process import Process from vivarium.core.composition import ( simulate_process_in_experiment, plot_simulation_output, PROCESS_OUT_DIR, ) NAME = 'gro...
"""The mikettle component."""
import sys import numpy as np import pandas as pd import matplotlib.pyplot as plt def normalizing(matrix, k): for i in range(k): mean = np.mean(matrix[:, i]) std = np.std(matrix[:, i]) matrix[:, i] = (matrix[:, i] - mean) / std def fit(learning_rate, trials): coefficien...
#!/usr/bin/env python # pylint: disable=no-value-for-parameter from jumpscale.loader import j from jumpscale.clients.stellar.exceptions import NoTrustLine,TemporaryProblem import jumpscale import click import time import stellar_sdk from requests.exceptions import ConnectionError _ASSET_ISUERS = { "TEST": { ...
# import necessary modules from discord.ext import commands # creates a bot instance with "$" as the command prefix bot = commands.Bot("$") TOKEN = "TOKEN" # ^^^^^^^ FILL IN THIS! This is the generated token for your bot from the Discord Developer Page # a command in discord.py is <command-prefix><command-na...
from django.core.exceptions import ImproperlyConfigured try: from django.contrib.gis.db import models except ImproperlyConfigured: from django.db import models class DummyField(models.Field): def __init__(self, dim=None, srid=None, geography=None, *args, **kwargs): super(DummyField, se...
# This is a sample Python program that trains a simple TensorFlow California Housing model. # This implementation will work on your *local computer* or in the *AWS Cloud*. # To run training and inference *locally* set: `config = get_config(LOCAL_MODE)` # To run training and inference on the *cloud* set: `config = get_c...
import unittest import os import test PEM_FILEPATH = os.path.join(os.path.abspath('.'), 'forwarders.pem') def forwarders(*args): return test.scloud("forwarders", *args) class TestForwarders(unittest.TestCase): def setUp(self): # retrieve the selected tenant name code, self.tname, _ = test...
# -*- coding: utf-8 -*- """ This modules provides most core features of PyAlaOCL. It defines the various functions and classes that constitutes the OCL library. """ #import setup #__version__ = setup.getVersion() import logging log = logging.getLogger(__name__) __all__ = ( 'floor', 'isUndefined', 'ocl...
import os import dj_database_url import raven from raven.exceptions import InvalidGitRepository PROJECT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) BASE_DIR = os.path.dirname(PROJECT_DIR) DEBUG = False if 'SECRET_KEY' in os.environ: SECRET_KEY = os.environ['SECRET_KEY'] if 'ALLOWED_HOSTS...
''' Given an array of integers, find two numbers such that they add up to a specific target number. The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based...
import sys from pathlib import Path import warnings from io import StringIO import mypythontools mypythontools.tests.setup_tests() import mylogging from help_file import info_outside, warn_outside, traceback_outside, warn_to_be_filtered from conftest import logs_stream, setup_tests setup_tests() ...
#!/usr/bin/python # -*- coding utf-8 -*- # # Ausnahme - Klassen von agla # # # This file is part of agla # # # Copyright (c) 2019 Holger Böttcher hbomat@posteo.de # # # Licensed under the Apache License, Ve...
import json def test_add_project_check_with_soap(app, data_project): project = data_project old_projects = app.soap.get_project_list(app.config["webadmin"]["username"], app.config["webadmin"]["password"]) app.session.ensure_login("webadmin") app.project.add(project) new_projects = app.soap.get_pro...
#!/usr/bin/env python 3 ############################################################################################ # # # Program purpose: Counts characters at same position in a given string (lower and # # ...
''' Author: Jason.Parks Created: April 19, 2012 Module: common.perforce.__init__ Purpose: to import perforce ''' print "common.perforce.__init__ imported"
class Subclass(Behave): def once(self): print '(%s)' % self.name subInstance = Subclass("Queen Bee") subInstance.repeat(3)
# _*_ coding:utf-8 _*_ # __author__ = 'JiangKui' # __date__ = '2020/11/23 9:51 上午' """这个文件放入口函数""" from yaml import load, Loader def load_access_conf(conf=""): """ 读取配置文件 :param file_name: :return: """ file = open(conf) return load(file, Loader=Loader) # 传入绝对路径 config_dict = load_access_c...
from googletrans import Translator import sys translator = Translator() translation = translator.translate(sys.argv[1], dest=sys.argv[2]) text = translation.text.encode('utf8') sys.stdout.buffer.write(text)
from util import database, toolchain, bitdiff with database.transact() as db: for device_name, device in db.items(): package, pinout = next(iter(device['pins'].items())) for macrocell_name, macrocell in device['macrocells'].items(): if macrocell['pad'] not in pinout: pr...
from django.urls import path, re_path from django.contrib.auth.decorators import login_required from apps.user.views import RegisterView, ActiveView, LoginView, CenterInfoView, CenterOrderView, CenterSiteView, LogoutView urlpatterns = [ path('register', RegisterView.as_view(), name='register'), # 用户注册 r...
# -*- coding: utf-8 -*- ############################################################################### # # CSVToXLS # Converts a CSV formatted file to Base64 encoded Excel data. # # Python versions 2.6, 2.7, 3.x # # Copyright 2014, Temboo Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you ...
import setuptools def _requirements(): return ["http","urllib"] def _test_requirements(): return ["http","urllib"] setuptools.setup( name="chatbotweb", version="0.2.4", author="Yoshiki Ohira", author_email="ohira.yoshiki@irl.sys.es.osaka-u.ac.jp", description="Automatic generation of web...
#imports import numpy as np import skimage.draw as draw import math import matplotlib.pyplot as plt import random import imageio import skvideo skvideo.setFFmpegPath("C:/ffmpeg/bin") import skvideo.io class FaceCreator(object): #initialize the variables def __init__(self, ImageSize, FaceSize = 3, Subar...
import numpy as np import re import string import pandas as pd corpus = """ Simple example with Cats and Mouse Another simple example with dogs and cats Another simple example with mouse and cheese """.split("\n")[1:-1] # clearing and tokenizing l_A = corpus[0].lower().split() l_B = corpus[1].lower().split() l_C...
# 6-1 アンダーサンプリングによる不均衡データの調整 # §4, 5と同様の方法で実現可能 # 偏りのないランダムサンプリングを実現するためには、 # 事前にデータをクラスタリングし、作成されたクラスタごとにサンプリングする # 貴重なサンプル数を減らすことになるので、なるべく使わないようにする # 6-2 オーバーサンプリングによる不均衡データの調整 # True/False間で極端なデータ量の差がある場合、それを調整する必要がある # SMOTEの実装→imblearnライブラリを使うのがシンプルで使いやすい from preprocess.load_data.data_loader import load_product...
import timeit import numpy as np from bingo.SymbolicRegression.AGraph.AGraphCrossover import AGraphCrossover from bingo.SymbolicRegression.AGraph.AGraphMutation import AGraphMutation from bingo.SymbolicRegression.AGraph.AGraphGenerator import AGraphGenerator from bingo.SymbolicRegression.AGraph.ComponentGenerator \ ...
# coding: utf-8 from __future__ import unicode_literals import pytest def test_ml_tokenizer_handles_long_text(ml_tokenizer): text = """അനാവശ്യമായി കണ്ണിലും മൂക്കിലും വായിലും സ്പർശിക്കാതിരിക്കുക""" tokens = ml_tokenizer(text) assert len(tokens) == 5 @pytest.mark.parametrize("text,length", [("എന്നാൽ അച്ച...
""" Script that scans a list of IPs to see which support TCP Fast Open. Done using scapy and by looking for the fast open option to be sent in the SYN ACK from the server. Requires sudo to run scapy. """ __author__ = "Jacob Davis as part of research at imaal.byu.edu" from scapy.all import sr1 from scapy.layers.inet i...
"""Manage AWS policies.""" import copy import json import math import pathlib import re import uuid from typing import Dict, Generator, List, Union from xdg import xdg_cache_home from wonk import aws, exceptions, optimizer from wonk.constants import ACTION_KEYS, JSON_ARGS, MAX_MANAGED_POLICY_SIZE, PolicyKey from won...
from pymongo import MongoClient from datetime import datetime client = MongoClient("mongodb+srv://doodko:fyyeirf1008@evo-python-lab-2022.iow5y.mongodb.net/PyLab?retryWrites=true&w=majority") db = client['PyLab'] friends = db['friends'] def add_new_friend(name): friend = {'name': name, 'date': dateti...
def add(w,y): w=list(w) y=list(y) k=[0]*32 c=[0]*32 #print w[31] if w[31]=='1' and y[31]=='1': c[31]='0' k[30]='1' elif w[31]=='0'and y[31]=='0': c[31]='0' k[30]='0' else: c[31]='1' k[30]='0' for i in range(31): ...
# -*- coding: UTF-8 -*- import json from jsonpath import jsonpath import config from awesome.utils.get_content import send_request from awesome.utils.operation_to_mysql import OsuMySQL def get_osu_id(user_id): """ 根据qq号查询osu的id :param user_id: qq号 :return: osu_id, mode """ sql_str = "select ...
# -*- coding: utf-8 -*- import datetime import urllib import scrapy from scrapy.spiders.init import InitSpider from scrapy import Selector from scrapy_splash import SplashRequest from spider.consts import DOWNLOADER_MIDDLEWARES_HTTP_PROXY_OFF, MYSQL_ITEM_PIPELINES from spider.items import SpiderLoaderItem, NovelNoberu...
import spacy from spacy.tokens import Token nlp = spacy.blank("en") # Define the getter function that takes a token and returns its reversed text def get_reversed(token): return token.text[::-1] # Register the Token property extension "reversed" with the getter get_reversed Token.set_extension("reversed", gette...
import pickle import socket import _thread from scripts.multiplayer import game, board, tetriminos server = "192.168.29.144" port = 5555 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: s.bind((server, port)) except socket.error as e: print(e) s.listen() print("Waiting for connection") connected ...
import warnings import matplotlib.pyplot as plt import mmcv import torch from mmcv.parallel import collate, scatter from mmcv.runner import load_checkpoint from mmdet.core import get_classes from mmdet.datasets.pipelines import Compose from mmdet.models import build_detector from mmdet.ops import RoIAlign, RoIPool ...
from abc import ABC, abstractmethod from dataclasses import dataclass from typing import Tuple, Optional, ClassVar @dataclass(eq=False, repr=False, frozen=True) class StringTreeNode(ABC): """ A Abstract class that can be inherited to build delimited strings. By subclassing DotStringTree, one can design a DSL de...
from confluent_kafka import TopicPartition from confluent_kafka.admin import ( BrokerMetadata, GroupMember, GroupMetadata, PartitionMetadata, TopicMetadata, ) from kaskade.kafka.models import Broker, Cluster, Group, Partition, Topic from tests import faker def random_broker(id=faker.pyint()): ...
import sys import subprocess import importlib import argparse import torch def parse_args(): a = argparse.ArgumentParser() a.add_argument('--batch-dim', type=int, default=8) a.add_argument('--height-dim', type=int, default=300) a.add_argument('--width-dim', type=int, default=300) a.add_argument('-...
# BOJ 3079 입국심사 import sys sys.stdin = open("../input.txt", "r") input = sys.stdin.readline def check(mid): cnt = 0 for i in range(n): cnt += mid // arr[i] return True if cnt >= m else False n, m = map(int, input().split()) arr = [int(input()) for _ in range(n)] arr.sort() start = 1 end = arr...
# Copyright 2017 Aaron Barany # # 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,...
import time words = input('Please input the words you want to say!:') #例子:words = "Dear lili, Happy Valentine's Day! Lyon Will Always Love You Till The End! ? Forever! ?" for item in words.split(): #要想实现打印出字符间的空格效果,此处添加:item = item+' ' letterlist = []#letterlist是所有打印字符的总list,里面包含y条子列表list_X for y in rang...
import logging from logging.config import dictConfig from os import name from configs import StaticConfigs from configs.configs import base_url,ds_contribution_endpoint,model_bm_contribution_endpoint,ds_search_list_endpoint from utils.notifierutils import NotifierUtils from repository import NotifierRepo log = lo...
import collections, os, sys import numpy as np import matplotlib import matplotlib.pyplot as plt from scipy.special import erf import scipy.interpolate fontsize = 11/1.4 latex_preamble = r''' \usepackage{lmodern} \usepackage{amsmath} \usepackage{amsfonts} \usepackage{mathtools} \usepackage{bm} ''...
import gspread from oauth2client.service_account import ServiceAccountCredentials scope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive'] credentials = ServiceAccountCredentials.from_json_keyfile_name('../python-write-test-325506-04f791ddf6a9.json', scope) gc = gspread.auth...