text
stringlengths
8
6.05M
# 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 "License"); you may not use ...
def sort_by_height(a): indices = [c for c,x in enumerate(a) if x==-1] output = sorted(a)[len(indices):] for x in indices: output.insert(x, -1) return output ''' Task Some people are standing in a row in a park. There are trees between them which cannot be moved. Your task is to rearrange the...
def group_letter_check(S): letter = [] letterTF = [] then = 1 for i in S: if i not in letter: letter.append(i) letterTF.append(True) if len(letterTF) != 1: letterTF[letter.index(i)-1] = False elif i in letter and letterTF[letter.index(i...
class solution: def isSubsequence(self, s, t):
# 今年一定要美好!!! # 1. 暴力枚举 + set去重 class Solution: def longestNiceSubstring(self, s: str) -> str: def check(s : str)->bool: n1, n2 = len(set(s)), len(set(s.lower())) if n1 == n2*2: return True else: return False maxl, n = -1, len(s)...
import functools import inspect from ..session import api_session, AsyncSession __all__ = ( 'APIFunctionMeta', 'BaseFunction', 'api_function', ) def _wrap_method(cls, orig_name, meth): @functools.wraps(meth) def _method(*args, **kwargs): # We need to keep the original attributes so that...
import logging, os, gensim from collections import defaultdict import re logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO) directory = './dataset/train' class MySentences(object): def __iter__(self): for filename in os.listdir(directory): data = open(directory+'/'+filena...
from string import ascii_uppercase AZ = dict(zip(ascii_uppercase, xrange(1, 27))) def product_mod_47(seq): return reduce(lambda a, b: a * b, (AZ[c] for c in seq)) % 47 def ride(group, comet): return 'GO' if product_mod_47(group) == product_mod_47(comet) else 'STAY'
'''Objects/Classes Experiment''' # Developed by Smit Rao class Locker(object): '''A locker object.''' def __init__(self, status='Closed'): self.status = status def open(self): self.status = 'Open' def close(self): self.status = 'Closed'
def makebold(fn): def wrapped(): return "<b>" + fn() + "</b>" return wrapped def makeitalic(fn): def wrapped(): return "<i>" + fn() + "</i>" return wrapped @makebold @makeitalic def hello(): return "hello habr"
__author__ = 'iceke' import urllib2 from stage import Stage from bs4 import BeautifulSoup from spark_data import SparkData from worm import Worm from util import Util def main(): stage_url = 'http://192.168.226.211:8012/stages/' gc_html = Worm.get_html(stage_url+'stage/?id='+str(1)+'&attempt=0', True) gc_...
from battle.battleeffect.BattleEffect import BattleEffect class RunAction(BattleEffect): def __init__(self, source_fighter): self.source_fighter = source_fighter self.effect_type = None def get_battle_text(self): return self.source_fighter.name + " tried to run... but couldn't!!" ...
from itertools import islice def solution1(input): ret = 0 cc = next(input) mc = next(input) if cc is None or mc is None: return ret ret += sum(solution1(input) for _ in range(cc)) ret += sum(islice(input, mc)) return ret def parse_input1(input): return map(int, input.split(...
import sys sys.path.insert(0, 'tools/publications_generax/utils_plots') import plot_rrf import plot_scaling import plot_boxplots import plot_runtimes import plot_ll if (__name__ == "__main__"): plot_rrf.plot_simulated_metrics() #plot_rrf.plot_simulated_metrics_ils() #plot_scaling.plot_scaling() #plot_boxp...
""" Kept for Django purposes """
from matplotlib import pyplot as plt import tensorflow as tf from sklearn.metrics import f1_score, roc_auc_score, accuracy_score import tensorflow.keras as keras import tensorflow.keras.layers as layers from tensorflow.keras import activations from tensorflow.keras.datasets import mnist from tensorflow.keras.models imp...
import os import csv from django.core.management.base import BaseCommand from geofr.models import Perimeter # Field column indexes NAME = 2 DEPARTMENT = 0 CODE = 1 MEMBER = 9 DRAINAGE_BASINS = { 'FR000001': 'Rhin-Meuse', 'FR000002': 'Artois-Picardie', 'FR000003': 'Seine-Normandie', 'FR000004': 'Loi...
from openerp.osv import osv, fields class res_company(osv.osv): _inherit = 'res.company' _columns = { 'account_expense_id': fields.many2one('account.account', u'Conta Despesa Padrao',domain="[('type','=','other'),('user_type.code','=','expense')]"), 'account_revenue_id': fields...
import multiprocessing from multiprocessing import Queue, Pool import cv2 from src.FPS import FPS from src.WebcamVideoStream import WebcamVideoStream from src.ObjectDetection import ObjectDetection class Realtime: """ Read and apply object detection to input video stream """ def __init__(self, args)...
import torch as tc import torchvision.datasets as dsets import torchvision.transforms as transforms from torch.utils.data import DataLoader import torch.nn as nn import matplotlib.pyplot as plt import random USE_CUDA=tc.cuda.is_available() device=tc.device("cuda"if USE_CUDA else "cpu") print("asdf:",device) random.seed...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __version__ = '1.0.1' from sanic.log import logger from sanic.request import Request from .specification.get_notification_type_specification import get_notification_type_list_query __all__ = [ # SERVICES WORKING ON LANGUAGE TABLE 'get_notification_type_list' ] ...
#!/usr/bin/python2 # -*- coding: ascii -*- # Ledger Capture The Flag 2018 Challenge 3 # Copyright (C) 2018 Antoine FERRON - BitLogiK from ECDSA_BTC import * from ECDSA_256k1 import * load_gtable('G_Table') import base64 # Check the validity of the example msgAlice = "Amount:42 From:1Ppecdv2jWjZjdSJjnQs5JaGhethCsdT...
################################################################################ # # # CALCULATE TIME-DEPENDENT AND TIME-AVERAGED QUANTITIES # # ...
import json www=[] file=open('C:\Users\lenovo\PycharmProjects\user\movieplus.json','r+',encoding='utf-8') for line in file.readlines(): we=json.loads(line) print(we) www.append(we) result=[] for le in www: if le not in result: result.append(le) print(len(result)) print(result[0]) for item in re...
import cv2 # 需要裁剪的图片路径 infile = '/home/asimov/PycharmProjects/DataMining/深度学习/RNN/testimages/31.jpg' # 裁剪后图片的保存路径 outfile = '/home/asimov/PycharmProjects/DataMining/深度学习/RNN/cut_imgs/31.jpg' # 目标裁剪图片的宽和高 weight = 28 hight = 28 crop_size = (weight, hight) img = cv2.imread(infile) img_new = cv2.resize(img, crop_size, i...
#!/opt/csw/bin/python3 """ This script will move files to the FTP server. """ import argparse from Ftp_Handler import Ftp_Handler from lib import my_env # Initialize Environment projectname = "mowdr" modulename = my_env.get_modulename(__file__) config = my_env.get_inifile(projectname, __file__) my_log = my_env.init_...
# -*- coding: utf-8 -*- from typing import List class Solution: def average(self, salary: List[int]) -> float: return (sum(salary) - min(salary) - max(salary)) / (len(salary) - 2) if __name__ == "__main__": solution = Solution() assert 2500.0 == solution.average([4000, 3000, 1000, 2000]) a...
# -*- coding: utf-8 -*- """ Created on Tue Jul 14 11:17:20 2020 @author: anusk """ import numpy as np import math import cv2 def dftuv(M, N): u = np.arange(M) v = np.arange(N) idx = np.nonzero(u > M/2) u[idx] = u[idx] -M idy = np.nonzero(v > N/2) v[idy] = v[idy] -N V, U = np.meshgrid...
import numpy as np from scipy.sparse import lil_matrix, csc_matrix from scipy.sparse.linalg import spsolve import matplotlib.pyplot as plt import matplotlib # Define geometry nodes = np.array([[0, 0], [1, 0], [0.5, np.sqrt(3)/2]]) elements = np.array([[0, 1], [1, 2], [2, 0]]) # Material properties E = 210000 # Young...
"""check the weather""" from typing import Union import requests from wechaty import Message, Contact, Room from wechaty.plugin import WechatyPlugin class WeatherPlugin(WechatyPlugin): """weather plugin for bot""" @property def name(self) -> str: """get the name of the plugin""" return '...
class Solution(object): def detectCapitalUse(self, word): c = 0 for i in word: if i == i.upper(): c += 1 return c == len(word) or (c == 1 and word[0] == word[0].upper()) or c == 0
import cv2 import sklearn import numpy as np from sklearn.model_selection import train_test_split from sklearn.neural_network import MLPClassifier fotosRecopiladas = {} BDFotos = [] fotoMessi = cv2.imread('messi3_rostro.jpg', cv2.IMREAD_GRAYSCALE) fotoMessi = cv2.resize(fotoMessi, (300, 300)) fotoMessi = np.array(fot...
# Web streaming example # Source code from the official PiCamera package # http://picamera.readthedocs.io/en/latest/recipes2.html#web-streaming import io import picamera import logging import socketserver import sys from http import server from dotenv import dotenv_values from threading import Condition import asynci...
import tensorflow as tf import numpy as np from tensorflow import keras import matplotlib.pyplot as plt data = keras.datasets.fashion_mnist (train_images,train_labels),(test_images,test_labels) = data.load_data() train_images = train_images/255.0 #divide the numbers so, the rbg value ranges towards 0 an...
import redis client = redis.Redis() client.hset('users:123', 'name', 'aan'.encode('utf-8')) client.hset('users:123', 'email', 'aan@mail.com'.encode('utf-8')) client.hset('users:123', 'dob', '1990-09-09'.encode('utf-8')) print(client.hgetall('users:1234')) print(client.hget('users:123', 'name')) print(client.hget('u...
# Copyright 2022 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import annotations import json import subprocess from typing import Iterable BASH_COMPLETION_TEMPLATE = """# DO NOT EDIT. # This script is autogenerated by build-support/...
emplist = ['John', 'David', 'Mark', 'Mike', 'James', 'Curry'] name = 'Maninder Singh' # Indexing or Subscription operation print("Employee 0 is {}.".format(emplist[0])) print("Employee 1 is {}.".format(emplist[1])) print("Employee 2 is {}.".format(emplist[2])) print("Employee 3 is {}.".format(emplist[3])) print("\nEm...
ang=str(input()) fo=ang[::-1] print(fo)
# Generated by Django 3.0.5 on 2020-08-11 06:13 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('register', '0002_attendance'), ] operations = [ migrations.AlterField( model_name='employee', name='city', ...
from flask import Markup if __name__ == '__main__': print(Markup('<strong>Hello {}!</strong>'.format('<blink>hacker</blink>'))) print(Markup.escape('<blink>hacker</blink>')) print(Markup('<em>Marked up</em> &raquo; HTML').striptags())
from django.contrib import admin from .models import Profile, Technologie, App, Note, BuildLink # Register your models here. admin.site.register(Profile) admin.site.register(Technologie) admin.site.register(App) admin.site.register(Note) admin.site.register(BuildLink)
#!/usr/bin/env python # -*-encoding:UTF-8-*- from django.conf.urls import url from ..views.vicqbpmssoj import ProblemTagAPI, ProblemAPI, ContestProblemAPI, PickOneAPI # 普通用户查看:题目标签、查看题目、pickone、查看比赛问题 urlpatterns = [ url(r"^problem/tags/?$", ProblemTagAPI.as_view(), name="problem_tag_list_api"), url(r"^proble...
from collections import namedtuple from functools import lru_cache from itertools import groupby from operator import itemgetter # small utility function for generating translation dicts groupdict = lambda tupgen: {k: [v for _k,v in vs] for k,vs in groupby(sorted(tupgen, key=itemgetter(0)), key=itemgetter(0))} clas...
import random class ComputerPlayer(): backgammon = None currentBoard = None dice = None colour = None howGood = 0 playerMove = 0 playerPosition = 0 def __init__(self,backgammon,currentBoard,dice,colour,howGood): self.backgammon = backgammon self.currentBoard = currentB...
#!/usr/bin/env python3 """Includes execution of classification algorithms from skicit learn package. Usage: python3 words.py <URL> """ import numpy as np from sklearn.model_selection import train_test_split from sklearn.decomposition import PCA def execute_classification(clf, data, target, split_ratio): "...
# /* # Copyright 2011, Lightbox Technologies, Inc # # 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 b...
vel = int(input('Digite a velocidade do carro: ')) if(vel > 80): multa = (vel - 80)*7 print('Você foi multado no valor de R${}.00'.format(multa)) else: print('Você está dentro do limite de velocidade.')
# Generated by Django 2.2.6 on 2021-01-26 16:34 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('consumers', '0015_auto_20200602_1252'), ] operations = [ migrations.AddField( model_name='consumer', name='division'...
import sympy def error(f, err_vars=None): from sympy import Symbol, latex s = 0 latex_names = dict() if err_vars == None: err_vars = f.free_symbols for v in err_vars: err = Symbol('latex_std_' + v.name) s += f.diff(v)**2 * err**2 latex_names[err] = '\\sigma_{' + la...
#!/usr/bin/env python3 import os from ..lib import utils ''' desc: get infomation of openssl - NAME/SYNOPSIS/DESCRIPTION/RETURN VALUES/NOTES/BUGS/SEE ALSO ''' # doc_dir - the storage directory of data def handle_openssl(doc_dir): print("===============================================") print("==== ...
# coding=utf-8 from ctypes import * from ft232.dll_h import * import logging class FT232: def __init__(self): self.ft232 = windll.LoadLibrary('ftd2xx.dll') self.handle = None # description:str, serialnum:str, location:int def open(self, description=None, serialnum=None, locati...
from bs4 import BeautifulSoup from lxml import html import pandas as pd import webbrowser import requests import datetime import json import time import csv import sys import re import os #---------------------InitializeValue-------------------------- url = 'http://edu.kiau.ac.ir' user =...
# -*- coding: utf-8 -*- # Module author: @dekftgmodules, @ftgmodulesbyfl1yd # requires: pydub numpy requests import io import math import os import requests import numpy as np from pydub import AudioSegment, effects from telethon import types from .. import loader, utils @loader.tds class AudioEditorMod(loader.M...
#!/usr/bin/python import numpy as np import pylab as py import os,sys from COMMON import mpc, light, grav, msun, yr, nanosec, week import mpmath #from time import time ############################################################################ #INPUT PARAMETERS: case='detection' #For 'upper_limit', the FAP will be 40...
#!/usr/bin/python from glob import glob from math import pi, sqrt import numpy as np import pickle from pyrosetta import * from pyrosetta.rosetta.core.scoring.dssp import Dssp from pyrosetta.rosetta.core.scoring import rmsd_atoms from pyrosetta.rosetta.core.scoring import superimpose_pose from pyrosetta.rosett...
import classes as Classes from copy import deepcopy aux = 90 while(aux!=None): print("1") aux = None a = 'aa' print(not(type(a) is str)) print(type(a))
from django import forms from .models import data, steps class creatation(forms.Form): title = forms.CharField(label='Tiêu đề', max_length=100) author = forms.CharField(label='Tác giả', max_length=20) step1 = forms.CharField(label='Bước 1', max_length=300) #img1 = forms.ImageField(label='Ảnh minh họa')...
class EmailService(object): EMAIL_SERVER={ "QQ":{"SMTP":["smtp.qq.com",465,True],"POP3":["pop.qq.com",995,True],"IMAP":["imap.qq.com",993,True]}, "GMAIL":{"SMTP":["smtp.gmail.com",465,True],"POP3":["pop.gmail.com",995,True],"IMAP":["imap.gmail.com",993,True]}, "FOXMAIL":{"SMTP":["SMTP.foxmai...
#!/usr/bin/env python3 ''' leetCode 1071. Greatest Common Divisor of Strings https://leetcode.com/problems/greatest-common-divisor-of-strings/ ''' class Solution(object): ''' def __init__(self,name,score): self.str1 = str1 self.str2 = str2 ''' def gcdOfStrings(self, str1, str2):...
''' ''' import gtk import vwidget.main as vw_main import vwidget.memview as vw_memview import visgraph.layouts.dynadag as vg_dynadag import visgraph.renderers.gtkrend as vg_rend_gtk import vwidget.menubuilder as vw_menu import vivisect.gui as viv_gui import vivisect.base as viv_base import vivisect.renderers as viv...
class RC4: S = [None] * 256 byte_to_int_mask = 255 max_key = 16 x = 0 y = 0 def set_key(self,key,offset=0): if key is None or len(key) < self.max_key: raise ValueError("Key length must be "+str(self.max_key)) #initalizing the S arrays for i in range(256): self.S[i] = i #swapping around/mixing ...
Input_Config ={ 'firstname' : ['get_name_real'], 'first_name' : ['get_name_real'], 'lastname' : ['get_name_real'], 'last_name' : ['get_name_real'], 'address' : ['apt_get'], 'homephone' : ['get_phone','get_phone_plus1','get_phone_3','get_phone_6','get_phone_10'], 'home_phone' :...
class Solution: """ https://leetcode.com/problems/reverse-bits/ """ def reverseBits(self, n: int) -> int: p = c = 0 while (n): x = n%2 p = p<<1 | x # or, ret += (n & 1) << power n = n >> 1 c += 1 for i in range(c, 32): ...
#The loop variable keeps the last value after the loop is over. # You may want to know about this behaviour, but it is better not to count on this in real programs. a=["din","kum","dha"] for i in a: print(i) print(i) #last element
from unittest.mock import Mock from model.event.event_bus import EventBus class TestEventBus: def test_bind_registers_event(self): event_bus = EventBus() event_name = 'event 1' callbacks = [Mock(), Mock(), Mock()] for callback in callbacks: event_bus.bind(event_name, ...
## Create directory path import os dataset_path = '/home/aaditya/Bach10/' song_paths = [] for song_name in os.listdir(dataset_path) : if (song_name != '.DS_Store') : song_paths.append(dataset_path + song_name + '/') length = len(song_paths) song_paths = sorted(song_paths) print(song_paths) ## Create directories m...
''' Created on 24 Jan 2016 @author: craig ''' from iFixList import IFixList from addBehavior import AddBehavior class OrdersList(IFixList, AddBehavior): ''' classdocs ''' def __init__(self): self.idName = "ProductId" self.idQ = "Quantity" self.idCost = "UnitCost" se...
#------------------------ FUNCTION DEFINITIONS ------------------------------ def compute_confusion_matrix(y_pred, y_true): """ 'y_pred' is ndarray of predicted category probabilities 'y_true' is ndarray of true labels Returns a type of confusion matrix comparing 'cats' vs. 'polygons' 'polyg...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = 'Tan Chao' ''' logger wrapper. use dictConfig. ''' import logging import logging.config import yaml def testLogging(): with open('dictconfig.yaml') as f: dict_config = yaml.load(f) logging.config.dictConfig(dict_config) logger1 = logging.getLogger...
from typing import Callable, Union from numbers import Number from phi import math from ._field import Field from ..geom import Geometry from phiml.math import Shape, spatial, instance, Tensor, wrap class AngularVelocity(Field): """ Model of a single vortex or set of vortices. The falloff of the velocit...
#!/usr/bin/python # calcualtes supervised weighted knn baseline from sparse format # This code does not handle tie cases import sys import gzip import pprint import collections as col; def map_keyfile(fname, withtags=False): #returns: dd:index-> word array maps:?? keys: index->key from ptb formated file #<s> ...
from fact import * def fib(x): j = 0 n = 1 print(j) print(n) for i in range(2,x): r = j+n j = n n = r print(r) fact(10)
import tkinter as tk from src.library import Library class GUI: def __init__(self, master): self.master = master self.library = Library() self.create_window() self.create_mainpage() def create_window(self): self.master.title("Game Manager") self.master.geometry(...
# function: transformation # version: v02 # input: before_transformation(), type # 0 for row Exchange # 1 for right circular Shift # 2 for middle clockwise rotation # output: after_transformation() # description: # this funtion will manipulate current_state # initial state 1 2 ...
hourlyRate = 10 hoursWorked = 34 weeklyWage = hourlyRate*hoursWorked print('Wages for\nFred\nFlintstone:', end='\n') print('Hourly Rate: $%d\nHours Worked: %d\nWeekly Wage: $%d' % (hourlyRate, hoursWorked, weeklyWage))
from django.contrib import admin from .models import SocialNetwork, TeamMember, MemberSocialNetwork # Register your models here. class MemberSocialNetworkInLine(admin.TabularInline): """ Inline admin for Social Network relation """ model = MemberSocialNetwork class MemberAdmin(admin.ModelAdmin): ...
import tkinter from torch.nn.utils.rnn import * import torch import torch.nn as nn import numpy as np import torch.nn.functional as F # # lst = [] # # lst.append(torch.randn((1, 4))) # lst.append(torch.randn((3, 4))) # lst.append(torch.randn((5, 4))) # # sort_list = lst # # sort_list = sorted(lst, key=len, reverse=Tru...
import os import time import json import pickle import logging from filelock import FileLock import torch import numpy as np from transformers import PreTrainedTokenizerBase logger = logging.getLogger(__name__) class TextDataset(torch.utils.data.Dataset): def __init__(self, tokenizer: PreTrainedTokenizerBase, f...
# I pledge my honor that I have abided by the Stevens Honor System. Andrew Ozsu def function(x): for i in range(len(x)): x[i]=x[i]*x[i] return (x)
import gevent from arago.actors.monitor import Monitor from arago.actors.actor import Task, ActorStoppedError class Router(Monitor): def _route(self, msg): """Override in your own Router subclass""" raise NotImplementedError def _forward(self, task): try: target = self._route(task) self._logger.trace("{...
""" Module that calculates the number of hunks made to a commit file. """ from statistics import median from pydriller import ModificationType from pydriller.metrics.process.process_metric import ProcessMetric class HunksCount(ProcessMetric): """ This class is responsible to implement the Number of Hunks met...
import requests import json import urllib import warnings import os from ._exceptions import * warnings.formatwarning = warning_format class here_API: def __init__(self, apiKey=None, credentials_file=None): if (apiKey is None) and (credentials_file is None): raise CredentialsMissing() ...
#!/usr/bin/python import sys, os; argvs = sys.argv; argc = len(argvs); prefix = ""; if argc > 1: prefix = argvs[1] + "_"; for i in range(7, 16): os.system("./calc.k " + prefix + "bt" + str(i) + ".log");
import argparse import pickle from drive_mix_v2 import DrivingMix2 import numpy as np import pandas as pd import time # Different ethical state for the negative, positive and mixed policies, but same general state for learning parser = argparse.ArgumentParser(description='ethical agent') parser.add_argument('--p_eth...
import sys data = sys.stdin.readline() data = ord(data[0]) minVal1 = ord("A") maxVal1 = ord("Z") minVal2 = ord("a") maxVal2 = ord("z") if data >= minVal1 and data <= maxVal1: print(chr(data+32)) elif data >= minVal2 and data <= maxVal2: print(chr(data-32)) else : print("문자만 입력하세요")
#!/usr/bin/python from statistics import mean num=input("Enter set of numbers to find average:") res=[int(x) for x in str(num)] #res=[num] a=mean(res) print(a)
import time import logging from parser import DefaultParser from fetcher import DefaultFetcher, HttpsFetcher from logger import set_up_logging logger = set_up_logging() class Crawler: '''Crawl a set to urls. Long description ''' def __init__(self, roots, exclude=None, strict=True, ...
def is_coprime_phi(phi, coprime_to_check): while phi % coprime_to_check == 0: coprime_to_check = input("Enter a prime number, to check if coprime with phi") e = coprime_to_check return True if not is_coprime_phi(phi,e): raise ValueError("e is not coprime with phi_n") def egcd(x, y): ...
from tkinter import Button, Label, Frame, Tk, RAISED, NSEW, Entry import os from functions import (add_as_dict, check_file_exists, verify_not_empty, add_in_freq, only_number) from html_func import update_table from datetime import datetime import time __location__ = os.path.realpath(os.p...
__author__ = 'luca' from videos.video import Video from images.image_comparator import ImageComparator class VideoComparator(object): def __init__(self, video, searcher): self._video = video self._searcher = searcher def compared_frames_statuses(self, motion_threshold, MAD_threshold): ...
# Generated by Django 3.0.3 on 2020-07-30 09:44 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('contactapp', '0003_auto_20200730_1511'), ] operations = [ migrations.AlterField( model_name='person', name='email', ...
from sklearn.metrics import accuracy_score from sklearn.datasets import load_digits from sklearn.model_selection import train_test_split from sklearn.linear_model import LogisticRegression from sklearn.metrics import confusion_matrix digits = load_digits() y = digits.target == 8 X_train, X_test, y_train, y_te...
""" 添加人员 """ # from app.企业微信.page.contactAddPage import ContactAddPage from appium.webdriver.common.mobileby import MobileBy from app.企业微信po.page.basepage import BasePage class AddMeberPage(BasePage): # def __init__(self,driver): # self.driver = driver add_manual_element = (MobileBy.XPATH, "//*[@text...
#This file is part of AstroHOG # # Copyright (C) 2013-2017 Juan Diego Soler import sys import numpy as np from astropy.io import fits import matplotlib.pyplot as plt sys.path.append('/Users/jsoler/Documents/astrohog/') from astrohog import * from astropy.wcs import WCS from reproject import reproject_interp def ast...
from setuptools import setup, find_packages from os.path import join, dirname with open(join(dirname(__file__), 'README.rst')) as f: readme_text = f.read() setup( name="everypolitician-popolo", version="0.0.11", packages=find_packages(), author="Mark Longair", author_email="mark@mysociety.org"...
#!/usr/bin/env python3 """Script to find all alarms which do not conform to the current naming scheme and delete them.""" import os import boto3 from botocore.exceptions import ClientError import logging FORMAT = '%(asctime)-15s %(levelname)s %(module)s.%(funcName)s %(message)s' DATEFMT = "%Y-%m-%d %H:%M:%S" logging.b...
SAVE_COMMENT_DIR = r'D:\MongoDB\savejson\comment' SAVE_NEWS_DIR = SAVE_COMMENT_DIR if __name__=='__main__': import pymongo client = pymongo.MongoClient('mongodb://localhost:27017/') db = client['cocoke'] news = db['news'] nt = db['news_table'] cs = db['comments'] comment = db['comment'] ...
import os import logging import threading import pygame # Import this when building for mac #import pygame._view import random from socket import * import base64 try: import android except ImportError: android = None if not android: import yaml from sound import Sound from graphics import widgets, men...
from django.contrib import admin from .models import Product, ProductGallery, ProductComment from django.contrib import messages from django.utils.translation import ngettext # Register your models here. class ProductAdmin(admin.ModelAdmin): list_display = ['__str__', 'thumbnail_pic', 'price', 'slug', 'active',...
# Day 12: Inheritance # Delving into Inheritance # Given two classes with templates, Person and Student, # complete the Student class. # Grading sale: T >= 0, D >= 40, P >= 55, A >= 70, E >= 80, and O >= 90 <= 100 # constructor with first name, last name, id, and array of test scores. # Write a method that calculate...