content
stringlengths
5
1.05M
""" Comparing ANN and linear model for evaluating model biases, differences, and other thresholds using explainable AI for historical data (and SMOOTHED data) Author : Zachary M. Labe Date : 19 May 2021 Version : 1 - adds extra class (#8), but tries the MMean """ ### Import packages import matplotlib.py...
import calendar from datetime import datetime import decimal import xml.etree.ElementTree as xmlET def dparse(*dstr): """Convert date string to datetime. This function is used by Pandas to parse dates. If only a year is provided the returned datetime will be for the last day of the year (e.g. 12-31). ...
import cv2 import numpy as np from matplotlib import pyplot as plt from tkinter import filedialog from tkinter import * root = Tk() root.withdraw() root.filename = filedialog.askopenfilename(initialdir = "/",title = "Select file",filetypes = (("all files",".*"),("jpg files",".jpg"))) img = cv2.imread(root.fi...
from __future__ import print_function import os import json import numpy as np import dask import toolz as tz import functools from .io import IoN5, IoHDF5 # IoDVID def load_input(io, offset, context, output_shape, padding_mode='reflect'): starts = [off - context[i] for i, off in enumerate(offset)] stops =...
from asyncio import get_event_loop from typing import Any, Coroutine, Optional from inspect import iscoroutinefunction from .src import IPSWME, SHSH2, SWSCAN, Jailbreak, Pallas class Client: """ Main class of PyApple. """ def __init__(self, *args, **kwargs): # needs to be reworked super()....
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Oct 22 14:33:59 2019 @author: SpaceMeerkat A script for testing the trained CAE with synthetic moment maps """ # ============================================================================= # Import relevant packages # ===============================...
__all__ = [ 'Socket', 'device', 'terminate', ] import curio import curio.traps from . import ( SocketBase, errors, terminate as _terminate, ) from .constants import ( AF_SP, AF_SP_RAW, NN_DONTWAIT, ) async def device(sock1, sock2=None): """Re-implement nn_device without threa...
import logging from celery import shared_task from django.conf import settings from django.contrib.auth import get_user_model from .utils import ( change_user_password as _change_user_password, create_user as _create_user, update_user as _update_user, ) logger = logging.getLogger('kompassi') @shared...
import re pattern = re.compile(r"([A-Za-z]).([a])") text = 'Search this inside ot this text please!' a = pattern.search(text) print(a.group()) # Sea b = pattern.findall(text) print(b) # [('S', 'a'), ('l', 'a')] c = pattern.fullmatch(text) print(c) # None d = pattern.match(text) print(d) # None
from collections import OrderedDict from enum import Enum, auto from threading import RLock from typing import ( TYPE_CHECKING, Callable, Generic, Iterable, Iterator, List, Mapping, MutableMapping, NoReturn, Optional, ) from typing import OrderedDict as OrderedDictType from typin...
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: MIT-0 import time import boto3 import logging import cfnresponse from botocore.exceptions import ClientError sm_client = boto3.client('sagemaker') logger = logging.getLogger(__name__) def delete_apps(domain_id): l...
import pandas as pd class IterateWrapper: def __init__(self, iter_df, key): self.iter_df = iter_df self.key = key def __call__(self, *args, **kwargs): results = DataFrameArray() for df in self.iter_df: results.append( getattr(df, self.key)(*args, **k...
from time import sleep while True: sleep(0.1) print("Test")
# -*- coding: utf-8 -*- import scrapy from scrapy_news.items import SoccerNewsItem import scrapy_news.url_selector as url_selector #to run #scrapy crawl metro class MetroSpider(scrapy.Spider): name = 'metro' allowed_domains = ['metro.co.uk'] source = 'Metro' start_urls = url_selector.get_urls(source) ...
import redis class RedisClient: def __init__(self, db = 0): ''' Init the RedisClient instance. It should be the direct contact with the redis-server on this machine. ''' self.db = db self.redis = redis.Redis() def ping(self) -> bool: try: return self...
#!usr/bin/python # -*- coding: utf-8 -*- import random import os import numpy as np import pandas as pd from pathlib import Path from functools import partial import torch from torch import nn import warnings from fastai.torch_core import defaults from fastai import vision from fastai.data_block import CategoryList, ...
from __future__ import annotations import abc import asyncio import dataclasses import functools import io import os.path import pickle import shlex import threading import uuid from typing import Callable, TypeVar, Union, Any, Dict, Optional, Sequence, cast, Tuple import cloudpickle import fabric import paramiko.ssh...
#!/usr/bin/env python # -*- coding: utf-8 -*- import os try: from setuptools import setup except ImportError: from distutils import setup def readfile(file_path): dir_path = os.path.dirname(os.path.abspath(__file__)) with open(os.path.join(dir_path, file_path), 'r') as f: return f.read() se...
class WrappedDictionary(object): def __init__(self): self.__dict = {} def __getattr__(self, item): return self.__dict[item] def __setattr__(self, key, value): object.__setattr__(self, key, value) self.__dict[key] = value def __repr__(self): return str(self.__di...
# -*- coding: utf-8 -*- import os import unittest from manolo_scraper.spiders.osce import OSCESpider from utils import fake_response_from_file class TestOsceSpider(unittest.TestCase): def setUp(self): self.spider = OSCESpider() def test_parse_item(self): filename = os.path.join('data/osce',...
def sunday(x, n): a = x b = 0 for i in range(len(n)): q = n[i] % 7 a += q if a%7 == 0: b += 1 if a>7: a -= 7 z = [a, b] return z if __name__ == '__main__': ans = 0 day = 2 for i in range(1901,2001): pri...
""" EXERCÍCIO 011: Pintando Parede Faça um programa que leia a largura e a altura de uma parede em metros, calcule a sua área e a quantidade de tinta necessária para pintá-la, sabendo que cada litro de tinta, pinta uma área de 2 m². """ larg = float(input('Largura da parede: ')) alt = float(input('Altura da parede: ')...
import pandas as pd import numpy as np import random # Reading data set df1 = pd.read_csv('.\data\wordsDataSet.csv') # Removed Count coloumn as it was not required df1 = df1.drop('count', 1) # Added length column to remove words with small length df1['length'] = df1.word.str.len() df1 = df1[df1.length > 6.0] df2 = p...
import os from subprocess import Popen, PIPE from tempfile import TemporaryDirectory _temp_dir = None source_path = "" def reset_checkout(): global _temp_dir, source_path if _temp_dir is None: _temp_dir = TemporaryDirectory() source_path = _temp_dir.name process = Popen([ 'repo', ...
from .settings_common import * DEBUG = False # This is handy for debugging problems that *only* happen when Debug = False, # because exceptions are printed directly to the log/console when they happen. # Just don't leave it on! # DEBUG_PROPAGATE_EXCEPTIONS = True # The base location, on disk, where we want to store ...
# -*- coding=utf-8 -*- """ 自编码器的学习目标是 使用少量稀疏的高阶特征重构输入: 1. 限制中间隐层节点的数量,比如让中级那隐含层节点的数量小于输入/输出节点的数量,就相当于一个降维 再给中间隐含层的权重加一个 L1 正则,则可以根据隐含系数控制隐含节点的稀疏程度,惩罚系数越大,学到的特征组合越稀疏,实际使用(非零权重) 的特征数量越少。 2. 如果给数据加入噪声,那么就是 Denoising Auto Encoder(去噪自编码器) 唯有学习数据频繁出现的模式和结构,将无规律的噪声略去,才可...
from __future__ import print_function import logging from eosetl_airflow.build_load_dag import build_load_dag from eosetl_airflow.variables import read_load_dag_vars logging.basicConfig() logging.getLogger().setLevel(logging.DEBUG) # airflow DAG DAG = build_load_dag( dag_id='eos_load_dag', chain='eos', ...
# # Copyright (c) 2021 Nitric Technologies Pty Ltd. # # This file is part of Nitric Python 3 SDK. # See https://github.com/nitrictech/python-sdk for further info. # # 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 cop...
module_name = "main" variable_name = "app"
from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import pandas from pandas.compat import string_types from pandas.core.dtypes.cast import find_common_type from pandas.core.dtypes.common import ( is_list_like, is_numeric_dtype, ...
from PyQuantum.Common.Matrix import * import numpy as np # import pandas as pd from scipy.sparse import identity, kron, csc_matrix class Hamiltonian(Matrix): # ----------------------------------------------------------------------------------------------------------------- # ----------------------------------...
""" @Author: yshhuang@foxmail.com @Date: 2020-07-23 16:13:08 @LastEditors: yshhuang@foxmail.com @LastEditTime: 2020-07-27 17:47:49 @FilePath: /d2l-zh/srcnn/model.py """ from mxnet.gluon import nn from mxnet import initializer class SrCnn(nn.Sequential): def __init__(self, prefix=None, params=None): sup...
# -*- coding: utf-8 -*- # Generated by Django 1.9 on 2016-01-07 05:21 from __future__ import unicode_literals from django.db import migrations def create_system_financial_account(apps, schema_editor): # We can't import the FinancialAccount model directly as it may be a newer # version than this migration exp...
# -*- coding: utf-8 -*- """Regression test for issue #49.""" from __future__ import unicode_literals import unittest import os.path from xml.etree import ElementTree as ET from statik.generator import generate class TestForAdditionalPathSegmentInjection(unittest.TestCase): def test_issue(self): test_p...
import datetime from PySide2 import QtWidgets, QtGui, QtCore import fseutil from fseutil.etc.images_base64 import OFR_LOGO_1_PNG from fseutil.etc.images_base64 import OFR_LOGO_2_PNG from fseutil.gui.layout.main import Ui_MainWindow from fseutil.gui.logic.dialog_0101_adb_datasheet_1 import Dialog as Dialog0101 from fs...
from setuptools import setup def readme(): with open('README.md') as f: README = f.read() return README # This call to setup() does all the work setup( name="hdfs-lmdc", version="2.0.7", description="Esta biblioteca tem como objetivo generalizar funções da integração entre HDFS e Python ut...
import random from math import floor def Generate(GUI): h = GUI.COL w = GUI.ROW GUI.restatGrid() GUI.paintGrid() for i in range (0,w): GUI.colorCase(0,i, "dimgray") GUI.colorCase(h-1,i, "dimgray") for i in range (0,h): GUI.colorCase(i,0, "dimgray") GUI.colorCas...
import json import random import math import numpy as np import matplotlib.pyplot as plt import pandas as pd import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torch.utils.data import Dataset, DataLoader, TensorDataset from torch.utils.data.sampler import Subs...
import csv import io from typing import IO, Optional, List, Tuple, Type from .._functions import get_open_func from ._CSVFile import CSVFile, DATA_TYPE, VALUE_TYPE, TYPES_TYPE # Number of lines to sample to try and determine CSV format SAMPLE_SIZE = 4 def loadf(filename: str, encoding: str = 'utf-8', ...
""" Test the automech CLI """ import os import tempfile import subprocess from automechanic import fs AUTOMECH_CMD = 'automech' PATH = os.path.dirname(os.path.realpath(__file__)) HEPTANE_PATH = os.path.join(PATH, '../examples/heptane') def test__help(): """ test `automech -h` """ subprocess.check_call([A...
# -*- coding: utf-8 -*- # python-holidays # --------------- # A fast, efficient Python library for generating country, province and state # specific sets of holidays on the fly. It aims to make determining whether a # specific date is a holiday as fast and flexible as possible. # # Authors: dr-prodigy <maurizio....
import os import shutil import subprocess import argparse import signal import time import datetime from customized_timeout import TimeoutException,TimeoutError proc_to_kill = {"PdrChc":"z3", "Cvc4Sy": "cvc4", "PdrAbc":"abc", "RelChc":"z3"} TestSucc = \ [("GB",[("GBpdrchc","PdrChc"), ("GBcvc4sy","Cvc4Sy")])] Tes...
# Author: Michał Bednarek PUT Poznan # Comment: Helper script for validating data created from the simulation import pickle import matplotlib.pyplot as plt import numpy as np # path = "./data/dataset/final_ds/real/real_train.pickle" paths = ["./data/dataset/final_ds/real/real_train.pickle", "./data/dataset/...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ https://leetcode.com/problems/perfect-squares/description/ Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16, ...) which sum to n. For example, given n = 12, return 3 because 12 = 4 + 4 + 4; given n = 13, return 2 be...
import os from ImageSimilarity import ImageSimilarity from ReportFoto import ReportFoto class ImageWorker: def generate_reportfoto(self): lista_foto_scaricate = self.get_path_files("photo_downloaded\\") correttezza_logo = self.find_and_classify_logo(lista_foto_scaricate) presenza_competi...
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class RRodbc(RPackage): """An ODBC database interface.""" homepage = "https://cloud.r-proje...
""" genjs constant database module """ import py from pypy.rpython.ootypesystem import ootype from pypy.translator.js.opcodes import opcodes from pypy.translator.js.function import Function from pypy.translator.js.log import log from pypy.translator.js._class import Class from pypy.translator.js.support import Javasc...
''' Linearly scale the expression range of one gene to be between 0 and 1. If a reference dataset is provided, then the scaling of one gene in the target dataset in done using the minimun and range of that gene in the reference dataset. ''' import sys import argparse sys.path.insert(0, 'Data_collection_processing/') f...
from flask import Flask from flask_bootstrap import Bootstrap app = Flask(__name__) app.config.update( TESTING=True, DEBUG=True, SECRET_KEY=b'_5#y2xwL"F4Q8z\n\xec]/' ) bootstrap = Bootstrap(app) from . import routes
from __future__ import annotations import tempfile from pathlib import Path from typing import Any import cv2 import matplotlib.pyplot as plt import numpy as np import pandas as pd import typer from kaggle_imaterialist2020_model.cmd.segment import main as segment from PIL import Image from segmentation.transforms imp...
# -*- coding: utf-8 -*- """ @author: Adam Reinhold Von Fisher - https://www.linkedin.com/in/adamrvfisher/ """ #This is a brute force optimizer for a short only, martingale style, volatility trading strategy #that takes incrementally larger positions #Import modules import numpy as np import random as ra...
#!/usr/local/bin/python3 # 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 use this file except in compliance with # the L...
import unittest def es_mayor_de_dad(edad): if edad>=18 : return True else: return False class PruebaDeCristal(unittest.TestCase): #aca se hacn los tests def test_es_mayor_de_edad(self): edad = 20 resultado= es_mayor_de_dad(edad) self.assertEqual(resultado,True) ...
from django.db import models class Parent(models.Model): parent_field = models.CharField(max_length=100) class Child(Parent): child_field = models.CharField(max_length=100) class Proxy(Parent): class Meta: proxy = True class Related(models.Model): parent = models.ForeignKey(Parent) ...
import os import unittest from hamerkop.lang import * def get_filename(filename): return os.path.join(os.path.dirname(__file__), filename) def read_file(filename): with open(filename, 'r') as fp: return fp.read() def tokenize(string): return string.split() class LangTest(unittest.TestCase): ...
try: from celery.task import task except ImportError: from celery import shared_task as task @task(bind=True) def subscribe(self, email, newsletter_list_id, user_id=None, **kwargs): from courriers.backends import get_backend from courriers.models import NewsletterList from courriers import signals...
#!/usr/bin/python # Filename: ex_global.py x = 50 def func(): global x print('x is ', x) x = 2 print('Changed local x to ', x) func() print('Value of x is ', x)
import sys from util.IO import IO from util.Calendar import Calendar def main(): queryObj = IO('ssmall') print(queryObj.userName) cal = Calendar(queryObj.userName) cal.plotEvents() cal.plotNext() cal.plotPrevious() if __name__ == '__main__': sys.exit(main())
from django.urls import path from . import views app_name = "payment" urlpatterns = [ path('orders/<str:order_id>/payment/', views.AlipayView.as_view()), # 获取支付宝支付链接 path('payment/status/', views.SavePaymentView.as_view()), # 保存支付宝支付结果视图 ]
''' The file takes in an excel file and creates a csv file for searching To-Do Create a dataframe for the excel for excel_match.py ''' import pandas as pd def excel_to_csv(excel_path): excel = pd.read_excel(excel_path) cols = ['Author', 'Title', 'Edition', 'Pub Place', 'Publisher', 'Date'] exc...
import joswig_dijkstra as jd import matplotlib.pyplot as plt # import numpy as np # Recursion depth __depth__ = 10 # make sure the depth isn't too big, high enough accuracy will mess up the decimals ''' ****************** Function totalweight ****************** Given a weighted graph, returns the sum of all constant...
import queue q=queue.PriorityQueue() q.put(20) q.put(10) q.put(30)#[20,10,30] q.get() #20 q.get() #10 #indexing with priority queue qu=[] qu.append((1,"Ashwin")) qu.append((2,"Arjun")) qu.append((3,"Hari")) print(q) #[(3,"Hari"),(2,"Arjun"),(3,"Ashwin"))]
""" 面试题 55(一):二叉树的深度 题目:输入一棵二叉树的根结点,求该树的深度。从根结点到叶结点依次经过的 结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。 """ class BSTNode: """docstring for BSTNode""" def __init__(self, val): self.val = val self.left = None self.right = None def connect_bst_nodes(head: BSTNode, left: BSTNode, right: BSTNode) -> BS...
import csv import os from functools import lru_cache from typing import Iterable, List def get_first_common_element(first: Iterable[str], second: Iterable[str]) -> str: """ Get first common element from two lists. Returns 'None' if there are no common elements. """ return next((item for item in first ...
# Copyright (C) 2021 Nippon Telegraph and Telephone Corporation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICE...
# Copyright (c) 2006,2007 Mitch Garnaat http://garnaat.org/ # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modi...
import os import sys import torch from TorchProteinLibrary import FullAtomModel import numpy as np import unittest import random import math from TorchProteinLibrary.Volume import VolumeConvolution import _Volume class TestVolumeConvolution(unittest.TestCase): device = 'cuda' dtype = torch.float places = 5 batch_s...
import argparse import borg_verifier import logging import sys logger = logging.getLogger(__name__) def main(): parser = argparse.ArgumentParser() parser.add_argument('pushgateway') parser.add_argument('repos', nargs='+') parser.add_argument('--auth_username', default=None) parser.add_argument('-...
from flask import render_template,redirect,url_for, flash,request from flask_login import login_user,logout_user,login_required from . import auth from ..models import User from .forms import LoginForm,RegistrationForm from .. import db from ..email import mail_message # @auth.route('/signup',methods=['GET','POST']) ...
from flask import Flask,jsonify from flask_restplus import Api, fields, Resource from pathlib import Path from Gender_Classifier import retrainModel, normalize, name_encoding import tensorflow as tf import numpy as np import csv app = Flask(__name__) api = Api( app, version='1.X', title='Gender Classif...
crc_table = ( 0x0000, 0xC0C1, 0xC181, 0x0140, 0xC301, 0x03C0, 0x0280, 0xC241, 0xC601, 0x06C0, 0x0780, 0xC741, 0x0500, 0xC5C1, 0xC481, 0x0440, 0xCC01, 0x0CC0, 0x0D80, 0xCD41, 0x0F00, 0xCFC1, 0xCE81, 0x0E40, 0x0A00, 0xCAC1, 0xCB81, 0x0B40, 0xC901, 0x09C0, 0x0880, 0xC841, 0xD801, 0x18C0, 0x1980, 0xD941...
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2012 SINA Corp. # 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/licen...
#!/usr/bin/env python """ Copyright Gerald Kaszuba 2008 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 3 of the License, or (at your option) any later version. This program is distri...
class Solution(object): def singleNumber(self, nums): """ :type nums: List[int] :rtype: int """ # 00 for 0, 01 for 1, 11 for 2 one = 0 two = 0 for i in nums: # 00 -> 01 temp1 = one | ~one & ~two & i # 01 -> ...
from collections import defaultdict import operator from .constants import LOG_LEVELS, LOG_TYPES, LOG_ROLES def is_code_valid(code): required_keys = { "type": basestring, "level": int, "selectable_by": list, "description": basestring, "stops_timer": bool, } all_keys...
# Copyright 2022, Google LLC. # # 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 pytest from co2_diag.formatters import numstr, my_round, \ tex_escape def test_number_string_formatting_2decimals(): assert numstr(3.14159, decimalpoints=2) == '3.14' def test_number_string_formatting_largenumber(): assert numstr(3141592.6534, decimalpoints=3) == '3,141,592.653' def test_round...
#! /usr/bin/env python3 # -*- coding: utf-8 -*- import os import unittest import logging import sys import xml.etree.ElementTree as ET import fedora.rest.api as fra from fedora.utils import sha1_for_file from fedora.rest.ds import DatastreamProfile test_file = "easy-file:219890" test_dataset = "easy-dataset:5958" ...
#!/usr/bin/env python3 from z3 import * from graph_partitioning.Gralog import * def graph2z3(g): s = Solver() global R R = {} global G G = {} global B B = {} for v in g.getVertices(): v = v.getId() R[v] = Bool('R_%i' % v) G[v] = Bool('G_%i' % v) B[v]...
""" Rules for defining the branching logic in :class:`Choice` states. `See Step Functions docs for more details. <https://docs.aws.amazon.com/step-functions/latest/dg/amazon-states-language-choice-state.html#amazon-states-language-choice-state-rules>`_ """ from datetime import datetime from decimal import Decimal fro...
import re from time import strftime import RPi.GPIO as GPIO import Adafruit_DHT import time_converter from dht import DHT from lcd import HD44780 import urllib import json # Length LEN_CLOCK = 5 LEN_TEMP = 6 LEN_HUMIDITY = 5 LEN_SEPARATOR = 1 LEN_TIME = 3 LEN_DESTINATION_NUMBER = 3 LEN_DESTINATION = 8 LEN_SPACE = 1...
import fastapi import ulid import socket from fastapi import Request from pkg_resources import require def get_ulid() -> str: return ulid.new().str def get_request_info(request: Request) -> str: return request.client.host def get_host_by_ip_address(ip_address: str) -> str: return socke...
# BEGIN_COPYRIGHT # # Copyright (C) 2015-2017 Open Microscopy Environment: # - University of Dundee # - CRS4 # # 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/lice...
from dictionarydb.language import get_language def test_get_language(): assert get_language("deu") is not None def test_get_invalid_language(): assert get_language("invalid") is None
#!/usr/bin/env python """ Utilities for running code: logging, timing/benchmarking. Author: Johann Petrak """ import sys import logging import datetime import time logger = None start = 0 def set_logger(args=None, name=None, file=None): """ Set up logger for the module "name". If file is given, log to that f...
import json import numpy as np import time from keras.models import Sequential, Model, model_from_json from keras.layers import Input, Masking, Dense, Activation, Dropout,CuDNNLSTM, LSTM, Conv1D, Flatten, GlobalAveragePooling1D, BatchNormalization, MaxPool1D, AveragePooling1D, PReLU from keras.optimizers import Adam, S...
import logging from datetime import datetime import json import core from core import sqldb from core.helpers import Url from fuzzywuzzy import fuzz logging = logging.getLogger(__name__) class ScoreResults(): def __init__(self): self.sql = sqldb.SQL() return # returns list of dictionary re...
import math import torch def compute_reward(monitor_interval): """ Get an Estimate of the throughput of the network using on the last few packets (the lag) """ loss = len(monitor_interval.ack)/len(monitor_interval.sent) latency = sum(monitor_interval.rtts)/len(monitor_interval.rtts) ######...
from abc import ABC, abstractmethod from collections import defaultdict, deque from curses import qiflush import json import pickle from queue import Queue import random import time from typing import Tuple from astar_py.constants import WallPlacement from astar_py.node import Node class Maze: def __init__(self,...
""" http://cs-people.bu.edu/sbargal/Fall%202016/lecture_notes/Nov_3_3d_geometry_representation https://en.wikipedia.org/wiki/Quadratic_form https://en.wikipedia.org/wiki/Conic_section https://en.wikipedia.org/wiki/Matrix_representation_of_conic_sections """ import numpy as np from sympy import * def print_implicit(...
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. import os import argparse import shutil import sys from subprocess import call def run_cmd(command): try: call(command, shell=True) except KeyboardInterrupt: print("Process interrupted") sys.exit(1) if __name__ =...
# -*- coding: utf-8 -*- from django.contrib.auth.mixins import LoginRequiredMixin from django.views.generic.base import ContextMixin from django.views.generic import ListView, CreateView, DetailView, UpdateView, DeleteView from dictionaries.models import Category from django.core.urlresolvers import reverse_lazy from d...
"""Simple AES interface via command line.""" from ._version import get_versions __version__ = get_versions()["version"] del get_versions
def dig(num): return int(str(num)) a, b = map(int, input().split()) mult = 1 if b - a > 4: print(0) else: for i in range(b-a): mult *= dig(b-i) print(str(mult)[-1])
#!/usr/bin/env python # # Copyright (c) 2015, Arista Networks, Inc. # 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, # ...
#!/usr/bin/env python3 # Copyright 2019 Johannes von Oswald # # 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...
import io import os import tempfile import pytest from dagger import DeserializationError, Serializer from dagger_contrib.serializer.path.as_tar import AsTar SUPPORTED_COMPRESSION_MODES = [ None, "gzip", "xz", "bz2", ] def test__conforms_to_protocol(): with tempfile.TemporaryDirectory() as tmp:...
import pytest import os, sys import pickle from tensorflow.keras import losses sys.path.insert(0, os.path.abspath('..')) sys.path.insert(1, os.getcwd()) os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' import tensorflow as tf from tensorflow.keras.losses import Huber from deepts.models import TCN from deepts.metrics import ...
import pymysql import models import random import queue from util import СircleCollection, RandomData from faker import Faker from db_logic import MySQLConnector class Generator: """Генерация данных""" CURRENT_CLIENT_ID = 1 CURRENT_ORDER_ID = 1 CURRENT_PRODUCT_ID = 1 CURRENT_BOOKING_ID = 1 C...
#!/usr/bin/env python """The setup script.""" from setuptools import find_packages, setup with open('README.md') as readme_file: readme = readme_file.read() with open('HISTORY.rst') as history_file: history = history_file.read() with open('requirements.txt') as requirements_file: requirements = require...