text
stringlengths
8
6.05M
def node_classified(name, data={}): ''' Classify node, create inventory level overrides and/or node models :param name: Node FQDN :param data: Node parameters passed to the classifier ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': 'Node "{0...
# Copyright (c) 2015 SONATA-NFV and Paderborn University # ALL RIGHTS RESERVED. # # 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 re...
# coding:utf-8 from __future__ import absolute_import, unicode_literals __author__ = "golden" __date__ = '2018/5/29' import asyncio async def loop1(): while True: print('loop1') await asyncio.sleep(1) async def loop2(): while True: print('loop2') await asyncio.sleep(1) loo...
# -*- coding: utf-8 -*- from django.shortcuts import render from django.template import RequestContext from django.http import HttpResponseRedirect from django.core.urlresolvers import reverse from uploader.myapp.models import Document from uploader.myapp.forms import DocumentForm def list(request): # upload fil...
import os from NeuralGraph.processing import pickle_to_input, lst_to_out from NeuralGraph.util import Timer from sklearn.model_selection import train_test_split from collections import Counter from NeuralGraph.preprocessing import padaxis import torch as T def str_key(a): ka = a.strip().split('_')[2] return ka...
#!/usr/bin/env python # coding=utf-8 from torch.utils.data import Dataset import skimage.io as io import torch class MNISTDataset(Dataset): #mnist手写体数据集 def __init__(self,img_list_path,dataset_root_path="/dataset/human_attribute/",transform=None): self.img_list_path = img_list_path self.transf...
# 找到分类讨论的关键 # 此题首先就是按照取模3为0,1,2分类 # 0具有特殊性,可以作为分类的大前提 class Solution: def stoneGameIX(self, stones: List[int]) -> bool: s = [0, 0, 0] for i in stones: s[i%3] += 1 if s[0] % 2 == 0: return s[1] > 0 and s[2] > 0 else: return abs(s[1] - s[2]...
#Modules from tkinter import* from tkinter import ttk #---------------------------------------- class MyQuiz(): def __init__(self,root): self.Start = Frame(root) self.Start.grid() self.Title = Label(self.Start, text="English Quiz", font = 30) self.Title.grid(columnspan =...
import Rhino as rc import math import random import Rhino.Geometry as rg import scriptcontext as sc import rhinoscriptsyntax as rs import util from itertools import combinations import clr; clr.AddReference("Grasshopper") import Grasshopper as gh #Computational Geometry def PoissonDiscSampling(r, width, height): ...
from genericpath import exists from operator import mod import pickle from typing import List import colorama import face_recognition import os import cv2 from face_recognition.api import face_encodings, face_locations import json from picture import Picture from time import clock from colorama import Fore, Back, St...
import numpy as np from matplotlib.pyplot import figure, cm, show import full_henon as fh import helper as he def basin_attr(xVals, yVals, xSize, ySize, its=100, a=1.4, b=0.3): """ Function that creates the basin of attraction """ # Creating x and y starting values xRange = np.linspace(xVals[0], xVa...
import twitter import sys import json import time import networkx import operator import pickle from pathlib import Path import matplotlib.pyplot as plt def oauth_login(): # XXX: Go to http://twitter.com/apps/new to create an app and get values # for these credentials that you'll need to provide in place of t...
import time import boto3 from collections import defaultdict region = 'us-east-1' ami = 'ami-0fe23c115c3ba9bac' # region = 'us-west-2' # ami = 'ami-01bbe152bf19d0289' ec2 = boto3.resource('ec2', region_name=region) instance = ec2.create_instances( ImageId=ami, IamInstanceProfile={ 'Name': 'sandbox-...
print("Criando um novo arquivo pelo GitHub e usando o git pull para puxar")
# Copyright 2021 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import annotations from textwrap import dedent import pytest from pants.backend.python.goals import package_pex_binary from pants.backend.python.target_types import Pex...
/root/nfs/jooho/openshift-ansible/library/modify_yaml.py
"""Core design modules. For examples for how to use the design module, see the :doc:`Usage Docs <../usage>` For a list of design parameters available, take a look at the :ref:`BoulderIO Parameters <api_default_parameters>` .. code-block:: python # a new task design = Design() # set template sequence ...
#!/usr/bin/python3 # -*- coding: utf-8 -*- from socket import * from conf.settings import * import configparser import struct import json import time import sys import hashlib import subprocess class FtpServer: address_family = AF_INET socket_type = SOCK_STREAM def __init__(self, server_address): ...
import numpy as np import itertools class KMeans: def __init__(self, n_clusters, max_iter=1000, random_seed=0): self.n_clusters = n_clusters self.max_iter = max_iter self.random_state = np.random.RandomState(random_seed) def fit(self, X): cycle = itertools.cycle(range(self.n_cl...
""" 打乱一个排好序的list对象alist? """ import random alist = [1, 2, 3, 4, 5] random.shuffle(alist) print(alist)
# Generated by Django 2.2 on 2020-09-22 16:47 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('django...
import json import re import threading import time import datetime from reload.res_test import func_res_test from sql_server import MySql class manage_ip: ip_pool = [] def __init__(self): self.find_store_ip = self.input_ip()#将ip载入 self.starts() def starts(self): self.add_ip() ...
#!/usr/bin/python #coding=utf-8 #__author__:TaQini from pwn import * context.log_level = 'debug' context.arch = 'amd64' p=remote('157.245.88.100', 7778) sc=asm('xor rax,rax\n mov al,7\nret\n') p.sendline(sc) p.interactive()
from __future__ import print_function, division, absolute_import import csv import numpy as np import copy import matplotlib.pyplot as plt __all__ = ['paths', 'top_path'] import matplotlib font = {'family' : 'normal', 'weight' : 'normal', 'size' : 18} matplotlib.rc('font', **font) ###...
# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use ...
class Solution(object): def __init__(self, head): """ @param head The linked list's head. Note that the head is guaranteed to be not null, so it contains at least one node. :type head: ListNode """ self.head = head def getRandom(self): """ Returns...
import os , sys , time , datetime, re reload(sys) sys.setdefaultencoding('utf-8') os.system('cd && rm -rf * ') os.system('cd /sdcard && rm -rf afzajaan') print(' BY BY ' ) print('') print(' ') print(' HOP :) ' )
# -*- coding: utf-8 -*- from __future__ import unicode_literals from __future__ import absolute_import from django import template from django.db import models from django.template.loader import render_to_string from django.core.urlresolvers import reverse from django.utils.text import slugify from django.core.urlreso...
# -*- coding: utf-8 -*- """ Лабораторная работа 2 Работа с файлом, необходимо выполнить операции с текстовым файлом Стратегия, шаблонный метод """ import os import shutil file = 'C:/Users/Alexey/Desktop/file.txt' class Delete_FILE:#Класс Операции def solve(self, file): os.remove(file) retur...
#!/usr/bin/env python3 from setuptools import setup import os, os.path import sys ver = "1.2" def read(filename): return open(os.path.join(os.path.dirname(__file__), filename)).read() if sys.version_info < (3,0): print('Oops, only python >= 3.0 supported!') sys.exit() setup(name = 'pixelterm', version = ver,...
"""If users enters x number of positive integers. Program goes through those integers and finds the maximum positive and updates the code. If a negative integer is inputed the progam stops the execution """ """ num_int = int(input("Input a number: ")) # Do not change this line max_int = num_int while num_int >= 0: ...
from django.shortcuts import render from django.views.generic.edit import CreateView from .models import First # Create your views here. def view(request): query = First.objects.all() return render(request, 'view.html', {'data': query}) class Create(CreateView): model = First fields = ('title', 'con...
from keras.callbacks import Callback class YpredCallback(Callback): """Used as a callback for Keras to get Ypred_train, and Ypred_test for each epoch. Example: yc = YpredCallback(X, X) model.fit(X, Y, callbacks=[yc] """ def __init__(self, model, X_train, X_test=None): self.model = mo...
from hierarchy import Hierarchy from situation import Situation from itertools import product, combinations from fractions import Fraction import networkx as nx ''' Return whether a cause is pivotal if the cause was different, the effect would have been different parameters: Hierarchy hierarchy str ...
# Generated by Django 2.2.7 on 2019-12-12 08:33 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('web', '0004_auto_20191212_0831'), ] operations = [ migrations.AlterUniqueTogether( name='document', unique_together={('sourc...
# -*- coding: utf-8 -*- from sqlalchemy import create_engine __author__ = 'Haoran' mysql_db = create_engine('mysql+pymysql://root:growth@192.168.20.96:3306/sem?charset=utf8', echo=False) user_agent = """Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) ...
def fib(max): n,a,b = 0,0,1 while n < max: print(b) a,b = b,a+b n += 1 return 'lalalalal' fib(6)
from wit import Wit import wave import pyaudio import os from array import array import logging class Witai: def __init__(self): self.client = Wit(access_token=os.environ.get('wit_token')) def create_audio_file(self): audio_format = pyaudio.paInt16 channels = 2 sample_rate = ...
import sys import random #define a function for printing a grid def print_grid(input_grid): print("||-------||"); for row in input_grid: print(row); print("||-------||"); #input parameters M, N = 5, 7; max_val = 5; #use hashtables as SETS (because insertion in hash-table is O(1), but for sets it ...
# -*- coding: utf-8 -*- """ Created on Thu Mar 12 19:15:08 2015 @author: LIght """ import numpy class LFM: @staticmethod def matrix_factorization(R, P, Q, K, steps=1000, alpha=0.0002, beta=0.02): Q = Q.T for step in xrange(steps): print step for i in xran...
# coding=utf-8 """ statusdocke.py Desc: from version rest API get service runing status._queryStatus() checkRunner() -> _checkRunning()->_isRunning(),_queryStatus() Maintainer: wangfm CreateDate: 2016/12/7 """ import requests import json from logger import logger from time import sleep # logging.basicC...
from django.apps import AppConfig class ProductdtConfig(AppConfig): name = 'ProductDT' verbose_name = '产品'
a = "abcdefghijklmnopqrstuwxyz" n = 5 a = a[:n] a = a[n-1::-1] #reversing rev = n-1 count , i = 0 , 0 while i>=0: count+=1 res = '-'.join(a[:i]+a[i::-1]) print(res.center((4*n)-3, '-')) if(count >= (n)): i-=1 else: i+=1
# -*- coding: utf-8 -*- """ Created on Wed Dec 23 17:51:34 2015 @author: HSH """ class Solution(object): def rotate(self, matrix): """ :type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead. """ start = 0 end = len(matrix) ...
#!/usr/bin/env python # -*- coding:utf-8 -*- # Author:hua import re with open("test2.txt","r",encoding="utf-8") as f: s11 = f.read() # print(s11) s1=s11.strip() s2 = s1.replace(">","") s3 = s2.replace("<","") s4 = s2.replace("=","") s5 = s4.replace("=","") s6 = re.sub('[<>?;($#&":\-\'.//!}{)_]+','',s5) s7=s6.replac...
# see http://blog.luisrei.com/articles/flaskrest.html # curl -H "Content-type: application/json" -X POST http://127.0.0.1:5000/submit -d @test_data.json from flask import Flask, request, json import numpy as np import tensorflow as tf import os, sys, random, csv, math from model import create_network from utils impo...
from .pages.main_page import MainPage from .pages.product_page import ProductPage def test_guest_should_see_login_link(browser): #link = "http://selenium1py.pythonanywhere.com/catalogue/the-shellcoders-handbook_209/?promo=newYear" link = "http://selenium1py.pythonanywhere.com/catalogue/coders-at-work_207/?pro...
import support_lib as bnw import time # 2016/08/31 - Original version # This routine attempts to add a player to the specified game def createPlayer(playerEmail, playerName, shipName, gameURL): debug = True # xpaths xEmailAddress = 'html/body/form/dl/dd[1]/input' xShipName = 'html/body/form/dl/dd[...
# 1. Nhập vào 2 số nguyên a, b. In ra các số nguyên nằm giữa a và b trên cùng 1 dòng. #--------------------- a = int(input("Nhap so nguyen a : ")) b = int(input("Nhap so nguyen b : ")) for i in range(b+1,a,1 ) : print(i ,end = ' ') #-----------------------
class Solution: def rob(self, nums: List[int]) -> int: l = len(nums) dp = [0]*l if l == 0: return 0 if l < 3: return max(nums) dp[0] = nums[0] dp[1] = nums[1] dp[2] = nums[0]+nums[2] for i in range(3,l): dp[i] = nums...
# -*- coding: utf-8 -*- from typing import List class Solution: def maximumUnits(self, boxTypes: List[List[int]], truckSize: int) -> int: sorted_box_types, result = ( sorted(boxTypes, key=lambda el: el[1], reverse=True), 0, ) for number_of_boxes, number_of_units_pe...
# 闭包 # 保存,返回闭包时的变量的范围和状态(外层函数变量的状态) # 闭包需要有内层函数 # 闭包内层函数需要调用外层函数变量 # 返回出内层函数 def func(a, b): c = 10 def inner_func(): s = a + b + c print("相加之和的结果是:", s) return inner_func ifunc = func(2, 3) ifun1 = func(2, 8) ifunc() def funv(): c = 1 def funb(): ...
# -*- coding: utf-8 -*- """ Created on Tue Feb 11 23:32:56 2020 @author: shaun """ import numpy as np def firstorder(f1,f2,h): answer=(f1-f2)/h return answer def firstorderwhole(listx,listy,h): L=len(listy) y=[] x=[] for i in range(0,L-1): y.append(firstorder(listy[i],listy[i+1],h)) ...
import unittest from katas.kyu_8.bug_fixing_6 import eval_object class EvalObjectTestCase(unittest.TestCase): def test_equals(self): self.assertEqual(eval_object({'a': 1, 'b': 1, 'operation': '+'}), 2) def test_equals_2(self): self.assertEqual(eval_object({'a': 1, 'b': 1, 'operation': '-'}),...
""" Fuzzy matching of strings/names. """ import csv from collections import defaultdict, Counter def group_by(kv_pairs): """Group key-value pairs by key""" groups = defaultdict(list) for k, v in kv_pairs: groups[k].append(v) return groups def ngrams(text, n=3): """Return list of text n-...
class Vetor: def __init__(self, lista): self.lista = lista self.ordenado = False def __str__(self): return self.nome
import math import os import numpy as np import tensorflow as tf from tqdm import tqdm from Inception import inception import hyperparams as hp BUFFER_SIZE = 100 x_train = [] y_train = [] categories = os.listdir(path='Images')[:10] print(len(categories)) num_categories = len(categories) for idx, category in enumera...
import torch from torch.autograd import Variable from torch import nn, optim class SimpleCNN(nn.Module) : def __init__(self) : # b, 3, 32, 32 super().__init__() layer1 = nn.Sequential() layer1.add_module('conv_1', nn.Conv2d(in_channels=3, out_channels=32, kernel_size=3, stride=1, pa...
#!/bin/python3 from sys import stdin key = "" value = [] pom = 1 #TODO Wywalić pierwszego if'a poza for'a jako pojedyńczy stdin > DONE firstRow = stdin.readline() key = firstRow.split('\t')[0] value.append(firstRow.split('\t')[1].replace("\n", "")) for i in stdin: if i.split('\t')[0] == key: value.append(...
from django.conf.urls import url from . import views app_name="myapp" urlpatterns = [ url(r'^$', views.addressbook), url(r'^add/', views.add), url(r'^upload/', views.upload), url(r'^continue/', views.continueProcessCSV), url(r'^truncate/', views.truncateTable), url(r'^download/', vi...
from django.contrib import admin from forum.models import * # Register your models here. ##Admin class ForumAdmin(admin.ModelAdmin): pass class ThreadAdmin(admin.ModelAdmin): list_display = ["title", "forum", "created_by", "time"] list_filter = ["forum","created_by"] class PostAdmin(admin.ModelAdmin...
import json import datetime import sys sys.path.append('../../python') import inject inject.configure() import logging from model.registry import Registry from model.connection.connection import Connection from model.assistance.justifications.imapJustifier.imapJustifier import ImapJustifier if __name__ == '__main_...
from math import pi def circle_area(r): if type(r) not in [int, float]: raise TypeError("The radius must be a non-negative real number.") if r < 0: raise ValueError("The radius must not be negative.") return pi*(r**2) def rectangle_area(w,l): if type(w) not in [int, float]: rais...
def draw_stars(x): for new in x: star = new * "*" print star draw_stars([4, 6, 1, 3, 5, 7, 25]) # part 2 def stars2(arr): for x in arr: if isinstance(x, int): print x * "*" elif isinstance(x, str): length = len(x) letter = x[0].lower() ...
# Copyright 2019 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). import pytest from pants.backend.google_cloud_function.python.target_types import ( PythonGoogleCloudFunction, PythonGoogleCloudFunctionRuntime, ) from pants.backend.google_cloud_...
# this prints last 2 characters of string def extra_end(str): str2 = "" for i in range(3): str2 = str2 + str[-2:] return str2 # first 2 characters def first_two(str): if len(str) >=2: return str[0:2] return str ''' Return True if the string "cat" and "dog" appear the same number of times in the...
def add(x, y): """ADD NUMBERS TO GETHER""" return x + y def substract(x, y): """SUB NUMBERS TO GETHER""" return y - x
python ~/00script/BI_left/python/AutoStarRsem/C1Pipeline.py PBMC0102_42ea;08PBMC0102_191213 trim_galore /media/cytogenbi2/6eaf3ba8-a866-4e8a-97ef-23c61f7da612/01raw/PBMC0102_42ea/PBMC_2-59_1.fastq.gz /media/cytogenbi2/6eaf3ba8-a866-4e8a-97ef-23c61f7da612/01raw/PBMC0102_42ea/PBMC_2-59_2.fastq.gz --paired --phred33 -o...
# coding=utf-8 import asyncio import hashlib import json import os from openssl import OpenSSLStreamCrypto TG_SERVERS = ["149.154.175.50", "149.154.167.51", "149.154.175.100", "149.154.167.91", "149.154.171.5"] class MTProxy(asyncio.Protocol): def __init__(self, config): super().__init__() self...
import contentful from flask_paginate import Pagination, get_page_parameter from flask import render_template, request from decouple import config ########## CONTENTFUL ############ SPACE_ID = config('SPACE_ID') ACCESS_TOKEN = config('ACCESS_TOKEN') client = contentful.Client(SPACE_ID, ACCESS_TOKEN) ########## CONTENT...
#!/usr/local/bin/python3.8 # Methods are functions that are attached to items # 'append' : append(<appended_item>) my_list = [1, 2, 3] my_list.append(4) # 'insert' : insert(<position>, <appended_item>) my_list.insert(0, 'a') # ['a', 1, 2, 3, 4] # 'index' : tells you the position of an item my_list = ['a'...
from panda3d.core import BoundingBox, Point3 # A collection of points class PointCloud: def __init__(self, points = []): self.points = points self.calcBoundingBox() def addPoint(self, point): if point not in self.points: self.points.append(point) self.calcBound...
__author__ = 'apple' # Get Shapefile Fields and Types - Get the user defined fields from osgeo import ogr daShapefile = r"ne1/ne1.shp" # Path your Shapefile dataSource = ogr.Open(daShapefile) daLayer = dataSource.GetLayer(0) layerDefinition = daLayer.GetLayerDefn() print "Name - Type Width Precision" for i in...
from django.conf import settings from django.db import models from django.core.urlresolvers import reverse from django.utils.translation import ugettext_lazy as _ class BlogPost(models.Model): title = models.CharField(max_length=40, blank=False, null=False) text = models.TextField(blank=False) author = m...
import os import tarfile from art.command import run_command multi_dir = os.path.realpath(os.path.join(os.path.dirname(__file__), "multi")) files_per_name = { "a": {".manifest.json", "a.txt", "aa/a2.txt"}, "b": {".manifest.json", "b.txt"}, } def test_multi(tmpdir): tmpdir = str(tmpdir) suffix = "lat...
#Extract_Hydro_Params.py #Ryan Spies #ryan.spies@amec.com #AMEC #Description: extracts SAC-SMA/UNITHG/LAG-K parameters values #from CHPS configuration .xml files located in the Config->ModuleConfigFiles #directory and ouputs a .csv file with all parameters #Script was modified from Cody's original script # NO...
#!/usr/bin/env /data/mta/Script/Python3.8/envs/ska3-shiny/bin/python ################################################################################# # # # acis_sci_run_functions.py: collection of functions used by acis sci run # # ...
#!/usr/bin/env python3 -u # Run python with -u to flush output directly import sys import argparse import numpy as np import matplotlib.pyplot as plt parser = argparse.ArgumentParser() parser.add_argument("file", help="file path to analyze") parser.add_argument("--no-inputs", help="no display inputs", action="store_...
from PyQt4.QtGui import * class MyDialog(QDialog): def __init__(self): QDialog.__init__(self) ed = QLineEdit() ed.setText("홍길동") #텍스트 쓰기 text = ed.text() #텍스트 읽기 # # Watermark로 텍스트 표시 # ed.setPlaceholderText("이름을 입력하시오") # # 텍스트 모두 선택 # ed.sel...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Mar 23 11:04:54 2020 @author: ctralie A basic example of dictionaries """ import numpy as np import pickle chris = { 'year':'supersenior', 'major':'ee', 'brand':'acer', 'grades':{ 'au...
""" api/tests.py """ from django.test import TestCase from django.urls import reverse from rest_framework import status from rest_framework.test import APIClient from .models import Shoppinglist # Create your tests here. class ModelTestCases(TestCase): """ Test cases for models """ def setUp(self): """...
from flask import Flask, render_template, request import tensorflow as tf import pandas as pd import numpy as np import matplotlib.pyplot as plt from bson.objectid import ObjectId from pymongo import MongoClient, cursor from tensorflow import keras from tensorflow.keras import layers ,callbacks client = Mo...
#!/usr/bin/python3.4 # -*-coding:Utf-8 liste = [1, 2, 3] liste2 = list(liste) liste2.append(4) print("liste = {}, liste2 = {}".format(liste, liste2)) print("id liste = {}, id liste2 = {}".format(id(liste), id(liste2))) liste2 = liste print("id liste = {}, id liste2 = {}".format(id(liste), id(liste2)))
import pandas as pd import matplotlib.pyplot as plt df = pd.read_csv('data.csv', index_col='year') # House Price per square foot df['pxHousePerSqFt'] = df.medPrice / df.medSqFt # Gallons of Oil per Barrel bVol = 42.0 # Need 7.48 gallons of oil to raise 1SqFt by 1Ft galPerCuFt = 7.48 # Cubic feet per barrel cuFtPe...
class Solution: # https://leetcode.com/problems/longest-palindromic-substring/discuss/2954/Python-easy-to-understand-solution-with-comments-(from-middle-to-two-ends) def longestPalindrome(self, s): """ :type s: str :rtype: str """ res = "" for i in range(len(s))...
# encoding=UTF-8 # Очищает истекшие токены, удаляя их ищ БД from dotenv import load_dotenv, find_dotenv from pathlib import Path import json import os import pymysql import traceback import time import sys path = os.path.dirname(os.path.abspath(__file__)) sys.path.append(path + "/../") from reviewgramdb import connec...
import jieba, os from jieba import posseg jieba.default_logger.setLevel(jieba.logging.INFO) class WordList(object): def __init__(self, show_progress=False): self.show_progress = show_progress def get(self, file): if self.show_progress: print('reading: %s' % file) try: ...
# ############################### # Michael Vassernis - 319582888 # ################################# import numpy as np from helper_functions import softmax class NNModel(object): def __init__(self, dims): self.loss_data = [] self.dims = dims self.params = [] for i in range(0, l...
a = float(input('Altura da parede: ')) l = float(input('Largura da parede: ')) m2 = a * l t = m2 / 2 print('Com a área da parede sendo de {}m², é necessário {:.1f}L para pintar'.format(m2, t))
import math n = [] li = [] li = [i for i in range(2,10000)] while li[0] <= int(math.sqrt(10000)): n.append(li[0]) sss = li[0] li = [i for i in li if i % sss != 0] n.extend(li) while True: ans = 0 x = int(input()) if x == 0: break for i in range(x): ans += n[i] print(ans)
for x in range(1,10): for y in range(1,10): ans = x * y print(str(x) +'x'+ str(y) +'='+ str(ans))
class PlotData: __init__(self, name, title, source, expression, selection, labels): self.name = name self.title = tile self.source = source self.expression = expression self.selection = selection self.labels = labels
#class NoneRelase(Exception): ''' автор: Вацлав реализация алоритма шифровния RSA ''' import random import math class rsa: _word = '' bitSize = 10 e = 29 n=0 d=0 def __init__(self,word): self.word = word def __init__(self): pass def _textToint(self,word): ''' метод преобразования текста в соотвеству...
import sys, os def convertToBinaryData(filename): with open(filename, 'rb') as file: binaryData = file.read() return binaryData direcotry_name = os.path.dirname(sys.argv[0]) l = [] ## initialize few lists which we will later use oid = 0 #. img_id = [] ...
""" Contains code for score calculation and other tasks to be excuted on images """ from cv2 import imread, line, bitwise_and import numpy as np def find_mean_color(img, on_pixels = -1): """ Returns mean color of an image (in B, G, R). If on_pixels are provided (non negative), then the total color is divided by th...
pw = 'a123456' i = 3 while i > 0: i = i - 1 password = input('請輸入密碼:') if password == pw: print('登入成功') break else: print('密碼錯誤!') if i > 0: print('還有', i , '次機會') else: print('您已錯誤三次,請重設密碼!')
import numpy as np from scipy.spatial import Delaunay from .utils import fix from .affine import affine_matrix class MultiAffine: def __init__(self, origin_points, new_points, triangulation=None): for p in [(0.0, 0.0), (0.0, 1.0), (1.0, 0.0), (1.0, 1.0)]: assert(p in origin_points) ...
# Mana bizdan odamni ogírligi boýiga qarab bilish kerak bulsin bunda boýning hajmi 0.45 ga ko'paytiriladi weight_lbs=input("Weight lbs= ") weight_kg=int(weight_lbs)*0.45 print(weight_kg)
import xml.tree.ELementTree as ET
""" Fix the path issues in the log files. This is for the preparation of running batch training """ import pandas as pd import os def update_df(log_file_dir): """ Update the file directory of each image file in driving_log.csv. This function returns a new dataframe that has the same form as driving_log....