text
stringlengths
8
6.05M
import matplotlib.pyplot as plt from matplotlib.colors import ListedColormap, Normalize from matplotlib.ticker import FormatStrFormatter, StrMethodFormatter import numpy as np def heatmap(datas, row_labels, col_labels, ax=None, cbar_kw={}, cbarlabel="", **kwargs): """ Create a heatmap from a nump...
""" Modify your own source code with this piece of Python black magic. When a piece of code calls `replace_me(value)`, that line will be replaced with the given `value`. If you want to insert a comment and keep the line that inserted it, use `insert_comment(value)`. **ATTENTION**: Calling these functions will modify ...
# -*- coding: utf-8 -*- """ Created on Fri Nov 6 20:28:14 2020 @author: Michele Milesi 844682 """ import re #Riceve come parametro la stringa che contiene il nome del file #e legge le rige del file mettendole in una lista def read_file(file_name): with open(file_name, 'r') as input_file: fi...
import views import unittest from mock import patch class TestFlask(unittest.TestCase): def setUp(self): self.app = views.app.test_client() def testStatus(self): urlList = ['/', '/sports_form', '/sports_form_ajax'] for url in urlList: response = self.app.get(url) ...
import uuid from blog import mongo from flask import jsonify from werkzeug.security import generate_password_hash class User: def __init__(self, data): self.data = data def validate(self, data): #Username validation username = data.get('username') if username: if mongo.db.user.find_on...
import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split from sklearn.svm import SVC from sklearn.naive_bayes import MultinomialNB from sklearn.metrics import classification_report, confusion_matrix from sklearn.preprocessing import OneHotEncoder, Multi...
from user import user from admin import admin from membre import membre dico = {'id':'','prenom':'','nom':'','role':'','pres':'','mail':'','mdp':''} u = user(dico) #print(u.connecte) print("Bonjour, Veuillez vous identifier") _id = int(input("Veuillez Saisir votre identifiant: ")) psw = input("Veuillez Saisir votre Mo...
#!/usr/bin/env python3 from subprocess import check_output, check_call, Popen, PIPE from tempfile import NamedTemporaryFile import sys import json import codecs import sys try: import ijson HAS_IJSON = True except ImportError: HAS_IJSON = False print("WARN: ijson not available. I may choke on big mail...
from pypi_simple import __version__ project = "pypi-simple" author = "John T. Wodder II" copyright = "2018-2023 John T. Wodder II" # noqa: A001 extensions = [ "sphinx.ext.autodoc", "sphinx.ext.intersphinx", "sphinx.ext.viewcode", "sphinx_copybutton", ] autodoc_default_options = { "members": True...
#! /usr/bin/env python # -*- coding: utf-8 -*- # Title :py_exception.py # Description : # Author :Devon # Date :2018/1/17 # Version :1.0 # Platform : windows # Usage :python test4.py # python_version :2.7.14 #=======================================================...
from flask import Flask, render_template import flask_restful from core.excel_handler import excel_reader EXCEL_FILE = 'datas/test_data.xls' app = Flask(__name__) api = flask_restful.Api(app) @app.route("/") def index(): return render_template('index.html') class ExcealReader(flask_restful.Resource): def ...
from unittest import mock from .helpers import ProviderForTesting class TestHooks: def test_basic(self, cmd, mocker, commit): result, _ = cmd('start', git_inited=True) assert result.exit_code == 0 mocker.spy(ProviderForTesting, 'stop') mocker.spy(ProviderForTesting, 'start') ...
import json from rest_framework import status from rest_framework.generics import get_object_or_404 from rest_framework.response import Response from rest_framework.views import APIView from snippets.models import Snippet from snippets.serializers import SnippetSerializer class SnippetListCreateAPIView(APIView): ...
import sys import os import time from twisted.python import log, monkey from twisted.application import service from twisted.internet import reactor from buildslave import bot # states for use below (using symbols prevents typos) STOPPED = "stopped" DISCONNECTED = "disconnected" CONNECTED = "connected" class Idleize...
import os import click import io import shutil import tarfile import logging import sonosco.common.audio_tools as audio_tools import sonosco.common.path_utils as path_utils from sonosco.datasets.download_datasets.create_manifest import create_manifest from sonosco.common.utils import setup_logging from sonosco.common....
# __init__.py from .bin_converter import * from .uni_inter_intergers import *
a=int(input()) b=int(input()) c=int() if a>b: c=1 elif a==b: c=0 else: c=2 print(c)
__author__ = 'Dell' import csv from datetime import datetime edgesreader = csv.reader(open("flickr-growth-sorted.txt", "r"), delimiter = '\t') ingraph = dict() outgraph = dict() def write_edge_file(input): inwriter = csv.writer(open(input[0], "wb"), delimiter='\t') outwriter = csv.writer(open(input[1], "wb"...
#!/usr/bin/python import sys import xml.etree.ElementTree as ET class Layout: def __init__(self, name, title, forOtherScreen, arg): self.name = name self.title = title self.arg = arg self.forOtherScreen = forOtherScreen self.uid = "layout." + name layouts = [ Layout("togglefullscreen", "Toggle full sc...
# coding: utf-8 #question 2 class WordFrequency(object): """ Analyses files to genrate a dictionary that has words and their frequencies """ def __init__(self): self.freq_dict = {} self.special_character = ",./;<>?:{}[]\1234567890!@#%^&*()-_=+" def getFreq(self,key): ...
from unittest import TestCase from unittest.mock import patch, Mock, call from bat.example.cli import ( hello_world, get_help, default, argparse, Configuration, ) class ExampleTests(TestCase): @patch('builtins.print') def test_hello_world(t: TestCase, print: Mock): conf = Mock(Con...
import cupy from cupy.core import _routines_logic as _logic from cupy.core import fusion def all(a, axis=None, out=None, keepdims=False): """Tests whether all array elements along a given axis evaluate to True. Args: a (cupy.ndarray): Input array. axis (int or tuple of ints): Along which axis...
from tkinter import* from time import* from random import* window = Tk() c = Canvas(window, height=400, width=300, bg='black') l = Text(window, height=1, width=6) l.pack() c.pack() player = c.create_rectangle(0, 380, 20, 400, fill='white', outline='white') c.move(player, 140, 0) s = Text(window, height=1, width=6) s.pa...
import os import numpy as np import h5py from PIL import Image data_dir = '/tempspace/hyuan/DrSleep/VOC2012/VOCdevkit/VOC2012' train_list = '/tempspace/hyuan/DrSleep/VOC2012/VOCdevkit/VOC2012/dataset/train.txt' val_list = '/tempspace/hyuan/DrSleep/VOC2012/VOCdevkit/VOC2012/dataset/val.txt' test_list = '/tempspace/hyua...
#!/usr/bin/env python3 # # Validator for 'throughput' test spec # import pscheduler from validate import spec_is_valid, MAX_SCHEMA try: json = pscheduler.json_load() except ValueError as ex: pscheduler.succeed_json({ "valid": False, "error": str(ex) }) valid, message = spec_is_valid(jso...
from .predict import Predictor, Prediction # from .mmdetection import MMTwoStagePredictor from .kalman import KalmanPredictor from .ecc import ECCPredictor
from enum import Enum import torch import torch.nn as nn import torch.nn.functional as F from .modules import MLP, Logit, ConvNet, GatedAttn, MixLogCDF, GatedConv2d, GatedLinear from .squeeze import (squeeze1d, unsqueeze1d, channel_merge, channel_split, checker_merge, checker_split) class Abst...
from bokeh.plotting import figure from bokeh.io import output_file, show x=[10,12,14,25,17] y=[40,56,76,54,43] output_file("graph2.html") f=figure() f.circle(x,y) show(f)
from konlpy.tag import Kkma from konlpy.tag import Hannanum from konlpy.tag import Komoran from konlpy.tag import Okt import sys kkma = Kkma() hannanum = Hannanum() komoran = Komoran() okt = Okt() analize_list = [kkma, hannanum, komoran, okt] analize_list_name = ["Kkma_Class", "Hannanum_Class", "Komoran...
import os import json import pandas as pd from flask import Flask, request, redirect, url_for, render_template, jsonify, Request from flask_caching import Cache from werkzeug.utils import secure_filename app = Flask(__name__) config = { "DEBUG": True, # some Flask specific configs "C...
# Create a program that asks the user to enter their name and their age. # Print out a message addressed to them that tells them the year that they will turn 100 years old. def main(): name = raw_input("Give me your name: ") age = raw_input("Give me your age: ") age = int(age) current_year = 2015 ...
class EngineNotDefined(Exception): pass class EngineNotConnected(Exception): pass
#!/usr/bin/env python import roslib import rospy import numpy as np import cv2 import copy from geometry_msgs.msg import Vector3Stamped,Point,PointStamped from sensor_msgs.msg import PointCloud2 from linemod_detector.msg import NamedPoint from visualization_msgs.msg import Marker from cv_bridge import CvBridge from tf...
from django.conf.urls.defaults import patterns, url,include from shopback.base.authentication import UserLoggedInAuthentication from shopback.base.views import InstanceModelView from shopback.base.permissions import IsAuthenticated, PerUserThrottling from shopapp.autolist.views import ListItemTaskView,CreateListItemTas...
def insertionSort(li):#insertion sort function for i in range(1,len(li)): C = i while (C>0) and (li[C] < li[C-1]): li[C], li[C-1] = li[C-1], li[C] C = C-1 return li #directly from previous assignment def mergesort(list): ...
import difflib import os import sys from podctl.container import Container from podctl.build import BuildScript from podctl.visitors import ( Base, Copy, Packages, Run, User, ) from unittest import mock from podctl.visitors import packages packages.subprocess.check_call = mock.Mock() os.environ[...
#tfrecord file import tensorflow as tf tf.enable_eager_execution() # to get the path of image and folder import pathlib import os # 1. the path of folder datadir = pathlib.Path(os.path.join(os.getcwd(), "disease_photos/")) print(os.getcwd()) # /Users/eunsukkim/Desktop/tutorial1 + disease_photos/ print(datadir) # ...
class Pixel: """ O objeto Pixel é composto por tuplas de cores. Seu atributo numero_fontes deve ser substituído por um objeto TuplaCores. """ def __init__(self, n_fontes: str): # self.tupla = TuplaCores(int(n_fontes[1])) self.numero_fontes = n_fontes class TuplaCores: """ ...
python简介 版本 www.python.org 2.7.x / 3.5.x 特点、应用场景 ''' 高级的、面向对象的、可扩展的、可移植的、易于学习和维护的程序语言 动态语言,程序在运行时可以动态修改对象元数据 弱类型语言,数据由 标量scalar和容器container 表示 ,GC进行内存资源管理 一种胶水语言,依赖第三方软件包,用于业务逻辑的编写和模块的组合 适用 快速交付、原型建模,自动化运维 。。 结合第三方软件包,具有强大的功能,适应于场景: 网络通信、UI、WebService、分布式计算和存储.. 除了OS和Driver,几乎没有不能做的! 灵活和松散的特性,入门容易,精通难,坑很多,步步惊心! ...
import matplotlib.pyplot as plt import numpy as np # This time will make a figure with two subplots arranged vertically. # First we initialize our figure plt.figure() # Again We set up numpy arrays covering the range we want to plot. xvals1 = np.linspace(-5, 5, 500) xvals2 = np.linspace(-5, 5, 20) # This creates a s...
# -*- coding: utf-8 -*- # @Time : 2021-03-11 16:38 # @Author : sloan # @Email : 630298149@qq.com # @File : MulprocessApply.py # @Software: PyCharm from concurrent.futures import ProcessPoolExecutor from MulprocessBased import SampleGeneratorBase from sloan_utils import Panda_tool import os import time import cv2 import...
""" The setup script to install Qrtmp as a package in your Python distribution. """ from distutils.core import setup setup(name='Qrtmp', version='0.2.0', description='Qrtmp - Quick/Simple RTMP Implementation.', author='Goel Biju', packages=['qrtmp'] )
import re import requests import tweepy import ssl import time from botocore.exceptions import ReadTimeoutError from requests.exceptions import Timeout, ConnectionError import datetime from PolitiStats.properties import getConsumerKey, getCivicsKey, getConsumerSecret, getAccessKey, getAccessSecret, \ getNewsKey ...
import pytest import pathlib import nipkg_assembler.create_default_package as nipm def test_create_default_package(): nipm.main('tests/temp_package', 'nipkg_assembler/default_package', False) assert pathlib.Path('tests/temp_package').exists()
# Generated by Django 2.1.12 on 2019-11-03 17:17 from django.conf import settings import django.contrib.auth.models import django.contrib.auth.validators import django.contrib.postgres.fields import django.contrib.postgres.fields.jsonb from django.db import migrations, models import django.db.models.deletion import dj...
from bs4 import BeautifulSoup from sklearn.feature_extraction.text import TfidfVectorizer from sklearn import svm from sklearn import neighbors from sklearn.ensemble import RandomForestClassifier from xlrd import open_workbook import sys #vectorize the training set def vectorize(begin,end): context = [] j_list = [] ...
#!/usr/bin/env python """Archive Now for python""" # usage: ./archiveNow.py -v mycluster -u myuser -d mydomain.net -j MyJob -r '2019-03-26 14:47:00' [ -k 5 ] [ -t S3 ] [ -f ] # import pyhesity wrapper module from pyhesity import * from datetime import datetime, timedelta # command line arguments import argparse pars...
# -*- coding: utf-8 -*- from email.mime.text import MIMEText from email import encoders import email.header import email.utils import smtplib def format_addr(s): name, addr = email.utils.parseaddr(s) return email.utils.formataddr((\ email.header.Header(name, 'utf-8').encode(), \ addr...
""" This is the X-Spider base class """ from celery import Task from rlibs.base import XSession from w3lib.url import canonicalize_url from requests_futures.sessions import FuturesSession class BaseSpider(Task): """ base spider class for all the spiders """ def __init__(self, **kwargs): self.se...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # 偏函数 # Python的functools模块提供了很多有用的功能,其中一个就是偏函数(Partial function)。要注意,这里的偏函数和数学意义上的偏函数不一样 print(int('12345')) print(int('12345', base=8)) print(int('12345', 16)) print(int('11111', base=2)) def int2(x, base=2): return int(x, base) # functools.partial就是帮助我们创建一个偏函数的,不需要我...
from openpyxl import Workbook from openpyxl import load_workbook from zlib import crc32 import sys import glob import logging import xml.etree.ElementTree as ET def GetCrc32(filename): # calculate crc32 with open(filename, 'rb') as f: return crc32(f.read()) def strnset(str,ch,n): # string change...
# -*- coding: utf-8 -*- def test_login(app, loggedout): app.session.login("administrator", "root") assert app.session.logged_username == "administrator"
from datetime import datetime from app import db from werkzeug.security import generate_password_hash, check_password_hash from flask_login import UserMixin from app import login @login.user_loader def load_user(id): return User.query.get(int(id)) class User(UserMixin, db.Model): id = db.Column(db.Integer, primary...
import pandas as pd import numpy as np from flask import Flask, render_template,request import pickle import yfinance as yf # Create an instance of Flask app = Flask(__name__) model = pickle.load(open('app/model.pkl', 'rb')) @app.route('/') def home(): return render_template('index.html') # Route that will tri...
import sys class Solution: def increasingTriplet(self, nums): """ :type nums: List[int] :rtype: bool """ value1 = sys.maxsize value2 = sys.maxsize for i in range(len(nums)): if nums[i] <= value1: value1 = nums[i] elif...
import matplotlib.pyplot as plt import numpy as np import PIL from PIL import Image import pandas as pd #(0=Angry, 1=Disgust, 2=Fear, 3=Happy, 4=Sad, 5=Surprise, 6=Neutral) kaggle_csv = pd.read_csv('fer2013.csv', header = None) print (kaggle_csv) kgc = [] for i in range(len(kaggle_csv[1])): if kaggle_csv[0][i] == 0...
from bibliopixel.animation import BaseMatrixAnim from bibliopixel import log import numpy as np import cv2 import os grab = None if os.name == 'nt': try: from desktopmagic.screengrab_win32 import getRectAsImage, getScreenAsImage log.debug("Using desktopmagic module") def nt_grab(bbox=None...
import numpy as np import pandas as pd def sample_X(n,p): return np.random.normal(loc=0, scale=1, size=(n,p)) def sample_epsilon(n): return np.random.normal(loc=0, scale=1, size=n) def sample_Z(n): return np.random.binomial(n=1,p=1/3,size=n) def sample_Q(n, omega, epsilon): return np.random.binomial...
# Generated by Django 2.0.5 on 2018-08-10 10:52 from django.db import migrations, models import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('weather', '0002_auto_20180810_0326'), ] operations = [ migrations.AddField( model_name='city', ...
import math import numpy as np import h5py import matplotlib.pyplot as plt import tensorflow as tf from tensorflow.python.framework import ops from ImproveDeepNN.TensorFlowTutorial.tf_utils import * np.random.seed(1) #0 example ''' y_hat = tf.constant(36, name='y_hat') y = tf.constant(39, name='y') loss = tf.Variabl...
def setup(): size(500, 500) smooth() background(255) noStroke() noLoop() def draw(): for i in range(0, 10, 1): for k in range(5): fill(i*20) rect(i*40+50, 75+40*(2*k-1), 35, 35) fill(160-15*i) rect(i*40+50, 75+40*2*k, 35, 35)
import pandas as pd import numpy as np import tensorflow as tf csv = pd.read_csv('bmi.csv') # print(csv.head()) # 값 fat normal thin / 정답*label # 학습하기 위한 Label의 종류 3가지를 one-hot Encoding : 이진화 하는거. # 가장 큰 키와 가장 작은키 # print(csv['height'].max()) # print(csv['height'].min()) # 가장 큰 몸무게와 작은 몸무게 # print(csv['weight'].max(...
# Copyright (c) 2019-2020, RTE (https://www.rte-france.com) # See AUTHORS.txt # This Source Code Form is subject to the terms of the Apache License, version 2.0. # If a copy of the Apache License, version 2.0 was not distributed with this file, you can obtain one at http://www.apache.org/licenses/LICENSE-2.0. # SP...
""" Author(s): Tushar Sharma <tushar.sharma@ivycomptech.com> Contains class UserAuth for operations relate to user management and access control """ from gms_services.utils.LoadQuery import LoadQuery from gms_services.utils.Database import Database class UserAuth: """ Class for user Authentication related stuff...
from flask import Flask, request, render_template, send_file, redirect from scrapper import get_stackoverflow, get_wwr, get_remote import csv """ These are the URLs that will give you remote jobs for the word 'python' https://stackoverflow.com/jobs?r=true&q=python https://weworkremotely.com/remote-jobs/search?term=py...
from graphics import * class Button: """A button is a labeled rectangle in a window. It is enabled or disabled with the activate() and deactivate() methods. The clicked(pt) method returns True if and only if the button is enabled and pt is inside it.""" def __init__(self, win, center, wi...
__author__ = 'tk' import random def merge(test1,test2): i , j , k = 0 , 0 , 0 arr = [] lens1 = len(test1) lens2 = len(test2) while i<lens1 and j<lens2: if test1[i] < test2[j]: arr.append(test1[i]) i = i+1 else: arr.append(test2[j]) j ...
from dxtbx.model.experiment_list import ExperimentListFactory from cctbx import miller import cPickle as pickle import numpy as np import sys, time, argparse, os """ Extract indexing matrices and reflection information from DIALS indexing output so that contents are accessible without libtbx.python; also, predict all...
# Escribir una funcion que calcule la traspuesta de una matriz de nxn # Recibe una matriz de nxn y devuelve la misma matriz traspuesta
from django.contrib import admin from . models import Check admin.site.register(Check)
import pickle import os import numpy as np import matplotlib.pyplot as plt from model import classifier from constant import * def time_taken(start, end): """Human readable time between `start` and `end` :param start: time.time() :param end: time.time() :returns: day:hour:minute:second.millisecond...
from django.shortcuts import render, redirect from django.contrib.auth import authenticate, get_user_model, login, logout from .forms import UserLoginForm, UserRegisterForm from django.http import HttpResponse from django.contrib.auth.models import User # Create your views here. # def login_view(request): # form ...
import requests from bs4 import BeautifulSoup def link_func(year): syear = str(year) syear1 = str(year + 1) test = requests.get('https://fbref.com/en/squads/53a2f082/' + syear + '-' + syear1 + '/Real-Madrid-Stats').text soup = BeautifulSoup(test, 'lxml') table = soup.find(id='matchlogs_for'...
from http import HTTPStatus class BaseApplicationException(Exception): _status = HTTPStatus.INTERNAL_SERVER_ERROR def __init__(self, *args): super().__init__(*args) self.status = self._status class BadRequest(BaseApplicationException): _status = HTTPStatus.BAD_REQUEST
from flask import Flask, render_template, request import md5 def encrypt(mechanism, message): if mechanism in ['rot13', 'base64', 'hex']: return message.encode(mechanism) if mechanism == 'md5': m = md5.new() m.update(message) return m.hexdigest() app = Flask(__name__) @app.rou...
from onegov.core.orm.abstract import AdjacencyListCollection from onegov.page.model import Page class PageCollection(AdjacencyListCollection[Page]): """ Manages a hierarchy of pages. Use it like this: from onegov.page import PageCollection pages = PageCollection(session) """ __list...
from django.conf.urls import url from . import views from django.conf import settings from django.conf.urls.static import static from django.views.generic.base import RedirectView favicon_view = RedirectView.as_view(url='/static/favicon.ico', permanent=True) urlpatterns = [ url(r'^$', views.home, name='home'), ...
"""The module contains functions and classes for MRI reconstruction. It provides convenient simulation and sampling functions, such as the poisson-disc sampling function. It also provides functions to compute preconditioners, and density compensation factors. """ from sigpy.mri import app, dcf, linop, precond, samp, ...
import urban_dictionary if __name__ == '__main__': urban_dictionary.UrbanDictionary()
####################################################################### # # CSV Readers # ####################################################################### import csv import os import pandas as pd from enum import Enum def not_eol(y): """helper function to test if field is empty""" if not("\n" in y): ...
import logging import uuid from django.contrib import auth from django.shortcuts import render from django.shortcuts import redirect from django.contrib import messages from django.conf import settings from apiclient import errors from smtplib import SMTPException from .models import User from mysite import const from ...
import numpy as np import random import matplotlib.pyplot as plt import math import tensorflow as tf # Creating z-matrix - shape(1000,1000) and filled from 1 (row[0]) to 1000 (row[999]) x = np.arange(1,1000,1) y = np.arange(1,1000,1) xx, yy = np.meshgrid(x,y, sparse = True) z = np.tile(yy, (1, 999)) def positionGener...
# Import the Flask module that has been installed. from flask import Flask, jsonify # Createing a "games" JSON / dict to emulate data coming from a database. games = [ { "id": 0, "name": "Scrabble", "editor": "mattel", "year_published": "1978", "description": "descp", "category": "family", ...
import urllib from bs4 import BeautifulSoup #Posting to http://egov1.co.gaston.nc.us/website/ParcelDataSite/viewer.htm #Query is for '4A017' in 'Neighborhood Code by Number' #Post Data data = urllib.urlencode(dict(ArcXMLRequest='''<?xml version="1.0" encoding="UTF-8" ?><ARCXML version="1.1"> <REQUEST> <GET_FEATURES o...
from models import db, Pet from app import app db.drop_all() db.create_all() Kilo = Pet(name='Kilo', species='Dog', photo_url='https://images.unsplash.com/photo-1587790311640-50b019663f01?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=800&q=80', age=3) Reggie = Pet(name='Reggi...
from flask import jsonify from service.student_questions_services import StudentQuestionsServices def route(app): # ----Retrieve all student questions from the database and return status code of 200 for successful retrieval @app.route("/studentquestions", methods=['GET']) def get_all_student_questions():...
#!/usr/bin/env python3 # encoding: utf-8 """ quick_sort.py Created by Jakub Konka on 2011-11-01. Copyright (c) 2011 University of Strathclyde. All rights reserved. """ import sys import random as rnd sys.setrecursionlimit(10000) def quick_sort(array): '''This function implements the standard version of the quick ...
t = int(input()) # Python program to compute sum of pairwise bit differences def sumBitDifferences(arr,n): ans = 0 # Initialize result # traverse over all bits for i in range(0, 32): # count number of elements with i'th bit set count = 0 for j in range(0,n): if...
alt = float(input('Digite a altura: ')) lar = float(input('Digite a largura: ')) area = alt * lar print(f"A área é: {area}")
import os import requests from flask import Flask, jsonify, render_template, request, session from flask_socketio import SocketIO, emit from flask_session import Session from datetime import datetime, date from flask_socketio import join_room, leave_room app = Flask(__name__) app.config["SECRET_KEY"] = os.getenv("SEC...
def sum(a,b): return a+b a=int(input('Enter first number ')) b=int(input('Enter second number ')) print("Sum of number is "+str(sum(a,b)))
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Jun 1 10:21:35 2018 @author: ddeng """ #!/usr/bin/env python3 # -*- coding: utf-8 -*- import pandas as pd import pdb import numpy as np from sklearn.preprocessing import MinMaxScaler from sklearn.svm import SVC, LinearSVC from sklearn.model_selection...
from __future__ import division, print_function, absolute_import import sys import numpy as np import vtk from vtk.util import numpy_support from scipy.ndimage import map_coordinates from fury.colormap import line_colors def set_input(vtk_object, inp): """ Generic input function which takes into account VTK 5 o...
from collections import deque # doubly ended queue """Breadth-First Search.""" """Can be used for Dijikstra's algorithm, Edmonds-Karp algorithm, Cheyen's algorithm or for AI surroundings exploration.""" class Node: def __init__(self, data, *neighbors: []): self.data = data self.adjacency_list...
import torch from torch import nn class NPairsLoss(nn.Module): def __init__(self, name): super(NPairsLoss, self).__init__() self.name = name def forward(self, r1, r2): """ Computes the N-Pairs Loss between the r1 and r2 representations. :param r1: Tensor of shape (bat...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def inorderTraversal(self, root): """ :type root: TreeNode :rtype: List[int] # Recursive solution is tri...
#Print 8 multiplied by 9 print (8*9)
from torch import nn as nn import torch from models.bert_modules.embedding import BERTEmbedding from models.bert_modules.transformer import TransformerBlock from utils import fix_random_seed_as import pickle class BERT(nn.Module): def __init__(self, args): super().__init__() #fix_random_seed_as(a...
#!/bin/python3 import math import os import random import re import sys # Complete the minimumSwaps function below. def minimumSwaps(arr): i = 0 l = len(arr) swaps = 0 while i < l-1: while arr[i]-1 != i: t = arr[arr[i]-1] arr[arr[i]-1] = arr[i] arr[i] = t ...
# Generated by Django 2.1.5 on 2019-03-19 22:11 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('flowchart', '0001_initial'), ] operations = [ migrations.RemoveField( model_name='flowchartquestion', name='solution...