content stringlengths 5 1.05M |
|---|
# Generated by Django 3.0.11 on 2021-03-23 08:16
from django.db import migrations
import wagtail.core.blocks
import wagtail.core.fields
class Migration(migrations.Migration):
dependencies = [
('home', '0004_auto_20210323_0728'),
]
operations = [
migrations.AddField(
model_na... |
import rdtest
import renderdoc as rd
class D3D12_Draw_Zoo(rdtest.Draw_Zoo):
demos_test_name = 'D3D12_Draw_Zoo'
internal = False |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Make a 2D histogram using scatter plots
See:
- http://jakevdp.github.io/mpl_tutorial/tutorial_pages/tut3.html
"""
import numpy as np
import matplotlib.pyplot as plt
# MAKE DATA ###################################################################
x, y = np.random.n... |
# Generated by Django 3.2.8 on 2021-11-03 02:06
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('api', '0002_auto_20211030_0137'),
]
operations = [
migrations.AddField(
model_name='case',
name='archive',
... |
"""This module is the implementation of the MSSSIM_VAE proposed in
(https://arxiv.org/abs/1511.06409).
This models uses a perceptual similarity metric for reconstruction.
Available samplers
-------------------
.. autosummary::
~pythae.samplers.NormalSampler
~pythae.samplers.GaussianMixtureSampler
~pythae... |
from setuptools import setup, find_packages
with open('requirements.txt') as f:
requirements = f.read().splitlines()
setup(
name='codonPython',
version='0.2.1',
license='BSD',
packages=['codonPython', ],
install_requires=requirements,
author='NHS Digital DIS Team',
author_email='paul.e... |
#!/usr/bin/env python3
from dateutil import parser
import json,datetime,time
import matplotlib.pyplot as plt
from numpy import sort
with open('tweet.js', 'r') as f:
file = f.read()
tweets_raw = json.loads(file)
tweets = []
for tweet in tweets_raw:
tweets.append(tweet['tweet'])
def showTweetsPerDay():
... |
import subprocess
import os
from GpdbBuildBase import GpdbBuildBase
INSTALL_DIR="/usr/local/gpdb"
def fail_on_error(status):
import sys
if status:
sys.exit(status)
class GpBuild(GpdbBuildBase):
def __init__(self, mode="orca"):
GpdbBuildBase.__init__(self)
self.mode = 'on' if mode ... |
'''
1. create a thread to borrow a book
2. I first do something else
3. If he has got the book and returns to me, then I pause the current task and place the book in the shelf
4. After that, I continue to do previous things
'''
import multiprocessing
import time
import os
import threading
def borrow(b... |
# Copyright (c) 2006-2009 The Trustees of Indiana University.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without ... |
import numpy as np
# np.random.seed(123)
# materix1 = np.random.randint(1,20,9).resize(3,3)
# materix2 = np.random.randint(1,20,9).resize(3,3)
# np.hstack(materix1,materix2)
# np.vstack(materix1,materix2)
'''Test Soluation '''
arr=np.random.randint(1,50,24).reshape(3,4,2)
print(arr) |
from mysql import connector
from database_login import username, password, host
from utility.bet_utility import BetPrice
def setup_database():
create_sql = """CREATE DATABASE `bets`;
USE `bets`;
CREATE TABLE `bet` (
`idbet` in... |
"""Module for testing Coding DNA Substitution Classifier."""
import unittest
from variation.classifiers import CodingDNASubstitutionClassifier
from .classifier_base import ClassifierBase
class TestCodingDNASubstitutionClassifier(ClassifierBase, unittest.TestCase):
"""A class to test the Coding DNA Substitution Cl... |
import pandas as pd
import numpy as np
from plotly.graph_objs import *
import plotly
import plotly.plotly as py
import plotly.graph_objs as go
from config import constants, logger_config, _data_dir
import logging.config
import logging
import credentials
plotly.tools.set_credentials_file(username=credentials.plotlyu,
... |
import pickle
import numpy as np
from scipy.stats import f as F
from scipy import stats
from matplotlib import pyplot as plt
# READ DATA
ang = [0, 15, 30, 45, 60, 75]
stokes_param = 'S'
L = []
for a in ang:
S = stokes_param + 'pol_' + str(a) + 'deg.pickle'
filename = '/'.join(['data', S])
with open(file... |
#!/usr/bin/env python
#
# Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
#
# Licensed under the Universal Permissive License v 1.0 as shown at
# http://oss.oracle.com/licenses/upl.
import collections
import os.path
import os
import stat
import tensorflow as tf
from tensorflow.contrib.keras i... |
import argparse
import os
import requests
def fetch_spacex_last_launch(path):
os.makedirs(path, exist_ok=True)
url = 'https://api.spacexdata.com/v3/launches/latest'
response = requests.get(url).json()
images_url = response['links']['flickr_images']
for num, image_url in enumerate(images_url, start... |
from selenium import webdriver
class Browser(object):
base_url = 'http://localhost:8080'
# insert browser here
driver.implicitly_wait(10)
driver.set_window_size(800, 800)
driver.set_window_position(400, 10)
def find_element(self, *locator):
return self.driver.find_element(*locator)
def close(se... |
try:
from . import lib_util
except ModuleNotFoundError:
import lib_util
class language(object):
CHINESE: int = 1
ENGLISH: int = 2
min_value = CHINESE
max_value = ENGLISH
languageList = [
language.CHINESE,
language.ENGLISH,
]
Connect = None
Start = None
ConnectMode = None
ConnectMod... |
import json
import requests
class SplunkForwarder:
def __init__(self, authorization_token, splunk_ingester_domain, connection_port='443'):
assert 'http' in splunk_ingester_domain
assert authorization_token
self.token = authorization_token
self.ingester_url = "{}:{}{}".format(splunk... |
"""Static Helper Module."""
from config.storage import DRIVERS
def static(alias, file_name):
"""Get the static file location of an asset.
Arguments:
alias {string} -- The driver and location to search for. This could be s3.uploads
file_name {string} -- The filename of the file to return.
... |
import numpy as np
import pandas as pd # required to load tensorflow properly
from tensorflow.keras.models import Sequential
from tensorflow.keras.optimizers import SGD
from json import load
from importlib import import_module
class MLP(object):
"""
Class associated with Multi-Layer Perceptron (Neural Netw... |
# Generated by Django 2.2.6 on 2019-12-01 02:12
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('api', '0014_auto_20191130_2133'),
]
operations = [
migrations.AlterField(
model_name='comment',
name='comment_id',
... |
# _*_ coding: utf-8 _*_
__author__ = 'mtianyan'
__date__ = '2017/8/26 17:06'
from flask import Blueprint
home = Blueprint("home", __name__)
import app.home.views |
name = "scrapy_webdriver"
from .scrapy_webdriver import ScrapyWebdriver
|
from __future__ import print_function, unicode_literals, absolute_import, division
class InternalError(Exception):
pass
class ConstraintNotFound(Exception):
pass
class RequiredFailure(Exception):
pass
|
# -*- coding: utf-8 -*-
# 迭代(iteration)
# 引入模块collections
from collections import Iterable;
# dict迭代操作
D = {'a': 1,'b': 2,'c': 3,'d': 4};
# 迭代key 和 value
for k,v in D.items():
print(k,"=>",v)
print('<------------------------>')
# 迭代key
for k in D:
print('k : ',k)
print('<------------------------>')
#... |
from __future__ import absolute_import
import json
import itertools
from eth_utils import (
force_bytes,
force_obj_to_text,
force_text,
)
from web3.middleware import (
combine_middlewares,
)
class BaseProvider(object):
_middlewares = ()
_request_func_cache = (None, None) # a tuple of (all_... |
from django.shortcuts import render
from django.db.models import F
from rest_framework.viewsets import ViewSet
from rest_framework.response import Response
from api.serializers import RegisterSerializer, TimeListSerializer, ScheduleApiSerializer, ApiCallsSerializer
from api.utils.validations import is_date_and_time_... |
# /usr/bin/env python3
# -*- coding: utf-8 -*-
'''
代理测试
'''
import requests as rq
if __name__ == '__main__':
ip = '120.77.201.46'
port = '8080'
def getAvailableIP( ip, port ):
url = 'http://2017.ip138.com/ic.asp'
proxies = { 'http': 'http://' + ip + ':' + port }
try:
... |
import datetime as dt
import time
from enum import Enum, auto
import uuid
from helpers.timer import Timer
class Type(Enum):
PCM = auto() # Wave Format
ExtPCM = auto() # Wave Format Extensible
class State(Enum):
NEW = auto()
STOP = auto()
ACQUIRE = auto()
PAUSE = auto()
RUN = auto(... |
import argparse
import os
import numpy as np
EMBS_ROOT = os.path.join(os.path.dirname(__file__), 'embs')
if __name__ != '__main__':
exit()
#======================================================================================
parser = argparse.ArgumentParser()
parser.add_argument('models', nargs='+')
parser.ad... |
from pysys.constants import *
from xpybuild.xpybuild_basetest import XpybuildBaseTest
class PySysTest(XpybuildBaseTest):
def execute(self):
self.xpybuild(stdouterr='xpybuild', args=['OUTPUT_DIR=%s/build-output'%self.output])
self.logFileContents('build-output/output.txt')
def validate(self):
self.assertDiff(... |
# Examples of creating a log with D3 graphics
from modules.html_log.html_log import HtmlLog as log
log.config(filename="logs/test_with_D3.htm", mode='overwrite', use_D3=True, css="../D3_barchart.css")
log.new_run()
################### 1st plot ##########################
log.write("Time to do a D3.js plot:", s... |
import qrcode
from PIL import Image
qr = qrcode.QRCode(
version = 1,
error_correction = qrcode.constants.ERROR_CORRECT_H,
box_size = 3.5,
border = 8,
)
data = "Test QR Code"
qr.add_data(data)
qr.make(fit=True)
img = qr.make_image()
img = img.convert('RGB')
img.save('../resources/qr.bmp')
print('QR C... |
from typing import Callable, Iterable, Union, List, Optional
from numpy import ndarray, vectorize, vstack
from optmlstat.functions.function_base import FunctionBase
class ComponentWiseFunction(FunctionBase):
"""
Component-wise function.
f(x) = [f1(x1) f2(x2) ... fn(xn)]^T
"""
def __init__(self... |
from django.contrib import admin
from django.contrib.auth.models import User
from django.contrib.auth.admin import UserAdmin
from django.db.models import Count
from .models import Blog, Post, Upvote, Hit, Subscriber, Emailer
from django.utils.html import escape, format_html
from blogs.helpers import add_email_address,... |
import numpy
import matplotlib.pyplot as plt
def display_data(x_array, example_width=None, figsize=(10, 10)):
"""
Displays 2D data in a nice grid.
Parameters
----------
x_array : array_like
The input data of size (m x n) where m is the number of examples and n is the number of
fe... |
#!/usr/bin/env python3
# SCRIPT TO TEST THE PROJECT
from glob import glob
import subprocess
import tempfile
import os
import argparse
import sys
import datetime
from pathlib import Path
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKCYAN = '\033[96m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\03... |
# generated from catkin/cmake/template/pkg.context.pc.in
CATKIN_PACKAGE_PREFIX = ""
PROJECT_PKG_CONFIG_INCLUDE_DIRS = "/home/hyperxai01/can-autoware/install/include".split(';') if "/home/hyperxai01/can-autoware/install/include" != "" else []
PROJECT_CATKIN_DEPENDS = "roscpp;geometry_msgs;rosconsole;autoware_msgs;messag... |
'''
sparkpy.utils
~~~~~~~~~~~~~~
Utility functions that are used internally by sparkpy
'''
import base64
from urllib.parse import urlparse
from uuid import UUID, uuid4
# Shortcuts to translate between internal API paths
# and the external url paths
url2api = {'messages': 'MESSAGE',
'rooms': 'ROOM',
... |
"""
Find the intersection of two sorted arrays.
OR in other words,
Given 2 sorted arrays, find all the elements which occur in both the arrays.
Input :
A : [1 2 3 3 4 5 6]
B : [3 3 5]
Output : [3 3 5]
Input :
A : [1 2 3 3 4 5 6]
B : [3 5]
Output : [3 5]
"""
class Solution:
# @param A : tuple o... |
import sqlite3
token = "2073864492:AAH0ksHyEU_9fR-EEVV0_ANe110e0GSWbvM"
#--------------------------------
# Функции работы с БД
# добавить пробежку в БД
def insertRunIntoBD(msg, text):
with sqlite3.connect('running.db') as con:
cursor = con.cursor()
cursor.execute('INSERT INTO runningData (user_id... |
from sqlalchemy import Column, ForeignKey
from sqlalchemy.orm import relation, backref
from sqlalchemy.types import Integer, String, DateTime, Boolean
from datetime import datetime
from cyberweb.model import meta
from cyberweb.model.meta import Base
class Resource(Base):
__tablename__ = 'resource'
id = Colu... |
#
# Copyright (c) 2013-2020 Contributors to the Eclipse Foundation
#
# See the NOTICE file distributed with this work for additional information regarding copyright
# ownership. All rights reserved. This program and the accompanying materials are made available
# under the terms of the Apache License, Version 2.0 whic... |
#-*-coding:utf-8-*-
import urllib, urllib2, time, json, random, traceback, sys
def download(url, data_dict=None, req_type='GET', timeout=15, num_retries=3, proxy=None, local_file=None, save=False, noprint=False):
""" 下载html
url 网页地址
data_dict 请求附带的字典数据,默认不附带数据
req_type 请求类型,默认GET
timeout 超时时间,默认2... |
#!/usr/bin/env python
from __future__ import print_function
import sys , rospy ,cv2 ,time ,signal ,rospkg ,os.path , yaml , io ,thread
import numpy as np
import camera_info_manager
from std_msgs.msg import String , Header
from sensor_msgs.msg import Image, CompressedImage, CameraInfo
from sensor_msgs.srv import SetCame... |
#!/usr/bin/env python3
import random
import math
class Food:
'''
Creates a food object.
'''
def __init__(self, id, mapsize):
'''
Creates a food object
'''
self.id = id
self.mapsize = mapsize
self.food_value = 1 + (0.2*random.random() - 0.1)
sel... |
import cv2, os
import config, displayinfo, separateframes, uploadtoftp
def setupCapture():
cap = cv2.VideoCapture(config.cameraID)
fourcc = cv2.VideoWriter_fourcc(*"XVID")
out = cv2.VideoWriter("capture.avi", fourcc, config.native_fps, config.cap_res)
frameCounter=1
while cap.isOpened:
ret... |
from django.apps import AppConfig
class EquipamentosConfig(AppConfig):
name = 'equipamentos'
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from datetime import datetime, timedelta
from django.test import TestCase
from django.test.utils import override_settings
try:
from unittest.mock import patch
except ImportError:
from mock import call, patch # NOQA
from red... |
"""
These functions query the software subscription configuration of a system or
cluster.
"""
|
from django.conf.urls import url
from .views import execute_script_view
urlpatterns = [
url(r'^execute/$', execute_script_view, name='execute-script'),
]
|
from uatu.watchers import *
from sklearn.model_selection import train_test_split
from os import path
from time import time
t0 = time()
dir = '/scratch/users/swmclau2/UatuTraining2/'
#dir = '/home/users/swmclau2/scratch/UatuTraining/'
X, y = get_all_xy(dir)
print time() - t0
X_train, X_test, y_train, y_test = train_te... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from solution import MedianFinder
mf = MedianFinder()
mf.addNum(1)
mf.addNum(2)
print(mf.findMedian())
mf.addNum(3)
print(mf.findMedian())
|
import cv2
import dlib
from scipy.misc import imresize
sp = dlib.shape_predictor('datasets\\shape_predictor_68_face_landmarks.dat')
detector = dlib.get_frontal_face_detector()
cap = cv2.VideoCapture(0)
cap.set(3, 640)
cap.set(4, 480)
win1 = dlib.image_window()
while True:
ret, img = cap.read()
im... |
import os
import random
import socket
from argparse import Namespace
from distutils.dir_util import copy_tree
import hydra
import numpy as np
import torch
from pytorch_lightning import Trainer
from pytorch_lightning.callbacks import EarlyStopping, ModelCheckpoint
from torch.backends import cudnn
from solver import So... |
# Classe abstrata, pode ser apenas "PAI", mas não pode ser instanciada diretamente
import abc
from interface_animal import InterfaceAnimal
class Animal(abc.ABC):
def __init__(self, nome, idade, cor, felicidade = 0):
self._nome = nome
self._idade = idade
self._cor = cor
self._felici... |
people=30
cats=40
trucks=15
if cars> people:
print("We should takes the cars.")
elif cars<people:
print("We should not takes the cars")
else:
print("We can't decide")
if trucks>cars:
print("That is too many trucks")
elif trucks<cars:
print("May be we could take the trucks")
else:
print("We still... |
"""
a file contains ad order by given field algorithm with limited memory use
"""
from typing import List
import csv
import csvsorter
import io_utils
def order_ads_limited(csv_file_path: str, column_name: str) -> str:
"""
the main function
:param csv_file_path: the csv's path
:param column_name: the... |
from glow_pytorch.generate_motion_from_model import generate_motion
from misc.shared import BASE_DIR
from misc.generate_test_sequences import generate_videos, get_vad_weights
from misc.find_test_segments import LengthFail, get_frames
import random
import torch
PADDING = 24 * 2
def render(name, output_folder, session,... |
from hustle import Table, insert
from hustle.core.settings import Settings, overrides
IMPS = '__test_imps'
PIXELS = '__test_pixels'
IPS = '__test_ips'
def imp_process(data):
from disco.util import urlsplit
_, (host, _), _ = urlsplit(data['url'])
if host.startswith('www.'):
host = host[4:]
da... |
# Generated by Django 3.0.7 on 2021-03-23 15:15
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('business_register', '0072_auto_20210322_1008'),
]
operations = [
migrations.RunSQL(
sql="""
UPDATE business_register_assignee... |
import pytest
from testrpc.client.filters import *
from testrpc.client.filters import (
check_filter_topics_validity,
)
@pytest.mark.parametrize(
'filter_topics,expected',
(
# valid
([], True),
(['A'], True),
([None, 'A'], True),
(['A', 'B'], True),
([['A',... |
"""
This tests whether
from future.builtins import *
works as expected:
- This should NOT introduce namespace pollution on Py3.
- On Python 2, this should not introduce any symbols that aren't in
__builtin__.
"""
from __future__ import absolute_import, print_function, unicode_literals
import copy
from futur... |
# proxy module
from __future__ import absolute_import
from traits.adapter import *
|
import itertools
import logging
import os
import torch
import numpy as np
from collections import OrderedDict
from fairseq import utils
from fairseq.data import (
SampledMultiEpochDataset,
BacktranslationDataset,
RoundRobinZipDatasets,
ConcatDataset,
LanguagePairDataset,
data_utils
)
from fairse... |
__extension_version__ = "0.11.0"
__extension_name__ = "pytket-honeywell"
|
"""
Starter lists have been included to handle the Latin enclitics
(-que, -ne, -ue/-ve, -cum). These lists are based on high-frequency vocabulary
and have been supplemented on a as-needed basis; i.e. they are not
comprehensive. Additions to the exceptions list are welcome. PJB
"""
from typing import List
que_except... |
#!/usr/bin/env python
#--coding:utf-8 --
"""
pipe.py
2017-03-22: finished basically
2017-06-26: runsecond model refined
2017-06-27: modified runsecond model, as extend the second time result
2017-06-30: modified the combining method
2017-07-20: modified some output.
2017-07-28: modified overlaps, change to the samll on... |
from math import trunc
n = float(input('Digite um valor: '))
inteiro = trunc(n)
print('O valor digitado foi {} e a sua porção inteira é {}'.format(n, inteiro))
|
# -*- coding: utf-8 -*-
from concurrent.futures import ThreadPoolExecutor
import asyncio
import zmq
import zmq.asyncio
url = "tcp://127.0.0.1:5000"
loop = zmq.asyncio.ZMQEventLoop()
@asyncio.coroutine
def recv_and_process(num):
ctx = zmq.asyncio.Context()
# sock = ctx.socket(zmq.SUB)
sock = ctx.socket(zmq.PULL... |
from pdfminer.pdfparser import PDFParser, PDFDocument
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.converter import PDFPageAggregator
from pdfminer.layout import LTTextBoxHorizontal, LAParams,LTTextBox,LTFigure,LTImage,LTTextLine,LTChar,LTPage
from pdfminer.pdfinterp import PDFTex... |
try:
import matplotlib
matplotlib.use('agg')
import matplotlib.pyplot as plt
from scipy import interp
from itertools import cycle
import numpy as np
from sklearn.metrics import roc_curve, auc
from sklearn.metrics import confusion_matrix
from sklearn.preprocessing import label_binari... |
import os, json, sys
import tornado.web
path = json.loads(open(os.path.join(sys.prefix, "etc", "jupyter", "jupyter-data-directory.json")).read())["path"].format(prefix=sys.prefix)
def url_path_join(*pieces):
"""
Duplicated from Jupyter Server
"""
initial = pieces[0].startswith('/')
final = pieces[... |
import os
import sys
DATASET_PATH_512='./data/humanprotein/input/test/'
DATASET_PATH_1024='./data/humanprotein/input1024/test/'
# DATASET_PATH_512='/ai/local/lichuanpeng/DataSet/Kaggle/HumanProtein/input/test/'
# DATASET_PATH_1024='/ai/local/lichuanpeng/DataSet/Kaggle/HumanProtein/input1024/test/'
class BaseConfig():... |
import numpy as np
import copy
from random import randrange
"""
We will check across the diagonal top left to bottom right,
This will allow us to check all possible solutions for a win
"""
def threecheck(board):
win=False
#Top Left
if board[0]!=0:
#Row T-L to T-R
... |
from .__init__ import *
from custom_widgets import *
from timer import Timer
from counter_thread import CounterThread
class View(BaseView):
def __init__(self, parent_window: QMainWindow, waiting_time: int, controller):
super(View, self).__init__(parent_window)
self.parent_window = parent_window
... |
import base64
import binascii
if __name__ == "__main__":
s = b'hello world!'
# 2进制转换成16进制
h = binascii.b2a_hex(s)
print(h)
# 16进制转换成2进制
print(binascii.a2b_hex(h))
h1 = base64.b16encode(s)
print(h1)
print(base64.b16decode(h1)) |
my_dic = {"first" : 1, "second" : 2}
print(my_dic["first"])
print(my_dic["second"])
|
# BLS API v1 url
base_url = 'https://api.bls.gov/publicAPI/v1/timeseries/data/'
# BLS series id for the civilian labor force participation rate
series = {'id': 'LNS11300000',
'name': 'Labor Force Participation Rate'}
data_url = '{}{}'.format(base_url, series['id'])
print(data_url)
import requests
r = reques... |
from zkay.examples.scenario import ScenarioBuilder
a = 'a'
sb = ScenarioBuilder('ShorthandOps', 'code/ShorthandOps.zkay').set_users(a)
sb.set_deployment_transaction(owner=a)
sb.add_transaction('f', [1, 2], user=a)
sb.add_balance_assertion(0)
SCENARIO = sb.build()
|
import unittest
import enum
from ...layers import UtilsParseString
from bin.commands.utils import parse_string
class TestEnum(enum.Enum):
A = 1
BB = 2
class TestParseString(unittest.TestCase):
layer = UtilsParseString
def test_asBool_true(self):
# expect
self.assertTrue(parse_str... |
# -*- coding: utf-8 -*-
"""A compatibility layer for different versions of PyTorch."""
from typing import Optional
import torch
try:
from torch.fft import irfft, rfft # works on pytorch >= 1.7
except ImportError:
from torch import irfft as old_irfft
from torch import rfft as old_rfft # works on pytor... |
"""
This pipeline first saves individual image maps to the database
- this is an issue because of storage space
1. Select images
2. Apply pre-processing corrections
a. Limb-Brightening
b. Inter-Instrument Transformation
3. Coronal Hole Detection
4. Convert to Map
5. Combine Maps
... |
# https://leetcode.com/problems/find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
def _go_left(node: TreeNode) -> TreeNode:
"""Gets th... |
from gensim.models import KeyedVectors
from nltk.corpus import stopwords
from nltk import word_tokenize
class prepare_similarity:
def __init__( self ):
"""
it's load and prepare the data and inialize the algorithm to start similar with data
"""
self.__load_dataset( "... |
#!/usr/bin/env python
# Roobert - home robot project
# ________ ______ _____
# ___ __ \______________ /_______________ /_
# __ /_/ / __ \ __ \_ __ \ _ \_ ___/ __/
# _ _, _// /_/ / /_/ / /_/ / __/ / / /_
# /_/ |_| \____/\____//_.___/\___//_/ \__... |
import click
import requests
import datetime
from tabulate import tabulate
from datetime import timezone
@click.command()
@click.option('--count', default=10, help='Number of Contests')
def cli(count):
"""
A basic command line tool to show the upcoming competitive programming contests
"""
now = dat... |
import csv
from Levenshtein import distance
import openpyxl
from utils import load_sheet
from utils import log
REF_SCO_PATH = './journals/CiteScore.xlsx'
REF_SCO_SHEET = 'DATA'
REF_SCO_INDEX_NAME = 'CiteScore 2020'
REF_SJR_PATH = './journals/scimagojr 2020.csv'
class Journals():
def __init__(self, data={}):
... |
import numpy as np
import cv2 as cv
import captureImage as cI
import findPerspective as fP
import detectDie as dD
import glob
import argparse
def main():
parseArgs()
frame = cI.captureFrame()
dieNumber = detectDie(frame, True)
print(dieNumber)
def detectDie(frame, showImages):
M = fP.findTranf... |
class Int64Converter(BaseNumberConverter):
"""
Provides a type converter to convert 64-bit signed integer objects to and from various other representations.
Int64Converter()
"""
|
try:
import _hpy_universal
disable = False
except ImportError:
disable = True
def pytest_ignore_collect(path, config):
return disable
|
"""Tests for the panel_custom component."""
|
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rcParams
from matplotlib.animation import FuncAnimation
import matplotlib.animation as animation
from get_data import shake_input
from itertools import count
import time
rcParams['animation.convert_path'] = r'/usr/bin/convert'
rcParams['animation... |
def convert(value, newType):
try:
return newType(value)
except ValueError:
return None
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import pkg_resources
import click
CONTEXT_SETTINGS = dict(
help_option_names=['-h', '--help'],
)
@click.group(context_settings=CONTEXT_SETTINGS)
@click.option(
'--project',
'-p',
'project_dir',
help=(
"Specify a punica project... |
# 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 or agreed to in writing, software
# distributed under the... |
class Solution:
def XXX(self, strs: List[str]) -> str:
if strs == []: # 字符串为空返回''
return ''
elif len(strs) == 1: # 若列表仅有一个单词,返回该单词
return strs[0]
else:
minlen = len(min(strs, key=len)) # 找到最短的单词长度
s = ''
for i in range(1... |
import os
import sys
sys.path.append("../")
from toolBox import EmailBot
import time
os.chdir("../")
emailbot = EmailBot("../data/settings.json")
import requests
url = "http://hq.sinajs.cn/list=sz002739"
field_list = [
"name",
"open",
"last_close",
"price",
"high",
"low",
"buy_price",
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.