content
stringlengths
5
1.05M
from dataclasses import dataclass @dataclass class GlobalState: verbose: bool = False _global_state = GlobalState() def get_global_state(): return _global_state
""" Alice recently started learning about cryptography and found that anagrams are very useful. Two strings are anagrams of each other if they have same character set. For example strings "bacdc" and "dcbac" are anagrams, while strings "bacdc" and "dcbad" are not. Alice decides on an encryption scheme involving 2 larg...
## # Maker's Digest # # MCP3008 ADC Example # # Dont forget to install the libraries! See README.md for details. ## import sys # Import sys module from time import sleep # Import sleep from time import Adafruit_GPIO.SPI as SPI # Import Adafruit GPIO_SPI Module import Adafruit_MCP3008 ...
def is_palindrome(s): if (s == reverse(s)): return True return False
#!/usr/bin/python import sys; import os; import argparse; OPT_PATH_INPUT = "input"; HELP_PATH_INPUT = "The root pathname of pattern folder."; WARN_PATH_INPUT = "The root pathname of pattern folder is not specified."; SUFFIX_CONTRIBUTE = "Contributed By:"; DECLARE_OFFSET = "Relative Offset"; def main(): parse...
# imports import os import tensorflow.nn as nn import tensorflow.keras.backend as K from tensorflow.keras import Input,Model from tensorflow.keras.utils import plot_model from tensorflow.keras import layers, regularizers,activations from utils import DotDict from models.DGV0.model_v0 import DGM # end imports config ...
import numpy as np import seaborn as sns def get_plot(u, s, v, clusters, dismiss=0): """ Get heat plot of clusters in rank 1 approximation. u, s, v = SSVD function output clusters = vector of predetermined groups dismiss = index discarded """ X_star = s*u[:,None]@v[None,:] uni...
import os import re import subprocess import sys import warnings import setuptools import setuptools.command.build_ext import wheel.bdist_wheel _this_dir = os.path.dirname(os.path.abspath(__file__)) _clib_dir = os.path.join(_this_dir, 'python', 'opencc', 'clib') _build_dir = os.path.join(_this_dir, 'build', 'python')...
# Generated by Django 2.2.4 on 2019-08-12 18:11 from django.db import migrations class Migration(migrations.Migration): dependencies = [("api", "0004_task_taskslug")] operations = [ migrations.RenameModel(old_name="Product", new_name="Repository"), migrations.RenameModel(old_name="ProductSl...
import token_names as tokens from node_visitor import NodeVisitor class Interpreter(NodeVisitor): def __init__(self, tree): self.tree = tree def visit_Program(self, node): self.visit(node.block) def visit_Block(self, node): for declaration in node.declarations: self.v...
from utils import sqlite as db class Accounts(db.Table): user_id = db.Column("BIGINT", nullable=False, primary_key=True) steamid64 = db.Column("BIGINT", nullable=False) brawlhalla_id = db.Column("INT", nullable=False) def creation(debug: bool = False): """ Create tables or add missing columns to tab...
import numpy as np from sklearn.base import BaseEstimator class Config: DISABLE_JIT = False def numba_jit(nopython=True, nogil=True, **kwds): def wrapped(func): if Config.DISABLE_JIT: return func try: from numba import jit except ImportError: retur...
import os import argparse import time from best_solution_in_the_wuuuuuuurld import * from Utilities import * avail_methods = [ 'rand', 'score', 'conv', 'skel' ] avail_methods_cable = [ 'bfs', 'mst' ] parser = argparse.ArgumentParser() # need to be parser.add_argument("input", help="input fi...
# -*- coding:utf-8 -*- """ """ import cudf import cupy from hypernets.tabular.ensemble import GreedyEnsemble from ._transformer import Localizable, as_local_if_possible, copy_attrs_as_local class CumlGreedyEnsemble(GreedyEnsemble, Localizable): np = cupy @staticmethod def _to_local(y): if isins...
def Counting_Sort(A, k=-1): if(k==-1): k=max(A) C = [0 for x in range(k+1)] for x in A: C[x]+=1 for x in range(1, k+1):C[x]+=C[x-1] B = [0 for x in range(len(A))] for i in range(len(A)-1, -1, -1): x = A[i] B[C[x]-1] = x C[x]-=1 return B A = [13,20,18,20,12,15,7] print(Counting_Sort(A))
from paillier import * class Voter(object): def __init__(self, name, voterID): self.name = name self.voterID = voterID self.voted = False priv, pub = generate_keypair(128) self.private_key = priv self.public_key = pub def __repr__(self): return 'Voter(\...
import torch import torchvision import torch.nn.functional import torchvision.transforms as transforms from torch.autograd import Variable from users.resnet18 import ResNet18 from PIL import Image device = torch.device('cpu') # cifar-10的标签 classes = ('plane', 'car', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'shi...
from lib.ReadCsv import ReadCsv from lib.ReadData import ReadData from lib.ReadConfig import ReadConfig
from robotchallenge.Board.board import Board from robotchallenge.Robot.robot import Robot from robotchallenge.Compiler.compiler import Compiler from robotchallenge.Simulator.simulator import Simulator def test_simulator(): # Create a new board board_size = 5 board = Board(board_size) # Create a new r...
import inspect import re import time from abc import ABC, abstractmethod from contextlib import suppress from typing import Any, Callable, Union, List, Dict import decorator class JunitDecorator(ABC): _func: Union[Callable, None] _start_time: Union[float, None] _stack_locals: List[Dict[str, Any]] d...
import os from scipy.sparse import vstack from sourced.ml import extractors from sourced.ml.models.bow import BOW from sourced.ml.models.model_converters.base import Model2Base class MergeBOW(Model2Base): """ Merges several :class:`BOW` models together. """ MODEL_FROM_CLASS = BOW MODEL_TO_CLASS ...
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: MIT-0 import json import os import requests_mock import boto3 from moto import mock_dynamodb2, mock_secretsmanager from unittest import mock from unittest import TestCase from validate import app, exceptions import tests.un...
from .sourcehooks import SourceHook import pandas as pd from .lrseg import Lrseg class Agency(SourceHook): def __init__(self, sourcedata=None, metadata=None): """ Methods for querying CAST data related to Agencies """ SourceHook.__init__(self, sourcedata=sourcedata, metadata=metadata) se...
import unittest import solution class TestQ(unittest.TestCase): def test_case_0(self): self.assertEqual(solution.angryChildren(3, [10, 100, 300, 200, 1000, 20, 30]), 40) def test_case_1(self): self.assertEqual(solution.angryChildren(4, [1, 2, 3, 4, 10, 20, 30, 40, 100, 200]), 10) if __name...
import os from setuptools import setup CURRENT_DIR = os.path.abspath(os.path.dirname(__file__)) PACKAGE_NAME = "petisco" VERSION = "0.2.1" # The text of the README file with open(os.path.join(CURRENT_DIR, "README.md")) as fid: README = fid.read() setup( name=PACKAGE_NAME, version=VERSION, descriptio...
# Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import logging import os import posixpath import uuid import sys import tempfile import time from py_utils import cloud_storage # pylint: disable=import-er...
import re import inspect from spark_lineage.LineageParser import LineageParser class RequiredFunction(LineageParser): def parse(self): required_cols = [] s=inspect.getsource(self.lineage.func).replace('\n', ' ').replace('\r', '').replace(" ", "") req_columns = re.findall(r'col\((....
import os import traceback from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions from selenium.common.exceptio...
# @lc app=leetcode id=779 lang=python3 # # [779] K-th Symbol in Grammar # # https://leetcode.com/problems/k-th-symbol-in-grammar/description/ # # algorithms # Medium (39.28%) # Likes: 1301 # Dislikes: 225 # Total Accepted: 70K # Total Submissions: 177.5K # Testcase Example: '1\n1' # # We build a table of n rows ...
from django.urls import include, path from . import views app_name = 'profiles' urlpatterns = [ path('', include('django.contrib.auth.urls')), path('profile', views.UserProfileView.as_view(), name='profile'), path('inactive', views.UserInactiveView.as_view(), name='i...
import pytest from runflow import runflow pytest.importorskip('slack_sdk') def test_pushbullet_push_note(mocker): pb = mocker.MagicMock() mocker.patch('pushbullet.Pushbullet', pb) runflow(path="examples/pushbullet_push_note.hcl", vars={ 'pushbullet_api_key': 'any' }) pb.return_value.pu...
import RPi.GPIO as GPIO import time led_pin = 23 GPIO.setmode(GPIO.BCM) GPIO.setup(led_pin, GPIO.OUT) while True: GPIO.output(led_pin, GPIO.HIGH) time.sleep(1) GPIO.output(led_pin, GPIO.LOW) time.sleep(1) GPIO.cleanup()
#!/usr/bin/python -OO # Copyright 2007-2019 The SABnzbd-Team <team@sabnzbd.org> # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later...
from datetime import datetime, timedelta from airflow.decorators import dag from airflow.models.baseoperator import chain from airflow.operators.dummy import DummyOperator from airflow.providers.snowflake.operators.snowflake import SnowflakeOperator from airflow_provider_census.operators.census import CensusOperator f...
#! /usr/bin/env python from os import path from setuptools import find_packages, setup def setup_package() -> None: root = path.abspath(path.dirname(__file__)) with open(path.join(root, "README.md"), encoding="utf-8") as f: long_description = f.read() setup( name="paranames", ve...
# -*- coding: utf-8 -*- from __future__ import unicode_literals import os from dfvfs.path.path_spec import PathSpec from plaso.tarzan.file.generic_file import FileObject from plaso.tarzan.lib.pyarrow_hdfs import PyArrowHdfs class HdfsFileObject(FileObject): """HDFS file access.""" def __init__(self): ...
from .default_skill import DefaultStatelessSkill
import re import django from django.conf import settings from django.utils.html import escape from django.utils.encoding import smart_str from django.template.base import Lexer, Parser try: from django.template import StringOrigin as Origin except ImportError: from django.template import Origin from django.t...
from typing import Any from sched_slack_bot.model.schedule import Schedule class Reminder: def __init__(self, schedule: Schedule): self._schedule = schedule @property def schedule_id(self) -> str: return self._schedule.id @property def channel_id_to_notify_in(self) -> str: ...
import random def check(a,b): if(x==y): print("Wow What a coincidence you both picked the same one try again Hope you may Win next time") if(x==1 and y==2): print("Oops You've Lost.. The system chose Rock and you chose Paper... Try Again....") if(x==1 and y==3): print("Yay! You'v...
"""Function that returns spray radius or discharge quantity by simulating projectile motion """ import pandas as pd import math import numpy as np import logging import coloredlogs def get_projectile( dia=0, h_f=3, dis=0, r=0 ): # returns discharge or spray radius using projectile motion if dia == 0: ...
import asyncio import json import aiohttp from aiohttp import web async def send_updates(request): message = json.dumps(list(request.app['customers'].values())) # list of carts for _ws in request.app['customers']: _ws.send_str(message) async def websocket_handler(request): ws = web.WebSocketRe...
class Vehiculo: pass class VehiculoTerrestre(Vehiculo): pass class VehiculoOruga(VehiculoTerrestre): pass miVehiculo = Vehiculo() miVehiculoTerrestre = VehiculoTerrestre() miVehiculoOruga = VehiculoOruga() for obj in [miVehiculo, miVehiculoTerrestre, miVehiculoOruga]: for cls in [Vehiculo, Vehicul...
import json import asyncio import aioredis import aiohttp def max_item_url(): return "https://hacker-news.firebaseio.com/v0/maxitem.json" def get_item_url(item_id): return "https://hacker-news.firebaseio.com/v0/item/{0}.json".format(str(item_id)) async def get_max_item(http): while True: async w...
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import os import functools from torch.autograd import Variable from util.image_pool import ImagePool from .base_model import BaseModel from . import networks im...
# -------------- # Code starts here # Create the lists class_1=['Geoffrey Hinton','Andrew Ng','Sebastian Raschka','Yoshua Bengio'] class_2=['Hilary Mason','Carla Gentry','Corinna Cortes'] # Concatenate both the strings new_class=class_1+class_2 print(new_class) # Append the list new_class.append('Peter War...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = 'Walson Tung' 'url handlers' import re,time,json,logging,hashlib,base64,asyncio import markdown2 from aiohttp import web from coreweb import get,post from apis import * from models import User,Comment,Blog,next_id from config import configs COOKIE_NAME =...
# repo originally forked from https://github.com/Confusezius/Deep-Metric-Learning-Baselines """to do: clean all of the files - particularly the main.py and also the losses and dataset files and the file for doing the dataloading -- fast loading etc need to change all of the copyrights at the top of all of the files...
import unittest import logging #from datetime import datetime, timedelta #from google.appengine.api import memcache from google.appengine.ext import ndb from google.appengine.ext import testbed import model class TestConfig(unittest.TestCase): def setUp(self): # First, create an instance of the Testbed class. ...
""" The Network :class:`Manager`. """ import os import sys import ssl import socket import inspect import asyncio import logging import platform from datetime import datetime from . import cryptography from .network import Network from .json import deserialize from .service import ( Service, filter_service_sta...
from tqdm import tqdm import os import sys from indicnlp.normalize.indic_normalize import DevanagariNormalizer import json import pandas as pd import random import copy DATADIR = sys.argv[1] TAGS = False if not os.path.exists(f'{DATADIR}/preprocessed'): os.makedirs(f'{DATADIR}/preprocessed') split...
from os import path, makedirs from threading import Thread from time import sleep from re import match, sub from base64 import b64decode, b64encode from binascii import b2a_hex from locale import getpreferredencoding from platform import system from pprint import pprint from random import choice, randint, sample from s...
#!/usr/bin/env python3 # Imports: standard library import os import shutil import argparse from timeit import default_timer as timer from multiprocessing import Pool, Value, cpu_count # Imports: third party import pandas as pd csv = "flowsheet.csv" count = Value("i", 0) total = Value("i", 0) def check_flowsheet_ro...
from scapy.layers.ppp import PPPoED from scapy.packet import Packet class PacketHandler: @staticmethod def filterPPPoED(packet: 'Packet') -> 'Packet': if packet.haslayer(PPPoED): PacketHandlerPPPoED.handle(packet)
from webdnn.backend.webgl.kernels.elementwise import register_elementwise_kernel from webdnn.graph.operators.elu import Elu register_elementwise_kernel(Elu, "y = x0 < 0.0 ? (exp(x0) - 1.0) : x0;")
def test(): assert ( "token1.similarity(token2)" or "token2.similarity(token1)" in __solution__ ), "你有计算两个token之间的相似度吗?" assert ( 0 <= float(similarity) <= 1 ), "相似度分数是一个浮点数。你确定你计算正确了吗?" __msg__.good("厉害!")
from .logger_helper import get_logger, init_logger from .time_helper import get_cur_time, TrainTimeHelper from .meter import AverageMeter from .misc import read_yaml, combine_submissions
import glob import os import pickle from collections import defaultdict import numpy as np from tqdm import tqdm from transformers import BertTokenizer, BertForMaskedLM, BertConfig, RobertaTokenizer, RobertaForMaskedLM, RobertaConfig from amnesic_probing.encoders.bert_encoding import lm_encoding, bert_based_encoding,...
"""Application module.""" from dependency_injector.wiring import Provide from flask import Flask from flask_bootstrap import Bootstrap from flask_executor import Executor from dermomedic.containers import Container from dermomedic import views def create_app() -> Flask: app = Flask(__name__) container = Conta...
#encoding:utf-8 subreddit = 'lost' t_channel = '@lostbackup' def send_post(submission, r2t): return r2t.send_simple(submission)
from dataclasses import dataclass from test.pycardano.util import check_two_way_cbor from typing import Union import pytest from pycardano.exception import DeserializeException, SerializeException from pycardano.plutus import ( COST_MODELS, ExecutionUnits, PlutusData, Redeemer, RedeemerTag, pl...
from src.features import healthcare from unittest import TestCase import pandas as pd from src.data.entities import prop_age, prop_gender, prop_ishealthcare class TestHealthcare(TestCase): def test_healthcare(self): age = list(range(0, 85)) gender = [0] * len(age) + [1] * len(age) age = ag...
# 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...
# Generated by Django 3.0 on 2019-12-04 07:06 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Game', fields=[ ('id', models.AutoField(auto_...
from sys import stdin readline = stdin.readline N = int(readline()) tlr = [map(int, readline().split()) for _ in range(N)] lr = [] for t, l, r in tlr: if t == 1: lr.append((l, r)) elif t == 2: lr.append((l, r - 0.1)) elif t == 3: lr.append((l + 0.1, r)) elif t == 4: lr...
#!/usr/bin/env python import os import os.path as op import sys import argparse from Bio import SeqIO if __name__ == "__main__": parser = argparse.ArgumentParser( description = 'unknown' ) parser.add_argument( 'org', nargs = "?", default = "HM034", help = 'genome to valid' ) args = ...
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # All rights reserved. # # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. import os import socket from string import Template from typing import List, Any def ge...
import sys import glob newx, newy, newz = float(sys.argv[1]), float(sys.argv[2]), float(sys.argv[3]) filelist = glob.glob('dist_density_*.txt') # Read first file with open(filelist[0]) as fh: data = fh.readlines() data = [line.strip().split() for line in data] idens = int(data[0][0]) x0 = float(data[1][0]) y0 =...
# This program is free software: you can redistribute it and/or modify it under the # terms of the Apache License (v2.0) as published by the Apache Software Foundation. # # This program is distributed in the hope that it will be useful, but WITHOUT ANY # WARRANTY; without even the implied warranty of MERCHANTABILITY or...
""" .. _knowledge_graph: Import and Analyze Knowledge Graph Results on a Large Scale =========================================================== If :ref:`analyzing SERPs <serp>` is the first step in understanding your rankings on search engines, then analyzing the knowledge graph can be thought of as step zero. SERP...
# Copyright (c) 2018, MD2K Center of Excellence # 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 conditio...
import os import networkx as nx from topology.generic_topology_provider import GenericTopologyProvider from topology.topology_zoo.file_mapping import file_map from utility import utility class TopologyZoo(GenericTopologyProvider): @staticmethod def get_topology_names(): """ returns names of all supp...
TAPIINT32 = "int" TAPIUINT32 = "unsigned int" TAPIINT64 = "long long" TAPIUINT64 = "unsigned long long" TAPIUINT16 = "unsigned short" TAPIUINT8 = "unsigned char" TAPIREAL64 = "double" TAPICHAR = "char" TAPISTR_10 = "string" TAPISTR_20 = "string" TAPISTR_30 = "string" TAPISTR_40 = "string" TAPISTR_50 = "string" TAPISTR_...
# Copyright 2021 Google LLC. 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 applicable law or a...
import os import json import requests class GithubIssueService: def get_auth(self): username, password = os.environ['gh-username'], os.environ['gh-password'] return username, password def get_repo(self): owner, name = os.environ['gh-owner'], os.environ['gh-name'] return owner, ...
import pytest import dash_html_components as html from app import app def test_layout_is_a_function_that_returns_a_div_element(): assert isinstance(app.layout(), html.Div)
from dataclasses import dataclass @dataclass class ObjFilesMk: asm_dir: str files: list[str] file_ext: str def strip(path: str) -> str: return path.strip().replace("\\", "").replace("\n", "") def __init__(self, path: str, asm_dir: str, file_ext: str): self.asm_dir = asm_dir ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # Source file for Microsoft Bulletin information # # Software is free software released under the "Modified BSD license" # # Copyright (c) 2016-2017 Pieter-Jan Moreels - pieterjan.moreels@gmail.com # Copyright (c) 2017 Hicham MEGHERBI # Copyright (c) 2017 ...
from PIL import Image, ImageTk from tkinter import NW from math import fabs class Piece: def __init__(self,x:int,y:int,typ:str,color:chr): self.x = x self.y = y self.typ = typ self.color = color self.img = ImageTk.PhotoImage(Image.open("imgs\\"+color+"_"+typ+".png").resize((64,64))) self.select...
from dash import html from dash import dcc from datetime import date from dateutil.relativedelta import relativedelta dashboard_filters = html.Div([ html.Div([ html.P('Data', className="panel__item-filter__dropdown-label"), dcc.DatePickerRange( id='my-date-picker-range', cla...
from scipy import misc import matplotlib.pyplot as plt import numpy as np l = misc.lena() l = l.astype(np.float64, copy=False) l = l/np.max(l) #rescale pixels into [0,1] plt.imshow(l, cmap=plt.cm.gray) #plt.show() from PIL import Image, ImageDraw num_lines = 5 width = 5 imshape = l.shape def drawRandLine(draw,widt...
from __future__ import print_function, division, absolute_import class SpinLock(object): def __init__(self): self.buffer = [0] self.current_idx = 0 self.max_val = 0 def spin(self, n): # print('start:', self.buffer, self.buffer[self.current_idx]) for i in range(n): ...
import requests from tqdm import tqdm from time import sleep BLOCK_SIZE = 1024 STATUS_WAIT_TIME = 3 N_TRAILS = 5 FAIL_SLEEP_TIME = 1 class Exporter: def __init__(self, client): self.client = client def download_file(self, url, export_file): with requests.get(url, stream=True, allow_redirects...
""" Slider widgets. """ from . import QtWidgets, QtCore, QtGui from .labelled_line_edit import LabelWithLineEdit from .editable_label import EditableLabel from typing import Any, List class Slider(QtWidgets.QSlider): """ Slider class """ def __init__(self, slider_id: Any, orientation...
from distutils.core import setup setup( name='mfMath', version='0.9.9999', author='Mat Fournier', author_email='mat@matfournier.com', packages=['mfMath'], scripts=['mfMath/util.py'], url='https://github.ubc.ca/mat4nier/DSCI_524_lab1_python', license='LICENSE.txt', description='Usefu...
from math import hypot co = float(input('Digite o cateto oposto:')) ca = float(input('Digite o cateto adjacente:')) r = hypot(co,ca) print('O comprimento da hipotenusa será {:.2f}'.format(r))
""" --- Day 1: Report Repair --- https://adventofcode.com/2020/day/1 """ import aocd DATA = set(int(line) for line in aocd.data.splitlines()) def find(s, n, inputs): if n == 1: return (s,) if s in inputs else None for i in inputs: rem = s - i if i >= rem / (n - 1): contin...
from math import sqrt a = int(input('Введите коэфициент а=')) b = int(input('Введите коэфициент b=')) c = int(input('Введите коэфициент c=')) # y = a*(x**2)+ b*x + c d = b*b - 4*a*c if d > 0: x1 = ( -b + sqrt(d))/ 2 x2 = ( -b - sqrt(d))/ 2 print('х1=', x1) print('х2=', x2) elif d == 0: ...
from .app import create_app '''Entry point to Twitoff app.''' tAPP = create_app()
"""Tests of proto.py """ import unittest import time from reversi.board import BitBoard from reversi.strategies.common import Timer from reversi.strategies import MinMax2, NegaMax3, AlphaBeta4, AB_T4, AB_TI class TestAlphaBeta(unittest.TestCase): """alphabeta """ def test_proto_minmax2_init(self): ...
#zR -*- coding: utf-8 -*- """ ./dev.py -t custom:affine_invariance=False,adapteq=True,fg_on=False --db Elephants_drop1_ears --allgt --index=0:10 --guiview # NOQA """ from __future__ import absolute_import, division, print_function, unicode_literals from os.path import join import numpy as np import utool as ut import ...
import torch import torch.nn as nn from model.utils import create_pointnet_components, create_mlp_components __all__ = ['pvt_semseg'] class pvt_semseg(nn.Module): blocks = ((64, 1, 32), (64, 2, 16), (128, 1, 16), (1024, 1, None)) def __init__(self, seg_num_all=13, width_multiplier=1, voxel_resolution_mult...
""" Transaction-related classes and functions. Many of the classes and functions importable from this module are defined and implemented using Cython, for speed. See `_tx_c.pyx`. """ # Make some names importable from this module: from ._tx_c import Tx, TxOutput, TxInput, CoinbaseTxInput from ._tx_c import deserializ...
#!/usr/bin/env python3 # encoding: rot-13 cevag('Uryyb, jbeyq!')
from src.constants import AMINO_ACIDS, WATER_MASS, SINGLY_CHARGED_B_BASE, SINGLY_CHARGED_Y_BASE, DOUBLY_CHARGED_B_BASE, DOUBLY_CHARGED_Y_BASE, INTEGER_ORDERED_AMINO_ACIDS, PROTON_MASS import numpy as np def b_ions(sequence: str, charge: int = None): '''calculate b ion masses for a sequence for a given charge(s) ...
"""Gradient Modes and InvTorch State""" from contextlib import contextmanager import torch __all__ = ['backward_mode', 'in_backward_mode', 'dry_mode', 'in_dry_mode'] def in_backward_mode(): """Whether we are in backward""" return backward_mode.flag @contextmanager def backward_mode(enabled=True): """E...
# -*- coding: utf-8 -*- """ Configuration file reading/writing. """ from __future__ import absolute_import, division, print_function, \ unicode_literals import codecs import logging import logging.config import os.path from bottle import template from yaml import load, dump try: from yaml import CLoader as ...
# Copyright 2020 StreamSets Inc. # # 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 writi...
# Copyright (c) 2022 PaddlePaddle 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 appli...
import docplex.cp.model as cp class PersonalCallback(cp.CpoCallback): """ Class inheriting cp.CpoCallback The "invoke" method must be overwritten When an object of this class is added to the model with : model.add_solver_callback(PersonalCallback()) several events will be invoked during so...