content
stringlengths
5
1.05M
############ Forms ############ from flask_wtf import FlaskForm from wtforms import StringField, PasswordField, SubmitField, TextAreaField from wtforms.validators import DataRequired, Email, EqualTo, Length, Optional ############ Signup ############ class SignupForm(FlaskForm): username = StringField( 'Use...
import sys import unittest def debug(arg): #pass print(arg) def calculate(lines): layer_length = 25 * 6 index = 0 minimum = 25*6 + 1 result = 0 while index < len(lines): layer = lines[:layer_length] debug(len(layer)) debug(layer.count('0')) debug(layer.count...
"""Check for a news entry.""" import functools import pathlib import re import gidgethub.routing from . import util router = gidgethub.routing.Router() create_status = functools.partial(util.create_status, 'bedevere/news') BLURB_IT_URL = 'https://blurb-it.herokuapp.com' BLURB_PYPI_URL = 'https://pypi.org/project...
# -*- coding: utf-8 -*- """Exports a json file with each json object containing the key/value pair of each object from selection.""" import rhinoscriptsyntax as rs import trkRhinoPy as trp import json import ast # objs = rs.GetObjects('select objects', rs.filter.polysurface, preselect=True) objs = rs.GetObjects('sele...
# Copyright (c) 2019, Build-A-Cell. All rights reserved. # See LICENSE file in the project root directory for details. from .component import Component from .components_basic import DNA, RNA, Protein from .chemical_reaction_network import ComplexSpecies, Species from .mechanisms_binding import One_Step_Cooperative_B...
import discord import time import birb_token as token from discord import embeds from discord.ext import commands from discord.flags import alias_flag_value from cogs import bsc_cmd client = commands.Bot(command_prefix='\'') c = '```' #erase default !help command client.remove_command('help') #load bsc_c...
from utils.solution_base import SolutionBase class Solution(SolutionBase): keys = ["byr", "iyr", "eyr", "hgt", "hcl", "ecl", "pid", "cid"] def solve(self, part_num: int): self.test_runner(part_num) func = getattr(self, f"part{part_num}") result = func(self.data) return result...
# -*- coding: utf-8 -*- """Docstring.""" import datetime import logging import math import os import tempfile from typing import Any from typing import Dict from typing import Iterator from typing import Optional from typing import Tuple from typing import Union import uuid from uuid import UUID import zipfile from ma...
# -*- coding: utf-8 -*- """ Created on Thu Mar 5 10:31:35 2015 @author: gferry """ import pandas as pd import numpy as np from sklearn.kernel_approximation import RBFSampler from sklearn.preprocessing import scale # entrée => dataFrame + liste champs à vectoriser + seuil # sortie => DataFrame vectorisé # !!! NaN ...
# Generated by Django 2.2.12 on 2020-06-03 12:52 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ("users", "0009_auto_20200505_0942"), ] operations = [ migrations.AlterField( model_name="useror...
import unittest import zserio from testutils import getZserioApi class UInt64EnumTest(unittest.TestCase): @classmethod def setUpClass(cls): cls.api = getZserioApi(__file__, "enumeration_types.zs").uint64_enum def testValues(self): self.assertEqual(NONE_COLOR_VALUE, self.api.DarkColor.NON...
#!/usr/bin/env python import sys import imaplib import email import datetime from barbara import app USER_EMAIL = app.config['USER_EMAIL_FOR_PROMOTIONS'] USER_PASSWORD = app.config['USER_EMAIL_PASSWORD'] EMAIL_LABEL = 'INBOX' SEARCH_TYPE_ALL = 'ALL' SORT_RECENT_FIRST = 'REVERSE DATE' # Descending, most recent email...
# UIM muxes are fuzzed in three stages. This third stage is a depth fuzzer: it discovers all # remaining UIM mux choices by recursively searching the routing state space with a highly # randomized algorithm based on Knuth's "Algorithm X". (This is the only nondeterministic fuzzer # in the project.) import random impor...
# -*- coding: utf-8 -*- from datetime import datetime, date, timedelta from odoo import models, fields, api, _ from odoo.exceptions import Warning class DocumentType(models.Model): _name = 'document.type' name = fields.Char(string="Name", required=True, help="Name")
import pytest from qforce_examples import Gaussian_default from qforce.main import run_qforce @pytest.mark.parametrize("batch_run,exist", [(True, False), (False, True)]) def test_BatchRun(batch_run, exist, tmpdir): setting = tmpdir.join('settings') setting.write('''[scan] batch_run = {} frag_lib = {}/qforce_...
import json import os import pickle import random import shutil import sys from pathlib import Path import pytesseract import yaml from tqdm import tqdm import cv2 from glob import glob from PIL import Image import torch import numpy as np from decord import VideoReader, cpu from brisque import BRISQUE import tracebac...
#!/usr/bin/env python3 # encoding=utf-8 from setuptools import setup, find_packages if __name__ == '__main__': setup( #package_dir={'animalia': 'animalia'}, # this works if species.txt is at ./animalia/species.txt #package_data={'animalia': ['species.txt']}, # blah #packages=['find:', 'animali...
from django.shortcuts import get_object_or_404 from rest_framework import serializers from rest_framework.exceptions import APIException from rest_framework.status import HTTP_400_BAD_REQUEST from accounts.serializers import UserBasicPublicSerializer from categories.models import SubCategory from posts.models import...
# Curso Python 12 # ---Desafio 42--- # Refaça o Desafio 035 dos triângulos, acrescentando o recurso # de mostrar que tipo de triângulo será formado from math import fabs seg1 = float(input('Digite o comprimento do Segmento AB: ')) seg2 = float(input('Digite o comprimento do Segmento BC: ')) seg3 = float(input('Digit...
import os import sys import re import tempfile import json import args_and_configs import scoring_metrics import text_extraction from pytest import approx from pandas.testing import assert_frame_equal ############################################# ## Test helper functions ############################################...
# 20140105 # Jan Mojzis # Public domain. import sys import nacl.raw as nacl from util import fromhex, flip_bit def exc(): """ """ a, b, c = sys.exc_info() return b def onetimeauth_bad_test(): """ """ k = nacl.randombytes(nacl.crypto_onetimeauth_KEYBYTES) ...
import numpy as np def print_matrix(data): print('[') for d2 in range(np.shape(data)[0]): print(" ",list(data[d2])) print(']') def print_array(data): print(" ".join(list(["%d" % i for i in data]))) x = np.array([[1,2,3],[4,5,6]]) print_matrix(x) """ x[0,:] """ print_array(x[0,:]) """ x[1,1:] """ y ...
import os,sys,random import veri NewName = os.path.expanduser('~') sys.path.append('%s/vlsistuff/verification_libs3'%NewName) import logs Monitors=[] cycles=0 GIVEUP_TIMEOUT = 10000 # how many cycles to run before retirment. import encrypt_piped_efficiency enc = encrypt_piped_efficiency.encrypt_piped_efficiency...
""" project.instance Create and expose the Flask application """ from flask import Flask, render_template def create_app(): application = Flask('app') from app.project import config application.config.from_object(config) from app.project.database import db_init application.db = db_init() fr...
import click from .base import ( devel_debug_option, devel_option, instance_option, map_to_click_exceptions, ) from ..consts import collection_drafts @click.command() # @dandiset_path_option( # help="Top directory (local) of the dandiset. Files will be uploaded with " # "paths relative to th...
from distutils.core import setup # setup setup(title="pyblast", name="pyblast", version="1.0.0a", packages=["pyblast"])
sample_who_response = [{ "url": "https://www.who.int/csr/don/2005_08_31/en/", "date_of_publication": "2005-08-31 xx:xx:xx", "headline": "Yellow fever in Guinea", "main_text": "WHO has received reports of 7 cases and 4 deaths from yellow fever in the region of Fouta Djalon. Four cases including 3 deaths ...
# BS mark.1-55 # /* coding: utf-8 */ # BlackSmith plugin # © WitcherGeralt ([email protected]) def command_calendar(mType, source, body): import calendar date = time.gmtime() y, z = 0, 0 if body: body = body.split() x = body.pop(0) if check_nubmer(x): z = int(x) if body and check_number(body[0...
from __future__ import print_function import os import os.path from PIL import Image import torch.utils.data as data import torchvision.transforms as transforms from torch.utils.data.dataloader import DataLoader from data.utils import TransformTwice, RandomTranslateWithReflect def find_classes_from_folder(dir): ...
# Copyright 2021 Alibaba Group Holding Limited. 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 ...
""" testable.py - NOTE: this module should not be run as a standalone scripts, excepts for built-in tests. """ # HISTORY #################################################################### # # 1 Mar11 MR Initial version # 2 Dec14 MR Ported to Py3 # ...
""" Copyright 2015 Ronald J. Nowling 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, softw...
# SISO program longerThan1K.py # Returns 'yes' if the input is longer than 1000 characters and 'no' # otherwise. import utils from utils import rf def longerThan1K(inString): if len(inString) > 1000: return "yes" else: return "no" def testlongerThan1K(): testVals = [ (1001 * "...
# Generated by Django 2.0.13 on 2021-04-28 11:08 import ddcz.models.magic from django.db import migrations class Migration(migrations.Migration): dependencies = [ ("ddcz", "0070_mentat_plural"), ] operations = [ # This may create user issues, but it's only 7 records migrations.R...
import enum class ContentType(enum.Enum): answer = 'answer' pinboard = 'pinboard' all = 'all' class UserActions(enum.Enum): view_answer = 'ANSWER_VIEW' edit_answer = 'ANSWER_SAVED' view_pinboard = 'PINBOARD_VIEW' view_old_embed_pinboard = 'PINBOARD_EMBED_VIEW' view_embed_pinboard = '...
from pymongo import MongoClient from bitcoin_price_prediction.bayesian_regression import * import warnings import pickle client = MongoClient() database = client['stock'] collection = database['x_daily'] collection = database['svxy_intra'] warnings.filterwarnings(action="ignore", module="scipy", message="^internal g...
import base64 import json from misty_client.perception.visual import Picture ### Take a standard rbg picture pic = Picture("10.10.0.7") filename = "test.png" resp = pic.take(filename, 600, 400) img_str = json.loads(resp.content)["result"].get("base64") img_data = base64.b64decode(img_str) with open(filename, 'wb')...
# Copyright 2017 The Bazel 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 applicable la...
from __future__ import division import numpy as np import argparse import random import nltk nltk.download('stopwords') from nltk.corpus import stopwords from nltk import word_tokenize from nltk.util import ngrams from nltk.collocations import * import timeit import sys import pickle import gzip class Classifier(obj...
word = ["python", "java", "kotlin", "javascript"].pop() display = ["-"] * len(word) guesses = set() lives = 8 print("H A N G M A N") while True: instruction = input('Type "play" to play the game, "exit" to quit: ') if instruction == "play": while lives > 0: print() print("".joi...
import collections import time import sklearn.feature_extraction import sklearn.preprocessing import numpy as np from scipy import sparse import tensorflow as tf def init_nunif(sz, bnd=None): if bnd is None: if len(sz) >= 2: bnd = np.sqrt(6) / np.sqrt(sz[0] + sz[1]) else: ...
def opt(): import option r = "\033[31m" g = "\033[32m" y = "\033[33m" print(f"{g}[{r}0{g}]{y}list tools properties") print(f"{g}[{r}1{g}]{y}screen") print(f"{g}[{r}2{g}]{y}battery") print(f"{g}[{r}3{g}]{y}activity") print(f"{g}[{r}4{g}]{y}system info") print(f"{g}[{r}5{g}]{y}type") print(f"{g}[{r}6{g}]{y}net...
from django.utils.translation import gettext as _ def test_location_list(francoralite_context): for username in francoralite_context.USERNAMES: # Open the locations list page for each profile francoralite_context.open_homepage(auth_username=username) francoralite_context.open_url('/locatio...
#### import the simple module from the paraview from paraview.simple import * # Create a wavelet and clip it with a Cylinder. wavelet = Wavelet() Show() clip = Clip() clip.ClipType = "Cylinder" clip.InsideOut = True cylinder = clip.ClipType cylinder.Axis = [-1, 1, -1] cylinder.Center = [8, 4, -3] cylinder.Radius = 3...
import threading import time import traceback import ccxt import json import datetime import logging import os import click import uuid import queue import collections import etcd3 import simpleProducer import configurationService STOP_REQUEST = "StopRequest" MAX_REQUEST_LAG = 100 class CcxtRequestProcessor(object):...
class CommandLine() : def __init__(self, inOpts=None) : import argparse self.parser = argparse.ArgumentParser(description = 'Extended Depth of Focus Image Processing Algorithm', epilog = 'Takes, in multiple layers of image data of a given s...
#!/usr/bin/env python3 # Utility to check for Pulse Connect Secure CVE-2021-22908 # https://www.kb.cert.org/vuls/id/667933 import requests from requests.packages.urllib3.exceptions import InsecureRequestWarning import argparse import sys from html.parser import HTMLParser import getpass parser = argparse.ArgumentPars...
# -*- coding: utf-8 -*- # 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, softwar...
from django.contrib.auth.decorators import login_required from django.shortcuts import render # Create your views here. def home(request): template_name = 'home.html' return render(request, template_name) def contato(request): template_name = 'contato.html' return render(request, template_name) ...
from unittest.runner import TextTestResult from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver from rest_framework.authtoken.models import Token # Create your models here. class Neighborhood(models.Model): name...
from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.naive_bayes import MultinomialNB from sklearn.pipeline import Pipeline from sklearn.datasets import fetch_20newsgroups from sklearn import metrics import joblib from api import CAT if __name__ == "__main__": # Just grab the training set: ...
# -*- coding: utf-8 -*- import pytest from tennis import TennisGame3 from tennis_unittest import test_cases, play_game class TestTennis: @pytest.mark.parametrize('p1Points p2Points score p1Name p2Name'.split(), test_cases) def test_get_score_game3(self, p1Points, p2Points, score, p1Name, p2Name): gam...
from typing import List from injector import inject from pandas import DataFrame from pdip.integrator.connection.base import ConnectionTargetAdapter from pdip.integrator.connection.types.sql.base import SqlProvider from pdip.integrator.integration.domain.base import IntegrationBase class SqlTargetAdapter(Connection...
#!/usr/bin/env python3.5 import numpy as np import cv2 from .data import SCALES class cv2Window( ): def __init__( self, name, type = cv2.WINDOW_AUTOSIZE ): self.name = name self.title = name self.type = type def __enter__( self ): cv2.namedWindow( self.name, self.type ) ...
""" =================================================== A class for VCF format =================================================== """ import re class VCFHeader: def __init__(self, hInfo = None): self.header = {} if hInfo and (type(hInfo) is not dict): raise ValueError ('The data type should b...
""" This module provides the molior BuildOrder relation table. """ from sqlalchemy import Column, Integer, ForeignKey, Table, UniqueConstraint from .database import Base BuildOrder = Table( # pylint: disable=invalid-name "buildorder", Base.metadata, Column("build_id", Integer, ForeignKey("build.id")), ...
"""Tests for hello function.""" import pytest def test_pythoncms(): assert 1 == 1
from bs4 import BeautifulSoup from .extracter import HTMLExtracter import streamlit as st from transformers import pipeline from selenium import webdriver from selenium.webdriver.chrome.service import Service class Scraper: def __init__(self): self.base_url = 'https://google.com/search' async def __e...
#!/usr/bin/env python # CNEscualos (c) Baltasar 2016-19 MIT License <[email protected]> import time import logging import webapp2 from model.member import Member from model.competition import Competition class DeleteTestCompetitionHandler(webapp2.RequestHandler): def get(self): # Check if the user i...
# Generated by the protocol buffer compiler. DO NOT EDIT! # sources: hello.proto # plugin: python-betterproto from dataclasses import dataclass import betterproto @dataclass class Greeting(betterproto.Message): """Greeting represents a message you can tell a user.""" message: str = betterproto.string_field...
import typing import datetime import tensorflow as tf from model_logging import get_logger from training_loop import k_to_true_ghi class MainModel(tf.keras.Model): TRAINING_REQUIRED = True def __init__( self, stations: typing.Dict[typing.AnyStr, typing.Tuple[float, float, float]], ta...
"""Init of the risk matrix package."""
import os def local(): with open('emails.txt','r') as local_database: return local_database.readlines() def file(): if os.path.exists('emails.txt'): return local() else: open("myfile.txt", "x") return local()
# coding=utf-8 # Copyright 2022 HyperBO Authors. # # 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 ag...
from django.urls import path from django.contrib.auth import views as auth_views from . import views urlpatterns = [ path('', views.profile, name='profile'), path('login', views.login_view, name='login'), path('logout', views.logout_view, name='logout'), path('register', views.register, name='register...
from typing import Dict, Any from enum import Enum from indico.errors import IndicoRequestError import time class HTTPMethod(Enum): GET = "GET" POST = "POST" PUT = "PUT" DELETE = "DELETE" HEAD = "HEAD" OPTIONS = "OPTIONS" class HTTPRequest: def __init__(self, method: HTTPMethod, path: st...
#!/usr/bin/env python from datadog import initialize, api def initialize_dd_api(account): options = { 'api_key': configs[account]["api_key"], 'app_key': configs[account]["app_key"] } initialize(**options) class Monitor: def __init__(self,type,query,name,message,tags,options): ...
# Copyright 2018 The Cornac 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 applicable ...
from setuptools import setup, find_packages from os import path this_dir = path.abspath(path.dirname(__file__)) with open(path.join(this_dir, "README.md"), encoding="utf-8") as f: long_description = f.read() setup( name="gretel-client", author='Gretel Labs, Inc.', author_email='[email protected]...
import json excludeSets = ['Homelands'] with open('Old Rarities.json', 'r') as f: # Cards include name and rarity fields setNameToCards = json.loads(f.read()) for setName in setNameToCards: if (setName in excludeSets): continue rarities = setNameToCards[setName] with open(setName, 'r')...
import os from loggers import AMC_HOLDING_DIR_PATH, linespace, prgm_end, finish, NO_FILES_IN_DIR_MSG dir_path = f"./{AMC_HOLDING_DIR_PATH}" fund_files = os.listdir(dir_path) # incase of empty folder if len(fund_files) == 0: print(NO_FILES_IN_DIR_MSG) exit(0) print(f"Comparing {len(fund_files)} AMCs") ...
from typing import List from collections import defaultdict import logging from django.conf import settings from online_payments.billing.enums import Currency from online_payments.billing.models import Item, PaymentMethod, Invoice, Customer from online_payments.billing.szamlazzhu import Szamlazzhu from payments.prices ...
# GENERATED BY KOMAND SDK - DO NOT EDIT from .create_query.action import CreateQuery from .get_query.action import GetQuery from .run_query.action import RunQuery
# This file is part of Pynguin. # # Pynguin is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Pynguin is distributed in the ho...
######################################################################## ## ## Copyright 2015 PMC-Sierra, Inc. ## Copyright 2018 Eidetic Communications 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 ...
def pattern(n): return "\n".join(" "*(n-1-i)+"".join([str(i%10) for i in range(1,n+1)])+" "*i for i in range(n))
"""FunCLI Package installer.""" from setuptools import find_packages, setup setup(name='CLIFun', version='0.0', packages=find_packages(), include_package_data=True, install_requires=['Click', 'Fabric', 'laboratory', ], entry_points={ ...
from pytest import fixture, raises from grblas import op, monoid, Scalar, Vector, Matrix from grblas.exceptions import DimensionMismatch @fixture def v1(): return Vector.from_values([0, 2], [2.0, 5.0], name="v_1") @fixture def v2(): return Vector.from_values([1, 2], [3.0, 7.0], name="v_2") @fixture def A1...
# クラスCoeffVarを定義 class CoeffVar(object): coefficient = 1 @classmethod # メソッドmulをクラスメソッド化 def mul(cls, fact): # 第1引数はcls return cls.coefficient * fact # クラスCoeffvarを継承するクラスMulFiveを定義 class MulFive(CoeffVar): coefficient = 5 x = MulFive.mul(4) # CoeffVar.mul(MulFive, 4) -> 20
import sys sys.path.append("../Structures/") import graph from dfs import Dfs from collections import deque class Scc: def execute(self, G): dfs = Dfs() dfs.executeNormal(G) G.buildTranspGraph() dfs.executeTransp(G) self.printScc(G, dfs.getSccList()) def printScc(self,...
import re from collections import namedtuple from .exceptions import ParseError, ExpressionNotClosed from .exceptions import NotClosedError, StatementNotFound from .exceptions import StatementNotAllowed, UnexpectedClosingFound from .registry import Registry class Node: def __init__(self, parent=None): s...
import bpy from bpy.props import * from .PesFacemod.PesFacemod import * import bpy.utils.previews bl_info = { "name": "PES2020 Facemod", "version": (1, 80, 0), "blender": (2, 80, 0), "location": "Under Scene Tab", "description": "Unpacks and packs face.fpk files for modification", "warning": "S...
import time class EditCommand: "undo/redo-able representation of an art edit (eg paint, erase) operation" def __init__(self, art): self.art = art self.start_time = art.app.get_elapsed_time() self.finish_time = None # nested dictionary with frame(layer(column(row))) str...
# Some python class related homework import math class Point: """Two values""" def __init__(self, *args): if len(args) == 2: if all(a for a in args if type(a) == float): self.x = args[0] self.y = args[1] elif len(args) == 1: if type(ar...
""" Unittests for fxos/ftd plugin Uses the unicon.mock.mock_device script to test the plugin. """ __author__ = "dwapstra" import unittest from unicon import Connection from unicon.eal.dialogs import Dialog from unicon.plugins.generic.statements import GenericStatements generic_statements = GenericStatements() pa...
from factory import Sequence, SubFactory from factory.django import DjangoModelFactory from documentation.models import Map, Block, IDE, Category class MapFactory(DjangoModelFactory): class Meta: model = Map title = Sequence(lambda n: "Concept %03d" % n) slug = Sequence(lambda n: "/concepts/%03d"...
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import unicode_literals, generators, division, absolute_import, with_statement, print_function from .__init__ import APIBase, log from urllib import urlencode class Scheduler(APIBase): """Scheduling operations Extends: APIBase """ ...
import requests #get list of connections def get_connections(URL,PARAMS): try: r = requests.get(url=URL,params=PARAMS) get_result = r.json()["results"] connection_dict = {} for connection in get_result: their_did = connection["their_did"] connection_id = conn...
from datasets.Loader import register_dataset from datasets.Mapillary.MapillaryLike_instance import MapillaryLikeInstanceDataset from datasets.util.Util import username DEFAULT_PATH = "C:/Users/Tunar Mahmudov/Desktop/TrackR-CNN/data/KITTI_MOTS" NAME = "KITTI_instance" @register_dataset(NAME) class KittiInstanceDatase...
import numpy as np import pandas as pd import matplotlib.pyplot as plt fname = 'model_train.log' print('Reading:', fname) df = pd.read_csv(fname) epoch = df['epoch'].values + 1 loss = df['loss'].values val_loss = df['val_loss'].values print('epochs: %8d ... %d' % (np.min(epoch), np.max(epoch))) print('loss: %...
import sys,math N=int(input()) A=input().split() for i in range(N): A[i]=int(A[i]) if not(0<=A[i]<=10**9): print("invalid input") sys.exit() M=int(input()) if not((1<=N<=10**6)and(N<=M<=10**9)): print("invalid input") sys.exit() K=math.ceil(sum(A)/M) print(K)
#TA 2 BASE import pdb import numpy as np import gym from gym import make import cProfile import re import uuid import os import random import time from utils import rollout import time import pickle #import cv2 import PIL import torch import json import argparse from collections import OrderedDict from functools impo...
# Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. # See https://llvm.org/LICENSE.txt for license information. # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception import re from typing import Iterable, Optional import numpy as np from mlir import ir as _ir from mlir.dialects impo...
# Software License Agreement (Apache 2.0 License) # # Copyright (c) 2021, The Ohio State University # Center for Design and Manufacturing Excellence (CDME) # The Artificially Intelligent Manufacturing Systems Lab (AIMS) # All rights reserved. # # Author: Adam Exley import os import numpy as np import pyrender import ...
import json from config.helper_model import ModuleHelper, db from datetime import datetime from werkzeug.security import generate_password_hash, check_password_hash from sqlalchemy.orm import validates class UserModel(ModuleHelper): """ When create new user, after make instance, before save, do instance....
import MySQLdb import sys from secret import config # Database configuration saved in secret.py # The secret.py file should contain something like this # config = { # 'host': 'localhost', # 'user': 'root', # 'passwd': 'SECRET', # } def assays_db(): """ Connect to MySQL, and attempt to create or sel...
'''production script for planetary nebula this script is a streamlined version of the code in planetary_nebula.ipynb. The notebook was used for testing and peaking into some results, while this script is used to produce the final plots/tables. ''' import sys from pathlib import Path import logging import json impor...
from collections.abc import Mapping from itertools import chain, repeat, zip_longest from operator import itemgetter from typing import ( TYPE_CHECKING, Any, Dict, ItemsView, Iterable, Iterator, List, MutableSequence, Sequence, Tuple, Union, overload, ) from funcy import...
from django.contrib.auth.models import User from mixer.backend.django import mixer import base64 from socialDistribution.models import LocalAuthor TEST_PASSWORD = "123456" def create_author(): user = mixer.blend(User) user.set_password(TEST_PASSWORD) user.save() author = LocalAuthor.objects.create(us...
import glob import os dir_names = glob.glob("prefetch_*") names = [] miss_rates = [] for dir_name in dir_names: os.chdir(dir_name) myCmd = os.popen('grep "l2.overall_miss_rate::total" stats.txt').readlines() print(myCmd) line = myCmd[1].strip() temp = dir_name.split("_") name = "".join([temp[...