content
stringlengths
5
1.05M
import time from neomodel import ( StructuredNode, StringProperty, IntegerProperty, BooleanProperty, ) from authlib.oauth2.rfc6749 import ( TokenMixin, AuthorizationCodeMixin, ) class OAuth2AuthorizationCodeMixin(AuthorizationCodeMixin): code = StringProperty(max_length=120, unique_index=T...
#!/usr/bin/env python # Copyright 2016 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. """Copy a directory and ignore some paths. This copies directories and files without access stats. """ import os import shutil import...
''' Generate root merkle tree hash in python. I use https://github.com/bitcoin/bitcoin as reference: BlockBuildMerkleTree --> Satoshi implmentation BlockMerkleRoot ---> new bitcoin core implementation ''' import pandas as pd from hashlib import sha256 from io import StringIO # h( h(1) + h(2) ) # 0df4085b3a6...
# -*- coding:utf-8 -*- # https://mp.weixin.qq.com/s/C6o6T9ju34vAxNBg5zobWw import math import os def JudgeEvenOrOddNumber(num): if num % 2 == 1: print("{0} is Odd.".format(num)) else: print("{0} is Even.".format(num)) if num & 1 == 1: print("{0} is Odd.".format(num)) else: ...
# This file was automatically created by FeynRules $Revision: 535 $ # Mathematica version: 7.0 for Mac OS X x86 (64-bit) (November 11, 2008) # Date: Fri 18 Mar 2011 18:40:51 from object_library import all_couplings, Coupling from function_library import complexconjugate, re, im, csc, sec, acsc, asec ################...
import gdal import numpy as np class RSImage(object): def __init__(self, file_path): self.img_path = file_path self.img_metaInfo = None self.projection = None self.dataTypeName = None self.geoTransform = None self.bandCount = 1 self.dataset = N...
# -*- coding: utf-8 -*- """ Tencent is pleased to support the open source community by making BK-BASE 蓝鲸基础平台 available. Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved. BK-BASE 蓝鲸基础平台 is licensed under the MIT License. License for BK-BASE 蓝鲸基础平台: ------------------------------------------...
# Copyright 2020 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 agreed to...
import matplotlib.pyplot as plt import numpy as np PM_times = [] cap_range = [10, 100, 250, 500] for i in range(len(cap_range)): filename = "../../results/outputs/Experiment_Binary_Cap/outBU_" + str(cap_range[i]) f = open(filename, "r") PM_times += [[]] for line in f.readlines(): words = line.strip().split(" ...
# Author : @Moglten # Fizz , Buzz and Fizzbuzz # from 1 to 100 def printFizzBuzz(n) : for x in range(1,n+1) : print(x) if print_FizzBuzz(x) else None def print_FizzBuzz(n): if n % 5 == n % 3 == 0: print( "FizzBuzz" ) return False else: return print_Buzz( n ) def print_Buz...
#!/bin/python # title: run_monitor.py # description: This script is meant for monitoring Linux-Computers. # author: Michael Muyakwa - IT8g # created: 2019-11-02 # updated: 2019-11-22 # version: 1.5 # license: MIT # Imports der verwendeten Bibliotheken. import os # Betriebssys...
import xclim.indicators.atmos from finch.processes.wps_base import make_xclim_indicator_process from finch.processes.wps_xclim_indices import XclimIndicatorBase def test_locales_simple(): base_class = XclimIndicatorBase indicator = make_xclim_indicator_process( xclim.indicators.atmos.cold_spell_days,...
# SPDX-License-Identifier: MIT # Left blank for now.
import random import numpy as np import pytest import torch import hivemind import hivemind.averaging.averager from hivemind.averaging.allreduce import AveragingMode from hivemind.averaging.key_manager import GroupKeyManager from hivemind.averaging.load_balancing import load_balance_peers from hivemind.averaging.part...
"""empty message Revision ID: 5dea293ee313 Revises: 84f11a2b5659 Create Date: 2021-07-29 14:45:35.873685 """ from alembic import op import sqlalchemy as sa from sqlalchemy.sql import column, table from sqlalchemy.sql.sqltypes import Boolean, String # revision identifiers, used by Alembic. revision = '5dea293ee313' ...
############# Credits and version info ############# # Definition generated from Assembly XML tag def # Date generated: 2018/12/03 04:56 # # revision: 1 author: -DeToX- # Created layout of plugin # revision: 2 author: DeadCanadian # naming tags # revision: 3 author: Moses_of_Egypt # Cleaned up and conv...
# coding: utf-8 import socketserver import email from io import StringIO import os # Copyright 2013 Abram Hindle, Eddie Antonio Santos # # Changes made by Joshua Smith # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obt...
# -*- coding: utf-8 -*- """ Модуль графической диаграммы для сомпонентов Table, QTable """ # pylint: disable=line-too-long import matplotlib.pyplot as plt from pyss.pyss_const import * from pyss import statisticalseries from pyss.pyssownerobject import PyssOwnerObject # Вывод графической диаграммы для сомпонента T...
import io import os from django.core.files.uploadedfile import SimpleUploadedFile from PIL import Image import pytest from app.models import Photo def generate_image(filename): file = io.BytesIO() image = Image.new('RGBA', size=(10, 10), color=(0, 0, 0)) image.save(file, 'png') file.name = filename ...
from django.test import TestCase from garnett.context import set_field_language from library_app.models import DefaultBook class DefaultTestCase(TestCase): """Test setting of default on translated field""" def test_default(self): """Test that default is returned by getter""" book = DefaultBo...
import os import glob from gooey import Gooey, GooeyParser from auto_crop.image import Image def _get_args(): parser = GooeyParser( prog="autocrop", description="tool to automatically crop images based on shapes" ) parser.add_argument( "folder", help="the place with all the images", widg...
# -*- coding: utf-8 -*- # Copyright 2018 The Blueoil 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 # # Unles...
# std from typing import Optional # external from alembic import util from alembic.config import Config from alembic.script import ScriptDirectory import pkg_resources from .cli_utils import load_config GLOBAL_VERSION_PATH = pkg_resources.resource_filename("molar", "migrations/versions") def get_alembic_config(ctx...
from .parser import * from .line import * from .obfuscator import * from .simulator import * from .generator import *
from catalyst.__version__ import __version__ # noqa: F401
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved from . import datasets, models, util __all__ = ["models", "util", "datasets"]
# create_schema.py import sqlite3 # conectando... conn = sqlite3.connect('base.db') # definindo um cursor cursor = conn.cursor() # criando a tabela (schema) cursor.execute(""" CREATE TABLE consultas ( id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, texto VARCHAR(200) NOT NULL, tip...
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # Copyright (c) 2010 Citrix Systems, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you m...
"""Using `weakref` to create a cache.""" import gc from weakref import WeakValueDictionary import pytest def test_weakref() -> None: """Use a `WeakValueDictionary` to cache large object.""" class BigImage: """Dummy class to simulate a large object.""" def __init__(self, value: int) -> None...
class Person(Object): def __init__(agent, past_traj, intention_getter, pos,): self.agent = agent self.neighbor = initial_neighbor_from_set(pos) self.pos = pos self.intention = intention_getter(past_traj) def learn(): # a network predicting traj from current neighbor and pos and intention
#------------------------------------------------------------------------------ # Copyright (c) 2005, Enthought, Inc. # All rights reserved. # # This software is provided without warranty under the terms of the BSD # license included in enthought/LICENSE.txt and may be redistributed only # under the conditions describe...
from .base import X11BaseRecipe class LibXxf86dgaRecipe(X11BaseRecipe): def __init__(self, *args, **kwargs): super(LibXxf86dgaRecipe, self).__init__(*args, **kwargs) self.sha256 = '8eecd4b6c1df9a3704c04733c2f4fa93' \ 'ef469b55028af5510b25818e2456c77e' self.name = 'li...
"""Kotlin JS Rules""" load("@io_bazel_rules_kotlin//kotlin:kotlin.bzl", _kt_js_import = "kt_js_import", _kt_js_library = "kt_js_library") load("@io_bazel_rules_kotlin//kotlin/internal:defs.bzl", "KtJsInfo") load("//third_party/bazel_rules/rules_kotlin/kotlin/js:impl.bzl", "kt_js_import_impl") kt_js_library = _kt_js_l...
# 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 pandas as pd import warnings warnings.simplefilter("ignore") import pickle from sklearn.linear_model import LinearRegression data = pd.read_csv(r'C:\Users\Prasanna\Desktop\model deployment\Admission_Predict.csv') data.columns X = data.drop('Chance of Admit ', axis = 1).copy() y = data['Chan...
import pygame #button class class Button(): def __init__(self, x, y, image, scale): width = image.get_width() height = image.get_height() self.X = x self.Y = y self.image = pygame.transform.scale(image, (int(width * scale), int(height * scale))) self.rect = self.image.get_rect() self.rect.topleft = (sel...
import pprint import numpy as np from core.net_errors import NetIsNotInitialized def calculate_average_neighboring(net_object): if net_object.net is None: raise NetIsNotInitialized() net = net_object.net zero_weights = np.zeros((net_object.config[0])) weights = np.ma.array(np.reshape(net[...
"""Exercício Python 064: Crie um programa que leia vários números inteiros pelo teclado. O programa só vai parar quando o usuário digitar o valor 999, que é a condição de parada. No final, mostre quantos números foram digitados e qual foi a soma entre eles (desconsiderando o flag).""" n = int(input('1º Número: ')) som...
from detectron2.data.datasets import load_cityscapes_instances from detectron2.data.datasets.cityscapes import load_cityscapes_semantic, cityscapes_files_to_dict from pycocotools.coco import COCO import functools import multiprocessing as mp from detectron2.utils import logger from detectron2.utils.comm import get_worl...
from .user_urls import *
from behave import given, when, then from acceptance_tests.features.pages import collection_exercise, collection_exercise_details from common.browser_utilities import is_text_present_with_retry, wait_for @given('the collection exercise is Scheduled') def collection_exercise_exists_and_scheduled_displayed(context): ...
from django.urls import path,include from rest_framework.routers import DefaultRouter from loan_app import views router = DefaultRouter() router.register('approval',views.ApprovalViewSet) urlpatterns = [ path('',include(router.urls)), ]
from joecool import create_app app = create_app()
from hamcrest import assert_that, equal_to, is_ from marshmallow import Schema from microcosm_flask.fields import TimestampField from microcosm_flask.swagger.api import build_parameter class TestSchema(Schema): unix_timestamp = TimestampField() iso_timestamp = TimestampField(use_isoformat=True) def test_fi...
""" Usage: trained_oie_extractor [--model=MODEL_DIR] --in=INPUT_FILE --out=OUTPUT_FILE [--tokenize] [--conll] [--beam=BEAM] Options: --beam=BEAM Beam search size [default: 1]. Run a trined OIE model on raw sentences. MODEL_DIR - Pretrained RNN model folder (containing model.json and pretrained weights). INPUT F...
import pathlib import numpy as np from math import log from pudzu.sandbox.wikipage import * from pudzu.sandbox.bamboo import * # wikifame scraping (messy; also requires manual cleanup and verificaiton at the moment) def extract_births(year): DATE_PATTERN = re.compile(r"^[_ 0-9]*(January|February|March|...
from __future__ import annotations import socket import sys from io import StringIO from typing import Iterable from .._exceptions import MarkerError, OfflineContractError, SilentContractError from .._types import ExceptionType KNOWN_MARKERS = frozenset({ # io markers 'io', 'network', 'read', 's...
from django.db import models from django.db.models import PROTECT from moneybird_accounting.models import MoneybirdReadWriteResourceModel class LedgerAccount(MoneybirdReadWriteResourceModel): class Meta: verbose_name = "ledger account" verbose_name_plural = "ledger accounts" moneybird_resour...
import random import server.tca.cellaut as ca class TCARule(ca.Rule): vmax = 3 random_slow_p = 0.3 background = 0 change_lane_p = 0.2 class StatesRule(TCARule): """Rules for calculating new state of non-empty cells""" def populate(self, map, address): self.address = address ...
from django.conf.urls import url from django.views.decorators.csrf import csrf_exempt from rest_framework_jwt.views import obtain_jwt_token from rest_framework_jwt.views import refresh_jwt_token from .views import PrivateGraphQLView urlpatterns = [ url(r'^graphql', csrf_exempt(PrivateGraphQLView.as_view(graphiql=...
from matplotlib.pyplot import get from pip import main import torch import gpytorch from config.modelconfig import * from tools.processdata import read_data, get_data, res_data, dwt_data_ca, dwt_data_cd def train(config, is_res): all_data = read_data(config.data_path) if is_res: train_x, train_y, t...
from math import ceil import redis import json import requests import pymysql from flask import g from steem import Steem from steem.amount import Amount from pymongo import MongoClient from dateutil.parser import parse from datetime import datetime from . import settings _steem_connection = None _mongo_connection =...
############################################################################## # Copyright (c) 2017 ZTE Corp and others. # # All rights reserved. This program and the accompanying materials # are made available under the terms of the Apache License, Version 2.0 # which accompanies this distribution, and is available at...
# This sample tests various assignment scenarios where # there is an expected type, so bidirectional type # inference is used. # pyright: strict from typing import Dict, Callable, Sequence, Tuple AAA = float BBB = int CCC = str DDD = str AAATuple = Tuple[AAA, BBB, Callable[[Sequence[int], AAA], Sequence[float]]] d...
##! python 3 ''' WHAT IS IT APP LAUNCHER developed by Mr Steven J walden Sept. 2020 SAMROIYOD, PRACHUAP KIRI KHAN, THAILAND [See License.txt file] ''' #Gui's and Sprite classes for game import sys from PyQt5 import QtWidgets, QtGui, QtCore import pygame as pg from methods import * class StartUpGui(QtWidgets....
from unittest.mock import MagicMock import pytest from auto_backup.argument_assigner import assign_arguments_to_self class AssignArgumentsMock(object): def __init__(self, water, earth="brown", *, wind, fire="purple"): assign_arguments_to_self() def values(self): return self.water, self.eart...
""" Incorrect hook file The hook file must be in the same directory as the package. This file is in a directory named by ``hook_import_dirs``, and we check that it is NOT found. """
# Project: MapServer # Purpose: xUnit style Python mapscript tests of clusterObj # Author: Seth Girvin # # =========================================================================== # Copyright (c) 2019, Seth Girvin # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software...
from hashlib import md5 import igql from .constants import IG_URL def set_instagram_gis(kwargs, rhx_gis): if "variables" in kwargs["params"]: kwargs["headers"]["x-instagram-gis"] = md5( (f'{rhx_gis}:{kwargs["params"]["variables"]}').encode() ).hexdigest() return kwargs def get_...
import pandas from sklearn import linear_model def predict(x: str,y: str,c: str, day: str): df = pandas.read_csv(x) depented = df[[c]] independent = df[[y]] linear = linear_model.LinearRegression() linear.fit(depented, independent) global cases_predict cases_predict = linear.p...
import os from loguru import logger from .common import retrieve_data, retrieve_data_gen, json_dump, mkdir_p import codecs def backup_issues(username, password, repo_cwd, repository, repos_template, since=None): #has_issues_dir = os.path.isdir('{0}/issues/.git'.format(repo_cwd)) # if args.skip_existing and h...
from pyverse import Pyverse import re import statistics def count_letters(text): count = 0 for char in text: if char.isalpha(): count += 1 if count == 0: return 1 else: return count def count_sentences(text): text = text.replace("\n", "") ...
import numpy as np class PoseCreateLayer(object): def __init__(self, num_joint, top, bottom, error_order): self.num_joint_ = num_joint self.top = top self.bottom = bottom self.error_order_ = error_order if bottom[0].width() != self.num_joint_ * 2: print("The ...
# -*- coding: utf-8 -*- """ Created on Sun Jul 25 00:58:52 2021 @author: 20210595 """ from space_to_vector2 import export, positions, positionClassifier, positionPreprocess from typing import Any from gama.genetic_programming.components.individual import Individual from gama.genetic_programming.compilers.scikitlearn ...
import dash import dash_core_components as dcc import dash_html_components as html import dash_table import plotly.express as px import dash_bootstrap_components as dbc from dash.dependencies import Input from dash.dependencies import Output from dash.dependencies import State import pandas as pd from dashboard_da...
import pickle import subprocess import sys import fire import pandas as pd import tensorflow as tf import datetime import os CSV_COLUMNS = ['gender', 'SeniorCitizen', 'Partner', 'Dependents', 'tenure', 'PhoneService', 'MultipleLines', 'InternetService', 'OnlineSecurity', 'OnlineBackup...
import sys import logging from collections import OrderedDict from substance import (SubProgram, Core) class Box(SubProgram): def __init__(self): super(Box, self).__init__() def setupCommands(self): self.addCommand('ls', 'substance.command.box.ls') self.addCommand('pull', 'substance...
import numpy as np import matplotlib.pyplot as plt N = 5000 #number of steps to take xo = 0.2 #initial position in m vo = 0.0 #initial velocity tau = 4.0 #total time for the simulation in s . dt = tau/float(N) # time step k = 42.0 #spring constant in N/m m = 0.25 #mass in kg g = 9.8 #in m/ s ^2 mu = 0.15 #friction coe...
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! import grpc from example import application_pb2 as example_dot_application__pb2 class UserMortgageServiceStub(object): # missing associated documentation comment in .proto file pass def __init__(self, channel): """Constructor. Args...
# -*- coding: utf8 -*- "Increment filter" from .abstract import AbstractFilter class Increment(AbstractFilter): "Increment a variable" name = 'Incrémenter variable' description = "Incrémente une variable numérique" parameters = [ { 'name': 'Variable', 'key': 'target',...
class Phrase: """A Phrase is a directed edge between one Paragraph and a second Paragraph. These two Paragraphs can be the same. The Phrase also has the ability to display text, but this should typically be short, with longer description left to Paragraphs. To identify themselves, Phrases have na...
from django.contrib import admin from applications.blog.models import Comments from applications.blog.models import Post @admin.register(Post) class PostAdminModel(admin.ModelAdmin): pass @admin.register(Comments) class CommentAdminModel(admin.ModelAdmin): pass # class Comment(admin.ModelAdmin): # li...
import requests from pyloggerhelper import log base_schema_properties = { "log_level": { "type": "string", "title": "l", "description": "log等级", "enum": ["DEBUG", "INFO", "WARN", "ERROR"], "default": "DEBUG" }, "base_url": { "type": "string", "title":...
from .context import KerasTools import pandas as pd class TestRNN: def setup(self): self.sales_df = pd.read_csv('https://raw.githubusercontent.com/torch/demos/master/logistic-regression/example-logistic-regression.csv') self.helper = "" def test_util(self): ...
from setuptools import setup, find_packages file = open('README.md', 'r') long_description = file.read() file.close() setup( name='gitcode', version='0.1', description='Interact with Git through Python', long_description=long_description, url='https://github.com/WindJackal/gitcode', autho...
#!/usr/bin/python # Copyright 2014 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. """Contains test runners for launching tests on simulators and devices.""" # pylint: disable=relative-import import environment_setup imp...
""" pySlip demonstration program with user-selectable tiles. Usage: pyslip_demo.py <options> where <options> is zero or more of: -d|--debug <level> where <level> is either a numeric debug level in the range [0, 50] or one of the symbolic debug level names: NOTSET 0 nothing is lo...
from django.db import models from django.utils.translation import gettext as _ from main.models import File, BaseModel class History(BaseModel): text = models.TextField() class Meta: verbose_name = _('History') verbose_name_plural = _('Histories') def __str__(self): return self....
import cv2 import pafy import numpy as np import glob from hitnet import HitNet, ModelType, draw_disparity, draw_depth, CameraConfig # Initialize video # cap = cv2.VideoCapture("video.mp4") videoUrl = 'https://youtu.be/Yui48w71SG0' videoPafy = pafy.new(videoUrl) print(videoPafy.streams) cap = cv2.VideoCapture(videoPa...
''' Created on Jul 6, 2018 @author: kumykov Wrapper for common HUB API queries. Upon initialization Bearer tocken is obtained and used for all subsequent calls Usage: credentials and hub URL could be placed in the .restconfig.json file { "baseurl": "https://hub-hostname", "username": "<userna...
# Adapted for numpy/ma/cdms2 by convertcdms.py import vcs import cdms2 as cdms import EzTemplate import support import os def clear(*args, **kargs): x = kargs['canvas'] x.clear() def plot_ts(*args, **kargs): x = kargs['canvas'] i = kargs['index_x'] j = kargs['index_y'] x.clear() x.plot(s...
"""底层的数据库引擎, 初期代码可能会比较丑陋""" from typing import Dict from peewee import MySQLDatabase, PostgresqlDatabase, SqliteDatabase, Model, CharField, FloatField, IntegerField, \ DateTimeField from ctpbee import current_app from ctpbee.exceptions import ConfigError type_map = { 'sqlite': SqliteDatabase, 'mysql': MyS...
import tkinter as tk from tkinter import filedialog from tkinter import * from PIL import ImageTk, Image import numpy #To classify sign load the trained model. from keras.models import load_model model = load_model('traffic_classifier.h5') #dictionary for labelling all traffic signs classes. classes = { 1:'Speed limi...
import datetime import os from jinja2 import Environment, FileSystemLoader from bin.contentctl_project.contentctl_core.domain.entities.security_content_object import SecurityContentObject class ConfWriter(): @staticmethod def writeConfFileHeader(output_path : str) -> None: utc_time = datetime.datetim...
import os import numpy as np import matplotlib as mpl mpl.use('Agg') import matplotlib.pyplot as plt import pandas as pd import seaborn as sns import matplotlib.style as style def APA_usage(bamfile, APA_sitefile, celltype, gene): """ Get the abundance for each cell barcode for each APA in the gene. :param bam...
# vim: tabstop=4 shiftwidth=4 softtabstop=43 # Copyright 2013 IBM Corp. # # 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 # #...
# This is the practice on the web crawling book from urllib.request import urlopen import requests from bs4 import BeautifulSoup import re import pymysql.cursors import random import datetime #用系统当前时间生成一个随机数生成器,这样可以保证在每次程序运行的时候,维基百科词条的选择都是一条全新的随机路径 # random.seed(datetime.datetime.now()) # # # def get_links(article_ur...
from django.urls import path from accounts.views import signup_view urlpatterns = [ path('signup/', signup_view, name="signup_view"), ]
import swigstarterkit si = swigstarterkit.Script_Interface(); print si.get_a_value();
""" TODO: Docstring """ import numpy as np class Replay(object): """ For RL a memory of experiences must be written to train the batches with old experiences and returns in the form of (s, a, r, s'). """ def __init__(self, max_memory=100, discount=.9): """TODO: Docstring for __init__. ...
# stdlib import copy # 3p from mock import Mock from nose.plugins.attrib import attr # project from tests.checks.common import AgentCheckTest INSTANCE = { 'class': 'Win32_PerfFormattedData_PerfProc_Process', 'metrics': [ ['ThreadCount', 'proc.threads.count', 'gauge'], ['IOReadBytesPerSec', 'p...
# Autogenerated by onnx-model-maker. Don't modify it manually. import onnx import onnx.helper import onnx.numpy_helper from onnx_model_maker import omm from onnx_model_maker import onnx_mm_export from onnx_model_maker.ops.op_helper import _add_input @onnx_mm_export("v12.LessOrEqual") def LessOrEqual(A, B, **kwargs):...
# This source file is part of the Aument language # Copyright (c) 2021 the aument contributors # # Licensed under Apache License v2.0 with Runtime Library Exception # See LICENSE.txt for license information import re import os def cleanup_params(array): def each_line(x): return CMT_CONT_REGEX.sub("", x) ...
import streamlit as st import pandas as pd import numpy as np import torch from PIL import Image, ImageChops import os from torch.nn.functional import cross_entropy from streamlit_image_comparison import image_comparison st.set_page_config(layout="wide") @st.cache(allow_output_mutation=True) def load_model(): ...
class Logger(): ''' Logs information about model progress into a file ''' def __init__(self, filename=None): if filename is None: self.f = None else: self.f = open(filename,'a') def log(self, message): ''' Adds message file ''' print(message) ...
""" Provides a dataclass for shared variables across server processes """ from dataclasses import dataclass from multiprocessing import Barrier, Value @dataclass class SharedVariables: """Shared variables used across the server processes""" compute_barrier: Barrier write_barrier: Barrier price_shared...
import pyqbdi import struct import rpyc import sys conn = None SEG_PROT_R = 4 SEG_PROT_W = 2 SEG_PROT_X = 1 # implements the methods defined in the abstract class angrdbg.Debugger class AngrQBDI(object): def __init__(self, vm, mod): self.name = "AngrQBDI" self.vm = vm self.mod = mod ...
from flask import Flask from noteapp.views.index import bp as index_bp app = Flask(__name__) app.register_blueprint(index_bp)
from ..util import orm async def get_voice_roles_by_guild(guild_id): result = await orm.select( 'SELECT guild_id, voice_channel_id, role_id FROM voice_role WHERE guild_id=%s;', [guild_id] ) return result async def create_voice_role(guild_id, voice_channel_id, role_id): aw...
import sklearn import os from joblib import dump, load skip = [36, 52, 13, 39, 68, 69, 78, 79, 32, 33, 34, 72, 73, 57, 74, 75, 64] class_dict = { 0: "W", 1: "N1", 2: "N2", 3: "N3", 4: "REM", 5: "UNKNOWN" } def evaluateAcc(true, predictions): total = true.shape[0] tota...