text
stringlengths
8
6.05M
import numpy as np from ucca4bpm.util.visualization import build_run_history_from_path runs = { 'Ours on Quishpi Data': 'ucca4bpm/runs/our_approach_quishpi_data/quishpi_their_data.json', 'Ours on Our Data ala Quishpi': 'ucca4bpm/runs/our_approach_quishpi_data/quishpi_our_data.json', 'Quishpi on Quishpi D...
from math import log2 from random import randint from enums.Attributes import Attributes from enums.EquipmentType import EquipmentType from enums.Monsters import Monsters from enums.Stats import Stats from model.Equipment import Equipment from model.Player import Player class Fight: def __init__(self, player, p...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ app.modules.menus ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 菜单模块 """ from flask_smorest import Blueprint blp = Blueprint("Menu", __name__, url_prefix="/menus", description="菜单模块")
import requests class FixerAPI(object): """docstring for network""" baseApi = 'https://api.fixer.io/' # https://api.fixer.io/latest?base=EUR&symbols=EGP def getExchangeRate(self,base,currency,date=''): # print("network loading...") # initialization url query params payload = {'base':base,'symbols':currency} ...
from myhdl import * class SignalMatrix(object): def __init__(self, size=(4,4,), stype=intbv(0)[9:]): # the size of the matrix self.size = size nrows,ncols = size # the size (number of bits) for each item in the matrix if isinstance(stype, intbv): self.nbits =...
# Definicio de Aplicaciones de Flask # Aqui iran todas las aplicaciones from flask import Flask # Importo el modulo de configuraciones from config import Develop # Creo una nueva app llamada blog blog = Flask(__name__) # Configuro mi app para que tome estas configuraciones: blog.config.from_object(Develop)
from django.conf import settings from django.core.exceptions import ObjectDoesNotExist, MultipleObjectsReturned from django.db import models from django.template.defaultfilters import slugify from django.utils import timezone from django.utils.translation import ugettext_lazy as _ from apps.articles.managers import Ar...
import io import cv2 import time import base64 import requests import numpy as np import dlib_detection from PIL import Image from flask import Flask,render_template,request,jsonify import sys app = Flask(__name__) class Singleton(object): _instance = None def __new__(cls, *args, **kw): if not cls._in...
""" Type definition for model parameters """ from math import floor from pydantic import BaseModel, Extra, root_validator, validator from pydantic.dataclasses import dataclass from datetime import date from typing import Any, Dict, List, Optional, Union from autumn.models.covid_19.constants import COVID_BASE_DATETIME...
# -*- coding: UTF-8 -*- u''' ****************************************************************************** * 文 件:HCSR04.py * 概 述:HCSR04超声波传感器模块功能模块 * 版 本:V0.10 * 作 者:Robin Chen * 日 期:2018年4月27日 * 历 史: 日期 编辑 版本 记录 2018年4月27日 Robin Chen V0.10 创建文件 ******************...
from tkinter import Toplevel, Label, StringVar, BooleanVar, Entry, Button, Frame, Radiobutton, Checkbutton from tkinter import ttk from tkinter import N, S, E, W import re import helpers class Timer_settings (): def __init__ (self, parent): ''' class to: edit timer precision, splits to display...
#!/usr/bin/python import sys import json from datetime import time, datetime if len(sys.argv) < 3: print "Convert space delimited file of \"Date time count sum\" into \"Date time reply_latency\"" print "USAGE:", sys.argv[0], "<file> <latency|ops-per-second>" sys.exit(0) l = 0 f = open(sys.argv[1]) stat = ...
# -*- coding: utf-8 -*- """ Created on Wed Feb 6 15:13:53 2019 @author: Lenovo """ from sklearn.naive_bayes import MultinomialNB import os import glob file_path = 'enron1/spam/' file_path_ham = 'enron1/ham/' emails, labels = [], [] for filename in glob.glob(os.path.join(file_path_ham, '*.txt')): wi...
from __future__ import absolute_import from __future__ import division from __future__ import print_function import torch import torch.nn as nn import torch.nn.functional as F import numpy as np import json from json import encoder import random import string import time import os import sys from captioning.utils imp...
from pyspark import SparkContext import json def map_a(res): return ('review_count', 1) def count_a(a,b): return a+b\ def map_b(res, y): pass def main(argv): sc = SparkContext(appName="inf553hw1") with open(argv[1], 'r') as load_f: load_dict = json.load(load_f) rdd = sc.paralleli...
valores = [] while True: valores.append(int(input('Digite um valor: '))) opcao = input('Quer continuar? [S/N]: ') if opcao in 'Nn': break print(f'Foi digitado {len(valores)} valores na lista.') valores.sort(reverse=True) print(f'A lista ordenarna em ordem descrescente é {valores}') if 5 in valores...
#!/usr/bin/python3 # -*- coding: utf-8 -*- ''' 1.随机生成一个整数,1-100之间,你最多猜5次,如果大了,就提示,小了,提示小 猜对了就提示猜中了 5次都没有,就猜没猜中 ''' import random number = random.randint(1,100) for i in range(7): user_number = int(input("输入的数字:")) if number == user_number: print("你猜中了,数字是:",user_number) print("你猜了 %s 次"%i) break elif number >...
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import sys import argparse import numpy from ising import Ising from ext import progressbar as pb from misc import drawwidget from ext.hdf5handler import HDF5Handler def main(): if os.path.exists(args.filename): pythonversion = sys.version_info[0] ...
class Solution(object): def letterCombinations(self, digits): """ :type digits: str :rtype: List[str] """ if digits == '': return [] mapping = { '2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl', '6...
# -*- coding: utf-8 -*- # # * Copyright (c) 2009-2017. Authors: see NOTICE file. # * # * 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...
import string def text_analyzer(text = ""): """This function counts the number of upper characters, lower characters, punctuation and spaces in a given text.""" while text == "": text = input("What is the text to analyse?\n>> ") print(f"The text contains {len(text)} characters:") upper_letters = 0 lower_letters...
"""Compare two alignments for potential phosphorylation sites (Ser/Thr/Tyr). Based on the "urn" model, but testing for conservation of Ser/Thr/Tyr instead of the foreground consensus residue type. """ import logging import math from scipy.stats import binom from biofrills import consensus, alnutils from .shared im...
API_KEY= 'NN0xGCu6UZ7xQFudZYjR0R9Xs' API_SECRET_KEY= 'wU0cC2H4l86K57j0D6EkXHMNTlmLptbFrpCC8PgUmwIdAHeqEl' ACCESS_TOKEN = '1263547688043401217-ZaFADOwmTYplu5yRpxJ5MHtNzQEPly' ACCESS_TOKEN_SECRET = 'KqcjTKbrNIoUZPMyXTwXmHm5RfUz6jHDWcGC4rH4IqkcQ'
fname = "/local/pcurran/leads_frag/"
# ================================================================================================== # Copyright 2011 Twitter, Inc. # -------------------------------------------------------------------------------------------------- # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use thi...
import cinje import requests from web.app.djrq.templates.lastplayed import lastplayed_row from helpers.sec_to_hms import sec_to_hms from statistics import mean def update_database(ctx=None, djlist=None, as_dj=None, info=None, found_info=None, no_updates=None, update_played_only=False, ...
import sys sys.stdin=open("input.txt", "r") # # 파이프 옮기기 # ''' # pipe: 위치 (파이프가 끝나는 지점) + 모양 # 모양: # 0 = 가로 # 1 = 세로 # 2 = 대각선 # ''' # def isHorizontalPossible(r, c): # if c + 1 > N - 1: # return False # if board[r][c + 1] == 1: # return False # return True # def isVerticalPo...
from django.test import TestCase from django.test.client import Client from django.core.urlresolvers import reverse from person.models import Token, UserProfile, Timing from django.conf import settings from instructor.views import (create_question_template, render) from course.models import Course from question.models ...
# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2019-11-29 03:29 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('web', '0001_initial'), ] operations = [ migr...
from __future__ import division from __future__ import print_function import pickle #import pandas as pd import numpy as np import sys from sklearn.preprocessing import StandardScaler from sklearn.model_selection import train_test_split import matplotlib matplotlib.use('Agg') import matplotlib.pylab as plt #get_ipython...
import morepath import os.path import time from onegov.core.framework import Framework from onegov.core import utils from onegov.core.static import StaticFile from webtest import TestApp as Client def test_static_file(temporary_directory): class App(Framework): serve_static_files = True @App.static...
from chats.views import chat_list, create_chat from chats.views import send_message, user_chats, read_message from django.urls import path urlpatterns = [ path('', chat_list, name='chat_list'), path('<int:pk>', chat_list, name='chat_list'), path('new/', create_chat, name='create_chat'), path('<str:pk>'...
from __future__ import division from __future__ import print_function import struct ''' reads the file ../lena_256.png starts 0x800000 ends 0x8ffff little endian 0000000 009c 0000 00a4 0000 00a4 0000 00a4 0000 0000020 009c 0000 009c 0000 009c 0000 00a4 0000 0000040 009c 0000 009c 0000 009c 0000 009c 0000 . . . 0...
n=int(input() l=[int(x) for x in input().split()] print(*sorted(l))
# # tuple=('a','b','c') # tuple1=('a','b','c') # tuple2=('a1','b1','c1') # # a=tuple1 # # tuple1=tuple2 # # tuple2=a # tuple1,tuple2=tuple2,tuple1 # print(tuple1) # print(tuple2) # a={"hello" : "сайн уу", # "bye" : "баяртай", # "name" : "нэр"} # print(a) # print(a["hello"]) # print(a.get("hello")) # if("hel...
from flask import Flask from pymongo import MongoClient app = Flask(__name__) client = MongoClient('db', 27017) db = client.test @app.route('/') def hello(): return 'Hello World v7' @app.route('/create_post',methods=['GET','POST']) def create_post(): post={"author": "Mike", "text": "My first...
from onegov.core.security import Private from onegov.org import _, OrgApp from onegov.org.models import SiteCollection @OrgApp.json(model=SiteCollection, permission=Private) def get_site_collection(self, request): """ Returns a list of internal links to be used by the redactor. See `<https://imperavi.com/red...
import turtle as t t.shape('classic') width = 2 t.width(width) side = 100 for i in range(10): t.penup() t.goto(-side/2, -side/2) t.pendown() for j in range(4): t.forward(side) t.left(90) t.penup() t.goto(-side//2, -side//2) t.pendown() side += 30
# @Title: 二叉搜索树的最小绝对差 (Minimum Absolute Difference in BST) # @Author: 2464512446@qq.com # @Date: 2020-10-12 10:20:22 # @Runtime: 64 ms # @Memory: 15.6 MB # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None c...
a, b, c ,d = map(int, input().split()) if a < c: a1 = a b1 = b a2 = c b2 = d else: a1 = c b1 = d a2 = a b2 = b print('[',end='') if b1 < a2: pass else: if a1<=a2<=b1: print(a2,end=',') if b1 >= b2: print(b2, end='') else: print(b1, end='') print(']...
#!/usr/bin/env python # coding: utf-8 import requests import base64 import datetime from urllib.parse import urlencode client_id = "" client_secret = "" class SpotifyAPI(): access_token = None access_token_expires = datetime.datetime.now() access_token_did_expire = True client_id = None client_se...
import numpy as np import pytest from simulation.diffusion import discrete_laplacian from simulation.grid import RectangularGrid @pytest.fixture def grid(): yield RectangularGrid.construct_uniform(shape=(3, 3, 3), spacing=(1, 1, 1)) @pytest.fixture def mask(grid): yield np.zeros(grid.shape, dtype=np.dtype(...
import zmq ctx = zmq.Context.instance() server = ctx.socket(zmq.ROUTER) server.bind('inproc://foo') clients = [ctx.socket(zmq.REQ) for i in range(10)] for i, client in enumerate(clients): client.connect('inproc://foo') client.send_string('FOO%d' % i) messages = [] while server.poll(0): messages.append(ser...
#Push and Pop in stack stack = [] n=int(input("Enter number of elements:")) # append() function to push # element in the stack for i in range(0,n): ele=int(input()) stack.append(ele) print('Initial stack') print(stack) # pop() fucntion to pop # element from stack m=int(input("enter nu...
import requests import urllib from urllib.request import urlopen # test for internet connection def is_internet(): try: urlopen('https://www.google.com', timeout=3) return True except urllib.error.URLError as Error: return False # if internet...
# Generated by Django 2.0.4 on 2018-05-05 09:22 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('patient', '0001_initial'), ] operations = [ migrations.AlterField( model_name='patient', name='mname', f...
#!/usr/bin/env python import sys for fn in sys.argv[1:]: elems = fn.split("/") if len(elems)==1: continue newfn = elems[-1] print "writing", newfn, "..." lines = open(fn, 'r').readlines() newfp = open(newfn, 'w') for l in lines: if l[:6] == "TITLE=": title = l.strip() ...
from misc_utils import LRU if __name__ == '__main__': f = LRU(ord, maxsize=3) for c in 'ABCDCE': print('%s -> %s\t\t%r' % (c, f(c), f.cache)) print ("========= removing 'C' ") f.cache.pop(('C',), None) # invalidate 'C' print(f.cache) print ("========= Add 'C' bac ") f(...
def isSafe(x, y, initial, final): return 0 <= x < 3 and 0 <= y < 3 def printPath(l): for i in l: for j in i: print(j, end=" ") print() print() def isEqual(intial, final): for i in range(3): for j in range(3): if intial[i][j] != final[i][j]: ...
import sys def minstepto1(n, dp): if n == 1: return 0 div2 = sys.maxsize if n % 2 == 0: num2 = n//2 if dp[num2] != -1: div2 = dp[num2] else: div2 = minstepto1(n//2, dp) dp[num2] = div2 div3 = sys.maxsize if n % 3 == 0: nu...
from onegov.fsi.models.course_attendee import CourseAttendee from onegov.fsi.models.course_event import CourseEvent from onegov.fsi.models.course_subscription import CourseSubscription def test_db_mock_function_session(session, db_mock_session): session = db_mock_session(session) assert session.query(CourseA...
from flask import Flask, render_template, redirect, url_for, request app = Flask(__name__) @app.route('/XSS') def XSS(): if request.method == 'GET': return render_template("myForm.html") else: return "Hello there!" if __name__ == "__main__": app.run(debug=False)
N, X = map( int, input().split())
# -*- coding: utf-8 -*- """ Created on Wed May 29 13:41:26 2019 @author: Nate """ import pandas as pd import quandl import pickle import matplotlib.pyplot as plt from matplotlib import style style.use('ggplot') api_key=open("api_key.txt", "r").read() def state_list(): fifty_states = pd.read_html('https://simple...
my_name = 'ilya pasichnyk' unknown_name = str(input('|Input your name to access locked data|\n:')) if my_name == unknown_name.lower(): print('|Access Granted!|\n|Have a good day)|') else: print('|Access Denied|')
from pandas import merge, notnull import random import re import wrcX.core.data as d from wrcX.core.utils import strfdelta import inflect p = inflect.engine() def report_driverStageSectors(stagenum,carNo,ddf_sectors=None): if ddf_sectors is None: ddf_sectors=d.df_splitSectorTimes_all[stagenum-int(wrcX.c...
import jpegio as jio import scipy.stats import numpy as np def chi_attack(file_name: str) -> None: """ Реализует атаку хи-квадрат на JPEG файл. """ # Считываем ДКП коэффициенты dct = jio.read(file_name) # Выбираем синий канал, в который спрятано сообщение. # Здесь важно, что сообщение пре...
import json from django.db import models class Card(models.Model): number = models.CharField(max_length=20) name = models.CharField(max_length=50) image_name = models.CharField(max_length=70) @classmethod def transform_json(cls, card_json): cards = [] for card_data in card_json: ...
from lib.saga_service.filesystem_service import FilesystemService from lib.command.command_template import CommandTemplate import argparse class CatCommand(CommandTemplate): """ A Unix like, cat command for concatenating and printing files using SAGA as a backend. Result can be displayed to stdout or...
import csv f=open("input2.txt") total = 0 for row in csv.reader(f): length = (len(row)) print(row) while length > 0: total = total + int(row[length - 1]) print(total) length -= 1 print(total)
"""afrivent URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.2/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-base...
# 转移序列 \ tabby_cat = "\tI'm tabbed in." persian_cat = "I'm split\non a line." backslash_cat = "I'm \\ a \\ cat." fat_cat = """ I'll do a list: \t* Cat food \t* Fishies \t* Catnip\n\t* Grass """ print tabby_cat print persian_cat print backslash_cat print fat_cat # 转移序列 列表 # \\ 反斜杠 # \' 单引号 # \" 双引号 # \a 响铃符 # \b 退格符 ...
# coding: utf8 from django.shortcuts import render, redirect from consult_panel.models import * from django.contrib import messages from django.contrib.auth.decorators import login_required, user_passes_test from admin_panel.user_tests import * from admin_panel.user_tests import * import time import json @user_pass...
""" Django settings for BusinessContact project. Generated by 'django-admin startproject' using Django 1.11.7. For more information on this file, see https://docs.djangoproject.com/en/1.11/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.11/ref/settings/ """ i...
import numpy as np import torch from config import config from net import Net import utils #============================== class Brain: def __init__(self, pool): self.pool = pool self.model = Net() self.model_ = Net() self.epsilon = config.PI_EPSILON_START self.lr = con...
# Imports import sys import rospy from PyQt4 import QtCore, QtGui, uic from PyQt4.QtCore import QObject, pyqtSignal from threading import Thread from geometry_msgs.msg import Point from sensor_msgs.msg import Image from cv_bridge import CvBridge, CvBridgeError import cv2 from random import randint # Load GUI formClass...
import csv import os import pandas as pd #Creates a CSV file in the same folder where the experiment is being carried out train_path = "/Users/megh/Work/github-repos/data/cifar-10-batches-py/cifar/train/" label_list = ['airplane','automobile','bird','cat','deer','dog','frog','horse','ship','truck'] f1 = open('train.cs...
#!/usr/bin/python # # Copyright © 2020 Bell Canada. # # 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 ...
# Found this in a python book my wife is using. from datetime import datetime # The following line hurts my feelings - a lot. odds = [ 1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41, 43, 45, 47, 49, 51, 53, 55, 57, 59 ] right_this_minute = datetime.today().minute if right_this_minut...
def sumall(*args):# this is passed if we dont know hw many argumenst are passed sum=0 for i in args: sum=sum+i return sum print(sumall(1,2,3,3,4,4,4,5,5,6,6,6,78,8,8,8,9,9,0))
import numpy try: import scipy.sparse scipy_available = True except ImportError: scipy_available = False import cupy from cupy import core from cupy._creation import basic from cupy import cusparse from cupyx.scipy.sparse import base from cupyx.scipy.sparse import data as sparse_data from cupyx.scipy.spars...
from flask import Flask, request, render_template,jsonify import pickle import sys import logging app = Flask(__name__) app.logger.addHandler(logging.StreamHandler(sys.stdout)) app.logger.setLevel(logging.ERROR) def do_something(text1): loaded_model = pickle.load(open('finalized_model1.pkl', 'rb')) cv = pickl...
import falcon from app.utils.testing import AuthenticatedAPITestCase DECK_COLLECTION_ROUTE = '/deck' VALID_DATA = { 'count': 1 } INVALID_DATA = { 'count': 'abc' } class DeckCollectionTestCase(AuthenticatedAPITestCase): def test_create_a_deck(self): body = self.simulate_post(DECK_COLLECTION_RO...
import math def get_phi_value(): return (5 ** (1/2) + 1) / 2 def get_function(x): return (x + x ** 2) ** (1/2) + 1 / (1 + x ** 2) def golden_ratio_method(a, b, eps): if a == 0 or b == 0: return -1 else: while math.fabs(b - a) > eps: t = (b - a) / get_phi_value() ...
##### Farhad Ramezanghorbani 20131758 HW#7 class Cell: "Single cell in a matrix" def __init__( self, data ): "Cell constructor" self.data = data self.nextCell = None #self.index = index def getData( self ): "Get cell data" return self.data def setData( self, data ): "Set cell data" ...
from os import getenv import tweepy from setup_db import KVStorage class Twitor: def __init__(self): self.twid = 0 self.tw_url = "https://twitter.com/twitter/statuses/" # Auth auth = tweepy.OAuthHandler( getenv("TWITOR_API_KEY"), getenv("TWITOR_API_KEY_S") ...
usuarios = 0 Pessoas12e21 = 0 Altura12e21 = 0 Mais70 = 0 Mais90 = 0 AcumulaPeso = 0 AcumulaIdade = 0 AcumulaAltura = 0 for usuario in range(1, 11): idade = int(input("Por favor, digite a idade: ")) altura = float(input("Por favor, digite a altura em m: ")) peso = float(input("Por favor, digite o peso: ")...
from django import forms from . models import TeachingStaff, NonTeachingStaff, NonTeachingWork, NonTeachingWorker from django_countries.widgets import CountrySelectWidget class TeachingStaffForm(forms.ModelForm): class Meta: model = TeachingStaff fields = ['first_name', 'last_name', 'gender', 'dob...
from math import sqrt A = int(input("n1: ")) B = int(input("n2: ")) C = int(input("n3: ")) Del = (B**2)-(4*A*C) if Del > 0: R1 = (-B+sqrt(Del))/2*A R2 = (-B-sqrt(Del))/2*A print("As raizes da esqueção são: ", R1, R2) else: print("Não existe raiz Raiz de Delta negativo, por isso, não existe Raiz da equ...
from rest_framework import status from rest_framework.decorators import api_view from rest_framework.response import Response from django.http import HttpResponse from django.views.generic import View from django.conf import settings import tweepy as tweepy import re import random import sys from collections import de...
# Generated by Django 2.1 on 2019-01-08 14:44 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('order', '0002_auto_20181206_1410'), ] operations = [ migrations.AlterField( model_name='ordergood...
from selenium.webdriver.common.by import By from Paragraphs.Paragraph import Paragraph from magic_box.find_elements import find_element from magic_box.scrolling import scroll_to from selenium.webdriver import ActionChains from Pages.MediaBrowser import MediaBrowser import pytest class EmployeesParagraph(Paragraph): ...
"""This module sets up the main game and event loop.""" import pygame from pygame.sprite import Group from settings import Settings from ship import Ship import game_functions as gf def run_game(): """Set up the game objects and event loop.""" # Initialize game and create a screen object. pygame.init() ...
import sys import pygame def check_keydown_events(event, rocket): """Respond to keypresses""" if event.key == pygame.K_RIGHT: rocket.moving_right = True elif event.key == pygame.K_LEFT: rocket.moving_left = True elif event.key == pygame.K_UP: rocket.moving_up = True elif ev...
#coding: utf-8 from datetime import date import boundaries boundaries.register(u'Québec boroughs', domain=u'Québec, QC', last_updated=date(2013, 8, 20), name_func=boundaries.clean_attr('NOM'), id_func=boundaries.attr('CODE'), authority=u'Ville de Québec', source_url='http://donnees.ville.quebe...
import tqdm import argparse import sys sys.path.append("..") from utils.config import Config from torch.autograd import Variable import torch from model.DADA import DADA from model.Logger import Logger from tensorboardX import SummaryWriter import numpy class INVScheduler(object): def __init__(sel...
# Greatest product of two numbers A = list(map(int, input().split())) if len(A) == 2: print(*A) Max1 = A[0] Min1 = A[0] for i in range(1, len(A)): if A[i] > Max1: Max1 = A[i] if A[i] < Min1: Min1 = A[i] A.remove(Max1) A.remove(Min1) Max2 = A[0] Min2 = A[0] for i in range(1, len(A)): ...
# coding=utf-8 import csv import datetime target_stock = "Y9999 加權指數" #記得改結尾輸出的檔名 raw = open('D:\\譚\\大數據與商業分析\\期中報告\\大盤指數.csv','r',encoding = 'ANSI') #大盤指數 # raw16 = open('D:\\譚\\大數據與商業分析\\期中報告\\2016_stock_data.csv','r',encoding = 'ANSI') #個股 # raw17 = open('D:\\譚\\大數據與商業分析\\期中報告\\2017_stock_data.csv','r',encoding =...
import numpy as np import cv2 import time raw_data = [] val1 = 0 val2 = 10000000 val3 = 100000000000000 count = 0 while(True): raw_data.append([val1,val2,val3]) val1 += 1 val2 += 1 val3 += 1 if len(raw_data) % 100 == 0: file_name = "temp_data/" + str(time.time()) + ".npy" np.save(...
""""" This is application """
from django.conf.urls import * urlpatterns = patterns('', url(r'^following/(?P<username>[\w-]+)/$', 'friends.views.follow_list', name="friends_following"), url(r'^feed/(?P<username>[\w-]+)/$', 'friends.views.feed', name="friends_feed"), )
from django.urls import path from estates.views import UserEstateListView, EstateCreateView app_name = 'estates' urlpatterns = [ path('predios/', UserEstateListView.as_view(), name='estate-list'), path('predio/crear/', EstateCreateView.as_view(), name='estate-create'), ]
# -*- coding: utf-8 -*- """ Created on Thu Aug 22 19:18:09 2019 @author: Joule """ import random as rn from Spiller import Spiller class Historiker(Spiller): """Må finne en matchende tidligere substring i en mutert kopi av enemy_choices listen""" def __init__(self, name, husk): supe...
from join import Join as join from joindocuments import joindocuments import pandas as pd from pandas import Series, DataFrame from oddratio import OddRatio as ratio from laplace import Laplacian_matrix from scipy.linalg import eigh as eigenvectors import nltk import numpy as np import numpy.matlib import arff from PC...
# main.py (FLASK APP FOR MNIST IMAGE RECOGNITION USING COLAB FILE) from keras.preprocessing.image import img_to_array from keras.models import load_model from flask_restplus import Api, Resource, fields from flask import Flask, request, jsonify import numpy as np from werkzeug.datastructures import FileStorage from PI...
class Solution(object): def __init__(self, head): self.head = head def getRandom(self): import random res, n, head = -1, 0, self.head while head: if random.randint(0, n) == 0: res = head.val head = head.next n += 1 retu...
#!/usr/bin/python3 """ Latin I with acute -> Cyrillic I with combining dot adove and combining acute """ strict = [ ["í", "и̇́"] ] soft = []
from typing import List class Solution: def twoCitySchedCost(self, costs: List[List[int]]) -> int: aCityCostSum = 0 bCityCostRefund = [] noOfInterviewer = len(costs) for i in range(noOfInterviewer): aCityCostSum += costs[i][0] bCityCostRefund.append(costs[i]...
# INTRODUCTION """ 1. torch Module: 提供各种对tensor的操作 2. tensor and torch.autograd Module: pytorch允许张量跟踪对其所执行的操作,并通过反向传播来计算输出相对于任何输入的导数。注意:此功能由张量自身提供。并通过torch.autograd模块进一步扩展完善。 3. torch.nn Moduel:是pytorch用于构建神经玩过的核心模块,该module提供了常见的神经网络层和其他架构组件。全连接层、激活函数、损失函数都在这个module。这些组件可用于构建和初始化一个还未经训练的模型。 4. torch.util.data Module: 能...
from .login import * from .logout import * from .signup import * from .login_required import * from .profile import *