text
stringlengths
38
1.54M
import math import matplotlib.pyplot as plt import numpy as np import tensorflow as tf from PIL import Image # from tf_cnnvis import * def weight(shape): return tf.Variable(tf.truncated_normal(shape, stddev=0.1)) def bias(length): return tf.Variable(tf.constant(0.1, shape=[length])) def layer(input, num_i...
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved """misc helper functions """ import hashlib from collections import Counter, OrderedDict import numpy as np import torch def make_weights_for_balanced_classes(dataset): counts = Counter() classes = [] for _, y in dataset: y ...
print("welcome to shenzhen!") print("welcome to shenzhen!") print("welcome to shenzhen!") print("welcome to shenzhen!") print("welcome to shenzhen!") print("welcome to shenzhen!") print("welcome to shenzhen!") print("welcome to shenzhen!") print("welcome to shenzhen!") print("welcome to shenzhen!") print("welcome to sh...
#!/usr/bin/env python2 # -*- coding: utf-8 -*- from pwn import * exe = context.binary = ELF('sum') host = args.HOST or '35.207.132.47' port = int(args.PORT or 22226) env = {'LD_PRELOAD':'./libc-2.27.so'} def local(argv=[], *a, **kw): '''Execute the target binary locally''' if args.GDB: return gdb.deb...
# !usr/bin/env python # -*- coding: utf-8 -*- import pandas as pd from datetime import datetime import os def old2new(df): df[1] = df[1].apply(num2date) df = df.sort_values([1, 0]) df.columns = ['place', 'date', 'people'] return df def num2date(num, year='2017'): num = str(num) ...
import gdsfactory as gf def test_transition_ports() -> None: width1 = 0.5 width2 = 1.0 x1 = gf.cross_section.strip(width=width1) x2 = gf.cross_section.strip(width=width2) xt = gf.path.transition(cross_section1=x1, cross_section2=x2, width_type="linear") path = gf.path.straight(length=5) c ...
from math import sin, cos, tan, radians angi = int(input('Informe o ângulo: ')) ang = radians(angi) s = sin(ang) c = cos(ang) t = tan(ang) print(t)
''' Copyright (C) 2018-2023 Bryant Moscon - bmoscon@gmail.com Please see the LICENSE file for the terms and conditions associated with this software. ''' from cryptofeed import FeedHandler from cryptofeed.backends.influxdb import BookInflux, CandlesInflux, FundingInflux, TickerInflux, TradeInflux from cryptofeed.defin...
from pydub import AudioSegment import random origAudio = AudioSegment.from_wav("Full2.wav") for i in range(180): t1 = i * 1000 #Works in milliseconds t2 = (i+1+random.random()) * 1000 newAudio = origAudio[t1:t2] newAudio.export('gen_samples/'+str(i)+'.wav', format="wav")
# ---LICENSE-BEGIN - DO NOT CHANGE OR MOVE THIS HEADER # This file is part of the Neurorobotics Platform software # Copyright (C) 2014,2015,2016,2017 Human Brain Project # # 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...
from jinja2 import Environment, FileSystemLoader # from weasyprint import HTML # import pdfkit table_placeholder = """<div class="row" > <table class="u-full-width"> <thead class="fqred"> <tr> <th>Name</th> ...
from __future__ import absolute_import from django.db import models from .utils import ugettext_lazy_compact as _ # from localflavor.in_ import models as india_models class ClientIndustry(models.Model): name =models.CharField( max_length=50, blank=False, unique=True, null=False) ...
#coding=utf-8 ''' FileName :decomPCA.py Author :@zch0423 Date :Jun 11, 2021 Description : PCA 查看bert embedding主成分 ''' #%% import numpy as np from sklearn.decomposition import PCA import matplotlib.pyplot as plt #%% def loadData(data_type="trn", w2v_type="avg"): ''' @De...
# Header magic = "P3" author = "# Created by Shawn Wilkinson" size_x, size_y = (320, 240) inten = 255 # Open/Create File and Add Header f = open('1.4pe1.ppm', 'w+') f.write(magic + "\n") f.write(author + "\n") f.write(str(size_x) + " " + str(size_y) + "\n") f.write(str(inten) + "\n") # Write Image colo...
#!/usr/bin/env python3 import riotgear.cli import riotgear.plugin if __name__ == "__main__": parser = riotgear.cli.clidriver() reg = riotgear.plugin.Registry(default_dirs=['plugins']) reg.load_all() args = parser.parse_partial() extra = parser.parse() print(extra) parser.launch()
# Flask Framework from flask import Flask, jsonify, request, make_response, Response # Routes from src.routes.api import api # Authentication from src.models.auth import Auth # Dummy Credentials users = { 'email': 'ruel@mindo.com', 'auth': { 'key': 'secretkey', 'password': 'test', 'token': 'F6Xik2zCXdAEBdI...
#!/usr/bin/env python """ http://wiki.dominionstrategy.com/index.php/Hill_Fort""" import unittest from dominion import Game, Card, Piles ############################################################################### class Card_Hill_Fort(Card.Card): def __init__(self): Card.Card.__init__(self) se...
from AlgoExpert import allkindsofnodedepths as program import unittest class TestProgram(unittest.TestCase): def test_case_1(self): root = program.BinaryTree(1) root.left = program.BinaryTree(2) root.left.left = program.BinaryTree(4) root.left.left.left = program.BinaryTree(8) ...
# Generated by Django 3.0.5 on 2020-04-16 09:04 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('stores', '0012_auto_20200416_1414'), ] operations = [ migrations.AddField( model_name='product', name='quantity', ...
import numpy as np from scipy.integrate import ode import matplotlib.pyplot as plt def f(t, p, m): return [ p[6], p[7], p[8], p[9], p[10], p[11], -fac3(p[0], p[1], p[2], p[3], p[4], p[5], m[1], m[2]), -fac3(p[1], p[0], p[3], p[2], p[5], p[4], m[1], m[...
from .. import yshoog from datetime import datetime from flask import render_template, session, redirect, url_for,request, jsonify from ....models import ToolCategory,Tool from ....utils import utils from app import db # 查询所有工具分类 @yshoog.route('/toolcategory/all',methods = ['GET','POST']) def getAll(): try: ...
# Generated by Django 3.1.2 on 2020-11-12 03:35 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('article', '0004_paragraphimage_leading'), ] operations = [ migrations.AddField( model_name='articleparagraph', name=...
# Start adventure at the forest - can go left to the mountain or right to the castle. Which way do you want to go? # variable choice # if choice is = input something # elif the other choice #print final outcome for choices import PySimpleGUI as sg """ Adventure Game - open and closing windows simultaneously. ...
#------------------------------------------------------------------------------- # Name: 265 # Purpose: # # Author: wrongrook # def e265_recurse(S,last,N): if len(S)==N: return last last*=2 t=last&(N-1) s=0 if t not in S: S.add(t) s+=e265_recurse(S,last,N) ...
import os import aiohttp from quart import Quart, abort, jsonify, request, session, redirect, url_for, render_template from quart_discord import DiscordOAuth2Session, requires_authorization, Unauthorized, AccessDenied from urllib.parse import quote from alttprbot.tournaments import TOURNAMENT_DATA, fetch_tournament_h...
# import train_helper # import time # import os import helper # import sys # import eval_helper import numpy as np import tensorflow as tf import read_cityscapes_tf_records as reader tf.app.flags.DEFINE_string('config_path', "config/cityscapes.py", """Path to experiment config.""") FLAGS = ...
# 给定一个由整数组成的非空数组所表示的非负整数,在该数的基础上加一。 # # 最高位数字存放在数组的首位, 数组中每个元素只存储单个数字。 # # 你可以假设除了整数 0 之外,这个整数不会以零开头。 # # 示例 1: # # 输入: [1,2,3] # 输出: [1,2,4] # 解释: 输入数组表示数字 123。 # # # 示例 2: # # 输入: [4,3,2,1] # 输出: [4,3,2,2] # 解释: 输入数组表示数字 4321。 # # Related Topics 数组 # leetcode submit region begin(Prohibit modif...
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.FileItem import FileItem from alipay.aop.api.constant.ParamConstants import * class ZhimaCreditEpCodecCreateRequest(object): def __init__(self, biz_model=None): self._biz_model = biz_model self._channel_id = None ...
import os import pickle import time import numpy as np import tensorflow as tf import sentencepiece as spm from model import * class ChatEngine(): def __init__(self): self.checkGPU() self.maxlen = 32 with open('./data/dict.pkl', 'rb') as f: self.index = pickle.load(f) s...
#!/usr/bin/python # -*- coding: UTF-8 -*- __author__ = 'jiaojianfeng' import types x = 20 print type(x) is types.IntType print x.__class__ print x.__class__ is type(x) is int is types.IntType y = x print hex(id(x)), hex(id(y)) #id(object) 获取内存地址 print hex(id(int)), hex(id(types.IntType))
# Generated by Django 2.2.14 on 2020-12-01 00:38 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ('Materias', '0001_initial'), ] operations = [ migrations.CreateModel( name='Alumno', fields=[ ...
##### Message Types #### C_M_Create = 1 C_M_Read = 2 C_M_Write = 3 C_CS_Write = 4 C_CS_Read = 5 CS_M_Completed = 6 CS_M_Heartbeat = 7
def foo(var): try: print(var) # 1 + print(var) except: 1 + print('Why do you print me?') + 1 else: 1 + print('Why do you print me?') + 1 finally: return print(foo("Hello")) """ >> Why do you print me? no raise of errors """
# -*- coding: utf-8 -*- """ Created on Mon Feb 9 19:20:11 2015 @author: A30123 """ ###################################### #alternative code for retrieving variable values def read_single_variable_as_float_csv(csvpathfilename, variablename): import csv import numpy as np notfirst=1 thel...
# 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 json import re import discord import os import requests from lxml import etree from random import randint from secret import utils async def on_message(message, secret_context): parts = message.content.split(" ") if len(parts) < 2: # print the help secret_context.bus.emit('secret_comma...
import numpy as np import openmc import pytest @pytest.fixture(scope='module') def pincell1(uo2, water): cyl = openmc.ZCylinder(r=0.35) fuel = openmc.Cell(fill=uo2, region=-cyl) moderator = openmc.Cell(fill=water, region=+cyl) univ = openmc.Universe(cells=[fuel, moderator]) univ.fuel = fuel u...
from unittest import mock import pytest from myst_parser.docutils_renderer import SphinxRenderer @pytest.fixture def renderer(): renderer = SphinxRenderer() with renderer: yield renderer @pytest.fixture def sphinx_renderer(): with SphinxRenderer(load_sphinx_env=True) as renderer: yield...
#!/bin/python3 # # COMPLETED # # PROBLEM: # http://hr.gs/fnu import math import os import random import re import sys # Complete the twoStrings function below. def twoStrings(s1, s2): chars = {} for char in s1: chars[char] = 1 for char in s2: if char in chars: return('YES') return('...
import numpy as np import pytest from chainconsumer import ChainConsumer def test_gelman_rubin_index(): data = np.vstack((np.random.normal(loc=0.0, size=100000), np.random.normal(loc=1.0, size=100000))).T consumer = ChainConsumer() consumer.add_chain(data, walkers=4) assert cons...
fruit = 'banana' print(len(fruit)) prefixes = 'JKLMNOPQ' suffix = 'ack' # for letter in prefixes: # print(letter + suffix) fruit = 'banana' print(fruit[3:]) # 取后3个item print(fruit[:3]) # 取前3的item print(fruit[:]) # 取全值 # 计算字母a在字符串中出现的次数: word = 'banana' count = 0 for letter in word: if letter == 'a': ...
import os import sys, argparse import random parsers = argparse.ArgumentParser() parsers.add_argument("-i", "--index", help="Please enter begin index") parsers.add_argument("-f", "--folder", help="Please enter folder path") args = parsers.parse_args() def changeFileName(oldName, newName): os.rename(oldName, newName...
# coding: utf-8 import unittest from lxml import etree as ET from updatepreprint import pipeline_xml namespaces = {'dc': 'http://purl.org/dc/elements/1.1/', 'xmlns': 'http://www.openarchives.org/OAI/2.0/', 'xsi': 'http://www.w3.org/2001/XMLSchema-instance', 'oai': 'http://ww...
__all__ = ['priors', 'logging', 'gpu_utils', 'utils', 'driver', 'fit_model', 'galaxy', 'instrument', 'isochrones', 'plotting', 'results', 'metalmodels', 'agemodels', 'dustmodels', 'distancemodels', 'sfhmodels', 'data', '__version__'] from .simulation import gpu_utils from . import inst...
''' 用画刷填充图形区域 ''' import math import random import sys import threading from PyQt5 import QtCore from PyQt5.QtWidgets import * from PyQt5.QtGui import * from PyQt5.QtCore import * from com.music_Play import MyThread class musicGraphy(QWidget): def __init__(self): super(musicGraphy, self).__init__() ...
import click from aws_organized_policies import aws_organized_policies @click.group() def cli(): """cli for pipeline tools""" pass @cli.command() def hello() -> None: print("Hello world") @cli.command() @click.argument("role_arn") def import_organization(role_arn) -> None: # TODO remove print ...
"""(°C × 9/5) + 32 = °F""" celsius = float(input('Temperatura em °C: ')) fahrenheit = celsius * 9 / 5 + 32 print('{:.2f} °C é equivalente a {:.2f} °F.'.format(celsius, fahrenheit))
""" OPERACIONES TIPO CURD CON TABLAS EN BASES DE DATOS MYSQLITE """ #LEER o READ---------------------------------> # Importar librería import sqlite3 # Conexion con base de datos miCon = sqlite3.connect('weapons_bd') # Cursor o puntero miCur = miCon.cursor() # Ejecutar consulta reed------------------------------------...
"""API Functions. This module implements two main functions called via HTTP. The module structure is the following: - Function ``predict`` is called with some arguments in order to predict if some text contains hate speach. - Function ``train`` is called to re-train the estimator with some new data which will be...
# Generated by Django 3.0.3 on 2020-10-08 20:08 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Tag', fields=[ ('id', models.AutoField(auto...
from django.shortcuts import render from django.views.generic.edit import FormView from .forms import PreferenceForm from django.contrib import messages class CustomerForm(FormView): form_class = PreferenceForm template_name = 'preferences/main.html' # redirect to same home page def get_success_url...
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Wed Feb 19 16:43:18 2020 @author: chetanrupakheti """ """ Container of value and right and left children """ class Node: def __init__(self,x): self.val = x self.right = None self.left = None """ Given a root node, prints out th...
"""My first program for Comp110.""" __author__ = "730399808" print("Hello, world this is a slight change.")
from django.db import models from django.core.exceptions import ValidationError from django.utils.translation import gettext as _ from django.utils import timezone from django.contrib.auth.models import User from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes.fields import Generi...
#!/usr/bin/env python import io import os import picamera from config import WIDTH, HEIGHT, FRAMERATE, VFLIP, HFLIP from subprocess import Popen, PIPE from threading import Thread from time import sleep from HttpServer import HttpServer from WebsocketServer import WebsocketServer class CameraOutput(object): def ...
""" Blackmoth API class library will allow for code base in other applications to be cut down by a large amount. Still not complete. """ import requests import json """ GPSStream is still under development """ class GPSStream: def __init__(self, ip): self.ip_entry_data = ip self.gps_stream_...
from django.db import models from apps.web_config import * #from apps.product.models import Product # Create your models here. # 用户登录帐号 class UserAccount(models.Model): nickname = models.CharField(verbose_name='昵称', max_length=120, unique=True, null=True) phone = models.CharField(verbose_name='电话号码', max_leng...
import numpy as np import datetime class RSWaveformGenerator(): """ Generates .wv files from I/Q for the AFQ 100B I/Q modulation generator and related Rohde & Schwarz instruments RSWaveformGenerator(instrument) Initialises waveform generator ready to upload to qcodes instrument ...
import logging log = logging.getLogger(__name__) import re import numpy import itertools import westpa from oldtools.aframe import AnalysisMixin class KineticsAnalysisMixin(AnalysisMixin): def __init__(self): super(KineticsAnalysisMixin,self).__init__() self.dt = None self.ana...
"""adds timestamp to posts Revision ID: 39c16cd10ee8 Revises: 4907810d149c Create Date: 2021-01-24 06:34:07.126310 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '39c16cd10ee8' down_revision = '4907810d149c' branch_labels = None depends_on = None def upgrade...
import cv2 import numpy as np from shapely import affinity from shapely.geometry import LineString, box def get_patch_coord(patch_box, patch_angle=0.0): patch_x, patch_y, patch_h, patch_w = patch_box x_min = patch_x - patch_w / 2.0 y_min = patch_y - patch_h / 2.0 x_max = patch_x + patch_w / 2.0 ...
#Problem ID: CACHEHIT #Problem Name: Cache Hits for _ in range(int(input())): n, b, m = map(int, input().split()) l = list(map(int, input().split())) c = 1 acc = l[0]//b for i in range(m): if l[i]//b != acc: c+=1 acc = l[i]//b print(c)
def feet_to_inches(feet): return feet * 12 print("Inches: ", format(feet_to_inches(float(input("Enter number of feet: "))), ",.2f"))
alp=["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"] def valid(parties): s=sum(parties) for i in parties: if i>s/2 or i<0: return False return True def solve(parties): if valid(parties) and sum(parties)==0: return [] fo...
# -*- coding: utf-8 -*- { 'name': 'Dogma Partner Fields', 'version': '13.0.1.4.0', 'author': 'HomebrewSoft', 'website': 'https://github.com/HomebrewSoft/dogma_partner_fields', 'category': 'Operations', 'depends': [ 'sms', ], 'data': [ 'views/res_partner.xml', ], }
def SalvarArvoreGeradoraMinimaEmArquivo(arquivoDeSaida, arvoreGeradoraMinima): with open(arquivoDeSaida, 'w') as arquivo: for aresta in arvoreGeradoraMinima: arquivo.write('fonte: {}, destino: {}, peso: {}\n'.format(aresta['source'], aresta['target'], aresta['weight'])) print("isso ai")
# -*- coding: utf-8 -*- """ Spyder Editor This is a temporary script file. """ # Simple Linear Regression : Linear dependency between Salary & Years of Exeperience # Machine is : Simple Linear Regression Model # Learning is : We trained our machine model on training set that is we train our model. # It lear...
#!/usr/bin/env python2 """ builtin_assign.py """ from __future__ import print_function from _devbuild.gen import arg_types from _devbuild.gen.option_asdl import builtin_i from _devbuild.gen.runtime_asdl import ( value, value_e, value_t, value__Bool, value__Str, value__MaybeStrArray, value__AssocArray, lval...
"""Extra admin commands to manage the DomiNode minIO server This script adds some functions to perform DomiNode related tasks in a more expedite manner than using the bare minio client `mc`. """ import json import shlex import subprocess import tempfile import typing from contextlib import contextmanager from pathli...
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. import sys import threading import time gEnableTracing = False def SetTracingEnabled(isEnabled): global gEnableTraci...
from .. import sensors from ..components.headlight import Headlight from signal import pause from time import sleep s = sensors.UltrasonicSensor() led = Headlight() while True: if s.distance < 1: print(s.distance) if s.in_range: print(s.next_turn()) break sleep(0.3) def on(): ...
import os import glob import logging from logging.handlers import RotatingFileHandler LOG_FILENAME = 'logging_rotatingfile_example.out' # Set up a specific logger with our desired output level my_logger = logging.getLogger('MyLogger') my_logger.setLevel(logging.DEBUG) formatter = logging.Formatter("[%(asctime)s] {%(...
#import module import math ''' Collection of some small practice questions Create a Cricle class and intialize it with radius. Make two methods getArea and getCircumference inside this class. ''' class circle(): def __init__(self,radius): self.radius = radius def getArea(self): return 3.14*(...
def countTriplets(arr, r): d = {} for i in arr: if i not in d: d[i] = 1 else: d[i] += 1 count = 0 if r == 1: for key in d: count += d[key] * (d[key] - 1) * (d[key] - 2) / 6 return int(count) else: for key in d...
from flask import Flask,jsonify,request app = Flask(__name__) @app.route('/person/<person_id>') def person(person_id): response = jsonify({'hello':person_id}) return response if __name__ == '__main__': app.run()
class Solution: def maxProfit(self, prices:list) -> int: dp = [0] * len(prices) for i in range(len(prices)): print('dp:', dp) if i > 0 and prices[i] > prices[i-1]: # dp[i] 加上 prices[i] 减去上一次买入的价格 dp[i] += dp[i-1] + prices[i] - prices[i...
# -*- coding: UTF-8 -*- import numpy as np import matplotlib.pyplot as plt import tensorflow as tf import seq_LSTM_filter as slf from tensorflow.python.framework import ops ops.reset_default_graph() # parameters INPUT_LENGTH = 1 # the input data length at one time if __name__ == '__main__': # generates the ...
import numpy as np import time from skimage.io import imread import matplotlib.pyplot as plt import scipy.io as sio from scipy.misc import imresize from matplotlib.patches import Circle import sys sys.path.append('/home/pieter/projects/caffe/python') import caffe def loadModel(): model_def = '/home/pieter/projects...
import numpy as np import tensorflow as tf # import random from dataloader import Gen_Data_loader, Dis_dataloader # from generator import Generator from two_layer_generator import Generator2 from rnn_discriminator import RNNDiscriminator2 from rollout import ROLLOUT import os from config import * def generate_samples...
from invoke import task @task(default=True) def package(c, n="switch-dip"): c.run("rm -rf order/*", warn=True) c.run(f"cp out/{n}-F_Cu.gbr order/{n}.GTL") c.run(f"cp out/{n}-B_Cu.gbr order/{n}.GBL") c.run(f"cp out/{n}-F_Mask.gbr order/{n}.GTS") c.run(f"cp out/{n}-B_Mask.gbr order/{n}.GBS") c.ru...
class aborted_tasks: def __init__(self, index, arrival, proc_time, period, abs_deadline, finished, observed_proc_time): self.index = index self.arrival = arrival self.proc_time = proc_time self.period = period self.abs_deadline = abs_deadline self.finished = fi...
import base64 import os import sys if os.path.join(os.path.dirname(__file__), "pybase62") not in sys.path: print('adding pybase62 to sys.path') sys.path.append(os.path.join(os.path.dirname(__file__), "pybase62")) try: from .pybase62 import base62 except: import pybase62 as base62 def _b62encode_int(s...
import sys, struct I=[ [1,0,0,0], [0,1,0,0], [0,0,1,0], [0,0,0,1] ] def transpose(matrix): return [[v[i] for v in matrix] for i in xrange(len(matrix[0]))] def multmatrix(vector,matrix): return map(sum, transpose(map(lambda x:[x[0]*p for p in x[1]], zip(vector, transpose(matrix))))) d...
# Generated by Django 2.2.10 on 2020-05-12 01:41 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('servicios', '0016_auto_20200512_0018'), ] operations = [ migrations.AlterField( model_name='prestamotienda', name='...
import torch import datasets from lib.utils import AverageMeter, traverse import sys from packages.register import REGISTER from packages.loggers.std_logger import STDLogger as logger def NN(net, npc, trainloader, testloader, K=0, sigma=0.1, recompute_memory=False, device='cpu'): # switch model to evalu...
price = 2 # 单注价格 bonus = 5 # 中奖金额 costs = [] # 总成本 for i in range(20): current_costs = sum(costs) times = 1 # 买多少注 while True: cost = times * price # 本次购买总金额 reward = times * bonus # 本次中奖总金额 costs_total = current_costs + cost # 总成本 if costs_total < reward: costs.append(cost) print(i + 1, '=...
import sys print('|'+('-'*68)+'|' + '\n| Data_Verification process has been executed successfully. Please |' + '\n| follow the instructions below! Terminating process earlier might |' + '\n| leave unnecessary files behind, and might not hide your data. |' + '\n|'+('-'*68)+'|') def tex...
import os from .utils import BASE_DIR TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, 'apps', 'canvas_gadget', 'templates'), os.path.join(BASE_DIR, 'apps', 'feedback', 'templates') ], 'APP_DIRS': T...
import os from django import forms from django.shortcuts import render from django.core.urlresolvers import reverse from django.http import HttpResponseRedirect, HttpResponse from django.contrib.auth.decorators import login_required from django.contrib.auth import authenticate, login, logout from .forms import Upload...
from flask import Flask, jsonify, request import mysql.connector #from flaskext import MySQL from flask_mysqldb import MySQL from datetime import datetime app = Flask(__name__) #Verbindung mit der Datenbank app.config['MYSQL_HOST']= 'localhost' app.config['MYSQL_USER']= 'Bob' app.config['MYSQL_PASSWORD']= '' app.confi...
def biggest(num1,num2,num3): if num1>num2 and num2>num3: return num1 elif num2>num3: return num2 else: max=num3 return num3 num1=int(input("enter the number1:")) num2=int(input("enter the number2:")) num3=int(input("enter the number3:")) print(biggest(num1,num2,num3))
import cv2 as cv2 import unittest import getlines import skew import extract import math ##WHAT THESE TESTS DO: # The first twelve test classes represent different image inputs to the functions within # getlines.py and skew.py, which represent the two facets of our processing algorithm. # The tests within classes: ...
import datetime x=datetime.datetime.now() print(x) x=datetime.datetime.now() print(x.year) print(x.strftime("%A")) x=datetime.datetime(2019,9,19) print(x) x=datetime.datetime(2019,9,19) print(x.strftime("%B"))
import command class Loop(command.Command): def execute(self, env): body = env.qframe.popleft() resp = body.execute_loop(env) if resp == command.LOOP_TERMINATE: return command.NO_TERMINATE elif resp == command.FUNC_TERMINATE: return command.FUNC_TERMINATE ...
# Kazi Shadman Sakib # Roll : 097 import socket import random def errorInserted(encodedVoltageStream): length = len(encodedVoltageStream) while(1): i = random.randint(0,length) if(encodedVoltageStream[i] != " " and encodedVoltageStream[i] != "5" and encodedVoltageStream[i] != "V"): if(encodedVoltageStream[i]...
class Solution: def nextGreaterElement(self, n: int) -> int: seq = list(str(n)) N = len(seq) if N < 2: return -1 i = N - 2 while seq[i] >= seq[i+1]: i -= 1 if i < 0: return -1 j = N - 1 ...
# -*- coding: utf-8 -*- """ Created on Thu Mar 1 15:04:03 2018 @author: Administrator """ from PIL import Image import glob, os size = 128, 128 for infile in glob.glob("*.jpg"): file, ext = os.path.splitext(infile) im = Image.open(infile) im.thumbnail(size) im.save(file + ".thumbnail", "JPEG")
import json data = json.load(open('table.json', 'r')) keys = list(data.keys()) second_level = [data[k].keys() for k in keys] for l in second_level: assert l == second_level[0] table = '<div style="display: flex; justify-content: center;">\n<table class="styled-table">\n' table += f'<thead>\n<tr>\n<th>Estrategias...
""" (C) Copyright 2020-2023 Intel Corporation. SPDX-License-Identifier: BSD-2-Clause-Patent """ from os.path import join from data_mover_test_base import DataMoverTestBase from exception_utils import CommandFailure class DmvrPosixMetaEntry(DataMoverTestBase): # pylint: disable=too-many-ancestors """Test ...
from dataclasses import dataclass,field import numpy as np from ..header_utils import get_last_keyword @dataclass class Result(object): method: str='' x: np.ndarray=field(default = np.zeros(0)) istop: int=-1 itn: int=0 r1norm: float=0.0 r2norm: float=0.0 anorm: float=0.0 acond: float=0...