text
stringlengths
8
6.05M
from django import forms class CalculatorForm(forms.Form): w = forms.IntegerField() h = forms.IntegerField() b = forms.IntegerField()
from google.appengine.ext import ndb class Plante(ndb.Model): name = ndb.StringProperty(required=True) soleil = ndb.StringProperty() variete = ndb.StringProperty() famille = ndb.StringProperty() type = ndb.StringProperty() cycleCulture = ndb.StringProperty() hauteur = ndb.IntegerProperty()...
P=[1,1,1,2,2] for i in range(5,101): P.append(P[i-1]+P[i-5]) for i in range(int(input())): N=int(input()) print(P[N-1])
import torch import torch.nn.functional as F import torch.optim as optim import numpy as np import os import traceback import sys import shutil from shutil import copyfile import tempfile from data_utils import SquadDataLoader from rnet_model import RNetModel from config import base_config def get_checkpoint_file_nam...
#!/usr/bin/python3 # //////////////////////////////////////////////////////////////// # // IMPORT STATEMENTS // # //////////////////////////////////////////////////////////////// import spidev import os from time import sleep import RPi.GPIO as GPIO from pidev.stepper import s...
import typing _T = typing.TypeVar("_T") BytesLike = typing.Union[bytes, bytearray] Coroutine = typing.Coroutine[typing.Any, typing.Any, _T]
#!/usr/bin/python import json import urllib2 import sys import re URL = 'http://169.254.169.254/latest/user-data' try: data = json.load(urllib2.urlopen(URL)) except: print >> sys.stderr, 'Was not able to connect to the Amazon API' sys.exit(2) # Python doesn't like a list of 1 tags = [] tags.append(data[...
""" Test for our implementation of stack. """ from stack import Stack if __name__ == "__main__": ourStack = Stack() ourStack.push("A") ourStack.push("B") ourStack.push("C") print(ourStack) # after remove one element from top # last element which is added now is removed ourStack....
#!/usr/bin/env python #encoding:utf-8 # # Copyright (c) 2015 Ministerio de Fomento # Instituto de Ciencias de la Construcción Eduardo Torroja (IETcc-CSIC) # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Softw...
import json from uuid import uuid4 from django.contrib.auth.models import User from django.test import TestCase from django.urls import reverse from scheduler.models import Job from scheduler.views import JobStatus from spiderTemplate.models import Site, Template, Param from task.models import Task def create_test_...
import time import asyncio from urllib.request import urlopen urls = ('http://daum.net', 'https://naver.com', 'http://mlbpark.donga.com/', 'https://tistory.com', 'https://wemakeprice.com/') async def get_url_data(url: str) -> (str, str, str): '''특정 URL에 요청을 보내어 HTML 문서를 문자열로 받는다. ...
#========================================================================# # Generate LSWT "completeness monitoring" plots #------------------------------------------------------------------------# # R. Maidment #========================================================================# #-------------------------------...
#detec cycles in graph def cycle(g): color = {u : 'white' for u in g} found_cycle = [False] print(color) for u in g: if color[u] == "white": dfs_visit(g , u , color , found_cycle) if found_cycle[0]: break ...
# -*- coding: utf-8 -*- """ The :mod:`.data` module implements data download and loading. """ from .load_data import (load_TFinfo_df_mm9_mouse_atac_atlas, load_mouse_scATAC_atlas_base_GRN, load_Paul2015_data, load_tutorial_links_object, ...
# ----------------------------------------------------------------------------- # Copyright (c) 2014--, The Qiita Development Team. # # Distributed under the terms of the BSD 3-clause License. # # The full license is in the file LICENSE, distributed with this software. # ------------------------------------------------...
#IMPORT HERE.. import shuffler import pandas as pd import tkinter as tk import tkinter.font as tkfont #DEFINE CONSTANTS HERE.. CODE = None PADX = None PADY = None HEIGHT = None OPTION_FONT = None QUESTION_FONT = None CALCULATOR_FONT = None CALCULATOR_BUTTON_WIDTH = None CALCULATOR_BUTTON_FONT = None #INITIALISE HERE....
######################################################################################################################## # # # # # # This is a Python script for implenting optimization of a problem using Steepest Descent and Newton's Methods# # # # The code is also able to choose betwe...
from __future__ import annotations from contextlib import asynccontextmanager from datetime import datetime, timezone from tempfile import TemporaryDirectory from typing import AsyncGenerator import anyio import pytest from freezegun.api import FrozenDateTimeFactory from pytest_lazyfixture import lazy_fixture from a...
from django.shortcuts import render, HttpResponse, redirect from django.contrib.auth import login, authenticate, logout from django.contrib.auth.forms import AuthenticationForm, UserCreationForm from django.views.generic import UpdateView from .models import UserProfile, City, Post from .forms import RegistrationForm, ...
n = int(input()) print(int(2**(n-1)))
from numpy import * def deg2rad(x): return ((x*pi)/180) def rad2deg(x): return ((x*180)/pi)
import csv import json def generateName(row): temp = [ row['category'], row['alternate'], row['name'], ] return " ".join(temp)[0:54] def getPrice(row): return int( float(row["price"])*1000000 ) crdict = csv.DictReader(open("ffinput.csv","rb")) print("Opening file...") f =...
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import requests from config.settings import MAP_API_URL, NO_DATA, DEFAULT_COORDINATES from grandpy.errors import HereNetworkError, HereJsonError, HereBadRequestError from grandpy.api.parser import Parser class MapApi: """ MapApi class To man...
from math import sqrt # A dictionary of movie critics and their ratings of a small # set of movies critics={'Lisa Rose': {'Lady in the Water': 2.5, 'Snakes on a Plane': 3.5, 'Just My Luck': 3.0, 'Superman Returns': 3.5, 'You, Me and Dupree': 2.5, 'The Night Listener': 3.0}, 'Gene Seymour': {'Lady in the Water': 3.0, '...
import sys import argparse import numpy as np import tensorflow as tf import keras import gym import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt from reinforce import Reinforce class A2C(Reinforce): # Implementation of N-step Advantage Actor Critic. # This class inherits the Reinforce cla...
#!/usr/bin/env python # -*- coding: utf-8 -*- # time: 2020-8-9 23:11:00 # version: 1.0 # __author__: zhilong import requests headers = { 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) ' 'Chrome/86.0.4240.111 Safari/537.36 ' } url = "https://image...
from .models import DengueBite from rest_framework import status from rest_framework.response import Response from rest_framework.views import APIView class BiteCollection(APIView): def post(self, request): lng = request.data.get('lng', '') lat = request.data.get('lat', '') try: ...
#!/usr/bin/python #\file intplcalc #\brief Calculating user-defined functions f(y) from interpolations of data files {t,y}. #\author Akihiko Yamaguchi, info@akihikoy.net #\version 0.1 #\date Jul.13, 2016 import os,sys from scipy.interpolate import interp1d #Float version of range def FRange1(x1,x2,num_div): ...
#!/usr/share/env python import glob import os import sys filenumber = 0 failed = 0 totalpngsize = 0 cansavepngsize = 0 totalzscisize = 0 numcansave = 0 def convert(dir,f): cwd = os.getcwd() os.chdir(dir) os.system('~/png2zsci/png2zsci/png2zsci -c 100 %s'%f) os.chdir(cwd) if __name__ == '__main__': dir = sys.ar...
import re from share.regulate.steps import NodeStep from share.util import strip_whitespace class TokenizeTags(NodeStep): """Recognize lists of tags, split them into multiple nodes Example config: ```yaml - namespace: share.regulate.steps.node name: tokenize ``` """ node_types = ('...
# https://www.reddit.com/r/dailyprogrammer/comments/3r7wxz/20151102_challenge_239_easy_a_game_of_threes/ def gameOfThrees(number): while number != 1: if number % 3 == 0: print("%d 0" % number) elif number % 3 == 1: print("%d -1" % number) number -= 1 elif...
import os import time from Base.BaseElementEnmu import Element as be from Base.BaseError import get_error from Base.BaseOperate import OperateElement from PageObject.SumResult import statistics_result PATH = lambda p: os.path.abspath( os.path.join(os.path.dirname(__file__), p) ) class PagesObjects: def __i...
# Easy-to-use python functions for reading epochs import pandas as pd import mne def read_all_epochs(subject_name, auto_baseline=True, use_list=False): ''' # Read all epochs of [subject_name] on the disk - @subject_name: The name of subject - @auto_baseline: Whether apply baseline of (None, 0) to the ...
from flask_restful import Resource import logging as logger class ProjectAPI(Resource): def get(self): logger.debug("Inside the post method of Task") projectDetails = { "owner" : "Harsham Sevak", "projectName" : "Simple Flask app for Docker container...
from django.views.static import serve from django.views import View from django.contrib.auth.mixins import LoginRequiredMixin from django.core.exceptions import PermissionDenied from django.db.models import Q from apps.authentication.models import User class ProtectServe(LoginRequiredMixin, View): def get(self, ...
from django.conf.urls import url from . import views app_name = 'scheduler' urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^scheduler/about/*$', views.about, name='about'), url(r'^scheduler/feedback/*$', views.feedback, name='feedback'), url(r'^scheduler/request_history/*$', views.reques...
# from lxml import etree import re from bs4 import BeautifulSoup import pandas as pd from datetime import datetime from ipdb import set_trace from config.xbrl_config import US_GAPP_TAGS_LIST, ALTERNATIVE_TAG_NAMES class XBRL: def __init__(self, use_dei=False, extra_tags=[]): self.data = {} self...
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'mywindow.ui' # # Created by: PyQt5 UI code generator 5.13.0 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_mywindow(object): def setupUi(self, mywindow): mywindow....
# --- # jupyter: # jupytext: # formats: ipynb,py:light # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.6.0 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Functions for grabbin...
#Sample Python 2 sequential code import random def process(num): random_numbers = [] for i in range(num): random_numbers.append(random.randint(0, num)) sum = 0 for number in random_numbers: sum+=number print sum if __name__ == '__main__': for i in range(5000): process(i)
# Generated by Django 2.2.4 on 2019-10-21 01:54 from django.db import migrations, models import django.db.models.deletion import products.models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Big', ...
from django.shortcuts import render from django.views import generic from treehouse.models import * from datetime import date def books(request): books = Book.objects.filter() context = {'books': books} return render(request, 'treehouse/list_books.html', context) def book(request, object_id): book = Book.obj...
import scipy.sparse as sparse import scipy.io as sio from sklearn import metrics import numpy as np from sklearn.decomposition import PCA def main(): f= sio.loadmat('/home/dmitriy/workspace/MLFinalProject/MatlabFiles/finalVectors.mat') full = np.nan_to_num(np.matrix(f['finalVectors'])) full /= np.max(np.abs(full),...
#!/usr/bin/python3 from iterpop import iterpop as ip import itertools as it from keyname import keyname as kn from matplotlib.offsetbox import AnchoredText import matplotlib.pyplot as plt import numpy as np import pandas as pd from scipy.stats import stats import seaborn as sns from slugify import slugify import stats...
from os.path import join, realpath import sys; sys.path.insert(0, realpath(join(__file__, "../../../../../"))) import unittest import unittest.mock import asyncio import os from decimal import Decimal from typing import List import contextlib import time from hummingbot.core.clock import Clock, ClockMode from hummingbo...
''' Name: Darius Sandford Date Assigned: 03-26-2018 Course: 1384 Sec 01 Date Due: 04-02-2018 File Name: postfixNotation.py Description: Create a Stack class as a fixed length stack that can hold a maximum of 10 values and a program th...
# -*- coding: utf-8 -*- """ Created on Tue Sep 8 13:23:20 2020 @author: skyso """ # import matplotlib.pyplot as plt import pandas as pd df = pd.read_csv("cba_data.csv") dfn = pd.DataFrame({'Fieldwork sites':['PNG (March 2018)', 'PNG,BAY(July 2016)'], 'Fieldwork Budget (php)': [df.budget1.sum(), df.budget...
# -*- coding: utf-8 -*- # Generated by Django 1.11.5 on 2017-10-09 11:18 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('carto', '0012_remove_messagetiers_question_text'), ] ...
#!/usr/bin/env python from pydbus import SystemBus, Variant import Queue import time import sys import threading from dbus.mainloop.glib import DBusGMainLoop import gi gi.require_version('Gtk', '3.0') from gi.repository import Gtk, GObject, GLib BT_ADAPTOR_HINT = None BLUEZ_SVC_NAME = 'org.bluez' ADAPTER_IFACE = 'o...
from tweet_fetcher import TweetFetcher from sentiment_analyser import SentimentAnalyser import tweepy from datetime import datetime, timedelta class LoveIslandFetcher(TweetFetcher): ''' Returns all tweets in the last 24 hours with the hashtag love island ''' def get_love_island_tweets(self, hashtag='#loveisl...
import logging import multiprocessing import pickle import queue import threading import numpy as np import transaction from keras.utils import Sequence from file_store import database from file_store.database import * from model.nn import InputNames from params import in_use_features from pipeline import features _...
# Question: https://www.hackerrank.com/challenges/non-divisible-subset/problem n,k = map(int, raw_input().split()) s = list(map(int, raw_input().split())) count = [0 for x in range(k)] for i in range(len(s)): s[i]= s[i]%k count[s[i]]+=1 total = 0 for i in range((k/2)+1): if i==0 or i==k-i: if c...
import os import numpy as np from sklearn.cluster import KMeans from sklearn.metrics.cluster import adjusted_mutual_info_score, adjusted_rand_score, completeness_score, \ fowlkes_mallows_score, homogeneity_score, normalized_mutual_info_score, v_measure_score from machine_learning.aux.constants import get_cluster_lab...
import dash from dash_bootstrap_components._components.CardBody import CardBody import dash_core_components as dcc import dash_html_components as html import dash_bootstrap_components as dbc from dash_html_components.Center import Center from dash_html_components.Div import Div import plotly.express as px import plotly...
import math ''' Reference: http://brucelindbloom.com Whites Illuminant X Y Z A 1.09850 1.00000 0.35585 B 0.99072 1.00000 0.85223 C 0.98074 1.00000 1.18232 D50 0.96422 1.00000 0.82521 D55 0.95682 1.00000 0.92149 D65 0.95047 1.00000 1.08883 D75 0.94972 1.00000 1.22638 E 1.00000 1.00000 1.00000 F2 0.99186 1.00000 0.6739...
import tkinter as tk from tkinter import Tk, Frame, Scrollbar, Listbox, Button, filedialog, Checkbutton, Label import os import pandas as pd def get_filenames(dirname, folder_ids): sel_files = pd.DataFrame() with os.scandir(dirname) as entries: for dir in entries: image_path = 0 ...
import os import asyncio # noqa: F401 import discord import logging from discord.ext import commands from cogs.utils.dataIO import dataIO from cogs.utils import checks from datetime import datetime log = logging.getLogger('red.EmbedMaker') class EmbedMaker: """ Make embed objects. Recall them, remove them, ...
# import colorgram # # colors = colorgram.extract('artimage.jpg', 30) # rgb_color_list= [] # for color in colors: # r = color.rgb.r # g = color.rgb.g # b = color.rgb.b # rgb_colour = (r,g,b) # rgb_color_list.append(rgb_colour) # # print(rgb_color_list) import turtle from turtle import Turtle from t...
a = 0 b = 0 c = 1 n = int( input()) for _ in range(3,n): d = a + b + c d %= 10007 a, b, c = b, c, d if n == 1: print(a) elif n == 2: print(b) elif n == 3: print(c) else: print( d)
svar=input("Heltal ") x=int(svar) y=x*x print (f"Talet i kvadrat är {y}") svar=input("Decimaltal ") x=float(svar) y=x*x print (f"Talet i kvadrat är {y:.5f}")
class Observer: "观察者的基类" def update(self, observer, object): pass class Observable: "被观察者的基类" def __init__(self): self.__observers = [] def add_observer(self, observer): self.__observers.append(observer) def remove_observer(self, observer): self.__observers....
import abc from base_abstract_worker import BaseAbstractWorker import threading # We do not rely on atomicity of the basic operations # http://blog.qqrs.us/blog/2016/05/01/which-python-operations-are-atomic/ class AtomicVar(object): def __init__(self, init_val=None): super(AtomicVar, self).__init__() ...
from django.urls import path from . import views app_name = "tickets" urlpatterns = [ path("buses/", views.bus_index, name="bus_index"), path("bus/<str:bus_id>", views.bus, name="bus"), path("busstops/", views.bus_stop_index, name="bus_stop_index"), path("busstop/<str:bus_stop_id>", views.bus_stop, na...
#!/usr/bin/env python #-*-coding:utf-8-*- ''' ''' import timeit class Poker: def __init__(self, cards): self.numbers = {} self.suits = {} for card in cards: n = self._to_number(card[0]) s = card[1] self.numbers[n] = self.numbers.get(n, 0)+1 ...
import numpy as np class Cut: def __init__(self, MaxLen): self.MaxLen = MaxLen self.cutDic = self.loadDic1('.\dic\chineseDic.txt') # 分词词典List类型 self.frequencyDic = self.loadDic2('.\dic\WordFrequency.txt') # 词频词典List类型 # 读取词典chineseDic def loadDic1(self, dicFile): ...
# Problem Set 2 # Name: Natalia Prósińska # Collaborators: Małgorzata Metryka # Time Spent: 3:00 Initialbal = float(input("What is your outstanding balance on your credit card: ")) interestrate = float(input("What is your annual percentage rate (as a decimal, i.e. 18% is .18): ")) bal = Initialbal lowpay = bal/12 ...
import first_module print("Second module name: {}".format(__name__))
#!/usr/bin/env python # -*- coding: utf-8 -*- from config.settings import STOPWORDS, NO_DATA from grandpy import Parser parser = Parser() ########################################################## ############# Test of refuse_empty_string() ############## ########################################################## d...
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def zigzagLevelOrder(self, root): """ :type root: TreeNode :rtype: List[List[int]] """ ...
import os import sys main_dir = os.path.split(os.getcwd())[0] result_dir = main_dir + '/results' sys.path.append(main_dir) from data import fmri_data_cv as fmril from data import fmri_data_cv_rh as fmrir from data import meg_data_cv as meg from data import fmri_localizer as newfmri from model import procedure_functio...
import contextlib import logging import typing import urllib.parse import celery from django.conf import settings import kombu import kombu.simple import requests import sentry_sdk from share.search.messages import MessagesChunk, MessageType from share.search.index_strategy import IndexStrategy logger = logging.get...
# -*- coding: utf-8 -*- """ Created on Wed Aug 11 21:16:52 2021 @author: Gustavo @mail: gustavogodoy85@gmail.com """ import csv import sys def costo_camion(ruta_archivo): f = open(ruta_archivo) prod = 0.0 rows = csv.reader(f) header = next(f) for row in rows: try: prod += int...
#!/usr/share/python3 import socket,os import time connect = input('IP: ') s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((connect,21)) r = s.recv(1024) s.send("USER seven:)\r\n") s.send("PASS adsfadsf\r\n") time.sleep(.5) os.system("nc -v connect 6200")
""" """ from __future__ import print_function import ngmix import numpy as np import galsim import copy class Coadder(): def __init__(self, observations, interp='lanczos3', flat_wcs=False, weight_type='noise', jacobian=None): ...
def circus_tower(array): array.sort(key=lambda x:(x[0],x[1])) dp=[] for i in array: dp.append(1) for i in range(len(array)): j=0 while(j<i): if array[j][0]<array[i][0] and array[j][0]<array[1][1]: if dp[j]+1>array[i]: dp[i]=dp[j]+1 j+=1 return max(dp) ...
from scipy.linalg import eigh import sys Atemp = sys.argv[1] Btemp = sys.argv[2] # Atemp = '364.8,-182.4;-182.4,182.4' # Btemp = '.407,0;0,.407' A = []; for a in Atemp.split(';'): A.append([float(x) for x in a.split(',')]) B = []; for b in Btemp.split(';'): B.append([float(x) for x in b.split(',')]) eigva...
# -*- coding:utf-8 -*- import bisect class Solution: """ 子数组=>想到双指针 """ def minSubArrayLen_2fen(self, s: int, nums: list) -> int: """ 使用2分方法也可以做出来,对的 """ for i in range(1, len(nums)): nums[i] = nums[i] + nums[i - 1] # 不能忽略全部和的情况 nums.insert(...
import csv import click import jinja2 from . import ao3 from .exceptions import LoginRequired from .exceptions import SessionExpired from .exceptions import UnexpectedError from .exceptions import ValidationError @click.group() def cli(): pass @cli.command() @click.argument( 'csv_file', type=click.Fil...
from django.apps import AppConfig class QuestionairesConfig(AppConfig): name = 'Questionaires'
__version__ = '0.1.3' version = __version__ version_info = __version__.split('.')
import unittest from src.pub import Pub from src.drink import Drink from src.customer import Customer class TestDrink(unittest.TestCase): def setUp(self): self.drink_beer = Drink("Beer", 5.00) self.drink_wine = Drink("Wine", 6.00) self.drink_gnt = Drink("Gin & Tonic", 7.50) self.dri...
from PIL import Image, ImageFilter import tkinter.simpledialog as simpleDialog class MyGaussianBlur(ImageFilter.Filter): name = "GaussianBlur" def __init__(self, radius=2): self.radius = radius def filter(self, image): return image.gaussian_blur(self.radius) def effect(image_data) -> Imag...
#leetcode 139 #bruteforce #algo : CReate a hash set to get the presence of word in dictionary in O(1), and then we get throught the string to find all the possoible word combinatios #Time Limit Exceeded error class Solution(object): def wordBreak(self, s, wordDict): """ :type s: str ...
""" File: similarity.py ------------------------ This file should implement a console program that prompts users for a DNA strand that they want to search through and a DNA target strand that they want to search for. The program then outputs the closest match to the target strand, as defined by the similarity metric. "...
a = int(input()) b = int(input()) c = int(input()) x = int(input()) result = 0 for i in range(a+1): for j in range(b+1): for k in range(c+1): if(x ==i*500 + j*100 + k*50): result += 1 print(result)
import math t=int(raw_input()) while t: n=int(raw_input()) print math.factorial(n) t=t-1
import os from typing import List, Any, Union import math class Point(object): """ Point class """ x: float y: float data: Any def __init__(self, x, y, data=None): self.x = x self.y = y self.data = data def __repr__(self): return '<Point: ({0},{1})>'.f...
from Lista_de_movimientos import diccionario_movimientos class Pokemon(): # Ejemplos para los distintos pokemon pokemon = 'Pokémon' tipo = None tipo_experiencia = 'Rapido' atributos = None lista_mov = None def __init__(self, nivel, nombre, movimientos_guardados, experiencia): self....
#import pygame #pygame.init() #pygame.mixer.music.load('ex021.mp3') #pygame.mixer.music.play() #pygame.event.wait() from pygame import mixer mixer.init() mixer.music.load('ex021.mp3') mixer.music.play() input('Agora você escuta?')
# 1. Two Sum # Easy # 13962 # 511 # Add to List # Share # Given an array of integers, return indices of the two numbers such that they add up to a specific target. # You may assume that each input would have exactly one solution, and you may not use the same element twice. # Example: # Given nums = [2, 7, 11, 15...
import click import transaction from onegov.core.cli import command_group from onegov.translator_directory.collections.translator import \ TranslatorCollection from onegov.translator_directory import log from onegov.translator_directory.utils import update_drive_distances, \ geocode_translator_addresses from o...
# -*- coding: utf-8 -*- import pdb import os import hashlib from bottle import route, run, template, SimpleTemplate, static_file, request, redirect #from TransmissionClient import NoSuchTorrent, TransmissionClient # FILE UPLOAD FROM STACK OVERFLOW # http://stackoverflow.com/questions/22839474/python-bottle-how-to-uplo...
# stackoverflow.com/questions/3537170 import itertools, operator def minima(lol, f=operator.itemgetter(1)): return list(next(itertools.groupby(sorted(lol, key=f), key=f))[1]) white = (255,255,255) gray = (50,50,50) import random as r def randomColor(): return (r.randrange(255),r.randrange(255),r.randrange(255)) de...
import shutil import numpy as np import random from sklearn import preprocessing from config import * def generateKfoldCrossValidataData(fold = 5, isShuffle = True, isPreProcessing = False, dataDir = dataDir, startOver = True): if startOver and os.path.exists(dataDir): # clean previously generated data ...
# -*- coding: utf-8 -*- # @Time : 2020/7/25 17:34 # @Author : CaiXin # @File : test_VO_pose.py ''' 用来测试训练后的Pose net,即VO模型 有位姿图优化PGM模块,但是只做位姿记录,不做优化 开关介绍: --isDynamic:适用于有动态物体的测试集,能够额外输出光度误差的光度掩码 --isKitti:适用于带有位姿真值的kitti测试集;能够额外输出和真值比较得到误差 ''' import hashlib import os import torch from PIL import Imag...
from evennia import DefaultCharacter from evennia.commands.cmdset import CmdSet from base import ClassCommand from ..objects import Seed, HydroponicBed, Fertilizer, Vegetable from evennia.utils.spawner import spawn from Hail.world.prototypes import PRODUCE_LIST class Horticulturist(DefaultCharacter): pass class...
import os import sys import json from kivy.app import App from kivy.uix.boxlayout import BoxLayout from kivy.uix.floatlayout import FloatLayout from kivy.uix.popup import Popup from kivy.uix.treeview import TreeViewLabel from kivy.uix.screenmanager import ScreenManager, Screen from kivy.properties import ObjectProperty...
# -*- coding: utf-8 -*- import urllib import httplib from datetime import datetime import hmac import hashlib import socket import json import time import threading class ProductAPIError(Exception): pass class ConnectionPool: def __init__(self, host, protocol, size=10): self.protocol = protocol ...
import urllib.request #构建response类的实例response response = urllib.request.urlopen('https://www.baidu.com') #查看response类的类型 print(type(response)) #调用response类方法。read()来获取网页内容 #print(response.read().decode('utf-8')) #打印状态码 print(response.status) #打印响应的头信息 print(response.getheaders()) # response.getheaders()返回对象是一个列表:[(...
import os import json import re import string import random import numpy as np from collections import Counter from tqdm import tqdm import torch from torch.utils.data import Dataset, TensorDataset, DataLoader, RandomSampler, SequentialSampler from .utils import MyQADataset, MyDataLoader from .zest_evaluate import ...