text
stringlengths
38
1.54M
class Solution(object): def dailyTemperatures(self, T): """ :type T: List[int] :rtype: List[int] """ wait = [0]*len(T) # days to wait for a warmer day stack = [] # list of tuples (temp, index) for i in range(len(T)): if stack an...
import RPi.GPIO as GPIO class TrackSensor(object): def __init__(self, db): """ setting 5-way's pin number to variable :param db: setup.py's pin numbers """ self.left2 = db['track_left2'] self.left1 = db['track_left1'] self.center = db['track_center'] ...
#abs 절댓값 print(abs(3)); print(abs(-3.5)) #all 모두 참이면 Treu / 하나라도 거짓이 있으면 False print(all([0,3,4,5])) #any 하나라도 참이면 True / 모두 거짓일 때 False print(any([1,2,3,0])) #dir print(dir([1,2,3])) #divmod a를 b로 나는 몫과 나머지를 튜플 형태로 돌려줌 print(divmod(7,3)) #enumerate 순서가 있는 자료형을 입력으로 받아 인덱스 값을 포함하는 enumerate 객체를 돌려줌 for i, name in ...
# -*- coding: utf-8 -*- import sys, os sys.path.append('../siftsample') # ここまでおまじない import numpy, pylab from siftsample import SiftSample class Prob25(SiftSample): def _process_image(self, resultname, params): """ 画像を処理してファイルに結果を保存する """ if self._is_color: self.convert_grey() ...
import sys, time class Display: def __init__(self, width, height, xoffset=0, yoffset=0, reversehori=False, reversevert=False): self.width = width self.height = height self.xoffset = xoffset self.yoffset = yoffset self.reversehori = reversehori self.reversevert = reve...
#!/usr/bin/env python # -*- coding: utf-8 -*- #makedocument_ns.py ###example################################ #python makedocument_ns.py directory_path ########################################## import sys from github import Github #get token t = open('token','r') token = t.read() token = token.rstrip('\n') #Create Gi...
from flask import Flask, redirect, url_for app = Flask(__name__) @app.route('/') def index(): return '<a href="/goto">Go to</a>' @app.route('/goto') def goto(): return redirect(url_for('user_page')) @app.route('/user') def user_page(): return 'User page'
import datetime as dt import logging import os import time from typing import Union import discord from aiomysql import IntegrityError from discord.ext import commands from discord_slash.context import SlashContext import src.utils as utils from src.plotting import plot_bar_daily, plot_csv logger = logging.getLogger...
import numpy as np def read_input(filename): input_file = open(filename, "r") k, t = input_file.readline().strip().split(" ") dnas = input_file.read().splitlines() input_file.close() return int(k), int(t), dnas def profile_most_probable_kmer(genome, k, profile_matrix): n = len(genome) most...
#!/usr/bin/env python # encoding: utf-8 """ Copyright (c) 2014 tiptap. All rights reserved. """ import time import traceback import twython import logging log = logging.getLogger(__name__) RATE_LIMIT_RESOURCES = ["statuses", "followers", "search", "users"] class TwitterClient(object): def __init__(self, appKey...
''' Spiral copy ''' import numpy def spiral_copy(mat): if len(mat) == 0: return [] rows = len(mat) cols = len(mat[0]) result = [] for j in range(cols): result.append(mat[0, j]) for i in range(1, rows): result.append(mat[i, cols - 1]) for j in range(cols - 2, -...
#!/usr/bin/python import sys # Open a file to be turned into CG-only gff fileHandle = open ( sys.argv[1] ) # Create an output file OutFileName = sys.argv[1] + '_CG-only.gff' OutFile = open(OutFileName, 'w') # Give your output file headers in the first line OutFile.write("Chr\tReads\tContext\tStart\tEnd\tMC\tStr...
from django.db import models from user.models import User # Create your models here. class Event(models.Model): class Meta: verbose_name = "事件" verbose_name_plural = "事件" index_together = [ ['event_type', 'created_at'], ['created_at', 'vote_count'] ] t...
""" 之前的程序中都是根据操作数据的函数或语句块来设计程序的。这被称为面向过程的编程。 还有一种把数据和功能结合起来,用称为对象的东西包裹起来组织程序的方法。这种方法称为面向对象的编程理念。 类和对象是面向对象编程的两个主要方面。类创建一个新类型,而对象这个类的实例。这类似于你有一个int类型的变量,这存储整数的变量是int类的实例(对象)。 对象可以使用普通的属于对象的变量存储数据。属于一个对象或类的变量被称为域。 对象也可以使用属于类的函数来具有功能。这样的函数被称为类的方法。 域和方法可以合称为类的属性。 域有两种类型--属于每个实例/类的对象或属于类本身。它们分别被称为实例变量和类变量。 类使用class关键字创建。类的...
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU...
import numpy as np from matplotlib import pyplot as plt #x0=-1.3604886221977293 #y0=58.22147608157934 #z0=-1512.8772100367873 #a=0.00016670445477401342 data=np.loadtxt('dish_zenith.txt') x_data=data[:,0] y_data=data[:,1] z_data=data[:,2] # A: c1+c2*x+c3*x*x+c4*y+c5*y*y A=np.zeros([len(x_data),4]) A[:,...
import time import shelve import atexit import threading from UserDict import UserDict from datetime import datetime from celery import conf from celery import registry from celery.log import setup_logger from celery.exceptions import NotRegistered class SchedulingError(Exception): """An error occured while sche...
from .code_climate_formatter import CodeClimateFormatter from .html_report_formatter import HTMLReportFormatter
#!/usr/bin/env python # -*- coding:utf-8 -*- # @Filename: test.py # @Project: GuideNet # @Author: jie # @Time: 2021/3/16 4:47 PM import os os.environ["CUDA_VISIBLE_DEVICES"] = '0' import torch import yaml from easydict import EasyDict as edict import datasets import encoding def test(): net.ev...
import os import gemicai.data_iterators as test import torchvision import unittest raw_dicom_directory = os.path.join("..", "examples", "dicom", "CT") raw_dicom_file_path = os.path.join(raw_dicom_directory, "325261597578315993471860132776680.dcm.gz") wrong_dicom_file_path = os.path.join("..", "000001.gemset") dicom_d...
# This code is the same we have discussed in CSV file. import unicodecsv enrollments_filename = '/datasets/ud170/udacity-students/enrollments.csv' ## Longer version of code (replaced with shorter, equivalent version below) # enrollments = [] # f = open(enrollments_filename, 'rb') # reader = unicodecsv.DictReader(f...
from __future__ import annotations from copy import deepcopy from typing import TypeVar, TYPE_CHECKING, List, cast, Any, NoReturn, Optional from errors.not_impl_error import NotImplError from keywords import * from position import Position if TYPE_CHECKING: from context import Context from lang_types.lang_bo...
Q = int(input("Quantidade de jogos (1 / 2): ")) j1 = float(input("Valor do jogo 1: ")) if(Q == 2): j2 = float(input("Valor do jogo 2: ")) total = j1 + (j2 * 0.75) else: total = j1 print(round(total, 2))
from bs4 import BeautifulSoup import csv import requests import re def scrape(next_page_url): headers = {'User-Agent': 'Mozilla/5.0'} response = requests.get(next_page_url, headers=headers) soup = BeautifulSoup(response.text, "html.parser") return soup def getDetailsInPage(url): soup = scrape(url)...
from django.conf.urls import patterns, url from animals import views urlpatterns = patterns('', url(r'^$', views.Index.as_view(), name='index'), url(r'^(?P<pk>\d+)/$', views.AnimalDetail.as_v...
from django import forms from django.forms import ModelForm from .models import Order class OrderUpdate(forms.ModelForm): class Meta: model = Order fields = ('end_at', 'plated_end_at') widgets = { 'end_at': forms.DateTimeInput(attrs={'class':'form-control'}), ...
# coding:utf-8 import socket T1="""HTTP/1.1 200 OK\r\n\r\n <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Null</title...
#!/usr/bin/env python # # Copyright 2007 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law o...
import cv2, time, pandas from datetime import datetime first_frame = None statu_list = [None, None] times = [] df = pandas.DataFrame(columns=["Start" , "End"]) video = cv2.VideoCapture(0) while True: check, frame = video.read() statu = 0 gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) gray = c...
#!/usr/bin/python #show "Hello World on the LCD screen"" # CByrer import subprocess import Adafruit_CharLCD as LCD import time lcd = LCD.Adafruit_CharLCDPlate() Name = subprocess.check_output(['hostname']).strip() displayText = Name IP = subprocess.check_output(["hostname", "-I"]) refresh = True while (True): ...
# Create your views here. #coding=utf-8 from django.http import * from django.shortcuts import * import datetime def hello(request): return HttpResponse("hello word") def loginAction(request): """ :param request: :return: """ time = datetime.datetime.now() return render_to_response('log...
class Dog(object): __instance = None#类属性 用来保存对象 __flag = True #默认第一次 def __init__(self,name): if Dog.__flag: self.name = name Dog.__flag = False def __new__(cls,*ares,**kwargs): if cls.__instance == None: cls.__instance = super().__new__(cls)#把对象保存起来 return cls.__instance else: #把保存的对象之间返回 不需要...
import os from enum import Enum from logging import Logger from typing import Optional import pandas as pd from mdrsl.data_handling.one_hot_encoding.encoding_book_keeping import EncodingBookKeeper from mdrsl.data_handling.one_hot_encoding.encoding_io import store_encoding_book_keeper from experiments.utils.experiment...
import os import django import requests from datetime import datetime from bs4 import BeautifulSoup from my_app.models import Stats,News def populate_stat(): os.environ.setdefault('DJANGO_SETTINGS_MODULE','corona.settings') django.setup() url = "https://www.worldometers.info/coronavirus/" page = reques...
from pwn import * context.terminal = ['tmux', 'splitw', '-h'] p = process("./bcloud") #p = remote("training.jinblack.it", 2016) gdb.attach(p, ''' #b *0x08048978 b *0x08048a19 b *0x8048a8c''') context.log_level = 'debug' f = elf.ELF('./bcloud') libc = elf.ELF('./libc-2.27.so') raw_input("Wait") readGot = 0x0804b...
# -*- coding:utf-8 -*- # ------------------------------- # ProjectName : autoDemo # Author : zhangjk # CreateTime : 2020/6/23 20:32 # FileName : 2 # Description : # -------------------------------- def gys(a,b): if a < b: b,a = a,b while a%b!=0: a,b = b,a%b print(b) ages = [5, 16, 19, 2...
# -*-coding:utf-8-*- from flask_sqlalchemy import SQLAlchemy from flask_mail import Mail from flask_assets import Environment db = SQLAlchemy() mail = Mail() assets_env = Environment()
import random num = int(input()) lst = random.sample(range(1, 20), 10) # PRE: `num` is an integer, `lst` is a list of integers of size N > 0 i = 0 num_found = False # INVARIANT: i <= len(lst), `num_found` == False if `num` not in {lst_0, lst_1, ..., lst_i-1}, otherwise `num_found` == True # AFTER INITIAL...
from enum import Enum class Dir(Enum): UP = 0 DOWN = 1 LEFT = 2 RIGHT = 3 class State(Enum): CLEAN = 0 WEAKENED = 1 INFECTED = 2 FLAGGED = 3 DIR_ORDER = [Dir.UP, Dir.RIGHT, Dir.DOWN, Dir.LEFT] def turn(dir, diff): return DIR_ORDER[(DIR_ORDER.index(dir) + diff) % len(DIR_ORDER...
# This program prompts a user to enter an integer and reports whether the integer is a palindrome or not # A number is a palindrome if its reversal is the same as itself. def reverse(number): position1 = number % 10 remainder1 = number // 10 position2 = remainder1 % 10 remainder2 = remainder1 // ...
import random import redis from configs import products def main(): r = redis.client.StrictRedis(db=0) r.flushdb() list_products = products random.shuffle(products) product_men = products[0:400] random.shuffle(products) product_brand1 = products[0:200] product_brand2 = products[200...
import pymongo import datetime import os def get_result(f,t,s,r): client = pymongo.MongoClient() repo = client.repo repo.authenticate('minteng_tigerlei_zhidou', 'minteng_tigerlei_zhidou') # user will set the grade they want transport=t food=f safety=s rent=r #find the fitted area def if_fitted(A,requireme...
from wave_app import db class User(db.Model): __tablename__ = 'User' id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(20), nullable=False) password = db.Column(db.String, nullable=False) level = db.Column(db.String(15), nullable=False) waves = db.relationship('Se...
# Assignment_1, 11 Aug 14, 05:09 __author__ = 'subin' # Function For Addition def Addition(First_Input,Second_Input): Add=First_Input+Second_Input return Add # Return result of Addition # Function For Subtraction def Subtraction(First_Input,Second_Input): Sub=First_Input-Second_Input return Sub # Return...
__copyright__ = """\ (c). Copyright 2008-2020, Vyper Logix Corp., All Rights Reserved. Published under Creative Commons License (http://creativecommons.org/licenses/by-nc/3.0/) restricted to non-commercial educational use only., http://www.VyperLogix.com for details THE AUTHOR VYPER LOGIX CORP DISCLAIMS ALL WARRA...
class Node: def __init__(self, inputVal): self.value = inputVal self.next = None class Stack: def __init__(self): self.top = None def push(self, value): newnode = Node(value) if self.top == None: self.top = newnode else: newnode.next...
import matplotlib.pyplot as plt import matplotlib.image as mpimg import numpy as np import glob, os, sys import xml.etree.ElementTree as ET import math STEP = 8 # The path in the console arguments. path = sys.argv[1] imgs= sorted(glob.glob(os.path.join(path, '*.jpg')) + glob.glob(os.path.join(path, '*.JPG'))) xm...
"""Make a time table acript that ask user the following things: 1- how many tables you want to print 2- what should be user starting point 3 = ending point point of table NOTE: tables should be print horizentally """ if __name__ == "__main__": table_no = int(input('Enter table no: ')) start = ...
import numpy as np interestRate = 0.07 numberOfMonths = 25*12; principalBorrowed = 3500000 principal2Pay = np.ppmt(interestRate/12, 1, numberOfMonths, principalBorrowed); interest2Pay = np.ipmt(interestRate/12, 1, numberOfMonths, principalBorrowed); print("Loan amount:%7.2f"%principalB...
from MainWindows.MainWindow import MainWindow from SubWindows.SubWindow import SubWindow import tkinter as tk class Application(): def __init__(self,master=None): self.main_window = MainWindow(master) self.sub_window = SubWindow() self.change_command() def change_command(self...
from drf_yasg.utils import swagger_auto_schema from rest_framework import status from rest_framework.decorators import action from rest_framework.viewsets import ModelViewSet from rest_framework.permissions import IsAuthenticated from rest_framework.response import Response from authentication.serializers import Curre...
#while roof 돌려서 lew line으로 만든다 #len(board)가 일자 #count 가 place에 도달했을떄 new에다가slash추가 #r.strip = 오른쪽에있는가 사라진다 class Molecule: def __init__(self, row, column): grid = [] board = '' for x in range(row): grid.append(('. ' * column)[:-1]) ...
from enum import Enum class VariableType(Enum): variable = 0 temporary = 1 user_function = 2 builtin_function = 3 class ScopeType(Enum): top = 0 function = 1 sub = 2
from itertools import cycle from sys import argv if argv[1][-4:] == '.txt': route = open(argv[1], 'r').read().strip().split(',') else: route = argv[1].split(',') options = 'nw', 'n', 'ne', 'se', 's', 'sw' def optimize(route): for option in options: counter_option = (options + options)[options.in...
#importing of the neccessary modules and method #the os path module implements some useful functions on pathnames and directory access #imports that are making big changes from os.path import abspath, dirname, join from flask import flash, Flask, Markup, redirect, render_template, url_for from flask.ext.sqlalchemy im...
import numpy as np import os import cv2 from tqdm import tqdm import tables def check_widefield_frame_times(base_directory): # Load Widfield Frame Times widefield_frame_times = np.load(os.path.join(base_directory, "Stimuli_Onsets", "Frame_Times.npy"), allow_pickle=True)[()] widefield_frame_times = list(...
# %load q01_get_total_deliveries_players/build.py # Default imports import numpy as np batsman_input= b'SR Tendulkar' ipl_matches_array =np.genfromtxt('data/ipl_matches_small.csv', dtype='|S50', skip_header=0, delimiter=',') def get_total_deliveries_played(batsman_input): batsman=ipl_matches_array[:,13] ...
from django.utils import timezone from django.db import models from django.contrib.auth.models import BaseUserManager from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin # CUSTOM USER AUTH ############################################################################### class UserManager(BaseUserMa...
#!/usr/bin/env python3 """Module implementing a CLI for the Cook scheduler API. """ import logging import signal import sys from cook import util from cook.cli import run from cook.util import print_error def main(args=None, plugins={}): if args is None: args = sys.argv[1:] try: result = ru...
# C3 == 2 "String" # C17 == 15 "В заданому тексті замінити слова заданої довжини визначеним рядком." # Створити клас, який складається з виконавчого методу, що виконує дію текстовим рядком (п.3), тип якого визначено варіантом (п.2). # Необхідно обробити всі виключні ситуації, що можуть виникнути під час виконання прогр...
# # Python script that takes a folder and a file # and creates the galaxy html # # @author James Boocock. import os galhtmlprefix = """<?xml version="1.0" encoding="utf-8" ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://w...
""" Este modulo contiene todo lo necesario para dar soporte al menu de inicio, de pausa y de compra """ import pygame class Shop(): """ Esta clase da soporte a la tienda del juego """ def __init__(self, screen, settings): self.screen = screen self.settings = settings # Establece...
import cx_Oracle as c from flask import Flask,render_template, request,make_response app=Flask(__name__) @app.route('/') def index(): return render_template('index.html') @app.route('/form',methods=['POST']) def form(): return render_template('form.html') @app.route('/store',methods=['POST']) de...
# -*- coding: utf-8 from __future__ import unicode_literals from httplib import responses from flask import current_app as app from flask import Blueprint, jsonify, request from www.content import repository, exceptions from www.main.serializers import serialize from www.main.exceptions import ApiError from www.decora...
# Databricks notebook source # MAGIC %md # MAGIC ScaDaMaLe Course [site](https://lamastex.github.io/scalable-data-science/sds/3/x/) and [book](https://lamastex.github.io/ScaDaMaLe/index.html) # MAGIC # MAGIC This is a 2019-2021 augmentation and update of [Adam Breindel](https://www.linkedin.com/in/adbreind)'s initial ...
# Python for Healthcare ## 500 Cities Linear Regression ### Import Standard Libraries import os # Inlcuded in every script DC! import pandas as pd # Incldued in every code script for DC! import numpy as np # Incldued in every code script for DC! ### Set working directory to project folder os.chdir("C:/Users/drewc/Gi...
from django.contrib.auth.forms import AuthenticationForm, UsernameField from django import forms from django.contrib.auth import ( authenticate, get_user_model, password_validation, ) from django.contrib.auth.hashers import ( UNUSABLE_PASSWORD_PREFIX, identify_hasher, ) from django.contrib.auth.models import Us...
# -*- coding: utf-8 -*- """ Created on Wed Jul 28 14:51:32 2021 @author: Hewlett-Packard """ from sklearn.model_selection import KFold from sklearn.feature_extraction.text import TfidfVectorizer from sklearn import svm from sklearn import metrics from sklearn.metrics import confusion_matrix, classification_report imp...
__author__ = 'dowling' import logging ln = logging.getLogger(__name__) from mongokit import Document from model.db import connection from model.db import db class Fridge(Document): structure = { 'content': { unicode: int } } use_dot_notation = True use_autorefs = True ...
from collections import Counter s = input() lettr_freq = Counter(s) most_comn = list(lettr_freq.items()) most_comn.sort(key=lambda t: (-t[1], t[0])) for lettr, freq in most_comn[:3]: print(lettr, freq)
""" Experiment with face detection and image filtering using OpenCV """ import cv2 import numpy as np cap = cv2.VideoCapture(0) face_cascade = cv2.CascadeClassifier('/home/audrey/ToolBox-ComputerVision/haarcascade_frontalface_alt.xml') kernel = np.ones((21,21),'uint8') while(True): # Capture frame-by-frame ret,...
import unittest import smart_match class TestHammingDistance(unittest.TestCase): def setUp(self): smart_match.use('HD') def test_distance(self): self.assertEqual(smart_match.distance('12211','11111'), 2) self.assertEqual(smart_match.distance('hello','heool'), 3) def te...
import sys class Solution(object): def maxSubArray(self, nums): """ :type nums: List[int] :rtype: int """ answer = -sys.maxsize current_sum = 0 for num in nums: current_sum = max(num, current_sum + num) answer = max(answer, current_su...
''' Don't believe everything below... ''' from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import argparse, os import tensorflow as tf from tensorflow.contrib.rnn import BasicLSTMCell from toy_data import prepare_data def next_batch(tr...
import sqlite3 db = sqlite3.connect("world.db") cr = db.cursor() ans = cr.execute("SELECT name FROM country WHERE population > 100000000") print("1-\n", ans.fetchall(), "\n") ans = cr.execute("SELECT name FROM country WHERE name like '%land'") print("2-\n", ans.fetchall(), "\n") ans = cr.execute("SELECT name FROM...
import cv2 import numpy as np class Zoom(object): def __init__(self, window, img): self.window = window self.img0 = img self.img = img self.left_clicked = False self.xm0, self.ym0 = 0,0 cv2.namedWindow(self.window) cv2.setMouseCallback(self.window, self.onmouse) self.img = cv2.resize(img, (850, 1...
''' 70. データの入手・整形 文に関する極性分析の正解データを用い,以下の要領で正解データ(sentiment.txt)を作成せよ. 1. rt-polarity.posの各行の先頭に"+1 "という文字列を追加する (極性ラベル"+1"とスペースに続けて肯定的な文の内容が続く) 2. rt-polarity.negの各行の先頭に"-1 "という文字列を追加する (極性ラベル"-1"とスペースに続けて否定的な文の内容が続く) 3. 上述1と2の内容を結合(concatenate)し,行をランダムに並び替える sentiment.txtを作成したら,正例(肯定的な文)の数と負例(否定的な文)の数を確認せよ. ...
import cmd import textwrap import sys import os #import math #import copy #from pydub import AudioSegment #from pydub.playback import play #from text_utilities import * from item import* from Player import* from json_handler import* from move import* screen_width = 60 ### Title Screen ### def title_screen_selec...
#!/usr/bin/python3 import urllib3, sys, json, os class Recon(): def __init__(self): self.domain = sys.argv[1] self.http = urllib3.PoolManager() try: os.mkdir(sys.argv[1]) except Exception: pass def passive_dns(self): r = self.http.request("GET",f"...
import dash import dash_html_components as html import time from jitcache import Cache cache = Cache() app = dash.Dash(__name__) server = app.server app.layout = html.Div( children=[ html.Button("Submit", id="button"), html.Div(id="output-container-button1", children=[]), html.Div(id="ou...
#!/usr/local/bin/python2.7 # coding=utf8 import sys, os import traceback from inspect import stack sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), '../Config')) sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), '../Utility')) sys.path.append(os.path.join(os.path.dirname(...
import reference import re import random def main(): print("Hello. How are you feeling today?") while True: statement = input("> ") print(translate(statement)) if statement == "quit": break def translate(statement): statement = statement.replace("!", " ") statem...
import boto3 import sys class AWS: def __init__(self, bucket_name, bucket_region): self.bucket_name = bucket_name self.bucket_region = bucket_region self.file_name = file_name self.key key def create_user_bucket(self, bucket_name, bucket_region): client = boto3.clie...
from faker import Faker from .flow_helper import ( authenticity_token, confirm_link, do_request, get_env, otp_code, personal_key, querystring_value, random_phone, resp_to_dom, sp_signout_link, url_without_querystring, ) from urllib.parse import urlparse import logging import ...
# Lifo -> last in first out books = [] books.append("C") books.append("C++") books.append("C#") print(books) print(books.pop()) print(books) print(books[-1]) # print(books.pop()) # print(books.pop()) if not books: print("No books left")
import numpy as np from helpful_functions import * import scipy.optimize as opt from nelder_mead import * def sa1(): """ Write a function that returns the potential energy U=∑i<j (1/r_ij^12 -1/r_ij^6) where r_ij is given at the top of p. 581. Apply Nelder–Mead to find the minimum energy for n=5. Try s...
from urllib.parse import urlparse from starline.sources import Source from starline.sources.common.booru import BooruDataClient from starline.model import Post, PostFile, PostMeta from utils import prepare_logger log = prepare_logger(__name__) class DanbooruDataClient(BooruDataClient): DOMAIN = 'danbooru.donmai...
# Given a sum, find if it exists in the list. # Naive solution would be to use for loops that would require n^2 time # Second solution is to store list elements in dictionary and use them # seond approach will run in 2n time, and would require extra memory. arr_l = [10,3,3,-4,-2,1,3,9] required_sum = 5 dict_arr_l = {...
mytuple=("veena",25,"arya",65,89,"vinu") urtuple=("Shamshil",4563) #print(mytuple) #print(mytuple) #print(mytuple[0]) #print(mytuple[1:3]) #print(mytuple[1:]) print(mytuple+urtuple)
# -*- coding: UTF-8 -*- import tensorflow as tf import numpy as np import pprint class RNN_Model(object): def __init__(self, config, is_training=True): self.keep_prob = config.keep_prob # self.batch_size = tf.Variable(0, dtype=tf.int32, trainable=False) self.batch_size = config.batch_size num_step = config...
#!/usr/bin/python3 """this file stes up a simple flask server """ from flask import Flask, escape, render_template app = Flask(__name__) @app.route('/') def hello_route(strict_slashes=False): """ route for default page """ return ("Hello HBNB!") @app.route('/hbnb') def hbnb_route(strict_slashes=False): ...
# lst=[-2,-1,0,1,2,3,4]#find least +ve missing in # # # # print(1 in lst)#chk for 1 is in list or not # # cnt=1 # for i in range(0,len(lst)): # if cnt in lst:#1 in lst 2 in lst 3 4 5 # cnt+=1#cnt=2,3 # else: # print(cnt ,"is missing least +ve missing integer") # break # # st={1,2,3,3,4} ...
from django.shortcuts import render, redirect, get_object_or_404 from django.http import HttpResponse, JsonResponse from django.contrib.auth.mixins import LoginRequiredMixin from django.contrib.auth.decorators import login_required from django.contrib.auth.decorators import permission_required from django.contrib.auth....
farm_animals = {"sheep", "cow", "hen"} print(farm_animals) for animal in farm_animals: print(animal) print("="*40) wild_animals = set(["lion", "tiger", "panther"]) print(wild_animals) for animal in wild_animals: print(animal) print("="*40) farm_animals.add("horse") wild_animals.add("elephant") print() prin...
"""a = 2 arr = [1, 2, 3] cnt = 0 for i in arr: if a > i: cnt +=1 arr.insert(cnt, a) print(arr) """ n = int(input()) arr_1 = list(map(int, input().split())) m = int(input()) arr_2 = list(map(int, input().split())) for num in arr_1: cnt = 0 for i in arr_2: if num > i: cnt += 1...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Oct 6 20:17:09 2018 @author: tyler """ import numpy as np import sys #%% def karger(G,vertex_label,vertex_degree,size_V): size_V = len(vertex_label) #N = int(size_V*(1-1/np.sqrt(2))) iteration_schedule = [size_V-2] for N in ...
from app.app import app from Users.model import checkJWT from Topics.model import Topics @app.route('/topics',methods = ['GET']) @checkJWT def getTopics(userId): return Topics().getTopics()
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'cat_men.ui' # # Created by: PyQt5 UI code generator 5.15.0 # # WARNING: Any manual changes made to this file will be lost when pyuic5 is # run again. Do not edit this file unless you know what you are doing. from PyQt5 import QtCore, QtGu...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Apr 9 19:49:58 2021 @author: jayesh """ #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Apr 12 08:20:17 2021 @author: jayesh @teammate: Yoseph Kebede """ import numpy as np import copy import math import time import ast import cv2 i...
import requests import tkinter as tk import webbrowser as wb class Application(tk.Frame): def __init__(self, master=None): super().__init__(master) self.master = master self.pack() self.create_widgets() def create_widgets(self): self.vaccine = tk.Button(se...