text stringlengths 8 6.05M |
|---|
class Solution:
def findDisappearedNumbers(self, nums: List[int]) -> List[int]:
#return list((set(nums)^set([x for x in range(1,len(nums)+1)])))
if not nums:
return []
for i in range(len(nums)):
if nums[abs(nums[i])-1]>0:
nums[abs(nums[i])-1] *= -1
ans = []
for i in range(len(nums)):
if nums... |
import urllib.request, re, time, random, time, winsound, webbrowser
TARGET="June"
URL="https://store.htcvivecart.com/store/htcus/en_US/quickcart/ThemeID.40533800/OfferID.48383055501"
isFound=False
count=0
def check():
f=urllib.request.urlopen(URL)
source=f.read()
res=re.match(".*"+TARGET,str(source)... |
#!/usr/bin/python
# -*- coding:utf-8 -*-
# This is a dictionary script
# Author: Eason
import json
dict = {}
flag = 'a'
tod = 'p'
di = 'n'
while flag == 'a' or tod == 'p':
flag = raw_input("请输入选择项,(a)添加姓名,(s)查找姓名: ")
if flag == 'a':
print "请输入姓名、年龄和部门,谢谢。"
dict ['姓名'] = raw_input("姓名: ")
... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import django.utils.timezone
import django.core.validators
class Migration(migrations.Migration):
dependencies = [
('auth', '0001_initial'),
]
operations = [
migrations.CreateModel(
... |
# encoding:utf-8
__author__ = 'hanzhao'
import urllib
def run(msg):
if '<br/>' in msg: #为群聊消息时候
[FromUser,msg] = msg.split('<br/>')
else: #为个人消息时候
pass
if msg in ['打开英雄榜','.英雄榜']:
return 'http://www.battlenet.com.cn/wow/zh/'
if msg.startswith('英雄榜') a... |
#coding=utf-8
flag = bin(int('flag{0123456789abcdef}'.encode('hex'),16))[2:]
s='01' # or '10'
for i in range(len(flag)):
if flag[i]=='1':
s+=s[-2:][::-1]
else:
s+=s[-2:]
print hex(int(s,2))[2:-1]
#6565659565569a99665959555956a6a55959596aa696a69aa69959aaa6569aa9655a9aa69a95656965656669
r=""
tmp =... |
"""
views has functions that are mapped to the urls in urls.py
"""
import datetime
import io
from collections import OrderedDict
import xlsxwriter
from fuzzywuzzy import fuzz
from django.core import serializers
from django.core.exceptions import ObjectDoesNotExist
from django.http import HttpResponseForbidden, HttpResp... |
import mysql.connector
from mysql.connector import Error
try:
con = mysql.connector.connect(host='localhost', database='db_products', username='root', password='')
query = "SELECT * FROM tbl_products"
cur = con.cursor()
cur.execute(query)
records = cur.fetchall()
print("Number of recor... |
from config import config, desarollo
from flask_script import Manager, Server
#inportat funcion
from src import ini_app
configuracion = config['desarollo']
app = ini_app()
# configuracio del server
Manager = Manager(app)
Manager.add_command('runserver', Server(host='127.0.0.1', port=9200))
if __name__ == '__main_... |
import os
import sys
import csv
import json
import jsonschema
import requests
from pyelasticsearch import ElasticSearch
import xlrd
import xlwt
from base64 import b64encode
# set headers. UNCLEAR IF THIS IS USED PROPERLY
HEADERS = {'content-type': 'application/json'}
# get object from server
def get_ENCODE(obj_id):
... |
# Generated by Django 3.0.7 on 2020-10-09 07:42
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('cl_table', '0005_auto_20201009_0730'),
]
operations = [
migrations.CreateModel(
name='Stock',
fields=[
... |
from django.contrib import admin
from django.conf.urls import include
from django.urls import re_path
from stored_messages.tests.views import message_view, message_create, message_create_mixed
admin.autodiscover()
urlpatterns = [
re_path(r'^consume$', message_view),
re_path(r'^create$', message_create),
... |
from django.db import models
from django.utils import timezone
# from django.contrib.auth.models import User
from account.models import customUser
from django.urls import reverse
# Create your models here.
class Plant(models.Model):
name = models.CharField(max_length=100)
description = models.TextField()
date_poste... |
from xmind.tests import logging_configuration as lc
from xmind.core.topic import TopicElement
from xmind.tests import base
from unittest.mock import patch, Mock, PropertyMock, call
from xmind.core.const import (
TAG_TOPIC,
TAG_TOPICS,
TAG_TITLE,
TAG_MARKERREF,
TAG_MARKERREFS,
TAG_POSITION,
T... |
#!/usr/bin/env python3
import os
import pathlib
source_root = pathlib.Path(os.environ['MESON_DIST_ROOT'])
modfile = source_root / 'prog.c'
contents = modfile.read_text()
contents = contents.replace('"incorrect"', '"correct"')
modfile.write_text(contents)
|
# This file is part of the pyMOR project (http://www.pymor.org).
# Copyright 2013-2020 pyMOR developers and contributors. All rights reserved.
# License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
from pymor.core.base import ImmutableObject
class InstationaryProblem(ImmutableObject):
"""I... |
from ..base import *
from ..button import *
from ..toolbar import *
from ..dialog import *
class SnapButton(ToolbarButton):
def __init__(self, toolbar):
tooltip_text = "Enable snapping"
command = lambda: Mgr.update_locally("object_snap", "snap")
ToolbarButton.__init__(self, toolbar, "",... |
import numpy as np
import PIL.Image
import PIL.ImageDraw
import PIL.ImageFilter
import PIL.ImageFont
import PIL.ImageOps
from ..image import image_line
from .mullerlyer_parameters import _mullerlyer_parameters
def _mullerlyer_image(parameters=None, width=800, height=600, outline=20, background="white", **kwargs):
... |
import sys
if __name__ == "__main__":
ops = [l.strip() for l in sys.stdin]
SIGNAL = [1, 1]
for op in ops:
if op.startswith("noop"):
SIGNAL.append(SIGNAL[-1])
else:
_, v = op.split()
SIGNAL.append(SIGNAL[-1])
SIGNAL.append(SIGNAL[-1] + int(v... |
import os
def main():
for count, filename in enumerate(os.listdir("out/itemTrendDetail")):
data = str(filename).decode()
print(data)
if __name__ == '__main__':
main() |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
def Postorder_Traverse(root):
ret = []
stack = []
while True:
# the same as in order
while now:
stack.append([now, ... |
# -*- coding: utf-8 -*-
"""
Created on Sun Jun 2 18:36:46 2019
@author: Thomas
"""
import os
os.chdir('C:\\Users\\Thomas\\Documents\\Uni_masters\\Masterpraktikum')
from CustomDataset import CustomDataset
from CNN import SimpleCNN
import numpy as np
import pickle
import torch
from torch.utils.data import DataLoader
im... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.5 on 2016-04-20 21:45
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('contentt... |
import unittest
class Solution:
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
letter_to_ind = {}
l = 0
ans = 0
for r in range(len(s)):
if s[r] in letter_to_ind:
l = max(l, letter_to_ind[s[r]])
ans = max(ans, r - l + 1)
letter_to_ind[s[r]] = r + 1
return ans
cl... |
# coding: utf-8
# 导入数据集mnist
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("./../data/MNIST/", one_hot=True)
import tensorflow as tf
import os
INPUT_NODE = 784
OUTPUT_NODE = 10
IMAGE_SIZE = 28
NUM_CHANNELS = 1
NUM_LABEL = 10
# 第一层卷积层的尺寸和深度
CONV1_DEEP = 32
CONV1_SIZE... |
import peri0
import time
def touchsound():
buzzer = peri0.Buzzer()
buzzer.set_tempo(180)
buzzer.tone(4,"MI",1/8)
def opensound():
buzzer = peri0.Buzzer()
buzzer.set_tempo(120)
opensound = ((4,"DO",1/4), (4,"MI",1/4),(4,"SOL",1/4))
buzzer.play(opensound)
def closesound():
buzzer = per... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from vdgnn.units import DynamicRNN
class DiscriminativeDecoder(nn.Module):
def __init__(self, args, encoder):
super(DiscriminativeDecoder, self).__init__()
self.args = args
# share word embedding
self.word_embed =... |
import re
import psutil
import misc
import socket
from mylogger import iotlogger
logger = iotlogger(loggername="DevStatus")
def handle_exception(function):
def wrapper_function(*args, **kwargs):
try:
return function(*args, **kwargs)
except Exception as e:
logger.error("Erro... |
# Generated by Django 2.2.3 on 2019-10-24 17:21
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Background',
fields=[
('id', models.AutoFie... |
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def index():
return 'Hello'
@app.route('/about')
def about():
return 'Built by Chris Grant'
if __name__ == '__main__':
app.debug = True
app.run('localhost', port=3000)
|
from mod1 import City
mayor = City(10000)
mayor.gradual_peace(5000) |
# start pt2 8:55 - paused 9:30
# unpaused 13:30 - solved pt2 13:50
for noun in range(100):
for verb in range(100):
filepath = 'input_2019-2.txt'
with open(filepath) as fp:
xintcode = [int(x) for x in fp.readline().split(",")]
# print( noun, verb )
xintcode[1] = n... |
import scipy as sp
import OpenPNM
import pytest
def test_find_connected_pores():
pn = OpenPNM.Network.Cubic(shape=(10,10,10))
a = pn.find_connected_pores(throats=[0,1])
assert sp.all(a.flatten() == [0, 1, 1, 2])
a = pn.find_connected_pores(throats=[0,1], flatten=True)
assert sp.all(a == [0, 1, 2])
... |
import cv2
import numpy as np
from time import sleep
width_min=80 #MIN WIDHT
height_min=80 #min height
offset=6
pos_line=550 #LINE POSITION
delay= 60 # VIDEO FPS
detect = []
cars= 0 # NO of CARS
def takes_center(x, y, w, h): # FRAME CENTER
x1 = int(w ... |
#! /usr/bin/python
class HelloWorld():
def __init__(self):
self.words = ['Beijing','Chongqing','Shanghai']
self.capitals = ['Beijing','WashtionDC','Berlin']
def printword(self):
for w in self.words:
if w == 'Beijing':
print 'Beijing is the capital of China'
else:
for c in self.capitals:
if ... |
import Functions.datafunctions as df
import Functions.vasicek_loop as vl
import numpy as np
import scipy.stats as stats
import matplotlib.pyplot as plt
delinq_data = df.get_data()
last_pd = {}
score_b = delinq_data["CREDIT_BUCKET"].unique()[delinq_data["CREDIT_BUCKET"].unique() != "No Score"]
for c in score_b:
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 1 17:13:02 2020
@author: baxcruiser
"""
n=int(input())
ar=list(map(int,input().strip.split()))
pairs = 0
for element in set(ar):
pairs += ar.count(element) // 2
print(pairs)
|
import os
class Node:
"""Data structure for creating n-ary trees.
"""
def __init__(self, word, index=1, parent=None):
self.index = index
self.word = word
self.parent = parent
self.children = []
def add_child(self, word):
if self.has_child(word):
re... |
print("Welcome to hello world! \n\n")
|
import requests
from lxml import etree
from urllib import request
import os
import re
import threading
from queue import Queue
class Producer(threading.Thread):
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36'
... |
import solve
data = [
[5, [2, 1, 2, 6, 2, 4, 3, 3], [3,4,2,1,5]],
[4, [4,4,4,4,4], [4,1,2,3]]
]
def test(N, stages, res):
ans = solve.solution(N, stages)
assert ans == res
for d in data:
test(d[0], d[1], d[2]) |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Author: Gusseppe Bravo <gbravor@uni.pe>
# License: BSD 3 clause
"""
This module provides the logic of the whole project.
"""
import define
#import analyze
import prepare
import feature_selection
import evaluate
import time
import os
from pyspark.ml import Pipeline
from p... |
#!/usr/bin/python3
class Point:
""" Create a new Point, at coordinates x, y """
def __init__(self, x=0, y=0):
""" Create a new point at x, y """
self.x = x
self.y = y
def distance_from_origin(self):
""" Compute my distance from the origin """
return ((self.x ** 2)... |
import sys
import multiprocessing
import threading
import ipyparallel
import numpy as np
from time import time
import pickle
import argparse
def timer(fn):
"""Timing decorator"""
def timed(*args, **kwargs):
start = time()
result = fn(*args, **kwargs)
end = time()
print(fn.__nam... |
class Solution(object):
def isPowerOfThree(self, n):
"""
:type n: int
:rtype: bool
"""
if n == 0: return False
while n % 3 == 0:
n /= 3
return n == 1
def isPowerOfThreeR(self, n):
"""
:type n: int
:rtype: bool
"... |
import argparse
import base64
import json
import sys
import functools
import requests
def generate_json_data(image_filename, output_filename):
"""Translates the input file into a json output file.
Args:
input_file: a file object, containing lines of input to convert.
output_filename: the nam... |
class DuplicateHandlerError(Exception):
""" Raised when a handler with a duplicate id or shortcode exists. """
class InvalidStateChange(Exception):
""" Raised when an invalid state change is executed (e.g. closing an open
ticket without the intermediary 'pending' step).
"""
|
from django.contrib import admin
from import_export import resources
from import_export.admin import ImportExportModelAdmin
from products.models import Product
from . import models
class ProductInline(admin.StackedInline):
model = Product
fields = ('id', 'name', 'price')
extra = 0
show_change_link = ... |
import csv
import re
def get_category_list(category_string):
if not re.search('[a-zA-Z]', category_string):
return []
category_string.lower()
category_string.strip()
return re.split('\*',category_string)
def title_string_to_file_name(title_string):
title_string.strip()
title_string = ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from plugins.plugin import Plugin
from components.constants import *
class Dilatacao(Plugin):
def __init__(self):
self.x = 0
self.y = 0
self.w = 0
self.h = 0
pass
def set_properties(self, data):
#Escrev... |
import sys, time, json, time, random, string
from argparse import ArgumentParser
from datetime import datetime
from kafka import KafkaProducer
def randomname(n):
return ''.join(random.choices(string.ascii_letters + string.digits, k=n))
def get_option(topic, num):
argparser = ArgumentParser(description='This s... |
import os
import joblib
import pandas as pd
import statsmodels.api as sm
class Modeler_Price:
def __init__(self):
self.df = pd.read_csv('D:/MY DATA\Desktop/DB/Proposal/new Senior/Models Deployment/All Models/modeler/Price_Deployment_Data.csv')
try: self.model = joblib.load('models/price.mo... |
N = int (input ())
M = int (input ())
print (N * M * (N + 1) * (M + 1) // 4) |
######saral que 4
# number=[50,40,23,70,56,12,5,10,7]
# i=0
# sum=number[i]
# length=len(number)
# while i<length:
# a=number[i]
# if a<sum:
# sum=a
# i=i+1
# print(a,"is second greater number") |
import zipfile,re
zf = zipfile.ZipFile("channel.zip","r")
num = 90052
comments = []
while True:
try:
num = int(re.findall('\d+',zf.read(str(num)+".txt"))[0])
except:
print zf.read(str(num)+".txt")
break
comments.append(zf.getinfo(str(num)+".txt").comment)
print "".join(comments)
... |
###################################################
## By Dan Melacon, Jeff Ong, and Kat Sullivan
###################################################
import serial, sys, binascii
addresses={
'radio1': '0013A200409756B8',
'radio2': '0013A200409756BD',
'radio3': '0013A20040975703',
'radio4': '0013A200409756E2'
}
r... |
#ex016.py:私有成员的访问
class A:
def __init__(self, value1=0, value2=0):
self._value1 = value1
self.__value2 = value2
def setValue(self, value1, value2):
self._value1 = value1
self.__value2 = value2
def show(self):
print(self._value1)
print(self.__value2)
|
import torch
import torch.nn as nn
import numpy as np
from edflow.util import retrieve
from iin.models.ae import FeatureLayer, DenseEncoderLayer, weights_init
class Distribution(object):
def __init__(self, value):
self.value = value
def sample(self):
return self.value
def mode(self):
... |
import keras
from keras import models, layers
from keras import backend
class CNN(models.Sequential):
def __init__(self, inputShape, numOfClass):
super().__init__()
self.add(layers.Conv2D(32, kernel_size = (3, 3),
activation = 'relu',
... |
from django import forms
from django.contrib.auth.models import User
from .models import *
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm, UsernameField
from django.contrib.admin.widgets import AdminDateWidget
from django.forms.fields import DateField
from django.forms import CharField, Mode... |
def do():
month = int(input('Введите номер месяца: '))
print('Решение через списки')
winter = [1, 2, 12]
spring = [3, 4, 5]
summer = [6, 7, 8]
autumn = [9, 10, 11]
if month in winter:
print('Зима')
elif month in spring:
print('Весна')
elif month in summer:
pr... |
import cv2
import time
from invoke import run
cmd = "xdotool search --onlyvisible --class 'Chrome' windowfocus key 'space'"
cap = cv2.VideoCapture(0)
r_t = (70,200)
r_b = (200,370)
last_jump = time.time()
while (True):
_, frame = cap.read()
frame_copy = frame.copy()
frame = cv2.cvtColor(frame, cv2.COLOR_RG... |
r"""
Composition Statistics (:mod:`skbio.stats.composition`)
=======================================================
.. currentmodule:: skbio.stats.composition
This module provides functions for compositional data analysis.
Many 'omics datasets are inherently compositional - meaning that they
are best interpreted as... |
#!/usr/bin/python
# Copyright (C) 2009, Sugar Labs
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is... |
import re
from DisplayFile import DisplayFile
from Figuras import Poligono
class DescritorOBj:
def __init__(self):
self.DisplayFile = DisplayFile()
def importFile(self, path):
self.DisplayFile.limpar()
vertices = dict()
vertice_counter = 0
nome = ""
self.file = open(path, "r+") # read an... |
#Keyboard row
class Solution(object):
def findWords(self , words):
r1 = set('qwertyuiop')
r2 = set('asdfghjkl')
r3 = set('zxcvbnm')
return[w for w in words if any(set(w.lower()) <= r for r in (r1 , r2 , r3))]
s = Solution()
words = ["Hell... |
from collections import OrderedDict
import numpy as np
from typing import Dict
from module import Module, Parameter
from operators import PlusOperator, MulOperator
class FullyConnectedLayer(Module):
def __init__(self,
input_size: int,
output_size: int,
w_init_p... |
# -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# https://doc.scrapy.org/en/latest/topics/items.html
from scrapy import Item,Field
class ScrapyItem(Item):
image_url=Field()
class JianshuItem(Item):
nickname = Field()
description = Field()
followed = ... |
import maya.cmds as cmds
import os
from functools import partial
import Utils.Utils_File as fileUtils
#NOET: Remove this import!
import Utils.Utils_Part as Utils_Part
reload(Utils_Part)
class PartParam_UI:
def __init__(self, *args):
""" Create a dictionary to store UI elements """
self.U... |
one = ["Primeiro", "Segundo", 3, 4]
print ("Lista eh", one);
print ("Olha o ", one[-4], " position -4")
|
#coding: utf8
import util_pickle as up
from char_feature import *
from char_feature_lib_builder import *
from switcher import *
# FeatureDiv = 10000
FDIV = 10000
def get_allowance_list():
lst = [0]
for k in range(10000 * 0.10): #容许度 10%
lst.extend([k, -k])
return lst
def search_recur(ftree, t... |
# This file is only intended for development purposes
from kubeflow.kubeflow.cd import base_runner
base_runner.main(component_name="notebook_controller",
workflow_name="nb-c-build")
|
from selenium import webdriver
from time import sleep
driver = webdriver.Chrome()
driver.get("https://www.baidu.com")
driver.set_window_size(480,800) #控制浏览器的大小
sleep(2)
driver.refresh()
sleep(2)
driver.maximize_window() #浏览器全屏
sleep(2)
driver.get("https://www.baidu.com")
sleep(1)
driver.back() #浏览器后退
sle... |
import math # 调用数学库
# from math import pi
def main(): # 计算圆的面积
r = eval(input("请输入待求圆的半径")) # input()输入圆的半径 并对输入的字符串进行格式转换(eval())
SquareR = pow(r, 2)
# pow()函数为幂计算所用 其中pow(a,b)代表的是a的b次幂
# pow(Exp,x)->e^x
S = SquareR * math.pi
# 此处的math.pi为精度很高的常数 存放在math库中
# S = math.pi*r*r
# prin... |
#컴퓨터가 생각하는 수를 맞추기
#기회는 6번
#6번 이후에는 정답을 출력한다.
import random as r
root = tk.Tk()
root.geometry("200x200")
q_num = r.randint(1,100)
print("----숫자 맞추기---", q_num)
for num in range(1,7):
u_ans = int(input("%d번째 예상 숫자: "% num))
if u_ans == q_num:
print("정답이야!!")
break
if u_ans > q_num:
... |
# Generated by Django 3.2.6 on 2021-08-30 04:52
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('product_register', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='ProductOptio... |
"""
Type definition for model parameters
"""
from pydantic import BaseModel as _BaseModel, Extra, root_validator, validator
from pydantic.dataclasses import dataclass
from functools import partial
from datetime import date
from typing import Any, Dict, List, Optional, Union
from autumn.settings.constants import (
... |
import PyPDF2
import nltk
from os import walk
from nltk.tokenize import word_tokenize, sent_tokenize
from nltk.corpus import stopwords
def get_all_files(folder_name):
f =[]
for (dirpath, dirnames, filenames) in walk(folder_name):
f.extend(filenames)
return f
def save_text_file(file_name, file_tex... |
# -*- coding: utf-8 -*-
# flake8: noqa
# Generated by Django 1.10.7 on 2017-06-08 15:27
from __future__ import unicode_literals
import ckeditor_uploader.fields
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('pages', '0012_auto_20170531_1612'),
]
... |
# -*- coding: utf-8 -*-
"""
Created on Fri Apr 23 17:04:33 2021
@author: THIS-PC
"""
from tensorflow import keras
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
from tensorflow.keras import regularizers
from tensorflow.keras import metrics
import scipy.misc
import os
import numpy as np
fro... |
import numpy as np
import PIL.Image
import matplotlib.pyplot as plt
def load_image(filename, max_size=None, shape=None):
# PIL.Image.LANCZOS is one of resampling filter
image = PIL.Image.open(filename)
if max_size is not None:
factor = max_size / np.max(image.size)
# Scale the image"s height and widt... |
a=list(input('Enter the list'))
a*=0
print(a) |
from flask import Flask
from flask import jsonify
from flask import request
from logging.handlers import RotatingFileHandler
from chat_service import chat
from config import Config
import logging
app = Flask(__name__)
app.config['PROPAGATE_EXCEPTIONS'] = False
@app.route("/chat", methods=['POST'])
def login():
d... |
import sys
import os
from conans.client.output import ConanOutput
from conans.client.rest.uploader_downloader import Downloader
from conans.client.tools.files import unzip, check_md5, check_sha1, check_sha256
from conans.errors import ConanException
_global_requester = None
def get(url, md5='', sha1='', sha256=''):... |
# -*- coding: utf-8 -*-
import re
from math import ceil
from ipcalc import Network
from django.db import models
from django.core.exceptions import ValidationError
from django.core.urlresolvers import reverse
from datetime import datetime
from django.utils.timezone import get_default_timezone
STATUS_ALLOCATED = u'al... |
import mmh3
from bitarray import bitarray
import math
class BloomFilter:
def __init__(self, false_positive_rate, estimated_word_count):
#find size and number of hashes desired for false positive rate and word count
self.size = int((-estimated_word_count * math.log(false_positive_rate)) / (math.lo... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
class Consulta(models.Model):
codigo = models.AutoField(primary_key=True)
user_codigo = models.CharField(max_length=10)
date = models.CharField(max_length=14)
hora = models.CharField(max_length=10)
coment... |
#This is a sketchy Ripoff of pong using TK graphics
#There will be two players, each controlled by a different set of keys, and there will be at least one ball
import tkinter # built-in Python graphics library
import os
import random
balls = []
players = []
class Thing():
def __init__(self,x,y):
self.x = ... |
with open("./learning_python.txt", "r") as f:
origin = f.read()
copyed=origin.replace("python","C")
with open("./learning_python_copyed.txt","w") as f:
f.write(origin+"\n"+copyed) |
import os, sys
import gmsh
import numpy as np
# ========================================================= #
# === make__magnet routine === #
# ========================================================= #
def make__magnet():
# ------------------------------------------------- #
#... |
class Goods:
def __init__(self):
# 商品原始价格
self.original_price = 100
# 商品折扣
self.discount = 0.8
@property
def price(self):
# 实际价格 = 原价 * 折扣
return self.original_price * self.discount
@price.setter
def price(self,val):
self.original_... |
import pygame
from src.gameObject import GameObject
from src.sprite import SpriteSheet
class Character(GameObject):
def __init__(self, color, spritePath):
super().__init__()
self.color = color
self.dimension = [40.0, 60.0]
self.sprite = SpriteSheet(spritePath, 4, .25)
self.s... |
import numpy as np
from time import time
import random, string
from Model.model import Model
m = Model(print_obj={
'start_conf': True,
'end_conf': True
})
def get_by_key(arr,key):
result = []
for i in arr:
result.append(i[key])
return np.array(result)
blocks = [
{"pred": [], '... |
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
import random
plt.style.use('fivethirtyeight')
data = pd.read_csv('insurance.csv')
#data.describe()
#data.info()
data.hist('charges') #A single variable plot, showing how often it meets
quant_95 = data['charges']... |
'''
Created on Nov 3, 2015
@author: Jonathan
'''
def clubsize(names, club):
return len(set(names) & set(club))
if __name__ == '__main__':
pass |
#Read an integer N . For all non-negative integers i < N, print i^2. See the sample for details.
if __name__ == '__main__':
n = int(raw_input())
for i in range(n):
print(i*i)
|
#!/usr/bin/env python
# Jamie Bodeau
# Imports -------------------------------------------------
import sys
# Classes -------------------------------------------------
# Functions -----------------------------------------------
# Main Execution ------------------------------------------
if __name__ == "__main... |
a=input()
b=input()
a=int(a)
b=int(b)
c=(a**2+b**2)**0.5
print(c) |
# Generated by Django 3.0.8 on 2020-07-17 14:00
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('reviews', '0004_auto_20200717_2200'),
('message', '0002_auto_20200717_2200'),
('profiles', '0008_auto_20200717_2200'),
]
operations = [
... |
import torch
import torch.utils.data as Data
import json
import os
from PIL import Image
import git_ssd-transform as ssd_transform
"""
创建自己的数据集
需要定义__len__方法,返回的是dataset的数量
需要定义__getitem__方法,返回的是第i个图像,bboxes、labels.基于的是json文件
Dataset是一个抽象类,所有自定义的Dataset需要继承它并复习__getitem__()函数,即接收一个索引,返回一个样本
__getitem__:返回一条数据或一个样本
__... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.