index
int64
0
1,000k
blob_id
stringlengths
40
40
code
stringlengths
7
10.4M
4,600
7fd5e83d28e919e7b94cea290c6b4db3378938b6
from fastapi import APIRouter, Depends, status, Response from typing import List import schemas, database from sqlalchemy.orm import Session import repository.blog as blog from .oauth2 import get_current_user router = APIRouter( prefix="/blog", tags=['Blog']) @router.get('/', status_code=statu...
4,601
f7d29dd1d990b3e07a7c07a559cf5658b6390e41
#create a list a = [2,3,4,5,6,7,8,9,10] print(a) #indexing b = int(input('Enter indexing value:')) print('The result is:',a[b]) print(a[8]) print(a[-1]) #slicing print(a[0:3]) print(a[0:]) #conconteation b=[20,30] print(a+b) #Repetition print(b*3) #updating print(a[2]) a[2]=100 print(a) #membership print(5 in a) ...
4,602
62fe29b0ac4dee8fec4908cf803dba9bd7e92fa5
from tkinter import * from get_train_set import * from datetime import * counter = 0 week = int ( datetime.today().isocalendar() [1] ) def update (a,b): global counter if b == 'x': b = 0 a = week counter = 0 else: counter += b a += counter ...
4,603
7474e60feff61c4ef15680ecc09d910e6e1d6322
def IsPn(a): temp = (24*a+1)**0.5+1 if temp % 6 == 0: return True else: return False def IsHn(a): temp = (8*a+1)**0.5+1 if temp % 4 == 0: return True else: return False def CalTn(a): return (a**2+a)/2 i = 286 while 1: temp = CalTn(i) if IsHn(temp) and IsPn(temp): break i += 1 print i,temp
4,604
f56978d5738c2f8cb4ed5ce4f11d3aae6a9689b1
import datetime class Schedule: def __init__(self, start, end, name, other): # Constructor self.start = self.str_convert(start) # Schedule start time (ex. 9:00) self.end = self.str_convert(end) # Schedule end time (ex. 22:00) ...
4,605
3923aed29006b4290437f2b0e11667c702da3241
# %% import numpy as np import pandas as pd import tensorflow as tf import matplotlib.pyplot as plt import seaborn as sns from sklearn.manifold import TSNE from sklearn.decomposition import PCA, TruncatedSVD import matplotlib.patches as mpatches import time from sklearn.linear_model import LogisticRegression from skle...
4,606
97637e2114254b41ef6e777e60b3ddab1d4622e8
from django.forms import ModelForm from contactform.models import ContactRequest class ContactRequestForm(ModelForm): class Meta: model = ContactRequest
4,607
cca543f461724c3aac8fef23ef648883962bd706
from os import getenv LISTEN_IP = getenv('LISTEN_IP', '0.0.0.0') LISTEN_PORT = int(getenv('LISTEN_PORT', 51273)) LISTEN_ADDRESS = LISTEN_IP, LISTEN_PORT CONFIRMATION = getenv('CONFIRMATION') if CONFIRMATION: CONFIRMATION = CONFIRMATION.encode() class UDPProtocol: def __init__(self, consumer): self...
4,608
0a7a95755924fd264169286cc5b5b7587d7ee8e4
import turtle import math from tkinter import * #活性边表节点: class AetNode(object): def __init__(self,x,tx,my): self.x=x self.tx=tx self.my=my def op(self): return self.x class AetList(object): def __init__(self,y): self.y=y self.numy=0 self.l=[] p...
4,609
a8fb8ac3c102e460d44e533b1e6b3f8780b1145d
# Downloads images from http://www.verseoftheday.com/ and saves it into a DailyBibleVerse folder import requests, os, bs4 os.chdir('c:\\users\\patty\\desktop') #modify location where you want to create the folder if not os.path.isdir('DailyBibleVerse'): os.makedirs('DailyBibleVerse') res = request...
4,610
53519c704ca9aff62140f187d4246208350fa9ba
# Generated by Django 2.1.2 on 2018-11-05 12:00 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('PDPAPI', '0011_auto_20181105_1021'), ] operations = [ migrations.RemoveField( model_name='optionvoting', name='total...
4,611
63e5ead200fb2884d93f19e7d9b8dc76c7f4f0e3
#!/usr/bin/python # -*- coding: utf-8 -*- # Python version 3.8.5 # # Author Maria Catharina van Veen # # Purpose To provide users with a tool to create # or edit an html file. # # Tested OS This code was written and tested to # work with Windows 10. ...
4,612
d625e6724a3fe077a6f80b6de6b1f5bb0b95d47d
import requests from bs4 import BeautifulSoup import json headers = {'User-Agent':'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36'} url = 'http://api.tvmaze.com/singlesearch/shows?q=game+of+throne&embed=episodes' response = requests.get(url, headers = hea...
4,613
6c349b7b4d82b37ec1b1ff8e0d35a3557ed1af67
def calculaEuclidiana(obj1,obj2): soma = 0 for I in range(len(obj1)): soma += (obj1[I] - obj2[I])**2 return soma ** 0.5 def calculaMinkowski(obj1,obj2,p): # p = 2 => distancia Euclidiana # p = 1 => distancia de Manhattan soma = 0 for I in range(len(obj1)): soma += (abs(obj1[...
4,614
d60a2100127db859162890204655d313cdc2a4a5
# -*- coding: utf-8 -*- import scrapy import MySQLdb import openpyxl from scrapy.crawler import CrawlerProcess import sys class AllabolaSpider(scrapy.Spider): name = 'allabola' allowed_domains = ['https://www.allabolag.se'] start_urls = [] #'https://www.allabolag.se/7696250484/befattningar' host =...
4,615
66ae7f4ee01ca5516d8e3dc447eeb4709e2b6aec
import datetime import time def calculate(a): return a data = set() class Bank: amount = 0 def __init__(self): self.Bank_name = "State Bank of India" self.ifsc = 'SBI0N00012' def __repr__(self): return f'Bank Name: {self.Bank_name}, IFSC_Code : {self.ifsc} ' # se...
4,616
d30129248f5245560ee0d3ee786e118427e169d7
import numpy as np er = ['why','who','how','where','which','what','when','was','were','did','do','does','is','are','many','much'] qst = [] txt = None ans = None fnd = [] def chek_qst(qst): global er for h in er: for i in qst: if i == h: qst.remove(i) # qst ...
4,617
9cc672702d960088f0230cbd1694b295216d8b5a
from django.db import models from django.utils.translation import ugettext_lazy as _ class Especialidade(models.Model): def __str__(self): return self.nome # add unique=True? nome = models.CharField(max_length=200, verbose_name=_('Especialidade'), unique=True, blank=False, null=False)
4,618
42743ee2a812d8fe6fc036ba97daaff5be35564d
from pytorch_lightning.callbacks import Callback from evaluation.validator import Validator class LSTMCallback(Callback): def on_test_end(self, trainer, pl_module): f = open('/evaluation.log', 'w') for ev in pl_module.evaluation_data: f.write(ev + '\n') Validator(pl_module.eval...
4,619
dcef5f34a62939d992a109e991552e612bf5bad5
import pandas as pd import numpy as np from datetime import timedelta import scipy.optimize as optim from scipy import stats import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt from gen_utils.gen_io import read_run_params,log_msg ############################################# params = read_run_pa...
4,620
8bce394c651931304f59bbca3e2f019212be9fc1
import sys sys.stdin = open("1868_input.txt") dr = [-1, -1, -1, 0, 0, 1, 1, 1] dc = [-1, 0, 1, -1, 1, -1, 0, 1] def is_wall(r, c): if r < 0 or r >= n or c < 0 or c >= n: return True return False def find(r, c, cnt): Q = [] Q.append((r, c)) visited[r][c] = 1 while Q: tr, tc = Q...
4,621
d9f055301f050eea4281ce418974546c1245ac7e
strings = ['(())())', '(((()())()', '(()())((()))', '((()()(()))(((())))()', '()()()()(()()())()', '(()((())()('] #print(string[0]) ''' for i in string: testlist = [] for j in string[i]: if j == ')': if ''' def isVPS(phrase): testlist = [] for char in phrase: if char == '(...
4,622
420beba5b6fd575ab9be0c907ae0698ba7be5220
from xai.brain.wordbase.verbs._hinder import _HINDER #calss header class _HINDERED(_HINDER, ): def __init__(self,): _HINDER.__init__(self) self.name = "HINDERED" self.specie = 'verbs' self.basic = "hinder" self.jsondata = {}
4,623
0c37806f0a7c0976711edd685fd64d2616147cb6
""" Data pre-processing """ import os import corenlp import numpy as np import ujson as json from tqdm import tqdm from collections import Counter from bilm import dump_token_embeddings import sys sys.path.append('../..') from LIB.utils import save def process(json_file, outpur_dir, exclude_titles=None, include_titl...
4,624
1cc14836808d70c1e53a9ca948a52776ebc89f4a
import dlib import cv2 import imageio import torch from PIL import Image from model import AgeGenderModel from mix_model import MixModel from torchvision.transforms import transforms from tqdm import tqdm from retinaface.pre_trained_models import get_model transform = transforms.Compose([ transforms.Resize((112,...
4,625
11101273a02abec17fc884d5c1d5d182eb82ee0c
# -*- coding: utf-8 -*- """The main application module for duffy.""" from flask import Flask from duffy import api_v1 from duffy.types import seamicro from duffy.extensions import db, migrate, marshmallow from duffy.config import ProdConfig,DevConfig def create_app(config_object=DevConfig): app = Flask(__name__...
4,626
81fce5314a7611de11648e412151112e29271871
import random from z3 import * def combine(iter): tmp_list = [i for i in iter] res = tmp_list[0] for i in tmp_list[1:]: res += i return res def co_prime(num1, num2): for num in range(2, min(num1, num2) + 1): if num1 % num == 0 and num2 % num == 0: return False re...
4,627
cf65966f5daf88bdefc7a8aa2ff80835cff0d0b6
# -*- coding: utf-8 -*- import numpy as np import matplotlib.pyplot as plt from sklearn.ensemble import ( StackingClassifier, RandomForestClassifier ) import pandas as pd from sklearn.metrics import f1_score # feel free to import any sklearn model here from sklearn.linear_model import LogisticRegression from ...
4,628
f6838906c961a9ca7d91d2ab02fd2af72797b880
from torch import nn class MNIST3dModel(nn.Module): def __init__(self, input_c=3, num_filters=8, num_classes=10): super().__init__() self.conv1 = nn.Conv3d(in_channels=input_c, out_channels=num_filters, kernel_size=3, ...
4,629
1346bf78241b4be00f2da3c22731d2846f9d1ada
import shelve from club import Club #загальний бютжет клубів в заданій країні #клуб який має найбільше трофеїв country = input('country: ') FILENAME = "clubs" with shelve.open(FILENAME) as clubs: clubs_by_country = list(filter(lambda s: s.country.lower() == country.lower(), clubs.values())) if len(clubs_b...
4,630
a29a904290cb733ac7b526a75e0c218b952e2266
import mysql.connector # config = { # "user":"root", # "password":"Sm13481353", # "host":"3" # } mydb = mysql.connector.connect( user="seyed", password="Sm13481353", host="localhost", database="telegram_bot", auth_plugin="mysql_native_password" ) mycursor = mydb.cursor() query = "i...
4,631
872b13a93c9aba55c143ee9891543f059c070a36
# dg_kernel plots import os import re import numpy as np import matplotlib.pyplot as plt import matplotlib.colors as mcolors import csv import sys NE_SIZE = 128 TITLE_SIZE = 35 TEXT_SIZE = 30 MARKER_SIZE = 10 LINE_WIDTH = 5 colors = { idx:cname for idx, cname in enumerate(mcolors.cnames) } eventname = 'L1_DCM' cal...
4,632
a3ed47c285b26dca452fa192eb354a21a78b8424
from math import sqrt, ceil def encode_s(s): encoded_s = '' s_with_no_spaces = s.replace(' ', '') step = ceil(sqrt(len(s_with_no_spaces))) for j in range(0, step): i = j while i < len(s_with_no_spaces): encoded_s = encoded_s + s_with_no_spaces[i] i += step ...
4,633
b43ea8c32207bf43abc3b9b490688fde0706d876
A = int(input()) B = int(input()) C = int(input()) number = A * B * C num = str(number) for i in range(10): # 9를 입력해서 첨에 틀림 ! count = 0 for j in range(len(num)): if i == int(num[j]): count += 1 else: continue print(count)
4,634
a6cc0078fb37f9c63e119046193f521290c9fb21
# Generated by Django 3.2.8 on 2021-10-20 08:25 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('app', '0006_auto_20211020_0817'), ] operations = [ migrations.AlterModelOptions( name='currencies', options={'verbose_name':...
4,635
7273592ab8fea10d9a3cde58690063690c74b746
newList = [] noDuplicate = [] while True: elem = input("Enter a letter : (type quit to quit) ") if elem.lower() != "quit": newList.append(elem) else: break for item in newList: if item not in noDuplicate: noDuplicate.append(item) print(noDuplicate)
4,636
551e9c696eaad6c78f2eae66e50cca34c153d9dd
print "test" print "moreing" print " a nnnnn"
4,637
1b3493322fa85c2fe26a7f308466c4a1c72d5b35
import numpy as np import scipy.sparse as sparse from .world import World from . import util from . import fem from . import linalg def solveFine(world, aFine, MbFine, AbFine, boundaryConditions): NWorldCoarse = world.NWorldCoarse NWorldFine = world.NWorldCoarse*world.NCoarseElement NpFine = np.prod(NWorl...
4,638
012e4112970a07559f27fa2127cdffcc557a1566
list_angle_list = RmList() variable_flag = 0 variable_i = 0 def user_defined_shoot(): global variable_flag global variable_i global list_angle_list variable_i = 1 for count in range(3): gimbal_ctrl.angle_ctrl(list_angle_list[1], list_angle_list[2]) gun_ctrl.fire_once() variab...
4,639
0d3e1df1720812e8546b1f3509c83d1e6566e103
from django.http import HttpResponseRedirect from django.urls import reverse from django.contrib import messages from datetime import datetime, timedelta class DeadlineMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): re...
4,640
8417b63e2b7b16d3d58175022662c5b3e59e4aaf
import pytest from ethereum.tools.tester import TransactionFailed def test_cant_ever_init_twice(ethtester, root_chain): ethtester.chain.mine() with pytest.raises(TransactionFailed): root_chain.init(sender=ethtester.k0) with pytest.raises(TransactionFailed): root_chain.init(sender=ethteste...
4,641
b4d09b6d8ad5f0584f74adc0fd8116265bb6649b
from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index_view, name='accounts.index'), url(r'^login/$', views.login_view, name='accounts.login'), url(r'^logout/$', views.logout_view, name='accounts.logout'), url(r'^registro/$', views.registro_usuario_view, name='accou...
4,642
dc05a441c21a67fbb3a1975b3fccb865a32731c8
# Copyright (C) 2020 Francis Sun, all rights reserved. """A copyright utility""" import datetime import argparse import os import os.path class Copyright: _file_type = { 'c/c++': ['h', 'c', 'cpp', 'cc'], 'python': ['py'], 'cmake': ['cmake'], 'vim': ['vim'], ...
4,643
2b928dad60bfb0ba863e9039a5462faa885644f3
#!/usr/bin/python # -*- coding: utf-8 -*- import pywikibot from pywikibot import pagegenerators import re from pywikibot import xmlreader import datetime import collections from klasa import * def fraz(data): data_slownie = data[6:8] + '.' + data[4:6] + '.' + data[0:4] lista_stron = getListFromXML(data) ...
4,644
4863581a1a557186ceee8d544d1a996082edcf2c
#####coding=utf-8 import re import urllib.request import sys import redis from urllib.error import URLError, HTTPError import urllib.parse # /redis/cluster/23:1417694197540 def con(): pool = redis.ConnectionPool(host='ap2.jd.local', port=5360, password='/redis/cluster/1:1803528818953446384') r = redis.Stric...
4,645
2a13fffa105a5dd546c30c892e59888eb6ead996
def fonct(valeur, a= None): if type(a) is list: a.append(valeur) # a+= valeur elif type(a) is tuple: a += tuple((valeur,)) elif type(a) is str: a += str(valeur) elif type(a) is set: a.add(valeur) el...
4,646
4fd4c9cf3bdb73a003ce860bf2ee0ccab01f0009
# The error measures used in this project # # Rooth Mean Squared Error # Mean Absolute Error # # ! Both calculated after descaling the output of the system first import numpy as np def RMSE(min_y, max_y, yhat, y): # first scale output and target back to # original scale, to prevent scale bias yhat = descale(yhat,...
4,647
cfa064611a4aa16638bd649c68d64872b9fac1ff
from math import sqrt def prime_generator(n): pp=[2,3] for i in range(3,n): i+=2 count=0 for ps in pp: if ps>(sqrt(i)+1): break if i%ps==0: count+=1 break if count==0: pp.append(i) return pp ...
4,648
3dc3bbd00f9c2d00093bf8669963d96f5019b2da
import requests from multiprocessing import Process from atomic_counter import AtomicCounter class Downloader: def __init__(self, src_url, num_threads): try: header = requests.head(src_url).headers self.url = src_url self.file_size = int(header.get('content-length')) ...
4,649
6369c692e358c0dfd1193c6e961ecf9b521ea9ba
# Import the SDK import json import boto3 from botocore.exceptions import ClientError import uuid #dbclient = boto3.client('dynamodb') dbresource = boto3.resource('dynamodb', region_name='eu-west-1') rekclient = boto3.client('rekognition','eu-west-1') collection_name = 'swiftarycelebrity' ScannedFacestable = dbresour...
4,650
dff5a46c6f1eb715fe5e1eec87e42ceb295b0eae
from django.contrib import admin from django.urls import path, include from .views import hindex,galeria,mision_vision,direccion,registro,login,logout_vista,registro_insumo,admin_insumos urlpatterns = [ path('',hindex,name='HINDEX'), path('galeria/',galeria,name='GALE'), path('mision/',mision_vision,name=...
4,651
18d7c486b9070a1c607ba2ba5876309246013182
#!/usr/bin/python3 # -*- coding: utf-8 -*- # # Copyright 2021 Opensource ICT Solutions B.V. # https://oicts.com # #version: 1.0.0 #date: 06-11-2021 import requests import json import sys url = 'http://<URL>/zabbix/api_jsonrpc.php?' token = '<TOKEN>' headers = {'Content-Type': 'application/json'} hostname = sys....
4,652
e6aa28ae312ea5d7f0f818b7e86b0e76e2e57b48
from rest_framework import serializers from films.models import * from django.contrib.auth.models import User class UserSerializer(serializers.ModelSerializer): films = serializers.PrimaryKeyRelatedField(many=True, queryset=Film.objects.all()) theaters = serializers.PrimaryKeyRelatedField(many=True, queryset=F...
4,653
e2e2e746d0a8f6b01e6f54e930c7def2d48c2d62
import json import random import uuid from collections import OrderedDict import docker from .db_utils import DBUtils from .models import DynamicDockerChallenge class DockerUtils: @staticmethod def add_new_docker_container(user_id, challenge_id, flag, port): configs = DBUtils.get_all_configs() ...
4,654
ad59c1f0038294144b1c63db5f048b0a6b5ebb89
# coding: utf-8 ''' Programa : py02_variavel.py Homepage : http://www Autor : Helber Palheta <hpalheta@outlook.com> Execução: python py02_variavel.py ''' #variável curso e sua atribuição curso = "Introdução a Biopython!" #função print print("Nome do Curso: "+curso)
4,655
17548459b83fe4dea29f20dc5f91196b2b86ea60
# -*- coding: utf-8 -*- """ Created on Fri Oct 23 15:26:47 2015 @author: tomhope """ import cPickle as pickle from nltk.tokenize import word_tokenize from sklearn.feature_extraction.text import CountVectorizer import re def tokenize_speeches(text): text = re.sub('[\[\]<>\'\+\=\/(.?\",&*!_#:;@$%|)0-9]'," ", text) ...
4,656
c6ef9154285dee3b21980801a101ad5e34a50cab
import os import yaml import sys import random import shutil import openpyxl import yaml import audioanalysis as aa import numpy as np import argparse import logging """ manualtest.py Script to create a listeneing test. The output, test case directory and answer_key.yml file, can be found in the root directory. m...
4,657
be1638638c70cf761bf5d2f0eb474b44684dfa47
from __future__ import division import torch import torch.nn as nn import math def conv_bn(inp, oup, stride): return nn.Sequential( nn.Conv2d(inp, oup, 3, stride, 1, bias=False), nn.BatchNorm2d(oup), nn.ReLU(inplace=True) ) def conv_1x1_bn(inp, oup): return nn.Sequential( ...
4,658
aa2a268143856d8f33b1aaf24f4e28ffd95cab01
__author__ = 'susperius' """ Abstract class used to implement own fuzzers """ class Fuzzer: NAME = [] CONFIG_PARAMS = [] @classmethod def from_list(cls, params): raise NotImplementedError("ABSTRACT METHOD") @property def prng_state(self): raise NotImplementedError("ABSTRACT M...
4,659
7c2d57a8368eb8d1699364c60e98766e66f01569
from flask import Blueprint, current_app logging = Blueprint("logging", __name__) @logging.route("/debug/") def debug(): current_app.logger.debug("some debug message") return "" @logging.route("/warning/") def warning(): current_app.logger.warning("some warning message") return "" @logging.ro...
4,660
47c5fb03cb427d5c9f7703e1715e026b6f2c7a35
#!/usr/bin/env python import mcvine.cli from numpy import array from mcvine_workflow.singlextal.resolution import use_res_comps as urc beam_neutrons_path = '/SNS/users/p63/ORNL_public_research/MCViNE_Covmat_comparison/mcvine_resolution/beams/beam_125_1e9/out/neutrons' instrument = urc.instrument('ARCS', '3.*meter', '13...
4,661
635b75bc12718bccdfb9d04a54476c93fa4685ce
from django.db import models import eav from django.utils import timezone class RiskType(models.Model): """A model class used for storing data about risk types """ name = models.CharField(max_length=255) created = models.DateTimeField(default=timezone.now) modified = models.DateTimeField(auto_...
4,662
0a38cf6e0518a08895ed7155069aa2257c7b352e
import pandas as pd import numpy as np df1 = pd.DataFrame(np.ones((3, 4))*0, columns=['a', 'b', 'c', 'd']) df2 = pd.DataFrame(np.ones((3, 4))*1, columns=['a', 'b', 'c', 'd']) df3 = pd.DataFrame(np.ones((3, 4))*2, columns=['a', 'b', 'c', 'd']) # 竖向合并 # ignore_index对行索引重新排序 res1 = pd.concat([df1, df2, df3], axis=0, ig...
4,663
b7c43f4242e38318c9e5423ea73e9d9d86759a53
# -*- coding:utf-8 -*- __author__ = 'yyp' __date__ = '2018-5-26 3:42' ''' Given a string, find the length of the longest substring without repeating characters. Examples: Given "abcabcbb", the answer is "abc", which the length is 3. Given "bbbbb", the answer is "b", with the length of 1. Given "pwwkew", the answer is ...
4,664
49ffa225d433ef2263159ba2145da5ba2a95d1f2
#求11+12+13+。。。+m m = int(input('请输入一个数:')) S = m for x in range(11,m): S = S+x print('sum =',S)
4,665
3c2a611fd001f145703853f5ecfe70d0e93844e4
""" opsi-utils Test utilities """ import os import tempfile from contextlib import contextmanager from pathlib import Path from typing import Generator @contextmanager def temp_context() -> Generator[Path, None, None]: origin = Path().absolute() try: with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) ...
4,666
b4491b5522e85fec64164b602045b9bd3e58c5b8
#给你一个字符串 croakOfFrogs,它表示不同青蛙发出的蛙鸣声(字符串 "croak" )的组合。由于同一时间可以有多只青蛙呱呱作响,所以 croakOfFrogs 中会混合多个 “croak” 。请你返回模拟字符串中所有蛙鸣所需不同青蛙的最少数目。 #注意:要想发出蛙鸣 "croak",青蛙必须 依序 输出 ‘c’, ’r’, ’o’, ’a’, ’k’ 这 5 个字母。如果没有输出全部五个字母,那么它就不会发出声音。 #如果字符串 croakOfFrogs 不是由若干有效的 "croak" 字符混合而成,请返回 -1 。 #来源:力扣(LeetCode) #链接:https://leetcode-cn.com/pr...
4,667
60953878c377382f1c7f25ce284c9fa12b8eb25f
#coding: utf-8 import numpy as np import cv2 leftgray = cv2.imread('../image/1.jpg') rightgray = cv2.imread('../image/2.jpg') hessian=500 surf=cv2.xfeatures2d.SURF_create(hessian) #将Hessian Threshold设置为400,阈值越大能检测的特征就越少 kp1,des1=surf.detectAndCompute(leftgray,None) #查找关键点和描述符 kp2,des2=surf.detectAndCompute(rightgr...
4,668
7f7bd2e9ec1932ccfd8aa900956ce85473ee8dbd
#!/usr/bin/env python """Diverse wiskundige structuren weergeven in LaTeX in Jupyter Notebook.""" __author__ = "Brian van der Bijl" __copyright__ = "Copyright 2020, Hogeschool Utrecht" from IPython.display import display, Math, Markdown import re def show_num(x): return re.compile(r"\.(?!\d)")...
4,669
a83988e936d9dee4838db61c8eb8ec108f5ecd3f
import numpy as np labels = np.load('DataVariationOther/w1_s500/targetTestNP.npy') for lab in labels: print(lab)
4,670
511c555c88fb646b7b87678044b43a5a623a5ac7
from django.contrib import admin from django.urls import path from . import view urlpatterns = [ path('', view.enterMarks), path('MarkSheet', view.getMarks, name='MarkSheet'), ]
4,671
844c630d3fe2dda833064556228b524608cfece9
import numpy as np import cv2 from camera import load_K, load_camera_dist, load_camera_ret def undistort_img(img): ''' Return an undistorted image given previous calibrated parameters References from OpenCV docs ''' ret = load_camera_ret() K = load_K() dist = load_camera_dist() h,w = img.sha...
4,672
dd7c7fa6493a43988e1c8079797f6ff9b4d239dd
# -coding: UTF-8 -*- # @Time : 2020/06/24 20:01 # @Author: Liangping_Chen # @E-mail: chenliangping_2018@foxmail.com import requests def http_request(url,data,token=None,method='post'): header = {'X-Lemonban-Media-Type': 'lemonban.v2', 'Authorization':token} #判断是get请求还是post请求 if method=='ge...
4,673
5ef6b2ff89ee1667ddb01b1936557f1f11a49910
# -*- coding: utf-8 -*- # Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html from sqlalchemy import create_engine, MetaData, Table class DoubanPipeline(object): conn = None film_table = None ...
4,674
a2c93fd632a637d47f05e0a4fda851b465d03a31
import os import sqlite3 import datetime directory = 'C:\PyHelp' if not os.path.exists(directory): os.makedirs(directory) rand_facts = '''• Exception is used as a base class for all exceptions. It's strongly recommended (but not yet required) that user exceptions are derived from this class too. • System...
4,675
2747b2563c83e11261a7113d69921c1affb20ac8
class Balloon(object): def __init__(self, color, size, shape): self.color = color self.size = size self.shape = shape self.inflated = False self.working = True def inflate(self): if self.working: self.inflated = True else: print "Y...
4,676
0dce4ea8ef21f2535194330b82ce5706ae694247
class Order: """ Initiated a new order for the store """ def __init__(self, order_number, product_id, item_type, name, product_details, factory, quantity, holiday): """ Construct a new order :param order_number: str :param product_id: str :param item_type: str ...
4,677
6e614d1235a98ef496956001eef46b4447f0bf9b
from appium import webdriver from selenium.webdriver.support.ui import WebDriverWait from appium.webdriver.common.touch_action import TouchAction import time import re from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By import pymongo def getSize(): x = driv...
4,678
752affdfa1481b9a19a9b7dfe76f9d5d11c80073
# # Copyright John Reid 2009 # """ Code to handle bootstrap analyses. """ from itertools import cycle import random import bisect def generate_bootstrap_samples(num_samples, test_universe, test_set_sizes): """ Yield samples that match the sizes given in test_set_sizes """ for sample_idx, sample_siz...
4,679
6707723b3d0b42271e49c08c639afc9103066dc7
import numpy as np import math import datetime def multi_strassen(A,B, check_ig = True, check_quad = True, check_pot = True, check_time = True): def Strassen(matriz_1,matriz_2): # Função do algoritmo de Strassen para multiplicação de matrizes do tipo 2x2 if (matriz_1.shape[0] != 2) or (matriz_1.shape[...
4,680
68ea462f56ba029a7c977d9c8b94e6f913336fb7
from django.db import models from django.conf import settings from django.utils.translation import ugettext_lazy as _ from model_utils.models import TimeStampedModel user = settings.AUTH_USER_MODEL commment_lenght = settings.COMMENT_LENGTH # Entity Comment class Comment(TimeStampedModel): """ Text comment po...
4,681
66f3590381fe96c49a8926a806b4a845f0d7e25d
import inaccel.coral as inaccel import numpy as np import time class StereoBM: def __init__(self, cameraMA_l=None, cameraMA_r=None, distC_l=None, distC_r=None, irA_l=None, irA_r=None, bm_state=None ): # allocate mem for camera parameters for rectification and bm_state class with inaccel.allocator: if cameraMA_...
4,682
0d321193d68b463e3dd04b21ee611afdc212a22b
def flat_list(array): result = [] for element in array: if type(element) == list: result += flat_list(element) else: result.append(element) return result print flat_list([1, [2, 2, 2], 4]) print flat_list([-1, [1, [-2], 1], -1])
4,683
221a75d37fbb49e8508fc786ee8e6e90b19e12c0
#!/usr/bin/python # -*-coding:utf-8 -*- import smtplib import MySQLdb import datetime import types def sendEmail(sender,passwd,host,port,receivers,date,mail) : message = MIMEText(mail, 'html', 'utf-8') message['From'] = Header("告警发送者<"+sender+">", 'utf-8') subject = str(date) + '服务器告警通知' message['Subjec...
4,684
af8a3fbce35685cd89dee72449a8be2a133b4a3f
from os import chdir from os.path import dirname, realpath import random from flask import Flask, render_template, send_from_directory app = Flask(__name__) # gets list of list of all classes def get_data(): class_list = [] with open('counts.tsv') as fd: for line in fd.read().splitlines(): ...
4,685
822fc2941099cb9d7791580678cfb2a89a987175
import os, random, string from django.conf import settings from django.template.loader import render_to_string from django.core.mail import send_mail def generate_temp_password(): length = 7 chars = string.ascii_letters + string.digits rnd = random.SystemRandom() return ''.join(rnd.choice(chars) for...
4,686
4948fd2062bdbd32bfa32d2b0e24587f0872132d
from .exceptions import InvalidUsage class HTTPMethodView: """ Simple class based implementation of view for the sanic. You should implement methods (get, post, put, patch, delete) for the class to every HTTP method you want to support. For example: class DummyView(HTTPMethodView): ...
4,687
001198459b038186ab784b6a9bed755924784866
from flask import Flask, render_template, redirect, request, session app = Flask(__name__) app.secret_key = 'ThisIsSecret' #this line is always needed when using the import 'session' @app.route('/') #methods=['GET'] by default def index(): return render_template('index.html') @app.route('/ninja'...
4,688
0656aba517023c003e837d5ad04daeb364f7fda8
import os CSRF_ENABLED = True basedir = os.path.abspath(os.path.dirname(__file__)) # Heroku vs. Local Configs if os.environ.get('HEROKU') is None: # Database path SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(basedir, 'app.db') # CSRF Key SECRET_KEY = os.urandom(24) # Pocket API CONSUM...
4,689
21526dabe8456c599e4409228fa69ffd0d672c5b
"""Helpers for FormatCBFMiniPilatus...""" from __future__ import annotations import calendar import time def get_pilatus_timestamp(timestamp_string): if "." in timestamp_string: timestamp, milliseconds = timestamp_string.split(".") else: timestamp = timestamp_string milliseconds = "...
4,690
be1ddaf5b4a7fb203fea62d061b06afb45d6867d
def most_frequent_char(lst): char_dict = {} for word in lst: for char in word: if char in char_dict: char_dict[char] += 1 else: char_dict[char] = 1 max_value = max(char_dict.values()) max_keys = [] for key, value in char_dict.items(): if value == max_value: max_keys....
4,691
9cf0174a8bd2bccbd8e5d0be1f0b031a1a23c9df
from Global import * import ShuntingYard from Thompson import * def check_string(automaton, word): inicial = automata['s'].closure for i in word: inicial = state_list_delta(inicial, i) return automaton['f'] in inicial def create_AFND(re): deltas = [] initial_node = ShuntingYard.create_tree(ShuntingYard.to_rpn...
4,692
027a049ffced721f2cd697bc928bfdf718630623
import os from apps.app_base.app_utils.cryp_key import decrypt, get_secret_key BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = get_secret_key DEBUG = True ALLOWED_HOSTS = ['.localhost', '127.0.0.1', '[::1]'] # Application definition INSTALLED_APPS = [ 'corsheaders', 'd...
4,693
33ac328b2bf16380b50c58013bd0d4d888dc3952
#!/usr/bin/env python from anytree import Node, RenderTree webtest = Node("WebappTest") registration = Node("Registration", parent=webtest) smsconfirm = Node("SMSconfirm", parent=registration) login = Node("Login", parent=smsconfirm) useruploadCV = Node("UserUploadCV", parent=l...
4,694
1ab5147ed8ce808de9667052b6d17f320d62484f
''' 手写识别系统 构建识别类 Recognize 调用getResult()函数即可 ''' import operator from numpy import * from PIL import Image from os import listdir from io import BytesIO def classify(inX, dataSet, labels, k): dataSetSize = dataSet.shape[0] #训练数据集的行数 # 计算距离 diffMat = tile(inX, (dataSetSize,1)) - dataSet sqDiffMat = ...
4,695
3302dc058032d9fe412bde6fd89699203526a72d
import random #import random module guesses_taken = 0 #assign 0 to guesses_taken variable print('Hello! What is your name?')# print Hello! What is your name? to console myName = input()#take an input from user(name) number = random.randint(1, 20)# make random number between 1 and 19 and save in number variable print...
4,696
d9f176262dcaf055414fbc43b476117250249b63
class Solution: def levelOrder(self, root): if root is None: return [] currentList = [root] nextList = [] solution = [] while currentList: thisLevel = [node.val for node in currentList] solution.append(thisLevel) f...
4,697
e550a2d46e46f0e07d960e7a214fbaa776bab0d5
import tensorflow as tf from rnn_cells import gru_cell, lstm_cell from tensorflow.python.ops import rnn def shape_list(x): ps = x.get_shape().as_list() ts = tf.shape(x) return [ts[i] if ps[i] is None else ps[i] for i in range(len(ps))] def bi_dir_lstm(X, c_fw, h_fw, c_bw, h_bw, units, scope='bi_dir_lstm')...
4,698
df828344b81a40b7101adcc6759780ea84f2c6b4
from os import read from cryptography.fernet import Fernet #create a key # key = Fernet.generate_key() #When every we run this code we will create a new key # with open('mykey.key','wb') as mykey: # mykey.write(key) #To avoid create a new key and reuse the same key with open('mykey.key','rb') as myk...
4,699
5d92c68e0fe7f37d4719fb9ca4274b29ff1cbb43
#!/usr/bin/python #The MIT License (MIT) # #Copyright (c) 2015 Stephen P. Smith # #Permission is hereby granted, free of charge, to any person obtaining a copy #of this software and associated documentation files (the "Software"), to deal #in the Software without restriction, including without limitation the rights #to...