text
stringlengths
38
1.54M
list1=[[2,44],3,1,5,8] list2=[] def get_max(list1): for i in list1: if type(i)==list: get_max(i) else: list2.append(i) return max(list2) print(get_max(list1))
import numpy as np import time from scipy import linalg from scipy.special import logsumexp def gausscov(X, resp, nk, mean, regcovar): n_com, n_fe = mean.shape cov = np.empty((n_com, n_fe, n_fe)) for k in range(n_com): diff = X - mean[k] cov[k] = np.dot(resp[ : , k] * diff.T, diff) / nk[k] cov[k].flat[ : : n_...
import uuid import json from dot_base import base_data class Dot(): """A dot.""" def __init__(self, did=None): self.database_location = "data/characters.json" if did: self.did = did self.data = self.load() else: self.did = uuid.uuid4().hex d...
########## Essential for script import sys,os sys.path.insert(0,os.path.abspath("/srv/tigerapps")) import settings from django.core.management import setup_environ setup_environ(settings) ########### from card.models import Member, Club club = Club.objects.get(name=sys.argv[1]) f = open(sys.argv[2]) for line in f: ...
def main(): S = input() y, m, d = map(int, S.split('/', 2)) if y < 2019: print('Heisei') elif y > 2019: print('TBD') else: # 2019 if m < 4: print('Heisei') elif m > 4: print('TBD') else: # 2019/04 if d <= 30: ...
a = 0 b = 1 c = 0 while b != 0: b = int(input()) if a < b: a = b c = 1 elif a == b: c += 1 print(c)
import numpy as np import os import matplotlib.pyplot as plt import librosa import soundfile as sf from pydub import AudioSegment import librosa.display # rate, data = wf.read('clairvoyant.wav') def main(): orig_filepath = "music/the_story_so_far/The Story So Far 'Small Talk'-LHIVOa-9AgE.wav" sides_subtract...
import numpy as np import matplotlib.pyplot as plt def gather_pdos_data(data_name): """Gathers PDOS data and stores each row in dictionary, returns dic""" data = np.genfromtxt(data_name, unpack=True, comments="#", skip_header=1) data_dic = {} orbital = ["s", "p", "d", "f"] for spalte in range(len(data)): if sp...
from pyrogram import Client, Filters, StopPropagation, InlineKeyboardButton, InlineKeyboardMarkup @Client.on_message(Filters.command(["support"]), group=-2) async def start(client, message): # return socialButton = InlineKeyboardMarkup([ [InlineKeyboardButton("Youtube", url="https://t.me/PapyProjects"...
threeDigitNumber = input("Enter a three digit number: ") sum = 0 for i in range(0, 3): sum = sum + int(threeDigitNumber[i]) print(sum)
from .helper import parse_file def enrich_features_from_csv(corpus_context, path): """ Enriches corpus from a csv file Parameters ---------- corpus_context: :class:`~polyglotdb.corpus.CorpusContext` the corpus being enriched path : str the path to the csv file """ data...
from flask import Flask from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////home/check_user/envs/prueba.db' db = SQLAlchemy(app) class Datos(db.Model): id = db.Column(db.Integer, primary_key=True) consumoCpu = db.Column(db.String(80), nullable=Fal...
from django import forms from models import Person class PersonForm(forms.ModelForm): class Meta: model = Person exclude = ["person_id"]
import math base = [2,3,4,5,6,7,8,9,10] def is_prime_c(n): if n % 2 == 0 and n > 2: return False for i in range(3, 100 + 1, 2): if n % i == 0: return False return True def check_prime_through_bases(x): for b in base: if is_prime_c(int(str(x),b)): ...
# This sample code uses the Appium python client # pip install Appium-Python-Client # Then you can paste this into a file and simply run with Python from appium import webdriver caps = {} caps["platformName"] = "android" caps["deviceName"] = "hogwarts" caps["appPackage"] = "com.xueqiu.android" caps["appActivity"] = "...
#!/usr/bin/env python # coding=utf-8 import sys import os import time import version bin_version_file_dir= 'user/version.h' product_modle = [] def main(): global product_moudle bin_description = '' if len(sys.argv) == 2: single_moudle = [sys.argv[1]] product_moudle = single_moudle if len(sys.argv) == 3: s...
# -*- coding: utf-8 -*- """ Description : Author : xxm """ from torchmeta.datasets import MiniImagenet from torchmeta.transforms import Categorical, ClassSplitter, Rotation from torchvision.transforms import Compose, Resize, ToTensor from torchmeta.utils.data import BatchMetaDataLoader dataset = MiniImag...
#!/u/ki/mbaumer/anaconda/bin/python import matplotlib.pyplot as plt from astropy.io import fits import treecorr import yaml import numpy as np import datasets import time import tricorder import yaml import sys import os import paths from simple_script import out_path, config_dir def load_config(config_fname): c...
print('Bank Management System') b=[] c='y' while(c=='y'): name=input('Enter customer name: ') accno=str(input('Enter the account number: ')) amount=int(input('Enter the amount you have: ')) b.append((accno,(name,amount))) c=input('do u want to enter details? '...
# Copyright 2022, Google LLC. # # 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 in writing...
from car import Car from account import Account if __name__ == "__main__": print("Hola Mundo") car = Car("AMS234", Account("Andres Herrera", "ANDA876")) print(vars(car)) print(vars(car.driver))
#!/usr/env/bin python """ Newsreader - Main Copyright (c) 2018 Trevor Bramwell <trevor@bramwell.net> SPDX-License-Identifier: Apache-2.0 """ from string import digits from datetime import timedelta, date from configparser import SafeConfigParser from os.path import expanduser import logging import urwid from urwid im...
#!/usr/bin/env python #coding:utf-8 # Author: LPP --<lpp1985@hotmail.com> # Purpose: Trans 454 to fastq # Created: 2011/8/8 from lpp import * from optparse import OptionParser usage = '''usage: python %prog [options] It can automaticly transfer 454 to fastq!!''' parser = OptionParser(usage =usage ) parser.add_opt...
import numpy as np def check_is_binary(array): """Checker if array consists of int or float binary values 0 (0.) and 1 (1.) Args: array (1d array-like): Array to check. """ if not np.all(np.unique(array) == np.array([0, 1])): raise ValueError(f"Input array is not binary. " ...
#!/usr/bin/env python # coding=utf-8 from boa.compiler import Compiler # bytes = Compiler.load_and_save('./file.py') # bytes = Compiler.load_and_save('./Hello.py') # bytes = Compiler.load_and_save('./Domainpy2.py') # bytes = Compiler.load_and_save('./print.py') # bytes = Compiler.load_and_save('./base.py') # bytes =...
import pprint def putInfoToDict(fileName): fileName1 = open(fileName,'r').readlines() stu = [] stu_map = {} for i in fileName1: stu.append(i.replace(' ','').replace('\t','').replace("'",'').replace(';','').replace('\n','')) for one in stu: if one == '': break name...
""" This file contains the function required to "fry" the image. This is not a required part of the final project, and may not be included. However, out of the inteset of jokes, this can be used to "deep fry" images and memes dependancies: Pillow (PIL) """ from PIL import Image, ImageEnhance def image_fryer(path: ...
from gpiozero import LED from time import sleep pump = LED(17) print("Turning pump ON!") pump.on() sleep(1) print("Turning pump OFF!\n\n Thank you!\n") print("Thank fren!")
import os from datetime import datetime, timedelta from typing import Optional import jwt from fastapi import Depends, HTTPException, Security, status from fastapi.openapi.models import OAuthFlows as OAuthFlowsModel from fastapi.security import OAuth2, SecurityScopes from fastapi.security.utils import get_authorizatio...
from turtle import* import random speed(speed= 'fastest') def draw(n,x,angle): #%23 loof for number of stars for i in range(n): colormode(255) # %23 choosing random integer # %23 between 0 to 255 # %23 to generate random rgb values a= random.randint(0, 255) ...
import string def is_pangram(s): for let in string.ascii_lowercase: if not let in s.lower(): return False return True print(is_pangram("The quick, brown fox jumps over the lazy dog!"))
from django.contrib import admin from user.models import User class UsersAdmin(admin.ModelAdmin): list_display = ['id', 'username', 'email'] # 用户账号的配置 # Register your models here. admin.site.register(User, UsersAdmin)
from coders.vae_coding import fc_mnist_encoder, fc_mnist_decoder import tensorflow as tf import numpy as np from plots.grid_plots import show_samples, show_latent_scatter from tensorflow.examples.tutorials.mnist import input_data from tqdm import tqdm from models.vae import VAE """ This simple implementation is heavil...
# Generated by Django 2.1.2 on 2020-01-03 15:30 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('pages', '0005_auto_20200103_1519'), ] operations = [ migrations.AddField( model_name='apartment', name='image1', ...
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # # Name: ABE65100 Lab01 Exercise 3.2 # # Purpose: Script to use the function do_twice to call print_twice twice # and passing 'spam' as an argument # # Author: Tao Huang (huan1441) # # Created: Jan 17, 2020 # # - - - - - ...
""" Revision ID: 0375_doc_download_verify_email Revises: 0374_email_branding_to_org Create Date: 2020-09-13 28:17:17.110495 """ import sqlalchemy as sa from alembic import op revision = "0375_doc_download_verify_email" down_revision = "0374_email_branding_to_org" def upgrade(): op.execute("INSERT INTO service_...
#-*- coding:utf-8 -*- """ > I-VDT algorithm for eye movement events detection. > author: Mike Zheng > 08, May, 2021 > Reference: Komogortsev, Oleg V. and Alex Karpov (2013). “Automated classification and scoring of smooth pursuit eye movements in the presence of fixations and s...
from config import PROVIDER_CONFIG from concurrent_log_handler import ConcurrentRotatingFileHandler import logging LOGGING_CFG_KEY = 'logging' LOG_FOLDER_CFG_KEY = 'logFolder' ROTATING_PERIOD_TYPE_CFG_KEY = 'rotatingPeriodType' ROTATING_PERIOD_VALUE_CFG_KEY = 'rotatingPeriodValue' LOG_FOLDER = PROVIDER_CONFIG[LOGGIN...
from heapq import * class Solution: def kthSmallest(self, matrix: List[List[int]], k: int) -> int: minHeap = [] res = [] for elem in matrix: heappush(minHeap, elem) while minHeap and len(res) < k: popped = heappop(minHeap) res.append(popped[0]) ...
import redis class CacheHandler: def __init__(self): self.connection = redis.Redis(host='0.0.0.0', port=6379, db=0, password='6r!7n3y0') def get_info(self, token_name): cached_token = None try: cached_token = self.connection.get(name=token_name) except Exception: ...
import random import string def u_letters(upp_letters): """ :param upp_letters: :return: a list of random uppercase letters """ return list("".join([random.choice(string.ascii_uppercase) for _ in range(upp_letters)])) def l_letters(low_letters): """ :param low_letters: :return: a l...
#!/usr/bin/env python """ setup.py file for afnumpy """ from distutils.core import setup from afnumpy import __version__ setup (name = 'afnumpy', version = __version__, author = "Filipe Maia", author_email = "filipe.c.maia@gmail.com", url = 'https://github.com/FilipeMaia/afnumpy', ...
#xox game functions def display_board(gameBoard): #printing game board print " {} | {} | {} ".format(gameBoard[6],gameBoard[7],gameBoard[8]) print "-----------" print " {} | {} | {} ".format(gameBoard[3],gameBoard[4],gameBoard[5]) print "-----------" print " {} | {} | {} ".format(gameBoard[0],gameBoard[1],gameB...
import sqlite3 import pandas as pd conn = sqlite3.connect( "data-10.sqlite" ) c = conn.cursor() def replacePlayer(name, season,team): itr = c.execute('''select g.player_name, round(avg(g.eff),3), round(avg(s.salary),1) from games g join salaries s on (g.player_name = s.player and g.season = s.season_sta...
from kivy.lang import Builder from kivy.uix.screenmanager import Screen Builder.load_file('medication_entry.kv') class MedicationEntryScreen(Screen): def print_number(self): pass
# -*- coding: utf-8 -*- # @Time : 2018/1/9 15:52 # @Author : ddvv # @Site : https://www.bangcle.com/ # @File : douyin1Spider.py # @Software: PyCharm import scrapy from appspider.spiders.douyinspider.douyincore import * from appspider.commonapis import * ''' app: 抖音短视频 备注:爬取首页-推荐接口的数据 ''' CONST_INFO = { ...
import argparse import aws_comprehend as ac import json import os import qa_engine as qa import slackclient import time import urllib.request INSTANCE_ID = urllib.request.urlopen('http://169.254.169.254/latest/meta-data/instance-id').read().decode() AVAILABILITY_ZONE = urllib.request.urlopen('http://169.254.169.254/l...
from django.contrib.auth import authenticate, login, logout from django.shortcuts import render, redirect from django.urls import reverse_lazy, reverse from django.http import JsonResponse from django.views.generic import * from .forms import * from .models import * class LoginView(FormView): template_name = "sta...
from django.contrib.auth.signals import user_logged_in, user_logged_out from django.contrib.messages import success from django.dispatch import receiver @receiver(user_logged_in) def display_login_message(sender, **kwargs): request = kwargs.get('request') user = kwargs.get('user') success( request,...
# coding = utf-8 __author__ = 'Zhou Shengshuai' __version__ = '1.0' import logging import os from time import sleep from selenium import webdriver from selenium.common.exceptions import WebDriverException, TimeoutException from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_co...
# # file: convnet.py # author: MING Yao # import os import numpy as np import tensorflow as tf from convnet.utils.io_utils import before_save, get_path from convnet.core.preprocess import DataGenerator, ImageDataGenerator from convnet.core.sequential_net import SequentialNet, Layer from convnet.core.config import da...
from datetime import datetime from apscheduler.schedulers.background import BackgroundScheduler from stock.pipeline import pipeline def job(): print("\n job",datetime.now()) pipeline() def start(): print("apscheduler start..") scheduler = BackgroundScheduler() scheduler.add_job(job, 'interval', se...
""" Axes.py -- This file implements the axes class. Date of creation: 2006...
import zipreport.report.job as j import zipreport.report.const as const class TestReportJob: def test_init(self): # fake job job = j.ReportJob(None) opts = job.get_options() assert type(opts) is dict assert len(opts) == len(j.ReportJob.DEFAULT_OPTIONS) # test vali...
import numpy as np import pandas as pd from sklearn.model_selection import KFold from sklearn.model_selection import cross_val_score import sklearn.metrics as mt from sklearn.neighbors import KNeighborsClassifier from sklearn.preprocessing import scale def Calculate(X, y): best_score = 0.0 best_k = 0 gen =...
# Generated by Django 3.1.2 on 2020-11-27 10:12 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('application', '0003_auto_20201115_1239'), ] operations = [ migrations.AddField( model_name='donation', name='is_take...
import asyncio import functools import sys from typing import ( Any, AsyncIterator, Awaitable, Callable, Coroutine, Dict, List, Set, TypeVar, cast, ) from async_generator import asynccontextmanager from trio import MultiError from async_service._utils import iter_dag from .abc...
# -*- coding: utf-8 -*- """ Created on Mon Dec 21 01:09:42 2020 @author: dennis """ import numpy as np import math class Image: def __init__(self, img, id_): self.id = id_ self.img = img self.neighbours = set() self.cunstruct_all_versions() def cunstruct_all_versions(sel...
import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D # noqa: F401 unused import from numpy.testing import assert_almost_equal from acrolib.geometry import pose_x from acrobotics.robot_examples import ( PlanarArm, SphericalArm, AnthropomorphicArm, Arm2, Kuka, ...
"""Lambda Function Source Code Adheres to Smart Home Skill V3 API Responds to discovery and control requests """ # Import AWS SDK and set up client import uuid import time import boto3 import json client = boto3.client('iot') client_data = boto3.client('iot-data') # Main Lambda handler # First function invoked when...
# 정수 배열이 주어졌을 때, 부분 배열(sub-array)의 합이 0이 될 수 있는지 확인하시오. # 부분 배열은 배열 내의 연속된 원소들의 집합입니다. def solution(arr): answer = [] length = len(arr) for i in range(length): temp = i for j in range(length - i): if sum(arr[j:temp + j + 1]) == 0: answer.append(arr[j:temp + ...
import RPi.GPIO as GPIO import time import cv2 import numpy as np global lxy_BZ lxy_BZ=0 def L_BUTTON(event,x,y,flags,param): # 判断事件是否为 Left Button Double Clicck if event == cv2.EVENT_LBUTTONDOWN: if x>280 and x<360 and y>88 and y<140: canvas=cv2.imread("JS.jpg") cv2.putText(...
class Node: def __init__(self): # is_word表示这个结点是否为一个单词的结尾 # next[]表示这个结点的下一个26个字母结点 self.is_word = False self.next = [None] * 26 class Trie: def __init__(self): """ Initialize your data structure here. """ self.root = Node() def insert(self...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Apr 26 16:22:55 2018 @author: macbook """ import numpy as np from sklearn.metrics import confusion_matrix import glob import pandas as pd from imageio import imread #1.1 Mittelwert der Kanäle train_files = glob.glob('./haribo1/hariboTrain/*.png') tra...
#!/usr/bin/python # -*- coding: utf-8 -*- # @Time : 2019/7/16 10:47 # @Author : journal # @File : Note_3_4_impl.py # @Software: PyCharm import tensorflow as tf # 定义输入、参数、向前传播过程 def practice_1_param(): # 定义输入 x = tf.constant([[0.7, 0.5]]) # 定义参数 w1 = tf.Variable(tf.random_normal(shape=[2, 3], m...
from django.shortcuts import render from .models import Products, Order from django.core.paginator import Paginator # Create your views here. def index(request): product_objects = Products.objects.all() # search code item_name = request.GET.get("item_name") if item_name != '' and item_name is not N...
import socket import cache default_redirects = 4 # where header is a dictionary of HTTP field name: value pairs def httpheader(header: dict) -> str: return "\r\n".join(map(lambda x: f"{x[0]}: {x[1]}", header.items())) + "\r\n" def request(url: str, redirects: int = default_redirects): assert redirects >= 0, f"Er...
def cheese_and_crackers(cheese_count, boxes_of_crackers): #function definition print(f"You have {cheese_count} cheeses!") print(f"You have {boxes_of_crackers} boxes of crackers!") print("Man thats enough for a party!") print("Get a blanket.\n") def cnc(a,b): c = a+b print("Sum :",c) print("We can just...
from django.shortcuts import render # Create your views here. from rest_framework import mixins, viewsets from rest_framework.permissions import AllowAny, IsAuthenticated from rest_framework.response import Response from rest_framework.views import APIView from rest_framework_jwt.authentication import JSONWebTokenAuth...
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.response.AlipayResponse import AlipayResponse class AlipayInsAutoBenefitUseResponse(AlipayResponse): def __init__(self): super(AlipayInsAutoBenefitUseResponse, self).__init__() self._use_flow_id = None @property ...
# -*- coding:utf-8 -*- import logging from tornado.ioloop import IOLoop from tornado.web import Application from tornado import options from TemplateTornado.utils.util import parse_cfg from TemplateTornado.basedb.customsqlalchemy import CustomSqlalchemy __author__ = "lqs" # Get the config file from command line. opt...
# Univariate multi-step output Encoder-Decoder LSTM from numpy import array from keras.models import Sequential from keras.layers import LSTM, Dense, RepeatVector, TimeDistributed # Split a univariate sequence into samples def split_sequence(sequence, n_steps_in, n_steps_out): X, y = [], [] for i in range(len(...
# -*- coding: utf-8 -*- from collections.abc import Iterable def conv_output_shape(hw, kernel_size=1, stride=1, pad=0, dilation=1): """Computes output shape of 2D conv operation.""" if not isinstance(hw, Iterable): assert isinstance(hw, int) hw = (hw, hw) else: assert len(hw) == 2...
#!/usr/bin/env python # coding: utf-8 # IMPORTANDO LIBRERIAS ##################################################################################################################### import numpy as np import pygame import gtk import cv2 # CLASE UTILIZADA PARA CREAR UN BOTON class Button: """ Clase de botón ...
#!/usr/bin/env python # -*- coding: utf-8 -*- """:Mod: lock :Synopsis: Create a simple file-based mutex lock. :Author: servilla :Created: 3/31/17 """ import os import random import string import daiquiri logger = daiquiri.getLogger('lock.py: ' + __name__) class Lock(object): def __init__(self,...
from tensorflow.keras import Model, Sequential, layers class Generator(Model): def __init__(self): # hidden dims = 100 super(Generator, self).__init__() self.model = Sequential() self.model.add(layers.Dense(7*7*256, use_bias=False, input_shape=(100,))) self.model.add(layer...
from django.contrib import admin from krishiKarma.models import State,Crop,District,Farmer,Category,Soil # Register your models here. admin.site.register(State) admin.site.register(District) admin.site.register(Crop) admin.site.register(Farmer) admin.site.register(Category) admin.site.register(Soil)
#Algorithme tp2 #Exo 1 class Point: """Classe definissant un point par: - x - y - z""" def __init__(self): self.x=4.0 self.y=1.0 self.z=2.5
import board,busio,digitalio,time #led = digitalio.DigitalInOut(board.D13) #led.direction = digitalio.Direction.OUTPUT uart = busio.UART(board.TX, board.RX, baudrate=9600) while True: data = uart.readline() print(data) time.sleep(.2)
import random def hladaj(lst,x): for i in range(len(lst)): if lst[i]==x: return i return -1 lst = [] for i in range(10): lst.append(random.randint(1,10)) print(lst) x = int(input('Zadaj x: ')) print(hladaj(lst,x))
from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import glob import numpy as np import tensorflow as tf import download_and_make_tfrecords as dl class Cifar10Input: def __init__(self): dl.maybe_download_cifar() self.HEIGHT = 32 se...
from PyQt5 import QtCore, QtGui, QtWidgets import controller.tab3_controller.commands as commands import controller.tab3_controller.commands.ResetUI as reset_ui import controller.tab3_controller.commands.track as track import controller.tab3_controller.commands.speakout as speakout import controller.Inspectors as insp...
from flask import Response, jsonify, make_response from loguru import logger from ..errors import * from ..main import app @app.errorhandler(BaseAppException) def app_error_handler(e: BaseAppException): return make_response(jsonify(e.to_dict()), e.error_code) @app.errorhandler(Exception) def exception(e: Excep...
#! /usr/local/bin/python2.7 # -*- coding: utf-8 -*- # # This software was developed by employees of the National Institute of # Standards and Technology (NIST), and others. # This software has been contributed to the public domain. # Pursuant to title 15 Untied States Code Section 105, works of NIST # employees are not...
""" Part 3: Here you should improve viterbi to use better laplace smoothing for unseen words This should do better than baseline and your first implementation of viterbi, especially on unseen words """ import math def viterbi_2(train, test): ''' input: training data (list of sentences, with tags on the word...
import sys import hashlib f= open(str(sys.argv[2])) with open(str(sys.argv[2])) as file: blah = f.read() md5result = hashlib.md5(blah.encode()) sha1result = hashlib.sha1(blah.encode()) sha256result = hashlib.sha256(blah.encode()) print("MD5 is: ",md5result.hexdigest()) print("SHA1 is: ",sha1result.hexdig...
from django import forms from blog_app.models import Comment class EmailSending_form(forms.Form): name = forms.CharField() From_Mail = forms.EmailField() To_Mail = forms.EmailField() Comment = forms.CharField(required= False,widget = forms.Textarea) class CommentForm(forms.ModelForm): class Meta:...
# -*- coding: utf-8 -*- import tensorflow as tf import os import random import math import sys _NUM_TEST=200 #验证集数量 _RANDOM_SEED=0 #随机种子 _NUM_SHARDS=5 #数据块 DATASET_DIR="E:/Pycharm/Project/NNetword/Tensorflow/slim/images" #数据集路径 LABELS_FILENAME="E:/Pycharm/Project/NNetword/Tensorflow/slim/images/labels.txt"#标签路径 ...
# -------------------- Import libraries import random as rnd import matplotlib.pyplot as plt import numpy as np import pylab as pl import matplotlib.ticker as mticker from matplotlib.ticker import FormatStrFormatter from trafficsim import* # -------------------- Calculation # iteration for positions vs time, nCars =...
#-*- coding:utf-8 -*- import pandas as pd import numpy as np import matplotlib.pyplot as plt # %matplotlib inline # from IPython import get_ipython # get_ipython().run_line_magic('matplotlib', 'inline') #正常显示画图时出现的中文和负号 from pylab import mpl mpl.rcParams['font.sans-serif']=['SimHei'] mpl.rcParams['axes.unicode_m...
class Solution: def findInversions(self,arr,count): if len(arr) == 1: return mid = len(arr) // 2 left = arr[:mid] right = arr[mid:] self.findInversions(left,count) self.findInversions(right,count) i...
import cv2, dessinMagique, utils ####### ## Parametres a saisir par l'utilisateur ####### nomImage = 'caillou.png' nombreDeCouleur = 6 aireZoneMax =100 largeurZoneMax = 2 rayonDisqueCouleur = 4 ####### ## Fin parametre a saisir par l'utilisateur ####### img = cv2.imread('Images/' + nomImage) utils.displayImage(img,...
import requests from lxml import html STUDENTID = "11988401" PASSWORD = "code2@learn" LOGIN_URL = "https://sso.lib.uts.edu.au/cas/login?service=https%3A%2F%2Fwww.lib.uts.edu.au%2Froombooking%2F%3F_casCheck%3Dtrue" BOOKING_URL = "https://www.lib.uts.edu.au/roombooking/bookings/create" URL = [ 'https://www...
def tabulate(data, headers=None, key_order=None): if isinstance(data[0], list): tabulate_lists(data, headers=headers) elif isinstance(data[0], dict): tabulate_dicts(data, headers=headers, key_order=key_order) else: assert False, 'First record in data of unexpected type: {}'.format(ty...
import dash_html_components as html def blank_link(string, href): return html.A(string, href=href, target="_blank") """-------------------------------LINKS--------------------------------------""" # INDEX build_logo_src = "https://image.flaticon.com/icons/svg/346/346195.svg" vis_logo_src = "https://image.flaticon...
from torch import nn from torch.nn import functional as F import torch from torchvision import models import torchvision class NAS_Unet(nn.Module): def __init__(self): pass def forward(self, input): pass
n= 5 def func_greater(n): repr = bin(n)[2:] length = len(repr) #next greater with same bits is -> if gap bw leftmost and right nearest then +1. if 2**(length) - 1 == n: return (int(repr[0] + "0" + repr[1:],2)) right_first = None; for i in range(length-1,0,-1): if repr[i] == "1": right_first = ...
from tortoise import BaseDBAsyncClient async def upgrade(db: BaseDBAsyncClient) -> str: return """ ALTER TABLE `asynctournamentpermalink` ADD `par_updated_at` DATETIME(6); ALTER TABLE `asynctournamentpermalink` ADD `par_time` DOUBLE; ALTER TABLE `asynctournamentrace` ADD `score_updated_at`...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ File: join2_reducer.py Description: Reducer function. """ import sys prev_tv_show = "" flag = False curr_tot_count = 0 for line in sys.stdin: line = line.strip() curr_tv_show, value = line.split('\t') if curr_tv_show != prev_tv_show: if flag: ...
import csv import math BIG_A = [] BIG_B = [] match = [] BIG_A_DIR="BIG_A.csv" BIG_B_DIR="BIG_B.csv" #define leagal year range BEGIN_YEAR=1800 END_YEAR=2017 def load_table_A(table_A_dir): #load data from table A with open(table_A_dir, 'rb') as A: spamreader1 = csv.reader(A, delimiter=',', quotechar='|...