text stringlengths 8 6.05M |
|---|
import os, lfc, sys, commands
from testClass import _test
global testHome
class test_setcomment_ok(_test):
def info(self):
return "Set file comment existing file name"
def prepare(self):
guid = commands.getoutput('uuidgen').split('/n')[0]
self.name = "/grid/dteam/python_setcomment_tes... |
"""Users are of CustomUser type. Models include all user profile and bio
info as well as user Role and currency tracking/transacting.
Login/Authorization information available here as well"""
import datetime
import os
from django.conf import settings
from django.contrib.auth.models import (
BaseUserManager, Abstra... |
#!/usr/bin/env /data/mta/Script/Python3.8/envs/ska3-shiny/bin/python
#################################################################################################
# #
# extract_hrma_focus_data.py: extract data a... |
"""
My solution: works but times out when submitted :(
"""
class Solution:
def fourSumCount(self, nums1: List[int], nums2: List[int], nums3: List[int], nums4: List[int]) -> int:
n = len(nums1)
a, b, c = set(), set(), set()
for i in range(n):
for j in range(n):
... |
from django.shortcuts import render,redirect,HttpResponse
from time import gmtime, strftime
import random
def index(request):
if 'your' not in request.session:
request.session['your']=0
request.session["activity"]=[]
return render(request,"index.html")
def colgold(request):
time=strftime(... |
"""Support for lienci Gateways."""
""" version 0.3 """
import socket
import json
import time
from collections import defaultdict
from threading import Thread
import logging
import voluptuous as vol
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers import discovery
from homeassistant.helpe... |
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
file_name = 'ieee_30'
pmu = [9, 12, 25]
n = 7
df_length = 30
# test_buses = [1, 1, 1, 1]
test_buses = []
for i in range(n):
test_buses.append(i + 1)
print(test_buses)
def create_test_buses(n, test_buses, pmu, df):
for k in range(n... |
from django.db import models
try:
from django.urls import reverse
except ImportError:
from django.core.urlresolvers import reverse
class Budget(models.Model):
"""
Represents a Budgets in the system
"""
amount = models.DecimalField('Amount (NET)', max_digits=11, decimal_places=2)
year =... |
string=input()
print(string+'.')
|
import re
from nltk.stem import PorterStemmer
import spacy
spacy_nlp = spacy.load('en_core_web_sm')
def findIntersection(lst1, lst2):
ps = PorterStemmer()
#print("lst1",lst1)
#print("lst2",lst2)
lst3 = [value for value in lst1 if ps.stem(value.lower()) in lst2]
#print(lst3)
return lst3
def f... |
# -*- coding: utf-8 -*-
import cserial
import camabio
import time, codecs, logging
import inject
from threading import Semaphore
import model
from model.config import Config
"""
Reader nulo
usado cuando se desactiva el reader en la config
"""
class Reader:
def start(self):
logging.debug('Read... |
#!/usr/bin/env python
# Standard Imports
import sys
from pprint import pprint
# Object Loader
sys.path.insert(0,'../WebScrapper')
from obj_loader import read_armor_files
# Cassandra Driver
import cassandraDriver as db
KEYSPACE = 'testkeyspace'
def main():
print("Connecting to Cassandra")
db.connect()
pri... |
from puddles.puddles import *
|
import os
os.sys.path.insert(0, os.path.abspath('..\settings_folder'))
import settings
from utils import *
import msgs
import pandas as pd
import numpy
import matplotlib.pyplot as plt
def filter(data, key, value):
result = {}
res_index = []
ctr = 0
for el_val in data[key]:
if el_val == value:
... |
# Generated by Django 2.1 on 2018-10-02 13:41
from django.db import migrations, models
import tinymce.models
class Migration(migrations.Migration):
dependencies = [
('mainapp', '0029_auto_20181002_1315'),
]
operations = [
migrations.AddField(
model_name='organization',
... |
#!/usr/bin/env python
#
# Copyright (c) 2019 Opticks Team. All Rights Reserved.
#
# This file is part of Opticks
# (see https://bitbucket.org/simoncblyth/opticks).
#
# 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... |
from flask import Flask, render_template, request, redirect, url_for, session
from flask_mysqldb import MySQL
import MySQLdb.cursors
import re
db = MySQL()
def createApp():
app = Flask(__name__)
app.config['SECRET_KEY'] = 'thisisaverysecurekeylmaoplsdontstealthisthx'
app.config['MYSQL_HOST'] = 'localhost... |
from user_registration import UserRegistration
from user_registration_input import UserRegistrationInput
obj_user_input = UserRegistrationInput()
obj_user_check = UserRegistration()
if __name__ == '__main__':
first_name = input("Enter your first name:")
obj_user_input.set_first_name_input(first_name)
... |
"""
This example demonstrates how to upload a video.
"""
import pyyoutube.models as mds
from pyyoutube import Client
from pyyoutube.media import Media
# Access token with scope:
# https://www.googleapis.com/auth/youtube.upload
# https://www.googleapis.com/auth/youtube
# https://www.googleapis.com/auth/youtube.for... |
import random
import smtplib
import datetime
import imghdr
import email.message
# Mailing List
# Credentials
my_email = "{Enter E-Mail}"
password = "{Enter Password}"
# Creating current date object
current_date = datetime.datetime.now()
# Initializing connection and starting TLS
connection = smtplib.SMTP("smtp.... |
import random
import time
class Formula:
def __init__(self):
self.n = [0.5492, 0.5492, 0.5719, 0.5694, 0.5675, 0.5569, 0.5552, 0.5447, 0.5380, 0.5361, 0.5295, 0.5288, 0.5281, 0.5245, 0.5238, 0.5215]
self.h1 = [8.45,8.64, 9.52, 10.67, 11.82, 13.98, 17.82, 24.25, 28.56, 32.64, 37.76, 41.64... |
# -*- coding: utf-8 -*-
# @Time : 2019/12/26 11:44
# @Author : Jeff Wang
# @Email : jeffwang987@163.com OR wangxiaofeng2020@ia.ac.cn
# @Software: PyCharm
import cv2
import numpy as np
import matplotlib.pyplot as plt
img = cv2.imread('./picture/wave.png')
"""本文档学习了图像识别基础,主要包含:
0. 模式和模式类(基础知识... |
str_no_string = 0
str_empty_string = 1
str_yes = 2
str_no = 3
str_blank_string = 4
str_error_string = 5
str_noone = 6
str_s0 = 7
str_blank_s1 = 8
str_reg1 = 9
str_s50_comma_s51 = 10
str_s50_and_s51 = 11
str_s52_comma_s51 = 12
str_s52_and_s51 = 13
str_s5_s_party = 14
str_given_by_s1_at_s2 = 15
str_given_by_s1_in_wildern... |
from django.urls import path
from . import views
urlpatterns = [
path('', views.PostView.as_view(), name='post'),
path('<int:pk>', views.PostDetailView.as_view(), name='post'),
path('like/<int:pk>', views.TooglePostLikeView.as_view(), name='post_like'),
]
|
import requests as rq
from bs4 import BeautifulSoup
crtfc_key = '25320e73e479a8e8b9dcfa7a5a76faf0233652b5'
corp_code = '00126380' # 고유번호(주식코드 불가)
bsns_year = '2015'
reprt_code = '11011'
# dart_url = 'https://opendart.fss.or.kr/api/alotMatter.xml?crtfc_key='+crtfc_key+'&corp_code='+corp_code+'&bsns_year='+bsns_year+'&r... |
import sys, os, platform
#This function is used to print runtime process and error messages to console and log file
#If the testcase is run on linux, it will only print the runtime process to console and will not create any log files
class Logger(object):
def __init__(self):
self.terminal = sys.stdout
filename =... |
#!/usr/bin/env pybricks-micropython
from pybricks.hubs import EV3Brick
from pybricks.ev3devices import ColorSensor
from pybricks.parameters import Port
import time
from sys import stderr
ev3 = EV3Brick()
colourLeft = ColorSensor(Port.S2)
def RLI_testing2():
x=0
start_time = time.time()
while time.time() < s... |
import pytest
from django.contrib.auth.models import User
def test_new_user(create_user):
user = create_user
print(User.objects.count()) # 1
print(user.username) # django
assert True
|
def calculate(a, o, b):
if(o == "+"):
return a + b
if(o == "-"):
return a - b
if(o == "/" and b != 0):
return a / b
if(o == "*"):
return a * b
'''
Debug a function called calculate that takes 3 values.
The first and third values are numbers. The second value is a charac... |
from Cookie import SimpleCookie
from cgi import parse_qs, escape
import os
import sys
import base64
import traceback
import ConfigParser
from datetime import datetime
from BaseHTTPServer import HTTPServer
import json
parDir = os.path.abspath(os.path.join(os.path.dirname(__file__),".."))
sys.path.append(p... |
#Trivial solution plus some memoization... still too slow
def findmin(s,A):
n=len(A)
B=[]
for i in range(len(A)):
B.append(A[i])
for l in range(1,n+1):
for i in range(len(B)):
if B[i] >= s:
return l
B.pop()
for i in range(len(B)):
... |
#!/urs/bin/env python3
import sys
import re
import io
import unittest
from unittest.mock import patch
try:
from count_well_duplicates import output_writer, TALLY, LENGTH
except:
#If this fails, you is probably running the tests wrongly
print("****",
"You want to run these tests from the top-leve... |
#!/usr/bin/env python3
# coding: utf-8
#--------------------------------------------------------------------------------------------------------------------------------------------
# Reading the Bank Dataset
print('Reading the Bank Dataset...')
# importing pandas for reading the datasets
print('Importing pandas for re... |
# #*********************************************************************
# content = Utility for reading and writing json files
# version = 0.1.0
# date = 2017-09-30
#
# license = MIT
# copyright = Copyright 2017 Thomas Moore
# author = Thomas Moore <moore.thomasj@gmail.com>
# #***************************... |
def rand5_recursive():
roll = rand7()
return roll if roll <= 5 else rand5_recursive()
#O(infinity)
def rand5():
result = 7 # arbitrarily large
while result > 5:
result = rand7()
return result
|
#!/usr/bin/env python
import sys
import pandas as pd
import argparse
import math
from os.path import basename
from scipy.stats import spearmanr
DEFAULT_MIN_CORR = 0.5
DEFAULT_ZSCORE = 1.0
def na_spearmanr(a, b):
mask = a.notnull().values & b.notnull().values
rho, p = spearmanr(a[mask], b[mask])
if not is... |
import cv2
import numpy as np
import sys
facePath = "opencv-master/data/haarcascades/haarcascade_frontalface_default.xml"
smilePath = "opencv-master/data/haarcascades/haarcascade_smile.xml"
faceCascade = cv2.CascadeClassifier(facePath)
smileCascade = cv2.CascadeClassifier(smilePath)
eye_cascade = cv2.CascadeClassifier... |
################################################# -*- python -*-
#
# SConstruct makefile for Second Life viewer
# and servers.
#
# To build everything:
#
# scons ARCH=all BTARGET=all DISTCC=yes
#
# For help on options:
#
# scons -h
#
# Originally written by Tom Yedwab, 6/2006.
#
#############################... |
# author: Chengtian Liu
from sqlalchemy import create_engine
import sqlite3
# define database engines
sqlite_engine = create_engine(
'sqlite:///database.db',
echo=True
)
def add_favorite(id, ticker):
conn = sqlite3.connect('StockTracking/database.db')
cursor = conn.cursor()
create_favorite_db =... |
"""
check out my youtube channel
link: https://www.youtube.com/channel/UCjPk9YDheKst1FlAf_KSpyA
"""
import pygame
import os
from Boundary import Boundary
from ray import Ray
from random import randint
os.environ["SDL_VIDEO_CENTERED"]='1'
width, height = 1920, 1080
size = (width, height)
#colors
black = (0, 0, 0)
whit... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import configparser
import pexpect
import os
import csv
import multiprocessing
from multiprocess import Pool, Manager
# from py2neo import Graph, Node
# from py2neo import authenticate
# from toolz import thread_last
from funcy import partial, compose, lmap, re_all, re_test... |
# -*- encoding:utf-8 -*-
# __author__=='Gan'
# Given an array of integers, every element appears three times except for one,
# which appears exactly once. Find that single one.
# Note:
# Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
# 11 / 11 test cases p... |
"""
---------------------------------------------------------------------------
pool2.py
09/2018
Kirk Evans, GIS Analyst\Programmer, TetraTech EC @ USDA Forest Service R5/Remote Sensing Lab
3237 Peacekeeper Way, Suite 201
McClellan, CA 95652
kdevans@fs.fed.us
script to: DoPool and supportin... |
from django import forms
from .models import People, Job, Eye
class Edit_employee(forms.ModelForm):
class Meta:
model = People
fields = '__all__'
# fields = ['person_name', 'birthday', 'telephone', 'job', 'eyes']
def is_valid(self):
res = super(Edit_employee, self).is_valid()... |
#!/usr/bin/env python
adc_ngps=1 #to choose between adc and gps testing scrpt
if(adc_ngps==1):
import spqradc
else:
import spqrgps
def main():
if(adc_ngps==1):
adc1 = spqradc.SpqrADC(reset_pin=23, send_rdy_pin=21, port="/dev/ttyUSB1", baudrate=230400)
#buff="a,b,c\n"
#adc1.readBuff2(buff)
#return
if... |
"""
This python script contains the main Flask app.
"""
import tempfile
import yaml
import markdown
from werkzeug.utils import secure_filename
from flask import *
from flask_cors import cross_origin
from rq import Queue
from rq.job import Job
from rq.exceptions import NoSuchJobError
from misc.logger import *
from man... |
#! /usr/bin/python
# -*- coding: iso-8859-1 -*-
class Mapeamento(object):
def __init__(self, origem, destino, listaIncluidos = ['*'], listaExcluidos = []):
self.origem = origem
self.destino = destino
self.listaIncluidos = listaIncluidos
self.listaExcluidos = listaExcluidos |
# -*- coding: utf-8 -*-
"""Tests for view serializers."""
from ..test_view_serializers import (
TestBaseViewFeatureViewSet, TestBaseViewFeatureUpdates)
from .base import NamespaceMixin
class TestViewFeatureViewSet(TestBaseViewFeatureViewSet, NamespaceMixin):
"""Test ViewFeaturesViewSet read operations."""
... |
from .nbconvert import *
def _jupyter_nbextension_paths():
return [
dict(section="notebook", src="static", dest="nbsimplegrader", require="nbsimplegrader/authoring_tools"),
dict(section="tree", src="static", dest="nbsimplegrader", require="nbsimplegrader/tree")
]
|
import marshaltools
prog = marshaltools.ProgramList('Cosmology')
t = prog.table
name = t['name'][1]
print (t)
print (name)
lc = prog.get_lightcurve(name)
|
'''
Usage:
test twoSum_1.py by using pytest
'''
import pytest
import os
import sys
# append parent path
sys.path.append(os.path.pardir)
from twoSum_1 import Solution
from twoSum_1 import Solution2
test_data = [
([2, 7, 11, 15], 13, [0, 2]),
([3, 2, 4], 6, [1, 2])
]
@pytest.mark.parametrize("nums,target,... |
# Copyright 2022 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
import logging
import re
from collections import OrderedDict
from dataclasses import dataclass
from enum import Enum
from pathlib import Path, PurePath
f... |
import hashlib
from cache_backends import get_backend
def get_cache_key(environ):
raw_key = unicode((environ['PATH_INFO'], environ['QUERY_STRING']))
return hashlib.sha1(raw_key).hexdigest()
def cache_middleware(app, backend=None):
cache = get_backend(backend)
def caching_app(environ, start_... |
hungry=input("are you hungry")
if hungry=="yes":
print("eat something")
print("drink water")
print("eat biriyani")
else:
print("dont eat")
|
from math import ceil
print('Loja de tintas\n')
area_a_ser_pintada = float(input('Informe o tamanho em metros quadrados da área a ser pintada: '))
um_litro_pinta = 6
quantidade_de_uma_lata = 18
preco_de_cada_lata = 80.00
quantidade_de_um_galao = 3.6
preco_de_cada_galao = 25.00
litros_necessarios = area_a_ser_pinta... |
with open('input.txt', 'r') as f:
total = 0
s = set()
found = False
while found == False:
for num in f:
total += int(num)
if total in s:
print("found duplicate total")
print(total)
found = True
break
else:
s.add... |
# -*- coding: utf-8 -*-
class Solution:
def fizzBuzz(self, n):
result = []
for i in range(1, n + 1):
if i % 15 == 0:
result.append("FizzBuzz")
elif i % 5 == 0:
result.append("Buzz")
elif i % 3 == 0:
result.append(... |
##########################################################
# #
# General clustering abstract class with specific #
# implementations for k-means, DBSCAN and biclustering #
# (from Cheng and Church's "Biclustering Expression #
# Data") ... |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
#from itertools import zip
from openpyxl import load_workbook
from sklearn.decomposition import PCA
from scipy.stats.stats import pearsonr
from scipy.stats import linregress
#read from excel file
def read_excel(filename):
wb = load_workbook(fi... |
# _*_ coding: utf-8 _*_
# @Time : 2017/8/22 10:55
# @Author : GanZiB
# @Site :
# @File : JieBaDemo.py
# @Software: PyCharm
import jieba
titles = []
titles.append('中印边界纠纷会影响12天后召开的金砖厦门峰会吗?')
titles.append('历史上最著名的三个“女流氓”,连上海皇帝杜月笙都对她敬畏三分')
titles.append('美国海底发现巨大断层,科学家:与日本大地震构造一样,无法预防')
titles.append('带案督办:成... |
'''
高楼扔鸡蛋问题
你面前有一栋从 1 到 N 共 N 层的楼,
然后给你 K 个鸡蛋(K 至少为 1)。
现在确定这栋楼存在楼层 0 <= F <= N,在这层楼将鸡蛋扔下去,
鸡蛋恰好没摔碎(高于 F 的楼层都会碎,低于 F 的楼层都不会碎)。
现在问你,最坏情况下,你至少要扔几次鸡蛋,才能确定这个楼层 F 呢?
'''
def drop_egg(egg_num, building_height):
def dp(k,n):
# 当鸡蛋数 K 为 1 时,显然只能线性扫描所有楼层
if k == 1:
return n
# 当楼层数 N 等于 0 时,显然不需要扔鸡蛋
if n == 0:
... |
import sqlite3
from datetime import date
import page
import bcolor
def markAnswer(conn, curr, aid):
'''
Mark the selected answer post as accepted and update it into the database.
Prompts the user whether to overwrite if an accepted answer already exists.
inputs:
conn -- sqlite3.Connection
... |
import curses
import os
import subprocess
from curses.textpad import Textbox, rectangle
from time import sleep
def get_command(stdscr, win):
win.border()
win.overlay(stdscr)
k = ">"
win.addch(1, 1, k)
col = 2
row = 1
command = ""
MAX_ROW = win.getmaxyx()[0] - 2
MAX_COL = win.getmaxy... |
#-*-coding: utf-8-*-
from tkinter import *
from json import loads
with open("atoms.json", "r") as f:
ATOMS = loads(f.read())
with open("symbols.json", "r") as f:
SYMBOLS = loads(f.read())
def convert(element):
if element in SYMBOLS:
return SYMBOLS[element]
return "-*-*-*-*-"
def calculate(element1, element2, s... |
from configparser import ConfigParser
parser = ConfigParser()
CONF='/home/pi/Desktop/inserttest-master/inserttest.config'
parser.read(CONF)
print("PSNERGY BREAK TEST")
print("PSNERGY INSERT TESTING")
##print("Select the default insert size")
##print("1. 5 inches")
##print("2. 5.5 inches")
##print("3. 7 inches")
prin... |
# Copyright 2021 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
import pytest
from pants.backend.docker.utils import format_rename_suggestion, suggest_renames
@pytest.mark.parametrize(
"tentative_paths, actual... |
# Copyright (c) 2017 UFCG-LSD.
#
# 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,... |
import sys
sys.path.append("../logorec")
from app import App
import unittest
class AppTestSuite(unittest.TestCase):
"""
Test suite for the main app.
"""
def setUp(self):
"""
Set up componenets for each test.
:return: nothing
"""
self.app = App()
self.... |
from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.core.files.storage import FileSystemStorage
from django.views.generic import ListView ,CreateView
from django.urls import reverse_lazy
from .forms import UserForm, UserProfileForm
from django.contrib.auth.models import User
f... |
# #!/usr/bin/python
from __future__ import division, print_function
from math import sin, cos, pi
def disc(x):
"""
Returns 'x' rounded to the nearest integer.
"""
return int(round(x))
def to_signed(x, bits):
"""
Returns a signed representation of 'x'.
"""
if x >= 0:
return x... |
# https://stackoverflow.com/questions/64394768/how-calculate-the-area-of-irregular-object-in-an-image-opencv-python-3-8
import cv2
import numpy as np
import math
# input image
path = "/home/pam/Desktop/streamlit_tcc/Mask_RCNN-Multi-Class-Detection/Leaf/test/30.jpg"
# 1 EUR coin diameter in cm
coinDiameter = 2.325
# r... |
n = int(input())
a = input()
eight = 0
for el in a:
if(el == '8'):
eight += 1
ans = min(n//11, eight)
print(ans)
|
# Author: Ziga Trojer, zt0006@student.uni-lj.si
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import random
from sklearn.preprocessing import StandardScaler
from cvxopt import solvers
from cvxopt import matrix
def scale_data(X):
"""
:param X: Input data
:return: Scaled data
"""... |
import param_estimate as pe
import matplotlib.pyplot as plt
import numpy as np
import time
import pickle
filename = 'fitting_data'
save_data_series = [1,2,3]
for j in save_data_series:
pkl_file = open(filename+'_'+str(j)+'.par', 'rb')
SAVE_DATA = None
SAVE_DATA = pickle.load(pkl_file)
pkl_file.close()
fig = pl... |
# _*_ coding:UTF-8_*_
from zhihu import *
if __name__ == '__main__':
GoDownloadPage().startCrawl()
print 'done' |
"""
for x in range (10000):
print(f"ループ変数:{x}")
"""
"""
i = input("繰り返し回数>")
count = int(i)
for x in range(count):
print(f"Hello,world{x + 1}")
"""
"""
count = int(input("繰り返し回数>"))
for x in range(count):
print("Hello")
"""
"""
for x in range(5):
print(f"残り{5-x}")
print("終了")
"""
"""
for x in range(5):
... |
import numpy as np
from sklearn import linear_model
X = np.array([[-1, -1], [-2, -1], [1, 1], [2, 1]])
Y = np.array([1, 1, 0, 0])
clf = linear_model.SGDClassifier(max_iter=1000, tol=1e-3)
clf.fit(X, Y)
clf.partial_fit(X, Y)
print(clf.predict(np.array([[-1,-2],[2,2]])))
a = [[1,1], [12,2], [3,4], [5,6]]
b =... |
# I use this for simulating log, currently I only use the file, not the database
import pickle
import os
import os.path
WRITE_LOG_FILE = 'WRITE_LOG' # the write transaction id of WRITE_LOG
# when the write is involked
## Write Log ###################################################
def log_write(server_id,... |
# Generated by Django 2.0.9 on 2018-12-18 20:27
import datetime
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('empresas', '0004_auto_20181218_2002'),
]
operations = [
migrations.CreateModel(
... |
"""Base runtime interface.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import abc
import logging
import os
import shutil
import six
from treadmill import appcfg
from treadmill import exc
from treadmill impor... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# The above encoding declaration is required and the file must be saved as UTF-8
################################################################################
### LISTS
# List indices begin with 0, not 1!
zoo_animals = ["pangolin", "cassowary", "sloth", "dog"];
if len(zoo... |
from typing import Any
from typing import Callable
from typing import cast
from typing import List
from typing import Optional
from typing import Type
from typing import Union
from fastapi_crudrouter.core import CRUDGenerator
from fastapi_crudrouter.core import NOT_FOUND
from fastapi_crudrouter.core._types import DEPE... |
class SLL :
class node:
def __init__(self, element, nextlink = None) :
self.element = element
self.nextnode = nextlink
def __init__(self):
self.head = None
self.size = 0
def __str__(self):
result = " "
pointer = self.head
while point... |
import traceback
import tornado
from tornado.gen import Return
from handlers.api.base import BaseApiHandler
from handlers.provider_wrapper import BaseProviderWrapper
class ViewApiHandler(BaseApiHandler):
def __init__(self, application, request, **kwargs):
super(ViewApiHandler, self).__init__(application, ... |
import torch
from torchvision import transforms
import argparse
from PIL import Image
import pickle
from model import EncoderCNN, DecoderRNN
import numpy as np
import matplotlib.pyplot as plt
from build_vocab import Vocabulary
import io
def load_image(bytes_stream, transform=None):
image =Image.open(io.BytesIO(bytes... |
import json
filename="username.txt"
with open(filename) as file:
username=json.load(file)
print("Welcome back, "+username+"!")
|
# 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
# d... |
num = [2, 5, 9, 2, 1]
num[2] = 3
print(num,'\n')
num.append(7) #adiciona um novo espaço
print(num,'\n')
num.sort() #coloca em ordem
print(num,'\n')
num.sort(reverse=True)
print(num,'\n')
print(f'Essa lista tem {len(num)} elementos.')
num.insert(2, 0) #adiciona o 0 na posição 2 e realoca o resto
print(num,'\n')
nu... |
import numpy as np
from utils import resize, opt
from skimage import morphology
def find_focal_points(image, scope='local', maxima_areas='large', local_maxima_threshold=None, num_points=None):
"""
Finds the 'focal_points' of a model, given a low resolution CAM. Has two modes: a 'local' scope and a 'global' on... |
# -*- coding: utf-8; -*-
import logging
from pubsub import pub
import pygame.display
import pygame.font
import pygame.draw
logger = logging.getLogger("platakart.title")
from platakart.ui import Scene
from platakart.ui import Menu
from platakart.ui import labeled_button
from platakart.ui import WHITE
from platakart.u... |
import os
async def main(args):
if len(args) == 0: print("What you want to test?")
module = __import__("test.{}".format(args[0]))
try:
command = args[0]
print(await getattr(module, command).main(args[1:]))
except Exception as e:
print(e)
print("Failed to run test fi... |
num1 = int(input('Type your first number: '))
num2 = int(input('Type your second number: '))
print(num1*num2) |
def boo():
return "Boo" |
def smallestDifference(arrayOne, arrayTwo):
arrayOne.sort()
arrayTwo.sort()
smallest = float("inf")
currentSum = float("inf")
smallest_array = []
firstIdx = 0
secondIdx = 0
while firstIdx < len(arrayOne) and secondIdx < len(arrayTwo):
firstNum = arrayOne[firstIdx]
second... |
import random
some_list = [random.randint(1, 10) for i in range(10)]
print(some_list)
for k in range(len(some_list)):
if float(some_list[k]) % 2 != 0:
some_list[k] = 0
print(some_list.count(0)) |
from chrombpnet.evaluation.variant_effect_prediction.snp_generator import SNPGenerator
from scipy.spatial.distance import jensenshannon
from tensorflow.keras.utils import get_custom_objects
from tensorflow.keras.models import load_model
import chrombpnet.training.utils.losses as losses
import pandas as pd
import ... |
# Generated by Django 2.1.5 on 2019-01-23 23:27
from django.db import migrations, models
import users.models
class Migration(migrations.Migration):
dependencies = [
('users', '0004_auto_20190122_2039'),
]
operations = [
migrations.AlterField(
model_name='customuser',
... |
name=input("请输入你的姓名")
c=input("请输入你的班级")
number=input("请输入你的学号")
QQ=input("请输入你的QQ")
print(name,c,number,QQ) |
from mmpy_bot.bot import Bot
import re
from mmpy_bot.bot import listen_to
from mmpy_bot.bot import respond_to
import wisdom
import email_sender
@respond_to('$', re.IGNORECASE)
def hi(message):
leave_type = "Casual"
name = message.get_username()
date, leave_type, response = wisdom.text_analyser(message.get_... |
# Copyright 2017 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 or agreed to in writin... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.