text stringlengths 8 6.05M |
|---|
# @Title: 矩阵置零 (Set Matrix Zeroes)
# @Author: 2464512446@qq.com
# @Date: 2019-12-16 11:59:44
# @Runtime: 116 ms
# @Memory: 12.1 MB
class Solution(object):
def setZeroes(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: None Do not return anything, modify matrix in-place instead.
... |
'''
author: juzicode
address: www.juzicode.com
公众号: juzicode/桔子code
date: 2020.5.27
'''
print('\n')
print('-----欢迎来到www.juzicode.com')
print('-----公众号: juzicode/桔子code\n')
print('str类型例程:')
print('\n大小写变换:')
e='juzicode.com'
u = e.upper()
print('转换为大写:',u)
e='JUZIcode.com'
l = e.lower()
print('转换回小写:',l)
|
#!/bin/python3
def get_primes(n):
"""
Return a list of prime numbers below n.
Uses the sieve of eratosthenes to perform the function.
"""
primes = [i for i in range(n + 1)]
for i in range(2, n + 1):
if primes[i] == -1: continue
j = i * 2
while j < n + 1:
pri... |
from browser.html import INPUT, LABEL, BR, FORM
from browser import document
def login_form():
form = FORM(id="meu-forme", action="#", method="GET", target="_blank")
form <= LABEL('seu nome', For='nome', name="nome")
form <= INPUT(id='nome')
form <= BR()
form <= LABEL('sua senha', For='senha', sen... |
for row in range(7):
for col in range(7):
if (col==0 or col==6) or (row==4 and col==3) or (row==5 and (col==2 or col==4)) or (row==6 and (col==1 or col==5)) :
print("*",end="")
else:
print(end=" ")
print()
|
#!/usr/bin/python
from polygon_point_in_out import PointInPolygon2D as PointInPolygon2D_1
from shapely import geometry
def PointInPolygon2D_2(points, point):
line= geometry.LineString(points)
pt= geometry.Point(point)
polygon= geometry.Polygon(line)
return polygon.contains(pt)
from scipy.spatial import Con... |
from action_unit_metric.confusion_mat import reg,confmat
from action_unit_metric.confusion_mat_f1_frame import cm2f1f
from collections_toolkit.dot_dict import Map
def get_F1_frame(label, pred):
'''
Compute F1-Frame
:param label: binary ground turth, type is np.ndarray
:param pred: prediction
... |
import unittest
import mis_funciones as mf
class TestMisFunciones(unittest.TestCase):
def test_es_primo(self):
self.assertFalse(mf.es_primo(256))
self.assertFalse(mf.es_primo(50))
self.assertTrue(mf.es_primo(2))
self.assertTrue(mf.es_primo(7))
self.assertTrue(mf.es_primo(3950827))
def test_es_potencia(sel... |
from tbay import *
def main():
mark = User(name="BigBoo", password="qwerty")
sean = User(name="PillarOfSand", password="qasdfg")
karen = User(name="kbhix", password="zxcvbn")
baseball = Item(name="Signed Baseball", description="Baseball signed by C.R.Jr", owner=mark)
bid1 = Bid(price=10.00, bidder=sean,... |
import jwt
from ...ports.providers import JwtProvider
class JwtProviderImpl(JwtProvider):
def __init__(self, secret: str) -> None:
self._secret_ = secret
def verify(self, token: str):
return jwt.decode(token, self._secret_, algorithms=["HS256"])
|
"""
16Jan20
Genetic Algorithm
The swam laziness is in walking behavior
The threshold is for walking. A random number is used to compare with the walking threshold. Agents always report if detect algae.
If the threshold is to0 high, the agents do not move -> fail.
If the threshold is too low, agents always move and lose... |
from django.apps import AppConfig
class IpamAppConfig(AppConfig):
name = 'ipam'
verbose_name = 'IP Address Management'
def ready(self):
import ipam.signals
|
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'form.ui'
#
# Created by: PyQt5 UI code generator 5.15.2
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
from PyQt5 import QtCore, QtGui, ... |
#!/usr/bin/env python
################################################################
#
# CGC_parser.py
#
# Programmer: Carol Zhou
#
# Description: This code inputs the name of a gene caller plus
# the gene-caller's output file, and outputs a properly formatted
# file for input to CGC_main.py. The ... |
#import sys
#input = sys.stdin.readline
Q = 10**9+7
def main():
N, K = map( int, input().split())
m = 0
M = 0
for i in range(K-1):
m += i
M += N-i
ans = 0
for i in range(K-1, N+1):
m += i
M += N-i
ans += M-m+1
ans %= Q
print(ans)
if __name__ =... |
from itertools import accumulate
N, K = map( int, input().split())
A = list( map( int, input().split()))
accA = [0] + list( accumulate(A))
V = [1]*(N*(N+1)//2)
ans = 0
check = False
for i in range(40,-1,-1):
W = [0]*(N*(N+1)//2)
for l in range(N):
for r in range(l+1,N+1):
if V[l*(2*N+1-l)//2... |
class ElectricGrid:
def __init__(self, power_sources):
self.power_sources = power_sources
def total_power(self):
return sum(power_source.power for power_source in self.power_sources)
def can_fulfill_demand(self, demand):
return self.total_power() >= demand
def simulate_time(se... |
"""
Course scraper for HMC Portal and Lingk. Combines data from the
two sources to get course descriptions.
"""
import re
import traceback
import psutil
import hyperschedule.scrapers.claremont.lingk as lingk
import hyperschedule.scrapers.claremont.portal as portal
import hyperschedule.scrapers.claremont.shared as sh... |
from ED6ScenarioHelper import *
def main():
# 格兰赛尔
CreateScenaFile(
FileName = 'T4220 ._SN',
MapName = 'Grancel',
Location = 'T4220.x',
MapIndex = 1,
MapDefaultBGM = "ed60017",
Flags = 0,
... |
x=input()
a=[]
for i in range(len(x)):
a.append(int(x[i]))
if(a[0]*100+a[1]*10+a[2]==a[0]**3+a[1]**3+a[2]**3):
print(1)
else:
print(0)
|
import sys
import math
import gc
import collections
def solve(jump, start, end, bridge):
jump = jump**2
q = collections.deque()
q.append(start)
visited = [False] * len(bridge)
while q:
x1, y1 = q.pop()
for idx, value in enumerate(bridge):
if visited[idx]:
... |
import numpy as np
# helper function to carefully multiply probabilities
def multiply_probabilities(values):
tolerance = 1e-100
if any([v < 1e-100 for v in values]):
return 0
else:
sum_log = sum([np.log(v) for v in values])
if sum_log <= np.log(tolerance):
return 0
... |
from django.urls import path
from . import views
urlpatterns = [
path(
route='login/',
view=views.login_view,
name='login'
),
path(
route='logout/',
view=views.logout_view,
name='logout'
),
path(
route='home/',
view=views.home_view,
... |
#!/usr/bin/env python3
# May first need:
# In your VM: sudo apt-get install libgeos-dev (brew install on Mac)
# pip3 install https://github.com/matplotlib/basemap/archive/v1.1.0.tar.gz
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import pandas as pd
import datetime
import numpy as np
from ... |
import json
import argparse
import pathlib
from os import listdir
from os.path import isfile, join
import os, sys
import shutil
import boto3
from utils import benchmark_utils as bu
def create_directory(current_path):
if os.path.isdir(current_path):
shutil.rmtree(current_path)
pathlib.Path(current_path... |
import tkinter as tk
root = tk.Tk() # 创建主窗口,容纳整个GUI程序。
root.title = ("Demo") # 设置主窗口对象的标题栏。
theLabel = tk.Label(root , text="The 2nd window!") # 添加Label组件,可以显示文本、图表和图片。
theLabel.pack() # 用于自动调节组件本身的尺寸。
root.mainloop() # 进入主事件循环。 |
import sys
import requests
import argparse
import pandas as pd
import numpy as np
from tools import utils, valuation_funcs
from tools.xbrl_parser import XBRL
from ipdb import set_trace
parser = argparse.ArgumentParser(description='Optional app description')
parser.add_argument('--ticker', '-t', type=str,
... |
# 1 = path
# 0 = wall
# X = Start
# Y = End
# need to find if there is a path from X to Y
# 1 1 1 0 1 1 1
# 1 X 1 0 1 1 1
# 1 0 1 1 1 0 1
# 1 0 1 1 0 1 1
# 1 1 0 1 1 1 1
# 1 1 1 1 0 Y 1
# 0 0 1 1 0 1 0
# 1 1 1 0
# 0 X 0 1
# 1 1 1 1
# 1 0 1 Y
# 1 X 0
# 0 1 1
# 0 1 Y
# maze=[[1,"X",0],[0,1,1],[0,1,"Y"]]
maze=[[1,1,1,... |
import json
import subprocess
import threading
import time
vms = ['vm-1', 'vm-2', 'vm-3', 'vm-4']
def get_cpu_usage(prev, curr):
prevIdle = prev['idle'] + prev['iowait']
currIdle = curr['idle'] + curr['iowait']
prevActive = prev['user'] + prev['nice'] + prev['system'] +\
prev['irq'] + prev['softir... |
# -*- coding: utf-8 -*-
# ! /usr/bin/env python
"""
@author:LiWei
@license:LiWei
@contact:877129310@qq.com
@version:
@var:
@note:
"""
import zmq
import zmq
import time
context = zmq.Context()
server = context.socket(zmq.PUSH)
server.bind("tcp://192.168.3.230:61616")
# server.bind('tcp://192.168.3.230:61616')
count ... |
#!/usr/bin/env python
"""Taken from gdal script 'rgb2pct.py' """
try:
from osgeo import gdal
except ImportError:
import gdal
import sys
import os.path
class RGB:
def __init__(self, bright, green, wet, dst_filename, fformat='GTiff', color_count=256,
pct_filename=None):
self.dst... |
import cobra
import numpy as np
def miFuncion():
model = cobra.io.read_sbml_model("iMM904.xml")
print "Ajustanto modelo segun datos experimentales=============="
value=3.632
model.reactions.get_by_id("EX_etoh_e").upper_bound=value+0.1*value
model.reactions.get_by_id("EX_etoh_e").lower_bound=value-0.1*val... |
import torch
from torch import nn
from torch.nn import functional as F
import numpy as np
class BaseModel(nn.Module):
"""Base model for both Actor and Critic"""
@staticmethod
def fan_in_initializer(layer):
"""Initializer hidden layer weights as described in DDPG paper"""
fan_in = layer.we... |
#!/usr/bin/python3
def text_indentation(text):
if type(text) != str:
raise TypeError("text must be a string")
l = (".", "?", ":")
k = 0
x = [x for x in text.split(" ") if x.strip()]
nbwords = len(x)
for i in range(nbwords):
wordlen = len(x[i])
for c in range(wordlen):
... |
"""
Tests for model_functions.py. The fit_model function or tests that use that function are commented out of the code
because it would take too long to run, because the model gets fitted every time.
"""
import pytest
from tensorflow.keras import Sequential
from src.models.classification_model.conv.conv_model import b... |
#!/usr/bin/python
#\file scatter_markers.py
#\brief certain python script
#\author Akihiko Yamaguchi, info@akihikoy.net
#\version 0.1
#\date Aug.31, 2021
import numpy as np
import matplotlib.pyplot as plt
if __name__=='__main__':
markers= ['.', ',', 'o', 'v', '^', '<', '>', '1', '2', '3', '4', '8', 's', 'p'... |
"""
Python 格式化字符串时尽量使用 .format 方式而不是 %
数字格式化
^, <, > 分别是居中、左对齐、右对齐,后面带宽度, : 号后面带填充的字符,只能是一个字符,不指定则默认是用空格填充。
+ 表示在正数前显示 +,负数前显示 -; (空格)表示在正数前加空格
b、d、o、x 分别是二进制、十进制、八进制、十六进制。
"""
# 保留小数点后两位。但是注意不应该用该方式做四舍五入计算。 >>> 3.15
print('{:.2f}'.format(3.155))
# 如果需要四舍五入 >>> 3.16
def get_int(num):
import decimal
... |
import os
from sklearn.svm import SVC
from sklearn.model_selection import GridSearchCV
from sklearn.metrics import classification_report
from sklearn.preprocessing import StandardScaler
from utils import load_data, define_output_redirecter
import numpy as np
import pickle
DATA_PATH = os.path.join("data", "model")
MODE... |
# coding:utf-8
from SingleLinkList import SingleLinkList
"""
用栈可以解决的问题,就可以使用递归来解决这个问题。 递归在本质上就是一个栈结构
使用递归的时候注意栈溢出的问题。
"""
def print_item_reverse(single_link_list):
if not single_link_list.isEmpty():
print(single_link_list.pop())
print_item_reverse(single_link_list)
if __name__ == '__mai... |
import json
from boto.s3.connection import S3Connection
from boto.s3.key import Key
# create connection to bucket
c = S3Connection('AKIAIQQ36BOSTXH3YEBA','cXNBbLttQnB9NB3wiEzOWLF13Xw8jKujvoFxmv3L')
# create connection to bucket
b = c.get_bucket('public.tenthtee')
affiliate_links = {}
affiliate... |
import sys
import collections
def get(state, index):
return (state >> (index * 2)) & 3
def set(state, index, value):
return (state & ~(3<< (index * 2))) | (value << (index * 2))
def inc(n):
if n > 0 :
return n + 1
elif n < 0:
return n - 1
else:
return 0
def set_list(state... |
import logging
from django.views import generic as generic_views
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from unavis import models
from unavis import forms
logger = logging.getLogger('django.forms')
class CategoryList(generic_views.ListView):
model = models.Cate... |
#1
#v 0.001
_LOG = []
# ''.join( []+[] ) is much faster than ''+''
# (believe me, I've tried it already)
def LOG(Message): global _LOG; _LOG+=['\n',Message]
def LABEL(Name): global _LOG; _LOG+=[Name]
def WRITE_LOG(mode): #write/append the log data once per import/export
global _LOG
if not mode:... |
import os
import telegram_api
from time import sleep
from binance.client import Client
from binance.exceptions import BinanceAPIException, BinanceOrderException
from binance.websockets import BinanceSocketManager
from twisted.internet import reactor
RES_LEVEL_1 = 38
RES_LEVEL_2 = 38.5
BELOW_RES_LEVEL_1 = 0
BETWEEN_R... |
import asyncio
from pyppeteer import launch
from pprint import pprint
import json
import sys
sys.path.append("../")
from color_output import hprint
import urllib.request
async def main():
browser = await launch()
page = await browser.newPage()
opts = {
# https://miyakogi.github.io/pyppeteer/referen... |
import json
import urllib2
import re
import logging
from contextlib import closing
from private import api_keys
from programs import Program
from programs import promoteProgram
# TODO:
# - need some description on display for minute contdown
# - need better display values for NaN, inf, and zero (asterisk!)
# -... |
from selene.api import s, by, be
from selenium.webdriver.common.keys import Keys
from lib.global_.helper.h_methods import set_select_option
from lib.sales.selectors.s_sales import SelectorsSales, Configured
from lib.sales.test_data.td_sales_core import DEFAULT_CLIENT_NAME
class SalesHelper(Configured):
def __in... |
import json
import http.client
from configparser import ConfigParser
import os
def pytest_generate_tests(metafunc):
funcarglist = metafunc.cls.params[metafunc.function.__name__]
argnames = list(funcarglist[0])
metafunc.parametrize(argnames, [[funcargs[name] for name in argnames] for funcargs in funcarglis... |
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import pandas as pd
import numpy as np
import tushare as ts
from time import sleep
import os
pro = ts.pro_api('7d1f3465439683e262b5b06a8aaefa886ea48aafe2cda73c130beb97')
#df = pro.trade_cal(exchange='', start_date='20180101', end_date='20181231')
#data = pro.stock_basic... |
import sqlite3, time, random, re
class Rechner:
def diff():
# Funktion zum Ableiten von Polynomen
print("\nEs müssen Grad des Polynoms und die Koeffizienten " +
"in absteigender Reihenfolge eingegeben werden.\n")
max_exp = int(input("Grad des Polynoms: "))
... |
#!/usr/bin/env python
# SPDX-License-Identifier: GPL-2.0+
#
# This determines how many parallel tasks "make" is expecting, as it is
# not exposed via an special variables, reserves them all, runs a subprocess
# with PARALLELISM environment variable set, and releases the jobs back again.
#
# https://www.gnu.org/software... |
from mmfunc import mmfunc
from
|
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-8, 5, 400)
a = 4
b = 9
c = -20
y = a * x * x + b * x + c
ydev = 2 * a * x + b
fig = plt.figure()
fig.subplots_adjust(hspace=.5)
ax1 = fig.add_subplot(111)
ax1.plot(x, y, x, ydev)
ax1.set(title=f"y = {a}x^2 + {b}x + {c}")
plt.grid(True)
plt.axhline(y... |
from django.shortcuts import render
from .models import Menu
def index(request):
full_url = request.path
menu_list = Menu.objects.all()
if full_url == "/":
full_url = "/%s" % menu_list[1].name.lower()
list = full_url.split('/')
active_menu = list[1]
act_menu = menu_list.get(name=active... |
import ast
from typing import Any, Union
from enums import ErrorCode
from errors import SemanticError
from nodes import Compound, Declaration, DupaCall
from symbols import ScopedSymbolTable, ProcedureSymbol, VarSymbol
class SemanticAnalyzer(ast.NodeVisitor):
def __init__(self):
self.current_scope: Union[... |
"""Advent of Code Day 24 - Immune System Simulator 20XX"""
import copy
import re
def build_groups(armies):
"""Parse armies into seperate groups with side flag and return groups."""
groups = []
unit_regex = re.compile(r'(\d+).*?(\d+).*?(\d+)\s(\w+).*?(\d+)')
modifier_regex = re.compile(r'\((.*)\)')
... |
"""
数据库操作, 暂时只支持MySQL,
需要再环境变量中配置DB_URI=mysql://root:password@localhost:3306/test
"""
import os
import re
import cx_Oracle
def parse_db_uri(db_uri):
"""从db_uri中解析出数据host,port,db,user,password等信息,返回字典格式的数据库配置"""
try:
db_type, user, password, host, port, db = re.split(r'://|:|@|/', db_uri)
except Val... |
import numpy as np
# import random
from .minimax import *
from .state import *
from .constants import *
import pygame
import sys
import math
turn_count = 0
def create_board():
b = np.zeros((NUM_OF_ROWS, NUM_OF_COLS))
return b
def draw_board():
for r in range(NUM_OF_ROWS):
for c in range(NUM_OF_COLS):
pygame... |
from enum import Enum
from random import choice
class Monsters(Enum):
"""
id level life damage defence rarity, drop item / gold,is boss, picture
"""
kaaul = 0, 85, 40000, (2000, 2000), (70, 40), 1, (
100,
(100, 70000)), True, "https://cdn.discordapp.com/attachments/340501145661341... |
peso = float(input("Digite seu peso: "))
altura = float(input("Digite sua altura: "))
altura_2 = altura * altura
imc = peso/altura_2
if imc <= 18.5:
print("Você esta abaixo do peso com um IMC de:", imc)
elif imc >= 25:
print("Você esta acima do peso comum IMC de:", imc)
else:
print("Seu peso esta... |
import apoNN.src.data as apoData
import apoNN.src.utils as apoUtils
import apoNN.src.vectors as vectors
import apoNN.src.fitters as fitters
import apoNN.src.evaluators as evaluators
import apoNN.src.occam as occam_utils
import numpy as np
import random
import pathlib
import pickle
from ppca import PPCA
import apogee.to... |
"""banking URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.1/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')
Class-based... |
w, h, n = map( int, input().split())
l = 0
r = w
d = 0
u = h
for _ in range(n):
x, y, a = map( int, input().split())
if a == 1:
l = max(l,x)
elif a == 2:
r = min(r,x)
elif a == 3:
d = max(d,y)
else:
u = min(u,y)
if r-l <= 0 or u-d <= 0:
print(0)
else:
print(ma... |
import os
# funkcja identyczna jak w pliku main.py. Zamienia plik na liste krotek
def zamien(plik):
przedzialy = []
for linia in plik:
a = linia.split('|')[0]
b = linia.split('|')[1]
litera = linia.split('|')[2]
a = a.replace(',', '.').replace(' ', '').replace('[', '').replace('... |
#-*- coding:utf-8 -*-
import unittest
from cyac import AC
import sys
class TestAC(unittest.TestCase):
def test_init(self):
ac = AC.build([u'我', u'我是', u'是中'])
arr = [(end_, val) for val, start_, end_ in ac.match(u"我是中国人")]
self.assertEqual(arr, [(1, 0), (2, 1), (3, 2)])
def test_sep(s... |
import os
import numpy as np
import math
from scipy.optimize import curve_fit
def phase_correction(i, v, cyc):
v_shifted = np.zeros(v.size, dtype=np.complex128)
i_shifted = np.zeros(v.size, dtype=np.complex128)
index = cyc
N = len(v)
i_phase_reference = 0
phase_correction = i_phase_reference -... |
from dog.app import create_app
from flask_mail import Mail
app = create_app('dev')
|
import sys
import os
import string
import binascii
from struct import pack
from typing import Optional
from Crypto.Random import get_random_bytes
from Crypto.Cipher import AES
from Crypto.Hash import SHA256, HMAC
from Crypto.Util.Padding import pad, unpad
from Crypto.Signature import pss
from Crypto.PublicKe... |
print(sum(num for num in range(1, 1000) if num%3==0 or num%5==0))
|
from gpiozero import Button
from signal import pause
def PressedKeyStart():
print("Start")
def PressedKeyStop():
print("Stop")
def PressedKeySelect():
print("Select")
def PressedKeyStepOver():
print("StepOver")
def PressedKeyStepInto():
print("StepInto")
def PressedKeyStepOut():
print("StepOut"... |
import os
from importlib import import_module
import yaml
def main(component_name, workflow_name):
component = import_module("kubeflow.kubeflow.cd.%s" % component_name)
WORKFLOW_NAME = os.getenv("WORKFLOW_NAME", workflow_name)
WORKFLOW_NAMESPACE = os.getenv("WORKFLOW_NAMESPACE", "kubeflow-user")
pri... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jun 2 11:32:08 2021
@author: georgengin
"""
import numpy as np
import os
import tensorflow as tf
from tensorflow.keras import layers
from tensorflow.keras import losses
from tensorflow.keras import optimizers
from tensorflow.keras import metrics
from ... |
from flask import Flask, request, redirect, render_template
import cgi
import os
import jinja2
template_dir = os.path.join(os.path.dirname(__file__), 'templates')
jinja_env = jinja2.Environment(loader = jinja2.FileSystemLoader(template_dir), autoescape=True)
app = Flask(__name__)
app.config['DEBUG'] = True
@... |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
def load_file(path):
print("Loading " + path)
return pd.read_csv(path, header=None, delimiter=";").values
constant32 = load_file("constant32.csv")
constant64 = load_file("constant64.csv")
plt.plot(constant32[:, 1], constant32[:, 2], lab... |
placeValue = float(input('Enter the place value: '))
clientSalary = float(input('Enter the client salary: '))
yearToPay = float(input('Enter number of year of payment: '))
valuePayToMonth = placeValue / yearToPay * 12
minimValue = clientSalary * 30 / 100
if valuePayToMonth > minimValue :
print('Cannot take money.'... |
# -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html
import pymysql
class WangyiproPipeline:
def __init__(self):
pass
def process_item(self, item, spider):
... |
from flask import Flask
app = Flask(__name__)
POSTGRES = {
'user': 'helloNamesAdmin',
'pw': 'hellonames',
'db': 'helloNamesAdmin',
'host': 'hellonames.c9xzd6caea05.us-east-1.rds.amazonaws.com',
'port': '5432',
}
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://%(user)s:\
%(pw)s@%(host)s:%(po... |
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def deleteDuplicates(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
temphead = head
temp = set()
if head:... |
#ex004.py: 使用writelines()写文件
f1=open('hello1.txt','w+')
f2=open('hello2.txt','w+')
str='hello world!\nhello China!\n'
context=['hello world!\n','hello China!\n']
f1.writelines(context)
f2.write(str)
f1.close()
f2.close()
|
from concurrent.futures.thread import ThreadPoolExecutor
from flask_sqlalchemy import SQLAlchemy
from redis import Redis
from flask_pymongo import PyMongo
db = SQLAlchemy(session_options={"autoflush": False})
redis_test2 = None # Redis
mongo = PyMongo()
executor = ThreadPoolExecutor(max_workers=10)
appium_drivers =... |
import torch
from DatasetManager.piano.piano_helper import MaestroIteratorGenerator, PianoIteratorGenerator
from DatasetManager.piano.piano_midi_dataset import PianoMidiDataset
from BFT.dataloaders.dataloader import DataloaderGenerator
class PianoDataloaderGenerator(DataloaderGenerator):
def __init__(self,
... |
from collections import deque
N = int( input())
P = [0]*N
H = [0]*N
E = [[] for _ in range(N)]
for i in range(1,N):
P[i], H[i] = map( int, input().split())
E[P[i]].append(i)
d = deque()
for t in E[0]:
d.append((t, H[t]))
MV = [0]*N
e = []
while d:
s, h = d.popleft()
MV[s] = h
for t in E[s]:
... |
import numpy as np
from scipy import sparse
from program_synthesis.label_aggregator import LabelAggregator
def odds_to_prob(l):
"""
This is the inverse logit function logit^{-1}:
l = \log\frac{p}{1-p}
\exp(l) = \frac{p}{1-p}
p = \frac{\exp(l)}{1 + \exp(l)}
"""
return np.exp(l) / (1.0 + ... |
from django.contrib import admin
from django.urls import path
from django.conf.urls import url
from app import views
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [
path('admin/', admin.site.urls),
url('^$',views.index,name='homepage'),
url('predictImage',views.p... |
from ner import NER
from helper_functions import get_restaurant_review_path
import json
import math
from textblob import TextBlob
from nltk.tokenize import sent_tokenize, word_tokenize
# import ssl
# try:
# _create_unverified_https_context = ssl._create_unverified_context
# except AttributeError:
# pass
# else... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import homie
import subprocess
import time
import datetime
import pytz
from astral import Location
import logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s %(message)s')
logger = logging.getLogger(__name__)
from modules.homiedevice import HomieDevice
fr... |
import sys
import json
# loading dictionary
dict_full = []
dict_10k = []
dict_20k = []
with open('comprehensive.json') as file:
dict_full = json.load(file)
with open('top-10000.json') as file:
dict_10k = json.load(file)
with open('top-20000.json') as file:
dict_20k = json.load(file)
def count_letters(word):
... |
class Solution(object):
def repeatedStringMatch(self, A, B):
"""
:type A: str
:type B: str
:rtype: int
"""
new_a = ""
cnt = 0
while(len(new_a) < len(B)):
new_a += A
cnt += 1
if new_a.find(B) != -1:
return cnt... |
H, W = map( int, input().split())
P = [ input() for _ in range(H)]
print('#'*(W+2))
for i in range(H):
print('#'+P[i]+'#')
print('#'*(W+2))
|
import itertools
import os
import random
### for ssl ###implement later###
##import base64
##import hashlib
##from Crypto import Random
##from Crypto.Cipher import AES
################################
def HexCodeInteger(INT,
HexCodes=2,
Swap=True):
val = hex(INT)[2:]
... |
#!/bin/python3
for T in range(int(input().strip())):
charlist = [ord(char) for char in input().strip()]
charlist_reversed = list(reversed(charlist))
for i in range(1, len(charlist)):
if abs(charlist[i] - charlist[i-1]) != abs(charlist_reversed[i] - charlist_reversed[i-1]):
break
els... |
# @Title: 二叉搜索树中的众数 (Find Mode in Binary Search Tree)
# @Author: 2464512446@qq.com
# @Date: 2020-09-24 15:39:57
# @Runtime: 60 ms
# @Memory: 17.2 MB
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# список списков слов женского рода в формате:
# (
# ( # единственное число
# 0. именительный,
# 1. родительный,
# 2. дательный,
# 3. винительный,
# 4. творительный,
# 5. предложный,
# ),
# ( # множественное числ... |
from onegov.election_day import _
from onegov.form import Form
from onegov.form.fields import MultiCheckboxField
from wtforms.fields import DateField
from wtforms.fields import StringField
class ArchiveSearchForm(Form):
term = StringField(
label=_("Term"),
render_kw={'size': 4, 'clear': False},
... |
# -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# https://docs.scrapy.org/en/latest/topics/items.html
import scrapy
class ArticleItem(scrapy.Item):
article_id = scrapy.Field()
title = scrapy.Field()
tag = scrapy.Field()
website = scrapy.Field()
u... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Dec 11 13:36:12 2018
@author: zhihuan
"""
import numpy as np
from sklearn.preprocessing import scale
def preprocessing(data, series = 6, gap = 6):
Y = data[['IS_VENT', 'IS_VENT_P_F_ratio_target']]
X = data.drop(['FIO2','PO2','PCO2','P_F_ratio',... |
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
import os
from dotenv import load_dotenv
load_dotenv()
DB_CONNECTION=os.getenv("DATABASE")
engine = create_engine(
DB_CONNECTION
)
SessionLocal = sessionmaker(autocommit=False, aut... |
import os
import logging
import importlib
logger = logging.getLogger(__name__)
class Compute:
"""
A Compute object is used by invokers and other components to access
underlying compute backend without exposing the implementation details.
"""
def __init__(self, compute_config):
self.log_l... |
munja = 65 #44032
for y in range(1, 10) :
for x in range(y) :
print(chr(munja), end = '')
munja += 1
print() |
# Generated by Django 2.2.4 on 2019-08-23 20:32
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import phonenumber_field.modelfields
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(sett... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.