text
stringlengths
8
6.05M
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import os.path import shutil import nysol.mcmd as nm import nysol.util as nu import nysol.util.mtemp as mtemp from nysol.take import graph as ntg from nysol.take import extcore as extTake class mpolishing(object): helpMSG=""" ---------------------------- #{...
""" LeetCode - Easy """ class Solution: def findMaxLength(self, nums): count_0 = 0 count_1 = 0 index = 0 while index < len(nums) - 1: if (nums[index] == 0 and nums[index + 1] == 1) or (nums[index] == 1 and nums[index + 1] == 0): count_0 += 1 ...
def find_all_paths(graph, start, end, path=[]): path = path + [start] if start == end: return [path] paths = [] for node in graph[start]: if node not in path: newpaths = find_all_paths(graph, node, end, path) for newpath in newpaths...
""" Aprimore o desafio 93 para que ele funcione com vários jogadores, incluindo um sistema de visualização de detalhes do aproveitamento de cada jogador. """ jogadores = list() jogador = dict() while True: jogador['nome'] = str(input('Nome do jogador: ')) partidas = int(input('Quantidade de partidas: ')) ...
# -*- coding: utf-8 -*- """ A script to process all the files in a given folder Written by: Andy Kiss Created: 2017-05-15 Last modified: 2017-05-15 """ # %% Import modules import numpy as np import os import time from skimage.feature import register_translation from skimage.transform import warp, SimilarityTransfor...
# Copyright 2016 Husky Team # # 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, softw...
#This program allows user 6 chances to guess a random number import random secretNo = random.randint(1,20) print('I am thinking of a number between 1 and 20.') #Ask player to guess 6 times. for guessesTaken in range(1,7): print('Take a guess.') guess = int(input()) if guess < secretNo: print('Yo...
""" Creación del tipo especifico del selector de temperatura """ from agentes_sensores.proxy_selector_temperatura import * class FactorySelectorTemperatura: @staticmethod def crear(tipo: str) -> AbsSelectorTemperatura: if tipo == "archivo": return SelectorTemperaturaArchivo() else: return N...
import pylab as pl from get_fish_info import get_fish_info from fit_integrator_model import get_model_result, get_target_result import numpy as np from pathlib import Path import gmm_model_fit import pandas as pd from pymoo.factory import get_problem, get_visualization, get_decomposition from sklearn.manifold import TS...
a=int(input()) for i in range(a+1): b=2**i if (b==a): print(2**(i+1))
from numpy import random, exp, sqrt, pi, exp, square, log, power import numpy as np def sigmoid(x): return 1 / (1 + exp(-x)) def sigmoid_dot(x): return sigmoid(x) * (1 - sigmoid(x)) class ErrorFunction: def __init__(self, delta): self.delta = delta def p(self,t, mu, sigma): retur...
import click import io import nbformat import os from nbconvert import HTMLExporter from nbconvert.preprocessors import ExecutePreprocessor, ClearOutputPreprocessor from common import * def execute(input, to_html, to_self, to_clear): print('Processing ' + Fore.LIGHTGREEN_EX + input) with open(input, 'rb') as...
from supports import verify_input as vI from core import convert_radix as cR from core import infix_to_postfix as itp from core import cal_postfix_to_result as ptr menu = """ \t SUPER CALCULATOR FX6969 --- Choose one option --- A. Simple expression calculate. B. Convert to another radix. C. Calculate the system of ...
import os with open("file.txt",mode="w",encoding="utf-8") as myfile: myfile.write("some random text \n more random text \n even more random text\n welcome to random text") with open("file.txt",mode="r",encoding="etf-8") as myfile: linenum=1 line=myfile.readline() if not line: break print(...
# -*- coding: utf-8 -*- import subprocess as sub class HCSProcess(object): def __init__(self, app): self.__app = app self.__p = None def run(self): self.__p = sub.Popen(self.__app, stdout=sub.PIPE, stderr=sub.PIPE, shell=True) output, errors = self.__p.communicate()
import time import os import unittest from appium import webdriver import logging from appium.common.exceptions import NoSuchContextException # 写入数据的函数进行封装 class Auto_execise(unittest.TestCase): def device(self): d = { "deviceName": "CN42195G00019", "platformName": "Android", ...
#!/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", "fake_codes") listview = "Code.CodeListView" login_roles = [ROLES.CodeM...
from tkinter import * root = Tk() root.title("Tkinter Calculator") entry_box = Entry(root, width=35, borderwidth=5) entry_box.grid(row=0, column=0, columnspan=5, padx=2, pady=8) def button_click(number): current = entry_box.get() entry_box.delete(0, END) entry_box.insert(0, str(current) + str(number)) def b...
#!/usr/bin/python from my_pkg import conv_boh from my_pkg import uandi_int import re import sys menu = 0 while menu!=3: menu = int(input("Select menu: 1)conversion 2)union/intersection 3)exit ?")) if menu==1: bin = int(input("input binary number: ")) conv_boh.conv(bin) elif menu==2: lst1 = re.findall("\d+", i...
""" TODO(sshah): Complete Module Docstring""" import tensorflow as tf import tensorflow.keras.backend as K from tensorflow.keras.initializers import Orthogonal from tensorflow.python.keras.utils import tf_utils from tensorflow.keras.layers import RNN, Dense, TimeDistributed, LSTMCell, Input, Embedding from tensorflow.k...
import function_library as func_lib import json from glob import glob import logging def test_speakers(): # Change location file_name = "user_study_output\\user_study_initial_output\\lecture\\Elon_Musk_chunk_19.wav" result = func_lib.transcribe_robustly(file_name, True) speaker_list = func_lib.get_s...
# -------- # Note # -------- # round() =>နီးရာကိန်းပြည့်ပြောင်း # abs() => absolute , အပေါင်းကိန်းပြောင်း # module => separated file with some reusable code # math.ceil(x) , math.floor() => အားလုံးကို လေ့လာဖို့ python3 Documentation ကိုဖတ်ပါ import math x = 2.9 print(round(x)) print(abs(x)) x = -2.3 print(round(x)...
#!/usr/bin/env python from __future__ import print_function import sys import re import os from datetime import datetime worker_re = re.compile('worker_([0-9]+)_of_16') for fn in os.listdir('.'): if not (fn.startswith('slurm-') and fn.endswith('.out')): continue print(fn) last_time = {} with...
from datetime import date anoatual = date.today().year idademaior = 0 idademenor = 0 for c in range(1, 8): ano = int(input(f'Digite o ano de nascimento da {c}ª pessoa: ')) idade = anoatual - ano if idade > 18: idademaior += 1 else: idademenor += 1 print(f'Temos {idademaior} maior(es) de ...
from goldfnd.lib.database import get_database_session from goldfnd.models.ScheduledAnswer import ScheduledAnswer class ScheduleService(object): def __init__(self): self.session = get_database_session() self.unsent_answers = ScheduledAnswer.get_unsent_answers_have_to_be_sent(self.session) def...
import os import pathlib import numpy from skimage import io def create_test_csv_from_ids(image_ids, csv_file): with open(csv_file, 'w') as f: f.write(f'ID,ImageHeight,ImageWidth,Label') if isinstance(image_ids, str): image_ids = [image_ids] for iid in image_ids: f....
from django import forms from django.forms import ModelForm, Textarea from review.models import Review class ReviewForm(ModelForm): #rating = forms.IntegerField(widget=forms.TextInput(attrs={'id': 'reviewRating'})) comment = forms.CharField(widget=forms.TextInput(attrs={'id': 'reviewComment'}), max_length=200,...
#!/usr/bin/env python # -*- coding: utf-8 -*- from global_parameters import * import pandas as pd import pickle def cal_vehicles(): data = pd.DataFrame(columns=('vehicle_ID', 'start_loc', 'start_time', 'stop_time', ...
"""Eliezer_Website URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.2/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') Cla...
from django.test import TestCase from apps.teams.models import Team from apps.teams.util import get_next_unique_team_slug class UniqueSlugTest(TestCase): def test_unique_slug_no_conflict(self): self.assertEqual('a-slug', get_next_unique_team_slug('A Slug')) def test_unique_slug_conflicts(self): ...
# dechexbin.py bob # import c1 = 48; c2 = 57; c3 = 65; c4 = 96; t1 =c1; t2 = c2; t3 = c3; t4 = c4 print(c1,"\t",c2,"\t",c3,"\t",c4) c1 = chr(c1); c2 = chr(c2); c3 = chr(c3); c4 = chr(c4); print(c1,"\t",c2,"\t",c3,"\t",c4) print (" CONVERT TO HEX AND BINARY" ) c1 = bin(t1); c2 = bin(t2); c3 = bin(t3); c4 = bin(t4); pri...
from Assignment.main import future_two_weeks, change_weekday_to_date, check_if_green_day, find_delivery_date import datetime from Assignment.test_data import product_list_1, post_code, product_list_2, expect_delivery_response_for_product_list_2 def test_change_weekday_to_date(): deliveryweekdays = [0, 1, 2, 3, 4,...
ano = int(input("Digite um ano: ")) mes = int(input("Digite um mes: ")) if (mes==1) or (mes==3) or (mes==5) or (mes==7) or (mes==8) or (mes==10) or (mes==12): print("Esse mes tem 31 Dias") elif (mes==4) or (mes==6) or (mes==9) or (mes==11): print ("Esse mes tem 30 Dias") if (mes==2): print("Esse mes tem 29 Dias")...
import random # получение случайного числа в заданном диапазоне def gen_number(mini, maxi): return random.randrange(mini, maxi + 1) # получение ответа пользователя def get_answer(): try: answer = int(input('Введите ответ: ')) while answer < 0: print('Нужно ввести целое положительно...
from chess.engine import Move, get_location from chess.board import Board from chess.pieces import * import pytest def test_start_config_white(start_board): lst = get_location(start_board) assert lst == set([(6, 0), (6, 1), (6, 2), (6, 3), (6, 4), (6, 5), (6, 6), (6, 7), (7, 0), (7, 1...
import time from multiprocessing import Queue class Instruction: def __init__(self,text,time): self.textInst=text self.time=time def execute(self,cpu,pcb): time.sleep(self.time) def getText(self): return self.textInst def setText(self,textInst): ...
#!/usr/bin/python3 """tests for rectangle class methods""" import io import sys import unittest from models.base import Base from models.rectangle import Rectangle class TestRectangle_instantiation(unittest.TestCase): """Unittests for testing instantiation of the Rectangle class.""" def test_rectangle_is_bas...
from django.dispatch import receiver from bifrost.signals import init_service from bifrost.src.ioc.ServiceContainer import Container from bifrost_timeline.Services import Timeline @receiver(init_service) def declare_services(sender, **kwargs): Container.set_service('timeline_service', Timeline.Service)
# -*- coding: utf-8 -*- """ Created on Sun Apr 21 21:51:16 2019 @author: standl """
#! /usr/bin/python # SPDX-License-Identifier: GPL-2.0 # -*- python -*- # -*- coding: utf-8 -*- import perf class tracepoint(perf.evsel): def __init__(self, sys, name): config = perf.tracepoint(sys, name) perf.evsel.__init__(self, type = perf.TYPE_TRACEPOINT, ...
def parse_molecule (formula): import re #change all brackets to same type - curly because of regex formula = formula.replace('(', '{').replace(')', '}').replace('[', '{').replace(']', '}') #find all elements and create a dict with them elements = re.findall(r'[A-Z][a-z]*', formula) ...
from django.db import models from django.core.urlresolvers import reverse from users.models import User class CommentManager(models.Manager): def get_queryset(self): queryset = super(CommentManager, self).get_queryset() return queryset.select_related( 'post', 'user', ...
import db import threading import time def create_user(username): conn = db.get_connection() c = conn.cursor() c.execute('INSERT INTO users (username) VALUES (?)', (username,)) conn.commit() conn.close() def get_user(username): conn = db.get_connection() c = conn.cursor(...
import json import pickle import csv data_path = "../../Data/OLIDv1.0_2019/" train = data_path + "olid-training-v1.0.tsv" test_a = data_path + "testset-levela.tsv" labels_a = data_path + "labels-levela.csv" test_b = data_path + "testset-levelb.tsv" labels_b = data_path + "labels-levelb.csv" test_c = data_pat...
import os # Para pegar o diretório atual usar os.getcwd() print('Diretório atual: ', os.getcwd()) # Para ver o diretório do arquivo usar os.path() # Para referenciar o arquivo atual, usar __file__ na função print('Arquivo Atual:', __file__) #para nome do arquivo usar os.path.basename() print('Nome do arquivo atual: ...
demand_level = 8 # -*- coding: UTF-8 -*- import os, sys import xml.etree.ElementTree as etree import xml.dom.minidom as doc import math import numpy as np import random from tqdm import tqdm from time import time from scipy.optimize import linprog from cvxopt import matrix,solvers from scipy.sparse import identity from...
# ================================================================================================== # Copyright 2011 Twitter, Inc. # -------------------------------------------------------------------------------------------------- # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use thi...
from django.http import HttpResponse from django.shortcuts import render, get_object_or_404 from django.contrib import messages from django.db.models import F from django.template.loader import get_template from django.core.mail import EmailMessage from django.template import Context # Create your views here. # Post ...
#!/usr/bin/python #\file box_plane_intersection.py #\brief Get an intersection polygon between box and plane. #\author Akihiko Yamaguchi, info@akihikoy.net #\version 0.1 #\date Mar.02, 2021 import numpy as np from scipy.spatial import ConvexHull as scipy_ConvexHull from geometry import * def BoxPlaneIntersect...
import nltk from prettyPrint import prettyPrint from nltk.tokenize import TreebankWordTokenizer as tbwt def nltkCountWords(FILE): dictionary = {} with open(FILE) as file: doc = file.read() # print tbwt().tokenize(doc) for sentence in nltk.sent_tokenize(doc): for word in nltk.word_tokenize(sentence): #...
# # from prettytable import PrettyTable # # x = PrettyTable() # # # # # # # # x.field_names = ["City name", "Area", "Population", "Annual Rainfall"] # # x.add_row(["Adelaide",1295, 1158259, '600.5, 45654']) # # x.add_row(["Brisbane",5905, 1857594, 1146.4]) # # x.add_row(["Darwin", 112, 120900, 1714.7]) # # x.a...
# https://pymotw.com/2/functools/ import functools import inspect from pprint import pprint @functools.total_ordering class MyObject(object): def __init__(self, val): self.val = val # The class must provide an implmentation of __eq__() # and any one of the other rich comparison methods. # Th...
from Models.MobileNet import MobileNet, rpn, Classifier, pose, roi_pooling from tensorflow.python import keras from tensorflow.python.keras.layers import Input from Helpers.config import Config from Helpers import Losses config = Config() classes_count = 21 img_input = Input(shape=(None, None, 3)) roi_input = Input(...
# Bruk Ideone.com for å kompilere eller http://www.tutorialspoint.com/execute_python_online.php from threading import Thread i = 0 def someThreadFunction1(): # Potentially useful thing: # In Python you "import" a global variable, instead of "export"ing it when you declare it # (This is probably an effort to...
from bs4 import BeautifulSoup as bs from splinter import Browser import pandas as pd import time def scraper(): executable_path = {'executable_path': 'chromedriver.exe'} browser = Browser('chrome', **executable_path, headless=False) title, text = mars_news(browser) data = { 'title': title, ...
# Object Oriented Program for motogp # Building Parent Class of Sports Motorcycle class Sports_Motorcycle(): """Model Street Legal Sports Motorcycle""" # Create init Method for parameters self, manufacturer, model of motorycle # Added attributes with value 0 for later use def __init__(self, manufactur...
class Solution: def coinChange(self, coins, amount): dp = [0]+[amount+1]*amount for i in range(len(dp)): for coin in coins: if coin <= i: dp[i] = min(dp[i], dp[i-coin]+1) return [dp[amount], -1][dp[amount] == amount+1]
''' Audit Log Models ''' import json from django.db import models from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes.fields import GenericForeignKey from django import dispatch from django.conf import settings from .utils import serialize_data, data_has_changes audit = dispat...
"""project URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.2/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...
from selenium import webdriver from selenium.webdriver.common.keys import Keys import time import random sites = [] openedsites = [] driver = webdriver.Firefox() def init(): with open("sites.txt","r") as f: for line in f.readlines(): sites.append(line) def open_and_focus_new_tab(): ...
import pytest from capitalize import capital_case, square def test_capital_case(): assert capital_case('semaphore') == 'Semaphore' assert capital_case('trent') == 'Trent' assert capital_case('Hello') == 'hello' @pytest.mark.parametrize("data, expected", [(5, 25),(2, 4), (9, 81), (-3, 9)]) def test_squar...
# ----------------------------------------------------------------------------- # Copyright (c) 2014--, The Qiita Development Team. # # Distributed under the terms of the BSD 3-clause License. # # The full license is in the file LICENSE, distributed with this software. # ------------------------------------------------...
__all__ = ['flexible_distribute', 'FlexibleDistribute', 'to_admin'] import csv import os import threading from BusinessCentralLayer.middleware.work_io import * from BusinessLogicLayer.dog import subs2node @logger.catch() class FlexibleDistribute(object): """数据交换 弹性分发""" def __init__(self, docker: tuple = N...
import logging import time import uuid import dateparser import xmltodict import random import re import datetime import os import requests from pteromyini.lib.web.liteemail.main import EmailFactory from pteromyini.lib.web.liteemail.parser import PFEmailBodyParser from pteromyini.lib.web.liteemail.val...
#Author: Angelina B # Write a function that prints out a menu of commands we can perform, ie add, #view and quit. The function should return what the user chose. import json filename = "students.json" def menu(): print ('What would you like to do?\n (a) Add new student \n (v) View students\n (s) Save students\n ...
from torch_geometric.typing import OptTensor, PairTensor, PairOptTensor, Adj import torch from torch import Tensor from torch_geometric.nn.conv import MessagePassing import torch.nn as neural_net import torch.nn.functional as F class MOLGCN(MessagePassing): """docstring for MOLGCN""" def __init__(self, nn, ...
#!/usr/bin/python3.10 import os import textwrap from pylib import iter_header_paths def setup_one_entry(header_path: str) -> str: return ( f'#include "../../../third-party/Empirical/include/emp/{header_path}"' ) header_guard = "UIT_EMP_VENDORIZATION_CONSOLIDATE_CONTEXT_SWITCHES_HPP_INCLUDE" content ...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ 基于heap的, top_k问题解法。 """ from __future__ import print_function, unicode_literals import time import random import string from heapq import * from pyclopedia.deco import run_if_is_main def create_test_data(): n = 9999 test_data = list() for _ in range(n): ...
# 旋转数组 # 可以把数组想象为一个圆盘,数组中的值就是圆盘边的数字,然后拨动圆盘 # 给定一个数组,将数组中的元素向右移动 k 个位置,其中 k 是非负数。 # 示例 1: # 输入: [1,2,3,4,5,6,7] 和 k = 3 # 输出: [5,6,7,1,2,3,4] # 解释: # 向右旋转 1 步: [7,1,2,3,4,5,6] # 向右旋转 2 步: [6,7,1,2,3,4,5] # 向右旋转 3 步: [5,6,7,1,2,3,4] def rotate(nums, k): """ :type nums: List[int] :type k: int :rtype:...
#Trust Fund Buddy car = input("car: ") rent = input("rent: ") jet = input("jet: ") games = input("games ") total = car+rent+jet+games print(total)
import cv2 from matplotlib import pyplot as plt imageFile = '.\OpenCV_Python/data/lena.jpg' imgBGR = cv2.imread(imageFile) plt.axis('off') imgRGB = cv2.cvtColor(imgBGR, cv2.COLOR_BGR2RGB) plt.imshow(imgRGB) plt.show()
# Bag of words for classifying actions from neural data # Each feature is: number of times each state is contained in the sequence import numpy as np import cPickle import sys expDir = '/run/media/mzanotto/dataFast/renvision/experiments/P29_01_04_16/'+str(sys.argv[1])+'/' with open(expDir+'crbm.pkl') as f: c = c...
from bs4 import BeautifulSoup import requests import os import re class Subscene: def __init__(self,**kwargs): self.args = kwargs self.__header = { "user-agent" : "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36" ...
# tail recursion is a type of recursion in which parent recursion has nothing to do when execution of child recursion finishes # tail recursions exceuted fast when there input size is large # main reason for the tailrecursion is fast because the caller dosent want to save the state # tail recursion is one of the reas...
# Librerias Django from django.contrib import admin # Librerias en carpetas locales from .submodels.website_config import WebsiteConfig admin.site.register(WebsiteConfig)
''' @title Text Adventure @author Carlos Barcelos @date TODO The main class to start the adventure ''' import os # Search files/directories import argparse # Command line arguments import json # Handle JSON files import sys # DEV TOOL from src.Achievements import Achievements # Import the Achievements...
from behaviordisc import * from relationdisc import * from forecasting import * from sdl import Sdl import matplotlib.pyplot as plt import warnings warnings.filterwarnings("ignore") def relation(sd_log): #k_means_clustering(sd_log) non_linear_granger_causation(sd_log) df, relations, exogenous_factors = g...
import pyaudio import wave from scipy.io import wavfile import matplotlib.pyplot as plt import numpy as np #part recording chunk=1024 sample_format=pyaudio.paInt16 filename="audiofile.wav" channels=2 fs=44100 seconds=1 p=pyaudio.PyAudio() print("recording") stream=p.open(format=sample_format,cha...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from .preprocessing.text_prepare import text_prepare from .rhvoice_say.rhvoice_say import rhvoice_say, say_clipboard from .rhvoice_config.rhvoice_conf_gui import main as rhvoice_config
from onegov.form import Form class EmptyForm(Form): pass
import os import sys import time sys.path.insert(0, './') # 定义搜索路径的优先顺序,序号从0开始,表示最大优先级 import faceAntiSpoofing # noqa print('faceAntiSpoofing module path :{}'.format(faceAntiSpoofing.__file__)) # 输出测试模块文件位置 from faceAntiSpoofing import datasets # noqa from faceAntiSpoofing import models # noqa if...
'''this is module program from mod to main''' a=[1,2,3,4,5,6] def ad(a,i): a[i] return a[i] ad(a,4)
from authors.apps.article_rating.models import ArticleRating from rest_framework.serializers import HyperlinkedModelSerializer, ValidationError, PrimaryKeyRelatedField, CurrentUserDefault from rest_framework import serializers class ArticleRatingSerializer(HyperlinkedModelSerializer): """This serializer is for cre...
from keras.layers import Conv2D, DepthwiseConv2D, Dense, GlobalAveragePooling2D from keras.layers import Activation, BatchNormalization, Add, Multiply, Reshape from keras.models import Model from keras.layers import Input, Conv2D, GlobalAveragePooling2D, Reshape from keras.utils.vis_utils import plot_model from keras ...
from matplotlib.dates import date2num import csv import datetime as dt import logging import numpy as np import os import networkNames as names import mospat_inc_directories as IncDir import mospat_utils_equation import IncludeFile as IncF from INetwork import INetwork from aux_operations import naive_num2date cla...
def urlify_in_place(s): """ strings are immutable, so we at least do it with O(N) space """ escaped = "" for c in s: escaped += '%20' if c == ':' else c return escaped
class _Config(object): _message_introspection = True def is_message_introspection_enabled(self): return self._message_introspection def enable_message_introspection(self): self._message_introspection = True def disable_message_introspection(self): self._message_introspection =...
# -*- coding:utf-8 -*- class Solution(object): def numDecodings(self, s): """ :type s: str :rtype: int """ dp = [0 for _ in range(len(s)+1)] if s[0] == '0': return 0 dp[0] = dp[1] = 1 for i in range(1,len(s)): if s[i] == '0': ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # Author: itabas <itabas016@gmail.com> # https://github.com/itabas016/bing-wallpaper from distutils.core import setup from setuptools import setup, find_packages import io, os, re def read(*names, **kwargs): with io.open( os.path.join(os.path.dirnam...
import unittest import requests import time class TestAdd3ToQueueMethods(unittest.TestCase): def test_empty_queue_backend(self): response = requests.get(url="http://localhost:8081/") self.assertEqual("Queue is empty", str(response.json())) def test_queue_dummy_1(self): time.sleep(1) # Wait 1 se...
#!/usr/bin/env python3 import os import random from PIL import Image if __name__ == '__main__': pwd = os.path.dirname(os.path.realpath(__file__)) file_path = os.path.join(pwd, "lenna.png") im = Image.open(fp=file_path) width, height = im.size[0], im.size[1] pixels = im.load() x = random.rand...
#!/usr/bin/env python # -*- coding: utf-8 -*- # pylint: skip-file from setuptools import setup requirements = [ 'numpy>=1.10.0', 'pytest>=3.5.0', ] setup( name='tensorcheck', version="0.0.1", author="Erik Bodin, Andrew Lawrence", author_email="mail@erikbodin.com", description="Tensor val...
from Gens import gen_random from iterators import Unique data1 = [1, 1, 1, 1, 1, 2, 2, 2, 2, 2] data2 = gen_random(1, 3, 10) data3 = ['a', 'A', 'b', 'B'] # Реализация задания 2 for element in Unique(data1): print(element, end=' ') print('\n') for element in Unique(list(data2)): print(element...
def Hello3(Greeting = "No Value Supplied"): print(Greeting) Hello3() Hello3("This is a string.") Hello3(5) Hello3(2 + 7)
from src.lib.orm_util import DBInstance, get_session_from from configs import DevMysql class ScraperEngine: def __init__(self, scraper): self.scraper = scraper self.db = None self.connect_db() def connect_db(self): """ 进行数据库连接 """ self.db = DBInstance(DevMysql) de...
"""Pytorch Dataset object that loads 27x27 patches that contain single cells.""" import os import random import scipy.io import numpy as np from PIL import Image from skimage import io, color import torch import torch.utils.data as data_utils import torchvision.transforms as transforms import utils_augemntation c...
import configparser import codecs import threading import os import time import queue import re from requests_html import HTMLSession import jieba # ============================================= 引擎 ============================================================ class Engine(object): def __init__(self, configPath): ...
from brownie import * from archive.deploy_lgt import deploy_lgt def main(): lgt = deploy_lgt() for _ in range(6): lgt.mint(100, {'from': accounts[1]}) lgt.addLiquidity(0, 500, 99999999999, {'from': accounts[1], 'value': "0.1 ether"}) lgt.transfer(accounts[0], 10, {'from': accounts[1...
# -*- coding: utf-8 -*- ############# # # Copyright - Nirlendu Saha # # author - nirlendu@gmail.com # ############# import inspect import sys, os from app_core import core_interface as core from libs.logger import app_logger as log def store_url( url, url_title, url_desc, url_imagefi...
import os import shutil diretorio = 'desafio' num_pastas_arq = int(input('Quantas pastas e arquivos? ')) if os.path.exists(diretorio): shutil.rmtree(diretorio) os.mkdir(diretorio) for c in range(0, num_pastas_arq): if not os.path.exists(f'{diretorio}\\pasta_{c + 1}'): os.mkdir(f'{diretorio}\\pasta_{c...