text
stringlengths
38
1.54M
from django.urls import path from . import views from .views import BlogDetailView,AddPostView, CategoryView, LikeView, AddCategoryView, UpdatePostView, DeletePostView, AddCommentView, ThoughtsView, AllBlogsView, Overview urlpatterns = [ path('',views.home,name="home"), # path('',HomeView.as_view(),nam...
#!/usr/bin/env python # coding: utf-8 # # Question 54 # # ### **Question** # # > **_Assuming that we have some email addresses in the "username@companyname.com" format, please write program to print the company name of a given email address. Both user names and company names are composed of letters only._** # # > *...
import numpy as np from Optimizer.Adam import Adam from Optimizer.AdaGrad import AdaGrad from Optimizer.SGD import SGD from Optimizer.RMSprop import RMSprop from Optimizer.Default import Default def give_optimizer_dict(): functions = { 'adam': Adam, 'default': Default, 'sgd': SGD, ...
import FWCore.ParameterSet.Config as cms from Configuration.Eras.Era_Run3_pp_on_PbPb_approxSiStripClusters_cff import Run3_pp_on_PbPb_approxSiStripClusters from Configuration.Eras.Modifier_run3_egamma_2023_cff import run3_egamma_2023 Run3_pp_on_PbPb_approxSiStripClusters_2023 = cms.ModifierChain(Run3_pp_on_PbPb_appro...
import pygame import random import configparser pygame.mixer.pre_init(44100, -16, 2, 1024) pygame.mixer.init() pygame.init() var = configparser.RawConfigParser() var.read('./config_file.ini') ftype = var.get('font', 'type') fsize = int(var.get('font', 'size')) c1 = eval(var.get('color', 'black')) c2 = eval(var.get('...
# -*- coding: utf-8 -*- """ Created on Thu Nov 8 16:52:19 2018 取消批大小固定限制,固定模型全连接节点个数 @author: Bllue """ import os import cv2 import numpy as np import matplotlib.pyplot as plt import tensorflow as tf #filenames = os.walk('./') img_width = 100 img_height = 100 #path = os.walk('data/') #for d in path: # print(d...
import time from fetch import post from logger import Logger import urllib3 urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) HOST='https://pet-chain.duxiaoman.com' def autoCollect(): getVigorList() lottery() def getHeader(timestamp): return { 'Host': 'pet-chain.duxiaoman.com', ...
import json # Return json data def readJson(path): try: with open(path) as fh: return json.load(fh) except Exception as e: print("Error", e) # Return json data def writeJson(path, jsonData, mode = 'w'): try: with open(path, mode) as outfile: json.dump(jsonDa...
import paho.mqtt.client as mqttPaho import time import logging import json logging.basicConfig(level=logging.INFO) class Mqtt: def __init__(self, host, port, ID, user, passwd, topic = "/"): self.host = host self.port = port self.ID = ID self.user = user self.passwd = pa...
from . import baseService, masterDataService, workTimeAccountingService class Client: def __init__(self, url): self.url = url self.session = dict( sessionID=None, personID=None ) def change_time_state(self, **params): return workTimeAccountingService.ch...
from .lenet import LeNet from .utils import edl_mse_loss, BaseModel, relu_evidence, softplus_evidence __all__ = [ "BaseModel", "LeNet", "edl_mse_loss", "relu_evidence", "softplus_evidence" ]
"""mysite URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.0/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based ...
from modulo import confirm def main(): senha = input("Digite sua senha: ") if confirm(senha) == False: print("\nDigite uma nova senha.") else: print("\nSenha correta.") if __name__ == "__main__": main()
#!/usr/bin/env python import os import re from setuptools import setup, find_packages VERSION_RE = re.compile(r'''__version__ = ['"]([0-9.]+)['"]''') HERE = os.path.abspath(os.path.dirname(__file__)) def read(*args): return open(os.path.join(HERE, *args)).read() def get_version(): init = read('aws_encrypt...
from wtforms import TextField, SubmitField,PasswordField, IntegerField, DecimalField from wtforms.validators import InputRequired, Email from flask_wtf.file import FileAllowed, FileField, FileRequired from wtforms import Form, IntegerField, StringField, BooleanField, TextAreaField, validators class Addproducts(Form): ...
def login_test(): from selenium import webdriver import config login_test = webdriver.Firefox() login_test.get('https://secure-garden-12181.herokuapp.com') login_test.find_element_by_link_text('Login').click() login = login_test.find_element_by_name("username") password = login_test.find_element_by_name("pass...
# File that reads the data from raw dining data as input and creates a raw csv for each day's data. import pandas as pd import sys, os origin=os.getcwd() os.chdir("data/Dining data Virginia Tech/Atomic Pizza/2014-2015/April 2015") xls_file= "04-01-15.3" csv_file = xls_file.replace(".xls",".csv") data_xls = pd.read_exc...
import csv import os from django.conf import settings from django.contrib import messages from django.contrib.auth.decorators import login_required, user_passes_test from django.contrib.auth.mixins import LoginRequiredMixin, PermissionRequiredMixin, UserPassesTestMixin from django.templatetags.static import static fro...
# -*- coding: utf-8 -*- from odoo import api, fields, models import datetime from datetime import datetime, date,timedelta from odoo.tools.translate import _ import calendar from odoo.exceptions import ValidationError,UserError from dateutil.relativedelta import relativedelta from odoo.tools import DEFAULT_SERVER_DATE...
# def big(a,b): # if a>b: # print(f"this is bigger {a}") # else: # print(f"this is bigger {b}") # # a = int(input("enter first number : ")) # b = int(input("enter second number : ")) # print(big(a,b)) def big(a,b): if a>b: return a return b a = int(input("enter first number : ")...
# # plugins/TellStickDuo/__init__.py # # Copyright (C) 2010 Telldus Technologies # ############################################################################## # Revision history: # # 2012-09-08 Improved the handling of repeated events for devices and sensors. # 2012-08-14 Added actions for dimming Good Morning and...
from django.views.generic import TemplateView, DetailView, ListView from . import models # Create your views here. class BaseView: @property def extra_context(self): company_info = models.CompanyInfo.objects.filter(display=True).first() banners = models.Banner.objects.filter(display=True) ...
"""Tests runner.""" import unittest from tests.fs import TestPreparer from tests.basic import BasicTestCases from tests.remove import RemoveTestCases from tests.netfile import NetfileTestCases from tests.netdir import NetdirTestCases if __name__ == '__main__': preparer = TestPreparer() try: prepare...
import heapq import random class Process: def __init__(self, id, time): self.id = id self.time = int(time) def get_time(self): return self.time def get_id(self): return self.id def __lt__(self, other): return self.time < other.time class Machine: def ...
from flask import Flask, escape, request, jsonify, Response import random from random import sample from json import dumps app = Flask(__name__) @app.route('/',methods=['GET','POST']) def response(): multi_dict = request.args array = [] for key in multi_dict: array.append(multi_dict.get(key)) ...
#coding: utf-8 # from common.models import Language, PaymentSystem from django.contrib.auth.models import User from django.db import models from django.utils.translation import ugettext, ugettext_lazy as _ # from ormcache.models import CachedModel from utilites.funcs import easy_upload_path, make_upload_path PARAM_VA...
from turtle import * # for i in range(5): # color("black") # forward(50) # color("white") # forward(50) # color("red") # forward(50) # color("white") # forward(50) n = int(input("Enter a number: ")) speed(-1) for i in range(n): circle(500/n,180) right(180 * (n-2) / n) mainloop(...
import pytest from dataclasses import dataclass, field from typing import Union, NewType, Optional from hologram import JsonSchemaMixin, ValidationError from hologram.helpers import StrEnum class MySelector(StrEnum): A = "a" B = "b" C = "c" @dataclass class RestrictAB(JsonSchemaMixin): foo: MySele...
import serial import sys from collections import deque from config.constants import NovaConstants from config.config import NovaConfig from utils.commandtype_enum import CommandType from utils.frequencytimer import FrequencyTimer from communication.protocol import NovaProtocolCommandReader class SerialCommunication: ...
#Week 1 Tasks #Task 1 def randomRearrange(yourList): """This function will randomly shuffle the elements in a list""" import random for i in yourList: oldPos = yourList.index(i) #get the original position of the element in the list newPos = random.randint(0,(len(yourList)-1)) #get ...
# -*- coding: utf-8 -*- { 'name': 'Fee Enhancement', 'version': '1.0', 'category': 'Edsys', "sequence": 4, 'summary': 'Manage Fee structure', 'complexity': "medium", 'description': """ This module provide fee management system over OpenERP """, 'author': 'Edsys', 'web...
#Linear cryptanalysis of a basic SPN cipher #Try to determine linear expressions between input and output bits which have #a linear probability bias. Randomly chosen bits would only satisfy the #expression with probability 0.5 (Matsui's Piling up Lemma) import basic_SPN as cipher from math import trunc, fabs import i...
from __future__ import unicode_literals from django.db import models from datetime import datetime class Genre(models.Model): genre_name = models.CharField(max_length=100,unique=True) def __str__(self): return self.genre_name class Movie(models.Model): movie_name = models.CharField(max_length=20...
from numpy import* x=array(eval(input("tabela 1: "))) y=array(eval(input("tabela 2: "))) m=zeros(3,dtype=int) h=0 j=0 t=0 g=0 for i in x: if(i > y[h]): j=j+1 h=h+1 elif (i ==y[h]): t=t+1 h=h+1 elif (i < y[h]): g=g+1 h=h+1 m[0]=m[0]+j m[1]=m[1]+t m[2]=m[2]+g print (m)
#!/usr/bin/python3 import requests import json import sys import re import os from subprocess import call if os.geteuid()!=0: print ( 'You need root permissions to perform this operation') sys.exit(1) if ( len(sys.argv) != 2 ): print ( 'Incorrect number of arguments', file=sys.stderr ) print ( 'Usage...
from pylab import * 2 3 def dy_forward(y, h): 4 N = len(y) 5 dy = zeros(N) 6 for k in range(N - 1): 7 dy[k] = (y[k+1] - y[k])/h 8 return dy 9 10 def dy_central(y, h): 11 N = len(y) 12 dy = zeros(N) 13 for k in range(1, N - 1): 14 dy[k] = (y[k+1] - y[k-1])/(2*h) 15 return dy 16 17 def dy_richardson(y, h)...
#!/usr/bin/env python # 3rd party packages import RPi.GPIO as GPIO # https://pypi.python.org/pypi/RPi.GPIO import eiscp # https://pypi.python.org/pypi/onkyo-eiscp import time import datetime import logging LedPin = 11 # pin11 --- led BtnPin = 12 # pin12 --- button receiver = eiscp.eISCP('192.168.1.122') # ...
from graphics import* def askUserColour(): coloursList = [] validColours = ["red", "green", "blue", "magenta", "cyan", "orange", "brown", "pink"] while True: colour = input("Enter a colour for your patch (eg: red, green, " + "blue, magenta,...
from nornir import InitNornir nr = InitNornir(config_file="config.yaml") def testplatform(task): print(f"{task.host.platform}-templates") nr.run(task=testplatform)
from django.urls import reverse import json import pytest from api.models import Car add_cars = reverse("cars") rate_cars = reverse("carrate") popular_cars = reverse("popular") pytestmark = pytest.mark.django_db # <---------- GET for add cars def test_add_car_should_succeed(client) -> None: test_car: Car = Car...
import numpy as np from PIL import ImageGrab, Image import cv2 import time from directkeys import PressKey, ReleaseKey, W, A, S, D def draw_lines(img, lines): try: for line in lines: coords = line[0] cv2.line(img, (coords[0],coords[1]) , (coords[2],coords[3]), [255,255,255], 5) except: pass def roi(img,...
#coding=utf-8 ''' 切片 ''' import random name = "abcdefg" # 从start到end - 1 print(name[0:4]) # 从start到(字符串总长度 - end) print(name[0:-4]) # 从start到最后 print(name[0:]) # len方法获取长度 name2 = "x" * random.randint(200, 1000) print(len(name2)) # 步长为10 print(name2[::10]) name3 = "xaskdjnasdnjaksdnkajsndkjasndkjansdkjasnjdk...
""" Base class for drawing the soccer/ football pitch.""" import warnings from abc import ABC, abstractmethod from collections import namedtuple import matplotlib.pyplot as plt import numpy as np import pandas as pd from matplotlib import rcParams from typing import List from mplsoccer import dimensions from mplsocc...
# https://www.acmicpc.net/problem/1300 # K번째 수 import sys def counts(num): cnt = 0 for i in range(1,n+1): cnt += min(num//i,n) return cnt def binary(k,l,r): global result if l > r: return mid = (l+r) // 2 if counts(mid) >= k: result = mid binary(k,l,mid-1) ...
__author__ = 'Artiom' import logging from base_handler import * from docs import * from config import * from business_db import * #This class is handling all the Mechanic representation requests class BusinessPageHandler(BaseHandler): def get(self, pid): logging.error("pid is ++++++++++ %s" % pid) ...
from django.conf.urls import url,include from . import views urlpatterns = [ url(r'author/', views.authorView.as_view(),name='author'), url(r'authordetail/(?P<author_id>[0-9]+)',views.authordetail.as_view(),name='authordetail'), url(r'bookdetail/(?P<book_id>[0-9]+)',views.bookdetail.as_view(),name='bookdetail'), url...
#!/usr/bin/python # # Copyright (C) 2015 # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, version 2 of the License. # # This program is distributed in the hope that it will be useful, # but WIT...
import os import sdg import pandas as pd import numpy as np import sdmx import time from slugify import slugify from sdmx.model import ( SeriesKey, Key, AttributeValue, Observation, GenericTimeSeriesDataSet, DataflowDefinition, Agency, PrimaryMeasureRelationship, DimensionRelationshi...
import argparse import os from lib.textgrid import TextGrid from predict import predict def run_dir(in_path, out_path): for item in os.listdir(in_path): if item.endswith('.wav'): out_file_path = out_path + item.replace('.wav', '.TextGrid') predict(in_path + item, out_file_path, 'r...
import numpy as np import multiprocessing as mp import matplotlib.pyplot as plt from datetime import datetime from block_propagation import Block_Propagation_Simulator def main(): # run(N, policy, num_arrivals_per_process, arrival_rate, num_processes) run(40, 'oldest-first', 30000, 0.5, 5) run(40, 'random', 30...
def finiteDifference(x,y): dy=diff(y) dx=diff(x) dydx=dy/dx dydx1=zeros(y.shape,float) dydx1[:-1]=diff(y)/diff(x) dydx1[-1]=(y[-1]-y[-2])/(x[-1]-x[-2]) return dydx1 def fourPtFiniteDiff(x,y): dy=zeros(y.shape,float) h=x[1]-x[0] dy[2:-2]=(y[0:-4]-8*y[1:-3] + 8*y[3:-1] - y[4:])/(12.*h) dy[0]=(y[1]-y[0])/(x[1]...
from django.test import TestCase class IndexViewTestCase(TestCase): def test_should_have_metrics_on_context(self): response = self.client.get("/") self.assertIn("object_list", response.context)
# -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import unicode_literals import unittest from nepalicalendar import * from datetime import date, timedelta from random import randint class NepDateTestCase(unittest.TestCase): """ Tests for NepDate class """ def test_prope...
"""" Write a decorator function that wraps text passed to it in a specified HTML tag. The user should be able to decide which tag to use. """ def p_html(inititial_func): def wrapper_func(input, tag): print(f"<{tag}>{input}</{tag}>") return wrapper_func @p_html def simple_print(text): print(text)...
#coding:utf-8 from flask import Flask,request,render_template import mysql.connector import datetime import os import json import sys import requests reload(sys) sys.setdefaultencoding('utf8') conn = mysql.connector.connect(host='183.66.213.82',port="8803",user= 'tylin',password ='Tylin@123',database ='shenzhen_event'...
import os import numpy as np from tools import JSON2Bboxes,IOU def GetBboxes(pred_dir,test_dir,pred_file): pred_json_path=pred_dir+"/json/"+pred_file+".json" test_json_path=test_dir+"/json/"+pred_file+".json" pred_bboxes=JSON2Bboxes(pred_json_path) pred_bboxes.sort(key=lambda x:float(x[4]),reverse=True...
n, c, k = map(int, input().split()) T = sorted([int(input()) for _ in range(n)]) out = T.pop(0) + k peo = 1 bus = 1 for t in T: if t <= out and peo < c: peo += 1 else: out = t + k peo = 1 bus += 1 print(bus)
class TuplesExample: pass """Create a Tuples: We can create tuples in two different way Using parenthesis or without parenthesis""" # Tuples are immutable: Once you created you created you can't change it's content: t = "a", 'b', "c" t2 = ("a", "b", "c") print(t) # Printing out tuple ...
#! /usr/bin/env python import curses curses.setupterm() from pwn import * import requests r = remote("player", 5000) r.sendlineafter("> ", '3') r.sendafter("Your team name: ","T1Z334ckd00r=") r.sendlineafter("[y/n] ",'y') r.sendlineafter("> ", '3') r.sendafter("Your team name: ","123") r.sendlineafter("[y/n] ",'n')...
"""Sparse Autoencoder """ # Author: Issam Laradji <issam.laradji@gmail.com> # Licence: BSD 3 clause import numpy as np from scipy.optimize import fmin_l_bfgs_b from scipy.linalg import norm from itertools import cycle from sklearn.utils import check_X_y,check_array from sklearn.utils import check_random_state from s...
#!/usr/bin/python import cv2.cv as cv import sys import urllib2 # Rearrange the quadrants of Fourier image so that the origin is at # the image center # src & dst arrays of equal size & type def cvShiftDFT(src_arr, dst_arr ): size = cv.GetSize(src_arr) dst_size = cv.GetSize(dst_arr) if dst_size != size: ...
# Copyright 2019 Baidu 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 or agreed to in wr...
from hanabi_learning_environment.rl_env import Agent class ReinforcementAgent(Agent): def __init__(self): pass
import abc import typing import splendor_sim.interfaces.coin.i_coin_type as i_coin_type class ISponsor(abc.ABC): @abc.abstractmethod def __init__( self, name: str, victory_points: int, cost: typing.Dict[i_coin_type.ICoinType, int], ): """ :param name: ...
import os import sys import allure import pytest sys.path.append((os.path.abspath(os.path.join(os.path.dirname(__file__), '../..')))) from HJT_pkg.AppSettingPageObject import AppSetting from HJT_pkg.ReserveMeetingPageObject import ReserveMeeting from HJT_pkg.OperateInMeetingPageObject import OperateInMeeting from HJT...
for i in range(3): print i count = 0 while (count < 3): print 'The count is:', count count = count + 1 var = 1 while var != 0 : var = int(raw_input("Enter a number(enter 0 to exit): ")) print "You entered: ", var
# -*- coding: UTF-8 -*- # Copyright (c) 2007 Daniele Favara <nomed@dsslive.org>. # # This is free software you can redistribute it and/or modify it # under the terms of the GNU General Public License as published by the # Free Software Foundation; either version 2, or (at your option) any # later version. # # This sof...
#!/usr/bin/env.python # -*- coding:utf-8 -*- ''' 20分题一般不考太多算法,考审题和考虑全不全面。 看似n很大,实际扫描代价很小。上限由n一开平方后直接没多少了,连乘几下就除完了,不整除直接跳出了。 ''' import math n = int(input()) maxl = 0 maxf = int(math.sqrt(n)) + 1 start = 0 for i in range(2, maxf): # 连乘的因子上限肯定不超过这个,恰好开平方连乘长度也才1,所以扫描起点只要在这之间就好了 temp = n start_ = i count = 0 ...
from tenacity import retry, stop_after_attempt, wait_random_exponential from cuwb_sensor.network_api import API from cuwb_sensor.tools.logging import logger class FailedToStartException(Exception): def __init__(self, name): super().__init__(f"Failed to start `{name}` cuwbnet") class FailedToStopExcept...
import argparse import chainer import matplotlib.pyplot as plt import numpy as np from siam_rpn.siam_rpn import SiamRPN from siam_rpn.siam_rpn_tracker import SiamRPNTracker from siam_rpn.siam_mask_tracker import SiamMaskTracker from siam_rpn.general.vot_tracking_dataset import VOTTrackingDataset from siam_rpn.genera...
import sys from email.mime.text import MIMEText from twisted.internet import reactor from twisted.mail.smtp import sendmail from twisted.python import log log.startLogging(sys.stdout) host = 'localhost' sender = 'secretguy@example.com' recipients = ['you@localhost'] msg = MIMEText('Violets are blue,\nCan you read...
import FWCore.ParameterSet.Config as cms genCandidates = cms.EDProducer("HepMCCandidateProducer", src = cms.string('generatorSmeared'), verbose = cms.untracked.bool(False), stableOnly = cms.bool(True), excludeList = cms.vstring('nu_e', 'nu_mu', 'nu_tau', 'gamma', 'pi...
import json import datetime from django.shortcuts import render, get_object_or_404, get_list_or_404 from django.views.generic import View from django.contrib.auth.mixins import LoginRequiredMixin from .mixins import UserArrivalAccessMixin from .models import Arrival, ArrivalPos, Material from .serializers import Mate...
import pygame, sys, random, math from Bird import Bird import functionality pygame.init() pygame.font.init() score_font = pygame.font.SysFont('arial', 30) final_font = pygame.font.SysFont('arial', 70) clock = pygame.time.Clock() SCREEN_WIDTH = 500 SCREEN_HEIGHT = 700 screen = pygame.display.set_mode((SCREEN_WIDTH, SC...
from django.db import models from extranet.models.course import Course from extranet.models.student import Student class Grade(models.Model): NDST = 2.0 DST = 3.0 DST_PLUS = 3.5 DB = 4.0 DB_PLUS = 4.5 BDB = 5.0 VALUES = [ (NDST, '2.0'), (DST, '3.0'), (DST_PLUS, '3....
# Generated by Django 3.1.2 on 2020-11-05 06:48 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Authors', fields=[ ...
from django.test import TestCase from polls.models import Race # Create your tests here. raca=Race(raca='H',destreza=20,forca=10,inteligencia=15,agilidade=29,sorte=0,vitalidade=100) raca.save()
from django.db import models from core.models import NanoIdModel, TimeStampModel from .managers import PublishedManager class Tag(NanoIdModel): name = models.CharField(max_length=100) def __str__(self): return self.name class Link(NanoIdModel, TimeStampModel): title = models.CharField(max_leng...
#!/usr/bin/python # -*- coding: utf-8 -*- from chatterbot import ChatBot from chatterbot.trainers import ChatterBotCorpusTrainer import logging import os from chatterbot.corpus import Corpus from chatterbot.conversation import Statement, Response from chatterbot import utils # Enable info level logging logging.basicCo...
import os import sys import yaml import logging from cvpysdk.commcell import Commcell from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate if not os.path.exists('logs/testr.log'): with open('logs/testr.log', 'w+') as logfile: print("Initalized new log file") ...
# Generated by Django 2.2.12 on 2020-06-01 11:53 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('users', '0004_connectedsocialmedia_userdetail_usertype'), ] operations = [ migrations.AlterField( model_name='userdetail', ...
import argparse from ImageScraper import ImageScraper, ImageNormalizer scraper = ImageScraper() imageNorm = ImageNormalizer() parser = argparse.ArgumentParser(description='Collect and curate a dataset of images.') parser.add_argument('phrase', nargs=1) parser.add_argument('--count', nargs=1, type=int) parser.add_argu...
group8bits = input('Enter 8 bits: ') while group8bits != '': if group8bits.count('0') + group8bits.count('1') != 8 or len(group8bits) != 8: print('Invalid group of bits.') else: ones = group8bits.count('1') if ones % 2 == 0: parity = '0' else: parity = '...
def add(x, y): try: return x + y except TypeError: raise TypeError('You have different types of data use valid combinations')
# -*- coding: utf-8 -*- CONFIG = { 'name': 'qa', 'task': [ 'memnn' ], 'memnn': { 'model_file': '/apps/data/ai_nlp_testing/qa/train/memnn/memnn.m5', 'feature_compact_path': '/apps/data/ai_nlp_testing/qa/feature/memnn/feature_compact.npz', }, }
from flask import Blueprint, render_template, request, redirect, url_for, session import pymysql from config import * con = pymysql.connect(HOST, USER, PASS, DATABASE) dataAnalys = Blueprint('dataAnalys', __name__) @dataAnalys.route("/dataAnalys") def DataAnalys(): legend = 'Monthly Data' labels = [] for...
import asyncio from typing import List, Optional from hummingbot.connector.derivative.bybit_perpetual import ( bybit_perpetual_constants as CONSTANTS, bybit_perpetual_web_utils as web_utils, ) from hummingbot.connector.derivative.bybit_perpetual.bybit_perpetual_auth import BybitPerpetualAuth from hummingbot.co...
from collections import defaultdict class Graph: def __init__(self, V): self.V = V self.graph = defaultdict(list) def addEdge(self, u, v): self.graph[u].append(v) def isCycleUtilDfs(self, v, visited, recstack): visited.add(v) recstack.add(v) if v not in se...
# coding: utf-8 import pilasengine from settings import IMG_DIR pilas = pilasengine.iniciar() grilla = pilas.imagenes.cargar_grilla(IMG_DIR+"/grillaPEQUE.png", 23) grilla_animacion = pilas.actores.Animacion(grilla, True) pilas.ejecutar()
from argparse import ArgumentParser import requests HTTP_PREFIX = 'http://' WWW_PREFIX = 'www.' def escape_page(url): url = url[len(HTTP_PREFIX):] if url.startswith(WWW_PREFIX): url = url[len(WWW_PREFIX):] return url.replace('/', '_') def read_pages_file(page_list_filename): result = set() ...
import numpy as np import pandas as pd class ProbabilityMatrix: def __init__(self, prob_vec_dict: dict): assert len(prob_vec_dict) > 1, \ "The numebr of input probability vector must be greater than one." assert len(set([str(x.states) for x in prob_vec_dict.values()])) == 1, \ ...
from PyQt5.QtWidgets import * from numpy.core.numeric import False_ from unidecode import unidecode # Para eliminar los acentos import nltk # Para dividir el texto en tokens from nltk.tokenize import word_tokenize, sent_tokenize from nltk.corpus import stopwords # Para eliminar las palabras vacías from nltk.stem imp...
#import FPDF from fpdf module from fpdf import FPDF # save FPDF() class into a # variable pdf pdf=FPDF() #Add a page pdf.add_page() # set style and size of font # that you want in the pdf pdf.set_font("Arial",size=15) #open the pdf file in text mode f=open("myfile.txt","r") #insert the texts in pd...
#https://www.hackerrank.com/challenges/manasa-and-stones t = int(input().strip()) for i in range(t): n = int(input()) a = int(input()) b = int(input()) if(a!=b): c = a if a<b else b d = b if c==a else a ans=[] for j in range(n): temp = (n-1-j)*c + j...
import random randomNumber = random.randint(1,100) #I create a variable guess that stores the user's guess guess = str(input('Guess a number between 1 and 100, you have 5 guesses')) if type(guess)!= int: guess = input('Input is invalid, type a number ') #I create a counter that gets one added to it every loo...
import json import datetime import pandas as pd import pmdarima as pm with open('data\\states_daily.json') as f: data = json.load(f) confirmed_df = pd.DataFrame(data['confirmed']) confirmed_df['date'] = pd.to_datetime(confirmed_df['date'], infer_datetime_format=True) confirmed_df.index = confirmed_df['date'] conf...
#!/usr/bin/env python3 from tkinter import * from ascii_art import saint_clever print(saint_clever) window = Tk() window.title('Unit Convertor') def kilograms_to_grams_pounds_ounces(): # print('converted') output_grams.delete(1.0, END) # clear previous output grams = float(input_kilograms.get()) * 1000 outp...
# using range a = ['Mary', 'had', 'a', 'little', 'lamb'] for i in range(len(a)): print(i, a[i]) # using lambda def make_incrementor(n): return lambda x: x + n def make_incrementor1(n): return n f = make_incrementor(42) print(f(42))
import textbook def tb_similarity(samples, chs = None): samples_textbook = [sample.text for sample in samples]+textbook.getOrderedText(chs = chs) vectorizer = textbook.getTfidfVectorizer(chs = chs) tfidf = vectorizer.transform(samples_textbook) similarity = (tfidf*tfidf.T).A similarity = similarity[0:len(samples)...
# Loops print("Loops") for x in range(0, 11, 2): print(x) for x in range(10, -1, -1): print(x) title = "Good Die Young" print(title[0]) for index in range (0, len(title)): print(title[index]) for index in range (len(title)-1, -1, -1): print(title[index]) for letter in title: ...