text
stringlengths
8
6.05M
from typing import Optional, AsyncGenerator from urllib.parse import quote as encode_path_name_for_url from logging import getLogger import xmltodict from asgi_webdav.constants import ( DAV_METHODS, DAVPath, DAVLockInfo, DAVPropertyIdentity, DAVProperty, ) from asgi_webdav.response import DAVRespo...
# Author:ambiguoustexture # Date: 2020-02-02 str = "Hi He Lied Because Boron Could Not Oxidize Fluorine. New Nations Might Also Sign Peace Security Clause. Arthur King Can." str = str.split(" ") res = [] for word, index in zip(str, range(len(str))): if index+1 in (1, 5, 6, 7, 8, 9, 15, 16, 19): res.app...
#!/usr/bin/env python3 def merge_two_files(fname1: str, fname2: str) -> str: """Takes two files with ordered numbers (positive or negative), one number per line, merges these files int new one, preserving the order and returns the name of a new file""" def proc_file(file): while True: ...
# a questo punto abbiamo i dati in modo da costruire il grafo from twitter_data_retrieve.twitter_data_retriever import * def graph_from_data(source=SOURCE, verbose=True): tweets_map = {} people = get_dir_people() people.remove(SOURCE) base_path = os.path.join(os.pardir, DATA_DIRECTORY, PEOPLE_DIREC...
#coding:utf-8 from flask.ext.wtf import Form from wtforms import StringField, SubmitField, PasswordField, BooleanField from wtforms.validators import DataRequired, Email,EqualTo class UserSearchForm(Form): input = StringField(u'用户名:',validators=[DataRequired(message=u'用户名不能为空')]) submit = SubmitField(u'查找') ...
# -*- coding: utf-8 -*- """ Created on Thu Jun 7 20:18:28 2018 @author: user 字元次數計算 """ def compute(a,b): c=a.count(b) print("{:} occurs {:} time(s)".format(b,c)) a=input() b=input() compute(a,b)
# Author: ambiguoustexture # Date: 2020-03-11 import pickle import numpy as np from scipy import io def sim_cos(word_a, word_b): """ calculate the cosine similarity """ mul_ab = np.linalg.norm(word_a) * np.linalg.norm(word_b) if mul_ab == 0: return -1 else: return np.dot(word_...
dist = int(input("Informe a distânica em metros: ")) print(f"{dist}m = {dist*100}cm")
from string import ascii_lowercase with open('Day 5/data.dat', "r") as data: input_base = str(data.read()) min_length = len(input_base) for y in ascii_lowercase: input = input_base input = input.replace(f'{y}',"") input = input.replace(f'{y.upper()}',"") removed = True while removed...
"""Main assignment module.""" import csv import utils def get_must_dict(): """Read the csv and return the Orderdict.""" musts_file = open("Mobile Phone Masts.csv", "r") must_dict = csv.DictReader(musts_file) return must_dict def first_five_lowest_current_rent(): """Produce a list sorted by Curr...
""" Routes and views for the api application. """ from datetime import datetime from flask import render_template , jsonify from globalsuperstore import app import json import requests from globalsuperstore.pgsql import getStoreData @app.route('/table') def table(): """Renders the contact page.""" print("ren...
import os import dd import time import json import gmail import requests import traceback import sched, time from flask import Flask from flask_caching import Cache app = Flask(__name__) cache = Cache(config={'CACHE_TYPE': 'SimpleCache'}) cache.init_app(app) MINE_POOL=os.getenv("mine_pool_url") HIVE_EMAIL=os.getenv('...
calories = [6,13,8,7,10,1,12,11] n=len(calories) lower=5 upper=37 s=0 k=6 for i in range(0,n,k): count=0 for j in range(i,i+k): if j<n: count+=calories[j] print(count) if count<lower: s-=1 elif count>upper: s+=1 print(s)
__author__ = 'Shafikur Rahman' urlpatterns = []
""" Python I/O tools """ import numpy as np def print2D(data, fmt=None): """ Print 2D array (list) to stdout, used fmt ("{:d} {:f}"...) to specify format """ arr = np.asarray(data) for row in arr: if fmt is None: print(*row) else: print(fmt.format(*row)) ret...
import gspread import pandas as pd from google.oauth2.service_account import Credentials def get_data(sheet_name): SCOPES=['https://spreadsheets.google.com/feeds','https://www.googleapis.com/auth/drive'] credentials = Credentials.from_service_account_file('client_secret.json', scopes=SCOPES) client=gsprea...
#!/usr/bin/env python import pygame import mimo import random from utils import utils from utils import neopixelmatrix as graphics from utils.NeoSprite import NeoSprite, AnimatedNeoSprite, TextNeoSprite, SpriteFromFrames from utils.NewsProvider import news from utils import constants from scenes.BaseScene import Sce...
import numpy as np import pandas as pd import matplotlib.pyplot as plt import geopandas as gpd def uk_plot(shp_path, geo_code, df, var_name, title, cmap='coolwarm'): "Choropleth map of the given variable." print("\nGenerating plot...") map_df = gpd.read_file(shp_path) merged = map_df.merge(df[var_na...
from django.apps import AppConfig class BlackAppsConfig(AppConfig): name = 'black_apps'
# # (C) 2013 Varun Mittal <varunmittal91@gmail.com> # JARVIS program is distributed under the terms of the GNU General Public License v3 # # This file is part of JARVIS. # # JARVIS is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public Licens...
import os import threadpool from datetime import time from html_dloader import HtmlDLoader from html_outputer import HtmlOutputer from html_parser import HtmlParser from url_manager import UrlManager class GrabMain(object): def __init__(self, url): self.root_url = url self.urlManager = UrlManage...
# -*- coding: utf-8 -*- # Generated by Django 1.11.3 on 2017-09-04 00:11 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('api_', '0005_auto_20170830_2101'), ] operations = [ migrations.RemoveField(...
import requests import sys from jsonConvert import jsonConvert def getPage(date): """Récupère la page de l'ordre du jour du Sénat à la date donnée Args: date (string): date format: 'jjmmaaaa' Returns: [requests.Response]: réponse à la requête avec l'URL (contenu html: requests.get(url).co...
from django.shortcuts import render from .models import login_data import jwt import random from django.views.decorators.csrf import csrf_exempt from django import forms from django.contrib.auth.models import User from django.contrib.auth.decorators import login_required from django.http import HttpResponse,HttpRespon...
"""Generator stuff""" import os import sys from flask import Blueprint, jsonify from flaskbox import constants from flaskbox.config import config from flaskbox.fake_data import fake_data from flaskbox.helpers import create_init_file class YAMLGenerator: """Generator class for the flaskbox stuff Method...
'''Kevin and Stuart want to play the 'The Minion Game'. Game Rules Both players are given the same string, . Both players have to make substrings using the letters of the string . Stuart has to make words starting with consonants. Kevin has to make words starting with vowels. The game ends when both players have mad...
a=int(input("Enter the first number:")) b=int(input("Enter the second number:")) print("Before swapping") print("The value of a is ",a) print("The value of b is ",b) temp=a a=b b=temp print("After swapping") print("The value of a is ",a) print("The value of b is ",b)
# Generated by Django 2.1.2 on 2018-11-19 18:57 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('ann', '0002_auto_20181114_1654'), ] operations = [ migrations.CreateModel( ...
import ccobra import pandas import pykmeans import numpy import math import principleextractor import collections class SyllogisticKMeans: """ Class to model a syllogistic kmean solver using a category hamming distance Input: Syllogistic Data (see e.g. Ragni2016), number of clusters to form (k) Output...
import random import secrets import time from datetime import datetime, timedelta from pathlib import Path from unittest.mock import ANY from uuid import UUID import pytest from _test_mockups import get_fake_authdevice, random_bool from wacryptolib.authenticator import initialize_authenticator from wacryptolib.except...
import utils import json from umls_api.Authentication import Authentication import requests import json class UMLSAPI(object): api_url = "https://uts-ws.nlm.nih.gov/rest" def __init__(self, api_key): self._tgt = None self._api_key = api_key self._auth = Authentication(api_key) @p...
# coding:utf-8 from __future__ import absolute_import, unicode_literals __author__ = "golden" __date__ = '2018/6/26' from .spider import SpiderManager from .process import Multiprocessing
import nltk from nltk.corpus import wordnet import spacy # lst_events = ['appears_static_object', 'vehicle_1_comes_near', 'vehicle_1_moves_far', 'vehicle_2_comes_near', # 'vehicle_2_moves_far', 'vehicle_3_comes_near', 'vehicle_3_moves_far'] # # for adv_pr in lst_events: # adv_pr_str = nltk.word_token...
import unittest from datetime import datetime from flask import current_app from app import create_app, db from app.models import Company, Executive, Compensation, NonEquityPayment class ExecutiveModelTestCase(unittest.TestCase): def setUp(self): self.app = create_app('testing') self.app_context =...
import numpy as np def generate_data(num_point, cluster_center): dat_x = np.random.randn(num_point, 2) cluster = np.array(cluster_center) return (dat_x+cluster_center) def construct_cluster(num_points, clusters): """Constructs num_points number of points at the specified cluster locations. Clusters ...
import cv2 import os def detect_face(img): gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) face_cascade = cv2.CascadeClassifier(os.path.join(cv2.haarcascades, "haarcascade_frontalface_default.xml")) faces = face_cascade.detectMultiScale(gray_img, scaleFactor=1.2, minNeighbors=5) if len(faces) == 0: ...
# -*- coding: utf-8 -*- import sys reload(sys) sys.setdefaultencoding('utf-8') def ex1(): s = raw_input() print s s = s.split() print s s.sort() print s if __name__ == '__main__': ex1()
#coding=utf-8 import requests import re import time import random import os from bs4 import BeautifulSoup # Start a new session every time to keep the cache update in runtime. s = requests.Session() def get_html(url): '''Send http request Args: url: the web url need to fetch Return: html: ...
from plot_cell import * from readGEOMinfo import * from collections import defaultdict import matplotlib.pyplot as plt import matplotlib.colors as col import matplotlib.cm as cm import numpy as np from mpl_toolkits.mplot3d import Axes3D import pdb ''' INCLUDE VISUALIZATION OF SYNAPSES ''' from readNRNdata import * ...
# author: Jonathan Marple from pyexcel_ods import get_data from bisect import bisect_left import praw import time import re # Reading pokemon data from spreadsheet data = get_data("Pokemon Weightlist.ods") # Number of pokemon in list numOfPokemon = 151 # Creating lists based on the spreadsheet data pokemonNums = [l...
# Network skills ### cifar10 loss def cifar10_loss(logits, labels): """ Add summary for for "Loss" and "Loss/avg". Args: logits: Logits from inference(). labels: Labels from distorted_inputs or inputs(). 1-D tensor of shape [batch_size] Returns: Loss tensor of type float. """ # Calculate the average ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # # calculando.py # print("***Calculo del área de un triangulo***") base=6;altura=2; base,altura=altura,base calculo=(base*altura)/2 print("La base es:", base, "La altura es:", altura) print("El resultado es :", calculo)
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer as vds from features.feature_tools import get_all_texts, get_statistical_results_of_list from collections import Counter import emoji analyzer = vds() def extract_emojis(s): emojis=[c for c in s if c in emoji.UNICODE_EMOJI] return emojis d...
#!/usr/bin/python # Copyright 2014 Google. # # 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 agreed to...
from scrapy.spiders import Spider from scrapy.selector import Selector from twisted.internet import reactor from scrapy.crawler import CrawlerRunner from scrapy.utils.log import configure_logging from pathlib import Path import os import json import scrapy class MySpider1(Spider): name = "spider1" allowed_dom...
import matplotlib.pyplot as plt from sklearn import datasets from sklearn import svm import random digits = datasets.load_digits() clf = svm.SVC(gamma=0.0001) x,y = digits.data[:-1],digits.target[:-1] clf.fit(x,y) def yes_or_no(question): reply = str(input(question+' (y/n): ')).lower().strip() if reply[0]...
from ._title import Title from plotly.graph_objs.parcats.line.colorbar import title from ._tickformatstop import Tickformatstop from ._tickfont import Tickfont
""" Auto-encoder network model definition. Only defined if kwcnn is available. """ from .kwcnndescriptor import kwcnn AutoEncoderModel = None if kwcnn is not None: class AutoEncoderModel(kwcnn.core.KWCNN_Auto_Model): # NOQA """FCNN Model.""" def __init__(self, *args, **kwargs): """FC...
import unittest from katas.kyu_7.candy_problem import candies class CandiesTestCase(unittest.TestCase): def test_equal_1(self): self.assertEqual(candies([5, 8, 6, 4]), 9) def test_equal_2(self): self.assertEqual(candies([1, 2, 4, 6]), 11) def test_equal_3(self): self.assertEqual...
import os import uuid import logging log = logging.getLogger( __name__ ) from sqlalchemy import * from sqlalchemy import event from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import relation, backref, sessionmaker, scoped_session from sqlalchemy.exc import OperationalError Base = declarat...
from __future__ import print_function import pickle import os.path from googleapiclient.discovery import build from google_auth_oauthlib.flow import InstalledAppFlow from google.auth.transport.requests import Request import json from bs4 import BeautifulSoup import requests # If modifying these scopes, delete the file...
""" Escreva um programa que receba 10 valores, e ao final, imprima quantos valores negativos foram inseridos. """ cont = 0 print("Digite 10 valores") for i in range(10): valor = int(input()) if valor < 0: cont = cont + 1 print(str(cont) + " Números Negativos")
import environement import numpy as np import random as rd import matplotlib.pyplot as plt import time import cv2 from threading import Thread done = False done2 = False def view(name): global done global done2 name1 = 'Q' name2 = 'S' show().start() lenbd1 = 0 lenbd2 = ...
l= list(input()) le = 0 a= [] for i in range(len(l)): t = l[:i] rt = list(reversed(t)) if t != rt: if len(t) > le: le = len(t) a = t #print("p",t,le) for i in range(len(l)): t = l[i:] rt = list(reversed(t)) if t != rt: if l...
from django.urls import path from . import views urlpatterns = [ # TODO 此处添加映射的url地址 path('test/',views.test), path('get_brief/',views.get_article_info), path('get_detail/',views.get_article) ]
# -*- coding: ms949 -*- import pandas as pd # pandas의 경우 문자열도 읽을 수 있음 from sklearn.model_selection import train_test_split from sklearn.linear_model.base import LinearRegression # pandas로 csv 파일 읽기 data = pd.read_csv("test-score.csv", header=None, # header가 없다고 전달 ...
from __future__ import print_function import os import random import math import numpy as np import lightgbm as lgb import pandas as pd import subprocess import datetime import time from tqdm import tqdm from multiprocessing import Pool #USER = 'Zhiying' USER = 'Heng' if USER == 'Zhiying': THREAD_COUNT = 4 else: ...
import sys def match(command, settings): try: import CommandNotFound if 'not found' in command.stderr: try: c = CommandNotFound.CommandNotFound() pkgs = c.getPackages(command.script.split(" ")[0]) name,_ = pkgs[0] return Tr...
# -*- coding:utf-8 -*- # Author: Jorden Hai class Dog(): def __init__(self,name): self.name = name def bulk(self): print("%s :Wang Wang Wang"%self.name) d1 = Dog("陈中华") d2 = Dog("杨哲") d3 = Dog("焦海") d1.bulk() d2.bulk() d3.bulk()
from __future__ import print_function, absolute_import import logging import re import json import requests import uuid import time import os import argparse import uuid import datetime import socket import apache_beam as beam from apache_beam.io import ReadFromText from apache_beam.io import WriteToText, textio from...
with open("sentenceAnalysis.txt", "rb") as f: for x in f: print(x) '''text = f.read().decode('utf-8-sig') print(text)'''
import base64 import json import hashlib import hmac import httplib2 import time toby_ACCESS_TOKEN = '*' toby_SECRET_KEY = '*' ACCESS_TOKEN = '*' SECRET_KEY = '*' URL = 'https://api.coinone.co.kr/v1/transaction/coin/' PAYLOAD = { "access_token": ACCESS_TOKEN, "address": "16ZMTadHVy6kx6dfVNtu4QyRdg1qXSuQR8", "...
# 创建子进程 # multiprocessing模块就是跨平台版本的多进程模块 # multiprocessing模块提供了一个Process类来代表一个进程对象 # from multiprocessing import Process # import os # # # # 子进程要执行的代码 # def run_proc(name): # print('子进程运行 %s (%s)...' % (name, os.getpid())) # # if __name__=='__main__': # print('父进程 %s.' % os.getpid()) # p = Process(target=ru...
import smbus import time import board import busio import adafruit_character_lcd.character_lcd_rgb_i2c as character_lcd # Create the bus connection bus = smbus.SMBus(1) # This is the address we setup in the Arduino Program address = 0x04 # Character LCD size lcd_columns = 16 lcd_rows = 2 # Initialise I2C bus. i2c =...
#!/usr/bin/env python3 """Annotate the output of ReQTL as cis or trans Created on Aug, 29 2020 @author: Nawaf Alomran This module annotates the output of ReQTL as cis or trans based on whether the SNVs resides within its paired gene. Input + Options ---------------- + -r: the path to the ReQTL analysis result...
import django.contrib.auth as auth from django.http import HttpResponseRedirect from django.shortcuts import render from authapp.forms import LoginForm, RegisterForm def login(request): if request.method == 'POST': form = LoginForm(data=request.POST) if form.is_valid(): auth.login(req...
from django.contrib import admin from . import models @admin.register(models.Region) class RegionAdmin(admin.ModelAdmin): list_display = ["id", "name"] list_display_links = ["id", "name"] @admin.register(models.Gallery) class GalleryAdmin(admin.ModelAdmin): list_display = ["id", "name", 'location', 'regi...
numlist = [] submit = input('Enter a number: ') #stop and exit program while True: submit == 'Done' break #add valuables into the list else: numlist.append(submit) #max and min methods for list print('Maximum:', max(numlist)) print('Minimum:', min(numlist))
#!/usr/bin/env python3 import serial ser = serial .Serial('/dev/ttyACM0', 9600) ser.write(b'1') print("nay")
class Memory: def __init__(self): self.mem = 0 def store(self, val): self.mem = val return val def recall(self): return self.mem memory = Memory()
#!/usr/bin/env python class RESTOperation(object): def __init__(self, api_ref=None, callback=None, *kwargs): self.api_ref = api_ref self.args = kwargs self.callback = callback def execute(self, api_obj): func = getattr(api_obj, self.api_ref) self.callback(func(*self.arg...
# coding=utf-8 import logging import os import time as _time import sqlite3 import threading from persistqueue.exceptions import Empty import persistqueue.serializers.pickle sqlite3.enable_callback_tracebacks(True) log = logging.getLogger(__name__) # 10 seconds internal for `wait` of event TICK_FOR_WAIT = 10 def...
def test_analysis(): pass
from torchvision import models import json import numpy as np import torch from collections import OrderedDict from operator import itemgetter import os def return_top_5(processed_image): # inception = models.inception_v3(pretrained=True) inception = models.inception_v3() inception.load_state_dict(torch.lo...
from app import app from flask import json as fJson @app.route('/') @app.route('/index') def index(): return "Hello, Maxence" @app.route('/book') def book(): with open('./books.json', 'r') as jsonfile: file_data = json.loads(jsonfile.read()) print(file_data) #return json.dumps(file_d...
def power(x, n=2): s = 1 while n > 0: s = s * x n -= 1 return s def calc(*numbers): sum2 = 0 for n in numbers: sum2 = sum2 + n * n return sum2 nums = [1, 2, 3] print(calc(*nums)) def person(name, age, **kw): print('name:', name, 'age:', age, ...
import bs4 import requests from bs4 import BeautifulSoup from urllib.request import urlopen import csv from datetime import date import os def writeToCSV(name,info,summary): today = date.today() fileName = name + '.csv' try: os.mkdir("./"+str(today)) except OSError as e: print("Directory Exists") with open(...
#!/usr/bin/env python3 import socket HOST = '127.0.0.1' PORT = 50000 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((HOST, PORT)) s.sendall(str.encode('Bom dia!')) data = s.recv(1024) print('Mensagem ecoada: ', data.decode())
import numpy as np import keras.backend.tensorflow_backend as backend from keras.models import Sequential from keras.layers import Dense, Dropout, Conv2D, MaxPooling2D, Activation, Flatten from keras.optimizers import Adam from keras.callbacks import TensorBoard from keras.callbacks import ModelCheckpoint import...
# Generated by Django 3.2 on 2021-04-30 08:00 from django.db import migrations, models import multiselectfield.db.fields class Migration(migrations.Migration): dependencies = [ ('Tour_app', '0025_auto_20210430_1312'), ] operations = [ migrations.AddField( model_name='room', ...
# Project 1: Implementation of Go-Back-N Protocol # Group Member: Daksh Patel ID: 104 030 031 # Group Member: Nyasha Kapfumvuti ID: 104 121 166 # Date: Mar 30th, 2018 import socket #Sockets are the endpoints of a bidirectional communications channel. Channel types include TCP and UDP import json #lightwe...
import dotenv from google.cloud import translate_v2 as translate dotenv.load_dotenv() def translate_to_english(recvmsg, location): # Instantiates a client translate_client = translate.Client() # The text to translate text = recvmsg # The target language target = location translation = t...
# http://www.practicepython.org/exercise/2014/12/14/23-file-overlap.html with open("EX23_DATA1", "r") as arch1: lista1 = [int(dato) for dato in arch1] with open("EX23_DATA2", "r") as arch2: lista2 = [int(dato) for dato in arch2] # concordancias = [a for a in lista1 for b in lista2 if a == b] concordancias =...
from common import * import sys if len(sys.argv) < 2: raise("Missing params! ") # taking the video frames process_ucf_dataset(sys.argv[1])
import json from bs4 import BeautifulSoup import requests import tldextract def extract(): """ Scrape data on https://isthereanydeal.com/specials/ """ freegames = [] url = "https://isthereanydeal.com/specials/" headers = { 'User-Agent': "Mozilla/5.0 (Windows; U; Windows NT 5.1;...
from .boykovkolmogorov import * from .capacityscaling import * from .dinitz_alg import * from .edmondskarp import * from .gomory_hu import * from .maxflow import * from .mincost import * from .networksimplex import * from .preflowpush import * from .shortestaugmentingpath import * from .utils import ( build_flow_di...
# -*- coding: utf-8 -*- """ Created on Mon Feb 10 18:35:36 2020 @author: raghed """ class etudiant(object): def __init__(self,numero,prenom,nom,niveau): self.numero = numero self.prenom = prenom self.nom = nom self.set_niveau(niveau) data.ajouterEtudiant(self) ...
alphabet = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"] position = [] string = input ('What would you like to "Encrypt": ') index = 0 for letter in list(string.lower()): if letter in alphabet: alpha_number = alpha...
#import the sys module and unpack the argv variable from sys import argv #specify the arguments to run the file script, filename = argv #specify the txt file to be opened by the script txt = open(filename) # print this phrase and the file name variable print "Here's your file %r:" % filename # print out what's in th...
#!/usr/bin/env python # -*- coding:utf-8 -*- import time # 示例,列表解析与迭代 li = [1, 2, 3, 4, 5] # 方法一,列表解析 start = time.perf_counter() res = [i + 10 for i in li] end = time.perf_counter() print('列表解析的结果:\n\t{}\n\t运行时间:{:.8f}'.format(res, end - start)) # 方法二,for循环迭代 start = time.perf_counter() res = [] for i in li: res.a...
from sys import argv script, first, second, third = argv print "The script is called:", script print "Your first variable is:", first print "Your second variable is:", second print "Your third variable is:", third
import asyncio import time import pandas as pd from typing import List from core.tools import aget, time_left_in_month class CryptoCompareAPI: """ CryptoCompareAPI class is a object that maintains information for requesting the Crypto Compare REST API. It has built in rate limiting and supports polling REST en...
# -*- coding: utf-8 -*- __author__ = 'Steven Willis' __email__ = 'onlynone@gmail.com' __version__ = '0.1.0' import subprocess __all__ = ["git", "CALL", "CHECK_CALL", "CHECK_OUTPUT"] CALL = 'call' CHECK_CALL = 'check_call' CHECK_OUTPUT = 'check_output' __sub_calls = { CALL: subprocess.call, CHECK_CALL: subp...
import random class Number: def __init__(self, player): self.player = player self.chances = 6 def gen_num(self): num = random.randint(0, 100) # print(num) print(f"Hello! {self.player} Game Starts... I've selected a number between 0-100. ...
import json import os import sys import pandas.io.sql as psql import requests crypto_tools_dir = os.getcwd().split('/scripts/')[0] + '/scripts/' sys.path.append(crypto_tools_dir) from crypto_tools import * class PopulateKraken(object): """ """ def __init__(self): """ """ self.po...
N = int(input("N=")) K = 1 S = 1 while S <= N: K += 1 S += K S -= K K -= 1 print("K=",K,"S=",S)
import sys from awg4100 import AwgDevice local_ip = "192.168.8.10" # 本机 IP out_ch = 1 # 定义波形代码 # sin(x,y),x represents x MHz,y represents running for y ns, x*y/1000 equals to how many periods for the function #wave_code = WAVE('C:\\Users\Administrator\Desktop\wave.wave'); with open('C:\\Users\Administ...
from typing import Any, Dict, Union from torchvision import tv_tensors from torchvision.transforms.v2 import functional as F, Transform class ConvertBoundingBoxFormat(Transform): """[BETA] Convert bounding box coordinates to the given ``format``, eg from "CXCYWH" to "XYXY". .. v2betastatus:: ConvertBounding...
import unittest from katas.beta.bin_to_decimal import bin_to_decimal class BinaryToDecimalTestCase(unittest.TestCase): def test_equal_1(self): self.assertEqual(bin_to_decimal('1'), 1) def test_equal_2(self): self.assertEqual(bin_to_decimal('0'), 0) def test_equal_3(self): self.a...
import numpy as np import pandas as pd import networkx as nx import matplotlib.pyplot as plt from scipy.sparse import coo_matrix, csr_matrix from scipy.spatial.distance import pdist, squareform import logging logger = logging.getLogger(__name__) STATES = ["S", "I", "R"] def csr_to_list(x): x_coo = x.tocoo() ...