content
stringlengths
5
1.05M
n = int(input()) print(pow(3, n, 2**31 -1))
import pytest from dagster import InitResourceContext, build_init_resource_context, resource from dagster.core.errors import DagsterInvariantViolationError def test_build_no_args(): context = build_init_resource_context() assert isinstance(context, InitResourceContext) @resource def basic(_): ...
# Copyright (C) 2017 Beijing Didi Infinity Technology and Development Co.,Ltd. # 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/LI...
## Read input as specified in the question. ## Print output as specified in the question. n = int(input()) li = [] sum = 0 li = [int(x) for x in input().split()] for ele in li: sum = sum + ele print(sum)
import platform import os import subprocess import requests from PyQt5 import uic from PyQt5.QtCore import pyqtSlot, Qt, QPoint, QFileInfo, QModelIndex, QRegExp from PyQt5.QtWidgets import QFileDialog, QMenu, QAction, QWidget, QTableView, QHeaderView, QTableWidget from PyQt5.QtGui import QRegExpValidator from gui.Work...
# -*- coding:utf-8 -*- import pika connection = pika.BlockingConnection(pika.ConnectionParameters('localhost')) # 相当于建立一个socket连接 channel = connection.channel() # 声明queue channel.queue_declare(queue='hello') # RabbitMQ a message can never be sent directly to the queue, it always needs to go through an exc...
import pytest from boardfarm.orchestration import TestStep as TS from boardfarm.tests.bft_base_test import BftBaseTest from unittest2 import TestCase # Assumption1 : later test won't define runTest # Assumption2 : BF pytest pluging won't call a wrapper to execute runTest # Assumption3 : BF pytest will directly used t...
"""Prepare a binned matrix of misalignments and plot it in different ways""" import click import pysam import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt from matplotlib.path import Path import matplotlib.patches as patches from matplotlib.colors import LogNorm import numpy as np def we_have_too...
# -*- coding: utf-8 -*- from __future__ import division, print_function __all__ = ["State"] import numpy as np from copy import deepcopy class State(object): """The state of the ensemble during an MCMC run For backwards compatibility, this will unpack into ``coords, log_prob, (blobs), random_state`` w...
"""expense_tracker URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.1/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Cla...
from tkinter import * import pygame import random import copy class tetrisGame(object): #################################### # Majority of the base Tetris Framework created by David Zhang @dlzhang Week6 # Adapted to Pygame and added notable features for the Term Project # Used pieces of the Pygame Framework from ...
# -*- coding:utf8 -*- """博实结""" from protocol import ProtocolTranslator from result import Location, Identity import datetime import logging import struct class A5(ProtocolTranslator): """A5""" @staticmethod def sum(s): a = "00" for i in range(0, len(s), 2): tmp = (int(a, 16)) ...
"""setup.py""" from distutils.core import setup setup(name='numutil', version='0.1.0', description='Utilities for parsing strings into numbers, and printing numbers as pretty strings', author='Naftali Harris', author_email='[email protected]', url='www.naftaliharris.com',...
import urllib import urllib2 import re try: url = 'http://pythonprogramming.net/parse-website-using-regular-expressions-urllib/' #values = {'q' : 'sql'} #data = urllib.urlencode(values) headers = {} headers['User-Agent'] = "Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.17 (KHTML, like Geck...
#!/usr/bin/env python import MKDatabase from MKFlowMessage import FBconvertLong # Main Class class MKFlowCommunication(): def __init__(self): self.nullNode = MKFlowNode(-1) self.node_numbers = [] self.nodes = [] def addNode(self, number): if not self.isNode(number): ...
import pytest from granula.config import Config from tests.fixtures import get_fixture_path from tests.stubs.serializer import CustomSerializer from tests.utils import replace_environment @pytest.mark.parametrize( ['serializer', 'directory', 'environment', 'expected'], [ ( 'yaml', ...
"""Class for sorting algorithms.""" ''' class Sortings(object): """A general class for sorting algorithms.""" def __init__(self, sort_list=None): """Take in empty list.""" if sort_list is None: self.sort_list = [] else: self.sort_list = sort_list def bub...
import unittest from reinvent_scoring.scoring.enums import ScoringFunctionComponentNameEnum from reinvent_scoring.scoring.enums import ScoringFunctionNameEnum from reinvent_scoring.scoring.scoring_function_factory import ScoringFunctionFactory from reinvent_scoring.scoring.scoring_function_parameters import ScoringFun...
import requests import json import settings as s class Bitmex(object): def __init__(self): self.trade_currency = "XBT" self.ask_price = 0 self.bid_price = 0 self.order_id_prefix = "lee_bot" self.symbol = s.SYMBOL self.BASE_URL = "https://www.bitmex.com/api/v1/" ...
from flask_appbuilder.widgets import RenderTemplateWidget class ChartWidget(RenderTemplateWidget): template = 'appbuilder/general/widgets/chart.html' class DirectChartWidget(RenderTemplateWidget): template = 'appbuilder/general/widgets/direct_chart.html' class MultipleChartWidget(RenderTemplateWidget): ...
from dataclasses import dataclass from typing import Any from pyckaxe.lib.resource.loot_table.loot_table import LootTable __all__ = ("LootTableSerializer",) # @implements ResourceSerializer[LootTable, Any] @dataclass class LootTableSerializer: # @implements ResourceSerializer[LootTable, Any] def __call__(se...
from typing import Dict, Optional, Union import numpy as np from werkzeug import ImmutableMultiDict from .endpoint import Endpoint def predict(model, input_data: Union[Dict, ImmutableMultiDict], config: Endpoint): # new model if hasattr(model, "public_inputs"): sample = {} for k, v in dict(i...
from .multipart import ( FormParser, MultipartParser, QuerystringParser, OctetStreamParser, create_form_parser, parse_form, ) __version__ == "2022.1"
import matplotlib.pyplot as plt def _get_labels(l, hours, items): """ Formats the labels, undocumented on purpose, not relevant. """ total_sum = sum(l) it = 0 temp_list = [] for p in l: pct = (p / total_sum) * 100 temp_list.append(f'{items[it]} - {hours[it]} ({round(pct, 2...
import os import unittest import zope.testrunner from zope import component from sparc.testing.fixture import test_suite_mixin from sparc.cli.testing import SPARC_CLI_INTEGRATION_LAYER import sparc.cli from sparc.cli.exceptions import CliTooManyAtempts, CliInvalidInput class SparcUtilsCliInputTestCase(unittest.TestCa...
"""Kata url: https://www.codewars.com/kata/57cfdf34902f6ba3d300001e.""" from typing import List def two_sort(array: List[str]) -> str: return '***'.join(sorted(array)[0])
n, a, b, c, d = [int(x) - 1 for x in input().split()] s = input() if c > d: x = s[a:c + 1] y = s[b - 1:d + 2] if "##" in x or "..." not in y: print("No") else: print("Yes") else: x = s[a:d + 1] if "##" in x: print("No") else: print("Yes")
# -*- coding: utf-8 -*- ''' .. created on 08.09.2016 .. by Christoph Schmitt ''' from __future__ import print_function, absolute_import, division, unicode_literals from reflexif.compat import * from reflexif.framework import model_base, declarative from reflexif.framework.model_base import structs def parentalias(c...
from STC_Path_Testing.nextdate import Date class TestNextDateCoverageClass: """ Valid Value Range: 1812 <= year <= 2016 1 <= month <= 12 1 <= day <= 31 """ def test_nextdate_c0(self): assert Date(1811, 0, 0).nextdate == "INVALID" assert Date(2015, 12, 31).nextdate == "2016...
# bendy.py # # animate the bones of the 'izzy' GLTF model from Sketchfab # bone names came from inspecting scene.gltf # assumes the model 'izzy' already exists in ARENA scene 'cesium' import arena import random import time import signal HOST = "oz.andrew.cmu.edu" SCENE = "cesium" bones=[ "CC_Base_Spine01_correct...
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. # pyre-strict import argparse import json import logging import os import sys import time from dataclasses import dataclass from typing impor...
"""Unit tests for the Edit user profile form.""" from django import forms from django.test import TestCase, tag from BookClub.forms import EditProfileForm from BookClub.models import User @tag('forms', 'user') class ProfileFormTestCase(TestCase): """Update User Details Form Tests.""" fixtures = ['BookClub/t...
import os from celery import Celery import synchronous.settings as settings os.environ.setdefault("DJANGO_SETTINGS_MODULE", "synchronous.settings") app = Celery("synchronous") app.config_from_object("django.conf:settings") app.autodiscover_tasks() # make sure to run `celery -A synchronous worker -B -l info` # as w...
from setuptools import setup, find_packages setup( name = "docuware-client", version = "0.1.0", description = "DocuWare REST-API client", long_description = open("README.md").read(), long_description_content_type = "text/markdown", url = "https://github.com/sniner/docuware-client", author =...
import numpy import lasagne, lasagne.updates, lasagne.regularization from lasagne import layers import theano from theano import tensor as T class MILogisticRegression(object): """Multi-instance logistic regression classifier. A class for performing [deep] multi-instance logistic regression using the Thea...
def load_bbox(bbox_file): img_to_bbox = {} with open(bbox_file, 'rb') as f: lines = f.readlines() for line in lines[2:]: flag = line.strip('\n').split(' ') img_to_bbox[flag[0]] = [int(flag[-4]), int(flag[-3]), int(flag[-2]), int(flag[-1])] return img_to_bbox ...
#!/usr/bin/env python """ This is a subclass seisflows.system.Serial Provides utilities for submitting jobs in serial on a single machine, mostly for testing purposes """ import os import sys import numpy as np import os from seisflows.tools import unix from seisflows.config import custom_import from seisflows.tools.e...
import copy def print_seating(s): print() for r in s: print(''.join(r)) print() def get_neighbors(seating, i,j): if i == 0: i_ops = [0,+1] elif i == max_r: i_ops = [-1,0] else: i_ops = [-1,0,+1] if j == 0: j_ops = [0,+1] elif j == max_c: ...
#!/usr/bin/env python3 """ Solve any size rubiks cube: - For 2x2x2 and 3x3x3 just solve it - For 4x4x4 and larger, reduce to 3x3x3 and then solve """ # standard libraries import argparse import datetime as dt import logging import resource import sys from math import sqrt # rubiks cube libraries from rubikscubennnso...
import turtle turtle.setup(1440,900) turtle.bgcolor('black') # Setup t = turtle.Turtle() t.penup() t.goto(-40,-50) t.pendown() # Yellow Square t.color('yellow') t.begin_fill() t.forward(100) t.left(90) t.forward(100) t.left(90) t.forward(100) t.left(90) t.forward(100) t.left(90) t.end_fill() # Orange Parallelogram...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def sumEvenGrandparent(self, root: TreeNode) -> int: self.k=0 def dfs(root): if ...
# Copies indices (settings, mappings, and optionally data) from a 5 cluster to a 7 cluster. # Note that when copying data, the copied is performed through this machine, meaning all data is downloaded from 5, # and then uploaded to 7. This can be a very slow process if you have a lot of data, and is recommended you only...
import numpy as np from sklearn.preprocessing import LabelBinarizer def vectorize_sequence(sequence): lb = LabelBinarizer() lb.fit(list(set(sequence))) sequence = list(sequence) return lb.transform(sequence) def load(verbose=False, vectorize=True): with np.load('rnn-challenge-data.npz') as fh: ...
import argparse if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("infile", type=str, help="Grepped input file") parser.add_argument("num_clients", type=int, help="Number of clients in experiment") parser.add_argument("ec_k_val", type=int, ...
import requests from bs4 import BeautifulSoup import re from selenium import webdriver import model URL = "https://sobooks.cc" VERIFY_KEY = '2019777' def convert_to_beautifulsoup(data): """ 用于将传过来的data数据包装成BeautifulSoup对象 :param data: 对应网页的html内容数据 :return: 对应data的BeautifulSoup对象 """ bs = Bea...
# Generated by Django 3.2.3 on 2021-06-01 19:32 from django.conf import settings import django.core.validators from django.db import migrations, models import django.db.models.deletion import pyuploadcare.dj.models import tinymce.models class Migration(migrations.Migration): initial = True dependencies = [...
""" Given a binary tree, return the level order traversal of its nodes’ values. (ie, from left to right, level by level). Example : Given binary tree 3 / \ 9 20 / \ 15 7 return its level order traversal as: [ [3], [9,20], [15,7] ] Also think about a version of the question where you are ask...
# -*- coding: utf-8 -*- # # Copyright (c) 2018~2999 - Cologler <[email protected]> # ---------- # # ---------- from typing import * import binascii import hashlib import os ALGORITHMS = set(hashlib.algorithms_available) ALGORITHMS.add('crc32') class Crc32Proxy: def __init__(self): self._value = 0 de...
# Copyright (c) Microsoft. All rights reserved. # Licensed under the MIT license. See LICENSE.md file in the project root # for full license information. # ============================================================================== """ Unit tests for function extension """ from __future__ import division, print_fu...
import server def main(): s = server.Server() s.startServer() main()
import matplotlib.patches as mpatches import matplotlib.pyplot as plt styles = mpatches.ArrowStyle.get_styles() figheight = (len(styles)+.5) fig1 = plt.figure(1, (4, figheight)) fontsize = 0.3 * fig1.dpi ax = fig1.add_axes([0, 0, 1, 1], frameon=False, aspect=1.) ax.set_xlim(0, 4) ax.set_ylim(0, figheight) for i, ...
#coding=utf8 """ # Author: Kellan Fan # Created Time : Fri 29 Jan 2021 01:32:29 PM CST # File Name: movie.py # Description: """ from app.common.pg_client import Mypostgres from flask_restful import reqparse, abort, Resource parser = reqparse.RequestParser() parser.add_argument('name', type=str, required=True, ...
#!/usr/bin/env python3 # File name: iaa.py # Description: Computes Cohen and Fleiss kappa statistics # Author: Louis de Bruijn # Date: 14-07-2020 import json import numpy as np import pandas as pd from sklearn.metrics import cohen_kappa_score from statsmodels.stats.inter_rater import fleiss_kappa def cohen_kappa_fu...
from enum import Enum class LensType(Enum): Undefined = 0 DTypeLenWithDistanceEncoder = 1 VRLensWithAntiVibrationMechanism = 2 DXLensExclusiveUseOfNikon = 4 AFSLens = 8 LensSupport...
from datetime import date from ....import_utils import * from ....models_dict import MODEL_REQUIREMENTS if is_all_dependency_installed(MODEL_REQUIREMENTS['encoders-audio-tfhub-speech_embedding']): import tensorflow as tf import tensorflow_hub as hub import traceback from ....base import catch_vector_errors...
from Homework_6.Exercise_1 import book_dict, role_dict, base_url_book, base_url_role, add_new_item, add_item_id, check_item_in_list, \ compare_dicts, check_new_item, role_update_and_check, delete_item_finally import pytest import uuid import random class TestAddNewRole: @pytest.fixture() def setup_and_tea...
""" Network architecture visualizer using graphviz """ import sys from epe_darts import genotypes as gt if __name__ == '__main__': if len(sys.argv) != 2: raise ValueError("usage:\n python {} GENOTYPE".format(sys.argv[0])) genotype_str = sys.argv[1] try: genotype = gt.from_str(genotype_st...
""" This module is the geometrical part of the ToFu general package It includes all functions and object classes necessary for tomography on Tokamaks """ # Built-in import sys import os import warnings import copy # Common import numpy as np import scipy.interpolate as scpinterp import scipy.stats as scpstats impor...
import tempfile from requre.helpers.simple_object import Simple from requre.storage import PersistentObjectStorage from requre.utils import run_command, StorageMode from tests.testbase import BaseClass class StoreFunctionOutput(BaseClass): @staticmethod @Simple.decorator_plain() def run_command_wrapper(c...
# Button mapping # Button indices start at 0 at the bottom of the remote, opposite the IR blaster # i.e. The unlit button is 0 # The indices must be from 0 to 5 only Button_HDMI = 5 Button_ChannelUp = 4 Button_ChannelDown = 3 Button_TvOnOff = 2 Button_Mute = 1 Button_Extra = 0 # Volume contro...
from maju.api import api from maju.config import config_db from maju.api.healthcheck.view import ns as healthcheck from maju.api.playlist.view import ns as playlist from maju.api.statistics.view import ns as statistics from flask import Flask, Blueprint from flask_cors import CORS def create_app(config_filename=None)...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # ---------------------------------------------------------------- # test_openingBraces.py # # test for openingBraces rule # ---------------------------------------------------------------- # copyright (c) 2014 - Domen Ipavec # Distributed under The MIT License, see LICEN...
# -*- coding: utf-8 -*- # Generated by Django 1.10.2 on 2016-10-05 19:41 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Pago',...
#!/usr/bin/env python3 # Import the API module import bosdyn.client # Create an sdk object (the name is arbitrary) sdk = bosdyn.client.create_standard_sdk('understanding-spot') # Create a connection to the robot robot = sdk.create_robot('192.168.50.3') # Get the client ID id_client = robot.ensure_client('robot-id')...
from PyInstaller.compat import is_darwin import os if is_darwin: # Assume we're using homebrew to install GDAL and collect data files # accordingly. from PyInstaller.utils.hooks import get_homebrew_path from PyInstaller.utils.hooks import collect_system_data_files datas = collect_system_data_files...
import _pickle import json INDIR = '/data/bugliarello.e/data/gqa/lxmert' OUTDIR = '/data/bugliarello.e/data/gqa/cache' f = json.load(open(INDIR + '/trainval_label2ans.json')) _pickle.dump(f, open(OUTDIR + '/trainval_label2ans.pkl', 'wb')) a2l = json.load(open(INDIR + '/trainval_ans2label.json')) _pickle.dump(a2l, op...
#***************************************************************** # terraform-provider-vcloud-director # Copyright (c) 2017 VMware, Inc. All Rights Reserved. # SPDX-License-Identifier: BSD-2-Clause #***************************************************************** import grpc import errors import logging from lxml im...
"""Primary class defining conversion of experiment-specific behavior.""" from nwb_conversion_tools import BaseDataInterface class MyEcephysBehaviorInterface(BaseRecordingExtractorInterface): """My behavior interface specific to the ecephys experiments.""" def __init__(self): # Point to data p...
""" 1914. Cyclically Rotating a Grid Medium You are given an m x n integer matrix grid​​​, where m and n are both even integers, and an integer k. The matrix is composed of several layers, which is shown in the below image, where each color is its own layer: A cyclic rotation of the matrix is done by cyclically r...
r"""Functions related to player motion under gravity. Typically you would want to compute *K* using the :py:meth:`strafe_K` or :py:func:`strafe_K_std` function, which is needed by many of the functions in this module. All functions in this module ignore the :math:`\Theta = 0` strafing corresponding to :math:`L - k_e ...
from Nodes.TemplateNode import TemplateNode from ryven.NENV import * import code from contextlib import redirect_stdout, redirect_stderr #this is important to ensure the path is set to the currect directory so it can find the other nodes import sys import os from os import walk import glob # open cv import cv2 import...
import sys sys.path.append('/home/myja3483/isce_tools/ISCE') import os import numpy import tops import re path = '/net/tiampostorage/volume1/MyleneShare/Bigsur_desc/az1rng2' dir_list = os.listdir(path) regex = re.compile(r'\d{8}_\d{8}') pair_dirs = [os.path.join(path, d) for d in list(filter(regex.search, dir_list))] ...
""" collipy ======= Provides an intuitive simple way to inject some particles """ from .particles import pdg from .helper import fit, n_sigma, breit_wigner, expon from .accelerator.accelerator import Accelerator from .injection import InjectionCollection, DecayMode from .helper import function_timer
# Base imports from typing import Dict, List, Union, Optional # Third-party imports import matplotlib.pyplot as plotter # Project imports from src.graphics.common import build_tc_plot_file_path from src.time_complexity.common import Number, TIME_COMPLEXITIES, TIME_RATIO_SCALE_FACTOR def plot_time_ratios( proble...
def modelling(): train_df[train_df.matchType.str.contains('normal')].groupby(['matchType']).count()
import io import unittest from contextlib import redirect_stdout from unittest.mock import patch class TestQ(unittest.TestCase): @patch('builtins.input', side_effect=[ '42 42', '__________________________________________', '__________________________________________', '____________...
import logging from pathlib import Path import requests from docs_name_parser import parse_urls from settings import DOWNLOAD_FOLDER logger = logging.getLogger(__name__) def load_urls(): with open("doc_urls.txt") as f: raw_urls = f.read().splitlines() return sorted(parse_urls(raw_urls)) def retri...
# -*- coding: utf-8 -*- import heapq def fnHeapq(): ''' Descobrindo quais valores tem maior ou menor valor: a lib heapq filtra os menores ou maiores valres ''' idades = [10,14,12,23,84,23,55,23,58,49,6] # os três menores números # print(heapq.nsmallest(3, idades)) # os três maiores números # pr...
# (C) Datadog, Inc. 2021-present # All rights reserved # Licensed under a 3-clause BSD style license (see LICENSE) from datadog_checks.aspdotnet import AspdotnetCheck from datadog_checks.base.constants import ServiceCheck from datadog_checks.dev.testing import requires_py3 from datadog_checks.dev.utils import get_metad...
################################################################################ # # display_results.py # # Shows all the results and downloads them as one .csv for each experiment # from results import * import argparse import pandas as pd import pickle def load_results(results_path): """ Loads the results and ...
import argparse import os import evaluation def parse_args(): parser = argparse.ArgumentParser() parser.add_argument("--RESULTS_PATH", type=str, required=True) parser.add_argument("--RUN_NAME", type=str, required=True) parser.add_argument("--DATASET", type=str, required=True) args = parser.parse...
"""Liquid specific Exceptions and warnings.""" from typing import Any from typing import Dict from typing import Optional from typing import Type from typing import Union from pathlib import Path class Error(Exception): """Base class for all Liquid exceptions.""" def __init__( self, *args: ...
import operator from sympy import symbols, S import pytest from galgebra.ga import Ga from galgebra.mv import Dop, Mv from galgebra.dop import Sdop, Pdop class TestDop(object): def test_associativity_and_distributivity(self): coords = x, y, z = symbols('x y z', real=True) ga, ex, ey, ez = Ga.bu...
import asyncio import websockets connected = [] bits = [] async def handler(websocket, path): global connected # Register. clientId = len(connected) bits.append(False) connected.append(websocket) try: # Implement logic here. while True: mssg = await websocket.recv() ...
from .envs import env_0_args, env_1_args from .envs import Observation from .envs import Configuration from .envs import Session from .envs import Context, DefaultContext from .constants import ( AgentStats, AgentInit, EvolutionCase, TrainingApproach, RoiMetrics ) from .bench_agents import test_age...
# Main logger import logging log = logging.getLogger('orgassist') from . import config from . import calendar from . import bots from . import assistant from .assistant import Assistant # Register commands from . import plugins
# -*- coding: utf-8 -*- from __future__ import annotations # system imports import os.path as osp import asyncio import urllib.parse from typing import Any # external imports import toga from toga.style.pack import Pack from toga.constants import ROW, COLUMN from maestral.daemon import MaestralProxy from maestral.mo...
import torch import torch.nn as nn import random import torchvision.transforms as T class PhotoMetricDistortion(nn.Module): def __init__(self, brightness: float = 0.4, contrast: float = 0.4, saturation: float = 0.4, hue: float = 0.4): super().__init__() self.cj = T.ColorJitter(brightness, contrast...
from django.contrib.auth.models import User from django.urls import reverse from rest_framework import status from rest_framework.test import APITestCase from posts.models import Post, Share, Comment, Like class PostTests(APITestCase): def test_create_post(self): """ Ensure we can create a new twee...
import os import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import torch.utils.data as data import copy import argparse import logging import gc import datetime import pprint from collections import OrderedDict, defaultdict from functools import partial from torch.optim...
import re # The `match` method matches a pattern at the beginning of a string def example_1(): ''' >>> example_1() <_sre.SRE_Match object; span=(0, 11), match='hello world'> ''' hello_regex = re.compile(r'hello world') result = hello_regex.match('hello world blah blah') print(result) de...
from __future__ import annotations import os import time from typing import Any, Dict, List, Optional, Set, Union from xrpl.models import FederatorInfo from slk.chain.chain import Chain from slk.chain.node import Node from slk.classes.config_file import ConfigFile class Mainchain(Chain): """Representation of a...
import numpy as np import collections class K_Means: def __init__(self, k=2, tol = 0.001, max_iter = 300): self.k = k self.tol = tol self.max_iter = max_iter def fit(self,data): self.centroids = {} for i in range(self.k): self.centroids[i] = data[i] ...
from __future__ import absolute_import from pytest import fixture, raises from openvpn_status.descriptors import ( LabelProperty, name_descriptors, iter_descriptors) @fixture def foo_class(): @name_descriptors class Foo(object): foo = LabelProperty('Foo') bar = LabelProperty('Bar', defau...
import jax.numpy as jnp from jax import grad, tree_util, lax from jax_meta.utils.losses import cross_entropy from jax_meta.utils.metrics import accuracy from jax_meta.metalearners.base import MetaLearner class MAML(MetaLearner): def __init__(self, model, num_steps=5, alpha=0.1): super().__init__() ...
from django import forms from django.forms import ModelForm from .models import * class TaskForm(forms.ModelForm): title = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Add New Task...'})) class Meta: model = Task # fields = ['title', 'complete']
import os import random import threading import codecs import queue import librosa import numpy as np from params import hparams def read_binary_lc(file_path, dimension): f = open(file_path, 'rb') features = np.fromfile(f, dtype=np.float32) f.close() assert features.size % float(dimension) == 0.0,\ ...
import socket, select, sys if len(sys.argv) != 3: print("USAGE: " + sys.argv[0] + " dstHost dstPort", file=sys.stderr) exit(1); # struktura zawierająca adres na który wysyłamy dstAddrInfo = socket.getaddrinfo(sys.argv[1], sys.argv[2], proto=socket.IPPROTO_TCP) # mogliśmy uzyskać kilka adresów, więc próbujemy używ...
from aiogram import types from keyboards.inline import soon_be_available, faculties, back_callback from keyboards.inline.admin import send_msg, edit_subgroups, admins, edit_admins from loader import dp from models import Admin from states import menu from states.admin import AdminStates from utils.misc import get_curr...
import numpy as np import qnt_utils as qntu def DyS(pos_scores, neg_scores, test_scores, measure='topose'): bin_size = np.linspace(2,20,10) #[10,20] range(10,111,10) #creating bins from 2 to 10 with step size 2 bin_size = np.append(bin_size, 30) result = [] for bins in bin_size: #.....