text
stringlengths
38
1.54M
# Generated by Django 3.1.2 on 2021-07-12 17:02 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('loot', '0014_auto_20201118_1745'), ] operations = [ migrations.AlterField( model_name='item', name='category', ...
import csv import numpy as np from nltk import word_tokenize, pos_tag, ne_chunk def readData(url, max_length): ''' Read Train Data Set ''' with open(url) as tsvfile: reader = csv.DictReader(tsvfile, dialect='excel-tab') array_data = [] array_labels = [] for row in reader: data = row['HEADLINE'] ...
import os import base64 import requests # disable ssl warnings import urllib3 urllib3.disable_warnings() # API configuration and parameters ... pc_address = '10.38.15.9' username = 'admin' password = os.environ.get('PASSWORD', 'nx2Tech911!') # change the password to a suitable value authorization = base64.b64encode(...
import sys from PyQt5.QtWidgets import QMainWindow,QApplication,QHBoxLayout,QVBoxLayout,QLabel,QWidget from PyQt5.QtWidgets import QPushButton,QMessageBox,QLineEdit,QFileDialog,QRadioButton from PyQt5.QtGui import QIcon,QPixmap,QPalette,QBrush,QFont from graduation_project.predict import pre_photo from graduation_...
N = int(input()) A = list(map(int, input().split())) sums =sum(A) l = 0 mlen = sums for i in A: l += i r = sums - l #print("l="+str(l) + "r="+str(r)) lr =l-r if lr <0:lr*=-1 #print("mlen="+str(mlen)+"rl=" + str(lr)) if mlen < lr: break else: mlen = r-l if mle...
from django.shortcuts import render from .models import Fooddishes from .models import Fooddishes1, Toprecipe # Create your views here. def home(request): dishes = Fooddishes.objects.all() dishes1 = Fooddishes1.objects.all() recipes = Toprecipe.objects.all() return render(request, "base.html", {'...
import tensorflow as tf import tensorflow.keras as keras from tensorflow.keras.metrics import AUC, BinaryAccuracy, FalseNegatives, FalsePositives, Precision, Recall, \ TrueNegatives, TruePositives from tensorflow.python.keras.callbacks import LambdaCallback from tensorflow.python.keras.layers import Dropout from te...
# -*- coding: utf-8 -*- """ Created on Wed Sep 30 22:45:10 2020 @author: admin """ import numpy as np import pandas as pd from flask import Flask,render_template,request,jsonify import pickle app = Flask(__name__) model =pickle.load(open('finalmodel_TRB.pkl','rb')) cols_when_model_builds = model.get_bo...
import tkinter as tk # TO DO: turns, purple highlithing for chosen pawn, better code class Checkers(tk.Frame): def __init__(self, parent, *args, **kwargs): tk.Frame.__init__(self, parent, *args, **kwargs) self.parent = parent my_frame = tk.Frame(parent) # holds coords and a corr...
'''' anisotropic TMM formulation PQ formulation breaks down since the differential equation dz([ex, ey, hx, hy]) = Gamma ([ex, ey hx, hy])) has a Gamma matrix which is completely dense ''' import numpy as np import cmath; from scipy.linalg import eig def Gamma(kx, ky, e_tensor, m_r): ''' :param kx: :para...
import datetime import json from flask import Blueprint, jsonify, request, current_app from flask_login import current_user import db from utils import database from utils.file_manager import FileManager, FileType bp = Blueprint("home", __name__) @bp.route("/ping", methods=["GET"]) def ping(): return jsonify({...
#Project Euler Question 48 #Self powers result = 0 for x in range(1,(1000 + 1)): result += (x**x) print (int(str(result)[-10::]))
''' @package fader @brief @details @author Remus Avram @date 2014.12 ''' from PyQt4 import QtCore, QtGui class FaderWidget(QtGui.QWidget): '''Fades between tow widgets''' def __init__(self, old_widget, new_widget=None, duration=1000, reverse=False): QtGui.QWi...
from sklearn import datasets # Load dataset iris = datasets.load_iris() # Create and fit a nearest-neighbor classifier from sklearn import neighbors knn = neighbors.KNeighborsClassifier() knn.fit(iris.data, iris.target) # Predict and print the result result=knn.predict([[0.1, 0.2, 0.3, 0.4]]) print(result)
# -*- coding:utf-8 -*- # __author__ = 'gupan' set_1 = set([1, 2, 3, 4, 5, 6, 7, 8]) set_2 = set([2, 3, 4, 5, 6, 8, 9, 10]) sub_1 = {1, 2, 3} sub_2 = {11} print(set_1) print(set_2) print(set_1.intersection(set_2)) print(set_1.union(set_2)) print(set_1.difference(set_2)) print(set_2.difference(set_1)) print(sub_1.issubs...
import sys import json from twisted.python import log from twisted.internet import reactor from autobahn.twisted.websocket import WebSocketServerFactory, \ WebSocketServerProtocol from utils.thread_with_trace import thread_with_trace from api.tal import Tal from config import token class Anna(WebSocketServerProt...
from django.utils.translation import ugettext_lazy as _ """ Django settings for vminventory project. For more information on this file, see https://docs.djangoproject.com/en/1.7/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.7/ref/settings/ """ # Build paths...
""" Sawyer Bailey Paccione and Olif Soboka Hordofa audioDetection.py Tufts University Spring 2021, ME-0035 Purpose: Detect whether audio was playing or not playing and convey that information to a LEGO SPIKE PRIME Description: This audio detection uses K-Nearest-Neighbors Algorithm. This ...
import uuid from jsonschema import FormatChecker @FormatChecker.cls_checks("uuid") def check_uuid_format(instance): try: uuid.UUID(instance) return True except ValueError: return False print("JSONSchema validation supported for the following 'format' values:") print(", ".join(Format...
import numpy as np from math_utils import * from entities import * def worldgenerator(densities, width, height): floor = np.empty([width, height], dtype=object) for x in range(width): for y in range(height): val = np.sum([step(np.random.uniform(0, 1) - np.sum(densities[:i]), 1) for i in range(1, len(densities))...
class Foo: def func(self): print('我胡汉三又回来了') f1=Foo() f1.func() #调用类的方法,也可以说是调用非数据描述符 #函数是一个非数据描述符对象(一切皆对象么) print(dir(Foo.func)) print(hasattr(Foo.func,'__set__')) print(hasattr(Foo.func,'__get__')) print(hasattr(Foo.func,'__delete__')) #有人可能会问,描述符不都是类么,函数怎么算也应该是一个对象啊,怎么就是描述符了 #笨蛋哥,描述符是类没问题,描述符在...
# Generated by Django 2.0.3 on 2018-10-21 06:31 import datetime from django.db import migrations, models import django.utils.timezone from django.utils.timezone import utc class Migration(migrations.Migration): dependencies = [ ('upload', '0001_initial'), ] operations = [ migrations.Add...
import numpy as np import numpy.fft as fft # Constant parameters Re = 10 nu = 1/Re NX,NY = 128,128 LX,LY = 2*np.pi,2*np.pi deltaX = LX/(NX-1) deltaY = LY/(NY-1) deltaT = 0.001 iter_step = 3000 def pre(): kx1 = np.linspace(-NX / 2, NX / 2, NX, endpoint=False).reshape(NX, 1) kx2 = np.linspace(-NX / 2, NX / 2,...
default_global_configuration = { 'dashboard': { 'show_not_required_requisitions': True, 'show_not_required_scheduled_entries': True, 'allow_additional_requisitions': False}, 'appointment': { 'allowed_iso_weekdays': '1234567', 'use_same_weekday': True, 'default_app...
import mock import unittest import datetime from common import helpers @mock.patch('common.config.DEFAULT_FILTER', {"validity": {"$ne": False}}) class Test(unittest.TestCase): # No argument passed def test_build_mongo_query_no_args(self): response = helpers.build_mongo_query(...
#!/usr/bin/env python ''' Author: Marco Boretto Mail: marco.boretto@cern.ch Python Version: 2.7 ''' import logging import logging.config from controllers import Gfal2Controller import logging import gfal2 if __name__ == '__main__': # logging.config.fileConfig('na62cdr-logging.ini') LOGGER = logging...
""" Extracts frames from youtube live streams Todo: - Add tests Ref: https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_gui/py_video_display/py_video_display.html """ import cv2 import pafy import youtube_dl import time import os from urllib.error import HTTPError import configparser import ...
import itertools class Conjunto: def __init__(self): self.conjunto = [] def adicionar(self, item): if item not in self.conjunto: self.conjunto.append(item) def remover(self, item): self.conjunto.remove(item) def pertinencia(self, item): return...
import time, requests, json, urllib, os from flask import Flask app = Flask(__name__) def get_data(): data = { "tillfalle":"Urval1", "vy":"Antagningspoang", "antagningsomgang":"HT2020", "larosateId":"", "utbildningstyp":"p", "fritextFilter":"", "urvalsGrupp":...
a = int(input()) reverse = 0 while(a > 0): reminder = a %10 reverse = (reverse *10) + reminder a = a//10 print("reverse of entered number is = %d" %reverse)
############################################################################################ ## A multifuntional python script to carryout secondary structure analyses using MDTraj ## ## Author: Sid Narasimhan ## #######################################...
# -*- coding: utf-8 -*- """ Created on Thu Sep 19 11:04:34 2019 @author: Blake """ import sqlite3 import os, sys prev_violations = [] # Checks if database file exists and if it does connects to database, else quits the script def check_db_file(): db_file = "./violations.db" # If file exists, run query i...
def multiply(x,y): result = 0 for i in range(y): result += x print(result) multiply(4,6)
""" Making an index page with search Engine for the Leetcode root folder @author: pkugoodspeed @date: 06/12/2018 @copyright: jogchat.com """ import os from jinja2 import Template from .utils import ColorMessage, getHtmlElement def _getIndexStyle(font="Chalkduster", theme="silver", boxcolor="gray", hovercol...
BASE_HOST = "http://0.0.0.0" PORT = 5000 BASE_PATH = "/api/" def get_formatted_URL(): return "{}:{}{}".format(BASE_HOST, PORT, BASE_PATH)
""" @author: Tingxuan Gu """ import logging import os from datetime import datetime, date from typing import Optional from urllib import error import rootpath import wget rootpath.append() from backend.connection import Connection from paths import SOIL_MOIS_DATA_DIR from backend.data_preparation.crawler.crawlerbase ...
import asyncio import json import pymongo import redis import opentracing import logging import time from nats.aio.client import Client as NATS from nats.aio.errors import ErrConnectionClosed, ErrTimeout, ErrNoServers from jaeger_client import Config async def run(loop): #=============== configuracion con servidor...
# -*- coding: utf-8 -*- # Copyright (C) 2016-TODAY touch:n:track <https://tnt.pythonanywhere.com> # Part of tnt: Flespi Monitoring addon for Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, fields, models class TntFlespiDeviceLog(models.Model): _inherit = 'tnt.flespi.device....
#Python program to get an input string from the user and replace all the empty spaces with _ underscore symbol input_string=input("enter the input string :") print("The input string is ",input_string) for x in input_string: if (x==" "): replaced_string=input_string.replace(" ","_") print("The input string after repl...
def funcao(nome,fabricante,**carro): carros={} carros["nome"]=nome carros["fabricante"]=fabricante for key, value in carro.items(): carros[key]=value return carros a=funcao("camaro","Chevrolet",ano=2015,porência=461) print(a)
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (C) 2016 Paul Brodersen <paulbrodersen+entropy_estimators@gmail.com> # Author: Paul Brodersen <paulbrodersen+entropy_estimators@gmail.com> # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public Li...
''' Approach 1: Backtracking Algorithm Backtracking is an algorithm for finding all solutions by exploring all potential candidates. If the solution candidate turns to be not a solution (or at least not the last one), backtracking algorithm discards it by making some changes on the previous step, i.e. backtracks an...
produkty = {'S1222': 'sukienka trojkat', 'P1222': 'spodnie krata', 'X212': 'konsola do gier'} igla = 'X2X' if igla in produkty: print("znalazlem{0}".format(igla)) else: print("Brak w magazynie {0}".format(igla))
#!/usr/bin/python3 #The seed() method initializes the basic random number generator. Call this function before calling any other random module function. # seed ([x], [y]) import random random.seed() print ("random number with default seed", random.random()) random.seed(10) print ("random number with int seed", random....
def solution_seventeen(str): sub_str = str[-2:] return sub_str * 4 print(solution_seventeen('Mcnilly')) print(solution_seventeen('Goshomi'))
from yolo3.model import YoloBody, TinyYoloBody, model_saver, channel_move_forward, yolo_head from yolo3.utils import letterbox_image import os import numpy as np import torch import colorsys import time import cv2 from PIL import Image, ImageFont, ImageDraw class Yolo(): def __init__(self): sel...
""" Creates CSV files where the data manipulations and cleaning are performed """ import csv import processor def writecsv(filename, keyword=None): """ Function for writing data into csv files :param filename: Name of the file to be generated """ if filename == 'tracksearch': print('Gener...
#Algoritmos y programación I. #Cátedra: Essaya. #Práctica: Grace. #Nombre: Mauro Javier Santoni. #Padrón: 102654. #Corrector: Juan Patricio Marshall. """ Conway's Game of Life --------------------- https://es.wikipedia.org/wiki/Juego_de_la_vida El "tablero de juego" es una malla formada por cuadrados ("células") que...
#记录生肖,根据年份来判断 #python对双引号和单引号没有区分,当str里面含有单引号就用双引号 chinses_zodiac = '猴鸡狗猪鼠牛虎兔龙蛇马羊' #print(Chinses_zodiac[0:4]) #从后往前用负数 #year = 2018 #print(year % 12) #print(Chinses_zodiac[year % 12]) #print('狗'in Chinses_zodiac) #year = int(input('请输入出生年份:')) #for cz in Chinses_zodiac: # print(cz) #for i in range(1,13): # pr...
import csv import glob import os import pathlib import random import subprocess import sys import cv2 # import dlib import joblib import numpy as np from tqdm import tqdm import shutil # import Models.Config.SEResNet50_config as config from mtcnn.mtcnn import MTCNN base_path = os.path.dirname(os.path.abspath(__file__)...
from sklearn import svm class Classifier: def __init__(self, configuration): self.configuration = configuration self.classifier = svm.SVC(kernel='linear', C=1000) # self.classifier = svm.SVC() # self.classifier = svm.LinearSVC() # self.classifier = svm.SVC(decision_function...
import time from fastapi import status, HTTPException from src.service.lesson_interface import LessonsInterface def hello_world(): return "Hello World!" def why_python(): return """ Tcl -- It is short (only three letters) and does a suprising amount given that it doesn't have a vowel. ...
#!/usr/bin/env python import sys filename = sys.argv[1] nfile = filename.split('.')[0] + '_swapped.2dm' with open(nfile, 'w') as ofile: with open(filename) as ifile: for line in ifile.readlines(): if line.split()[0] == "ND": h, n, x, y, z = line.split() nli...
#!/usr/bin/env python """ Test file for creating data training module """ import sys import pickle import string import random import re import math import nltk import numpy as np from nltk import FreqDist from nltk.tokenize import TweetTokenizer from nltk.corpus import stopwords from nltk.classify.scikitlearn import S...
import os import json import numpy as np import pandas as pd from itertools import chain from keras import optimizers from keras.applications.inception_v3 import InceptionV3, preprocess_input from keras.models import Model from keras.layers import Input from keras.layers import Dense, GlobalAveragePooling2D from keras....
import greenthumb import json import sched from greenthumb import util from greenthumb.models.mongo import (users, gardens, plant_types, user_plants) from flask import (abort, request, session, jsonify) import datetime import bson """ GreenThumb REST API: usergarden. GreenThumb Group <greenthumb441@umich.edu> ""...
from django.urls import path, include from rest_framework import routers from rest_framework.authtoken import views ## Import views from the Rest API from restAPI.views import ( TeamView, ProjectView, DefectView, ReviewView, ProductView, PhaseTypeView, UserView ) """ *** This file is used ...
from typing import Dict, Generator, List from dateutil.relativedelta import relativedelta from django.utils import timezone from ee.clickhouse.client import sync_execute SLOW_THRESHOLD_MS = 10000 SLOW_AFTER = relativedelta(hours=6) SystemStatusRow = Dict def system_status() -> Generator[SystemStatusRow, None, Non...
# -*- coding: utf-8 -*- from bot_proto import * from db_proto import DB def feedback_handler(update, feedback_state): if 'message' in update: message = update['message'] if 'from_id' in update: from_id = update['from_id'] if feedback_state == 1: log_event("FEEDBACK: {0}".format(m...
#!/usr/bin/python import boto3 import json import logging import time import sys import click client = boto3.client('iam') logging.basicConfig(filename='output.log', level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s') iam_output = dict() # Generating credentials report def get_credent...
import os def upload_cover_dir(obj,file_obj): file_ext = file_obj.split('.')[-1].lower _file = '{0}.{1}'.format(obj.id,file_ext) return os.path.join('book_cover',_file) def upload_pdf_dir(obj,file_obj): file_ext = file_obj.split('.')[-1].lower _file = '{0}.{1}'.format(obj.id,file_ext) return os.path.join('pdf'...
# -*- coding:utf8 -*- import os, sys, re, json import argparse from copy import deepcopy from copy import deepcopy from bs4 import BeautifulSoup from pyquery import PyQuery as pq from urllib.parse import urljoin import vthread import pymongo from copy import deepcopy html_text = ''' <div id="main-content" class="regio...
Num = int(input("Please enter a number:")) #print(Num%2) NumStr = str(Num) if(Num%2 == 0): print( NumStr +" is an Even Number") else: print(NumStr +" is a Odd Number")
from .mnist import get_mnist from .usps import get_usps from .sixteen_class_imagenet import get_16_class_imageNet_dataloader __all__ = (get_usps, get_mnist, get_16_class_imageNet_dataloader)
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Author rsg # import os import datetime import time import logging from utils import random_str logger = logging.getLogger(__name__) class FileService(object): def __init__(self, file_name, content): self._file_name = file_name self._content = c...
from dataloader import PortraitDataloader, PortraitToInferloader, mean, std import torch import segmentation_models_pytorch as smp from matplotlib import pyplot as plt import numpy as np import pandas as pd from pathlib import Path import os import cv2 #base_path = Path(__file__).parent.parent data_path = Path("./APDr...
import sys import traceback from typing import List from importlib import util from ConfigValidator.CustomErrors.BaseError import BaseError from ConfigValidator.CLIRegister.CLIRegister import CLIRegister from ConfigValidator.Config.Validation.ConfigValidator import ConfigValidator from ConfigValidator.CustomErrors.Con...
# graph by adjacency matrix INF = 99999999 #infinity graph = [ [0,7, 5], [7,0,INF], [5,INF,0] ] print(graph)
#Exemplo de rede convolucional usando Keras from keras.datasets import mnist from keras.utils.np_utils import to_categorical from keras.models import Sequential from keras.layers import Dense, Dropout, Conv2D, Flatten, MaxPooling2D (x_treino, y_treino), (x_teste, y_teste) = mnist.load_data() print(x_treino.sh...
import unittest from algkit.solutions import find_words, exist_word class WordSearchTestCase(unittest.TestCase): def test_find_words_n1(self): board = [ ['o', 'a', 'a', 'n'], ['e', 't', 'a', 'e'], ['i', 'h', 'k', 'r'], ['i', 'f', 'l', 'v'] ] ...
# # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: @staticmethod def get_carry_on(num): if num >= 10: return num - 10, 1 else: return num, 0 @staticmethod def n...
import app import item import uiScriptLocale window = { "name" : "Acce_CombineWindow", "x" : 0, "y" : 0, "style" : ("movable", "float",), "width" : 215, "height" : 270, "children" : ( { "name" : "board", "type" : "board", "style" : ("attach",), "x" : 0, "y" : 0, "width" : 215, "height" :...
#!/usr/bin/env python # imports from standard python from __future__ import print_function import os import sys # imports from local packages # imports from pip packages import keras import six # imports from MiST from MiST import eval from MiST import train from MiST import multi_train from MiST import utilis from...
''' check the +/- of the 10 E. coli specific regions for each of the downloaded enterobase genomes, and compile that as a table. eg. `name` `marker 1` `marker 2` `marker N` ''' import csv import logging import os import subprocess import sys import tempfile from tqdm import tqdm from multiprocessing import pool loggi...
from django.contrib import admin # Register your models here. from .models import newsletter_list class NewsletterAdmin(admin.ModelAdmin): list_display = ['email_address', 'user_name', 'threshold', 'timestamp', 'updated'] list_filter = ['email_address', 'user_name', 'threshold', 'timestamp', 'updated'] search_fi...
n = int(input()) numbers = [x for x in input().split()] count_final = 0 result = numbers[0] for i in numbers: count = 0 for j in range(len(numbers)): if i == numbers[j]: count += 1 if count > count_final: count_final = count result = i print(result)
from django.contrib import admin from polls.models import Person # Register your models here. admin.site.register(Person)
def is_polydivisible(s, b): digit_list = list(s) list_len = len(digit_list) + 1 list_power = range(1, list_len) list_power.reverse() base_10 = 0 for i, j in zip(digit_list, list_power): base_10 += int(i)*(b**j) decider = 0 base_10_list = [int(x) for x in str(base_10)] cal...
from component import * destroyables = [] def get_destroyables(): return destroyables # singleton class Destroyable(Component): type = 'destroyable' def __init__(self, shape = None, prefix = ''): self.shape = shape self.prefix = prefix def attach(self, entity): super(Destroya...
#encoding: UTF-8 # Autor: Karla Fabiola Ramirez Martinez # Descripcion: Porcentaje hombres y mujeres mujeres=int(input("Dime el numero de mujeres que hay: ")) hombres=int(input("Dime el numero de hombres que hay: ")) total=mujeres+hombres porcentaje=100/total pmujeres=porcentaje*mujeres phombres=porcentaje*hombres p...
#!/usr/bin/python3 # -*- coding: utf-8 -*- import itertools for x in itertools.permutations( [ 1, 2, 3, 4 ] ) : print( x )
""" Utilities for lists. """ from __future__ import absolute_import from __future__ import print_function from six.moves import xrange import numpy as np from operator import itemgetter from itertools import groupby def list2ndarray(a): if(isinstance(a, list)): return np.asarray(a) assert(isinstance(...
from thumbnail_image.utils import AWSUtils, ImageUtils, FileUtils class UploadThumbnailImageToS3: _s3_client = None def __init__(self, s3_client) -> None: self._s3_client = s3_client def execute(self, s3_event: dict) -> str: bucket, key = AWSUtils.get_s3_data(s3_event) if no...
# # Copyright (c) 2023, Gabriel Linder <linder.gabriel@gmail.com> # # Permission to use, copy, modify, and/or distribute this software for any # purpose with or without fee is hereby granted, provided that the above # copyright notice and this permission notice appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS"...
class Calculator: def __init__(self): self.result = 0 def add(self, num): self.result += num return self.result cal1 = Calculator() cal2 = Calculator() print(cal1.add(3)) print(cal1.add(4)) print(cal2.add(3)) print(cal2.add(7)) class FourCal: pass a=FourCal(...
import numpy as np import pandas as pd def mbe(observe:pd.DataFrame, predict:pd.DataFrame) -> pd.DataFrame: """Mean bias error of predicted data. Calculates mean bias error as sum(predict - observe)/(total entries). Parameters ---------- observe : pandas.DataFrame Observed va...
""" linked list ADT, a simple one, demonstrate the add """ class _Node: __slots__ = '_element', '_next' def __init__(self, element, next): self._element = element self._next = next class SinglyLinkedList: """singly linked list, no dummy head""" def __init__(self): se...
import base64 import re import graphene from graphene_django.registry import get_global_registry from graphql_relay import from_global_id registry = get_global_registry() INT_PATTERN = r"^\d+$" def get_id_from_base64_encoded_string(value): if isinstance(value, int): return value if re.match(INT_PAT...
#!/usr/bin/python import scipy.io.wavfile as wavfile import numpy #from scipy import signal #import matplotlib.pyplot as mplot import pydemod.modulation.phase as phasemod import pydemod.coding.manchester as manchester import pydemod.coding.polynomial as poly import pydemod.app.amss as amss import sys # symbolLengt...
import torch import time import numpy as np import logger import get_data_greedy import encoder_greedy import arg_parser import model_utils def load_model_and_optimizer(opt, num_GPU=None): resnet = encoder_greedy.FullModel(opt) optimizer=[] for idx, layer in enumerate(resnet.encoder): ...
try: import cPickle as pickle except: import pickle import six, os, sys, csv, time, \ random, os.path as osp, \ subprocess, json, \ numpy as np, pandas as pd, \ glob, re, networkx as nx, \ h5py, yaml, copy, multiprocessing as mp, \ pandas as pd, yaml, collections, \ loggin...
""" Created on Wed Sep 18 16:47:06 2019 @author: Kanthasamy Chelliah The function wavogram(wavFile) provides spectrogram for any wav file (mono). Simple usage: wavogram(wavFile) Optional arguments: str: pltTitle => send any string to be used as the plot title. bool: masked => set to false if full data needs to ...
# MNIST数据集:http://yann.lecun.com/exdb/mnist/ from tensorflow.examples.tutorials.mnist import input_data # 加载数据集 mnist = input_data.read_data_sets('e:/soft/MNIST_DATA', one_hot=True) # 加载训练集样本 train_x = mnist.train.images # 加载验证集样本 validation_x = mnist.validation.images # 加载测试集样本 test_x = mnist.test.images # 加载训练集标签 t...
import importlib import inspect import json import re import shutil import sys import traceback from os import path from getgauge import logger from getgauge.registry import registry from getgauge.util import * project_root = get_project_root() impl_dirs = get_step_impl_dirs() env_dir = os.path.join(project_root, 'en...
# -*- coding: utf-8 -*- # Generated by Django 1.9 on 2016-04-03 18:36 from __future__ import unicode_literals from django.db import migrations, models import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('pharmacies', '0003_drugs_recommended_price'), ] operation...
u"""Import utils functions.""" from __future__ import absolute_import from .utils import pairwise, unzip, admissible_filter, sanity_check from .bnode import Bnode from .drawbkps import draw_bkps
from rest_framework import serializers from .models import Bucketlist from .models import Teste from .models import Cliente, Notificacao, Promocao, Categoria, Prestador, Servico class BucketlistSerializer(serializers.ModelSerializer): """Serializer to map the Model instance into JSON format.""" class Meta: ...
#!/usr/bin/env python # -*- coding: utf-8 -*- import state def cmd_help(msg): """ Help message for IrcBot @param msg unused, only for consistency with other commands """ help_msg =\ """ IrcBot Implemented commands: help SHUTDOWN word-count karma calc """ return state.do...
import numpy as np import tensorflow as tf from Agent.networks import * np.random.seed(1) tf.set_random_seed(1) class PolicyGradient: def __init__( self, n_actions, learning_rate=0.02, reward_decay=0.95, ): self.n_actions = n_actions self.lr = ...
def add_simple_uvs(): '''Add cube map uvs on mesh ''' pass def add_texture_paint_slot(type='DIFFUSE_COLOR', name="Untitled", width=1024, height=1024, color=(0.0, 0.0, 0.0, 1.0), ...