text
stringlengths
8
6.05M
import yfinance as yf import streamlit as st import pandas as pd from datetime import date st.write(""" # Financial Dashboard """) ## define the ticker symbol (e.g. AAPL - Apple, AMZN - Amazon, MSFT - Microsoft) tickerSymbol = st.selectbox("Select Stock", ("Facebook (FB)", "Apple (AAPL)", "Amazon (AMZN)", "...
from flask_login import UserMixin from flask_sqlalchemy import SQLAlchemy from marshmallow import fields, post_load, pre_load, Schema client_db = SQLAlchemy() # Models class User(UserMixin, client_db.Model): id = client_db.Column(client_db.Integer, primary_key=True) username = client_db.Column(client_db.Str...
import numpy as np def zip_em_all(biglist, nfiles): if (nfiles < 2): print 'returning 0th element' zippedlist = np.array(biglist[0]) return zippedlist zippedlist = np.append(biglist[0], biglist[1], axis = 0) count = 0 endgame = nfiles - 2 while (count < endgame): zippedlist = np.append(zippedlist, biglist...
import time import pandas as pd import numpy as np CITY_DATA = { 'chicago': 'chicago.csv', 'new york city': 'new_york_city.csv', 'washington': 'washington.csv' } def get_filters(): """ Asks user to specify a city, month, and day to analyze. Returns: (str) city - name o...
#-------------------------------------------------------------------------------- # G e n e r a l I n f o r m a t i o n #-------------------------------------------------------------------------------- # Name: Exercise 2.1 - Another ball dropped from a tower # # Usage: Calculates time a dropped object takes to hit...
from PyQt5 import QtCore, QtGui, QtWidgets class CursorInterface(QtWidgets.QGraphicsView): """ A 2D cursor control interface implemented using a QGraphicsView. This view essentially just holds a QGraphicsScene that grows to fit the size of the view, keeping the aspect ratio square. The scene is displ...
from us_names import SURNAMES, FEMALE_NAMES, MALE_NAMES #Option 1: for-loop for i in range(0,2): print(FEMALE_NAMES[i] + ' ' + SURNAMES[i]) #Option 2: while-loop counter = 2 while counter > 0: print(MALE_NAMES[counter] + ' ' + SURNAMES[counter]) counter -= 1
# -*- encoding: utf-8 -*- import inspect import re from collections import defaultdict, OrderedDict from typing import List, Tuple, Optional, Dict, Union from .register import MobaseRegister from .mtypes import ( Type, CType, Class, PyClass, Enum, Arg, Ret, Method, Constant, ...
class Animal: def __init__(self,name,age): self.name=name self.age=age class Dog(Animal): def breedname(self,breed): self.breed=breed print(self.name) print(self.age) print(self.breed) d=Dog('chakki',2) d.breedname('Beagle')
import os import json import sys import commons.functions as func import commons.errors as errors cwd = os.getcwd() guildsdata_file_path = os.path.expandvars(f"{cwd}/data/guilds_data.json") help_file_path = os.path.expandvars(f"{cwd}/data/help_messages.json") notice_file_path = os.path.expandvars(f"{cwd}/da...
#!/usr/bin/env python x=['Fruit'] y='Apple' x.append(y) print x
def authenticate(uname, password): if (uname == "jashin" and password == "awesome"): return True else: return False
import numpy as np from scipy.optimize import minimize from scipy.io import loadmat from numpy.linalg import det, inv from math import sqrt, pi import scipy.io import matplotlib.pyplot as plt import pickle import sys def ldaLearn(X,y): # Inputs # X - a N x d matrix with each row corresponding to a training exa...
from django.urls import path from backend.api_gateway.group_endpoint.views import group, update_driver, update_cost urlpatterns = [ path('', group, name='group'), path('<int:group_id>', update_driver, name='update_driver'), path('<int:group_id>/cost', update_cost, name='update_cost'), ]
import random import string live = True specadd = str("") while live: user_input1 = int(input("How Long Do You Want Your Password?")) user_input2 = int(input("How Many Letters?")) while user_input2 > user_input1: error_input1 = int(input("Number Higher Than Total Password Length, Please Try Again....
from datetime import date atual = date.today().year sexo = str(input('Qual o seu sexo? ')).strip().capitalize() #Se for masculino if 'Homem' in sexo or 'Masculino' in sexo: nasc = int(input('Digite o ano de seu nascimento: ')) idade = atual - nasc print(f'Você nasceu em {nasc}, tem {idade} ano(s) em {atual}...
import network, time, urequests, utime, framebuf from time import sleep from machine import Pin, SoftSPI, I2C from mfrc522 import MFRC522 from ssd1306 import SSD1306_I2C #leds registro_correcto = Pin(4, Pin.OUT) registro_Incorrecto = Pin(2, Pin.OUT) #Modulo RFID sck = Pin(18, Pin.OUT) mosi = Pin(23, Pin.OUT) miso = P...
#!/usr/bin/env python # -*- coding: utf-8 -*- from smorest_sfs.modules.auth import ROLES from tests._utils.injection import GeneralGet class TestListView(GeneralGet): fixture_names = ("flask_app_client", "flask_app", "regular_user") item_view = "Role.RoleItemView" listview = "Role.RoleListView" view ...
import unittest from twitter_search import new_tweet_request # A few things to test for: # - If we ask to get x number of tweets, it returns x number of tweets # - It throws an error with a tag that has no tweets with it. class search_test_case(unittest.TestCase): def test_standard_request(self):...
#coding: utf-8 import requests import json def post_data(): headers = {"Content-Type": "application/x-www-form-urlencoded"} data = {"name":4,"sn_num":'123sds4',"remark":'数据1'} url = 'http://127.0.0.1:8080/service_info/' cent = requests.post(url, data=json.dumps(data), headers=headers) print(...
""" Useful tools for manipulating pieces of the URL according to the various RFCs. Original implementation is from the following repo: https://github.com/rbaier/python-urltools and used here with the MIT License, as posted here: https://github.com/rbaier/python-urltools/blob/master/LICENSE Copyright is Rode...
def bubble_sort(array: list): swaps = -1 while swaps != 0: swaps = 0 for i in range(len(array) - 1): if array[i] > array[i + 1]: tmp = array[i] array[i] = array[i + 1] array[i + 1] = tmp swaps += 1 def selection_sort(array: list): for i in range(len(array)): min...
'''a bootstrap server, returns a short list of nodes that are alive''' import socket import time import random def BootstrapServer(): """ """ nodes = {} host = "127.0.0.1" #loopback adress port = 5555 publicKey = hex(random.randint(0, 256**64 - 1))[2:] socket1 = socket.socket() so...
import numpy a = numpy.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]) print(numpy.min(a)) print(numpy.min(a, axis = 0)) print(numpy.min(a, axis = 1)) s1 = "4 2" s2 = ["2 5", "3 7", "1 3", "4 0"] dim = list(map(int, s1.split())) row = dim[0] col = dim[1] a = [] for x in s2: temp = list(map(...
'''Write a Python function to check whether a number is in a given range. ''' def test_range(num): if num in range(1,5): print(f" {num} is in the range") else : print(f"{num} is Not in given range.") test_range(2) test_range(22)
# Generated by Django 2.2.6 on 2020-03-24 09:20 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('candidate', '0008_recrui...
# PUBLIC DOMAIN NOTICE # National Center for Biotechnology Information # # This software is a "United States Government Work" under the # terms of the United States Copyright Act. It was written as part of # the authors' official duties as United States Government employees and...
from enum import Enum,auto #Enum that contains types of networks #SA_TO_Q = a network with state-action input that ouputs a single q value #S_TO_QA = a network with state input that ouputs a q value for each action #SM_TO_QA = a network with multiple state input (frame stacking) that outputs a q value for each action ...
# Generated by Django 3.0.5 on 2020-09-11 04:08 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='ServerKey', fields=[ ...
Esse é o conteúdo do Feature2 Esse é o conteúdo do Feature2
"""unittest for plugin""" import json import os import tempfile import unittest from wechaty import Wechaty, WechatyOptions from wechaty.plugin import WechatyPlugin from wechaty.utils.data_util import WechatySetting from wechaty.fake_puppet import FakePuppet def test_setting(): with tempfile.TemporaryDirectory() ...
# Generated by Django 3.0.3 on 2020-03-04 08:00 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('city', '0002_auto_20200304_1458'), ('sites', '0002_auto_20200304_1420'), ] operations = [ migration...
#!/usr/bin/env python # # aws_snapshot_manager.py # # Takes a daily snapshot and manages your archival snapshot inventory. # # Requirements: # # * A working boto configuration for establishing connection to your AWS environment # * This script is meant to be run once a day with a cron job # # Snapshot management l...
import os from glob import glob from random import shuffle from torch.utils.data import Dataset from torchvision.transforms import ToTensor import cv2 from albumentations import ( HorizontalFlip, IAAPerspective, ShiftScaleRotate, CLAHE, RandomRotate90, Transpose, ShiftScaleRotate, Blur, OpticalDistortion, GridD...
from django.contrib import admin from .models import TeachingTask,Semester # Register your models here. @admin.register(TeachingTask) class TeachingTaskAdmin(admin.ModelAdmin): list_display = ['semester','teacher','course','classes','is_changed','create_time'] search_fields = ['classes__name','teacher__teache...
from adapters.contact_adapter import ContactAdapter from devices.sensor.contact import ContactSensor class AV201021(ContactAdapter): def __init__(self, devices): super().__init__(devices) self.devices.append(ContactSensor(devices, 'tamper', 'tamper'))
from flask.ext.admin import BaseView, AdminIndexView, expose, form from flask.ext.admin.contrib.sqla import ModelView from flask.ext.admin.contrib.fileadmin import FileAdmin from flask.ext.login import current_user from flask import url_for, current_app, flash from wtforms import HiddenField, TextAreaField, PasswordFie...
class Person: def __init__(self, name, age): self.name = name self.age = age def __repr__(self): return '{}:{}'.format(self.name, self.age) if __name__ == '__main__': # Sort float list float_list = list_float = [645.32, 37.40, 76.30, 5.40, -34.23, 1.11, -34.94, 23.37, 635.46, -...
# -*- coding: utf-8 -*- import sys if sys.version_info.major == 3: from .config import Config else: from config import Config
N = 12 temp = [0] * 12 maior = 0.0 menor = 0.0 # primeiro mes deve ser lido seprado para atribuir a maior e a menor temperatura do momemto temp[0] = float(input("Digite a temperatura do mes de janeiro: ")) maior = temp[0] menor = temp[0] """ MAIORES E MENORES TEMPERATURAS """ cont = 1 while cont < N: temp[cont]...
import socket import threading PORT = 5000 ADDRESS_CLIENT = "10.90.37.15" ADDRESS_MID = "10.90.37.16" ADDRESS_SEVERNAME1 = "10.90.37.17" ADDRESS_SEVERNAME2 = "10.90.37.19" ADRESS_SERVER = "10.90.37.18" class ServerName1(): def __init__(self): self.retornaServer(ADDRESS_SEVERNAME1, PORT) def retornaServer(self, ...
import configparser import json import numpy as np import sys from tqdm import tqdm def load_glove_from_npy(glove_vec_path, glove_vocab_path): vectors = np.load(glove_vec_path) with open(glove_vocab_path, "r", encoding="utf8") as f: vocab = [l.strip() for l in f.readlines()] assert(len(vectors) =...
import sys input = sys.stdin.readline def main(): N = int( input()) t = 1 if N%2 == 0: t = 2 AB = [ tuple( map( lambda x: int(x)*t, input().split())) for _ in range(N)] A = [ab[0] for ab in AB] B = [ab[1] for ab in AB] A.sort() B.sort() if t == 1: m = A[N//2] ...
import json # import 3rd party data analysis package 'Pandas' import pandas # we use pyplot in particular here from matplotlib for creating # our charts, by convention pyplot is named plt when imported. # matplotlib is a 3rd party graphics package. import matplotlib.pyplot as plt tweets_data_path = 'tweet_mining.json'...
import turtle def draw(curList,distance,run,t): MAX_RUN = 8. if run <= MAX_RUN: BlueShade = 1-float(run)/MAX_RUN RedShade = float(run)/MAX_RUN GreenShade = float(run)/MAX_RUN RunColor=(RedShade,GreenShade,BlueShade) t.color(RunColor) t.pensize(1+4*(MAX_RUN-run)) print("run: ",run) #print(" cur...
#!/usr/bin/env python # encoding: utf-8 from simulator.modules.sim import * class TestEventHandler(EventHandler): def __init__(self, simulation_engine): super().__init__(simulation_engine) self.start_callback_received = False self.stop_callback_received = False self.events = [] def handle_start(s...
import unittest import json import sys sys.path.append('../Chapter02') _404 = "The requested URL was not found on the server. " \ " If you entered the URL manually please check your" \ "spelling and try again." class TestApp(unittest.TestCase): def setUp(self): from flask_error import app as _app ...
import pytest import time import zmq import cv2 import random from threading import Thread from back_machine.collector_node import collector from back_machine.input_node import producer from back_machine.ostu_node import consumer as otsu_consumer from front_machine.contours_node import consumer as contours_consumer fr...
import logging import click import torch from sonosco.common.constants import SONOSCO from sonosco.common.utils import setup_logging from sonosco.common.path_utils import parse_yaml from sonosco.models import TDSSeq2Seq from sonosco.decoders import GreedyDecoder from sonosco.datasets.processor import AudioDataProcesso...
import socket import os import sys def recibir(nombre): s.send(nombre.encode()) t = s.recv(1024).decode() tam = int(t) #print(tam) if(tam != 0): f = open(nombre,'wb') while (tam > 0): l = s.recv(1024) f.write(l) tam -= sys.getsizeof(l) #print(tam) f.close() print("Archivo '"+nombre+"' rec...
# Use pip install MySQL-python to install mysql dependencies # -*- coding: utf-8 -*- import MySQLdb as MySql import sys class MySQLInterface(): def __init__(self, host, port, user, password): self.host = host self.port = port self.user = user self.password = password self.database = "" self.table = dict()...
#!/usr/bin/env python """ pip install urllib3 pip install bs4 """ from coordinator import CoOrdinator coordinator = CoOrdinator() coordinator.farm()
import board import digitalio import time import microcontroller from DFPlayer import DFPlayer dfplayer = DFPlayer() builtin_led = digitalio.DigitalInOut(board.D13) builtin_led.direction = digitalio.Direction.OUTPUT led = digitalio.DigitalInOut(board.D2) led.direction = digitalio.Direction.OUTPUT pir = digitalio.Di...
__version__ = "0.1.25"
from ovpn import OpenVpn IP = "178.128.112.7" PORT = 5555 s = OpenVpn(IP,PORT) connect = s.connect() print(connect) clients = s.get_clients() print(clients)
# This code is based off code included in pywcsgrid2 import numpy as np from matplotlib.transforms import Transform from .base import CurvedTransform class WcsWorld2PixelTransform(CurvedTransform): """ """ input_dims = 2 output_dims = 2 is_separable = False def __init__(self, wcs): ...
class Solution: def minTimeToVisitAllPoints(self, points: List[List[int]]) -> int: cp = np = [] steps = 0 for i,point in enumerate(points): cp = point if i+1<len(points): np = points[i+1] vtc = [np[0]-cp[0], np[1]-cp[1]] ...
import json lines = file('decode.asl').read().split('\n') insns = [] def parseCase(level, oknowns, fields): case = lines.pop(0) assert case.startswith('\t' * level + 'case ') case = tuple(elem.strip() for elem in case.split('(', 1)[1].split(')', 1)[0].split(',')) case = () if len(case) == 1 and case[0] == '' else ...
#!/usr/bin/python # -*- coding: utf-8 -*- import sys import os import signal import time from subprocess import Popen chinadns = ['src/chinadns', '-l', 'iplist.txt', '-c', 'chnroute.txt', '-p', '15353', '-v'] p1 = Popen(chinadns, shell=False, bufsize=0, close_fds=True) with open(sys.argv[-1]) as f: ...
import gzip import httpx from app.core import settings class SecurityTrails: def __init__(self): self.base_url = "https://api.securitytrails.com/v1" async def download_new_domain_feed(self, *, date: str | None = None): url = self._url_for("/feeds/domains/registered") headers = { ...
class Test: def __init__(self): self.cards = [] self.index = 0 def createList(self): while self.index < 5: self.cards.append("Hello") self.index+=1 self.index = 0 def printList(self): while self.index < 5: print(self.cards[self.index]) self.index+=1 if __name__ == '__main__': var = Test...
from flask import (Flask, render_template, url_for, request, flash, redirect, session, abort) app = Flask(__name__) app.config['SECRET_KEY'] = 'sghowh2hg82gh09g20gh2hgohg90whewkjdhoiwjf092'#Произвольные символы. Чем тяжелее, тем лучше """ ! для активации виртуальной среды - source ./venv/bin/source """ "...
# -*- coding: utf-8 -*- """ Created on Tue Jun 20 21:50:16 2017 @author: Gavrilov """ def mult(base,exp): """ base == int or float, exp == int """ result=1 while exp>0: result=result*base exp=exp-1 return result print(mult(float(input("Enter int or float: ")), i...
import pygame from model.Board import Board from model.Item import Item from model.ScreenType import ScreenType from model.SquareType import SquareType from model.AIPlayer import AIPlayer class BoardView: def __init__(self, boardGame): self.SCREEN_WIDTH = 600 self.SCREEN_HEIGHT = 600 sel...
from OgameBot import OgameBot from GalaxySearcher import GalaxySearcher from Requirements import getRequirementsTech from planetState import PlanetState from fleet import Fleet from decisionMaking import find_steps from decisionMaking import convert_steps_to_orders testing = OgameBot() testing.launchBrowser() testing...
import numpy as np import random class Player: def __init__(self, strategy): self.strategy = strategy def choose(self, init_choice: int, host_choice: int, doors: np.array) -> int: if self.strategy == 'donkey': return init_choice elif self.strategy == 'switcher': ...
from ED6ScenarioHelper import * def main(): # 空贼要塞 CreateScenaFile( FileName = 'C1303 ._SN', MapName = 'Bose', Location = 'C1303.x', MapIndex = 52, MapDefaultBGM = "ed60031", Flags = 0, ...
"""empty message Revision ID: bd2b63bd04bc Revises: Create Date: 2020-03-27 20:31:38.665362 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = 'bd2b63bd04bc' down_revision = None branch_labels = None depends_on = None def upgrade(): # ### commands auto gene...
from __future__ import division import os import numpy as np from scipy import misc as ms import sys import re import cv2 ################################################### def write_kitti_png(path, flow, valid=None): temp = np.ones((flow.shape[0], flow.shape[1], 3), dtype=np.float64) temp[:, :, :2] = flow.a...
import sys sys.path.append('../streamlit-recommendation') import pytest from helper import data_processing from helper import lookup from helper.recommendation import get_recomendation import streamlit as st from random import randint def test_data(): # clear streamlit cache because load_data uses cache decorator...
import tensorflow as tf import random import matplotlib matplotlib.use('TkAgg') import matplotlib.pyplot as plt tf.set_random_seed(777) # for reproducibility from tensorflow.examples.tutorials.mnist import input_data # Check out https://www.tensorflow.org/get_started/mnist/beginners for # more information about the m...
# MSU CSE 231 Fall 2009 Project 4 # author: Joseph Malandruccolo # date: January 13, 2013 # # Program Specs: # Prompt the user for a year # Report the U.S. population # - actual if in the past # - projected if in the future #constants US_POPULATION_2013 = 315163513 SECONDS_BETWEEN_BIRTHS = 8 SECONDS_BETWEEN_DEAT...
#!/usr/bin/env python """ Usage: ./dual_plot.py <ctab1> <ctab2> """ import sys import pandas as pd import matplotlib.pyplot as plt import numpy as np coi = ['t_name', 'FPKM'] df893 = pd.read_csv( sys.argv[1], sep="\t" )[coi] df915 = pd.read_csv( sys.argv[2], sep="\t" )[coi] df_m = pd.merge( df893 , df915, on='t_name...
import decimal import math from inspect import getdoc from pytest import raises from fuzzyfields import (FuzzyField, MissingFieldError, DuplicateError, MalformedFieldError, FieldTypeError) from . import requires_pandas class FooBar(FuzzyField): """Stub field that tests that the input is '...
#use this to autenticate login def authenticate(uname,pword): if uname="
from preprocess_cnn import get_data from import_data import import_data from keras.models import Sequential from keras.layers import Bidirectional, Masking, MaxPool2D, Conv2D, Conv1D, Input, Flatten,Reshape, ConvLSTM2D import h5py from keras.layers.core import Dense, Dropout, Activation, Flatten from keras.layers.recur...
#!/usr/bin/env python from troposphere import Ref, Join from troposphere.dynamodb2 import (KeySchema, AttributeDefinition, ProvisionedThroughput, Table) from troposphere.cloudwatch import Alarm, MetricDimension def init(t, r): stackname = Ref('AWS::StackName') dynamodb_capa...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # 切片:取一个list或tuple的部分元素是非常常见的操作 L = ['Michael', 'Sarah', 'Tracy', 'Bob', 'Jack'] print(L[0:3]) # L[0:3]表示,从索引0开始取,直到索引3为止,但不包括索引3。即索引0,1,2,正好是3个元素 print(L[-3:-1]) # 记住倒数第一个元素的索引是-1 print(L[-1:]) # 甚至什么都不写,只写[:]就可以原样复制一个list print(L[:]) L = list(range(100)) # 前10个数,每两个取一个...
greeting = input("Write a greeting: ") print(greeting)
from voluptuous import Schema, All, ALLOW_EXTRA, Range config_schema = Schema( { 'DEBUG': bool, 'HOST': str, 'SECRET_KEY': str, 'PORT': All(int, Range(min=1, max=10000)) }, extra=ALLOW_EXTRA )
from math import ceil def merge_the_tools(string, k): for i in range(ceil(len(string) / k)): if (i * k + k < len(string)): s = string[i * k:i * k + k] else: s = string[i * k:] t = [] for j in range(len(s)): if (s[j] not in t): t.a...
class Solution(object): def maxRotateFunction(self, nums): if not nums: return 0 res = sum([i * nums[i] for i in xrange(len(nums))]) total, n, tmp = sum(nums), len(nums), res for idx in xrange(-1, - n - 1, -1): res = max(res, tmp) tmp += total - (n * nums[idx]...
import math import string import pyclipper import time from GerberReader import GerberLayer, GerberData __author__ = 'Thompson' """ Employs recursive descent parsing to parse a Gerber data file. This methodology is more flexible to bad formatting of data file This is a fully compliant parser. """ """ Maximum arc len...
class Solution: def maximalSquare(self, matrix: List[List[str]]) -> int: if (len(matrix)==0) : return 0 dp=[[0 for a in range(len(matrix[0]) +1)] for b in range(len(matrix) +1)] m,n=len(matrix),len(matrix[0]) gmax=0 for i in ra...
from nltk.tokenize import WordPunctTokenizer from gensim.models import Word2Vec def train_w2v(): sentences = [['this', 'is', 'the', 'first', 'sentence', 'for', 'word2vec'], ['this', 'is', 'the', 'second', 'sentence'], ['yet', 'another', 'sentence'], ['one', 'more', ...
# coding: utf-8 import sys import os import jump.commands # returns an environment variable as uppercase def get_env(field): return os.environ[field.upper()] # return the name of the function called as first argument of command def get_command_name(args): command_name = None for command in list(args...
from threading import local class NavigationRootInfo(local): root = None _current_root = NavigationRootInfo() def getNavigationRoot(): """Get the current navigation root """ return _current_root.root def setNavigationRoot(root): """Set the current navigation root. This is normally done by an ...
from onegov.org.models.atoz import AtoZ from onegov.org.models.clipboard import Clipboard from onegov.org.models.dashboard import Boardlet from onegov.org.models.dashboard import BoardletFact from onegov.org.models.dashboard import Dashboard from onegov.org.models.directory import DirectorySubmissionAction from onegov....
import torch import numpy as np from PIL import Image import os import random from IPython import display from IPython.core.interactiveshell import InteractiveShell import subprocess InteractiveShell.ast_node_interactivity = "all" import glob import clip perceptor, preprocess = clip.load('ViT-B/32') import sys c_encs=[...
class Readfile: def __init__(self, file): self.file = open(file, "r", encoding = "utf-8") self.mem = [] self.answer = [] path = self.file.readline() while path[0:1] == "#": path = self.file.readline() while path[0:1] != "#": path = path.strip(...
import math class Solution: def judgeSquareSum(self, c): """ :type c: int :rtype: bool """ divisorLimit = math.ceil(math.sqrt(c)) possible = set() for i in range(0, divisorLimit+1): possible.add(i**2) for i in possible: if c-i ...
# -*- coding: utf-8 -*- import scrapy from scrapy_redis.spiders import RedisSpider import re class IndonesiaGoodsNameSpider(RedisSpider): name = 'indonesia_goods_name' allowed_domains = ['www.tokopedia.com'] start_urls = ['https://www.tokopedia.com/p/buku/buku-remaja-dan-anak/dunia-pengetahuan'] redis_...
from Pages.MediaPages.DocumentMedia import DocumentMedia import pytest @pytest.allure.feature('Nodes') @pytest.allure.story('Press Release CT') @pytest.mark.usefixtures('init_press_release_page') class TestPressReleaseCT: @pytest.allure.title('VDM-188 Press Release CT - creating') def test_press_release_crea...
import sys import pymongo try: mongo_host = sys.argv[1] except IndexError as e: print(f"请输入初始化的mongo地址!") db = pymongo.MongoClient(mongo_host, 27017)['test_case']['tables'] db.insert_many( [ {"_id": "users", "index": 1}, {"_id": "products", "index": 1}, {"_id": "product_category_in...
import numpy as np iteration=0 Y=0.99 delta=1e-3 stepcost=-20 finalreward=10 utility=np.zeros([5, 4, 3], dtype=float) new=np.zeros([5, 4, 3], dtype=float) actionarr=np.zeros([5, 4, 3], dtype=object) action="-1" def recharge(i, j, k, utility): return round(0.8*(stepcost+Y*utility[i][j][min(utility.shape[2]-1, k+1)])+...
import time from sys import * INF = 10**10 if len(argv) == 2: f = open("X10M.txt", "r", encoding="utf-8") string = f.read().replace(" ","").replace("\n","") sl = int(argv[1]) string = string[:sl] #print("input end") else: string = "" f = input() while (f): try: st = f...
# ================================================================================================== # Copyright 2013 Twitter, Inc. # -------------------------------------------------------------------------------------------------- # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use thi...
import SocketServer import RPi.GPIO as GPIO import numpy as np import cv2 import os import thread import json import pickle class Servo(): pin = None NEUTRAL = 7.5 ZERO = 2.5 FULL = 12.5 servo = None def __init__(self, pin): self.pin = pin GPIO.setmode(GPIO.BOARD) GPI...
from django.shortcuts import get_object_or_404, render from django.http import HttpResponse from authentication.models import User from .forms import EditUserForm import json def update_user(request, user_id): user = get_object_or_404(User, pk=user_id) context = { 'user': user } if (request.PO...
from cms.app_base import CMSApp from cms.apphook_pool import apphook_pool from django.utils.translation import ugettext_lazy as _ class CellApphook(CMSApp): app_name = 'cells' name = _("Celulas") def get_urls(self, page=None, language=None, **kwargs): return ["cells.urls"] apphook_pool.register...