text stringlengths 38 1.54M |
|---|
import numpy as np
import sys
import cv2
def func3():
img1 = cv2.imread('7.17/cat.jpg', -1)
if img1 is None:
print('Image load failed!')
return
img2 = img1
img3 = img2.copy()
img1[:, :] = (0, 255, 255) # Yellow
cv2.imshow('img1', img1)
cv2.imshow('img2', img2)
cv2.im... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
from urllib2 import Request, urlopen, URLError, HTTPError
def Space(j):
i = 0
while i<=j:
print " ",
i+=1
def CnsAdmin():
f = open("link.txt","r");
link = raw_input("😈 Web 😈 \n(Domain : example.com Yada www.example.com ): ")
print "\n\Mevcut Ex... |
import math
# import timeit
# timeit.repeat("f1(x)", "from __main__ import f1", repeat=3, number=100)
# Digits Greatest
# 1 9 * 1 = 9
# 2 99 * 91 = 9009
# 3 993 * 913 = 906609
# 4 9999 * 9901 = 99000099
# 5 99989 * 99681 = 9966006699
# 6 999999 * 999001 = ... |
import unittest
import mop
from . import InMemoryDatabase
class DatabaseTest(unittest.TestCase):
def test_database(self):
db = InMemoryDatabase()
db.insert("foo", {"a": 1, "b": 2})
assert db.lookup("foo") == {"a": 1, "b": 2}
assert db.store == {"foo": '{"data":{"a":1,"b":2},"type... |
import pygame
from maze import Maze
import game_functions as gf
from pm import PM
from ghosts import Red, Blue, Pink, Orange, Cherry
from stats import Stats
from display import Display
def run_game():
# Initialize pygame, settings, and screen object.
pygame.init()
screen = pygame.display.set_mode((630, 80... |
# encoding=utf-8
import urllib
import json
import io
from BeautifulSoup import BeautifulSoup
URL = 'https://www.kinopoisk.ru/film/435/'
def parse_url(url):
data = urllib.urlopen(url)
data = data.read().decode("windows-1251").encode("utf-8")
soup = BeautifulSoup(''.join(data))
parsed_data = dict({'... |
#! /usr/bin/env python3
import sys
import subprocess
KERNEL_OFFSET = 1024 * 512
def _concat(a, b):
while (True):
buf = b.read(4*1024)
if (len(buf) == 0):
break
a.write(buf)
def main():
if len(sys.argv) != 4:
return -1
bootloader = sys.argv[1]
kernel = sys... |
import numpy as np
import mediapipe as mp
import cv2
mp_drawing = mp.solutions.drawing_utils
mp_hands = mp.solutions.hands
# Function takes in the all the coordinates for all the points, selects the relevants tracking point
# and OUTPUTS the average of all the markers in the xy plane (get centre of hand)
def get_par... |
import pygal
import csv
import operator
from matplotlib import pyplot as plt
from datetime import datetime
import os, re
#from clases.productos import Producto
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "subastas.settings")
import django
django.setup()
from django.db import models
from ah.mod... |
import socket
import threading
def send_message(udp):
addr = input("enter destination ip:")
port = int(input("enter destination port:"))
while True:
message = input("enter message to send:")
udp.sendto(message.encode(), (addr, port))
def recv_message(udp):
while True:
recv_da... |
from similarity import *
# WEIGHT_TFIDF = 0.25
# WEIGHT_PRICE = 0.25
# WEIGHT_ORDERING = 0.25
# WEIGHT_CUISINE = 0.25
def calc_r2u(user, restaurant, tfidf, weight):
tfidf *= weight["tfidf"]
price_sim = calc_price_sim(user['price'], restaurant['price']) * weight["price"]
ordering_sim = calc_ordering_sim(u... |
#!/usr/bin/env python
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... |
from django.contrib import admin
from .models import Employee,EmployeeEducationDetail,EmployeeWorkDetail
admin.site.register(Employee)
admin.site.register(EmployeeEducationDetail)
admin.site.register(EmployeeWorkDetail)
# Register your models here.
|
bike={"yamaha","apache","fz"}
#loop through the list
for x in bike:
print(x)
#yamaha
#apache
#fz
|
from django.db import models
from django.core.validators import RegexValidator
class Customers(models.Model):
TC = models.CharField(max_length=11, validators=[
RegexValidator(regex=r'^[1-9]{1}[0-9]{9}[02468]{1}$', message='Invalid TC', code='nomatch')],
null=False, unique=True)
... |
from distutils.command.bdist import bdist
import sys
if 'egg' not in bdist.format_commands:
try:
bdist.format_commands['egg'] = ('bdist_egg', "Python .egg file")
except TypeError:
# For backward compatibility with older distutils (stdlib)
bdist.format_command['egg'] = ('bdist_egg', "Pyt... |
#!/usr/bin/env python3
from aws_cdk import core
from aws_lambda.aws_lambda_stack import AwsLambdaStack
app = core.App()
AwsLambdaStack(app, "aws-lambda", env=core.Environment(region="eu-central-1"))
app.synth()
|
from pwn import *
byte_table=[0x0BB,0x2,0x9B,0x3,0x0C4,0x4,0x6C,0x5,0x4A,0x6,0x2E,0x7,0x22,
0x8,0x45,0x9,0x33,0x0A,0x0B8,0x0B,0x0D5,0x0C,0x6,0x0D,0x0A,
0x0E,0x0BC,0x0F,0x0FA,0x10,0x79,0x11,0x24,0x12,0x0E1,
0x13,0x0B2,0x14,0x0BF,0x15,0x2C,0x16,0x0AD,0x17,0x86,
0x18,0x60,0x19,0x0A4,0x1A,0x0B6,0x1B,0x0D8,0x1C,0x59,
0x1D,... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import unittest
import yaml
import indexer
import searcher
import api
import frontend
from indexer import stripTag
from searcher import binaryIndexSearch
class TestUM(unittest.TestCase):
config = {'PATH_WIKI_XML': 'testdata', 'PATH_INDEX_FILES': 'testdata/index', 'FIL... |
from django.shortcuts import render, redirect
from repository import models
from backend.auth import auth
@auth.check_login
def manage_index(request):
"""
管理界面首页
:param request:
:return:
"""
context = {
'user_info': request.session.get('user_info'),
}
print(request.session.get(... |
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from sklearn import svm, metrics
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
from sklearn.pipeline import Pipeline
from skimage import io
from skimage.tr... |
#!/users/jgrey/anaconda/bin/python
import sys
import time
import math
import cairo
import draw_routines
import logging
#constants
N = 12
X = pow(2,N)
Y = pow(2,N)
imgPath = "./imgs/"
imgName = "initialTest"
currentTime = time.gmtime()
FONT_SIZE = 0.03
#format the name of the image to be saved thusly:
saveString = "{}{... |
from numpy import mean
from numpy import std
from sklearn.datasets import make_regression
from sklearn.model_selection import cross_val_score
from sklearn.model_selection import RepeatedKFold
from sklearn.linear_model import LinearRegression
from sklearn.neighbors import KNeighborsRegressor
from sklearn.tree imp... |
from datasetLoaders.DatasetInterface import DatasetInterface
import os
import random
import re
from typing import List, Tuple, Type
import numpy as np
import pandas as pd
import torch
from torch import Tensor, cuda
from pandas import DataFrame
# from cn.protect import Protect
# from cn.protect.privacy import KAnonymit... |
import numpy as np
import torch
import torch.nn as nn
from torch.autograd import Variable
import torch.optim as optim
import PIL
from PIL import Image
import matplotlib.pyplot as plt
import torchvision.transforms as transforms
import torchvision.models as models
######### images
imsize = 200 # desired size of the... |
#This script tests the merra_dap module in WxMP
#Written by Christopher Phillips
#Import required modules
from wxmp import merra_dap as wm
import matplotlib.pyplot as pp
from datetime import datetime as dt
#Create test dates
start_date = dt.strptime("20160618", "%Y%m%d")
end_date = dt.strptime("20160621", "%Y%m%d")
... |
from banking import *
def pay_annual_interest(accounts):
for acc in accounts:
if isinstance(acc, Profitable):
amt = acc.interest(1)
acc.deposit(amt)
jack = CurrentAccount()
jack.deposit(15000)
jill = SavingsAccount()
jill.deposit(10000)
try:
payment = float(input('Amount to pay: '))
if payment >... |
# -*- coding: utf-8 -*-
"""
Messaging module
"""
if deployment_settings.has_module("msg"):
# =============================================================================
# Tasks to be callable async
# =============================================================================
def process_outbo... |
from selenium import webdriver
import math
def calc(x):
return str(math.log(abs(12*math.sin(int(x)))))
browser = webdriver.Chrome()
link = "http://suninjuly.github.io/get_attribute.html"
browser.get(link)
x_element = browser.find_element_by_id("treasure")
x = x_element.get_attribute("valuex")
y = calc(x)
input = ... |
# coding=utf-8
from captcha.fields import CaptchaField
from django import forms
from django.contrib.auth.models import User
from registration.forms import RegistrationForm
from models import Object, Observation, ImagingDevice, FITSFile
class UploadFileForm(forms.Form):
""" This form represents a basic request fr... |
from django.shortcuts import render,get_object_or_404,redirect
from .models import Blog
from django.utils import timezone
from .forms import BlogForm
from django.core.paginator import Paginator
# Create your views here.
def home(request):
blogs=Blog.objects.all()
search = request.GET.get('search')
if search... |
"""Test cases for the module that uses a cookbook programming style"""
# TODO: Add correct import statements
# TODO: Add test cases to adequately cover the program
# TODO: Run test coverage monitoring and reporting with pytest-cov
def test_read_file_populates_data_0():
"""Checks that reading the file populates g... |
#!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'getTotalX' function below.
#
# The function is expected to return an INTEGER.
# The function accepts following parameters:
# 1. INTEGER_ARRAY a
# 2. INTEGER_ARRAY b
#
def getTotalX(a, b):
temp = 0
contador = 1
... |
from django.db import models
# Create your models here.
class pfc(models.Model):
Year_to_be_forward = models.IntegerField(default=2017)
# For_the_year = models.IntegerField()
|
import argparse
args = argparse.ArgumentParser(description='MolGAN model for molecular.')
args.add_argument('--device', default=1)
args.add_argument("--mode", default="train", help='mode for model, default is true')
args.add_argument('--learning_rate', default=1e-3, help='learning rate')
args.add_argument('--batch_dim... |
from django.test import TestCase
import models as md
# class ApiViewTest(TestCase):
# def test_validate_user(self):
# response = self.
|
import socket
import unittest2 as unittest
from celery.task.builtins import PingTask
from celery.utils import gen_unique_id
from celery.worker import control
from celery.worker.revoke import revoked
from celery.registry import tasks
hostname = socket.gethostname()
class TestControlPanel(unittest.TestCase):
def ... |
import json
import re
class Matrix:
def __init__(self):
self.matrix = []
self.input_list = []
def rows(self):
return len(self.matrix)
def colums(self):
if self.row() == 0:
return 0
return len(self.matrix[0])
# ------------------- rea... |
import numpy as np
import matplotlib.pyplot as plt
Nt = 100
T = 30
t = np.linspace(0,T,Nt+1)
dt = t[1]-t[0]
R_list = np.zeros(Nt+1)
t_2 = np.linspace(0,T,T+1)
BP_data = [2,3,5,10,20,30,40,50,80,100,200,300,400,500,600,700,800,900,800,700,600,500,400,300,200,100,80,50,40,30,20]
for i in range(Nt):
t_ = 0.2*t[i+1]-... |
#!/usr/bin/env python3
import os
def nuke():
choice = input("do you really wish to nuke this file? (y/n) ")
if choice == 'y':
os.system('zip complex_sav.zip complex')
os.system('rm -rf complex')
os.system('unzip complex.zip')
os.system('zip -r complex.zip complex')
pri... |
import setuptools
with open("README.md", "r") as filep:
long_description = filep.read()
setuptools.setup(
name='Recombination_analysis',
version='0.1.4',
description='Analyze recombination events using kmers',
url='https://github.com/zhuweix/recombination_analysis',
author='Zhuwei Xu',
au... |
"""
*******
Errors
*******
Custom exceptions for ingest
"""
class InvalidIngestStageParameters(Exception):
"""
Exception raised if parameters passed to IngestStage.run fail validation
"""
# TODO
# Pretty stack straces using Pythons traceback module
pass
|
import re
def myAtoi(str):
raw_strig = str
new_string = re.sub("^\s*", "", raw_strig)
if not len(new_string):
return 0
elif new_string[0] == "-":
if len(new_string) == 1:
return 0
multiplier = -1
new_string = new_string[1:]
elif new_string[0] == "+":
if len(new_string) == 1:
return 0
multipli... |
import json
import cv2
import numpy as np
from os.path import join as pjoin
import os
import time
import shutil
from detect_merge.Element import Element
def show_elements(org_img, eles, show=False, win_name='element', wait_key=0, shown_resize=None, line=2):
color_map = {'Text':(0, 0, 255), 'Compo':(0, 255, 0), '... |
from selenium import webdriver
import time
## Author = [Przemysław Szmaj]
## GitHub = https://github.com/PSZMAJ
## YouTube = https://www.youtube.com/channel/UCewT7Lr5f6LWvqSPXm0JKRw
login = input('Please eneter login: ')
browser = webdriver.Firefox()
browser.get('https://www.facebook.com/login.php')
class Att... |
def is_perfect_square(n):
x = n // 2
y = set([x])
while x * x != n:
x = (x + (n // x)) // 2
if x in y: return false
y.add(x)
return True
print(is_perfect_square(8))
print(is_perfect_square(9))
print(is_perfect_square(100))
|
# -*- coding: utf-8 -*-
import logging
from .mysql import MySQLSingle, MySQLFoxHA, MySQLFoxHAAWS
from .mysql import MySQLSingleGCP, MySQLFoxHAGCP
from physical.models import Instance
from base import InstanceDeploy
LOG = logging.getLogger(__name__)
class MySQLPerconaSingle(MySQLSingle):
@property
def drive... |
import mysql.connector
mydb = mysql.connector.connect(host="localhost",user="root",passwd="krishnatej",database="sample1")
mycursor = mydb.cursor()
mycursor.execute("select * from s1")
for i in mycursor:
print(i) |
import sys
import pandas as pds
import numpy as np
if len(sys.argv) < 3:
print("Usage check_predict csv_file_name predict_field_name")
sys.exit()
filename = sys.argv[1]
predict = sys.argv[2]
print("Checking " + predict + " in " + filename)
dataf = pds.read_csv(filename,
sep=',',
... |
# coding: utf-8
from datetime import timedelta
from rest_framework.views import APIView
from rest_framework import generics
from rest_framework.response import Response
from rest_framework import exceptions
from rest_framework.authentication import TokenAuthentication
from rest_framework.permissions import IsAuthentic... |
import requests
import os
from tqdm import tqdm
import sys
def get_json(url):
"""
Gets a json response from the given url.
:param url: URL.
:return: the received Json data.
"""
resp = requests.get(url=url)
return resp.json()
def get_file(url, output_file, show_progress_bar=True):
""... |
"""
The Python standard library's 'calendar' module allows you to
render a calendar to your terminal.
https://docs.python.org/3.6/library/calendar.html
Write a program that accepts user input of the form
`14_cal.py month [year]`
and does the following:
- If the user doesn't specify any input, your program should
... |
import os
def visit_directory(path, file_name):
dirs = os.listdir(path)
for dir in dirs:
sub_path = os.path.join(path, dir)
if dir == file_name and os.path.isfile(sub_path):
os.remove(sub_path)
return True
elif os.path.isdir(sub_path):
visit_director... |
import numpy as np
import pickle
import matplotlib.pyplot as plt
class RaceTrack:
def __init__(self, course):
self.v_max = 5
self._load_course(course)
self.reset()
def _load_course(self, course):
# flip course upside down so 0,0 is botton left
self.course = ... |
import shelve
email_db = shelve.open('../Scripts/emails')
arr =['gstaines1@usnews.com', 'Gustave']
print(email_db['Gustave'],arr[0]) |
#created and edited by Samuel Phillips
#imports for data, classes and more
import pandas as pd
import numpy as np
from sklearn.datasets import load_iris
from sklearn import tree, metrics
from sklearn.model_selection import train_test_split
from matplotlib import pyplot as plt
from sklearn.neighbors import KNe... |
'''
use xmltodict library to export json file from xml file
'''
import io, xmltodict, json
infile = io.open("books.xml", 'r')
outfile = io.open("books.json", 'wb')
o = xmltodict.parse( infile.read() )
json.dump( o , outfile, indent=2) |
%cd /content/keras-YOLOv3-model-set
import os
import glob
CLASS_NAMES = [ "cat", "dog" ]
# TAGET_FOLDER_NAME = "labels"
TAGET_FOLDER_NAME = "dogs_cats_yolo_labeled"
label_file_names = []
for file_name in glob.glob(TAGET_FOLDER_NAME+'/*.xml'):
label_file_names.append(file_name)
print(len(label_file_names))
print... |
from . import __version__
from .defs import (
ENV_LOG_FILE,
ENV_LOG_LEVEL,
ENV_WASM_INTERPRETER,
LESS_THAN_OCAML_MAX_INT,
KERNEL_IMPLEMENTATION_NAME,
KERNEL_NAME,
)
from ipykernel.kernelbase import Kernel # type: ignore
import os
import logging
import pexpect # type: ignore
from .wasm_replwrap... |
#!/usr/bin/python
# Given two numbers x and y, return the sum of x and y.
# number, number --> number
# Example:
# add(1,2) = 3
# add(0,2) = 2
def add(x, y):
return x + y
# Given two numbers x and y, return the product of x and y.
# number, number --> number
# Example:
# multiply(1,2) = 2
# multiply(4,2) = 8
# ... |
import logging
import pytest
from ocs_ci.ocs import constants
from ocs_ci.framework.testlib import (
skipif_ocs_version,
ManageTest,
tier1,
skipif_ocp_version,
kms_config_required,
skipif_managed_service,
skipif_disconnected_cluster,
skipif_proxy_cluster,
config,
)
from ocs_ci.ocs.r... |
import unittest
from conans.test.utils.tools import TestClient, TestBufferConanOutput
import os
import zipfile
from conans.test.utils.test_files import temp_folder
from conans.util.files import load, save_files, save
from conans.client.remote_registry import RemoteRegistry, Remote
from mock import patch
from conans.cl... |
'''
print below pattern
3 * 1 = 3
3 * 2 = 6
3 * 3 = 9
3 * 4 = 12
3 * 5 = 15
3 * 6 = 18
3 * 7 = 21
3 * 8 = 24
3 * 9 = 27
3 * 10 = 30
'''
def print_pattern_14(n):
for i in range(1, 11):
pattern = str(n) + " * " + str(i) + " = " + str(n * i)
print(pattern)
print_pattern_14(3) |
import os
from pyutil.program.jsonconf import parse
conf = parse(os.path.normpath(os.path.join(os.path.dirname(__file__), '../config/deploy.json')))
|
import pandas as pd
from sklearn.model_selection import cross_val_score
from sklearn.model_selection import KFold
from sklearn.linear_model import LinearRegression
from sklearn.linear_model import Ridge
from sklearn.linear_model import Lasso
from sklearn.linear_model import ElasticNet
import matplotlib.pyplot ... |
# Ques-4 Write a Python program to sort a list of dictionaries using Lambda.
l = [{'make': 'Nokia', 'model': 216, 'color': 'Black'}, {'make': 'Mi Max', 'model': 2,'color': 'Gold'}, {'make': 'Samsung', 'model': 7, 'color': 'Blue'}]
sort_l = sorted(l, key = lambda x: x['model'])
print(sort_l)
|
import mlflow
def logModel(model):
mlflow.pyfunc.log_model(artifact_path="model",python_model=model)
# mlflow.pyfunc.save_model(
# path=model_path,
# python_model=model,
# code_path=['multi_model.py'],
# conda_env={
# 'channels': ['defaults', 'conda-forge'],
# ... |
import argparse
import os
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.optim as optim
import torch.utils.data
import torch.nn.functional as F
import time
import numpy as np
import pdb
import cv2
# import imageio
import utils.logger as logger
import models.anynet
parser = argparse.Argument... |
# -*- test-case-name: twisted.internet.test.test_sigchld -*-
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
This module is used to integrate child process termination into a
reactor event loop. This is a challenging feature to provide because
most platforms indicate process termina... |
first_name = "Eric"
question = ", would you like to learn some Python today?"
print(first_name.upper() +question)
my_14 = 14
print("Мое л число " + str(my_14)) #str - приводит число к строковому виду, сначала пишется str(), а в скобках указывается переменная
#списки
#Называть списки во множественном числе cycleS
#имя ... |
"""
General class for a recurrent language model
"""
__docformat__ = 'restructedtext en'
__authors__ = ("Alessandro Sordoni, Iulian Vlad Serban")
__contact__ = "Alessandro Sordoni <sordonia@iro.umontreal>"
import theano
import theano.tensor as T
import numpy as np
import cPickle
import logging
import operator
logger ... |
from .log import set_verbosity # , set_repeat
from .opt import nn_opt
TOL = 1e-12
def set_tolerance(tol):
global TOL
TOL = tol
|
import os
import sys
class output(object):
"""
ANSI console colored output:
* error (red)
* warning (yellow)
* debug (green)
Set environment variable `COLOR_OUTPUT_VERBOSE' to enable debug
"""
RED = 1
GREEN = 2
YELLOW = 3
ERROR = 4
DEBUG = 5
... |
import pytest
from pyspark.sql import Row
from splink import Splink
def test_nulls(spark):
settings = {
"link_type": "dedupe_only",
"proportion_of_matches": 0.1,
"comparison_columns": [
{
"col_name": "fname",
"m_probabilities": [0.4, 0.6],
... |
#!/usr/bin/env python3
__author__ = 'Wei Mu'
class Solution:
def romanToInt(self, s):
"""
:type s: str
:rtype: int
"""
ans = 0
value = dict()
value['I'] = 1
value['V'] = 5
value['X'] = 10
value['L'] = 50
value['C'] = ... |
from selenium import webdriver
import autogmailpy
import uuid
__author__ = 'Jorge'
driver = webdriver.Firefox()
glogin = autogmailpy.GmailLogin(driver)
glogin.visit_login()
inbox = glogin.fill_in_email().click_next_button().fill_in_password().click_signin_button()
body = '{0}'.format(uuid.uuid4())
inbox.click_compose... |
list = []#设一个空列表放所有信息
name_list = []#设一个空列表放所有输入过的信息
count = 0#输入的次数
while True:
if count == 3:#如果输入次数等于三次
break#则跳出循环
dict = {}#设一个空的字典
name = input("请输入名字:")
age = int(input("请输入年龄:"))
sex = input("请输入性别:")
qq = int(input("请输入QQ号:"))
weight = float(input("请输入体重:"))
#给字典赋值
if name not in name_list:#如果输入的名字不... |
from scheme.interpolation import Interpolator as BaseInterpolator
from scheme.util import recursive_merge
base_interpolator = BaseInterpolator()
class Interpolator(dict):
"""A parameter interpolator."""
def clone(self):
return Interpolator(self)
def evaluate(self, subject):
return base_i... |
from eval import *
#import eval
import unittest
deploy_path = "models/deploy.prototxt"
weight_caffemodel_path = "models/weight.caffemodel"
labels_csv = "models/labels.csv"
import json
import os
if __name__ == '__main__':
configs = {
"app": "cardapp",
"use_device": "GPU",
"batch_size":1,
... |
class Solution(object):
def canPlaceFlower(self, flowerbed, n):
"""
:type flowerbed: List[int]
:type n: int
:rtype: bool
"""
for i,c in enumerate(flowerbed):
if (not c and (i==0 or not flowerbed[i-1])) and (i==len(flowerbed)-1 or not flowerbed[i+1]):
... |
import cv2
img = cv2.imread("jogador.jpg")
(canalAzul, canalVerde, canalVermelho) = cv2.split(img)
print(cv2.split(img))
cv2.imshow("Vermelho", canalVermelho)
cv2.imshow("Verde", canalVerde)
cv2.imshow("Azul", canalAzul)
|
import matplotlib.pyplot as plt # pyplot contains a number of functions that help generate chars and plots.
input_values = [1, 2, 3, 4, 5]
squares = [1, 4, 9, 16, 25] # list to pass it tot he plot ft
plt.style.use('seaborn')
fig, ax = plt.subplots()
ax.plot(input_values, squares, linewidth=3) # make the line thicke... |
def stringDisplay():
while True:
s = yield
print(s*3)
c = stringDisplay()
next(c)
c.send('Hi!!')
def nameFeeder():
while True:
fname = yield
print('First Name:', fname)
lname = yield
print('Last Name:', lname)
n = nameFeeder()
next(n)
n.send... |
# lista = ["p", "y", "t", "h", "o", "n"]
#
# for item in lista:
# print (item)
#
# for i in range(5):
# print(i)
import numpy as np
m=[[5,4,7],[0,3,4],[0,0,6]]
a=np.array([[5,4,7],[0,3,4],[0,0,6]])
# print (a)
for item in a:
print (item)
for item in m:
print (item)
|
import numpy as np
x = np.array([[1], [2], [3]])
y = np.array([4, 5, 6])
# 对 y 广播 x
b = np.broadcast(x,y)
# 它拥有 iterator 属性,基于自身组件的迭代器元组
print ('对 y 广播 x:)'
r,c = b.iters
print (r.next(), c.next())
print (r.next(), c.next())
print ('\n' )
# shape 属性返回广播对象的形状
print ('广播对象的形状:')
print (b.shape)
print... |
#!/usr/bin/env python3
# read abelectronics ADC Pi board inputs
# uses quick2wire from http://quick2wire.com/ github: https://github.com/quick2wire/quick2wire-python-api
# Requries Python 3
# GPIO API depends on Quick2Wire GPIO Admin. To install Quick2Wire GPIO Admin, follow instructions at http://github.com/quick... |
# БСБО-05-19 Савранский С.
inp = []
while i := input('Line >> '):
inp.append(i)
print(*(f'Line {inp.index(line) + 1}: {line.lstrip()[2:]}\n' for line in inp if '#' in line))
|
from Hearthstone import *
def test_hearthstone():
g = load('replays/2015-01-21-09-14-36.hsrep', save_replay=False)
assert g.effect_pool == []
assert g.minion_counter == 1009
assert g.turn == 9
assert g.aux_vals == deque()
assert g.action_queue == deque()
assert g.minion_pool.keys() == [1000... |
import doctest
import os
import manuel.codeblock
import manuel.doctest
import manuel.testing
from . import testcode
from . import unicode_output
def get_doctest_suite(docnames):
"""Return the doctest suite for specified docnames."""
docnames = [
os.path.join(
os.getcwd(),
do... |
def may_be_password(number):
number = str(number)
return len(str(number)) == 6 and \
any((a == b for a, b in zip(number, number[1:]))) and \
all((a <= b for a, b in zip(number, number[1:])))
if __name__ == '__main__':
input_range = (138241, 674034)
print(sum((may_be_password(num... |
# Listnode.next: always check null
## digit is %
## carry is /
## binary question: "2" divide. mid is 0. mid right is 0 1. so size is still 2. avoid
## while loop完如果要用没有loop也能用的variable,需要保持var跳出while和没进loop的状态一样
## int(x) str(x)
isupper(), islower(), lower(), upper()
a = dict()
a.get(1) -> None a[1] -> KeyError... |
from .models import Backup, Host
from rest_framework import viewsets
from .serializers import BackupSerializer, HostSerializer
class BackupViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows users to be viewed or edited.
"""
queryset = Backup.objects.all().order_by('-id')
serializer_class... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from account.models import User
class AccountUserAdmin(UserAdmin):
list_display = ('username', 'email', 'first_name', 'last_name', 'is_staff',
'api_... |
from django.shortcuts import render, get_object_or_404
from .models import Blog
def all_blogs(request):
blogs = Blog.objects.all()
return render(request, 'blogs/blogs.html', {'blogs': blogs})
def details(request, blog_id):
detail_blog = get_object_or_404(Blog, pk=blog_id)
return render(request, 'blo... |
from flask import Response, make_response
from flask import render_template, flash, redirect, url_for, request, jsonify, session, g, abort
from app import app, db, lm
from flask_security import auth_token_required
from flask_security import Security, UserMixin, RoleMixin
from flask.ext.login import login_user, logout_u... |
"""Homework 7 tabs_to_commas for CSE-41273"""
# Yukie McCarter
import csv
import sys
OUTPUT_FILE = "_commas.csv"
def tab_to_comma(in_file, out_file):
with open(in_file) as inputFile:
with open(out_file, 'w') as outputFile:
reader = csv.DictReader(inputFile, delimiter='\t')
writer... |
# Solution of;
# Project Euler Problem 384: Rudin-Shapiro sequence
# https://projecteuler.net/problem=384
#
# Define the sequence a(n) as the number of adjacent pairs of ones in the
# binary expansion of n (possibly overlapping). E. g. : a(5) = a(1012) = 0,
# a(6) = a(1102) = 1, a(7) = a(1112) = 2Define the sequence... |
from random import randint
def sorteio(valor):
aleatorio = randint(1,100)
palpite = 1
while valor != aleatorio:
if valor > aleatorio:
print("Informe um valor menor!")
elif valor < aleatorio:
print("Informe um valor maior!")
palpite += 1
valor = int(i... |
'''
Uses data from Belfast-Harbour.co.uk/tide-tables to
print the tides that are greater than 3.5 meters
'''
import urllib
import re
url = 'https://www.belfast-harbour.co.uk/tide-tables/'
regexDepth = '<span class="depth">(.+?)</span>' #An array of whatever is between the two span tags
patternDepth = re.compile(... |
import json
import os.path
from collections import Mapping
from pathlib import Path
from typing import List
class RepositoryMap(Mapping):
"""Represents a JSON view of a git repository file structure.
>>> repo_map = RepositoryMap('repo')
>>> repo_map.add_path('path/to/file.txt')
>>> repo_map.add_path(... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.