text
stringlengths
8
6.05M
def add(): a=35 b=65 c=a+b print(c) add() def multiply(): d=2 e=2 f=d*e print(f) multiply() def divison(): x=26 y=2 z=x/y print(z) divison()
input = '109165-576723' pass_limits = list(map(lambda x: int(x), input.split('-'))) pass_range = range(pass_limits[0], pass_limits[1]+1) def is_valid(candidate): candidate = str(candidate) repeating_val = False for x in range(len(candidate)-1): if candidate[x] > candidate[x+1]: return ...
from django.contrib import admin from .models import Atom, Particle admin.site.register(Atom) admin.site.register(Particle)
#!/usr/bin/python # coding=utf-8 import urllib.request # 通过urllib.Request()方法构造一个请求对象 ''' Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8 Accept-Encoding: gzip, deflate, br Accept-Language: zh-CN,zh;q=0.9,en;q=0.8 Cache-Control: max-age=0 Connection: keep-alive Cookie: B...
""" In this problem, a tree is an undirected graph that is connected and has no cycles. You are given a graph that started as a tree with n nodes labeled from 1 to n, with one additional edge added. The added edge has two different vertices chosen from 1 to n, and was not an edge that already existed. The graph is rep...
def DNAtoRNA(dna): """ dna_to_rna == PEP8 (forced camelCase by CodeWars) """ return dna.replace('T', 'U')
from base import * import clsTestService import enums from selenium.webdriver.common.keys import Keys class EntryPage(Base): driver = None clsCommon = None def __init__(self, clsCommon, driver): self.driver = driver self.clsCommon = clsCommon #==============================...
import exceptions class ConversionError(exceptions.Exception): pass class Converter(object): def do_conversion(self, measure, timestamp): pass
#String Concatenation print ('I' + 'love' + 'Python') first = 'I' second = 'love' third = 'Python.' sentence = first + ' ' + second + ' ' + third + '.' #Reapating Strings print('-' * 10) happiness = 'happy' * 3 print(happiness) version = 3 print ('I love Python ' + str(version) + '.')
loop1 = 0 while loop1 < 1: print("\n******************* Python Calculator *******************") loop2 = 0 while loop2 < 1: print('\n') print('Adição - 1') print('Subtração - 2') print('Multiplicação - 3') print('Divisão - 4') print('\n') NumberAction =...
import pandas as pd import numpy as np import collections import matplotlib.pyplot as plt import seaborn as sns from sklearn.svm import SVC from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import balanced_accuracy_score, classification_report, confusion_matrix, accuracy_score from sklearn.model_...
import sys import json import MySQLdb u="rtluser" p="rtlpass" conn = MySQLdb.connect(host='localhost', user=u, passwd=p, db='rtlamr') conn.autocommit(True) db = conn.cursor() while 1: try: line = sys.stdin.readline() except KeyboardInterrupt: break if not line: break rec = ...
#!/usr/bin/env python # coding: utf-8 # # SONALI PATIL # # Task 1 - Prediction using Supervised ML (Level - Beginner) # # In[25]: # import all reuired libraries import numpy as np import pandas as pd import matplotlib.pyplot as plt get_ipython().run_line_magic('matplotlib', 'inline') # In[26]: # Reading the ...
from django import forms class LoginUsers(forms.Form): """Class for login of students, teachers...""" username = forms.CharField(label='Contrasena') password = forms.CharField(widget=forms.PasswordInput, min_length=8, label='Usuario') class AsesorLaboral(forms.Form): choices_calificacion = ( (1, '1'), (2, '2'...
# file létrehozva def teglalapKerulet(): a=float(input("Kérem a téglalap egyik oldalát[cm]:")) b=float(input("Kérem a téglalap másik oldalát[cm]:")) return float(2*(a+b)) def teglalapTerulet(): a=float(input("Kérem a téglalap egyik oldalát[cm]:")) b=float(input("Kérem a téglalap másik oldalát[cm]:")) return fl...
#! /usr/bin/python import cgi import cgitb cgitb.enable () form = cgi.FieldStorage () def fib (n): if n <= 1: return 1 else: return fib (n-1) + fib (n-2) print "Content-Type: text/html" print print """ <HTML> <HEAD> <TITLE>Python fibonacci</TITLE> </HEAD> <BODY> """ if "num" not i...
import unittest from value_objects import once from value_objects.util.testing import eq class OnceTestCase( unittest.TestCase ): def test_once_example( self ): ''' make sure properties decorated with @once are only computed once ''' class Person( object ): def __init__( s, age ): ...
"""basic ding-dong bot for the wechaty plugin""" from typing import Union from wechaty import Message, Contact, Room, FileBox from wechaty.plugin import WechatyPlugin class DingDongPlugin(WechatyPlugin): """basic ding-dong plugin""" @property def name(self): """name of the plugin""" retur...
from datetime import time lista_horarios = [time(x, y) for x in range(0, 24) for y in range(0, 60, 5)] HORA = tuple([(x, x.isoformat()) for x in lista_horarios]) DEVOLUCION = ( ("Lleno", "Lleno"), ("Mitad", "Mitad"), ("Vacio", "Vacio"), )
import numpy as np import matplotlib.pyplot as plt def distance(x1, y1, x2, y2): return (x2 - x1) ** 2 + (y2 - y1) ** 2 class Node(object): def __init__(self, i): self.index = i self.left = None self.right = None self.up = None self.down = None class Graph(object): ...
from PIL import Image import json def conv(img): pix = img.load() rdata = [] gdata = [] for y in range(16): rvalue = 0 gvalue = 0 for x in range(32): rvalue <<= 1 gvalue <<= 1 r,g,b = pix[x,y] if r: rvalue |= 0x01...
""" Faça um programa que receba um número e retorne o fatorial dele. O fatorial de um número qualquer n é: n*(n-1)*(n-2)*(n-3)*....*1. Exemplo: Entrada Saída 2 2*1 2 3 3*2*1 6 9 362880 """ #Solução num=int(input()) fact=1 fo...
#!/usr/bin/env python # -*- coding: UTF-8 -*- """ * UMSE Antivirus Agent Example * Author: David Alvarez Perez <dalvarezperez87[at]gmail[dot]com> * Module: Intelligence Console client * Description: This module implements Intelligence Console communication * * Copyright (c) 2019-2020. The UMSE Authors. All Rights...
from lists.linked.linked_list import Node from lists.linked.linked_list import LinkedList import math from trees.heap import * #Sample Graph: http://techieme.in/breadth-first-traversal/ class Vertex: sort_prop = 'val' def __init__(self, val, edges = None, weights = None): self.val = val ...
# Generated by Django 3.2 on 2021-05-13 13:24 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('listy', '0001_initial'), migrations.swappable_dependency(settings...
#ISBNから書名、著者、出版時期を取得するモジュール InputISBN = input() if len(InputISBN) == 13: ISBN_13 = InputISBN print(ISBN_13) elif len(InputISBN) == 10: print("WIP") # WIP 978 を追加して10->13変換するやつ #DigitISBN = len(InputISBN) - 1 #for i in range(DigitISBN // 2): #sum_even = sum(int(InputISBN[2 * i + 1 ]...
from open_pension_crawler.OpenPensionCrawlSpiderBase import OpenPensionCrawlSpiderBase class PsagotSpider(OpenPensionCrawlSpiderBase): name = 'psagot' allowed_domains = ['psagot.co.il'] start_urls = ['https://www.psagot.co.il/heb/PensionSavings/GeneralInformation/Pages/gemelcompanyreports.aspx'] regex...
import json dict1 = {'name': 'zengwenhai', 'age': 29} json.dump(dict1, open('name.json', 'w')) temp = open(r'C:\Users\Administrator\PycharmProjects\untitled1\day01\name.json', 'r', encoding='UTF-8') print(temp)
import RPi.GPIO as GPIO import time import network SWITCH = 21 GPIO.setmode(GPIO.BCM) GPIO.setup(SWITCH, GPIO.IN) def heard(phrase): print ("heard:" + phrase) for a in phrase: if a == "\r" or a == "\n": pass # strip it else: if (GPIO.input(SWITCH)): netw...
#!/usr/bin/env python from setuptools import setup, find_packages setup(name='pyfedid', version='1.0.0', plateformes='UNIX', description='Package for Decathlon FEDID', packages=find_packages(), packages_dir={'': 'pyfedid'}, author='Sylvain Lemoine', author_email='sylvain.lem...
from flask import request from flask import Flask import flask import hashlib from libs.thumbnail import * from libs.fs import FS from flask import request, Blueprint from libs.util import make_response from .authorization import require_auth import logging app = Blueprint('image', __name__) def image_ext(content_ty...
import re import utils import Dataset import torch import torch.utils.data import torchvision from engine import train_one_epoch, evaluate from torch.utils.tensorboard import SummaryWriter from torchvision.models.detection.faster_rcnn import FastRCNNPredictor # replace the classifier with a new one, that has # num_cla...
# -*- coding: utf-8 -*- # # Copyright 2015, 2016 Ramil Nugmanov <stsouko@live.ru> # This file is part of PREDICTOR. # # PREDICTOR is free software; you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation; either version 3 of the ...
#print("hello") def check(a): ln = len(a) pindex=0 #print(a[::-1]) for i in range(len(a)): for j in range(len(a)): if i<j: #print(a[i:j+1]) front = a[i:j+1] #print(a[j:i-1:-1]) if i+1==j or i-1<=0: if...
import matplotlib.pyplot as plt import numpy as np import uncertainties.unumpy as unp from scipy.optimize import curve_fit from scipy import stats from uncertainties import ufloat #Monozelle n1, U1 , I1 = np.genfromtxt('data/klemmspann_belastungsstrom.txt', unpack='True')#U in V, I in mA I1 = I1*10**(-3) def f1(m,x...
from collections import deque from abc import ABC, abstractmethod class Scheduler(ABC): """ Describes a scheduling algorithm and keeps track of the statistics concerned for evaluation. """ msg_warn = 'Scheduler internal state not fresh - are you sure you \ performed a reset?' def __in...
#!/usr/bin/python2 from copy import copy import math import rospy import baxter_interface import actionlib import sys from baxter_interface import CHECK_VERSION from baxter_interface import Gripper, Limb from geometry_msgs.msg import PoseStamped, Pose, Point, Quaternion from sensor_msgs.msg import JointState from s...
from logger import Logger from flask import Flask, render_template, request, make_response, Response, jsonify import datetime import json import os import shutil logger = Logger().get_logger() app = Flask(__name__) @app.route("/") def index(): return render_template('index.html') @app.route("/re...
#!/usr/bin/python import math def prime_factors(n): try: assert n > 1 except AssertionError: print 'Enter an integer > 1' return factors = [] factor = 2 limit = int(n / 2); while(factor <= limit): if(n % factor == 0): factors.append(factor) ...
# Copyright (c) 2020 Adam Souzis # SPDX-License-Identifier: MIT import six import collections import re import os from .support import Status, Defaults, ResourceChanges, Priority from .result import serializeValue, ChangeAware, Results, ResultsMap from .util import ( registerClass, lookupClass, loadModule, ...
# Copyright (c) 2017-2023 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved. # SPDX-License-Identifier: Apache-2.0 from __future__ import annotations from dazl.testing import SandboxLauncher, connect_with_new_party import pytest from .dars import DottedFields @pytest.mark.asyncio @pytest....
def treColorazione(grafo): '''Restituisce un 3-colorazione di un grafo se esiste, altrimenti una lista vuota.''' def genera(sol, nodo): # Se l'ultimo nodo è colorato si è trovata una colorazione completa. if nodo == len(grafo): # foglia return True else: # nodo interno ...
from django.apps import AppConfig class FlightDelayPredictionConfig(AppConfig): name = 'flight_delay_prediction'
from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('decades/', views.decade_list, name='decade_list'), path('fads/', views.fad_list, name='fad_list'), path('fads/new', views.fad_create, name='fad_create'), path('decades/new', views.decade_crea...
# -*- coding: utf-8 -*- # @Time : 2019-12-27 # @Author : mizxc # @Email : xiangxianjiao@163.com import os from flask import current_app, request, flash, render_template, redirect, url_for from flask_login import login_required, current_user from . import bpAdmin from project.common.dataPreprocess import strLengt...
# -*- coding: utf_8 -*- from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import cv2 import argparse import pickle import nsml import numpy as np from nsml import DATASET_PATH import keras from keras.models import Sequential, Model from keras.laye...
import numpy as np import cv2 import tensorflow as tf from tensorflow.keras import backend as K ''' Loading the Classifier Model from the disk ''' with open('classifier_model.json', 'r') as json_file: json_savedModel = json_file.read() # load the model architecture model = tf.keras.models.model_from_j...
from gtts import gTTS from tempfile import TemporaryFile import base64 class Tts: def __init__(self, s, lang): self.tts = gTTS(s, lang) def to_bytes(self): temp = TemporaryFile() self.tts.write_to_fp(temp) temp.seek(0) return temp.read() def to_base64(self): ...
# coding: utf-8 import os, zipfile import numpy as np from PIL import Image def crop_center(img, crop_size=128): """ This function can crop center of image. If image size is smaller than crop_size, image will be padded "0". """ if type(img) is np.ndarray: img = Image.fromarray(np.uint8(...
""" Collection of utilities for basic statistical distribution transformations. """ import numpy as np from scipy.special import erfinv from pyDOE import lhs from scipy.stats.distributions import norm, uniform def design_lhs_exp(variables, maps, offsets=None, samples=int(1e4), project_linear=True...
__all__ = [ 'ResetIssueActivity', ] from gim.core.tasks.issue import IssueJob class ResetIssueActivity(IssueJob): queue_name = 'reset-issue-activity' def run(self, queue): super(ResetIssueActivity, self).run(queue) try: self.object.activity.update() except self.model...
from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse from ckeditor.fields import RichTextField class Post(models.Model): title = models.CharField(max_length=100) image = models.ImageField(null=True,blank=True,upload_to='MedBa...
import sqlite3 from sqlite3 import Error def create_connection(db_file): conn = None try: conn = sqlite3.connect(db_file) except Error as e: print(e) return conn ,conn.cursor() def create_table(conn,cursor): command = """CREATE TABLE IF NOT EXISTS accounts ( id integer PRIMAR...
# -*- coding: utf-8 -*- from django.shortcuts import render_to_response from django.http import HttpResponse from django.views.generic import View from models import * from cart import Cart import json from django.template import RequestContext from robokassa.forms import RobokassaForm from django.core.paginator import...
import signal import subprocess import os import time class StateManager: APP_DOWNLOAD_NAME = "temp-led-matrix-app/" def __init__(self, app_parent_directory: str): assert os.path.isdir(app_parent_directory), f"Parent direcory {app_parent_directory} doesn't exist" self._app_directory = os...
## BAGGING CLASSIFICATION # Import models and utility functions from sklearn.ensemble import BaggingClassifier from sklearn.tree import DecisionTreeClassifier from sklearn.metrics import accuracy_score from sklearn.model_selection import train_test_split # Set seed for reproducibility SEED = 1 # Split data into 70% t...
import sys, string, math a,bg, = map(int,input().split()) for i in range(max(a,bg), a*bg+1) : if (i%a == 0) and (i%bg == 0) : ans = i break print(ans)
# Usage: $ python3 get_comment_ratio.py /home/kevin/Desktop/sac-data/stats output.csv # python3 get_comment_ratio.py <merged_files> <output_path> # # Merges all the extracted contribution per tag data into one single file. __author__ = 'kevin' import sys import csv import os # RQ 1: Generate a csv file for ...
#encoding:utf-8 from openpyxl import load_workbook import os base_dir=os.path.dirname(os.path.dirname(__file__)) data_path=os.path.join(base_dir,'data/ddt_data.xlsx') class Get_message: Cookie=None Api=load_workbook(data_path)['api'].cell(1,2).value TsestApi=load_workbook(data_path)['api'].cell(2,2).value ...
from karel.stanfordkarel import * """ File: ExtensionKarel.py ----------------------- This file is for optional extension programs. """ """ An part of the extension, I made a program that allows karel to draw a STAR shape in any square world """ from karel.stanfordkarel import * # pre: karel is facing east ready to...
# Bài 05: Viết hàm # def count_upper_lower(str) # trả lại số lượng chữ cái viết hoa, số lượng chữ cái viết thường trong chuỗi str s = input('Nhap chuoi: ') def count_upper_lower(a) : count_upper = 0 count_lower = 0 for i in s : if 'A'<= i <='Z' : count_upper +=1 if 'a...
# coding: utf-8 #!/usr/bin/python # THIS SCRIPT # 1. LISTS ALL OF YOUR HOST NAMES FOR A SPECIFIC ACCOUNT_KEY # 2. ALLOWS YOU TO SELECT A SPECIFIC HOST IN WHICH TO CREATE A NEW LOG # 3. IT THEN PROMPTS YOU FOR A NEW LOG NAME # 4. IT CREATES A LOG NAME UNDER YOUR SELECTED HOST # REQUIREMENT - you must have your Loge...
import math import yfinance as yf import matplotlib.pyplot as plt class Index: def __init__(self, index_ticker, date1, date2): #variables self.index_ticker = index_ticker self.start_date = date1 self.end_date = date2 self.ticker_data = yf.Ticker(index_ticker) #ge...
# -*- coding: utf-8 -*- ''' Crea un alumno en la base de datos. PYTHONPATH="../../../python" python3 createStudent.py dni name lastname legajo ''' from model.connection import connection from model.users import users from model.registry import Registry import systems import logging def createStudent(con, dni...
''' The training time is too long with >=100 lines of poem. Also, it gives low accuracy. Maybe HMM is not suitable for classification when the number of symbols is too large. ''' import sys from multiprocessing import Process import numpy as np from google.colab import drive from sklearn.utils import shuffle from src...
# Copyright 2021 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). import textwrap import pytest from pants.backend.java.compile.javac import rules as javac_rules from pants.backend.java.dependency_inference import symbol_mapper as java_symbol_mapper fro...
# Copyright 2019, The TensorFlow 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 ...
import importlib import pkgutil import aurora.drivers def iter_namespace(ns_pkg): # Specifying the second argument (prefix) to iter_modules makes the # returned name an absolute name instead of a relative one. This allows # import_module to work without having to do additional modification to # the ...
#! /usr/bin/env python #-*- coding: utf-8 -*- import socket host='0.0.0.0' port=50015 s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) s.connect((host, port)) while 1: cmd = raw_input("Please input cmd:") s.sendall(cmd) data = s.recv(1024) print data s.close()
# coding=utf-8 import sys from ualfred import Workflow3, notify log = None def main(wf): import pickle from workflow import web args = wf.args query = pickle.loads(str(args[0])) log.debug('test') url = 'https://api.caiyunapp.com/v2/' + wf.get_password('apiKey') + '/' + query[4] + ',' + query[5] + '/' if quer...
# How many numbers below 10,000 are Lychrel, i.e. do not collapse into palindromes by adding them with their reverses after 50 iterations? # ==================================================================================== # This is nice for thinking about palindromes: def compute(): ans = sum(1 for i in range(10...
def trailingZeroesInFact(num): count = 0 i = 5 while(num//i>0): count = count + num//i i = i*5 return count num = 100 print(trailingZeroesInFact(num))
# print("나는 %d 살입니다." % 24) # print("나는 %s 이고 %d 살입니다" %("홍길동", 24)) # print("나는 {} 이고 {} 살입니다" .format("홍길동", 24)) # print("나는 {1} 이고 {0} 살입니다" .format("홍길동", 24)) #print("나는 {name} 이고 {age} 살입니다" .format(name = "홍길동", age = 24)) text = """ 오늘의 온도는 {0:>10}도 이고, 습도는 {1:<10}도 입니다. 내일의 온도는 {2:^10}도 이고, 습도는 {3:-^10}도...
f1,f2=[int(x) for x in raw_input().split(" ")] n=input() def fseq(i): if i==1: return f1 elif i==2: return f2 else: return fseq(i-1)-fseq(i-2) print (fseq(n)%1000000007)
from picamraw import PiRawBayer, PiCameraVersion from ..constants import RAW_BIT_DEPTH def as_rgb(raw_image_path): """ Extracts the raw bayer data from a JPEG+RAW file and converts it to an `RGB Image` (see definition in README). Args: raw_image_path: The full path to the JPEG+RAW file R...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __version__ = '1.0.1' import ujson from sanic.request import Request from sanic.log import logger from web_backend.config import SALT from web_backend.nvlserver.module.user.service import get_user_by_id from web_backend.nvlserver.module.permission.service import ( get...
class WordCounter(dict): def add(self, word): if word not in self: self[word]=1 else: self[word]+=1 return self[word] # return the new count def get(self, word): rc = 0 if word in self: rc = self[word]...
import os import glob from mpl_toolkits.basemap import Basemap import numpy as np import matplotlib.pyplot as plt import hdr_writer as hdr def draw_map(input_file, pft = False, fun = 'mean'): dt = hdr.catch_data(input_file, 12, 120, 160) mask = dt == -9999.0 dta = np.ma.masked_array(dt, mask) ...
#!/usr/bin/env python #coding:utf8 from . import analysis from analysis.analyse import AnalyseUtils from flask import render_template, request from models import NodeUtils, LinkUtils # 通过指定路由,返回渲染html页面 # 客户端的URL直接在链接里面 @analysis.route('/demo_force',methods=['GET','POST']) def demo_force(projectId): return rend...
#!/usr/bin/env python import subprocess import sys import argparse import glob import os def call_process(cmd): print("cmd: %s" % cmd) child = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = child.communicate() if child.returncode != 0: print("Failed: %s: %s" % (cmd,...
from __future__ import division from __future__ import print_function import sys import os import torch import numpy as np from torch.autograd import Variable from collections import OrderedDict import torch.nn as nn import torch.nn.functional as F import torchvision import torchvision.transforms as transforms import ...
import datetime fname = "test.py.log" print(f"Append a line to {fname}") with open(fname, "a") as file: file.write(str(datetime.datetime.now())) file.write("\n")
from django.test import override_settings from colossus.apps.campaigns.tests.factories import EmailFactory, LinkFactory from colossus.apps.lists.tests.factories import MailingListFactory from colossus.apps.subscribers.constants import ActivityTypes from colossus.apps.subscribers.models import Subscriber from colossus....
# -*- coding: utf-8 -*- print("hello") print("some basic of python") '''DATA TYPE Text Type: str Numeric Types: int, float, complex Sequence Types: list, tuple, range Mapping Type: dict Set Types: set, frozenset Boolean Type: bool Binary Types: bytes, bytearray, memoryview -----''' #-------------------------------...
import requests import csv from bs4 import BeautifulSoup from csv import writer import re def textFinder(href): return href and re.compile("/text").search(href) searchResults = requests.get('https://www.congress.gov/bill/116th-congress/senate-resolution/316?q=%7B%22search%22%3A%5B%22air+pollution%22%5D%7D&s=1...
import pandas as pd import re from datetime import date import os, glob pd.set_option('display.max_columns', None) pd.set_option('display.max_rows', None) today = date.today() root_directory = 'pandemicmap/data/rki_files' def load_df(): #file_list = os.listdir('pandemicmap/data/rki_files/') list_of_files =...
#!/usr/bin/python3 # -*- coding: utf-8 -*- # TODO: Implements IPv4 option list extractor. import collections import datetime # Internet Protocol version 4 # Analyser for IPv4 header from .ip import IP from ..utilities import Info, ProtoChain # TOS (DS Field) Precedence TOS_PRE = { '111': 'Network Control...
from django.shortcuts import render, redirect from django.views import View from .forms import UserForm from django.contrib.auth import logout def index(request): if request.user.is_authenticated: return redirect('account:index') return render(request, 'home/home.html') class UserFormView(View): ...
Root / folder ~ .cd - current directory .pwd - previous working directory (shows absolute path, from root directory to where you are now) .mkdir - make directory .ls - list . (dot) stands for current directory ..(dot dot) will list structure of the parent directory to make a file: touch These are common Git command...
from keras.datasets import mnist from keras import models from keras import layers from keras.utils import to_categorical # The Simplified Big Picture of How Most Supervised Networks Work # The Just of It # [1] Draw a batch of training samples x and corresponding targets y. # [2] Run the network on x (a step c...
import os import zipfile import pandas as pd import pytest from pandas.testing import assert_frame_equal from powersimdata.network.usa_tamu.constants.zones import abv2state from prereise.gather.demanddata.nrel_efs.get_efs_data import ( _check_electrification_scenarios_for_download, _check_path, _check_tec...
""" Tests for mimic identity (:mod:`mimic.model.identity` and :mod:`mimic.rest.auth_api`) """ from __future__ import absolute_import, division, unicode_literals import json from twisted.trial.unittest import SynchronousTestCase from twisted.internet.task import Clock from mimic.canned_responses.auth import ( ge...
# -*- coding: UTF-8 -*- ''' @author: leochechen @summary: ctf framework运行过程中会出现的异常 ''' class FrameworkException(RuntimeError): ''' 框架异常 ''' pass class CTFRuntimeException(Exception): ''' CTF流程运行时会出现的异常 ''' pass class VarAbort(CTFRuntimeException): ''' 用例运行异常 ''' pas...
# building a translator from translate import Translator translator = Translator(to_lang="ja") text = '' try: with open('translation_file.txt', 'r') as f: text = f.read() translation = translator.translate(text) print(translation) except FileNotFoundError as err: print("file Not foun...
import cv2 import numpy as np class PolarHeightFilter: @staticmethod def filterHeight(inputImage, threshold = 30): ''' filter the area whose height is less than the threshold ''' height = inputImage.shape[0] width = inputImage.shape[1] blackColor = np.zeros((1, ...
import time import numpy as np import matplotlib.pyplot as plt import os import pandas as pd import glob import re from pupil_parse.preprocess_utils import config as cf from pupil_parse.preprocess_utils import extract_session_metadata as md def main(): (raw_data_path, _, processed_data_path, figure_path, simul...
#Hash 就是把任意长度的输入,通过散列算法,变成固定长度的输出 #简单来说就是将任意长度的输入压缩到某一固定长度 #hash的值要求必须固定,hash值必须是不可变的 #所以列表是不可能被hash的 hash((1,2,3)) print(hash((1,2,3))) #hash([1,2,3])会出错
import math import torch from torch import nn from torch.nn import functional as F import numpy as np import neural_network as mm from neural_network import tf, tint from replay_buffer import ReplayBuffer from envs import AtariEnv from rainbow import DQN parser = argparse.ArgumentParser() parser.add_argument("--lea...
def accum(s): return '-'.join(str.title(a * i) for i, a in enumerate(s, 1))
# coding: utf-8 from sklearn.feature_extraction.text import TfidfVectorizer from nltk.tokenize import word_tokenize from nltk.stem import RSLPStemmer import string import numpy class LSA: def __init__(self, ngram_max, min_freq, p_eig, phrases): self.ngram_max = ngram_max self.min_freq = min_freq ...