text stringlengths 38 1.54M |
|---|
import sys, os
import requests
import urllib
import types
import re
import math
from operator import itemgetter
handle = open("A-large (1).in","r")
allconts = handle.read().split("\n")
handle.close()
T = int(allconts[0])
results = []
for i in range(0,T):
sequence = str(allconts[i+1])
seqlen = len(... |
from pal.writer.printer.printer import PrinterWriter
class NonePrinterWriter(PrinterWriter):
def declare_fieldset_printer(self, outfile, register, fieldset):
pass
def declare_field_printer(self, outfile, register, field):
pass
|
import sys
from PyQt5.QtCore import pyqtSlot
from PyQt5.QtWidgets import QApplication, QDialog
from PyQt5.uic import loadUi
from PyQt5 import QtWidgets, uic, QtCore
from PyQt5.QtGui import QPixmap
from mysql.connector import Error
from datetime import datetime
import mysql.connector
from user_module import CL_userModul... |
#class to list
def salClassToList():
for i in range (0,len(classNo)):
for j in range (0,classlenth)
if classNo[i]==j:
salary.append(minSal+(maxSal-minSal)*(i+1))
|
'''
Longest decreasing subsequence
Given array of ints, find the longest subsequence that has all values in increasing order.
Also return the values themselves.
Examples:
Input: arr[] = [15, 27, 14, 38, 63, 55, 46, 65, 85]
Output: 3
Explanation: The longest decreasing sub sequence is [63, 55, 46]
Input: arr[] = [50,... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
11. タブをスペースに置換
タブ1文字につきスペース1文字に置換せよ.確認にはsedコマンド,trコマンド,もしくはexpandコマンドを用いよ.
"""
import sys
import fileinput
if __name__ == '__main__':
# file = open(sys.argv[1], 'r')
file = fileinput.input("-")
for line in file:
lis = list(line)
# f... |
from uxhub.models import Comment, ChangingComment, User, Milestone, ChangingMilestone, Issue, ChangingIssue
def create_comment_event(pk):
comment = Comment.objects.get(pk=pk)
comment_event = ChangingComment(description=comment.description, issues=comment.issues,
author=comm... |
# coding: utf-8
from __future__ import absolute_import
from bitmovin_api_sdk.common import BaseApi, BitmovinApiLoggerBase
from bitmovin_api_sdk.common.poscheck import poscheck_except
from bitmovin_api_sdk.models.bitmovin_response import BitmovinResponse
from bitmovin_api_sdk.models.mjpeg_video_configuration import Mj... |
from django.db import transaction
from django.db.models.query import QuerySet, ValuesListQuerySet, ValuesQuerySet
from django.db.models.query_utils import deferred_class_factory
from django.db.models.sql import UpdateQuery
from django.db.models.sql.compiler import SQLUpdateCompiler, SQLCompiler
from django.db.models.s... |
"""High-level methods to obtain information about accounts."""
from typing import Any, Dict, Union, cast
from xrpl.clients import Client, XRPLRequestFailureException
from xrpl.models.requests import AccountInfo
from xrpl.models.response import Response
def does_account_exist(address: str, client: Client) -> bool:
... |
#################################################################################
# FOQUS Copyright (c) 2012 - 2023, by the software owners: Oak Ridge Institute
# for Science and Education (ORISE), TRIAD National Security, LLC., Lawrence
# Livermore National Security, LLC., The Regents of the University of
# California... |
# -*- coding: utf-8 -*-
from __future__ import print_function
from collections import namedtuple
import exhibitionist.log
from exhibitionist.providers.IProvider import IProvider
GET_WS_URL_ATTR = "get_ws_url"
logger = exhibitionist.log.getLogger(__name__)
def WSMsg(msg_type,payload=None,**kwds):
# messages fr... |
from django.urls import path
from quiz_app.views.answer import CreateAnswer, UpdateAnswer
from quiz_app.views.question import question, QuestionDetail
from quiz_app.views.index import quiz_index, QuizDetail
app_name = 'quiz'
urlpatterns = [
path('<int:quiz_id>', quiz_index, name='index'),
path('<int:quiz_id>... |
# 迷宫的递归求解
dirs = [(0, 1), (1, 0), (0, -1), (-1, 0)] # 四个方向
def mark(maze, pos): # 给迷宫maze的位置表上pos表示到过了
maze[pos[0][pos[1]]] = 2
def passable(maze, pos):
return maze[pos[0][pos[1]]] == 0
def find_path(maze, pos, end):
mark(maze, pos)
if pos == end:
print('pos:', pos, end=' ')
retu... |
#Thesaurus App
import random
thesaurus = {
"hot" : ['balmy','summery','boiling'],
"cold" :['chilly','cool','frigid'],
"happy":['content','merry','cheery'],
"sad" : ['unhappy','glum','miserable']
}
print("Welcome to the Thesaurus\n\n Choose a word from below and I will give you a synonym.... |
#!/usr/bin/python
## @package bmp183
# Module for handling Bosch BMP183 pressure sensor
import logging
import time
import numpy
import threading
NaN = float('nan')
## Class for Bosch BMP183 pressure and temperature sensor with SPI interface as sold by Adafruit
class bmp183(threading.Thread):
## @var BMP183_RE... |
# -*- coding:utf-8 -*-
# __author__ = 'gupan'
import pickle
def sayhi(name):
print("my name is,", name)
with open("test.txt", "rb") as f_r:
data = pickle.load(f_r)
data["func"](data["name"]) |
#!/usr/bin/python3
"""returns the number of subscribers"""
import json
import requests
def number_of_subscribers(subreddit):
"""returns the number of subscribers"""
url = 'https://www.reddit.com/r/{}/about.json'.format(subreddit)
headers = {
'User-Agent': 'My User Agent 1.0'
}
response =... |
# Copyright 2023 Google LLC.
#
# 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, ... |
from django import forms
class Showdata(forms.Form):
price1 = forms.IntegerField()
price2= forms.IntegerField()
mcost = forms.CharField()
Mileage = forms.CharField()
engine= forms.CharField()
seat_capacity = forms.IntegerField()
# class update_data(forms.Form):
# mname = forms.CharField()
... |
import sys
sys.stdin = open("D4_8822_input.txt", "r")
T = int(input())
for test_case in range(T):
N, X = map(int, input().split())
print("#{} {}".format(test_case + 1, 0 if X == (1 or 2 * N - 1) else 1)) |
#If there are multiple pages on the website we will scrape through all of them and grab the data that we need. We will do this in the script below. In the previous script we grabbed the base page an grabbed the data out of it in this script we ill build intelligence to get the page range dynamically and crawl through... |
#!/usr/bin/python
import argparse
import glob
import os
import re
import shutil
import sys
import MySQLdb
import MySQLdb.cursors
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
PROJECT_PATH = os.path.normpath(os.path.join(BASE_DIR, '..', 'orb_api'))
if PROJECT_PATH not in sys.path:
sys.path.append(PROJECT_... |
#! /usr/bin/env python
import os
import sys
import json
import time
import argparse
import re
from oslo_utils import uuidutils
from subprocess import Popen, PIPE, check_output
from distutils.spawn import find_executable
def parse_list_output(output):
"""Parse the output of list commands (like `openstack project ... |
__author__ = 'Sean'
from TicTacToe import *
from time import time
from tkinter import *
class TTTgui:
def __init__(self, depth = 9):
self.temp = 0
self.game = None
self.player2 = None
self.buttons = [[None for i in range(0,3)] for j in range(0,3)]
self.depth = depth
de... |
"""Logging model and view defined"""
from flask import redirect, url_for, request
from flask_admin.contrib import sqla
from flask_sqlalchemy import SQLAlchemy
from flask_login import current_user
db = SQLAlchemy()
class Logging(db.Model):
"""defines the Logging model with its attributes to log app requests"""... |
# set of nodes with operations
from LinkedListPKG.Node import Node;
class LinkedList(object):
def __init__(self): #method to create a linked list
self.head = None; #make an empty linked list
self.counter = 0; #therefore the counter is set to 0
def remove(self, data):
s... |
import itertools
RANKS = "23456789TJQKA"
SUITS = "hsdc"
SUIT_PAIRS = list(itertools.combinations(SUITS, 2)) |
import logging
import pandas as pd
from tigeropen.common.consts import BarPeriod
from lib.date import date_delta, get_today
from lib.quant import alpha_beta
from tiger.config import get_bars_from_cache, get_quote_client
"""
波动率计算
https://blog.csdn.net/CoderPai/article/details/82868280
beta 计算
https://blog.csdn.net/... |
from contextlib import contextmanager
from typing import Generator, List
from unittest import mock
from prefect.utilities.dockerutils import ImageBuilder
@contextmanager
def capture_builders() -> Generator[List[ImageBuilder], None, None]:
"""Captures any instances of ImageBuilder created while this context is ac... |
"""
Apply tagging process
@author: Praveen Chandar
"""
from ctgov.load_data import load_data
from ctgov.utility.log import strd_logger
from multiprocessing import Process
import ctgov.index.es_index as es_index
from ctgov.concept_mapping.tagger import Tagger
import argparse
import sys
import math
log = strd_... |
#!/usr/bin/env python
import game
import gameio
r = 4 ;
l = 4;
boardsList = game.allocBoard(r, l);
mineBoard = boardsList[0];
statusBoard = boardsList[1];
mineBoard[0][0] = -1;
mineBoard[0][3] = -1;
print("initial board: ")
gameio.displayBoard(mineBoard, statusBoard);
game.uncoverLoc(mineBoard, statusBoard, 2, 2);... |
import time
import datetime
import copy
import numpy as np
class Station:
def __init__(self, name, state):
self.name = name
self.state = {'state': '', 'since': datetime.datetime.now(),
'booked': {
'Alarm': 0.0,
'Producing': 0.0,
... |
#!/usr/bin/python
import rospy
import sys
import struct
import argparse
import time
import numpy
import traceback
from sensor_msgs.msg import Image
from snark.imaging import cv_image
import cv2
import rosbag
help_description='listen to a ros topic for raw image and write it in cv format to stdout'
help_example="""
exa... |
# coding:utf8
"""
传统机器视觉方式寻找文档中的文本区域
"""
import cv2
import numpy as np
def preprocess(gray):
# 1. Sobel算子,x方向求梯度
sobel = cv2.Sobel(gray, cv2.CV_8U, 1, 0, ksize=3)
# 2. 二值化
ret, binary = cv2.threshold(sobel, 0, 255, cv2.THRESH_OTSU + cv2.THRESH_BINARY)
# 3. 膨胀和腐蚀操作的核函数
element1 = cv2.getStruct... |
# from __future__ import unicode_literals
# from django.db import models
# from django.conf import settings
# from django.db.models import ForeignKey
# from django.db.models.fields import (
# AutoField,
# CharField,
# IntegerField,
# DecimalField,
# BinaryField,
# DateTimeField
# )
#
#
#
# class... |
#!/usr/bin/env python
from distutils.core import setup
setup(name='gitli',
version='0.4',
description='Simple issue management for git',
long_description=
'''
gitli is a simple git extension to manage issues in single-developer projects.
The issues are stored in the current branch of the git ... |
from helper_code import find_challenge_files,load_header,load_recording,get_leads
import os
import sys
import numpy as np
import scipy as sp
import scipy.io
from shutil import rmtree
from multiprocessing import Pool
def extract_leads_wfdb_custom(src_path,dst_path,leads):
reduced_leads = leads
num_reduce... |
##############################################################################
# (c) Crown copyright Met Office. All rights reserved.
# For further details please refer to the file COPYRIGHT
# which you should have received as part of this distribution
###################################################################... |
import os
import json
from slack_sdk.webhook import WebhookClient
from flask import make_response
def index(request):
"""Responds to any HTTP request.
Args:
request (flask.Request): HTTP request object.
Returns:
The response text or any set of values that can be turned into a
Respo... |
def Drawsquare(sidelength):
turtle.forward(sidelength)
turtle.left(90)
turtle.forward(sidelength)
turtle.left(90)
turtle.forward(sidelength)
turtle.left(90)
turtle.forward(sidelength)
turtle.left(90)
|
# https://docs.python.org/2.7/library/stdtypes.html#bltin-file-objects - high-level file object returned by open() built-in
# https://docs.python.org/2.7/c-api/file.html - this describes the underlying C API that is used by Python. Not what I want
import os, subprocess
filepath = os.path.join(os.path.dirname(__file... |
# Made By DM
# This script downloads chrome extension crx packages from the store
# Serial Download
from tqdm import tqdm
import requests
from pymongo import MongoClient
from bson import json_util
import time
import json
import zipfile
import os
client = MongoClient('localhost', 27017)
db = client['Chrome-Webstore... |
#!/usr/bin/python
import sys
import os
import time
import logging
from watchdog.events import PatternMatchingEventHandler
from watchdog.observers import Observer
from clint.textui import colored
from datetime import datetime
# get the current time
now = datetime.now()
# the template for initial code
template = """/*
... |
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 12 13:43:57 2020
@author: Souwi
"""
from random import *
from conversion import *
from petalDec import *
from pruning import *
from randomGraphs import *
import pickle
import time
import timeit
def bfs(g, s,d):
dist = {}
toVisit = [s]
seen = ... |
import os
from urllib.request import urlretrieve
import boto3
from sqlalchemy import create_engine
from sqlalchemy.orm import Session
if not os.environ.get('UNIT_TEST', False):
db_host, port = os.environ.get('RDS_ENDPOINT').split(":")
db_user = os.environ.get('DB_USER')
region = os.environ.get('AWS_REGION... |
from scipy.optimize import minimize
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
V = np.matrix('123 37.5 70 30; 37.5 122 72 13.5; 70 72 321 -32; 30 13.5 -32 52')/100 # covariance
R = np.matrix('14; 12; 15; 7')/100 # return
# 风险预算优化
def calculate_portfolio_var(w,V):
# 计算组合风险的函数
w = np... |
'''
Created on Jun 20, 2021
@author: Rand
'''
from tensorflow.keras import optimizers
from tensorflow.keras import models
import random
import copy
import game
import model
# Assigns names for integers to avoid magic numbers
GAME_STATE_X = -1
GAME_STATE_O = 1
GAME_STATE_DRAW = 0
GAME_STATE_NOT_ENDED = 2
PLAYER_X_VAL... |
# AWS Lambda Handler
#
# Use Dockerfile.lambda to package/upload (see the instructions in the Dockerfile)
#
from strategies.base import CEPDistrict,CEPSchool
from cep_estimatory import add_strategies
import os,datetime,json,time
import zipfile
from io import BytesIO
import base64
import sys
import boto3,botocore
#pr... |
# -*- coding: utf-8 -*-
# Created by Hoanglv on 10/25/2019
from odoo import fields, models, api
from datetime import datetime
from dateutil.relativedelta import relativedelta
STATE_SELECTOR = [('active', 'Active'), ('deactive', 'Deactive')]
TYPE_SELECTOR = [('extend', 'Extend'), ('up', 'Up rank'), ('keep', 'Keep ran... |
import sys
import datetime
import math
def prepareResults(outputPath):
count = 0
nperms = 1000
result = ""
with open(outputPath) as infile:
approx_sum = 0
approx_max = 0
approx_min = 100000000 # good value for min approx
for line in infile:
if(count == nperms)... |
# -*- coding=utf-8 -*-
# Author: MrGuan
# CreatData: 2019-08-12 02:23:38
# Make your life a story worth telling
import json
from datetime import datetime
class Block():
"""
接受数据及父区块哈希
"""
def __init__(self, transactions, prev_hash):
"""
:param transactions:交易列表
:param prev_ha... |
#!/usr/bin/env python
# -*- coding:utf-8
"""
Author: Hao Li
Email: howardleeh@gmail.com
Github: https://github.com/SAmmer0
Created: 2018/4/9
"""
from datasource.sqlserver.zyyx.dbengine import zyyx
|
#!/usr/bin/python
import time
import os
from CheckForUSB import CheckForUSB
from DownloadCSVAndMoveIntoPosition import DownloadCSVAndMoveIntoPosition
from UploadData import UploadData
import datetime
# configuration
hibernate_hours = 1
heartbeat_seconds = 5
last_upload = 0
usb_notified = False
while True :
tim... |
"""
ETH DAO Arbitrage
Jon V (May 30th 2016)
"""
import time
from kraken import Kraken
from twilio.rest import TwilioRestClient
PERCENTAGE_RETURN = 1.10 # 10%
DAO_KRAKEN_DEPOSIT_ADDRESS = 'your_address'
ETH_KRAKEN_RETURN_ADDRESS = 'eth_address'
TWILIO_ACCOUNT_SID = "sid"
TWILIO_AUTH_TOKEN = "token"
def calc_DAO2ETH_... |
from tkinter import filedialog
from tkinter import *
import pymysql
import mysql.connector
from tkinter import messagebox
from mysql.connector import Error
from mysql.connector import errorcode
from caresys import *
connection = pymysql.connect(host='localhost',database='vehicle',user='root',password='')
c... |
#!/usr/bin/env python
from __future__ import print_function
import chainer
import chainer.functions as F
import chainer.links as L
class VGG(chainer.Chain):
def __init__(self, class_labels=10):
super(VGG, self).__init__()
with self.init_scope():
self.l1_1 =... |
from bs4 import BeautifulSoup
from datetime import date, datetime
import requests
r =requests.get('https://zerocater.com/m/BYFJ/')
soup = BeautifulSoup(r.text)
def menu_scrape():
d = datetime.isocalendar(date.today())
#this matches the format of zerocator
today_match = str(d).replace(', ','-').replace('('... |
import sys
import xlwt
from xlwt import Workbook
#wb = Workbook()
#outfile = "19122007output"
#sheet = wb.add_sheet(outfile)
print('Python: {}'.format(sys.version))
import pyabf
import numpy as np
import matplotlib.pyplot as plt
filename = r'C:\Users\Elijah\Documents\NanoporeData\abfRaw\filtered_besse... |
# Accepted
# Python 3
import numpy
ar = numpy.array([int(p) for p in input().split()])
arr = numpy.array([int(p) for p in input().split()])
print(numpy.inner(ar, arr))
print(numpy.outer(ar, arr))
|
# -*- coding: UTF-8 -*-
# @Time : 22/03/2019 17:43
# @Author : QYD
from utils import cal_r_max, median_draw_circle, convolution_image
import cv2 as cv
mode = ["wiener", "dia_conv"]
def rotational_deblur(img, theta, center=None, mode=mode[1]):
r_max = cal_r_max(img, center=center)
circle_list =... |
"""
|正则表达式是用来操作字符串的一种逻辑公式
"""
import re
# # eg.1
# s = "webset: http://www.baidu.com"
# reg = "http://[w]{3}\.[a-z0-9]*\.com"
#
# result = re.findall(reg,s)
# print(result)
#
# # eg.2
# s = "hello world hello"
# reg = "hello"
#
# print(re.findall(reg,s))
# print(re.findall(reg,s)[0])
# 元字符
"""
. 代表换行符以外的任意字符 \n
\w... |
from sqlalchemy import join
from datetime import datetime
import re
import time
import buildapi.model.meta as meta
from buildapi.model.reports import Report, IntervalsReport
from buildapi.model.util import get_time_interval, get_silos
from buildapi.model.util import NO_RESULT, SUCCESS, WARNINGS, FAILURE, \
SKIPPED, EX... |
def distance(strand_a, strand_b):
diffrent = 0
if not strand_a and not strand_b:
return 0
if not strand_a:
raise ValueError("The strand_a cannot be empty!")
if not strand_b:
raise ValueError("The strand_b cannot be empty!")
if len(strand_a) != len(strand_b):
rais... |
# Read files
# Using argv to read filename from users
#从sys module导入argv功能
from sys import argv
#利用argvuoqu用户输入它想要打开的文件名
script, filename = argv
# !!! Function: open (). Exp.: open(filename, mode ='r')
# mode = 'r' : open for reading
# mode = 'w' : open for writing, truncating the file first
# mode = '... |
from __future__ import absolute_import
import collections
from django import template
from django.core.urlresolvers import reverse
from django.utils.encoding import force_unicode
from commis.search.forms import SearchForm
from commis.utils.deleted_objects import get_deleted_objects
register = template.Library()
@re... |
## CONSTANT ##
FIN_IDX = 0
RSV_1_IDX = 0
RSV_2_IDX = 0
RSV_3_IDX = 0
OPCODE_IDX = 0
MASK_IDX = 1
PAYLOAD_LEN_IDX = 1
MASK_KEY_IDX = 0
PAYLOAD_IDX = 0
def parse_frame(frame):
## GET ALL FRAME DETAIL
fin = frame[FIN_IDX] >> 7
rsv1 = (frame[RSV_1_IDX] >> 6) & 0x01
rsv2 = (frame[RSV_2_IDX] >> 5) & 0x01
... |
from django.shortcuts import render, get_object_or_404
# Create your views here.
from .models import Specialmoments
def allmoments(request):
moments = Specialmoments.objects
return render(request, 'specialmoments/specialmoments.html', {'moments':moments})
def detail2(request, specialmoments_id):
detailm... |
__author__ = ['sibirrer', 'ajshajib']
import time
import sys
import numpy as np
from lenstronomy.Sampling.Samplers.pso import ParticleSwarmOptimizer
from lenstronomy.Util import sampling_util
import emcee
from schwimmbad import choose_pool
class Sampler(object):
"""
class which executes the different sampli... |
import tensorflow as tf
import numpy as np
import random
import networkx as nx
import scipy.io as sio
import os
import sys
import pickle
import walk
from configs import *
def get_batch(arr, n_seqs, n_steps):
n = int(arr.shape[0]/n_seqs) * n_seqs
nn = int(arr.shape[1]/n_steps) * n_steps
arr = arr[:n, :nn]... |
import ajustador as aju
from ajustador.helpers import save_params
from ajustador import drawing
import measurements1 as ms1
import os
#must be in current working directory for this import to work, else use exec
import params_fitness,fit_commands
# a. simplest approach is to use CAPOOL (vs CASHELL, and CASLAB for spine... |
class GitRepo(object):
def __init__(self, name, http_addr, ssh_addr):
self.name = name
self.http_addr = http_addr
self.ssh_addr = ssh_addr
def __str__(self):
return str(self.name) + '\n' + str(self.http_addr) + '\n' + str(self.ssh_addr)
|
"""Report NEM emissions intensity using NGER data.
Copyright (C) 2017 Ben Elliston <bje@air.net.au>
"""
import sys
import json
import argparse
import urllib2
import datetime
import pandas as pd
import numpy as np
ntndp = {'Broken Hill Gas Turbines': 0.93,
'Eraring Power Station': 0.88,
'Jeeralan... |
import os
# environment variables
TOKEN = os.environ["TOKEN"]
REDIS_URL = os.environ["REDIS_URL"]
DOCKER_PATH_TO_USER_DIR = os.environ["DOCKER_PATH_TO_USER_DIR"]
DOCKER_PATH_TO_QR_CODE = os.environ["DOCKER_PATH_TO_QR_CODE"]
SLACK_WEBHOOK = os.environ["SLACK_WEBHOOK"]
SLACK_CHANNEL = os.environ["SLACK_CHANNEL"]
SLACK_T... |
# encoding: utf-8
# Copyright 2013 maker
# License
"""
Identities Cron jobs
"""
from maker.identities import integration
def cron_integration():
"Run integration"
try:
integration.sync()
except:
pass
|
import numpy as np
from Layers.Base import BaseLayer
class SoftMax(BaseLayer):
# constructor
def __init__(self):
super().__init__()
# store input vector
self.input = None
self.y_pred = None
# initialize weights
self.weights = None
def forward(self, input_... |
"""Este programa simula um robô de serviços, num restaurante com uma mesa de forma, tamanho e posição
aleatórios. Quando o utilizador clica na área da mesa, o robô inicia o serviço para essa mesa,
consistindo numa ida à mesa para receber um pedido, regresso ao balcão para preparar o pedido,
entrega do pedido à mesa,... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Jun 14 15:31:37 2019
@author: daliana
"""
from keras.models import Model
from keras.layers import Input, concatenate, Convolution2D, MaxPooling2D, core, Conv2DTranspose
def Unet (nClasses = 3, input_width = 128 , input_height = 128 , nChannels = 16):
... |
"""Handle Home Assistant requests."""
import logging
import os
from typing import Dict, Optional, Generator
import requests
_LOGGER = logging.getLogger(__name__)
class HomeAssistant:
"""Handle Home Assistant API requests."""
def __init__(self):
"""Initialize Home Assistant API."""
self.url ... |
import tkinter
from tkinter import messagebox
app = tkinter.Tk()
def Display():
messagebox.showinfo("Hi Everone ",message= "Need coffee urgently")
CLICK_BUTTON = tkinter.Button(app, text="HEY I AM A BUTTON", bg="red", command=Display)
CLICK_BUTTON.pack()
app.mainloop()
|
# (C) Copyright 2005-2023 Enthought, Inc., Austin, TX
# All rights reserved.
#
# This software is provided without warranty under the terms of the BSD
# license included in LICENSE.txt and may be redistributed only under
# the conditions described in the aforementioned license. The license
# is also available online at... |
from flask_wtf import FlaskForm
from wtforms import SubmitField, RadioField
from flask_wtf.file import FileField, FileAllowed, FileRequired
class UploadForm(FlaskForm):
upload = FileField('Image', validators=[
FileRequired(),
FileAllowed(['jpg', 'png'], 'Images only!')
])
base = RadioField... |
import os
import glob
import numpy as np
import lsst.afw.image as afwImage
from astropy.io import fits
import matplotlib.pyplot as plt
def blkavg(arr,x1,x2,y1,y2):
arr = arr[x1:x2,y1:y2]
arr = arr.reshape((arr.shape[0], -1, 1))
arr = np.mean(arr, axis=1)
return arr
def createFlat(flist):
te... |
import requests
import time
from io import BytesIO
from PIL import Image
import os
import numpy as np
# 获取验证码的网址
CAPT_URL = "http://jwzx.usc.edu.cn/Core/verify_code.ashx"
# 验证码的保存路径
CAPT_PATH = "capt/"
if not os.path.exists(CAPT_PATH):
os.mkdir(CAPT_PATH)
# 将验证码转为灰度图时用到的"lookup table"
THRESHOLD ... |
import imutils
from imutils import paths
import face_recognition
import pickle
import cv2
import os, sys, inspect
import numpy as np
'''Encoding a new face'''
def new_face(img_path, name):
#check if encoded pickle file exists, otherwise write to new file
if os.path.exists('encodings.pickle'):
data ... |
import os, inspect, glob, time
import numpy as np
PACK_PATH = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))+"/.."
class DataSet(object):
def __init__(self, key_tr):
print("\n** Prepare the Dataset")
self.data_path = os.path.join(PACK_PATH, "dataset")
self.sy... |
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
Tests for C{setup.py}, Twisted's distutils integration file.
"""
from __future__ import division, absolute_import
import os, sys
import twisted
from twisted.trial.unittest import SynchronousTestCase
from twisted.python.filepath... |
from django.shortcuts import render, redirect
from django.contrib import messages
from .models import Contact
from .forms import ContactForm
from cart.models import Order
def refund_request(request):
if request.method == 'POST':
form = ContactForm(request.POST or None)
if form.is_valid():
... |
from selenium import webdriver
from selenium.webdriver.support.ui import Select
link = "http://suninjuly.github.io/selects1.html"
browser = webdriver.Chrome()
browser.get(link)
# находим элементы
num1_in_text = browser.find_element_by_id("num1")
num2_in_text = browser.find_element_by_id("num2")
# вытаскив... |
# http://www.codechef.com/problems/GCD2
# Using Python here isn't cheating right? ;)
def gcd(a, b):
if b == 0:
return a
else:
return gcd(b, a%b)
t = int(raw_input())
while t:
line = raw_input().split()
a = int(line[0])
b = int(line[1])
print gcd(a, b)
t -= 1 |
from setuptools import setup
try:
from jupyterpip import cmdclass
except:
import pip, importlib
pip.main(['install', 'jupyter-pip']); cmdclass = importlib.import_module('jupyterpip').cmdclass
setup(
name='nbjsmol',
packages=['nbjsmol'],
# ... more setup.py stuff here ...
install_requires=[... |
import warnings
from copy import deepcopy
from dataclasses import make_dataclass, field
from typing import Type, Dict, List, Tuple, TypeVar, NewType, Union
import pydantic
from pydantic import BaseModel, create_model, root_validator, BaseConfig
from pydantic.dataclasses import dataclass as pydantic_dataclass
from sqla... |
import setuptools
name = "bdendro"
variables = {}
with open("{}/version.py".format(name), mode="r") as f:
exec(f.read(), variables)
version = variables["__version__"]
setuptools.setup(
name=name,
version=version,
packages=setuptools.find_packages(),
python_requires=">= 3.6",
install_requires... |
import random as rnd
import math as ma
from scipy import stats
m = 10000
aleatorios = []
for i in range(m):
aleatorios.append(rnd.random())
subcadenas = []
for i in range(0,m-1):
if aleatorios[i] < aleatorios[i+1]:
subcadenas.append('+')
else:
subcadenas.append('-')
#pri... |
# -*- coding: utf-8 -*-
import sys,math
a=open(sys.argv[1]).read()
b=open(sys.argv[2], 'w')
alp=' აბგდევზთიკლმნოპჟრსტუფქღყშჩცძწჭხჯჰ'
singles={}
couples={}
for x in alp:
singles[x]=0
for y in alp:
couples[x+y]=0
for x in range(len(a)-1):
singles[a[x]]+=1/len(a)
couples[a[x:x+2]]+=1/(len(a)-1)
s... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.7 on 2017-12-02 22:40
from __future__ import unicode_literals
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.Crea... |
from chem21repo.api_clients import C21RESTRequests, RESTError
from chem21repo.drupal import drupal_node_factory
from chem21repo.repo.models import UniqueFile, Question
from django.core.management.base import BaseCommand
import os
class Command(BaseCommand):
help = 'Download all drupal files'
de... |
import time
def validarNumero():
objetivo = None
while objetivo == None:
objetivo_string = input('Ingresa un número que quieras saber su raíz cuadrada: ')
if(objetivo_string.isdigit()):
objetivo = int(objetivo_string)
return objetivo
else: print('ERROR: Ingresa... |
def read_csv(path_to_csv_file, delimiter=","):
try:
with open(path_to_csv_file) as inp:
new_file = []
for line in inp:
line = line.strip()
new_line = [i for i in line.split(delimiter)]
if '"' in line:
word = ... |
#!/usr/bin/env python
'''
$: line break
*: paragraph break
'''
import os, sys, string, re, json
grade_1 = [1401, 1603, 1903, 1505, 1804, 1807, 1502, 1703, 2001, '0000']
grade_2 = [350, 2203, 2401, 330, 2201, 2202, 310, 2102, 2302]
grade_3 = [420, 2403, 2701, 320, 450, 2503, 410, 2101, 2504]
grade_4 = [520, 2402, 290... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.