text
stringlengths
8
6.05M
import sys import os import os.path import re import dummy_wintypes import struct_parser import func_parser import def_parser TYPE_EQUIVALENCE = [ ('PWSTR', 'LPWSTR'), ('SIZE_T', 'c_ulong'), ('PSIZE_T', 'POINTER(SIZE_T)'), ('PVOID', 'c_void_p'), ('PPS_POST_PROCESS_INIT_ROUTINE', 'PVOID'), ('...
import sys sys.path.append('../streamlit-recommendation') import os import time import gc import argparse import pandas as pd from scipy.sparse import csr_matrix from sklearn.neighbors import NearestNeighbors from fuzzywuzzy import fuzz from helper import data_processing def get_recomendation(movie_set, ...
from django.contrib import admin from . import models admin.site.register(models.Publisher) admin.site.register(models.Informations)
#-*- encoding: utf-8 -*- import netsvc import pooler, tools import math import decimal_precision as dp from tools.translate import _ from osv import fields, osv def arrot(cr,uid,valore,decimali): #import pdb;pdb.set_trace() return round(valore,decimali(cr)[1]) class FiscalDocHeader(osv.osv): _inherit =...
a = input('a=:') print (a)
from urllib import request from bs4 import BeautifulSoup import pymysql class spider: def __init__(self): self.url = r"http://www.jianshu.com" self.header = {'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:52.0) Gecko/20100101 Firefox/52.0'} self.db_config = { 'host':...
#import sys #input = sys.stdin.readline def a_win(x,y): if x == y: return True if x == 1 and y == 0: return True if x == 0 and y == 2: return True if x == 2 and y == 1: return True return False def main(): n, k = map(int,input().split()) s = list(input()) ...
#!/usr/bin/env python3 """ test for the Interface module. """ import unittest from base_test import PschedTestBase from pscheduler.interface import interface_affinity, source_interface, LocalIPList class TestInterface(PschedTestBase): """ Interface tests. """ # The following are wrappers around an...
import rhinoscriptsyntax as rs import math as ma import random as rd def delete_all(): all_objects = rs.ObjectsByType(0) rs.DeleteObjects(all_objects) def delete_something(n): something = rs.ObjectsByType(n) rs.DeleteObjects(something) a = 0.1 b = 0.01 g = 1.0 t = 0.0 dt = 0.01 L = 0.5 class Firefly...
import numpy as np import matplotlib.pyplot as plt from sklearn.linear_model import LinearRegression X = [[6, 2], [8, 1], [10, 0], [14, 2], [18, 0]] y = [[7], [9], [13], [17.5], [18]] model = LinearRegression() model.fit(X,y) X_test = [[8, 2], [9, 0], [11, 2], [16, 2], [12, 0]] y_test = [[11], ...
#!/usr/bin/env python # coding: utf-8 # In[167]: import pandas as pd import numpy as np import warnings import re import nltk import seaborn as sns import matplotlib.pyplot as plt nltk.download('stopwords') from nltk.corpus import stopwords from nltk.stem import WordNetLemmatizer from nltk.tokenize import sent_token...
# Generated by Django 2.0.4 on 2019-01-23 23:22 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('PMGMP', '0001_initial'), ] operations = [ migrations.RemoveField( model_name='pmgbpmodel', name='parameters', ), ...
/Users/rasmuslevinsson/anaconda3/lib/python3.6/io.py
from django.http import HttpResponse from django.shortcuts import render from .models import Books, Authors def main_title(request): return render(request, "main_title.html") def books_title(request): books = Books.objects.all() context = {"books": books} return render(request,"books_title.html",con...
import sqlite3 import json from typing import List class SQLiteLoader(): """Загружает данные из SQLite, преобразовывает их и возвращает список словарей для последующей обработки в PostgresSaver. Parameters ---------- connection : sqlite3.Connection Объект соединения с SQLite """ ...
from rlib.objectmodel import we_are_translated from rlib.osext import raw_input from som.vm.globals import nilObject from som.vm.symbols import symbol_for class Shell(object): def __init__(self, universe): self.universe = universe def start(self): from som.vm.universe import std_println, erro...
#!/usr/bin/env python import numpy as np from math import sqrt DEFAULT_C1 = 1e-4 EPS = 1e-7 NEWTON_C2 = 0.9 CG_C2 = 0.1 # better c2 for conjugate gradient according to Nocedal/Wright DEFAULT_C2 = NEWTON_C2 def backtracking_linesearch(f, df, x, p, **kwargs): """ Convenience wrapper for _backtracking_linesear...
from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC import time import math import pytest @pytest.fixture() def browser(): print("\nstart browser for test..") browser...
#from '/Users/vsubr2/spark-1.6.1-bin-hadoop2.6/bin/pyspark' import collections from pyspark import SparkConf, SparkContext conf = SparkConf().setMaster("local").setAppName("PopularMoviesv") sc = SparkContext(conf=conf) data = sc.textFile("file:///Users/vsubr2/Projects/KaneSpark/ml-100k/u.data") ratings = data.map(lam...
import pickle from data_loader import DataLoader from classifier import model def train(data_path, model_file): data_loader = DataLoader(data_path) data_loader() weights = load_weights(model_file) if model_file else None classifier = model(data_loader.train_x, ...
""" Shows basic usage of the Google Calendar API. Creates a Google Calendar API service object and outputs a list of the next 10 events on the user's calendar. """ from apiclient.discovery import build from httplib2 import Http from oauth2client import file, client, tools from datetime import datetime import calendar f...
## -*- coding: utf-8 -*- """ Created on Tue 27 Oct 2020 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 ...
from flask import * from database import * import json import time, datetime import thermocontrol import switch app = Flask(__name__) @app.route('/') def hello_world(): #return "test" return render_template('index.html', is_pid_on=thermocontrol.is_pid_on(), setpoint=thermocontrol.setpoint()) @app.route('/pl...
from distutils.core import setup INSTALL_REQUIRES = [ "pandas", "numpy", ] setup( name="sudoku", version="1.0", author="Hendrik Scherner", packages=["sudoku"], install_requires=INSTALL_REQUIRES, )
import sqlite3 import yaml import os class Database: def __init__(self, dbconfig): dbfile = os.path.join(os.path.dirname(__file__), '..', '..', dbconfig.get("db_file")) self.db = self.create_or_open_db(dbfile) self.db.row_factory = self.dict_factory def dict_factory(self, cursor, row):...
import numpy as np from typing import Union from .base import BaseWidget from .utils import get_unit_colors from .unit_locations import UnitLocationsWidget from .unit_waveforms import UnitWaveformsWidget from .unit_waveforms_density_map import UnitWaveformDensityMapWidget from .autocorrelograms import AutoCorrelogra...
import tkinter as tk from tkinter import ttk from tkinter import * import bcrypt from datetime import date from datetime import timedelta from GestionHabitaciones import * import sqlite3 class RegistroHuesped: valorEntry = "" def Inicio(self,ventanaMenuPrincipal): ##################...
import numpy as np import cv2 from matplotlib import pyplot as plt import subprocess from moviepy.video.io.ffmpeg_tools import ffmpeg_extract_subclip from moviepy.editor import * from PIL import Image cap = cv2.VideoCapture("ball3.mp4") fps = cap.get(cv2.CAP_PROP_FPS) # OpenCV2 version 2 used "CV_CAP_PROP_FPS" fra...
from django.shortcuts import render from .models import * from rest_framework import viewsets,permissions from .serializers import * from rest_framework.pagination import LimitOffsetPagination,PageNumberPagination from .pagination import PostPageNumberPagination from rest_framework.filters import SearchFilter,OrderingF...
from flask import Blueprint blueprint = Blueprint( "locations_blueprint", __name__, url_prefix="/locations", template_folder="templates", static_folder="static", )
#__author: "Jing Xu" #date: 2018/1/25 import os,sys from core import db_handler from conf import settings from core import logger import json import time import random def v_code(): code = '' for i in range(5): add_str = random.choice([str(random.randrange(10)),chr(random.randrange(65,91)),chr(random.randrange(...
#!env python3 # -*- coding: utf-8 -*- from flask import Flask, render_template_string, request app = Flask(__name__) index_html = ''' <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> </head> <body> <h1>query</h1> <ul> <li><a href="/result?fruit_no=1">1番</a></li> <li><a href="/result?fruit_...
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Wed Oct 24 10:56:47 2018 @author: withheart """ import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns train_data = pd.read_csv('input/train.csv') test_data = pd.read_csv('input/test.csv') print(train_data.head()) pri...
from PyQt5 import QtCore, QtGui, QtWidgets from PyQt5.QtWidgets import QApplication, QMessageBox, QMainWindow, QAction import re import socket import threading import json import sys class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") MainWindow.resize...
from sklearn import tree, svm from sklearn.metrics import classification_report from sklearn.model_selection import GridSearchCV from sklearn.model_selection import train_test_split from sklearn.svm import LinearSVC from sklearn.svm import SVC from sklearn.externals import joblib treeClassifier = tree.DecisionTreeClas...
#!/usr/bin/env python3 """ Manipulation of CNF formulae and satisfying assignments """ import os.path import subprocess def sign(x): return 0 if x == 0 else int(x / abs(x)) class FormatError(IOError): """ Failure to parse a CNF/SAT file """ def __init__(self, message): super().__init__(message) ...
from google.appengine.api.modules import ( get_current_module_name, get_current_version_name ) from module_a import Entity def deferred_create_entity(entity_id): Entity(id=entity_id, created_at_module=get_current_module_name(), created_at_version=get_current_version_name()).put()
n1=float(input('1ª nota: ')) n2=float(input('2ª nota: ')) print(f'a media é: {(n1+n2)/2}')
from api.repositories.repos import Repos class Github(): def __init__(self, **kwargs): self.api_root_url = "http://api.github.com" self.repos = Repos(self.api_root_url, **kwargs) if __name__ == '__main__': r = Github(token="de4260ff9e5a21e64973cd55c693154c3b56a837") x = r.repos.list_your...
""" Integrates the Chameleon template language. This is basically a copy of more.chameleon, with the additional inclusion of a gettext translation function defined by :mod:`onegov.core.i18n`. To use a chameleon template, applications have to specify the templates directory, in addition to inheriting from :class:`oneg...
# -*- coding: utf-8 -*- from menucontext import MenuContext response.files.append(URL('static', 'css/last.css')) menuadds = MenuContext(db) response.menu += menuadds.menudocs() response.menu += menuadds.menupags() def read(): slug = request.args(1) pid = int(request.args(0)) post_data = db(db.post.id =...
# +JMJ+ # Paul A Maurais # 2018 class Card: """A single card. Attributes: name (Ace, One, ... King), suit, value (1-10), rank (1-13), and dataDict (tuple of the other four attributes)""" def __init__(self, name='', suit='N', value=0): """name (Ace, One, ... King), suit, value (1-10), rank (1-13). Assi...
""" Python solution for Supervised Neural Network Problem. """ import numpy as np import pandas as pd import matplotlib.pyplot as plt def weight_init(shape): """ Function to initialize the weight matrix. Arguments: shape: Shape of the weight matrix (W) """ mean = 0 std = 2/shape[1] w = np.random.nor...
#!/usr/bin/env python ## coding: UTF-8 # ros系のライブラリ import rospy from sensor_msgs.msg import Image from std_msgs.msg import Float32MultiArray from sensor_msgs.msg import CameraInfo # ros以外 import cv2 import numpy as np import math import dlib from cv_bridge import CvBridge, CvBridgeError import imutils import os impo...
x = 1 # local variable gv.x = 2 # global variable shared by all scripts print x,' ',gv.x
import math import itertools import numpy as np n = int(input()) result = 0 list2 = list(range(1,n+1)) all = list(itertools.combinations_with_replacement(list2, 3)) for i in all: if(i[0]==i[1] and i[0]==i[2]): result += np.gcd.reduce(i) elif (i[0]==i[1] or i[0]==i[2] or i[1]==i[2]): result += np...
# This program recursively parses all C++ header and code file in a # given directory and extract their depencencies on each other. # The dependency info is stored in a text file in a format that is # recognized by the "dot" program (GraphViz) # # Input : Path to src # Output: .dot file # # Note: The program makes f...
import textwrap from .script import Script class BuildScript(Script): export = ('base', 'repo') def __init__(self, container): super().__init__() self.container = container for var in self.export: self.append(f'{var}="{container.variable(var)}"') self.append('''...
import googlemaps import requests import json import os import numpy as np from openpyxl import load_workbook gmaps = googlemaps.Client(key='AIzaSyBxAxKmbEhLrO08SmCi9M_4r6w9Y7MOER4') basic_url = 'https://maps.googleapis.com/maps/api' mykey = 'key=AIzaSyBxAxKmbEhLrO08SmCi9M_4r6w9Y7MOER4' def geocoding(ad...
"this is a test" import os import shutil def SetupSymb(): """This function creates local copies of symbology. """ destsymbdir = "C:\Mapping_Project\MXDs\Symbology" if not os.path.exists("C:\Mapping_Project\MXDs\Symbology"): os.mkdir("C:\Mapping_Project\MXDs\Symbology") if not os.path.exists(...
#Operaciones con listas en Python #Cuando trabajamos con listas podemos también hacer operaciones por ejemplo, #https://www.geeksforgeeks.org/python-list/ #Unir listas my_lista = [1] my_lista2 = [2,3,4] my_lista3 = my_lista + my_lista2 print("hola" + str(my_lista3[1:])) my_lista3[1:] my_lista3 # [1,2,3,4] #Multipli...
import turtle import os # 배경 설정 screen = turtle.Screen() screen.bgcolor("lightgreen") screen.title("Turtle Run Ver.1") # 가장자리 그리기 mypen = turtle.Turtle() mypen.penup() mypen.setposition(-300, -300) mypen.pendown() mypen.pensize(3) for side in range(4): mypen.forward(600) mypen.left(90) mypen.hideturtle() # 배경음악 ...
from PagSeguroLib.singleton import Singleton from PagSeguroLib.config.PagSeguroConfig import PagSeguroConfig from PagSeguroLib.log.LogPagSeguro import LogPagSeguro from PagSeguroLib.resources.PagSeguroResources import PagSeguroResources class PagSeguro(Singleton): library = None resources = None config = None log =...
# Instructions: # ============= # 1. Collect from https://archive.ics.uci.edu/ml/datasets/wine # 2. Run this script import pandas as pd import numpy as np SEED = 998823 #--- np.random.seed(SEED) data = pd.read_csv("../data/raw/wine.data", header=None, sep=',') cols = data.columns.tolist() cols = cols[1:] + cols[:...
import random import string from typing import Tuple from hummingbot.core.utils.tracking_nonce import get_tracking_nonce_low_res from hummingbot.client.config.config_var import ConfigVar from hummingbot.client.config.config_methods import using_exchange from hummingbot.core.utils.tracking_nonce import get_tracking_non...
def label(basename, product, hash, state): return "solvent__%(basename)s__%(product)s__%(hash)s__%(state)s" % dict( basename=basename, product=product, hash=hash, state=state)
import time from block import TetrisBlock from features.feature import Feature from field import Field from painter import Led_Matrix_Painter, RGB_Field_Painter class Startscreen(Feature): def __init__(self, field_leds: Field, field_matrix: Field, rgb_field_painter: RGB_Field_Painter, led_matrix...
#!/usr/bin/env python """ File: plotting Date: 12/4/18 Author: Jon Deaton (jdeaton@stanford.edu) """ import os import sklearn import numpy as np import matplotlib.pyplot as plt from matplotlib.ticker import MaxNLocator from sklearn.metrics import roc_curve, auc from sklearn.metrics import average_precision_score, pr...
#garcia, gil #astr 231 hw 5 prob 1 #4/9/2020 ''' in this script we integrate the eqns of stellar structure to determine the maximum mass and radius of a white dwarf experiencing ultra-relativistic effects ''' import numpy as np import matplotlib.pyplot as plt DR = 10 # our step size in the integrations #######...
"""Change Table Name Revision ID: a3135c18513d Revises: 12b6ae6ce692 Create Date: 2018-11-28 23:03:31.895532 """ from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import mysql # revision identifiers, used by Alembic. revision = 'a3135c18513d' down_revision = '12b6ae6ce692' branch_labels = None ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # _Author_: xiaofeng # Date: 2018-04-01 12:12:42 # Last Modified by: xiaofeng # Last Modified time: 2018-04-01 12:12:42 from PIL import Image import tensorflow as tf import tflib import tflib.ops import tflib.network from tqdm import tqdm import numpy as np import data_loa...
#Programa: act7.py #Propósito: Una persona adquirió un producto para pagar en 20 meses. El primer mes pagó 10 €, el segundo 20 €, el tercero 40 € y así sucesivamente. Realizar un programa para determinar cuánto debe pagar mensualmente y el total de lo que pagará después de los 20 meses. #Autor: Jose Manuel Serrano Palo...
import smh import pickle from matplotlib import pyplot import sklearn.metrics from config import Config import sys sys.path.append('../common/') import evaluation import dataLoader # Folder paths objectsRankingFile = 'allObjetsRankingFile.pickle' model = smh.listdb_load(Config.MODEL_FILE) ifs = smh.listdb_load(Confi...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Clase 1. Primera parte Introducción a Python """ #La programación con la que vamos a trabajar se llama imperativa y se ejecuta línea por línea. 3*4+2 #Variables: """ Se puede guardar información en variables, usando el signo =, para ser utilizada después """ a=2 ...
#q7: one add choice: non-zero initialization of the account from example_creditcard import CreditCard class CreditCard_q7(CreditCard): """non-zero initialization of the account""" def __init__(self, customer, bank, acnt, limit, start=0): super().__init__(customer, bank, acnt, limit) i...
n,q=list(map(int,input().split())) D={} for i in range(n): S=input() D[str(i+1)]=S D[S]=str(i+1) for i in range(q): print(D[input()])
import day13 import unittest class Day2Tests(unittest.TestCase): def test_True(self): self.assertTrue(True) def test_Day13_Example(self): self.assertEqual(day13.solve((1,1),(7,4),data=10)[0], 11) def test_Day13_Data(self): self.assertEqual(day13.solve((1,1),(31,39))[0], 90) ...
errorMessage = "Oh dang! An error has occured." errorUnknownCommand = "I'm sorry, I don't know this command. Type /help for a list of commands." errorNoFile = "Either file is missing or is not readable. Creating." errorCommand = "Unknown command." errorAdmin = "You must be an admin to issue this command" errorMs...
"""mysite URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.9/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-base...
import os from flask import Flask, request, render_template from configs import settings from views.web import web_view def create_app(debug=settings.DEBUG): app = Flask(__name__, template_folder=settings.TEMPLATE_FOLDER) app.register_blueprint(web_view) app.debug = debug return app app = create_app...
"""Login form.""" from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User class SignUpForm(UserCreationForm): """Specific form with intermediate email value for signup.""" email = forms.EmailField( max_length=254, help_text='Requis....
"""MKS localzation module The MKS localization module fits data using the Materials Knowledge System in Fourier Space. Example: >>> from pymks.fmks.bases.primitive import discretize >>> from pymks.fmks.func import allclose >>> disc = discretize(n_state=2) >>> x_data = lambda: da.from_array(np.linspace(0, 1, 8).resh...
# Generated by Django 3.0.7 on 2020-12-02 08:16 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('cl_table', '0087_remove_stock_favorites'), ] operations = [ migrations.AlterField( model_name='posdaud', name='recor...
# extract ingredients from recipes and count frequency import pandas as pd import numpy as np from nltk import word_tokenize from nltk.corpus import stopwords from nltk import pos_tag import re import requests from bs4 import BeautifulSoup import ast import inflect from help_functions import read_csv_files # --------...
# -*- coding: utf-8 -*- { 'name': 'conector FTP wav', 'version': '0.1', 'category': 'ftp', 'summary': 'Conector Ftp', 'description': """ Genera un conector ftp, para agregar los archivos ftp, al sistema y relacionarlos con los mandatos ================================================== """, ...
import unittest from sample.strings_example import StringsExamples class TestStringsExamples(unittest.TestCase): def test_concat_strings(self): string1 = "hola" string2 = "adios" result = StringsExamples.concat_strings(string1, string2) assert result=="holaadios" de...
from functions import read_ncs, get_vectors, create_batch, train, get_non_comp_args, \ get_poly_features, rank_with_score, write_score, read_eval, build_model, regression_score from baseline import weighted_add_score from gensim.models.keyedvectors import KeyedVectors import logging from config import logging_confi...
# -*- coding: utf-8 -*- import time from openerp.osv import fields, osv from openerp.tools.translate import _ import logging _logger = logging.getLogger(__name__) class ProgressExamsWizard(osv.TransientModel): _name = 'progress.exams.wizard' _columns = { 'head': fields.text( string = 'Head...
""" a deque with sequence (1,2,3,4,5,6,7,8). given a queue, use only the deque and queue, to shift the sequence to the order (1,2,3,5,4,6,7,8) """ from example_queue import ArrayQueue from example_double_ended_queue import ArrayDoubleEndedQueue D = ArrayDoubleEndedQueue() for i in range(1, 8+1): D.add_last(i) Q...
from os import system system("cls") matriz=[] matriz2=[] matriz3=[] resta=0 res=[] res2=[] res3=[] suma=0 val=0 val1=0 n=[0,1,1,1,1,1,1,1,1] val2=-1 print(n) x1=2 y2=3 matriz4 = [[1]*x1 for i in xrange(y2)] def print_r(matriz4): for fila in matriz4: print fila def transpuesta(matriz...
# _*_ coding: utf-8 _*_ # @Time : 2021/04/14 17:02:35 # @FileName: mlp.py # @Author : handy # @Software: VSCode import tensorflow as tf import pandas as pd data = pd.read_csv('../data/Advertising.csv') X, Y = data.iloc[:, 1:-1], data.iloc[:, -1] model = tf.keras.Sequential( [ # 输入大小即为输入X的维度(即...
# Copying Holly Grimm's solution https://github.com/hollygrimm/cs294-homework/blob/master/hw1/bc.py # Copy and pasting and merging it into a copy of my behavior_cloner.py code. import argparse import pickle import os import sys import tensorflow.compat.v1 as tf import numpy as np from sklearn.model_selection import tr...
''' Created on 11-Dec-2018 @author: prasannakumar ''' #https://www.youtube.com/watch?v=rfscVS0vtbw #this is the URL for the python class that lasts for 4:30 HRS #from StdSuites.AppleScript_Suite import string #from idlelib.ReplaceDialog import replace #from __builtin__ import str from math import * print('hello worl...
import tempfile from pathlib import Path import numpy as np import tifffile from PIL import Image from xicam.common_ingestors import generic class TestGeneric: def test_tiff(self): # Write a small TIFF file test_data, _, _ = np.mgrid[0:30, 0:40, 0:50] test_data = test_data.astype("<u2") ...
import sys input = sys.stdin.readline num = 8 def check_right(start, direction): if start > 4 or meet[start-1] == 1: return if meet[start-1] == -1: check_right(start+1, -direction) if direction == -1: temp = tob[start].pop() tob[start].insert(0, temp) ...
import json import uuid from asgiref.sync import sync_to_async from channels.generic.websocket import AsyncJsonWebsocketConsumer from chat.models import Message, ChatGroup, MessagesGroups class TicTacToeConsumer(AsyncJsonWebsocketConsumer): async def connect(self): self.room_name = self.scope['url_route...
import dataclasses import pickle import h5py import numba import numpy as np import sklearn import sklearn.preprocessing import mabe.config @dataclasses.dataclass class TrainingBatch: X: numba.typed.List # [np.array] X_extra: numba.typed.List # [np.array] Y: numba.typed.List # [np.array] indices:...
# This is kept in 0.97.0 and then will be removed from .template_tools import ( get_template_amplitudes, get_template_extremum_channel, get_template_extremum_channel_peak_shift, get_template_extremum_amplitude, get_template_channel_sparsity ) from .template_metrics import (TemplateMetricsCalculato...
class Point: def __init__(self, x, y): self.x = x self.y = y def distance(point1, point2) -> float: """ Расстояние между двумя точками """ return round(((point1.x - point2.x) ** 2 + (point1.y - point2.y) ** 2) ** 0.5, 2) # Дано две точки на координ...
import tweepy # переменные ключей и токенов consumer_key = 'JsV6FCCUsCqkKsbc2LzsBLlh2' consumer_secret = 'flC0NzGyKsrnb8vTLJvUtUoaDkw2UPuchPlgmk3VeFdKKsVkNo' access_token = '2335158726-XBiP8R9HT7ijIyl0RvHx2UWtmH8gsZYYhXILCY9' access_token_secret = 'hOwHDL2TlQvPS9N0tfNoWd6hV78J8O7xnrpaHGNTFQ45k' # настройки OA...
# import các gói thư viện cần thiết from keras.applications.resnet import ResNet50 from keras.applications.inception_v3 import InceptionV3 from keras.applications.xception import Xception from keras.applications.vgg16 import VGG16 from keras.applications.vgg19 import VGG19 from keras.applications import imagenet_utils ...
def bfs(heads, tails): S = set((heads, tails)) Q = [(heads, tails, 0)] qi = 0 while qi < len(Q): h, t, d = Q[qi] qi += 1 if (h, t) in S: continue else: S.add((h, t)) if h == 2 and t == 0: return d + 1 if t >= 1: ...
''' ############# Need refactor for databas ###################### @app.route('/virtual/api/v1.0/styles',methods=['GET']) def checkDB(): user_id=request.args.get('user_id') clothes=models.db.session.query(models.Clothes.style,models.Clothes.user_id).distinct().filter(models.Clothes.user_id==user_id).all() ...
import sys sys.path.insert(0,'..') from Classes.polygon import Polygon from Classes.rectangle import Rectangle from Classes.tile import Tile import math import pickle def getROI(filename): with open(filename, "r") as file: line = file.readlines()[0] line = line.split() p1 = (float(line[2])...
import sqlite3 as lite import csv import re import pandas import string con = lite.connect('cs1656.sqlite') with con: cur = con.cursor() ######################################################################## ### CREATE TABLES ###################################################### ############################...
import psycopg2 import os from databaseconnection import * def create_FS(): command = "create table FireStation(" command += "FS_ID integer, " command += "NAME text, " command += "PASSWORD text, " command += "PREFECTUR text, " command += "COTY text, " command += "ADDRESS text, " comman...
import discord from discord.ext import commands import time import datetime import pytz class GameTime(commands.Cog): def __init__(self, bot): self.bot = bot @commands.command(pass_context=True) async def time(self, ctx): """Displays current game time.""" locationName = self.bo...
from requests import get from json import loads from bs4 import BeautifulSoup def get_synonym(word: str) -> str: try: html_doc = get(f'https://www.thesaurus.com/browse/{word}') soup = BeautifulSoup(html_doc.content.decode(html_doc.encoding), 'lxml') script_tags = soup('script') syn...
import math import numpy as np import cv2 from pythonRLSA import rlsa from ijazahpy.preprocessing import remove_noise_bin as remove_noise class DotsSegmentation: """ Pendekatan segmentasi baru Segmentasi dilakukan dengan mengambil area dots pada ijazah methods: segment:: remove_bin_noi...
#import sys #input = sys.stdin.readline def main(): N = int(input()) # print((2**N-1)//2) a = "A" D = 2**N K = D-1 L = K//2 Z = K if N >= 3: ANS = [["A"]+["B"]*K for _ in range(Z)] for j in range(K): for i in range(L): ANS[(i+j)%K][j+1] = a print(...