text stringlengths 38 1.54M |
|---|
# pip install beautifulsoup4 selenium lxml
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdri... |
from django import forms
from django.utils.translation import ugettext_lazy as _
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, Submit, Row, Column
from apps.classes.models import YogaClass
from tempus_dominus.widgets import DatePicker, TimePicker, DateTimePicker
from datetime impor... |
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 5 16:50:03 2019
@author: ZHOUFENG
"""
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 21 19:26:40 2019
@author: ZHOUFENG
"""
import os
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
import tensorflow as tf
#动态分配显存
config = tf.ConfigProto()
config.gpu_options.allow_growth = Tr... |
from unittest import TestCase
from cell import Cell
from row import Row
class TestRow(TestCase):
def setUp(self):
self.row = Row(0, [2, 0, 4, 3, 5, 0, 6, 9, 8])
def test_sum(self):
self.assertLessEqual(self.row.sum(), 45)
def test_add_type_error(self):
self.assertRaises(TypeErro... |
import subprocess
def test_equality():
completed = subprocess.run(["bin/canidae", "test/logic/equality.can"], text=True, capture_output=True)
assert completed.returncode == 0
lines = completed.stdout.split("\n")
assert len(lines) == 29
assert lines[0] == "false"
assert lines[1] == "true"
a... |
import numpy as np
import cv2
img = cv2.imread("chess.png")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 固定阈值
ret, th = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)
print(ret)
# cv2.imwrite("../doc/threshold_fix.png", th)
# 自适应阈值
th = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
... |
import tkinter as tk
from tkinter import *
from tkinter import messagebox
background_colour = '#707371'
button_color = '#18c9c1'
root = tk.Tk()
root.geometry("250x400+300+300")
root.title("Calculator")
root.resizable(0, 0) # Allows resizing of widget when run
root.configure()
data = StringVar()
val =... |
from mysql.connector import MySQLConnection
import settings
db = MySQLConnection(
user=settings.DB_USER,
password=settings.DB_PASSWORD,
database=settings.DB_NAME,
host=settings.DB_HOST,
port=settings.DB_PORT,
charset=settings.DB_CHARSET,
collation=settings.DB_COLLATION,
)
_managers = []
... |
import numpy as np
from astropy.io import fits
import matplotlib.pyplot as plt
from photutils import CircularAperture
from photutils import CircularAnnulus
from photutils import aperture_photometry
from colossus.cosmology import cosmology
from functools import partial
from scipy.optimize import curve_fit
import glob
im... |
import RPi.GPIO as GPIO
class Button:
def __init__(self, pin, cmd, noop):
self.pin = pin
self.cmd = cmd
self.noop = noop
self.state = False
def setup(self):
GPIO.setup(self.pin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
def get_command(self):
input_state = GPIO.in... |
# -*- coding:utf-8 -*-
"""
@Time: 2019/09/27 10:51
@Author: Shanshan Wang
@Version: Python 3.7
@Function:
"""
import numpy as np
import torch
import random
from torch.autograd import Variable
a=[[1,2,3],[4,5,6],[7,8,9]]
a=[torch.Tensor(row) for row in a]
print('a:',a)
a=[row.data.numpy() for row in a]
... |
# needs for implementing tests
import unittest
# needs for webdriver
from selenium import webdriver
# needs for typing in input
from selenium.webdriver.common.keys import Keys
# class that has used the unittest and declares it as TestCase
class PythonOrgSearch(unittest.TestCase):
# always run first
def setUp(... |
nombres = ["juan", "alejandro", "maria"]
print(type(nombres), type(nombres[0]))
print(nombres[0])
apellidos = ("diaz", "daza", "medina")
print(type(apellidos), type(apellidos[0]))
print(apellidos[0])
nombres[1] = "mario"
apellidos = (apellidos[0], apellidos[1], "salgado")
nombres.append("jose")
print(nombres)
print... |
from funcs import markov_chain
from random import random
from time import time
cdf = None
def get_symbol(table):
rnd = random()
for key in table:
if rnd < table[key]:
return key
def round_table(table, generated):
if not generated:
return table
else:
... |
from gtts import gTTS
from playsound import playsound
import datetime
import webbrowser
import wikipedia
import json, codecs, apiai
import speech_recognition as sr
def speak(mytext):
myobj = gTTS(text=mytext, lang='hi', slow=False)
myobj.save("groot.mp3")
playsound("groot.mp3")
def wishMe():
hour = in... |
# coding=utf-8
import numpy as np
import matplotlib.pyplot as mp
from mpl_toolkits.mplot3d import axes3d
n=500
x=np.random.normal(0,1,n)
y=np.random.normal(0,1,n)
z=np.random.normal(0,1,n)
mp.figure('3D Scatter')
ax3d = mp.gca(projection='3d')
ax3d.set_xlabel('x',fontsize=14)
ax3d.set_ylabel('y',fontsize=14)
ax3d.se... |
from __future__ import annotations
from collections import defaultdict
from datetime import date, datetime, timedelta, timezone
from typing import Dict, List
import pytest
from barkylib import bootstrap
from barkylib.domain import commands
from barkylib.services import handlers, unit_of_work
from barkylib.adapters impo... |
import random as r
import pygame as pg
import collections
from pygame_ops import pygame_fix
from rich.console import Console
from recursive_backtracker import draw_points
c = Console()
def available_vertices(width, game_display, multiplier):
return_vertices = set()
edges = {}
for i in range(0, width * 2... |
# Generated by Django 3.1.5 on 2021-05-29 01:09
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('auth', '0012_alter_user_first_name_max_length'),
]
operations = [
migrations.CreateMode... |
n = 10 # 12
def solution(n):
answer=''
while True:
if n%3 == 0 :
answer ='4'+answer
n=n//3 -1
elif n%3 == 1:
answer = '1' +answer
n=n//3
else :
answer = '2' +answer
n=n//3
if n == 0 : break
return answer
... |
import os
import numpy as np
import pandas as pd
import tensorflow as tf
import spacy
import matplotlib.pyplot as plt
EN = spacy.load('en_core_web_sm')
from sklearn.preprocessing import MultiLabelBinarizer
import fasttext
data = pd.read_csv('Preprocessed_data.csv')
# Make a dict having tag frequencies
data.tags = dat... |
# Untitled - By: Javier - Mon Jul 27 2020
import sensor, image, time, utime
from pyb import LED
sensor.reset()
sensor.set_pixformat(sensor.GRAYSCALE) # or GRAYSCALE...
sensor.set_framesize(sensor.VGA) # or QQVGA...
sensor.set_windowing((640, 80))
sensor.skip_frames(time = 2000)
#clock = time.clock()
FPS=10
red_led=... |
#!/usr/bin/env python
# coding=utf-8
#================================================================
# Copyright (C) 2020 Fisher. All rights reserved.
#
# 文件名称:DIEN.py
# 创 建 者:YuLianghua
# 创建日期:2020年01月18日
# 描 述:
#
#================================================================
from tensorflow as t... |
print(type('HelloWorld'))
print(type(10))
print(type(10.3))
print(type(False))
print(type(1j))
print(type('10')) # todo เป็นข้อความ
print(type(10+3.5))
|
## https://leetcode.com/problems/reverse-linked-list-ii/
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverseBetween(self, head: ListNode, m: int, n: int) -> ListNode:
node_val = []... |
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
def pca_variance(pca, dataframe):
dimensions = ['Dimension {}'.format(i) for i in range(1,len(pca.components_)+1)]
components = pd.DataFrame(np.round(pca.components_, 4), columns = dataframe.keys())
ratios = pca.explained_variance_... |
from tensorflow.keras.preprocessing.image import ImageDataGenerator, array_to_img, img_to_array, load_img
from skimage import io, color, filters, feature, restoration
import numpy as np
import matplotlib.pyplot as plt
import sys
import os
this_file = os.path.realpath(__file__)
SCRIPT_DIRECTORY = os.path.split(this_file... |
# ! /usr/bin/env python
# -*- coding: utf-8 -*-
# __author__ = "Miller"
# Datetime: 2019/11/20 9:09
import pymysql
conn = pymysql.Connect(host="127.0.0.1", port=3306, user="root", password="123", db="db10", autocommit=False)
cursor = conn.cursor()
cursor.executemany("insert into actor(name) values (%s)", args=("mil... |
#SendMail.py
import smtplib
from datetime import date
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
def sendEmailFn(fromaddr, toaddr, mailPass, zipFiles, dirPath):
print('SendMail')
try:
#set test val... |
import sys
i = 0
phrase = "The right format"
while i + len(phrase) < 42:
print('-', end='')
i += 1
print(phrase, end='')
|
class Room:
def __init__(self, room_number, capacity, room_cost):
self.room_number = room_number
self.song_list = []
self.guests = []
self.capacity = capacity
self.room_cost = room_cost
self.total_guest_money = 0
self.guest_money = {}
def check_guest_in(... |
# -*- coding:utf-8 -*-
"""
python 数据结构 : list
@author:dell
@file: Day07_05_list.py
@time: 2020/01/08
"""
if __name__ == '__main__':
# 创建方式一
list1 = list("abcde")
# 创建方式二
list2 = [1, 2, 3]
# 遍历
for ele in list1:
print(ele)
for i in range(len(list2)):
print(list2[i])
fo... |
N, K, L = map(int, input().split())
round = 1
while True:
if abs(K-L) == 1 and min(K,L) % 2:
break
K = (K+1)//2
L = (L+1)//2
round += 1
print(round)
'''
1 2 3 4 5 6 7 8 9 10 11
1 2 3 4 5 6
1 2 3
1 2
1
''' |
"""Django URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Clas... |
import pandas as pd
from sklearn.linear_model import LogisticRegression
train = pd.read_csv("train.csv")
print(train.head())
monthly_income_mean = train["MonthlyIncome"].mean()
train = train.fillna({"MonthlyIncome" : monthly_income_mean, "NumberOfDependents": 1})
y = train['SeriousDlqin2yrs']
print(y.head())
X = trai... |
import cv2
import numpy as np
import pandas as pd
import os
import csv
from csv import writer
from csv import reader
class BloodVesselsExtract:
def extract_bv(self, image):
b, green_fundus, r = cv2.split(image)
clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))
contrast_enhanced... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
class FaceExtInfo(object):
def __init__(self):
self._max_age = None
self._min_age = None
self._query_type = None
@property
def max_age(self):
return self._max_a... |
import hashlib
import logging
try:
from django.core.cache import caches
from django.conf import settings
except ImportError:
from diskcache import Cache as caches
# logger
logger = logging.getLogger('djangoweasycache')
class Conf(object):
"""
Configuration class
"""
try:
conf = se... |
# test.py
from src.WeatherAPP1 import WeatherAPP1
from src.WeatherAPP2 import WeatherAPP2
from src.WeatherAPP3 import WeatherAPP3
from src.WeatherSDK import WeatherSDK
from src.air_quality import AirQuality
sdk = WeatherSDK()
app1 = WeatherAPP1(sdk)
app2 = WeatherAPP2(sdk)
app3 = WeatherAPP3(sdk)
sdk.registeObserver(ap... |
import pygame
import pygame.freetype
import string
import settings as st
from math import sqrt
SQRT2 = sqrt(2)
def floatcastable(str):
try:
float(str)
return True
except:
return False
LATEX_FONT_PATH = st.font_locator("cmu.ttf")
LATEX_iFONT_PATH = st.font_locator("cmu_i.ttf")
LATEX_bFO... |
# Finding E to the Nth Digit
# ---------------------------
# Just like the previous problem, but with e instead of PI.
# Enter a number and have the program generate e up to that many decimal places.
# Keep a limit to how far the program will go.
# ---------------------------
# Ref - https://www.mathsisfun.com/numbers... |
# https://leetcode.com/problems/palindrome-linked-list/description/
"""
Given a singly linked list, determine if it is a palindrome.
Example 1:
Input: 1->2
Output: false
Example 2:
Input: 1->2->2->1
Output: true
Follow up:
Could you do it in O(n) time and O(1) space?
"""
# Definition for singly-linked list.
class... |
import psycopg2
import psycopg2.extras
from random import randint, choice, shuffle, randrange
import string
from math import ceil, floor
import matplotlib.pyplot as plt
import numpy as np
import os
def get_crossover_point(n_rows, more_size):
percentile_low = 0
percentile_high = 100
while True:
conn... |
import tensorflow as tf
import numpy as np
IMAGE_SIZE = 64
LABEL_NUM = 75
class Dataset(object):
def __init__(self, images, labels, one_hot=False, dtype=tf.float32):
dtype = tf.as_dtype(dtype).base_dtype
if dtype not in (tf.uint8, tf.float32):
raise TypeError('Invalid image dtype %r, e... |
import sys, urllib2, smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from bs4 import BeautifulSoup
class Book:
def __init__(self, title, author, price, summary):
self.title = title
self.author = author
self.price = price
self.summary = su... |
#!/usr/bin/env python
#-*-coding:utf-8-*-
"""
Copyright (c) 2013 Qimin Huang <qiminis0801@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitat... |
from unittest import TestCase
def num_coins(cents: int) -> int:
total_num_coins = 0
for coin in [25, 10, 5, 1]:
total_num_coins += cents//coin
cents %= coin
return total_num_coins
class TestNumCoins(TestCase):
def test_33(self):
self.assertEqual(num_coins(33), 5)
def ... |
#!/usr/bin/env python3
import pytest
from pftpy.actions import ActionContext
from pftpy.graph_actions import partition
import igraph
@pytest.fixture
def ctx():
ctx = ActionContext()
ctx.register_actions(*partition.defined_actions)
return ctx
def test_bfpartition(ctx):
graph: igraph.Graph = igraph.Gra... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import logging
import uuid
from django.utils.translation import ugettext_lazy as _
from django.db.models.signals import post_save
from django.dispatch.dispatcher import receiver
from django.db import models
from authtools.models import AbstractEmailUser
f... |
a = int(input("Enter the a:"))
b = int(input("Enter the b:"))
c = int(input("Enter the c:"))
disc = (b**2)-4*a*c
Real_1 = (-b+(disc**0.5))/(2*a)
Real_2 = (-b-(disc**0.5))/(2*a)
if disc > 0:
print("There are two real roots:")
print(Real_1)
print(Real_2)
elif disc == 0:
print("There is one real root")
print(R... |
from collections import Counter
import json
import os
data_root_list = [
"data/chinese/seq2umt_ops",
"data/chinese/wdec",
"data/nyt/wdec",
"data/nyt/seq2umt_ops",
"data/nyt/seq2umt_pos",
]
wdec_nyt_root = "data/nyt/wdec"
wdec_chinese_root = "data/chinese/wdec"
# triplet = s p o
def cnt_train_ke... |
from eutility.eutility import timer
from eutility.fileops import data
from eutility.fileops import printdoc
from eutility.fileops import matrix
from eutility.fileops import readcsv
# This is a list of solved problems.
# the euler000 function is the generic version of the problem.
# the problem000 function takes no ar... |
from django.shortcuts import render,redirect
#from student.forms import Studentform
from student.models import Studenttable
from django.contrib import messages
def studentpage(request):
return render(request,"student/studentpage.html")
def registerstudent(request):
return render(request,"student/registerstude... |
"""
Array of Array Products
Given an array of integers arr, you’re asked to calculate for each index i the product of all integers except the integer at that index (i.e. except arr[i]). Implement a function arrayOfArrayProducts that takes an array of integers and returns an array of the products.
Solve without using d... |
import pygame
import time
from project.objects.object_game import Game
from project import config
config_object = getattr(config, "MainConfig")
def main(level_id):
game = Game(level_id)
screen = pygame.display.set_mode(game.get_size())
pygame.display.set_caption("Tank Game")
clock = pygame.time.Clo... |
X, Y, Z = map(int, input().split())
ans = 0
for i in range(0, Z+1):
A = X + i
B = Y + (Z - i)
ans = max(ans, min(A, B))
print(ans)
|
'''
Created on Jul 10, 2014
@author: jtaghiyar
'''
import codecs
import os
import re
from setuptools import setup
def read(*paths):
here = os.path.dirname(os.path.abspath(__file__))
with open(os.path.join(here, *paths)) as f:
return f.read()
def get_version():
version_file = read("kronos", "kron... |
import unittest
import warnings
from gevent.testing.modules import walk_modules
from gevent.testing import main
from gevent.testing.sysinfo import NON_APPLICABLE_SUFFIXES
from gevent.testing import six
class TestExec(unittest.TestCase):
pass
def make_exec_test(path, module):
def test(_):
with op... |
givenTestCase = [0x20072000, 0x20e6fffd, 0x00072022, 0x00864020, 0x3105000f, 0x0085402a,
0xac082008, 0x20e70008, 0xace8fffc, 0x8c082004, 0x8ce50000]
myTestCase = [0x2084115c, 0x2001115c, 0x00812022, 0x200501a4, 0x30a60539, 0xac062000, 0x8c072000, 0xac070000]
instructions = {"0b000000": {"0b100000": "... |
#!/usr/bin/env python
"""
The DXPServer allows people to store and retrieve dynamic instruction
frequency information for Python programs. It is hoped that by offering
this service to the Python community a large database of instruction count
frequencies can be accumulated for different versions of Python.
The DXPse... |
import math
from tkinter import *
root = Tk()
root.title("DEV's CALCULATOR")
input_field = Entry(root, bg="#9bd12e", fg="black", width=27, font=20, borderwidth=9, relief=SUNKEN)
input_field.grid(row=0, column=0, columnspan=5)
op = ""
var1 = 0
def display(number):
input_field.insert(END, number)
def operation(... |
from spotipy import oauth2
from .config import base_url
SPOTIPY_CLIENT_ID = "9dacc40b7cf6403289c13726ae7a6647"
SPOTIPY_CLIENT_SECRET = "27e24d7036974055813ea973024b3a0c"
SPOTIPY_REDIRECT_URI = base_url + "auth_callback"
SCOPE = 'user-library-read playlist-read-private ugc-image-upload user-read-playback-state user-rea... |
import numpy as np
import math
class Vector2D():
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return "x={}, y={}".format(self.x, self.y)
def modul(self):
lenght = ((self.x)**2 + (self.y)**2)**0.5
return lenght
def zwi... |
from jarjar import jarjar
# define a jarjar
jj = jarjar()
# vanilla channel change
res = jj.text('1', channel='@nolan')
# unicode in message
res = jj.text(u'2 \ua000')
# unicode in attach
res = jj.attach({u'Unicode \ua000': u'Unicode \ua000'}, message='3')
# decorator
@jj.decorate(message='4', attach={'exception?... |
# -*- coding: utf-8 -*-
from .tools import getUrl, loadHTML, re_, writeToFile
def main():
lineUrl = input("Введите URL: ")
title = getUrl(str(lineUrl))
if title == None:
print("URL not found")
text = loadHTML(lineUrl)
textFound = re_(text)
writeToFile(textFound, lin... |
"""
2 - ( modificar parametros): A qualquer momento posso abrir a tela que define
e modificar os parâmetros das janelas de corte.
""" |
#!/usr/bin/env python
# coding: utf-8
import gym
import time
import numpy as np
import office_control.envs as office_env
#import MC.EpsilonGreedy as MCE
#import TD.QLearning as QL
import NN.DQN as DQN
#import FA.QLearning_FA as LQL
from lib import plotting
#import envTest
import argparse
import os
def get_output_fo... |
# 287. Find the Duplicate Number
# https://leetcode.com/problems/find-the-duplicate-number/
class Solution:
def findDuplicate(self, nums: 'List[int]') -> 'int':
# Floyd's Tortoise and Hare (Cycle Detection)
# 1. detect loop exist
# 2. detect the entrance to the cycle
tortoi... |
# This program takes two input files as input, (one is control file "zma_mature_700_701" and another one is treatment file "zma_mature_714", in case of my project) compares #them and gives common miRNAs between them and their respective count in each file.
with open('zma_mature_700_701', 'r') as file1:
with open(... |
from mininet.topo import Topo
class MyFirstTopo(Topo):
"Simple topolopy example."
def __init__(self):
"Create custom topo."
#Init topo
Topo.__init__(self)
#Add hosts and switches
h1 = self.addHost('h1')
h2 = self.addHost('h2')
h3 = self.addHost('h3')
h4 = self.addHost('h4')
leftSwitch = self.addSwi... |
#!/usr/bin/python
from __future__ import division
import logging
import math
import signal
import sys
import time
from threading import Timer
import led_configs
from nuimo import Nuimo, NuimoDelegate
from sonos import SonosAPI
nuimo_sonos_controller = None
class NuimoSonosController(NuimoDelegate):
def __in... |
import torch
from tqdm.notebook import tqdm
from utils import highlight, erase, binary_metric
import torch.nn.functional as F
def dice_loss(pred, label):
smooth=1e-3
true = label.masked_fill(label < 0, 0)
pred = F.softmax(pred, dim = 1)
true = F.one_hot(true, num_classes=pred.shape[1])
inse = torch.sum(pred * ... |
import socket # Import socket module
s = socket.socket()
host = socket.gethostname()
port = 8667 # Reserve a port for your service.
s.connect((host, port))
while True:
message=raw_input("Enter message: ")
if message=="end":
s.close()
break
s.send(message)
data=s.recv(1024)... |
# Generated by Django 2.2.2 on 2019-09-18 07:17
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('type_data', '0008_accident'),
]
operations = [
migrations.AlterField(
model_name='accident',
name='death_toll',
... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
"""Testing the different dict implementations in `gl.utils.dicts`.
"""
from __future__ import (
division, print_function, absolute_import, unicode_literals)
# Third party libraries.
import pytest
# DNV GL libraries.
from dnvgl.framework.dict import SortedDict, CaseI... |
for i in range (100,0,-1):
print(i, "bottles of cola on the wall, take one down, pass it around,", i-1,"bottles of cola on the wall!")
|
from datetime import datetime
class Spy:
def __init__(self,name,salutation,age,rating):
self.name= name
self.salutation = salutation
self.age= age
self.rating= rating
self.is_online=True
self.chats=[]
self.current_status_message= None
class chatmessage:
... |
# USAGE
# python motion_detector.py
# python motion_detector.py --video videos/example_01.mp4
# import the necessary packages
from imutils.video import VideoStream
import argparse
import datetime
import imutils
import time
import cv2
import yagmail
import os
import subprocess
# construct the argument parser and parse... |
max_coor = 300
def calculate_grid(serial):
grid = [[0 for row in range(0, max_coor)] for col in range(0, max_coor)]
for col in range(0, max_coor):
for row in range(0, max_coor):
grid[col][row] = calculate_power(col, row, serial)
return grid
def calculate_power(x, y, serial):
rack_i... |
import json
import pathlib
import os
import sys
import re
import difflib
import colorama
import typing
from ansible_collections.nhsd.apigee.plugins.module_utils.models.manifest import meta
from ansible_collections.nhsd.apigee.plugins.module_utils.models.manifest.manifest import Manifest
SCHEMA_VERSION_REGEX = re.com... |
# Math
import theano
import theano.tensor as T
import numpy
# Model
from model import *
from alphabet import Alphabet
from corpus import Corpus
# Plumbing
import pickle
import argparse
import os
import sys
# Increase the recursion limit, which is required for
# gradient compilation
sys.setrecursionlimit(9999)
# Con... |
# Copyright (c) OpenMMLab. All rights reserved.
import os
import os.path as osp
import re
import warnings
from operator import itemgetter
import mmcv
import numpy as np
import torch
from mmcv.parallel import collate, scatter
from mmcv.runner import load_checkpoint
from mmaction.core import OutputHook
from mmaction.da... |
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
df = pd.read_csv('data/titanic_data.csv')
print(df.head(10))
|
# 26:49
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution1(object):
def inorderSuccessor(self, root, p):
return self.inorderSearch(root, p)
def inorderSearch(self, node, p):
if not node:
return
... |
#!/usr/bin/python3
from gi.repository import Gtk
#from gi.repository import GLib
from gi.repository import GObject
from pprint import pprint
import urllib
#import sqlite3
import threading
#from "../py-sonic/py-sonic/"
#from importlib import import_module
#importlib.import_module("../py-sonic/py-sonic/")
#import_modu... |
# -*- coding: utf-8 -*-
from odoo import models, fields, api
from odoo.exceptions import UserError
import copy
class StockImmediateTransfer(models.TransientModel):
_inherit = "stock.immediate.transfer"
@api.multi
def process(self):
'''移动'''
context = self.env.context or {}
pickings... |
import requests
import json
#http://www.itwhy.org/%E8%BD%AF%E4%BB%B6%E5%B7%A5%E7%A8%8B/python/python-%E7%AC%AC%E4%B8%89%E6%96%B9-http-%E5%BA%93-requests-%E5%AD%A6%E4%B9%A0.html
#r = requests.get('http://10.199.96.149:8080/api/v3/banned/?_page=1&_limit=10000',auth=('intelligentFamily-client','Mjg5NTM2NTk1MzI0Mzg2MDExMjg... |
from typing import List, Set, Dict
import pytest
# 80ms, 15.7MB (98%, 43%)
class SolutionFirst:
def merge(self, intervals: List[List[int]]) -> List[List[int]]:
if not intervals:
return
res = []
intervals = sorted(intervals)
pre_begin, pre_end = intervals[0]
for... |
# Standard library imports
from datetime import datetime
import influxdb_client
from influxdb_client.client.write_api import SYNCHRONOUS
# Third party imports
import yfinance as yf
# Local application imports
from include.writetodb import writePriceToDb
def getTickerPriceHistory2Db(ticker,bucket,org,url,token):
... |
import streamlit as st
from datetime import date
from utils import load_model
from plot import plot
from data import get_date
from keras import backend as K
@st.cache
def load_date(dt):
return get_date(dt)
@st.cache(allow_output_mutation=True)
def load_fronts_model():
model = load_model("weights.hdf5")
... |
#!/usr/bin/env python
import cv2
import numpy as np
import rospy
from cv_bridge import CvBridge, CvBridgeError
from sensor_msgs.msg import Image
def find_circle(msg):
global bridge
img = bridge.imgmsg_to_cv2(msg, desired_encoding="passthrough")
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
img = cv2.... |
def max_subarray(arr, start, end):
if start == end:
return (arr[start], start, end)
else:
mid = (start+end)//2
lmax = max_subarray(arr, start, mid)
rmax = max_subarray(arr, mid+1, end)
cmax = max_cross_subarray(arr, start, mid, end)
return max((lmax, rmax, cmax), key=lambda x:x[0])
def max_cross_subarray... |
#!/usr/bin/env python
# coding: utf-8
# In[ ]:
#While loop
num = int(input("Enter the number: "))
sum = 0
i = 1
while i<=5:
sum = sum + i
i += 1
print("The sum till the given num is: ", sum)
# In[ ]:
#while loop to add digits in out given number
n = 9790058868
tot = 0
while 0<n:
dig = n % 10 # Thi... |
s = str(input())
teamA = 0
teamB = 0
answer = "NO"
for i in range(0, len(s)):
if(teamA == 7 or teamB == 7):
answer = "YES"
if(s[i] == "0"):
teamA += 1
teamB = 0
elif(s[i] == "1"):
teamA = 0
teamB += 1
print(answer) |
from setuptools import setup
setup(
name = 'Grub Wallpaper Generator',
version = '1.0',
py_modules = ['animewal'],
install_requires = [
'click',
'requests',
'bs4',
],
entry_points = '''
[console_scripts]
grubwallpaper = animewal:cli
''',
)
|
def classPhotos(r,b):
# Write your code here.
r.sort()
b.sort()
if(len(r)>=1 and len(b)>=1):
ct=0
while(r[ct]==b[ct]):
return False
if(r[ct]>=b[ct]):
for i in range(ct+1,len(r)):
if(r[i]<=b[i]):
return False
return True
elif(b[ct]>=r[ct]):
for i in range(ct+1,len(r)):
if(b[i... |
# coding=utf-8
import caffe
import numpy as np
deploy = "/Users/lhw/caffe-project/race_classification/race_deploy.prototxt"
caffemodel = "/Users/lhw/caffe-project/race_classification/race_iter_500000.caffemodel"
image = "/Users/lhw/caffe-project/race_classification/test_image/aaa.bmp"
net = caffe.Net(deploy, caffemo... |
import sqlite3
import os
class config():
path = os.path.dirname(os.path.realpath(__file__))
con = sqlite3.connect(path+"/db/"+"frameshock.db");
host="192.168.0.107";
LPORT=9669;
WebPort=80
Apache="/var/www"
#Shodan API KEY
#wAVHCCkorRhFNwGOE6JO9OXVkacdBxlH
APIKey="wAVHCCkorRhFNwGOE6... |
import json
import datetime
import random
from django.utils import timezone
from logging import Handler
class DBHandler(Handler, object):
"""
This handler will add logs to a database model defined in settings.py
If log message (pre-format) is a json string, it will try to apply the array onto the log even... |
from random import choice
def generateRelic():
return choice(relics)
relics = [
'Axe of the Dwarvish Lords',
'Baba Yaga\'s Hut',
'Codex of the Infinite Planes',
'Good Crown of Might',
'Neutral Crown of Might',
'Evil Crown of Might',
'Crystal of the Ebon Flame',
'Cup and Talisman of Al\'Akbar',
'... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.