text
stringlengths
38
1.54M
import librosa class Song: def __init__(self, song_path): self.hop_length = 1000000 self.filename = song_path self.waveform, self.sample_rate = librosa.load(self.filename) self.tempo, self.beat_frames = librosa.beat.beat_track(y=self.waveform, sr=self.sa...
class dotGrid_t(object): # no doc aCoordinateX=None aCoordinateY=None aCoordinateZ=None aLabelX=None aLabelY=None aLabelZ=None Color=None ExtensionForMagneticArea=None ExtensionLeftX=None ExtensionLeftY=None ExtensionLeftZ=None ExtensionRightX=None ExtensionRightY=None ExtensionRightZ=None IsMagnetic=No...
#練習:"Please count the character here." # Sample Output: {'r': 3, 'c': 3, 't': 3, ' ': 4, 'n': 1, 'u': 1, 'h': 3, # 'e': 6, 'l': 1, 'o': 1, 'a': 3, 's': 1, 'P': 1, '.': 1} # __________
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.response.AlipayResponse import AlipayResponse class MybankCreditSupplychainCreditpaySellerunsignCreateResponse(AlipayResponse): def __init__(self): super(MybankCreditSupplychainCreditpaySellerunsignCreateResponse, self).__init...
# Generated by Django 2.0.2 on 2018-03-30 04:02 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('quoteCalculator', '0003_auto_20180330_0305'), ] operations = [ migrations.AlterField( model_name='quote', name='admi...
#Author: Rami Janini import time from getpass import getpass from ring_doorbell import Ring print(''' ___ ___ _ / _ \__ __/ _ \(_)__ ___ _ / ___/ // / , _/ / _ \/ _ `/ /_/ \_, /_/|_/_/_//_/\_, / /___/ /___/ Author:Rami Janini v.1.1 ''') ringEmai...
import itertools numbs = str(input("Which Numbers: ")) leng = int(input("Length: ")) save = str(input("File Name: ")) counter = 0 wlistfile = open(f"{save}","w") for generate in itertools.product(numbs,repeat=leng): word= ("".join(generate)) wlistfile.write(word) wlistfile.write('\n') coun...
from typing import Optional from flask import make_response, jsonify, Blueprint, Response from flask_cors import CORS from src.database.schemas.trip_schema import TripSchema from src.logging.mixin import LoggingMixin from src.repository.trip_repository import TripRepository logger = LoggingMixin().logger trip_bluep...
# -*- coding: utf-8 -*- import logging import utool from wbia.guitool import api_item_view from wbia.guitool.__PYQT__ import QtCore, QtGui, QtWidgets from wbia.guitool.guitool_decorators import signal_, slot_ (print, rrr, profile) = utool.inject2(__name__, '[APITableView]', DEBUG=False) logger = logging.getLogger('w...
# Copyright (c) 2016-2018, University of Idaho # All rights reserved. # # Roger Lew (rogerlew@gmail.com) # # The project described was supported by NSF award number IIA-1301792 # from the NSF Idaho EPSCoR Program and by the National Science Foundation. import csv from wepppy.wepp.stats.row_data import parse_name, par...
# Used to make requests to AngelList API https://angel.co/api/spec/search class AngelAPI(object): def __init__(self): self.url_root = 'https://api.angel.co/1' self.access_token = None # must be set def request(self, route, parameters=None): url = self.url_root url += route ...
color=input("請輸入水果:") a={"橘子":"橘色","葡萄":"紫色","哈密瓜":"綠色","蘋果":"紅色","香蕉":"黃色"} if (color in a): print(color+"是"+a[color]) else: y=input("請輸入顏色:") a[color]=y print(color+"是"+a[color])
def multiplicationTable(start, end): end = end + 1 for i in range(start, end): if i == start: line = 'x\t' for j in range(start, end): line += str(j) + '\t' print line line = str(i) + '\t' for j in range(start, end): line +...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ @author: donald """ import sys from PyQt5.QtWidgets import QApplication, QMainWindow from temp import Ui_mainWindow app = QApplication(sys.argv) window = QMainWindow() ui = Ui_mainWindow() ui.setupUi(window) window.show() sys.exit(app.exec_())
TABLE = 'USStockPrice' import pandas as pd import os, sys import platform if 'Windows' in platform.platform(): PATH = "\\".join( os.path.abspath(__file__).split('\\')[:-1]) else: PATH = "/".join( os.path.abspath(__file__).split('/')[:-1]) sys.path.append(PATH) from BasedClass import Load,execute_sql2 class C...
############################################################################## # # Copyright (c) 2009 Zope Foundation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOF...
requested_toppings = ['mushrooms','anchovies', 'bacon'] #f requested_toppings == 'anchovies': # print ("Hold the anchovies") #else: # print ("Im all out man") #print('mushrooms' in requested_toppings) if 'mushrooms' in requested_toppings: print("Adding mushrooms") if 'peperoni' in requested_toppings: print("Adding ...
import math import pickle from pathlib import Path import shutil from typing import Iterable, Literal, Optional import json import numpy as np from copy import deepcopy from warnings import warn import probeinterface from .base import load_extractor from .baserecording import BaseRecording from .basesorting import B...
# -*- coding: utf-8 -*- # Generated by Django 1.9.6 on 2017-08-23 09:18 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('contest', '0004_auto_20170717_1324'), ] operations = [ migrations.RenameField( ...
def string_length(i): if type(i) == int: return "A number has no length" else: return len(i) #i = input("Enter a string to see its length: ") print(string_length("supercalifragalisticexpiallydocious"))
# test data locations and existance import os import deepforest # Make sure package data is present def test_get_data(): assert os.path.exists(deepforest.get_data("testfile_deepforest.csv")) assert os.path.exists(deepforest.get_data("testfile_multi.csv")) assert os.path.exists(deepforest.get_data("ex...
for i in range(1,11): for j in range(1,11): print(i*j,end="\t") # \t make a Horizontal TAB space between two strings or characters # for new line print()
""" This type stub file was generated by pyright. """ @<Expression> class : ... u = ... V = ... e: <Expression> F: <Expression>
from django.shortcuts import render from django.views import generic from django.http.response import HttpResponse # Create your views here. class IndexView(generic.TemplateView): template_name = 'index.html'
# Copyright 2016 Niek Temme. # Adapted form the on the MNIST expert tutorial by 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 # #...
import webbrowser """ Create a class "Movie" to store the following information: 1) Title 2) Storyline 3) Poster image 4) Trailer For use with fresh_tomates site code""" class Movie(): def __init__(self, movie_title, movie_storyline, movie_poster_image, trailer_youtube): self.title ...
from dkim_auth import DKIMAuth from gmail_spf_auth import GmailSPFAuth from spf_auth import SPFAuth from sender_auth_exception import SenderAuthException
import utils # fetch data data = utils.line_to_list('input_files/aoc_11.txt') ### START SOLUTION BODY ### def identify_adjacents(data, width, height, tx, ty): temp = [] paths = [(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)] for path in paths: if (tx + path[0] >= 0 and tx +...
############################################################################################################################################ # The goal here is to START an app on a connected android device, with gdbserer attached to it, and wait for a connection from a local gdb. # # IMPORTANT : # Since this script ...
# -*- coding: utf-8 -*- from sqlalchemy import func from datapro.framework.model.common import Date from datapro.framework.db import OrmConnection from datapro.framework.job import EtlJob from mlb.model import AtBat, PitchByPitch if __name__ == '__main__': connection = OrmConnection('common') cumulative_s...
# kullanıcıdan alınan sayıya kadar olan çşft sayıları bulma girizgah = """ girilen sayıya kadar olan çift sayıları gösteren program çıkmak için q""" print(girizgah) while True: sayi = input("Sayı giriniz\t:") if sayi == "q": print("Program sonlandırılıyor") break else: ...
Author : Mukliss from selenium import webdriver # from selenium.webdriver.chrome.options import Options import time # chrome_options = Options() # chrome_options.headless = True # chrome_options.add_argument('--headless') # driver = webdriver.Chrome(chrome_options=chrome_options) driver = webdriver.Chrome() driver....
# coding=utf-8 from math import log, pow, e, ceil import redis import mmh3 def calc_bloom_filter_params(error_rate, n): """ 计算 Bloom Filter 相关配置参数 :param error_rate: 假阳性概率 :param n: 容量 :return: (m存储位数, hash 函数个数(层数)k) """ assert 0 <= error_rate <= 1 and n > 0 m = ceil((n * log(error_ra...
import os WTF_CSRF_ENABLED = True SECRET_KEY = 'm^@H2w;PLSZuc=dnDAaH3F@`KPU8BiGkPoirPBKU[TdcXOTd;biXviJXKo@Ov]:2' basedir = os.path.abspath(os.path.dirname(__file__)) # SQLALCHEMY_DATABASE_URI = 'sqlite:////'+os.path.join(basedir,'app.db') SQLALCHEMY_MIGRATE_REPO = os.path.join(basedir, 'db_repository') # SQLALCHEMY...
# giacase=input('nhập giá dịch vụ: ') # tinhtrnghonnhan=input('Nhập tình trạng hôn nhân nha: ') # print(' trong vòng 14 ngày anh chị có : ') # benh=input('có nghi ngờ mình bị covid-19 hay k: ') # tiepxuc=input('Tiếp xúc với bệnh nhân nghi ngờ là F0 hay không: ') # vungdich=inp...
#! python3 # -*- coding: utf-8 -*- import nvksupport import tempfile import requests import codecs import random import time import json import sys import os from google.cloud import speech_v1p1beta1 from google.cloud.speech_v1p1beta1 import enums from google.cloud.speech_v1p1beta1 import types from google.cloud import...
#! /usr/bin/env python # -*- coding: utf-8 -*- """ Evaluates the accuracy of the EstNLTK morphological disambiguator. Usage: ./eval-disambiguate.py --output-types=csv,excel --verbosity=2 gold/*.txt Input format: - Mitmesus on esitatud kui tab-separated-values/4 tühikut. - Sõnaliik (POSTAG) ja sõnavorm (FORM) on er...
from numpy import array from sklearn.linear_model.perceptron import Perceptron # Definimos la data y su target para entrenar la red neuronal data = [ array([ # Vector de [forma;textura;peso] [1, 1, -1], # Manzana [1, -1, -1], # Naranja [1, 1, -1], # Manzana [1, -1, -1], # Nara...
if(10 > 5): print("10 (Dez) é maior do que 5 (Cinco)"); if(10 > 5): print("10 (Dez) é maior do que 5 (Cinco)"); if(7 > 3): print("7 (Sete) é maior do que 3 (Três)"); if(10 > 5): print("10 (Dez) é maior do que 5 (Cinco)"); if(10 > 5): print("10 (Dez) é maior do que 5 (Cinco)");...
''' Game board script ''' import sys, time import numpy as np import gym import cv2 from gym import spaces from .orb import Orb """ Puzzle environment in OpenAI gym API move_count -- start at 1 and anneal towards 0 with more moves -- simulate time """ class PadEnv(gym.Env): metadata = { 'render.modes': [...
print('>>>>>>>') #К.Ю.Поляков 3434 https://prnt.sc/1aib15w ''' Элементами множеств А, P и Q являются натуральные числа, причём P={2, 4, 6, 8, 10, 12, 14, 16, 18, 20} и Q={5, 10, 15, 20, 25, 30, 35, 40, 45, 50}. Известно, что выражение ((x ∈ A) → (x ∈ P)) ∨ (¬(x ∈ Q) → ¬(x ∈ A)) истинно (т.е. принимает значение 1 при...
from django.shortcuts import render, get_object_or_404, redirect from django.urls import reverse_lazy, reverse from django.views import generic, View from django.contrib.auth.decorators import login_required from django.http import HttpResponse, HttpResponseRedirect # from django.db import models # models.get_models(...
class Banker: def __init__(self,name,id,gender): self.name=name self.age=id self.gender def withdraw(self): return f"In the bank they aske for your {self.name},{self.id} and your {self.gender}" def loan(self): return f"In the bank they aske for your {self.nam...
#!/usr/bin/env python3 import sys import os import warnings import time import atexit from timeit import default_timer as timer from datetime import datetime import threading, queue import traceback sys.path.append(os.path.abspath(os.path.join( os.path.dirname(__file__), "./libs"))) from diycv.camera.capture_...
# https://www.codewars.com/kata/pick-peaks/train/python import unittest def pick_peaks(arr): prev, cur = 0, 0 pos = [] peaks = [] for next in range(1, len(arr)): if arr[next] > arr[cur]: prev = cur cur = next else: if arr[next] < arr[cur]: ...
from ns.utils import stampedstore class VirtualClockServer: """ Models a virtual clock server. For theory and implementation see: L. Zhang, Virtual clock: A new traffic control algorithm for packet switching networks, in ACM SIGCOMM Computer Communication Review, 1990, vol. 20, pp. 19. Pa...
for t in range(int(input())): n = int(input()) P = list(map(int, input().split())) P = list(sorted(P)) x = P[0] y = sum(P[1:]) print(x*y)
from ScenarioHelper import * def main(): CreateScenaFile( "r2010.bin", # FileName "r2010", # MapName "r2010", # Location 0x0062, # MapIndex "ed7202", 0x00000000, # Flags ...
#!/usr/bin/env python import os from redispipeline import __version__ from setuptools import setup with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as f: long_description = f.read() setup( name='redispipeline', version=__version__, description='Aync pipelined Python client for Redis'...
#!/usr/bin/env python # encoding: utf-8 """ @author: zhanghe @software: PyCharm @file: score.py @time: 2017/4/25 下午1:29 """ from app_backend.models import Score from app_backend.tools.db import get_row, get_rows, get_row_by_id, add, edit, delete def get_score_row_by_id(score_id): """ 通过 id 获取积分信息 :para...
def rot(S): return list(zip(*S[::-1])) def find_left_top(S): for i in range(N): print(f'[{i}]', S[i]) for j in range(N): print(S[i][j]) if S[i][j] == '#': return i, j def is_same(S, T): print('S') print(S) Si, Sj = find_left_top(S) print('T') print(T) Ti, Tj = find_lef...
from tkinter import * from tkinter import ttk def createLabels(widget,texto,fuente,padX,padY,width,height): label = Label(widget, text=texto, font=fuente, padx=padX, pady=padY, width=width, height=height, anchor=W) return label def createEntrys(widget, font, width, textvariable): entry = Entry(widget, fon...
#encoding:utf-8 from functions.anchor_target import compute_anchor_targets from functions.proposal_target import compute_proposal_targets from functions.rpn_proposal import compute_rpn_proposals from functions.predict_bbox import compute_predicted_bboxes import functools import torch import torch.nn.functional...
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # --------------------------------------------------------------------...
from django import forms class SearchForm(forms.Form): nome = forms.CharField(label='Nome do Imóvel Rural', required=False, widget=forms.TextInput( attrs={ 'class': 'form-control', ...
import html import json import logging import requests from bs4 import BeautifulSoup from provider_base import Provider class KleinanzeigenEbay(Provider): """Scraper class for Kleinanzeigen-Ebay.de""" def __init__(self): super(KleinanzeigenEbay, self).__init__() self.base_url = "https://www...
"""Explained in README""" import json import sys from pprint import pprint import re from concurrent.futures import ProcessPoolExecutor import os import numpy as np import pandas as pd import cv2 from tqdm import tqdm import skimage.transform as skt import skimage.io import constants as con import tools DOWNSAMPLE_...
#!/usr/bin/python import sys import os import time import subprocess #Reset hub # sudo ./usbreset /dev/bus/usb/008/004 #time.sleep(3*3600) zoomcall = ['gphoto2','--set-config', 'Zoom=4'] print ' '.join(zoomcall) subprocess.call(zoomcall) camcall1 = ['gphoto2', '--capture-image-and-download'] camcall1.append('--fi...
from django.conf.urls import url from apps.courses.views.AddCommentView import AddCommentView from apps.courses.views.AommentsView import CommentsView from apps.courses.views.ContaineView import ContainerView from apps.courses.views.CourseDetailView import CourseDetailView from apps.courses.views.CourseInfoView import...
''' N-gram model improved by Jieba ''' import gc from os import makedirs from os.path import join, isdir, exists from math import log from collections import defaultdict, Counter, OrderedDict import time import re import multiprocessing import dill as pickle from ngram_zhuyin import NGramPYModel from config import D...
from .cart import Cart from .coin import Coin from .bluecoin import BlueCoin from .bomb import Bomb from .death_zone import Death_Zone from .cart_one_v_one import Cart_One_V_One
#Python 2.7 script #Keszitett: Koncz Viktoria #Datum: 2017. december 1. #Feladata: Sav-bazis tranziens szimulacioja soran kimentett profilok (+ ido- es terbeli derivaltak) visszahelyettesites az eredeti differencial-egyenletbe, # ebbol valamilyen modon aggregalt hiba szamolas; ####################################...
# coding=utf-8 import sys reload(sys) sys.setdefaultencoding('utf8') from array import array __author__ = 'wei' from igt_push import * from igetui.template import * from igetui.template.igt_base_template import * from igetui.template.igt_transmission_template import * from igetui.template.igt_link_templ...
import random col= random.random()*100 if col <= 25: print("El numero " + str(col) + " Es menor que 25") elif col<=50: print("El numero " + str(col) + " Es menor que 50") else: print("El numero " + str(col) + " es mayor que 50")
from PIL import Image import sys if __name__ == "__main__": print(f'Argumentos: {len(sys.argv)}') for i, arg in enumerate(sys.argv): print(f"argumentos:{i}: {arg}") img = Image.open(sys.argv[1]) print(img.size) matriz = img.load() for y in range (img.size[0]): for x in range (img.size[1]): r = ...
from random import choice value = ["0 0 0 1 0 0 2 3 0", "0 2 4 0 0 0 0 0 0", "5 0 0 6 0 0 7 8 0" , "0 4 0 0 9 0 0 2 0", "0 0 7 0 8 0 6 0 0", "0 8 0 0 3 0 0 1 0" , "0 5 3 0 0 4 0 0 2", "0 0 0 0 0 0 3 5 0", "0 9 8 0 0 7 0 0 0"] def sudoku(): input = value + [] for r in range(9): for c ...
import sys line = sys.stdin.read().split() a = [] for word in line: if "@" in word: name = word.split("@") a.append(name[0]) for name_sur in a: name_sur = name_sur.split(".") print(name_sur[0].capitalize(), name_sur[1].capitalize())
import rospy import roslib roslib.load_manifest("robot_comm") from robot_comm.srv import * class Manipulator(object): def factory(type): if type == "abb120_mlab": return Abb120MLab() if type == "abb120_mcube": return Abb120MCube() assert 0, "Bad robot type: " + type factory = staticmeth...
# -*- coding: utf-8 -*- import time from tf_summary_reader.get_summary_data import get_summary_data def read_summary_data_periodically(summary_dir, time_interval_in_seconds=10): while True: result = get_summary_data(summary_dir) yield result time.sleep(time_interval_in_seconds)
zoo = ('dog', 'cat', 'elephant') new_zoo = ('monkey', 'camel', zoo) print('zoo length: ',len(zoo)) print('the last animal about old zoo is', new_zoo[2][2]) # len == 1的元组 tuple_len1 = ('a',) print(type(tuple_len1)) print('len: ', len(tuple_len1)) # len, 1
"""自定义通用模型字段""" from uuid import uuid4 from django.db import models from django.conf import settings from model_utils.models import TimeFramedModel as MUTimeFramedModel class UUIDModel(models.Model): """uuid""" id = models.CharField(verbose_name='id', max_length=32, default=uuid4().hex, primary_key=True, uniq...
#1 Manual way print('='*15,"#1","="*15) def doubleStuff(a_list): #return a new list in which contains doubles of the elements is a_list. new_list = [] for value in a_list: new_element = 2* value new_list.append(new_element) return new_list things = [2,5,9] print(things) things = double...
# Copyright 2013 by Allen Hubbe. All Rights Reserved. '''A priority queue implemented as a heap.''' from . import heap_alg from operator import le, ge __all__ = [ 'heap' ] def _no_get_pos(item): raise LookupError('no get_pos') _no_set_pos = heap_alg._no_set_pos def _identity(item): return item class heap(obj...
# -*- coding: utf-8 -*- # Generated by Django 1.11.13 on 2018-06-10 19:57 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('liveedu_project', '0002_rating'), ] operations = [ migrations.AddField( ...
import time import random a = set() a.add(1) a.add(2) a.add(3) b = set() b.add(2) b.add(3) b.add(4) c = a.union(b) print len(c)
#!/usr/bin/env python import sys class Clump_finding: # k: länge kmer L: länge interval t: menge der Kmere def __init__(self, params): # argv muss 9 elementig sein sonst sind zu viele ode zu wenige Paramenter angegeben if len(params) != 9: print('Wrong input') ...
''' This program is set up to read the json files written during our PyXSPEC runs. ex: filename = '/Users/KimiZ/GRBs2/analysis/LAT/%s/PYXSPEC/%s/%s/xspec_modelreload_%s_%s_%s_.json'%(burst, detdir, model, model, version, det) The results from each PyXspec run are saved in these files as a dictionary of model comp...
""" Definition of Interval. class Interval(object): def __init__(self, start, end): self.start = start self.end = end """ class Solution: """ @param intervals: interval list. @return: A new interval list. """ def merge(self, intervals): # write your code here i...
import sys reload(sys) sys.setdefaultencoding('utf-8') import requests import json import time import math import csv from haversine import haversine def changeTime(allTime): # convert seconds into day, hour, minute day = 24*60*60 hour = 60*60 min = 60 if allTime <60: ret...
from datetime import datetime from sqlalchemy import create_engine engine = create_engine('postgresql://yugabyte@localhost:5433/bi_automation') conn = engine.connect() def id_generate(): newimport_id = lambda : str(datetime.now().year)+(str(datetime.now().month).zfill(2))+'01' getid = 'select max(import_id) fr...
#!/usr/bin/python # coding: utf-8 L = ['Toyota', 'Nissan', 'Honda'] # リストを作成 for x in L : print x print '===' # 要素数をスキップ for x in L[2:]: print x print '===' x = range(10) print x print '===' x = range(5,10) print x print '===' for i in range(5): print i print '===' for i in range(1,10): for j in range(1...
import numpy as np with open("8_image.txt", "r") as f: content = f.read().strip("\n") array = np.reshape([int(i) for i in content], (-1, 6, 25)) print("Array shape:", array.shape) max_zero = array.shape[1] * array.shape[2] index = -1 for i in range(array.shape[0]): r = (array[i, :, :] == 0).sum() if r < ...
from string import ascii_lowercase def is_isogram(word): word = word.lower() repeats = {} for letter in word: if letter in ascii_lowercase: if letter in repeats: return False else: repeats[letter] = 1 return True
import json import unittest from json_fingerprint import _validators, create, exceptions, hash_functions class TestValidators(unittest.TestCase): def test_json_fingerprint_version(self): """Test JSON fingerprint FingerprintVersion exception. Verify that: - FingerprintVersion exception is...
from __future__ import division, print_function, absolute_import import argparse # import seaborn import sklearn import sklearn.linear_model import sklearn.ensemble from sklearn.metrics import roc_curve, roc_auc_score import numpy as np import pylab as plt from helpers import roc_auc, class_prob import data import c...
import bpy from bpy.props import * from bpy.types import Node, NodeSocket from arm.logicnode.arm_nodes import * class GetNameNode(Node, ArmLogicTreeNode): '''Get name node''' bl_idname = 'LNGetNameNode' bl_label = 'Get Name' bl_icon = 'QUESTION' def init(self, context): self.inputs.new('Ar...
from badge import oled, btn, readConfig, writeConfig, wlan from urandom import getrandbits from ubinascii import a2b_base64, b2a_base64, hexlify import socket import ujson import gc import network import machine def app_start(): oled.fill(0) oled.hctext('C01N Config',0,1) oled.fill_rect(0,55,128,9,1) oled.hctext('...
import rest_framework_filters from rest_framework_filters.filterset import FilterSetMetaclass class FilterSetNkg(rest_framework_filters.FilterSet, metaclass=FilterSetMetaclass): def filter_queryset(self, queryset): """ Provide support for: ``view.fieldset_computed_fields`` """ ...
import os import torch import pprint from nnlib.utils import dist from nnlib.utils.config import get_config from nnlib.utils.common import get_logger, set_random_seed from nnlib.models.builder import build_model from nnlib.datasets.builder import build_dataloader from eval_utils.trajectory_prediction import eval_traj...
from django.shortcuts import redirect, render, get_object_or_404 from onlineshop.models import Product from django.views.decorators.http import require_POST from django.contrib.auth.decorators import login_required from .cart import Cart from .forms import CartAddProductForm, CheckOutForm, PaymentForm from django.contr...
class Solution(): def maxDepth(self, root): """ :type root: TreeNode :rtype: bool """ if not root: return 0 depth = 0 current_level = [root] while current_level: depth += 1 next_level = [] for node in ...
import pymysql as pm try: con =pm.connect(host='localhost', database='Amita', user='root',password='root') cursor= con.cursor() query="select * from Authors" cursor.execute(query) data=cursor.fetchall() for row in data: print("Authors_Title_ID:{},AuthorID:{},TitleID:{}".format(row[0],row...
import os import argparse from tensorflow import lite import tensorflow.keras as k def parse_args(): # Parse input arguments parser = argparse.ArgumentParser( description="Convert keras model to tflite") parser.add_argument('--model_filename', help='name of the h5 file', ...
#This is a Lib test print('Hello World') def Hello(): print('Hi') def Test(): print('Test!') if __name__ == '__main__': Test()
from __future__ import print_function from PIL import Image from os.path import join import os from scipy.io import loadmat import torch.utils.data as data from torchvision.datasets.utils import download_url, list_dir, list_files class celebrity(data.Dataset): """IMDB-wiki Celeb Face Age Dataset""" """ Arg...
""" Image utils ~~~~~~~~~~~ """ import cv2 import numpy as np def imencode(arr: np.ndarray, ext='.png') -> str: """ Encodes numpy.ndarray into string :param numpy.ndarray arr: numpy.ndarray of an image :param ext: :return: encoded string :rtype: str """ return cv2.imencode(ext...
from PyQt5 import QtWidgets, QtCore from utils import utils_collection as utils from utils import db_manager from utils.styling import generic_title_style from widgets.spec_fields import AutocapField from widgets.message_boxes import QuestionBox, InformationBox class DeleteRecipeDialog(QtWidgets.QDialog): def __i...
import argparse def main(args): print(args) if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--algorithm", "--a", choices=["all", "kmeans", "k++", ], required=True) parser.add_argument("--mode", "--m", choices=["bench", "one"], required=True) parser.add_argument...
import codecs import os import sys from setuptools import find_packages, setup def read(fname): file_path = os.path.join(os.path.dirname(__file__), fname) return codecs.open(file_path, encoding="utf-8").read() with open("requirements.in") as f: install_requires = [line for line in f if line and line[0]...
#!/usr/bin/env python3 #create a list with three items my_list = [ "192.168.0.5", 5060, "UP" ] #display the first item print("The first item in the list (IP): " + my_list[0]) #display the second item and convert to a string print("The second item in the list (port): " + str(my_list[1]) ) #display the third item print(...