text
stringlengths
8
6.05M
# show image until 'esc' gets pressed import cv2 as cv img = cv.imread("irene.jpg", cv.IMREAD_UNCHANGED) # opencv에서는 BGR 순서로 색을 numpy에 저장 ESC = 27 cv.imshow('img', img) #윈도우 창이 생성되면서 while True: key = cv.waitKey() print(key) if key == ESC: break # 이거 없으면 바로 실행이 종료된다. 입력값을 받을 때 까지 대기한다. # ms단...
import os import pygame from game import App # Position of game screen x_pos = 300 y_pos = 120 cmd = 'wmic desktopmonitor get screenheight, screenwidth' os.environ['SDL_VIDEO_WINDOW_POS'] = "%d,%d" % (x_pos, y_pos) # Create class to show Start Window class Initial: # Screen size windowWidth = 8...
# Skanda Srikkanth # I pledge my honor that I have abided by the Stevens Honor System # Microsoft (MSFT) and Apple (AAPL) Stock """This program will analyze the open/close, high/low prices of Apple and Microsoft""" # Question: Which company's stock price was more negatively affected by the COVID pandemic, compared to...
"""Setup script for write-me Python package.""" from setuptools import setup, find_packages setup( name='write_me', # package_dir={'': 'write_me', 'readme_generator': 'readme_generator'}, # py_modules=['readme_generator', 'write_me'], packages=find_packages(), entry_points={ 'console_scrip...
# coding: utf-8 # adding javascript and CSS support from flask import Flask, render_template app = Flask(__name__) @app.route("/") def index(): return render_template("index.html") if __name__ == '__main__': app.run(debug = True) ''' in the template file, A special endpoint ‘static’ is used to generate URL ...
import unittest from katas.beta.sum_of_all_arguments import sum_all class SumAllTestCase(unittest.TestCase): def test_equals(self): self.assertEqual(sum_all(6, 2, 3), 11) def test_equals_2(self): self.assertEqual(sum_all(756, 2, 1, 10), 769) def test_equals_3(self): self.assertE...
#!/usr/bin/env python #------------------------------------------------------------------------------ # Copyright 2008-2011 Istituto Nazionale di Fisica Nucleare (INFN) # # Licensed under the EUPL, Version 1.1 only (the "Licence"). # You may not use this work except in compliance with the Licence. # You may obtain a co...
from utils import makeSoup link = 'https://mangadex.org/title/19636/8-tales-of-the-zqn' soup = makeSoup(link) a = soup.find_all('div', class_='chapter-row d-flex row no-gutters p-2 align-items-center border-bottom odd-row') for c in a: print(c) print('_________')
import tensorflow as tf import numpy as np tf.random.set_seed(1) np.random.seed(1) from sklearn.datasets import load_breast_cancer cancer = load_breast_cancer() # more info : https://goo.gl/U2Uwz2 X=cancer['data'] y=cancer['target'] from sklearn.model_selection import train_test_split X_train,X_test,y_train,y_test = t...
# -*- coding:utf-8 -*- import socket import sys import threading clist = [] def main(argc, argv): # メッセージ入力スレッド th = threading.Thread(target=send_loop) th.start() # サーバ起動 ssock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) ssock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) ...
# coding=utf-8 import os import sys import unittest from time import sleep from selenium import webdriver from selenium.common.exceptions import NoAlertPresentException, NoSuchElementException sys.path.append(os.environ.get('PY_DEV_HOME')) from webTest_pro.common.initData import init from webTest_pro.common.model.ba...
# Строим дом class House: """класс дома""" # Первая строка считается описанием класса/метода. Стандарт PEP8 house_size: int; house_weight: int # Локальные атрибуты класса def __init__(self): """инициализатор класса дома""" print("Класс дома создан") def setLocalValues(self, size: in...
# Generated by Django 3.0.8 on 2020-10-26 06:34 from django.conf import settings from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('eshop_products', '0015_product_attribute'), ] op...
import datetime import os import time import torch import torch.utils.data import torchvision import torchvision.models.detection import torchvision.models.detection.mask_rcnn from Utils.coco_utils import get_coco, get_coco_kp from Utils.group_by_aspect_ratio import GroupedBatchSampler, create_aspect_rat...
# program started num1 = int(input("Enter 1st number")) num2 = int(input("Enter 2nd number")) add = num1 + num2 print("The adition of " , num1 , " + " , num2 , " = " , add)
from datetime import datetime from django.views.generic import TemplateView from elections.models import Election class HomeView(TemplateView): template_name = "home.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) election_qs = Election.public_object...
# Copyright 2019 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from pants.core.util_rules.external_tool import ( DownloadedExternalTool, ExternalToolRequest, TemplatedExternalTool, ) from pants.engine.console import Console from pants.engi...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from .ligne import Ligne L4EB_recettes_brutes = Ligne('4EB', 'Micro foncier - recettes brutes') class Micro_Foncier: ''' https://www3.impots.gouv.fr/simulateur/calcul_impot/2020/aides/fonciers.htm https://www.corrigetonimpot.fr/impot-location-vid...
import unittest from Bubble_Sort import bubble_sort class BubbleSortTest(unittest.TestCase): def test_Bubble_Sort(self): self.assertEquals(bubble_sort([8,1,2,3,4,5,6,7]),[1,2,3,4,5,6,7,8]) self.assertEqual(bubble_sort([10,5,90,0,10]), [0,5,10,10,90]) self.assertEqual(bubble_sort([64, 34, 2...
from pywebio import * from pywebio.output import * from pywebio.input import * def generate_name(car_info): ''' Customized algorithm used to genearte a name (type: str) from input data (type: dict) This demo implements a very simple naming rule. ''' if car_info['year'] >= 2020: return 'Gold...
from configparser import ConfigParser from threading import Lock class Database(ConfigParser): """ Абстракция над ConfigParser Необходимо использовать как singleton, иначе может произойти потеря данных при использовании двумя разными скриптами Все переменные хранятся в нижнем регистре, соответственно рег...
# -*- coding: utf-8 -*- # Generated by Django 1.10.6 on 2017-05-12 15:58 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.Crea...
# The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. # Find the sum of all the primes below two million. # Comments Section: # - Straight forward algorithm using the fact that (if A divibes B) that implies that (A <= sqrt(B)) import math as m def isprime(x): for i in range(2,int(m.sqrt(x))+1): if x %...
import tensorflow as tf from tensorflow.contrib.layers import fully_connected from my.tensorflow.nn import linear_logits, get_logits, softsel from tensorflow.python.ops import tensor_array_ops, control_flow_ops from my.tensorflow.rnn import bidirectional_dynamic_rnn from my.tensorflow.rnn_cell import SwitchableDropoutW...
from django.contrib import admin from .models import Tag, Post, PostTag class TagAdmin(admin.ModelAdmin): list_display = ('name', ) class PostTagInline(admin.TabularInline): model = PostTag class PostAdmin(admin.ModelAdmin): list_display = ('title', ) inlines = [ PostTagInline, ] adm...
test_case = int(input()) for _ in range(test_case): l, r = map(int, input().split()) print(*[l, 2 * l] if 2 * l <= r else [-1]*2)
import Queue import threading import time import logging import logging.config from fxengine.execution.execution import ExecutionAtOANDA, MockExecution from fxengine.portfolio.portfolio import Portfolio from fxengine.settings import * from fxengine.strategy.strategy import TestRandomStrategy from fxengine.streaming.st...
#!/usr/bin/python -Wd # runTests.py -- Portage Unit Test Functionality # Copyright 2006-2012 Gentoo Foundation # Distributed under the terms of the GNU General Public License v2 import os, sys import os.path as osp import grp import platform import pwd import signal def debug_signal(signum, frame): import pdb pdb.s...
# import the main window object (mw) from ankiqt from aqt import mw # import the "show info" tool from utils.py from aqt.utils import showInfo # import all of the Qt GUI library from aqt.qt import * from anki.hooks import wrap import anki.sync # markdawn2.py from http://daringfireball.net/projects/markdown/ from mark...
# Section 1 # below is how we can import something into our code. # We can do this with things from the python team or our other files. import random # randint(a, b) allows us to get a psuedorandom number that is in integer random_integer = random.randint(1, 10) print(random_integer) random_float = random.random() * ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Jun 26 21:34:38 2020 @author: thomas """ import os, shutil, sys import pandas as pd import numpy as np import random import zipfile import matplotlib import matplotlib.pyplot as plt from shutil import copyfile import pathlib cwd_PYTHON = os.getcwd() ...
import reverse_geocoder as rg import pprint from collections import OrderedDict import pandas as pd import numpy as np df = pd.read_csv('3DMassing_2018_WGS84.csv') for frame in df.head(): print(rg.search((frame[2], frame[3]))) df.to_csv('output.csv') #coordinates =(43.66030373, -79.59226603) #result = rg.sea...
def create_list(element1, element2): i = 1 lst = [] while i <= 4: lst.append(element1) lst.append(element2) i += 1 return lst print(create_list('Me', 1))
# LEVEL 19 # http://www.pythonchallenge.com/pc/hex/bin.html import base64 with open('data/level_19.txt', 'rb') as f: content = f.read() decoded = base64.decodebytes(content) with open('data/indian_little.wav', 'wb') as wav_l: with open('data/indian_big.wav', 'wb') as wav_b: data_start...
#!/usr/bin/python #from pylab import plot,show,norm from pylab import plot,show,norm import numpy import sys from csv import reader, writer class Perceptron: def __init__(self): self.w = numpy.random.random(3) self.w[0] = 0 # weight for bias self.w[1] = 0 # weight for feature 1 se...
import cx_Oracle def getConnection(): connection = cx_Oracle.connect("system/system@localhost:1521/XE") return connection def fetchData(): connection = getConnection() cursor = connection.cursor() sql_fetch_data="select * from tab" cursor.execute(sql_fetch_data) for result in cursor: ...
# from openpyxl import load_workbook # from konlpy.tag import Komoran # from sklearn.feature_extraction.text import TfidfVectorizer # import pandas as pd # import numpy as np # # df = load_workbook('데이터의 복사본.xlsx') # 엑셀파일 열기 # data = df.active # 시트 활성화(시트 하나뿐이기때문에 첫번째 시트 선택됨) # # komoran = Komoran() # doc = list() # ...
#!/usr/bin/env python # coding: utf-8 # In[19]: import pandas as pd import numpy as np from bs4 import BeautifulSoup import requests import bs4 import smtplib # In[10]: url = 'https://www.xe.com/currencyconverter/convert/?Amount=1&From=AUD&To=NPR' # In[11]: page = requests.get(url) # In[12]: page.text ...
from unittest.mock import patch import pytest from rubicon_ml.client.utils.exception_handling import FAILURE_MODES, set_failure_mode from rubicon_ml.exceptions import RubiconException @pytest.mark.parametrize("failure_mode", FAILURE_MODES) def test_set_failure_mode(failure_mode): set_failure_mode(failure_mode=f...
from utility import swap def ripple(set, start, end): for i in range(end - 1, start, -1): set[i] = set[i - 1] def insert_sort(data_set): for i in range(1, len(data_set)): val = data_set[i] for j in range(i, 0, -1): if(val < data_set[j]): ripple(data_set, j+1...
import requests as req from bs4 import BeautifulSoup as soup import json def crawlhome(): url = "https://www.kabum.com.br/" rs = req.get(url) content =rs.content json = [] page_soup = soup(content,'html.parser') containers = page_soup.findAll('div',{"class":"H-box"}) for containe...
""" Batchcode for Balamb Garden. """ from evennia import create_object from typeclasses import rooms, exits, characters ############################################################################### # INITIATE ROOMS # Rooms are created first, as adding exits and details will cross refer to # different locations wh...
import email.mime.application import smtplib import ssl from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText def lacze_sie_z_poczta(adresat, adres_nadawcy, haslo_nadawcy, jezyk_adresata): # Przekazuję programowi dane logowania. serwer_nadawcy = ['smtp.gmail.com', 465] # Wska...
# What is the value of the first triangle number to have over five hundred divisors? # Comments Section: # - Straight forward algorithm but reducing the number of tests using factor pairs from math import sqrt def counter(n): counter = 0 for i in range(1,int(sqrt(n))+1): if n % i == 0: co...
import pandas as pd import numpy as np import matplotlib.pyplot as plt def find_missing(df): print(" \nshow the boolean Dataframe : \n\n", df.isnull()) print(" \nCount total NaN at each column in a DataFrame : \n\n", df.isnull().sum()) def basic_stats(column_name): """ takes a column nam...
# -*- coding: utf-8 -*- """ Created on Mon Dec 23 09:41:58 2019 @author: MG """ import pandas as pd import numpy as np import keras from keras.models import Sequential from keras.layers import Dense, Dropout, Flatten from keras.layers import Conv2D, MaxPooling2D from keras.utils import to_categorical from keras.prepro...
# I wanted to try making some classes as practice. RUNNING = True RESTING = False class Reindeer: def __init__(self, line): """ :param line: Parses line into the class. """ line = line.split() self.speed = int(line[3]) self.running_time = int(line[6]) self...
''' Capture multiple Faces from multiple users to be stored on a DataBase (dataset directory) ==> Faces will be stored on a directory: dataset/ (if does not exist, pls create one) ==> Each face will have a unique numeric integer ID as 1, 2, 3, etc Based on original code by Anirban Kar: https://github.com/thecodacus/...
#!/usr/bin/env python3 from lilaclib import * build_prefix = 'arch4edu-x86_64' depends = ['vtk-py3-qt4'] def pre_build(): aur_pre_build() for line in edit_file('PKGBUILD'): if 'makedepends=(' in line: print(line.replace(')',' "openmpi" "gdal" "unixodbc" "tk" "ffmpeg" "jsoncpp" "gcc-libs")')) eli...
from scripts.phone_basic_operate import Phone_Basic_Operate class JJFW(Phone_Basic_Operate): def __init__(self): Phone_Basic_Operate.__init__(self) def __del__(self): Phone_Basic_Operate.__del__(self) def click_jjfw(self): # 点击交警服务标签 xpath_jjfw_value = "//*[contains(@text,...
# Generated by Django 3.2.3 on 2021-06-07 18:13 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('beverages', '0010_auto_20210607_1758'), ] operations = [ migrations.AlterField( model_name='beverage', name='volume'...
# Generated by Django 3.1.4 on 2021-06-27 20:01 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('General', '0009_auto_20210627_2259'), ] operations = [ migrations.AlterField( model_name='delivery', name='time', ...
# Projeto e Analise de Algoritmos (PAA) # 2o sem/2018 - IFMG - Campus Formiga # Pedro Henrique Oliveira Veloso (0002346) # Saulo Ricardo Dias Fernandes (0021581) class Move(): """ Representacao de uma jogada. """ def __init__(self, word, pos, direction): self.word = word; # Palavra for...
#!/usr/bin/env python import rospy from sensor_msgs.msg import Image import cv2 import sys import os from cv_bridge import CvBridge, CvBridgeError from sensor_msgs.msg import Image, LaserScan, CameraInfo import random from std_msgs.msg import Bool, Int32, Float32 import numpy as np import math import time from std_msgs...
import numpy as np import functions as f ''' 単レイヤーのクラス群 ''' class MatMul: """ 乗算レイヤー """ def __init__(self, W): self.params = [W] self.grads = np.zeros_like(W) self.x = None def forward(self, x): W, = self.params out = np.dot(x, W) self.x = x ...
# MAIN GOAL # # In this project, you will make a game similar to 21/blackjack. Since this is not an actual game (as far as I'm aware of), here the the instructions for how to play. # # In this version, there is only one player, and there are two types of scores - the round score and the game score. The game score w...
# Generated by Django 3.1 on 2021-06-18 20:20 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('stores', '0002_country'), ] operations = [ migrations.AlterField( model_name='country', name='name', field...
#I pledge my honor that I have abided by the Stevens Honor System. #Zachary Jones #HW 5 Problem 2 def recursive_sum(list): if not list: return 0 return list[0] + recursive_sum(list[1:]) number_list = [2, 4, 6, 10, 23, 432, 43, 782] print('Sum of list: ' + str(recursive_sum(number_list)))
import dash_bootstrap_components as dbc from dash import html stack = html.Div( [ dbc.Stack( [ html.Div( "This stack has no gaps", className="bg-light border" ), html.Div("Next item", className="bg-light border"), ...
import logging import os import sys from logging.handlers import TimedRotatingFileHandler from flask import Flask from flask_cors import CORS from flask_injector import FlaskInjector from injector import singleton, Provider from parking.api.config.loader import load_config_from_json from parking.api.namespace import a...
import torch from pathlib import Path from tqdm import tqdm from test.edit_distance import edit_distance from model.asr_model import ASRTransformerModel from utils.logger import get_logger from utils.ipa_encoder import SOS_ID, EOS_ID, IPAEncoder from utils.config_utils import read_model_config, read_binf_mapping from u...
""" EXAMPLE 3.1 CONVERTED FROM THE BOOK TO PYTHON BY CASPER STEINMANN USING MPI BY GROPP ET AL. USE AT YOUR OWN RISK """ from numpy import pi from mpi4py import MPI from mpiutil import getMPIInformation comm = MPI.COMM_WORLD (rank,size) = getMPIInformation(comm) def f(x): return 4.0 / (1.0 + x*x) while True: ...
from django.db import models from easy_thumbnails.fields import ThumbnailerImageField from django.db.models.signals import post_delete from django.dispatch import receiver from ckeditor_uploader.fields import RichTextUploadingField # Create your models here. class Page(models.Model): name = models.CharField(verbos...
import json from pathlib import Path import sys import time import appdirs import click from tabulate import tabulate from ai.backend.cli.interaction import ask_yn from . import admin from ..pretty import print_done, print_error, print_fail, print_info, print_wait from ..session import Session @admin.group() def m...
# Copyright 2019 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import annotations import textwrap from typing import Iterable import pytest from pants.backend.python import target_types_rules from pants.backend.python.goals.package_...
import dropbox _API_ACCESS_TOKEN = 'Od8i3MHlBiAAAAAAAAAABZISCA_JLdWe5vROh3RpDGkyE1m3gwztshfcx863Eyy6' # all the bucket_name is unused in the dropbox implementation _BUCKET_NAME = '' def upload_file(service,from_file_name,to_file_name): # try delete it first try: delete_file(service,'',"/" + to_file_nam...
from __future__ import absolute_import # import apis into api package from .audit_api import AuditApi from .auth_api import AuthApi from .auth_groups_api import AuthGroupsApi from .auth_providers_api import AuthProvidersApi from .auth_roles_api import AuthRolesApi from .auth_users_api import AuthUsersApi from .cloud_a...
from collections import Counter input = [x.split('\n') for x in open('data/06.txt').read().split('\n\n')] summed = 0 for group in input: group_size = len(group) group_choices = [] for choice in group: group_choices += list(choice) for count in Counter(group_choices).values(): if count =...
""" 合工大 问句相似度研究算法实现 """ from model.questiontype import QuestionType from score.word_similarity import WordSimilarity class SentenceSimilarity: def __init__(self): # 初始化评分权重 self.__scores = 0.0 self.__syntax_scores = 0.0 self.__class_weight = 0.2 self.__key_weight = 0.3 ...
class Solution(object): def setZeroes(self, matrix): m = len(matrix) n = len(matrix[0]) # Mark them for i in range(m): for j in range(n): if matrix[i][j] == 0: matrix[i][j] = 'x' # Delete them for i in ...
# some training and examples on namedtuple!!!! from collections import namedtuple # Car = namedtuple("car", "color speed") # # Car = namedtuple("Car", ['color', 'speed']) # my_car = Car('red', 100) # print(my_car.color) # print(my_car.speed) # print(my_car) # print(*my_car) # '*' for unpacking the arguments!!! # # #...
import math def square(): numbers = input("Enter the numbers in the list seperated by a comma: ") squared = [] list = numbers.split(",") for number in list: squared.append(int(number) ** 2) print(squared) square()
''''''''''''''''''''''''''''''''''''''' import modules ''''''''''''''''''''''''''''''''''''''' import numpy as np import pygame import sys import math import tkinter as tk import json import os pygame.init() pygame.display.set_caption('Connect Four - Global Offensive') '''''''''''''''''''''''''''''''''''...
from PIL import Image from .mazeToGif import makeGIF #pylint: disable=relative-beyond-top-level def make_step(k:int): for i in range(len(m)): for j in range(len(m[i])): if m[i][j] == k: if i>0 and m[i-1][j] == 0 and a[i-1][j] == 0: m[i-1][j] = k + 1 if j>0 and m[i][j-1] == 0 and a...
@cuda.jit('void(uint64[:], uint64[:])', target='gpu') def checkwieferich(check, result): """ checks if a given number is a wieferich prime :param check: list of numbers to check :param result: list of wieferich numbers (or 0) :return: """ #current index i = cuda.grid(1) ac = check[i]...
from spack import * import sys,os sys.path.append(os.path.join(os.path.dirname(__file__), '../../common')) from scrampackage import write_scram_toolfile class GraphvizToolfile(Package): url = 'file://' + os.path.dirname(__file__) + '/../../common/junk.xml' version('1.0', '68841b7dcbd130afd7d236afe8fd5b949f017...
import numpy as np import torch from tqdm import trange from .inception import InceptionV3 from .fid_score import calculate_frechet_distance def get_inception_and_fid_score(images, device, fid_cache, is_splits=10, batch_size=50, verbose=False): block_idx1 = InceptionV3.BLOCK_INDEX...
import pandas as pd import numpy as np import os def load(folder): """ Method Description: This method will load Accelerometer, EMG, Gyro, Orientation, Orientation Euler for an input activity folder Input: Folder name of the folder containing the 5 data files Output: A list of 5 (Accelerometer, EMG...
""" Week 2, Day 2: Find the Town Judge In a town, there are N people labelled from 1 to N. There is a rumor that one of these people is secretly the town judge. If the town judge exists, then: - The town judge trusts nobody. - Everybody (except for the town judge) trusts the town judge. - There is exact...
import os import datetime from collections import OrderedDict from logging import basicConfig from logging import INFO from flask import Flask, request, logging, Response, jsonify, json from flask_cors import CORS from persistence import Persistence app = Flask(__name__) CORS(app) @app.route('/') def hello(): ...
from typing import Dict, Any, List from datetime import datetime class FleetSettings(object): def __init__(self, is_free_move: bool, motd: str) -> None: self.__is_free_move: bool = is_free_move self.__motd: str = motd def get_esi_data(self) -> Dict[str, Any]: data: Dict[str, Any] = {}...
def bubblesort(list1): #this is for the descending sorting temp = 0 for i in range (0,len(list1)-1,1): for j in range (len(list1)-1): if list1[j] < list1[j+1]: temp = list1[j] list1[j] = list1[j+1] list1[j+1] = temp ret...
# License ''' Code by Gugulothu Yashwanth Naik April 30,2020 Released under GNU GPL ''' import numpy as np import matplotlib.pyplot as plt from pylab import* #if using termux #import subprocess #import shlex #end if subplot(2,1,1) x=[5.08,5.67,6.34,6.88,6.98,7.08,7.58,7.9,8.02,9.86,11.17,14.33,57.91] y=[5.15,6.8,7...
from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import hashes from math import ceil import hashlib import binascii class Base58CheckAddress(object): VERSION_BYTE = bytes([0]) def __init__(self, public_key = None): self.ALPHABET = "123456789A...
import argparse import pandas as pd import torch from scipy.sparse import csr_matrix, vstack from sklearn.decomposition import PCA from pathlib import Path import numpy as np def load_cell_gene_features(params): """ return: (cell, pca_dim) """ random_seed = params.random_seed pca_d...
from apps.inventory.models.ships import * from apps.inventory.models.weapons import *
from django.shortcuts import render, redirect from .models import Books def index(request): context = { "books": Books.objects.all() } return render( request, "books/index.html", context ) def add_data(request): Books.objects.create( title = 'Title1', author = 'Author1', published...
""" =================== TASK 1 ==================== * Name: Sum Number Digits * * Write a function `sum_digits` that will return * sum of digits for given integer number. * If passed value is invalid, function should * return -1 which indicates something went wrong. * * Note: Please describe in details possible cas...
""" Artificial potential fields Basic idea : ----------- U_art = U_xd(attraction potential) + U_O(repulsive Potential) U_att = 1/2 * kp * (x - xd)^2 1/2 * n * (1/rho - 1/rho_node )^2 if rho <= rho_node U_rep = { 0 if rho > rho_node U_art = The artific...
from django.db import models from django.utils import timezone class LoginAttemptRecord(models.Model): username = models.CharField(max_length=255, null=True, blank=True, unique=True) count = models.PositiveIntegerField(null=True, blank=True, default=0) timestamp = models.DateTimeField(auto_now_add=True) ...
from django.db.models import Q from rest_framework.filters import SearchFilter, OrderingFilter from rest_framework.generics import ListAPIView,RetrieveAPIView,RetrieveUpdateAPIView,DestroyAPIView,CreateAPIView from chirps.models import Chirp from .serializers import ChirpListSerializer,ChirpDetailSerializer,ChirpCreate...
from flask import Flask, render_template, request from chatterbot import ChatBot from chatterbot.trainers import ChatterBotCorpusTrainer from chatterbot.trainers import ListTrainer app = Flask(__name__) with open('file.txt','r') as file: conversation = file.read() bot = ChatBot("Sunanda's Resume ChatBot") train...
from typing import List, Optional import torch import torch.nn as nn import torch.nn.functional as F from torch import Tensor from torch.nn.modules.batchnorm import BatchNorm2d from torch.nn.modules.instancenorm import InstanceNorm2d from torchvision.ops import Conv2dNormActivation from ...transforms._presets import ...
import soursecode.AI.ai as ai from soursecode.model.letters import Letters from soursecode.model.board import Board b1 = Board() l1 = Letters() ai.fill_spot(l1, b1) def game_over(state: bool): if state: print("***YOU WIN ASSHOLE***") else: print('sry you are out of lives! Fucking bitch')...
#!/usr/bin/env python #-*-coding:utf-8-*- # @File:learn_related.py # @Author: Michael.liu # @Date:2019/2/12 # @Desc: from os import listdir import xml.etree.ElementTree as ET from pyhanlp import * import sqlite3 import configparser from datetime import * import math import pandas as pd import numpy as np from pyhanlp ...
# Create your tests here. import datetime from django.test import TestCase from django.utils import timezone from .models import Question class QuestionModelTests(TestCase): def test_was_published_recently_with_future_question(self): """ was_published_recently() returns False for questions w...
#Desenvolva um programa que leia seis números inteiros e mostre a soma apenas daqueles que forem pares. Se o valor digitado for ímpar, desconsidere-o. soma=0 cont=0 for c in range(1, 7): n = int(input('Digite o {}º valor: '.format(c))) if n % 2 == 0: soma += n cont += 1 print('Foram informado {...
from music21 import * import os import random def getMidisToCombine(source_location): midisList = os.listdir(source_location) midisToCombine = random.sample(midisList, 4) #midisToCombine = [source_location + midi for midi in midisToCombine] return midisToCombine def combineMidis(source_location, writ...
""" Часть 1. Численной дифференцирование 1. односторонние разности 2. центральная разность 3. повышенная точность в граничных точках 4. формулы Рунге 5. Выравнивающие переменные (для экспоненты) Задается х, для которого необходимо найти производную """ import numpy as np import pandas as pd from math import exp, log ...
age = int(input("你的年龄是:")) if age >= 18: print("恭喜!你成年了。") else: diff = str(18 - age) print("要年满18岁才成年,你还差 " + diff + " 岁")