text
stringlengths
38
1.54M
from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('study/', views.study, name='study'), path('teach/', views.teach, name='teach'), path('search/', views.search, name='search') ]
import torch, random from Batch import nopeak_mask import torch.nn.functional as F import math, sys, traceback def init_vars(src, model, SRC, TRG, opt): init_tok = TRG.vocab.stoi['<sos>'] src_mask = (src != SRC.vocab.stoi['<pad>']).unsqueeze(-2) if opt.nmt_model_type == 'transformer': if opt...
""" Will read entire file in one go and retuns the values as a string. If file not found returns File Not Found String. """ def read_entire_file(filename): try: with open(filename) as file_obj: return file_obj.read() except FileNotFoundError as e: print(e) return f"{e.file...
from django.conf import settings CONNECTION = settings.ARKNODE_PARAMS DELEGATE = { 'ADDRESS': 'AZse3vk8s3QEX1bqijFb21aSBeoF6vqLYE', 'PUBKEY': '0218b77efb312810c9a549e2cc658330fcc07f554d465673e08fa304fa59e67a0a', 'SECRET': settings.PASSPHRASE }
''' [sample code] (https://github.com/xharaken/step2015/blob/master/calculator_modularize_2.py) ''' def readNumber(line, index): number = 0 while index < len(line) and line[index].isdigit(): number = number * 10 + int(line[index]) index += 1 if index < len(line) and line[index] == '.': ...
#calculator for poer consumption units = float(input("Please enter Number of Units you Consumed : ")) #USER CONSOLE if units < 50: amount = units * 3 elif units <= 100 and units>=51: amount = 150 + ((units - 50) * 6) elif units <= 200 and units>=101: amount = 150 + 300 + ((units - 100) * 9) else: ...
# -*- coding: utf-8 -*- """ Created on Fri Sep 16 16:29:52 2016 @author: Shaurita D. Hutchins """ # Part 3: Use multiple sequence alignments in phylip format to create phylogenetic trees. # Mark start of program with printed text description/title. print("\n" + (81 * "#") + "\n" + "#### Part 3: Use multiple sequence...
import os from .base import ExecCompiler class StylusCompiler(ExecCompiler): result_mimetype = 'text/css' executable = 'node' params = [os.path.join(os.path.dirname(__file__), 'stylus.js')] def get_args(self): args = super(StylusCompiler, self).get_args() args.append(self.asset.absol...
import logging import sqlalchemy_utils from .config import DB_CONN_STRING logging.getLogger().setLevel(logging.INFO) def drop_database() -> None: if sqlalchemy_utils.database_exists(DB_CONN_STRING): sqlalchemy_utils.drop_database(DB_CONN_STRING) logging.info('User identity database deleted') ...
#dicionario de alunos Alunos = {"marco": "email", "paulo":"hotmail", "matheus": "matheusemail", "jean": "jeanemail", } def mostralist(): for aluno, email in Alunos.items(): print(aluno,":" ,email) mostrarmenu() #Mostrandando em oredem alfabetica def mostra_alf(): for aluno, email in ...
class Server: def __init__(self): self.server_data = [] def get_data(self): return self.server_data def upload_data(self, payload): self.server_data = payload
import torch from copy import deepcopy from time import time from .losses import model_norm, round_loss, models_dist from .losses import node_local_loss, predict from .metrics import extract_grad, sp from .data_utility import expand_tens, one_hot_vids from .visualisation import disp_one_by_line from .hyperparameters i...
from tcn import TemporalConvNet import torch.nn as nn class ContextNet(nn.Module): def __init__(self, num_inputs, output_len, num_channels, kernel_size=2, dropout=0.2): super(ContextNet, self).__init__() self.m = TemporalConvNet(num_inputs, num_channels, kernel_size, dropout) #for now just ...
""" Class for Trainwave """ import numpy as np from obspy import UTCDateTime from obspy.signal.trigger import trigger_onset from scipy.signal import hilbert from locevdet.stations import Station from locevdet.waveform_processing import trim_trace from locevdet.utils import rolling_max, kurtosis_norm, starttimes_tr...
from django.conf.urls import patterns, include, url from django.conf.urls.static import static from django.conf import settings from django.contrib import admin admin.autodiscover() urlpatterns = (static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) + static(settings.MEDIA_URL, document_root...
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def levelOrder(self, root): if root is None: return [] que = [root, None] ret = [] ...
# -*- coding: utf-8 -*- # @Author : Erwin import tensorflow as tf """ 1. https://blog.csdn.net/cc1949/article/details/78422704 """ # 一维测试 a = tf.constant([1, 2, 3, 2]) with tf.Session() as sess: print("vector transpose:", sess.run(tf.transpose(a))) print("=" * 80) # 二维测试 a = tf.constant([1, 2, 3, 2], shape=[2, 2...
import torch from torch.autograd import Variable import torch.nn as nn import torch.nn.functional as F from constants import * class DecoderLSMT3(nn.Module): def __init__(self, input_size, output_size, max_length=MAX_LENGTH): super(DecoderLSTM3, self).__init__() self.hidden_size = hidden_size self.output_size...
from networkapi.test.test_case import NetworkApiTestCase from networkapi.plugins.SDN.ODL.flows.acl import AclFlowBuilder class TestSendFlowsWithTCPFlags(NetworkApiTestCase): """ Class to test flows that have tcp flags on it """ def test_flow_with_ack_flag(self): """ Try to send a flow with ACK flag ...
def main(): class_a_sold = int(input('How many class a sold:')) class_b_sold = int(input('How many class b sold:')) class_c_sold = int(input('How many class c sold:')) calc(class_a_sold, class_b_sold, class_c_sold) def calc(class_a, class_b, class_c): total = class_a * 15 + class_b * 12 + class_c * 9 print('Tot...
from django.http import HttpResponse from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger import json from django.views.decorators.csrf import csrf_exempt from freeLink.utils import error from commonLink import models from commonLink.repo import keywordContentRepo @csrf_exempt def rankingList(requ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Time : 下午3:49 Author : wangjf GitHub : https://github.com/wjf0627 """ import numpy as np def rmse(predictions, targets): # 真实值与目标值的误差 differences = predictions - targets differences_squared = differences ** 2 mean_of_differences_squared = differ...
import os import csv import log import sys import pytest import filecmp import stock import installer import updater from global_vars import * #PATH_FOR_INSTALLER = '/Users/Manda/StockWatch/development/' ## home PATH_FOR_INSTALLER = '/Users/phillipbrown/StockWatch/development/' ## Uni TEST_CODE = 'APT' TEST_TIME_...
#_*_ coding:utf-8 _*_ import sys sys.path.append('..') from sql.table import Table from utils.log import Log from task_tool import Task_Tool ''' 更新category中的book_count,book表中d_count,total,rate ''' def update_category(logger,is_test=False): ##更新table category 的book_count table = Table(logger=logger) bo...
from django.shortcuts import render from .models import Post def index(request): posts = Post.objects.all().order_by('-created_at') return render(request,"sharepic/index.html", {'posts':posts})
import math import wpilib from wpilib import SmartDashboard from wpilib.command import Command from wpilib.command import TimedCommand class DriveStraightDistance(TimedCommand): def __init__(self, distance = 10, timeout = 0): super().__init__('DriveStraightDistance', timeoutInSeconds = timeout) s...
import time import os import timeit from game_board import GameBoard from game_logic import update_path_weights, update_position_weights, choose_path, check_gameOver from submodule.piece_type import GAME_PIECE_O, GAME_PIECE_X def run_game(): # create the game board gameboard = GameBoard() GameOver = Fa...
from torch.utils.data import DataLoader from torch.autograd import Variable from Dataloader.Seq2Seq_DataLoader import DataTransformer import pandas as pd import numpy as np import torch import torch.nn as nn from Model.Encoder import VanillaEncoder, BidirectionalGRUEncoder from Model.Decoder import VanillaDecoder fr...
import requests import json import pickle username = '15168301541' password = 'ma199491' params = { 'ck': '', 'name': username, 'password': password, 'remember': False, 'ticket': '' } headers = { 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Geck...
from model.Servicemodel import ServiceRecord from lxml import etree class SeniorDatingSites(): def __init__(self): pass def parsing(self, response): return self.crawl(response,self.category,self.servicename) def crawl(self, response, category, servicename): reviews = [] self...
grid = [['.', '.', '.', '.', '.', '.'], ['.', 'O', 'O', '.', '.', '.'], ['O', 'O', 'O', 'O', '.', '.'], ['O', 'O', 'O', 'O', 'O', '.'], ['.', 'O', 'O', 'O', 'O', 'O'], ['O', 'O', 'O', 'O', 'O', '.'], ['O', 'O', 'O', 'O', '.', '.'], ['.', 'O', 'O', '.', '.', '.'], ...
from mediawiki import MediaWiki import model_2_all import sys import os def NE_features(data, i): ''' Defines the features of all words in a dictionary. ''' # Adds word and its POS tag features = { 'word': data[i][3], 'POS': data[i][4], } # Adds the named entity tag i...
""" test_app executes run(). Manually run in the project main directory. """ import sys, os import json from kivy.app import runTouchApp, stopTouchApp from kivy.uix.gridlayout import GridLayout sys.path.insert(1, os.path.join(sys.path[0], '..')) from controller import Controller from models import set_in_device, set_s...
# coding: utf-8 import numpy as np import matplotlib.pyplot as plt import astropy from astropy.io import fits image_list = [ 'AGN_1.fits.gz','AGN_2.fits.gz','AGN_3.fits.gz','AGN_4.fits.gz','AGN_5.fits.gz','AGN_6.fits.gz','AGN_7.fits.gz','AGN_8.fits.gz','AGN_9.fits.gz','AGN_10.fits.gz','AGN_11.fits.gz','AGN_12.fits.gz'...
# -*- coding: utf-8 -*- from flask import request, redirect, url_for, render_template, Flask, flash from apps import app from apps.forms import EventsForm @app.route('/events/events_create', methods=['GET', 'POST']) def events_create(): form = EventsForm() return render_template('events/events_create.h...
def palindrome(): x = input("Tell me a word: ") mid = int (len(x)/2) for i in range(0, mid): if x[i] != x[-(i + 1)]: break i += 1 return True
import os.path lines = (line.rstrip('\n') for line in open("last_test_coverage.txt")) for line in lines: words = line.split() fn = words[0].replace(".","/") + ".py" if os.path.isfile(fn) and words[3] != "0%": print fn
from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column, Integer, String, ForeignKey, Float, Boolean from sqlalchemy.dialects.postgresql import TIMESTAMP Base = declarative_base() class Arduino(Base): __tablename__ = 'tb_arduino' id = Column(Integer, primary_key=True, autoincre...
import dgl import math import torch import torch.nn as nn import torch.nn.functional as F class NeuPathLayer(nn.Module): def __init__(self, in_dim, out_dim, num_types, num_relations, n_heads, dropout=0.2, use_norm=False): super(NeuPathLayer, self).__init__() self.in_dim = in_dim ...
# Generated by Django 2.2.1 on 2019-06-04 18:48 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('questionnaire', '0007_auto_20190604_1615'), ] operations = [ migrations.AlterModelOptions( name...
import requests import json output = open("manga.csv", "w", encoding="utf-8") output.write("media_type_id, title, status, release_date, chapter_count, image_source\n") data = [] # Get manga data from Kitsu API for page in range(10): response = requests.get(f"https://kitsu.io/api/edge/manga?page[limit]=20...
_author_ = "Ethan Richards" # CIS 125 #War # WarV1.py #Simulates a game of War. import random #build the full deck and decks for each player Deck = [] A = [] B = [] rounds = 0 for i in range(52): Deck.append(i) random.shuffle(Deck) for card in range(26): A.append(Deck.pop()) B.append(Deck.pop()) ...
model = dict( type='MaskRCNN', # The name of detector pretrained='torchvision://resnet50', # The ImageNet pretrained backbone to be loaded # The config of backbone backbone=dict( type='ResNet', # The type of the backbone depth=50, # The depth of backbone, usually it is 50 or 101 for...
import sys import re import select import socket import psutil import threading SERVER_PORT = 1006 CLIENT_PORT = 1903 LISTEN_MAX = 5 BUFSIZE = 4096 # SERVER_IP = "25.53.181.229" # SERVER_IP = "25.10.32.20" # SERVER_IP = "25.44.168.204" # SERVER_IP = "25.6.9.155" SERVER_IP = "172.27.44.23" EMPTY_NAME = "__Em...
H, M = map(int, input().split()) h, m = divmod(60*H+M-45, 60) if h < 0: print(h+24, m) else: print(h, m)
#!/usr/bin/env python from argparse import ArgumentParser import matplotlib.pyplot as plt from history_utils import plot_history_file if __name__ == '__main__': arg_parser = ArgumentParser(description='show training history') arg_parser.add_argument('file', help='HDF5 file containing the ' ...
import winsound import time import sys import numpy as np import socket import os from random import randint filename = "../Logs/SoundLogs/Sound_" + time.strftime("%Y%m%d-%H%M%S") + ".txt" f = open(filename,'a') # Trying to create a new file or open one # f.close() current_milli_time = lambda: int(round(time.time()...
#! /usr/bin/python -tt ######################################################################## # Copyright (c) 2011 by Vinny Murphy # 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 re...
#!/usr/bin/env python #-*- coding:utf-8 _*- """ @File : rtckpi.py @version : 0.1 @Author : Kelvin @Time : 2020-03-01 -------------------------------------------------------------------- @Changes log: 2020-03-01 : 0.1 Create """ import getopt import logging import os import sys import config im...
''' You've been preparing all night for the upcoming test and entered the class certain that you will ace it. Now that you received the test questions, you died inside a little: looks like you prepared for the test on a completely different topic. You're not even sure if you should bother to answer the questions. You ...
import random from HeuristicaInsercionEjes import * from HeuristicaInsercionNodos import * from HeuristicaDeLaMediana import * from SolucionSwapperTablaPoda import * import psyco from psyco import * class Tp3: def limpiarDibujo(self,d,losEjesDe): g = d.g marcados1 = d.l1 marcado...
obj = hashlib.md5("sfdsg".encode("utf8")) #加盐加密 obj3 = hashlib.sha256("sfdsg".encode("utf8")) #加盐加密 obj1 = hashlib.md5("sfdsg".encode("utf8")) obj.update("hello".encode("utf8")) obj2.update("hello".encode("utf8")) obj3.update("hello".encode("utf8")) print(obj.hexdigest()) print(obj1.hexdigest()) print(obj3.hexdige...
#------------------------------------------------------------------------------- # # Utility module tests. # # Author: Martin Paces <martin.paces@eox.at> # #------------------------------------------------------------------------------- # Copyright (C) 2017 EOX IT Services GmbH # # Permission is hereby granted, free o...
""" entrada a-->int-->a b-->int-->b c-->int-->c salida respuesta-->str-->resultado """ a, b, c, d = map(int, input("Digite los 4 datos: ").split()) if d==0 : resultado = (a-c)**2 elif d>0 : resultado = ((a-b)**3)/d print("El resultado es: "+str (resultado))
# 8. Матрица 5x4 заполняется вводом с клавиатуры, кроме # последних элементов строк. Программа должна вычислять # сумму введенных элементов каждой строки и записывать ее в # последнюю ячейку строки. В конце следует вывести полученную # матрицу. m = 5 n = 4 b = [] a = [] sum = 0 for i in range(n): print(f'{i}-я с...
#! /usr/bin/env python import vrx_gazebo_python.generator_scripts.wamv_config.configure_wamv if __name__ == '__main__': vrx_gazebo_python.generator_scripts.wamv_config.configure_wamv.main()
import cv2 import sys import random def detect(ImagePath): # get cascade path cascPath = 'haarcascade_frontalface_default.xml' #create the haar cascade faceCascade = cv2.CascadeClassifier(cascPath) #read image and convert to grayscale image = cv2.imread(ImagePath) gray = cv2.cvtColor(imag...
import time import re from tenacity import retry, stop_after_attempt, wait_exponential import requests import lxml.html TEMPORARY_ERROR_CODES = (408, 500, 502, 503, 504) def scrape_list_page(res_list): html_list = lxml.html.fromstring(res_list.text) a_list = html_list.cssselect('#main table td.link > a') a_lis...
# https://leetcode.com/problems/number-of-islands/ def numIslands(grid): # looks like DFS # keep going while you can reach 1s, and add those 1s to visited hash # append 1 to numberOfIslands # keep recursing, check for visited, if not visited and it's 1, repeat above result = 0 for i ...
"""Condensed-Nearest Neighbors (CNN) Instance Selection 的方法""" import numpy as np from sklearn.utils.validation import check_X_y from sklearn.utils import check_array from sklearn.neighbors.classification import KNeighborsClassifier class CNN(): """"Condensed-Nearest Neighbors (CNN) 每個類別都需要一...
#!/usr/bin/env python # encoding: utf-8 """ __init__.py """ import datetime import itertools import os from nprslurp.version import VERSION as __version__ __all__ = ['nprslurp'] FILE = "{date.year}{date.month:02d}{date.day:02d}_{show}_{part:02d}.mp3" URL = "http://public.npr.org/anon.npr-mp3/npr/{show}/{date.year}/{...
from distutils.core import setup README = open('README.md').read() setup( author="R. C. Thomas", author_email="rcthomas@lbl.gov", description="IPython magic for SLURM.", long_description=README, name="slurm-magic", py_modules=["slurm_magic"], requires=["ipython"...
import matplotlib.pyplot as plt # matplotlib.use("Qt5Agg") import numpy as np import pandas as pd import Environments.transportEnvOld as transport from spinup.algos.sac.sac import sac env = transport.transportENV() env_fn = lambda: env # env_fn = lambda : gym.make('Pendulum-v0') # if __name__ == '__main__': # # ...
# Generated by Django 3.1.6 on 2021-02-04 05:14 import datetime from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Amenities', ...
import unittest class Node: """Klasa reprezentująca węzeł drzewa binarnego.""" def __init__(self, data=None, left=None, right=None): self.data = data self.left = left self.right = right def __str__(self): return str(self.data) def count_leafs(top): if top.data is No...
from classifiers.knn import KNN from classifiers.svm import SVM from data_utils import get_data, subsample_data, normalize_data, show_image from classification_utils import cross_validate_params, predict_success_rate, cross_validate_and_predict CIFAR10_FOLDER = 'cifar10_data' # KNN HYPERPARAMETERS Ks = (1, 3, 5, 8, 1...
from bs4 import BeautifulSoup import time import pandas as pd import json import requests import datetime import os import csv dflist = pd.DataFrame() ###setting path ltn_dict = r'./ltn_dict' #存至此目錄 ###if directory not exist add it if not os.path.exists(ltn_dict): #若目錄不存在則新增一個 os.mkdir(ltn_dict) ###setting tod...
from email.mime.text import MIMEText import smtplib def send_email(email,height,average_height,count): from_email="zyc378028556@gmail.com" from_passward="5015022zyc..." to_email=email subject="Height data" message="Hey there, your height is <strong>%s</strong>.<br>Average height of all is <strong>...
# -*- coding: utf-8 -*- """ Created on Tue Feb 7 13:32:59 2017 @author: jasonhuang """ import pandas as pd import numpy as np #import matplotlib.pyplot as plt inspect_data = 'nyc_ind_inspect.pkl' pkl_path = '../../Data/Pickles/' df = pd.read_pickle(inspect_data) #dta_path = 'Data/DTA/' df.sort_values(['CAMIS','INSP...
from cvxpy import * from os import listdir import numpy import glob import os import subprocess import time import numpy as np import matplotlib.pyplot as plt def run_testfile(filename): print filename settings.USE_CVXCANON = False exec("from cvxpy import *\nsettings.USE_CVXCANON=False\n" + open(filename).read...
import pgzrun import pygame from random import randint, choice import string WIDTH = 800 HEIGHT = 600 BLACK = (0, 0, 0) WHITE = (255, 255, 255) bgbutton = pygame.display.set_mode((WIDTH,HEIGHT)) image = pygame.image.load(r'PRGAME\images\img1.jpg') image1 = pygame.image.load(r'PRGAME\images\img2.jpg') image2 = pygame...
import boto3 import click from .click_tools import click_defaults @click.option("--export-type", "-e", type=click.Choice(["cfn"]), default="cfn") @click.argument("name") @click_defaults def click_import_value(export_type, name): if export_type == "cfn": print(cloudformation_export(name)) def cloudform...
from django.contrib import admin from .models import Users, Courses, Lectures, HomeworkSolution, Mark, CommentsToHomework admin.site.register(Users) admin.site.register(Courses) admin.site.register(Lectures) admin.site.register(HomeworkSolution) admin.site.register(Mark) admin.site.register(CommentsToHomework)
from rest_framework.routers import DefaultRouter from django.urls import path, include, re_path from . import views as posts_views router = DefaultRouter() router.register(r'posts', posts_views.PostsView, basename='posts') router.register(r'comments', posts_views.CommentsView, basename='comments') urlpatterns = [ ...
# ============================================== # Cameras # ============================================== from POVRaySimulatedCameraDevice import * from FakeCameraDevice import * try: from ProsilicaCameraDevice import * except e: pass # ============================================== # LED Controllers # ========...
# 暂未调通,不知原因 import nose2 from nose2.tools import params from src.demo.calculator import Calculator test_data = [ {"nums": (3, 5), "total": 8}, {"nums": (1, 2), "total": 3}, {"nums": (2, 2), "total": 4} ] @params(*test_data) def test_add(data): c = Calculator() result = c.add(*data["nums"]) ...
# Copyright CERFACS (http://cerfacs.fr/) # Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0) # # Author: Natalia Tatarinova from netCDF4 import MFDataset import numpy import util_dt def get_tile_dimension(in_files, var_name, transfer_limit_Mbytes=None, time_range=None): ''' Computes ...
# -*- coding: utf-8 -*- import requests import json import os from . import ispras class API(ispras.API): """This class provides methods to work with Texterra REST via OpenAPI, including NLP and EKB methods and custom queriesю Note that NLP methods return annotations only""" # Default Texterra path texterra...
import logging import sys def load_logger_conf(): FORMAT = '%(asctime)-15s %(message)s' logging.basicConfig(filename='loggings.log', level=logging.INFO, format=FORMAT) logging.getLogger().setLevel(logging.INFO) # add the handler to the root logger formatter = logging.Formatter('[%(asctime)s] %(mess...
import hashlib import sqlite3 from functools import partial from tkinter import * from tkinter import simpledialog from tkinter import ttk from passgen import passGenerator with sqlite3.connect('pv.db') as db: cursor = db.cursor() cursor.execute(""" CREATE TABLE IF NOT EXISTS masterpassword( id INTEGER PRIMARY...
'''Interfaces with the Crypt class and creates a GUI.''' __author__ = 'Stephen' __version__ = '1.0' from Crypt import Crypt import os from Tkinter import * from tkSimpleDialog import * from tkFileDialog import * from tkMessageBox import * class Application: '''Creates a GUI to interact with.''' def __init_...
############################################################################## from sklearn.ensemble import RandomForestClassifier from sklearn.linear_model import LogisticRegression, SGDClassifier """This module contains all variables for experimentation and prediction.""" # FILENAME OF THE ENCODED HEADERS CREATED...
import os, re, json import time from datetime import datetime, date, timedelta from flask import Flask, request, abort import requests from linebot import ( LineBotApi, WebhookHandler ) from linebot.exceptions import ( InvalidSignatureError ) from linebot.models import ( MessageEvent, TextMessage, TextSendM...
#!/usr/bin/env python import threading import time def worker(): print("i'm thread") t = threading.current_thread() time.sleep(8) print(t.name) #new_t = threading.Thread(target=worker, name='sjk_thread') #new_t.start() worker() t = threading.current_thread() print(t.name)
import requests import pandas as pd import numpy as np from pandas import read_csv import glob import time import datetime import os import os.path # Get Stock Tickers ticker = read_csv('/Data/TICKER.csv',header = None) # e.g. 0001.HK path = '/Data/' IDList = list(ticker[0]) IDList.sort() # Set Dates...
from flask import Flask, render_template, request, redirect #added request app = Flask(__name__) # We will let the index page handle the form rendering @app.route('/') def index(): return render_template('index.html') # The users page handles sending the info entered in the form to the backend via a dictionary. @...
""" findTubelets.py is a utility that will eventually be merged with extracFrames.py to process the tubelets from videos in an online manner. Precondition: There exist dataSet directories such as UCF, Validation, Test that contain directories corresponding to video names such as v_ApplyEyeMakeup_g08_c01. Each di...
import numpy as np import os from PIL import Image def load(dir, files, reshaped): "Load .npy or .npz files from disk and return them as numpy arrays. \ Takes in a list of filenames and returns a list of numpy arrays." data = [] for file in files: f = np.load(dir + file) if reshaped: ...
from time import sleep from selenium.webdriver.common.by import By from Test.PageObject.BasePage.Common import base_class from Test.PageObject.Locators import Locator class Registration(object): def __init__(self, driver): self.driver = driver # Defining the locators of Registration sel...
from __future__ import print_function import argparse import os import torch from model import Model from video_dataset import Dataset from test import test from train import train #from logger import Logger from torch.utils.tensorboard import SummaryWriter as Logger import options torch.set_default_tensor_type('torch....
import scrapy class DataSpider(scrapy.Spider): name = "data" start_urls = ['https://shop.mango.com/bg-en/women/skirts-midi/midi-satin-skirt_17042020.html?c=99', ] def parse(self, response, **kwargs): name = response.css('h1.product-name::text').get() price = response.css('span.product-sa...
from bintree import get_visible_nodes, Treenode def test_empty_tree(): assert get_visible_nodes(None) == -1 def test_one_node(): assert get_visible_nodes(Treenode(11, None, None)) == 1 def test_multiple_nodes(): n15 = Treenode(7, None, None) n14 = Treenode(4, None, None) n13 = Treenode(33, Non...
def cost(x,y,w): n = len(x) total_error = 0.0 for i in range(n): cost = (y[i]-w*x[i])**2 total_error+=cost return total_error/n def update(x,y,w,lr): m_deriv = 0 n = len(x) for i in range(n): m_deriv = m_deriv - 2*x[i] * (y[i] - (w*x[i])) ...
# Naam: Christiaan Posthuma # Datum: vandaag 11 okt # Versie: 1.0.0.0 ######################################## import tkinter as tk # importeer methodes voor keuzemenu vanuit tkinder module import tkinter.filedialog as tkFile openwindow = tk.Tk() # opent een window voor het keuzemenu openwindow.withdraw() # haal...
import sys from itertools import product,combinations from time import time ''' python FrequentWordsMismatch.py input.txt ''' Out=open("output.txt",'w') Input=open(sys.argv[1]) Input=Input.read().split("\n") String=Input[0] K=int(Input[1].split(" ")[0]) mis=int(Input[1].split(" ")[1]) def reverse_complement(s): c...
n1 = int(input('Digite um numero para saber toda a sua tabuada:')) n2 = n1*1 n3 = n1*2 n4 = n1*3 n5 = n1*4 n6 = n1*5 n7 = n1*6 n8 = n1*7 n9 = n1*8 n10 = n1*9 print('A tabuada de {} é:'.format(n1)) print('{} x 1 = {} \n{} x 2 = {} \n{} x 3 = {} \n{} x 4 = {} \n{} x 5 = {} \n{} x 6 = {} \n{} x 7 = {} \n{} x 8 = {} \n{}...
import FWCore.ParameterSet.Config as cms from RecoMuon.TrackingTools.MuonServiceProxy_cff import * from DQMServices.Core.DQMEDAnalyzer import DQMEDAnalyzer muonEnergyDepositAnalyzer = DQMEDAnalyzer('MuonEnergyDepositAnalyzer', MuonServiceProxy, ...
import sys from collections import deque while True: line = sys.stdin.readline().strip() n, k = [int(x) for x in line.split()] if n == 0 and k == 0: break row = deque() for i in range(0, n): row.append(i) payment = [40] * n cash = 1 dispense = cash while row: ...
""" SQLite database to persist the values. """ import sqlite3 from time import time class DB: def create_db(self): """ Create connection and table in SQLite DB. """ file = f'databases/values_{int(time())}.db' open(file, 'w') # TODO: 2 files are created self.conn = sqlite3.connec...
from contextlib import redirect_stdout import sys def manufacture_title(): TITLE_PREFIX = '3.3.2' FUNC_LVL = '#' * 5 FUNC_NUM = 2 DETAIL_LEVEL = FUNC_LVL + '#' for i in range(8, FUNC_NUM+8): print(f'{FUNC_LVL} {TITLE_PREFIX}.{i}') print(f'{DETAIL_LEVEL} {TITLE_PREFIX}.{i}.1 功能描述') ...