text
stringlengths
8
6.05M
import sys import os from PIL import Image # Grab first and second argument poke_path = sys.argv[1] new_path = sys.argv[2] # Check is new/ exists, if not create if not os.path.exists(new_path): os.mkdir(new_path) # Loop through Pokedex, convert images to PNG for filename in os.listdir(poke_path): img = Image...
registry = dict(version=0) def bind(): from cPickle import loads as _loads _lookup_attr = _loads('cchameleon.core.codegen\nlookup_attr\np1\n.') _init_scope = _loads('cchameleon.core.utils\necontext\np1\n.') _re_amp = _loads("cre\n_compile\np1\n(S'&(?!([A-Za-z]+|#[0-9]+);)'\np2\nI0\ntRp3\n.") _attrs_...
# Generated by Django 2.1.12 on 2019-11-05 04:32 import django.contrib.postgres.fields from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('course_rater_app', '0002_auto_20191105_0427'), ] operations = [ migrations.AlterField( mo...
from Exceptions import BFSyntaxError, BFSemanticError from Token import Token from functools import reduce """ This file holds functions that generate general Brainfuck code And general functions that are not dependent on other objects """ # ================= # Brainfuck code # ================= def get_set_cell_...
_plants = { 'C': 'Clover', 'G': 'Grass', 'R': 'Radishes', 'V': 'Violets' } _children = [ 'Alice', 'Bob', 'Charlie', 'David', 'Eve', 'Fred', 'Ginny', 'Harriet', 'Ileana', 'Joseph', 'Kincaid', 'Larry' ] class Garden(): def __init__(self, garden, students=_children): self...
#!/usr/bin/env python # Funtion: # Filename: # 假设密码为 123 # 则shell下自动输入密码的语句为: # echo "123" | sudo -S apt-get upgrade # echo "123" | sudo -S apt-get install vim # 可以查看标准文档 sudo --help import subprocess subprocess.Popen("echo '123' | sudo -S apt-get upgrade", shell=True)
from flask import request from gateway.app import app from gateway.http_client import filemanager_http_client from gateway.utils.handle_api import ( get_client_username,handle_request_response ) @app.route('/file/create',methods=['POST']) @handle_request_response @get_client_username def file_create(client_usern...
import time import os import torch import math import logging from conf.train.train_conf_expandnet import get_config from utils import utils from models import create_model from data import create_dataset, create_dataloader def main(): conf = get_config() utils.mkdir_experiments(conf.experiments_dir) uti...
from rest_framework import generics, status, permissions from rest_framework.response import Response from rest_framework.views import APIView from django.shortcuts import get_object_or_404 from .models import Profile from authors.apps.authentication.models import User from authors.apps.articles.models import Article f...
""" Definition of forms. """ from django import forms from app.models import WellInstance, WellInfo, GeoInfo, RiskProfile class WellForm(forms.ModelForm): class Meta: model = WellInstance fields = ['Country', 'State', 'City', 'Well'] class WellInfoForm(forms.ModelForm): class Meta: ...
#!/usr/bin/python2.7 # Standard library imports. from contextlib import closing from sqlite3 import connect # The path of the database. db_path = r"/mnt/c/Users/Amanda/Desktop/spring-2018/is211/pets.db" # The query used to query people. select_person = """ SELECT first_name, last_name, age FROM per...
import pytest from autumn.settings import Models from autumn.core.project.project import _PROJECTS, get_project COVID_PROJECTS = list(_PROJECTS[Models.COVID_19].keys()) COVID_CALIBS = list(zip(COVID_PROJECTS, [Models.COVID_19] * len(COVID_PROJECTS))) TB_PROJECTS = list(_PROJECTS[Models.TB].keys()) TB_CALIBS = list(zi...
import os from glob import glob import random import numpy as np from PIL import Image def Ramen_Dataset(): root_dir = os.path.dirname(os.path.realpath(__file__)) train_path = os.path.join(root_dir, 'dataset', 'train', '*\\*.png') test_path = os.path.join(root_dir, 'dataset', 'val', '*\\*.png') train_...
from bocadillo import App,view app = App() @app.route("/") async def index(req, res): res.text = "" @app.route("/user") @view(methods=["post"]) async def greet(req, res): res.text = "" @app.route("/user/{id}") async def user_info(req, res, id): res.text = id
import pytest import pytest_check as ck @pytest.mark.p0 @pytest.mark.api def test_query_fuel_card_normal(api,data): '''正常查询加油卡''' request_data = data.get('test_query_fuel_card_normal') res_dict = api.request_all(request_data).json() print(f'响应数据{res_dict}') # 响应断言 ck.equal(200, res_dict.get("co...
from django.core.management.base import BaseCommand, CommandError from django.utils import timezone from youtube.services import YoutubeService from youtube.models import Video from core.utils import db_table_exists class Command(BaseCommand): help = 'Get MostViewed Videos from Youtube and adds them to database' ...
# pylint: disable=duplicate-code, too-many-statements ''' Unit test for user model integration ''' import unittest import logging from test.common import async_test, UserModelTestCase from PIL import Image from utils import image_to_file # Initialize loggers logging.basicConfig(level=logging.WARNING) class TestTrai...
# 727. Minimum Window Subsequence ''' Given strings S and T, find the minimum (contiguous) substring W of S, so that T is a subsequence of W. If there is no such window in S that covers all characters in T, return the empty string "". If there are multiple such minimum-length windows, return the one with the left-mos...
#! /usr/bin/env python # -*- coding: utf-8 -*- """ #------------------------------------------------------------------------------ # Input Shaping Module - InputShaping.py # # Python module for the input shaping toolbox # - Adapted from MATLAB input shaping toolbox # # Created: 2/18/13 - Joshua Vaughan - joshua.vaug...
import numpy as np def loadDataSet(fileName): dataMat = [] labelMat = [] fr = open(fileName) for line in fr.readlines(): lineArr = line.strip().split('\t') dataMat.append([float(lineArr[0]), float(lineArr[1])]) labelMat.append(float(lineArr[2])) return dataMat, labelMat de...
import sys input = sys.stdin.readline def main(): N, P = map(int,input().split()) AB = [ tuple(map(int,input().split())) for _ in range(N)] AB.sort(reverse=True) dp = [0]*(P+1) ans = 0 for a, b in AB: if ans < dp[P]+b: ans = dp[P]+b for i in range(P,a-1,-1): ...
#Receba um número. Calcule e mostre a série 1 + 1/2 + 1/3 + ... + 1/N. n=int(input('digite um numero: ')) c=int(1) s=int(0) while c<=n: print(f'1/{c}+') s+=1/c c+=1 print(f'={s}')
# -*- coding:utf-8 -*- import json from Appointment.APmodel import APmodelHandler from BaseHandlerh import BaseHandler # 约拍伴侣 from Database.tables import WApCompanions, WAcAuth from FileHandler.ImageHandler import ImageHandler class ApCompanionHandler(BaseHandler): retjson = {'code':'', 'contents':''} def...
def soma(n1, n2): resp = n1 + n2 return resp retorno_soma = soma(0, 1024) print(retorno_soma)
import requests import datetime import random from django.db import models from django.db.models import Sum from django.contrib.auth.models import User from django.template.loader import render_to_string from django.template.defaultfilters import linebreaks from django.urls import reverse from django.utils import time...
import json import numpy as np import cv2 import matplotlib.pyplot as plt from PIL import Image import bit_stream_decoder import byte_stream_generator import channel_restorer import histogram_generator import huffman_code_decode_generator import image_compressor file_name = 'images/img.png' original_ima...
import json import logging import os import time import urllib import boto3 import numpy as np import pandas as pd import regex as re from util.aws.s3 import s3_exists def _parse_transcription(handle, speaker_labels={}): if isinstance(handle, str): from util.aws.s3 import s3_download handle = op...
#!/usr/bin/python """finding the area of a general space using only the boundry points this will only work for solid space as of now""" print "points:" raw_points = raw_input().split(' ') points = [] if (len(raw_points) % 2 == 1): raise Exception('not a list of points') else: for i in xrange(0,len(raw_points),2): ...
from measurements.api.viewsets import TemperatureViewSet, HumidityViewSet, ElectricityViewSet, WaterViewSet, PollutionViewSet, ConfigViewSet from rest_framework import routers router = routers.DefaultRouter() router.register('temperature', TemperatureViewSet, base_name='temperature') router.register('humidity', Humidi...
# print(f" Episode {episode_trajectory}") # print(f" State Value {new_state[0]} ")
import copy class Polynomial: def __init__(self, dictpoly={}): """initializing dictionary of polynomial""" self.dictpoly = dictpoly def printpoly(self, expo): """print coefficient of each needed exponent""" if self.dictpoly.has_key(expo) == 1: polyprint = self.dictpoly[expo] else: polyprint ...
def show_magicians(magicians_name): for name in magicians_name: print(name) magicians_name = ['aaa', 'bbb', 'ccc'] show_magicians(magicians_name)
import glob import os for file in glob.glob("*.c"): if os.access(file, os.R_OK): print(file)
from nanpy import (ArduinoApi, SerialManager, Servo) from time import sleep try: connection = SerialManager() a = ArduinoApi(connection = connection) except: print("Failed to connect to Arduino") servoPins = list() for i in range(6): number = ""; try: number = int(input("Enter ServoPWM pi...
import json import datetime from yoolotto.legacy.models import Drawings as LegacyDrawings, Drawings2 as LegacyDrawings2 from yoolotto.lottery.game.manager import GameManager from yoolotto.lottery.models import LotteryGameComponent, LotteryDraw from yoolotto.util.serialize import dumps class MigrateDraws(object): ...
try: from .pglocal import * except: try: from .sqlite import * except: pass try: from .production import * except: pass
#encoding=utf-8 import pymongo,os def connect_mongodb(): # servers="mongodb://localhost:27017" # conn = pymongo.Connection(servers) # print conn.database_names() # db = conn.my_mongodb #连接库 client = pymongo.MongoClient("localhost", 27017) print client.database_names() db=client.test print db.collect...
from flask import Flask,render_template,request,redirect,url_for import pymysql app=Flask(__name__) @app.route("/update_action/<int:movie_id>", methods=['GET','POST']) def update_action(movie_id): if request.method=="POST": sql="update new_movies.my_movies set movie_name=(%s), timing=(%s), location=(%s) ...
import argparse import pathlib from common import copytree, get_package_root def main(directory, source_folder, target_root): """ Copies the source folder and its subfolders to the package, under the desired target_root. This will not verify the target_root is proper. """ source_folder = pathlib.P...
n = input () l = len (n) s = 0 for i in range (l): s += int (n [i]) s1 = 3 - s % 3 for i in range (l): p = int (n [i]) + s1 if p < 10: p += (9 - p) // 3 * 3 n = n [:i] + str (p) + n [i + 1:] print (n) break elif i == l - 1: p = int (p - 1.5 * s1 ** 2 + 4.5 * s1 - 6) ...
# spiral.py # COMP9444, CSE, UNSW import torch import torch.nn as nn import matplotlib.pyplot as plt import math class PolarNet(torch.nn.Module): def __init__(self, num_hid): super(PolarNet, self).__init__() # INSERT CODE HERE input_nodes = 2 output_nodes = 1 self.layer_on...
#### -*- coding:utf-8 -*- ####### import socket from protocol import PackagedConnection, ClientDisconnected, BrokenPackage from server import PING, PONG, CLOSE from threading import Thread def main(): test_data = [ b"SOME DATA", b"B"*5000, b"", b"1234567890", b"LOL" ] ...
import socketio sio = socketio.Client() def sendMessage(event_name, data, namespaceSIO): #callback function sio.emit(event_name, data, namespace=namespaceSIO) print("message emitted") @sio.on('responsepi', namespace='/socket') def responsepi(msg): print('I received a message!', msg['data']) def ...
#!/usr/bin/env python import math import pickle from random import randint from itertools import permutations from sets import Set MAX_SEARCH_LEN=2 C1=1.95 C2=1.95 class node(): def __init__(self,parent,val): self.val=val self.parent=parent self.nextDict=None self.completed=False ...
import os import re class IncludeParser: def __init__(self, strict=True): self.__strict = strict def get_includes(self, filename, include_dirs, args): filedir = os.path.dirname(os.path.abspath(filename)) def list_includes(filename): ...
if __name__ == "__main__": usernames = [ 'beheerder', 'kjevo', 'user345', 'user89', 'user092' ] for username in usernames: print("Hello! " + username) if username == "beheerder": print("Do you want a status rapport? \n")
""" For use in dumping single frame ground truths of EuRoc Dataset Adapted from https://github.com/ClementPinard/SfmLearner-Pytorch/blob/0caec9ed0f83cb65ba20678a805e501439d2bc25/data/kitti_raw_loader.py You-Yi Jau, yjau@eng.ucsd.edu, 2019 Rui Zhu, rzhu@eng.ucsd.edu, 2019 """ from __future__ import division import num...
import multiprocessing from matplotlib import pyplot as plt import numpy as np def merge_by_y(left, right): """ Implements merge of 2 sorted lists by the second coordinate :param args: support explicit left/right args, as well as a two-item tuple which works more cleanly with multiprocessi...
import colorgram colors = colorgram.extract('image.jpg',6) color_list = [] for color in (colors): r = color.rgb.r g = color.rgb.g b = color.rgb.b new_color = (r,g,b) color_list.append(new_color) print(color_list)
""" Given two arrays, write a function to compute their intersection. Example 1: Input: nums1 = [1,2,2,1], nums2 = [2,2] Output: [2,2] Example 2: Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4] Output: [4,9] Note: Each element in the result should appear as many times as it shows in both arrays. The result can be in an...
import math a = int(input('Enter A value:')) b = int(input('Enter B value:')) c = int(input('Enter C value:')) if (a**2+b**2)==c**2: print('Given Triangle is rectangle') else: print('Given Triangle is not rectangle')
import serial import time x = (input('Enter size:'+'\n'+'a.Small'+'\t\t'+'b.Big'+'\t\t')).lower() y = (input('Enter color:'+'\n'+'a.green'+'\t\t'+'b.Red'+'\t\t')).lower() ser = serial.Serial('COM5', 9600, timeout=1) time.sleep(3) if(x == "small" and y == "blue"): ser.write(b'A') time.sleep(1) elif(...
from django.db.models.signals import post_save, pre_save, pre_delete from django.dispatch import receiver from django.db.models import F from sale.models import Stock, Transfer @receiver(post_save, sender=Transfer) def TransferInToStockSignal(sender, instance, created, **kwargs): if not created: pass detail = { ...
# coding: utf-8 import tensorflow as tf HIDDEN_SIZE = 1024 # LSTM的隐藏层规模。 NUM_LAYERS = 2 # 深层循环神经网络中LSTM结构的层数。 SRC_VOCAB_SIZE = 10000 # 源语言词汇表大小。 TRG_VOCAB_SIZE = 4000 # 目标语言词汇表大小。 BATCH_SIZE = 100 # 训练数据batch的大小。 NUM_EPOCH = 5 # 使用训练数据的轮数。 KEEP_PROB = 0.8 # 节点不被dropout的概率。 MAX_GRAD_NORM = 5 # 用于控制梯度膨胀的梯度大小上限。...
from selenium.webdriver import Chrome from selenium.webdriver.chrome.options import Options import sys from time import sleep def get_safety(place): options = Options() options.headless = True place = place.lower() place = place.replace(' ', '-') # insert your chromedriver path driver = Chrom...
import numpy as np import pandas as pd import log import matplotlib.pyplot as pl import matplotlib.dates as mdates import datetime DATAFRAME = pd.DataFrame.from_dict(log.DATA, orient='index') #print(DATAFRAME) #print(DATAFRAME["push_ups"]) def str_to_datenums( str_dates ): datenums = [] for date_str in str_d...
import pydot from Cp7_test.cmp.utils import ContainerSet class NFA: def __init__(self, states: int, finals: iter, transitions: dict, start=0): self.states = states self.start = start self.finals = set(finals) self.map = transitions self.vocabulary = set() ...
''' Created on Oct 13, 2015 @author: Jonathan Yu ''' def getFortunate(a, b, c): sums = [] for i in a: for j in b: for k in c: sums.append(i + j + k) num = 0 for sum in set(sums): isFortunate = True for digit in str(sum): if not ((digit ==...
#!/usr/bin/env python # -*- coding: utf-8 -*- from setuptools import setup, find_packages with open('README.rst') as readme_file: readme = readme_file.read() with open('HISTORY.rst') as history_file: history = history_file.read() requirements = [ 'cliff', 'datakit-core', 'requests' ] test_requi...
import os import re ################## CHANGE HERE ONLY ################## # The name of module you want name_module = "adc_list" # Brief description of module description_module = "Analog-to-Digital Converter (ADC)" # name_driver = "stm_driver.h" # The path of repository ksdk_path = "e:/C55SDK/sdk_codebase/" ...
#!/usr/bin/env python # -*- coding: utf-8 -*- from typing import Any, Callable, Iterator, Tuple, Type import pytest from flask import Flask from marshmallow import Schema from smorest_sfs.modules.email_templates.models import EmailTemplate @pytest.fixture def email_template_items( flask_app: Flask, temp_db_inst...
# -*- coding:utf-8 -*- """ 请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有 字符的路径。路径可以从矩阵中的任意一个格子开始,每一步可以在矩阵 中向左,向右,向上,向下移动一个格子。如果一条路径经过了矩阵中的 某一个格子,则之后不能再次进入这个格子。 例如 a b c e s f c s a d e e 这样的3 X 4 矩阵中包含一条字符串"bcced"的路径,但是矩 阵中不包含"abcb"路径,因为字符串的第一个字符b占据了矩阵中的第一 行第二个格子之后,路径不能再次进入该格子。 """ class Solution: def __init__(self): ...
# Generated by Django 2.0.7 on 2019-01-14 17:23 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('basedata', '0059_auto_20190114_1712'), ] operations = [ migrations.AlterField( model_name='device', name='Inquiry_pr...
# class A(object): # def foo(self, x): # print("executing foo(%s,%s)" % (self, x)) # # @classmethod # def class_foo(cls, x): # print("executing class_foo(%s,%s)" % (cls, x)) # # @staticmethod # def static_foo(x): # print("executing static_foo(%s)" % x) # # # a = A() # a.foo(2...
from math import ceil from function import * from equally_spaced_integration import newton_cotes, A, B, EXACT_VALUE, FIFTEEN_POINTS, FIFTEEN_POINTS_COEF from gauss_integration import composite_gauss, SEVEN_NODES, SEVEN_WEIGHTS COTES_15_P = 16 GAUSS_7_P = 14 def runge_rule_newton_cotes(p, accuracy): N1 = 1 N...
import cv2 import numpy as np import time #Select any model you want to use for inferencing #net = cv2.dnn.readNet('YoloV4-Tiny/yoloV4_best.weights', 'YoloV4-Tiny/y4_tiny_cfg.cfg') #net = cv2.dnn.readNet('YoloV4_Iterations_1000/yolov4-obj_last.weights', 'YoloV4_Iterations_1000/yolov4-obj.cfg') net = cv2.dnn.rea...
#!/usr/bin/env python3 import pyaudio import struct from math import pi, sin import sys SAMPLE_RATE = int(48 * 1000) # hertz WAVE_DURATION = 0.25 # seconds class Tone: """Represents a sine wave for a given frequency. freq - frequency (in hertz) duration - duration of the wave (in seconds) sample_rate - sampling ...
class Solution(object): def swapPairs(self, head): dummy = ListNode(0) dummy.next, ptr = head, dummy while ptr.next and ptr.next.next: tmp = ptr.next.next ptr.next.next = tmp.next tmp.next = ptr.next ptr.next = tmp ptr = ptr.next.ne...
from ._base import IndexStrategy __all__ = ('IndexStrategy',)
import h5py from scipy import sparse import query_chembl hf = h5py.File("data/cdk2.h5", "r") ids = list(hf["chembl_id"].value) # the name of each molecules smiles = query_chembl.get_smiles(ids[:1]) print(smiles)
""" The following are helper functions to handle the volumes of a Notebook. The new API Volume will work with objects of the following format: volume: mount: "mount path" newPvc?: metadata: ... spec: ... existingSource?: nfs?: ... persistentVolumeClaim?: ... ... These functions will parse su...
__version__ = '4.24.10'
import csv import pickle from keras import Sequential from sklearn import metrics import numpy as np from keras.models import Sequential from keras.layers import BatchNormalization from keras.layers import Dropout from keras.layers import Dense, Activation, Flatten from sklearn.model_selection import train_t...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Mar 11 19:20:15 2019 @author: ghosty """ import os from datetime import datetime import pytz import h5py import csv import scipy.signal import numpy as np import matplotlib.pyplot as plt #read filename stamp = '1541962108935000000_167_838.h5' filename ...
import json with open('pref.json') as f: data = json.load(f) streamUrl = data["informations"]["STREAMURL"] streamerName = data["informations"]["STREAMERNAME"]
import os import cv2 import json import argparse import numpy as np from PIL import Image import matplotlib.pyplot as plt def init_coco_dict(): return { 'info': { 'description': 'Kyoto pedestrian dataset', 'url': 'https://www.vision.rwth-aachen.de/page/mots', 'version':...
# Load CSV using Pandas import pandas as pd filename = 'pima-indians-diabetes.data.csv' data = pd.read_csv(filename) skew = data.skew() print(skew)
class BQueue: def __init__(self): self.q = [] self.rear = 0 self.front = 0 def enqueue(self, i): self.q.append(i) self.rear = self.rear + 1 def dequeue(self): if self.rear == self.front: print("Queue is empty") else: self.front = self.front + 1 return self.q[self.front - 1] def printq(self...
#!/usr/bin/env python # -*- coding: utf-8 -*- import os from conans.model import Generator from conans.client.generators import VisualStudioGenerator from xml.dom import minidom from conans.util.files import load class VisualStudioMultiGenerator(Generator): template = """<?xml version="1.0" encoding="utf-8"?> <P...
import cv2 import numpy import sqlite3 import os #Insert hoac Update vao Sqlite def insertOrUpdate(id, name, age, gender): conn = sqlite3.connect('/Users/vubao/OneDrive/Máy tính/SQLiteStudio/Data.db') query = "Select * from people Where ID = "+str(id) cusror = conn.execute(query) is...
import socket from contextlib import closing from http.server import BaseHTTPRequestHandler from urllib import parse import json # Ugggg # For use when a service provider doesn't account for ephemeral port numbers # in redirect uris and so you have to explicitly register uris with ports. _rando_reg_ports = [51283, 5...
# Generated by Django 3.0.2 on 2020-03-13 17:59 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('obsapp', '0008_product_product_date'), ] operations = [ migrations.CreateModel( name='LayoutPrice', fields=[ ...
DEBUG = True TEMPLATE_DEBUG = DEBUG VK_APP_ID = '2427007' VK_APP_KEY = '' VK_APP_SECRET = 'ohRM9foTz8GBZQQ7cFwV' GMAPS_API = 'ABQIAAAA92S7ccOh-SP6wUGsrpdL-BQizReYv0RYXMumyHYbF-1ckP5PhxTKio0m1x22jCulrae0aBIzIDpX3w' PUBLIC_URLS = [ '^admin/', '^callback/', ] ADMINS = ( ('Nergal', 'nergal.dev@gmail.com'), ...
import os import urllib.request VERSIONS = [ '4.2.0', '4.1.2', '4.1.1', '4.1.0', '3.4.9', '3.4.8', '3.4.7', '3.4.6', ] def downlown_opencvjs_file (version, filename): url = "https://docs.opencv.org/%s/opencv.js" % version with urllib.request.urlopen(url) as response, open(filename, 'wb') as out_file: dat...
# ----------------------------------------------------------------------------- # 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 cv2 import base64 img = cv2.imread("D:/21.jpg") retval, buffer = cv2.imencode('.jpg', img) jpg_as_text = base64.b64encode(buffer) print('len before : ',len(jpg_as_text)) print('Original Dimensions : ',img.shape) scale_percent = 40 # percent of original size width = int(img.shape[1] * scale_percent / 100) h...
import numpy as np def newton_step(y, f, fy, fyy, ltol=1e-3): ''' Compute the Newton step for a function fun on the Grassmann manifold `Gr(n,p)`. Parameters ---------- y : (n, p) ndarray Starting point on `Gr(n,p)`. f : double Value of `fun` at `y`. fy : (n, p) ndarray...
#!/usr/bin/env python ''' WxPython App ''' import wx class MenuBar(wx.MenuBar): def __init__(self): menuBar = wx.MenuBar() # Append Menu for File Menu fileMenu = wx.Menu() fileMenu.Append(wx.NewId(), "&Open", "") fileMenu.Append(wx.NewId(), "&Save", "") ...
# 674. Longest Continuous Increasing Subsequence # # Input: [1,3,5,4,7] # Output: 3 # Explanation: The longest continuous increasing subsequence is [1,3,5], its length is 3. # Even though [1,3,5,7] is also an increasing subsequence, # it's not a continuous one where 5 and 7 are separated by 4. # Example 2: # Input: ...
from django.db import models from django.urls import reverse # Create your models here. class Year(models.Model): year_id = models.AutoField(primary_key=True) year = models.IntegerField(unique=True) def __str__(self): return '%s' % self.year class Meta: ordering = ['year'] class Per...
#-- GAUDI jobOptions generated on Fri Jul 17 16:32:45 2015 #-- Contains event types : #-- 11104020 - 116 files - 2010993 events - 432.26 GBytes #-- Extra information about the data processing phases: #-- Processing Pass Step-124834 #-- StepId : 124834 #-- StepName : Reco14a for MC #-- ApplicationName : ...
print(''' OPERADORES DE COMPARACION Devuelve valores booleanos. -Igual que == -Distinto que != -menor que < -menor igual que <= -Mayor que > -Mayor igual que >= -Asignación = Ejemplo: 15 > 3 -> True 5 < 1 -> False 3 == 3 -> True 4 == 2+2 -> True PRESCENDENCIA DE OPERADORES Siempre se va a ejecutar lo operador...
from gym.envs.registration import register register( id="overcookedEnv-v0", entry_point="overcooked.envs:OvercookedEnvironment", )
from django.urls import path from . import views urlpatterns = [ path('movie/<int:movieId>', views.get_movie, name='get_movie'), path('login',views.login, name='login'), path('recommendations',views.recommendations,name='recommendations'), # path('popularity_movies',views.get_popularity_movies,name='po...
# from flask import request # # from usermanager.app import app # from usermanager.dao.user import UserMongoDBDao # from usermanager.mongodb import user_collection # from usermanager.utils.handle_api import handle_response # # # META_SUCCESS = {'status': 200, 'msg': '成功!'} # META_ERROR = {'status': 404, 'msg': '失败!该用户不...
import random def deal(deck): card = random.choice(deck) deck.remove(card) return card def playBlackjack(): players = [AI('Stardust'), Manual('Manual')] deck_count = 1 scores = [0 for _ in players] deck = ['A','K','Q','J',10,9,8,7,6,5,4,3,2] * 4 * deck_count faceUp = deal(deck) dealt = [faceUp] for id, pl...
#标注训练集的anchor """ 在训练集中,将每个anchor作为一个训练样本,为了训练目标检测模型,需要为每个anchor标注两类标签: 1.anchor所含目标的类别,简称类别 2.真实边界框ground truth相对anchor的偏移量,偏移量offset, 在目标检测时, 1.首先生成多个anchor, 2.然后为每个anchor预测类别以及偏移量, 3.接着根据预测的偏移量调整anchor位置从而得到预测边界框, 4.最终筛选需要输出的预测边界框 在目标检测的训练集中,每个图像已经标注了真实边界框ground truth的位置以及所含目标的类别; 在生成anchor之后,主要依据与anchor相似的真实边界框gr...
import tensorflow as tf from ._tf_oplib import _op_lib from kungfu.python import current_rank class Queue: def __init__(self, src, dst, id): self._src = int(src) self._dst = int(dst) self._id = int(id) def get(self, dtype, shape): return _op_lib.kungfu_queue_get( ...
import math import pytest import ipywidgets from pandas_visual_analysis import DataSource from pandas_visual_analysis.utils.config import Config from pandas_visual_analysis.widgets import BrushSummaryWidget from tests import sample_dataframes @pytest.fixture(scope="module") def small_df(): return sample_datafra...
#nonlocal x = 6#global def f(): x = 5#nonlocal = not global and local def g(): nonlocal x x = 8 g() print('x = ', x) # x = 8 #local f()