text
stringlengths
38
1.54M
#source: http://dataaspirant.com/2017/02/01/decision-tree-algorithm-python-with-scikit-learn/ #source: http://scikit-learn.org/stable/modules/tree.html import numpy as np import pandas as pd from sklearn.cross_validation import train_test_split from sklearn.tree import DecisionTreeClassifier from sklearn.metrics impor...
# Generated by Django 3.1.7 on 2021-03-09 15:33 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='User', fields=[ ('password', models.CharFie...
from concurrent.futures import ThreadPoolExecutor import requests import re import json pids = ["IE20517548", "IE20521161", "IE20521681", "IE20507286", "IE20507394", "IE20507968", "IE20508777", "IE20508906", "IE20509400", "IE20509504", "IE20509955", "IE20511623", "IE20512082", "IE20513522", "IE20519139", "IE20519253",...
numAlunos = input ( "Digite o número de alunos : " ) numAlunos = int ( numAlunos ) contador = 1 while contador <= numAlunos: nota = input ( "Digite a nota do aluno " + str ( contador ) + ":" ) nota = float ( nota ) if nota < 5.0 : print ( "Aluno " , contador , " reprovado! " ) else: p...
import math print("--------------------------------") print("PASAR ALFA A RADIANES") print("--------------------------------") PI = 3.1416 print("Ingrese los lados de un triangulo:") B = float(input("Lado B:")) C = float(input("Lado C:")) print("Ingrese el ángulo en grados sexagesimales:") alfa = float...
class Mammal: def __init__(self, species): self.species = species def walk(self): print('walk ' + self.species) class Dog(Mammal): def __init__(self, breed): super().__init__('Dog') self.breed = breed def bark(self): print('bark ' + self.breed) def fetch(...
#!/usr/bin/python # -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function import os import cv2 import imgaug.augmenters as iaa import numpy as np from PIL import Image from torch.utils.data.dataset import Dataset IMG_EXTENSIONS = [ '.jpg', '.JPG', '.jpeg', '.JPEG', '.png', '....
import argparse import os import json import pickle import numpy as np import matplotlib.pyplot as plt import cv2 def show_csv(team, output, original): if output=="": output = team.split('.pkl')[0].split('pkl/')[-1] writelines_detection = dict() writelines_localization = dict() for vid in ra...
import numpy as np import dask.array as da from abc import ABC, abstractmethod from enum import Enum from sklearn.linear_model import Ridge as sk_estimator from dask_ml.linear_model import LinearRegression as dask_estimator # hard data MLNameSpace class MLNameSpace: X_list = ['DayOfWeek','Distance', 'ArrDelay','...
from datetime import datetime import io from pybenzinaparse import headers, utils from benzina.utils import mp4 def test_find_headers_at(): creation_time = utils.to_mp4_time(datetime(2019, 9, 15, 0, 0, 0)) modification_time = utils.to_mp4_time(datetime(2019, 9, 16, 0, 0, 0)) samples_sizes = [198297, 12...
from smb_types import * def add(*_args, _locals): if len(_args) != 2: raise Exception(f'Expected number of _args 2, given: {len(_args)}') if not all(arg._type in ['FLT', 'INT', 'VAR'] for arg in _args): raise Exception( f'Expected types are float, integers but got: {(a...
# The configuration file for dataset paths Dataset_Path = dict( TuSimple = "/home/ubuntu/Developer/TuSimple/LaneDetection" )
from __future__ import absolute_import import re import bisect import sys from graphite.tags.base import BaseTagDB, TaggedSeries class RedisTagDB(BaseTagDB): """ Stores tag information in a Redis database. Keys used are: .. code-block:: none series # Set of all paths ...
from bitcoin_tools.core.keys import serialize_pk, load_keys from bitcoin_tools.core.transaction import TX # BUILD TRANSACTIONS prev_tx_ids = ["f0315ffc38709d70ad5647e22048358dd3745f3ce3874223c80a7c92fab0c8ba", # P2PK "7767a9eb2c8adda3ffce86c06689007a903b6f7e78dbc049ef0dbaf9eeebe075", # P2PKH ...
#!/usr/bin/python #this is a addision program a = 10 b = 20 c = a + b print "the value of c is", c
# -*- coding: utf-8 -*- """ Created on Wed Jun 13 17:56:05 2018 @author: ignacio """ ############################################################################ # PACKAGES AND MODULES ##################################################### ############################################################################ #...
""" List all argkeys for human inspection. The purpose is to check every argkey and manually link proper documentations to them. """ import csv from itertools import imap from codemend.docstring_parse.elemdoc import ElemDoc from codemend import relative_path with open(relative_path( 'docstring_parse/doc_polish...
#%% import os import platform from copy import copy from pathlib import Path import joblib import lightgbm as lgb import matplotlib.pyplot as plt import numpy as np import optuna import pandas as pd import seaborn as sns import shap from matplotlib.ticker import PercentFormatter from optuna.integration import LightGB...
from typing import List def Linear_search(arr, x): list_index=[] for i in range(len(arr)): if arr[i] == x: list_index.append(i) return list_index def startswith(arr,x): list_index=[] for i in range(len(arr)): if arr[i].startswith(x): list_index.append(...
import random import math from typing import List class Bottle: def __init__(self, pill_weight): self.pill = pill_weight def populate_pills(bottle_num:int ) -> List[Bottle]: special_bottle = random.randint(0,bottle_num) print(f"Special bottle will be {special_bottle+1} (1 indexed)") return [Bo...
class Node: def __init__(self, key, value, prev=None, next=None): self.key = key self.value = value self.prev = prev self.next = next class LRUCache: def __init__(self, capacity: int): self.capacity = capacity self.caches = {} self.head = Node(-1, -1) ...
#encoding:utf8 import os import sys import matplotlib.pyplot as plt from pymc.Matplot import plot import json import time import P_model import numpy as np import math from pymc import MCMC import scipy.signal as signal import pdb from QTdata.loadQTdata import QTloader from dpi.DPI_QRS_Detector import DPI_QRS_Detector ...
import os from flask import request, redirect from flask import Flask from flask import render_template from werkzeug.utils import secure_filename from getPrediction import get_prediction app = Flask(__name__) app.config['UPLOADS'] = './static/' @app.route('/', methods=["GET", "POST"]) def upload_file(): if ...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def largestValues(self, root: TreeNode) -> List[int]: # level traversal& BFS # ans = [] ...
from angr.analyses.code_location import CodeLocation from .context import CtxRecord, CallString, ExecutionCtx from .vars import Var, Register, StackVar, MemoryLocation, memory_location, get_type_size_bytes import operator from functools import reduce import pyvex from pyvex import IRExpr, IRStmt import logging l = ...
class Queue: def __init__(self): self.balance = 0 print("welcome to banking") def enqueue_deposit(self): amount = float(input("enter the amount to deposit: ")) self.balance += amount print("\nAmount deposited: ", amount) def enqueue_withdraw(self): amount = float(input("ent...
# The Riddler Classic 2019-05-24: Flip for Mankind # https://fivethirtyeight.com/features/one-small-step-for-man-one-giant-coin-flip-for-mankind/ # Monte-Carlo simulation from random import random Nsim = 5000000 #number of simulations p = 0.24213 #probability of coin landing on heads #divisions of probability space...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Feb 2 07:45:39 2019 @author: William Keilsohn """ ''' What makes a name gender neutral? Personally, I think a name is gender neutral if: 1) The name is used/given by both boys and girls. 2) Each gender makes up at least 20% of the people with...
# tamaño de un archivo: import os print(os.listdir()) tam_bytes = os.path.getsize('contenido.txt') print(tam_bytes) bytes_ = tam_bytes // 10 f = open("contenido.txt", "r") i = 1 while True: texto = f.read(bytes_) if not texto: break nombre = "parte_" + str(i) + ".txt" f2 = open(nombre, "w") ...
import random import time import numpy as np from utils.treebank import StanfordSentiment random.seed(314) dataset = StanfordSentiment() tokens = dataset.tokens() nWords = len(tokens) dims = 10 C = 5 random.seed(31415) np.random.seed(9265) startTime = time.time()
import numpy as np from scipy.special import comb class Bezier: def __init__(self, points): self.controlPoints = points self.degree = len(points) self.culBernsteinMatrix() def culBernsteinMatrix(self): self.matBernstein = np.array(np.zeros((self.degree, self.degree))) ...
import os import zipfile def openZip(path): dirs = os.listdir(path) for dir in dirs: savepath = path + '\\' + dir.split('.')[0] os.mkdir(savepath) with zipfile.ZipFile(path + '\\' + dir, 'r') as z: z.extractall(savepath) os.remove(path + '\\' + dir)
import numpy as np import matplotlib.pyplot as plt from matplotlib_venn import venn3, venn3_circles from upsetplot import UpSet def single_cardinalities_bar(df_sc, title='Single class cardinalities (%).', save_file=None): ax = df_sc['cardinality'][1:].plot(kind='barh', figsize=(16, 8)) for p, perc in zip(ax....
contador = 0 while not contador>0: if contador >= 0: contador+=1 print(contador, end=',') while not contador>15: if contador >= 1: contador+=2 print(contador, end=',')
from sklearn import datasets def get_dataset(shuffle=True, random_state=None): """Load the Olivetti faces data-set from AT&T. https://scikit-learn.org/stable/modules/generated/sklearn.datasets.fetch_olivetti_faces.html Keyword Arguments: shuffle {bool} -- Shuffle the data or not (default: {True})...
from Python.LinearRegression.DataManipulation import * from Python.LinearRegression.RegressionDataModel import * from sklearn.linear_model import LinearRegression from Python.LinearRegression.PickleModel import * from sklearn.metrics import r2_score import matplotlib.pyplot as plot import pickle """ DataTrainer is Ch...
"""Analysis of distance (ANODI)""" # The MIT License (MIT) # Copyright (c) 2019-2022 Guillaume Rongier # # Author: Guillaume Rongier # # 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...
#! /usr/bin/env python # coding=utf-8 """ \n\n List random Culture ship names Usage: shipnames.py [-l | -s] [-a] [<amount>] Options: -h --help Show this screen -l Lowercase -s Slugify (spaces and punctuation become hyphens and lowercase) -a Show all in alphabetical or...
""" OOI Datateam Import Module - Data Stream Model Functions """ #import sqlite3 import csv import time #from .common import * def find(db,table,column_name,id): """Find an id in a table""" sql = '%s="%s"' % (column_name,id) result = db.select(table,sql,'id') if len(result) > 0: return result[0]['id'] el...
from django.shortcuts import render from payments import provider_factory from saleor.order.models import Payment # Create your views here. def direct_to_pay(request, token): """post to cash flow merchantdise with params needed - use token to get correspond payment model - all data needed are in payme...
#################### # # Super Awesome Program Deleter # by Michael Aboff # January 2012 # #################### # Define the server folder here. If left empty, or there is no internet access, the program will look in the directory it lives. Example: "http://www.example.com/superdeleterconfigs/" server = "" # Define t...
# coding=utf-8 # author: Xiguang Liu<g10guang@foxmail.com> # 2018-04-27 13:23 # 题目描述:https://www.nowcoder.com/practice/1a834e5e3e1a4b7ba251417554e07c00?tpId=13&tqId=11165&tPage=1&rp=1&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking class Solution: def Power(self, base, exponent): ...
import torch import torch.nn as nn from .SaliencyBase import Saliency class GuidedBackprop(Saliency): """ Produces gradients generated with guided back propagation from the given image """ def __init__(self, model): super(GuidedBackprop, self).__init__(model) self.forward_relu_output...
from math import comb def combination(n: int, r: int) -> int: y = 1 x = 1 for i in range(r): y *= n - i x *= i + 1 return y // x def permutation(n: int, r: int) -> int: x = 1 for i in range(r): x *= n - i return x print(combination(2, 1)) print(combination(8, 5))...
# -*- coding: utf-8 -*- import theano import theano.tensor as T import numpy as np from breze.arch.component.transfer import ( sigmoid, tanh, tanhplus, rectifier, softplus, logproduct_of_t) test_matrix = np.array([ [-2, 3.2, 4.5, -100.2], [1, -1, 2, 0]]).astype(theano.config.floatX) def t...
import socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) LOCAL_IP = socket.gethostbyname(socket.gethostname()) s.connect((LOCAL_IP, 9999)) while True: try: #TODO: work i progress.... rx = s.recv(1, 0x40) # 0x40 = MSG_DONTWAIT a.k.a. O_NONBLOCK print(rx.decode('utf8')) ...
# -*- coding: utf-8 -*- """ Created on Fri Jul 6 22:42:23 2018 @author: Luky """ ''' Implementation & Evaluation of Naive Bayes classifier. ''' from datetime import datetime import data import numpy as np # Import pyplot - plt.imshow is useful! import matplotlib.pyplot as plt def binarize_data(pixel_values): '...
import sys import webbrowser print "Script initialized" try: print "Script arguments: ",sys.argv except: print delays = [] def readBarcode(arg): if arg > 3: if arg < 50: delays.append(arg) if len(delays) == 4: print delays th = findGap(delays) bits = categorize(delays,...
# Generated by Django 2.0.2 on 2018-09-10 20:10 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='account', fields=[ ('id', models.AutoField(...
import datetime import pytest from application import create_customers, process_event_history from customer import Customer from contract import TermContract, MTMContract, PrepaidContract from phoneline import PhoneLine from filter import DurationFilter, CustomerFilter, ResetFilter """ This is a sample test...
from django.contrib import admin from overseas.home.models import News from overseas.home.models import User from overseas.home.models import Project from overseas.home.models import ProjectSource from overseas.home.models import Resource from overseas.home.models import RFP admin.site.register(News) admin....
from corpus_reader import CorpusReader from simple_feature_builder import SimpleFeatureBuilder import gensim import pandas as pd from pprint import pprint from nltk import word_tokenize from nltk import sent_tokenize import numpy as np import os import time import pickle from itertools import chain import ast import ...
import numpy as np import cv2 import glob import PIL.ExifTags import PIL.Image from tqdm import tqdm import os ################################################################### # CALIBRAÇÃO DA CAMERA A PARTIR DE IMAGENS DE TABULEIRO DE XADREZ # ################################################################### che...
from app import app from flask import request from flask import render_template from flask import redirect from flask import url_for from flask import make_response from flask import flash from flask import get_flashed_messages from flask.views import MethodView import re import datetime applications = { "argo"...
import datetime x = datetime.datetime.now() print(x) ## VARIABLES name = "Joan"; ## Case Sensitive Book = "Digital Fortress"; book = "Dr. Jekyll & Mr. Hyde"; # List Var Assignment index,_serie = 1, "Mr. Robot"; #nombre = "Johan"; print(book) print(index,_serie) print(name); ## CONVENTIONS book_name = "Fight Cl...
#!/usr/bin/env python ''' Pymodbus Synchronous Client Examples -------------------------------------------------------------------------- The following is an example of how to use the synchronous modbus client implementation from pymodbus. It should be noted that the client can also be used with the guard construct t...
from agents.AlphaBetaAgent.AlphaBetaAgent import AlphaBetaAgent from core.ConnextXBitboard import ConnectXBitboard from heuristics.BitboardGameoversHeuristic import bitboard_gameovers_heuristic class AlphaBetaBitboard(AlphaBetaAgent): game_class = ConnectXBitboard heuristic_class = None heuristic_fn ...
# -*- coding:utf-8 -*- ''' @author: chenzf ''' def lazy_sum(*args): def sum(): ax = 0 for n in args: ax = ax + n return ax return sum f= lazy_sum(1,3,5,7,9) print(f) print(f()) def count(): fs = [] for i in range(1, 4): def f(): return i*i ...
import gdb if 1: LX_CLK_GET_RATE_NOCACHE = gdb.parse_and_eval("((((1UL))) << (6))") LX_SB_RDONLY = 1 LX_SB_SYNCHRONOUS = 16 LX_SB_MANDLOCK = 64 LX_SB_DIRSYNC = 128 LX_SB_NOATIME = 1024 LX_SB_NODIRATIME = 2048 LX_hrtimer_resolution = gdb.parse_and_eval("hrtimer_resolution") LX_MNT_NOSUID = 0x01 LX_MNT_NODEV = 0x02 L...
import sqlite3 from sqlite3 import Error def insert_into_db(fname, lname, outdoor=1, indoor=1, manage=0, desired_hours=40): conn = sqlite3.connect(r'Schedulerdatabase.db') c = conn.cursor() sql = ''' INSERT INTO employee(fname, lname, outdoor, indoor, manage, hours) VALUES(?,?,?,?,?,?) '...
from kafka import KafkaConsumer from pymongo import MongoClient from json import loads import base64 import numpy as np import cv2 consumer = KafkaConsumer( 'video_2_particiones', bootstrap_servers=['localhost:9092', 'localhost:9093'], auto_offset_reset='latest', enable_auto_commit=True, #group_id=...
import sys import subprocess import shlex import getopt # This program accepts one optional command line argument # Uses subprocess.Popen() to connect to the Unix/Linux command "w" and one of the command line # arguments [-h, -u, -s, -f, -V], and prints the results from running them through Popen. def main(): ...
class Solution(object): def countAndSay(self, n): """ :type n: int :rtype: str """ return ''.join(self.nextSequence(n, ['1', 'E'])) def nextSequence(self, n, prevSeq): if n == 1: return prevSeq[:-1] nextSeq = [] prevDigit = prevSeq[0]...
import random import string def generate_short_url(size=6, chars=string.ascii_lowercase + string.digits): return ''.join(random.choice(chars) for _ in range(size)) def create_short_url(instance, size=6): short_url = generate_short_url() Class = instance.__class__ duplicate = Class.objects.filter(short_url=short...
''' Copyright (c) 2018 Doomhawk 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 restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, subli...
# -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function, unicode_literals from conda import __version__ as CONDA_VERSION from os.path import isfile def parse_conda_version_major_minor(string): return string and tuple(int(x) for x in (string.split('.') + [0, 0])[:2]) or (0, 0) C...
import tensorflow as tf n_input_nodes = 2 n_output_nodes = 1 x = tf.placeholder(tf.float32, (None, 2)) y = tf.placeholder(tf.float32, (None, 2)) W = tf.Variable(tf.random_normal((n_input_nodes, n_output_nodes))) b = tf.Variable(tf.zeros(n_output_nodes)) z = tf.matmul(x, W) + b out = tf.sigmoid(z) loss = tf.reduce_mean...
# 15. 3Sum # Given an integer array nums, return all the triplets # [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, # and nums[i] + nums[j] + nums[k] == 0. # Notice that the solution set must not contain duplicate triplets. # Example 1: # Input: nums = [-1,0,1,2,-1,-4] # Output: [[-1,-1,2],[-1,0,1]]...
s=input() r=[None]*len(s) for index,item in enumerate(s): if not index%2: r[index+1]=item else: r[index-1]=item print(r)
from django.contrib import admin from rematchrApp.models import Conference, Researcher, Reviewer class ResearcherInline(admin.TabularInline): model = Researcher class ReviewerInline(admin.TabularInline): model = Reviewer class ConferenceAdmin(admin.ModelAdmin): list_display = ('title', 'date') inlines = [Rese...
def fuel_from_mass(mass): fuel = int(mass/3) - 2 return fuel def fuel_from_fuelmass(mass): fuel = fuel_from_mass(mass) if fuel < 0: return 0 else: fuelmass = fuel_from_mass(mass) return fuel + fuel_from_fuelmass(fuelmass) # Part 1 inputs = [int(input.rstrip('\n')) for input...
import requests import Queue import codecs import re import uuid from threading import Thread requests.packages.urllib3.disable_warnings() def check(q): while True: user = q.get() work = False proxies = { 'http': '127.0.0.1:8888', 'https': '127.0.0.1:8888' ...
import sys import numpy as np import matplotlib.pyplot as plt import argparse temp = 340.0 parser = argparse.ArgumentParser(description="") parser.add_argument("-bias", type=str, help="bias value to analyse") parser.add_argument("-full", action='store_true', help="anaylse long unbiased trajectory?") parser.add_argume...
import cv2 def show_video(): # 비디오 재생 capture = cv2.VideoCapture('gizmo.mp4') # 동영상 파일 불러오기 while True: if capture.get(cv2.CAP_PROP_POS_FRAMES) == capture.get( cv2.CAP_PROP_FRAME_COUNT): # cv.CAP_PROP_POS_FRAMES 현재 프레임 수 cv.AP_PROP_FRAME_COUNT 총 프레임 수를 받아옴 capture.set(c...
#Modèle 1 (2 025 280) class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.epochs = 0 self.conv = nn.Sequential( nn.Conv2d(3, 16, 3, 1, 1), nn.ReLU(), nn.BatchNorm2d(16), nn.Conv2d(16, 64, 3, 1, 1), nn.ReLU(), nn.BatchNor...
import FWCore.ParameterSet.Config as cms # Use this object to modify parameters specifically for Run 2 #### PF CLUSTER HO #### #cleaning #seeding _localMaxSeeds_HO = cms.PSet( algoName = cms.string("LocalMaximumSeedFinder"), thresholdsByDetector = cms.VPSet( cms.PSet( detector = cms.string("HCAL_BARREL2...
__author__ = 'diegopinheiro' __email__ = 'diegompin@gmail.com' __github__ = 'https://github.com/diegompin' from mhs.src.dao.mhs.documents_mhs import HospitalDischargeDocument from mhs.src.dao.mhs.documents_mhs import NetworkHospitalDischargeDocument from mhs.src.dao.base_dao import BaseDAO import pandas as pd class ...
""" Write a program that accepts sequence of lines as input and prints the lines after making all characters in the sentence capitalised. Input Format: The first line of the input contains a number n which represents the number of line. From second line there are statements which has to be converted. Each statement co...
import logging import redis import json cache = redis.Redis(host='redis', port=6379) # def get_query_candidates(db, seperate_brand_categories = False): # if(seperate_brand_categories): # res = db.session.execute(""" # SELECT query, count(record.query) as amount, cat.name as category, brand.name as...
import numpy as np import scipy as sp import scipy.linalg as la import math import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from mpl_toolkits.mplot3d.axes3d import get_test_data import time from gurobipy import * from plate_layerwise import * from opt import * from comp_solver import * # te...
from . import (auth, configprovider, credentials, loaders, # noqa: F401 parsers, serialize, session) __version__ = '1.8.0'
#!/usr/bin/env python from pwn import * import time LOCAL = False Debug = False lib = ELF('./libc.so.6.64') if not LOCAL: r = remote('172.16.113.50', 12015) else: r = process('./safe') print r.proc.pid #a = raw_input('Wait gdb attach...\n') ''' CANARY : ENABLED FORTIFY : disabled NX ...
#!/usr/bin/env python3 # # 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 # ...
# -*- coding: utf-8 -*- """ Created on Sat Jul 11 21:24:06 2020 @author: MANAV """ import tkinter as tk from tkinter import * import webbrowser from tkinter import ttk from tkinter import font, colorchooser, filedialog, messagebox from tkinter import Toplevel from tkinter.filedialog import asksaveasfile from PIL imp...
"""Test on calculation with operations: addition, subtraction, division, multiplication, etc.""" import pytest from formula import Formula @pytest.mark.parametrize( "var1, var2, expected_result", [ ("0", "0", "0"), ("2", "2", "4"), ("2.0", "2.0", "4"), ("+0e+0", "-0e-0", "0")...
""" This module contains global constants. """ # file paths for mock data/response MOVIES_RESP_FILE = "tests/data/movie_response.txt" SHOWS_RESP_FILE = "tests/data/show_response.txt" SINGLE_SHOW_FILE = "tests/data/single_show.txt" EPISODES_RESP_FILE = "tests/data/episode_response.txt" SOURCES_RESP_FILE = "tests/data/s...
import datetime def get_today(): print(datetime.datetime.today())\ #全局变量;如果全局变量是一个字典或者list则不需要声明可以直接进行修改;只有str、int、和元组才需要声明(即不可变的类型都需要进行声明) name = 'wyh' #全局变量 def get_name(): # name = 'gaobo' #函数内部的局部变量 global name #声明要修改的变量,为全局变量name; name = 'gaobo' print(name) def get_name2(): print('get_na...
# https://atcoder.jp/contests/abc271/tasks/abc271_b # # def input(): return sys.stdin.readline().rstrip() # # input = sys.stdin.readline # from numba import njit # from functools import lru_cache import sys input = sys.stdin.buffer.readline # sys.setrecursionlimit(10 ** 7) N, Q = map(int, input().split()) A = [[int(i...
#!/usr/bin/env python import smtplib from email.mime.text import MIMEText USERNAME = "riccardo.ancona@gmail.com" PASSWORD = "supbtqkuszearsql" MAILTO = "riccardo.ancona@gmail.com" msg = MIMEText('Hello,\nMy name is ArduinoCrono, \n the water level is too low ') msg['Subject'] = 'Watering System - Water Level is too ...
import pytest from r8.cli.events import format_untrusted_col from r8.cli.events import min_distinguishable_column_width from r8.cli.events import wcswidth def test_format_untrusted_col_simple(): assert format_untrusted_col(None, 5) == "- " assert format_untrusted_col("x", 5) == "x " assert format_u...
# coding:utf8 from untitled2 import db class Food(db.Model): __tablename__ = 'food' id=db.Column(db.Integer,autoincrement=True,primary_key=True) food_name = db.Column(db.String(50)) food_link = db.Column(db.Text, nullable=True) food_pic = db.Column(db.Text, nullable=True) city = db.Column(db.S...
input_file = open('romeo-full.txt', mode='r', encoding='utf-8-sig') word_dictionary = {} for line in input_file: line = line.rstrip() line_without_punctuation = "" for char in line: if char.isalpha() == True and char.isspace()== False: line_without_punctuation += char line = line_w...
import numpy as np import matplotlib.pyplot as plt import copy from fconcrete.helpers import getAxis, make_dxf class TransvSteelBar(): def __init__(self, x, height, width, diameter, space_after, area, as_per_cm, anchor, length, cost): self.x = x self.height = height self.width = width ...
# Generated by Django 2.2.7 on 2020-05-17 06:20 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] ope...
from ROOT import TFile, TTree from array import array #import numpy as np class IsoOutputTree(): def __init__(self, _fName): self.outFile = TFile(_fName,'RECREATE') maxN = 10 self.nGen = array('i',[0]) self.genPt = array('f',maxN*[0.]) self.genEta = array('f',maxN*[0.]) ...
import date_to_ms import os import unittest class SimplisticTest(unittest.TestCase): def test_str(self): """A minimal test to ensure this use case executes successfully.""" self.assertEqual(0, os.system("python date_to_ms.py -s '01/12/2011'")) def test_timestamp(self): """A minimal test to ensure thi...
#!/usr/bin/python #from __future__ import division import logging import json import socket import sys import re, os from daemon import Daemon import fnmatch import time import hashlib import yara import itertools import threading from multiprocessing import cpu_count, Process from multiprocessing.dummy import Pool as ...
from bokeh.models import ColumnDataSource, TapTool, OpenURL from bokeh.layouts import column, layout from bokeh.models import LinearColorMapper from bokeh.models.widgets import Div from bokeh.models import Range1d from dashboard.bokeh.helper import get_palette from dashboard.bokeh.plots.descriptors.table import Table f...
"""makes all the branch diagrams in a folder""" """make a diagram of the components in a branch""" import os import glob import pydot import sys sys.path.append('../EPlusInputcode') from EPlusCode.EPlusInterfaceFunctions import readidf import loops import getopt help_message = ''' The help message goes here. ''' ...
#!/usr/bin/env python import sys import os import math from PIL import Image from StringIO import StringIO # you need to install this library yourself # recent versions handle bigtiff too... import tifffile """ Extract a pyramidal TIFF with JPEG tiled storage into a tree of separate JPEG files into DZI compliant dir...