text
stringlengths
38
1.54M
from django.contrib.auth.mixins import PermissionRequiredMixin, LoginRequiredMixin from django.contrib.auth.models import User from django.contrib.auth import authenticate, login, logout, update_session_auth_hash from django.shortcuts import render, redirect from django.urls import reverse from django.views.generic im...
#!/usr/bin/env python import subprocess,sys,struct,os,time,shutil if len(sys.argv) < 5: sys.exit( 'Usage : [Read file] [k] [nks (min occurence of kmer)] [output file]' ) debut=time.time() readFile=sys.argv[1] k=sys.argv[2] nks=sys.argv[3] output=sys.argv[4] print "PHASE 1 : Get Kmers" subprocess.call(['dsk','-f...
# -*- coding: utf-8 -*- # # $Id: WavFiles.py 3445 2011-08-08 15:46:38Z jhill $ # # This file is part of the BCPy2000 framework, a Python framework for # implementing modules that run on top of the BCI2000 <http://bci2000.org/> # platform, for the purpose of realtime biosignal processing. # # Copyright (C) 200...
import matplotlib.pyplot as plt import numpy as np from matplotlib import patches from PIL import Image from homography import read_homography from metrics.evaluation_funcs import compute_IDF1 from model.video import Video from utils.sort import Sort, convert_x_to_bbox class Camera: def __init__( self, s...
from ems.config_reader.loaders import UserArguments import importlib def read_user_input(): """ Sets up the command line interface to ask for config file location """ # TODO If we don't want to support optional command line args, UserArgument's implementation can go here. usr_args = UserArguments() re...
# -*- coding: utf-8 -*- # # (c) 2014 Bjoern Ricks <bjoern.ricks@gmail.com> # # See LICENSE comming with the source of 'trex' for details. # from rest_framework import generics, status from rest_framework.response import Response import trex.filters as filters from trex.models.project import Project, Entry, Tag from ...
import torch from models import register_arch from layers import feature from layers.classifiers import make_fc_layers from layers import resnet2d from relation import RBLOCK_REGISTRY import torch.nn as nn import torch.nn.functional as F import os import logging from layers.spec_aug import freq_masking, time_masking lo...
listanotas=[] i=1 Cantidad=5 while Cantidad>0: Num=(float(input('Digite su nota '+str(i)+(': ')))) if Num>=5.1: print('no se admiten valores mayores a 5') break i+=1 listanotas.append(Num) Cantidad-=1 Total=(listanotas[0]*0.15)+(listanotas[1]*0.2)+(listanotas[2]*0.15)+(...
print("Welcome to the delegation link generator: Easy-Delegate.") delegator = input("\n Who is the delegator? \n") delegatee = input("\n Who is the delegatee? \n") vesting_shares = input("\n Amount of the delegation: \n") print("\n Generating ...") print("\n Link:") print("https://hivesigner.com/sign/delegateVestingSh...
"""Script for solving monte carlo assignment problem 9""" import numpy as np import matplotlib.pyplot as plt import itertools class M9Map: """Problem 9 travelling salesman map with enhanced features.""" def __init__(self, n_towns: int, sim_range: list = [0.0, 1.0]): self.n_towns = n_towns se...
import requests import re import logging import coloredlogs from urllib.parse import quote from base64 import b64encode class Archie: def __init__(self, host, username, password, debug_mode=False): self.credentials = '' self.token = '' self.host = host self.username = username ...
''' 카드 정렬하기 [핵심유형] 문제형: 정렬된 두 묶음의 숫자 카드가 있다고 하자. 각 묶음의 카드의 수를 A, B라 하면 보통 두 묶음을 합쳐서 하나로 만드는 데에는 A+B 번의 비교를 해야 한다. 이를테면, 20장의 숫자 카드 묶음과 30장의 숫자 카드 묶음을 합치려면 50번의 비교가 필요하다. 매우 많은 숫자 카드 묶음이 책상 위에 놓여 있다. 이들을 두 묶음씩 골라 서로 합쳐나간다면, 고르는 순서에 따라서 비교 횟수가 매우 달라진다. 예를 들어 10장, 20장, 40장의 묶음이 있다면 10장과 20장을 합친 뒤, 합친 30장 묶음과 40장을 합친다...
import csv import warnings from types import MethodType # if we're not running this as a script and importing it, we want the debug features if __name__ != '__main__': debug_mode = True else: debug_mode = False errorfile = open('sunshine-errors.txt', 'wb') # The university names are not consistent, so we need to ...
#include <QObject> #include <QMap> #include <QTimer> #include <QMutex> #include "httpglobal.h" #include "httpsession.h" #include "httpresponse.h" #include "httprequest.h" """ Stores HTTP sessions and deletes them when they have expired. The following configuration settings are required in the config file: <code>...
from ml_video_metrics.video_object_segmentation.metrics.metric_base import MasksMetric class Precision(MasksMetric, kind="precision"): """Class that calculates the Precision metric""" def calculate(self, true_mask_matrix, predicted_mask_matrix, **kwargs): true_positive = self.get_true_positive(true_m...
#!/usr/bin/env python import sys sys.path.append('.') from uuid import uuid4 import arrow import requests from rdflib import Graph, URIRef, Literal from util.generators import random_utf8_string default_n = 10000 webroot = 'http://localhost:8000/ldp' #webroot = 'http://localhost:8080/rest' container_uri = webroot...
from vision.ssd.vgg_ssd import create_vgg_ssd, create_vgg_ssd_predictor from vision.ssd.mobilenetv1_ssd import create_mobilenetv1_ssd, create_mobilenetv1_ssd_predictor from vision.ssd.mobilenetv1_ssd_lite import create_mobilenetv1_ssd_lite, create_mobilenetv1_ssd_lite_predictor from vision.ssd.squeezenet_ssd_lite impor...
from google.cloud import spanner import settings spanner_client = spanner.Client() table = settings.TBL_NAME src_instance = spanner_client.instance(settings.SRC_INSTANCE_ID) src_database = src_instance.database(settings.SRC_DATABASE) data = [] with src_database.snapshot() as snapshot: results = snapshot...
import subprocess import os import time class Gazebo: def on_start(self): """This block is used to launch gazebo in noVNC it builds the ros workspace, source it , then run a launch file which run gazebo ros and load the appropriate world file. """ self.ws_path = self.get_...
from ev3dev.ev3 import * import Planet import motors import math import const # rough_direction ist 0 in Richtung Norden und zaehlt sonst im Uhrzeigersinn Grad hoch # also 90 Grad sind Osten, 180 Sueden und 270 Westen # es enthaelt immer die letzte bekannte Richtung an einem Knoten # Norden: y + # Osten: x ...
import tensorflow as tf import conf class Layer: def __init__(self, shape, std, v): self.w = tf.Variable(tf.truncated_normal(shape=shape, stddev=std)) self.b = tf.Variable(tf.constant(value=v, shape=[shape[-1]])) class ConvolutionLayer(Layer): def __init__(self, shape, std, v): super(...
# https://leetcode.com/problems/power-of-four/ # # Given an integer (signed 32 bits), write a function to check whether it is a power of 4. # # Example: # Given num = 16, return true. Given num = 5, return false. # # Follow up: Could you solve it without loops/recursion? # # Not sure how i would do this without loops i...
DEFAULT = { "username": ["admin", "manager", "both", "role1", "root", "role", "tomcat", "superuser","test","administrator"], "password": ["Password1", "password1", "password", "admin", "tomcat", "changethis", "manager", "root", "r00t", "toor", "s3cret", "role1", "superuser", "test", "koolix", "1234"...
from pathlib import Path import cv2 from mmdet.apis import init_detector, inference_detector import mmcv import os import imutils config_file = './configs/cascade_rcnn/cascade_rcnn_r50_caffe_fpn_1x_coco.py' checkpoint_file = './work_dirs/cascade_rcnn_r50_caffe_fpn_1x_coco/latest.pth' # build the model from a config...
import os import imp from lib.datasets.dataset_catalog import DatasetCatalog def make_visualizer(cfg): task = cfg.task data_source = DatasetCatalog.get(cfg.test.dataset)['id'] module = '.'.join(['lib.visualizers', data_source, task]) path = os.path.join('lib/visualizers', data_source, task+'.py') ...
#!/usr/bin/env.python # -*- coding:utf-8 -*- n, k = map(int, input().split()) l = [None]*n for i in range(n): name,h = input().split() h = int(h) l[i] = (-h, name) l.sort() num, left = divmod(n,k) numforeach = [num]*k numforeach[0] += left i = 0 for r in range(k): j = numforeach[r] row = [None]*j ...
# -*- coding: utf-8 -*- """ Spyder Editor Load English dictionary """ with open('.\dictionaryFiles\OEngDictionary.txt', encoding="utf8") as f: lines = f.readlines() print(lines[1])
# Created on Wed May 31 14:48:46 2017 # Modify 18-3-30 9:33 # # @author: Frederik Kratzert modify by GYxiaOH """Containes a helper class for image input pipelines in tensorflow.""" import tensorflow as tf import numpy as np from tensorflow.contrib.data import Dataset from tensorflow.python.framework import dtypes fr...
#!/usr/bin/python3 """ An application server """ from flask import Flask app = Flask(__name__) @app.route('/') def hello(): """ an simply routing """ return 'Hello HBNB!' if __name__ == '__main__': app.run()
#!/usr/bin/env python3 from get_input import get_input, line_parser from day23 import Assembunny, Command from copy import deepcopy from itertools import count class Assembunny_v2(Assembunny): @Command.command(r'out (\S+)', Assembunny.commands) def out(a): return a.get() def part1(program): for ...
# Copyright 2014 rehabstudio. All rights reserved. # # 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...
a=[1,2,3,4,5] for i in a: while i==5: #print("enterted value is ",i,end="\n") print("all items in the list are displayed!") if(i!=4): print("something is wrong") break ...
import math import collections from PA import * ''' This file is for random walk ''' def initialize(G, num): stubborn_agents = random.sample(list(G), num) for node in G: G.nodes[node]['particle'] = 1 if node in stubborn_agents: G.nodes[node]['stubborness'] = 1 else: ...
import logging import shutil import git from ogr.abstract import GitProject, GitService from packit.utils import is_git_repo, get_repo logger = logging.getLogger(__name__) class LocalProject: def __init__( self, git_repo: git.Repo = None, working_dir: str = None, branch: str = N...
N = int(input()) def fac(n): num = 1 while n >= 1: num = num * n n = n - 1 return num print(fac(int(N)))
# -*- coding: utf-8 -*- import scrapy from ganji.items import Pcauto_comments import time from scrapy.conf import settings from scrapy.mail import MailSender import logging import random import re import hashlib from hashlib import md5 website='pcauto_comments' class CarSpider(scrapy.Spider): name=...
# -*- coding: utf-8 -*- """ Created on Wed May 6 23:43:34 2020 @author: Administrator """ import requests params={"content":''' ①投诉原因:因有信号无法正常使用引发用户的投诉 ②核实情况:根据用户诉求查询AN-AAA正常、AAA正常,HLR状态正常 ③处理结果:投诉原因:市电停电,富宁里达共移动基站目前已经恢复正常,联系用户,用户不在投诉区域,建议用户返还投诉区域后使用观察,用户表示认可 ④回复用户情况:(录音流水号 1901050000212832 )12947回复用户认可、无异议 ⑤说明备注:无...
import os import cv2 from haar_cascades.haar_classifier import HaarClassifier from image_processing.base_actions import draw_rectangle from limits import CWD from utils.input_video_stream_handler import InputVideoHandler from utils.output_video_stream_handler import OutputVideoHandler def process_frame(frame): ...
# Generated by Django 2.2 on 2019-05-11 06:04 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('movie', '0012_auto_20190509_1228'), ] operations = [ migrations.AlterField( model_name='place', name='hall_place', ...
# import tkinter from flask import Blueprint, render_template, request, session from utilities.db.db_manager import dbManager from utilities.db.DB_query import DBQuery from flask import flash products = Blueprint('products', __name__, static_folder='static', static_url_path='/products', template_...
# -*- coding: utf-8 -*- """ Created on Sun Jan 31 20:29:44 2021 @author: SVW_E """ #数据加载 import pandas as pd df=pd.read_csv('car_complain.csv') #数据处理 df=df.drop('problem',axis=1).join(df.problem.str.get_dummies(',')) #数据清洗 def f(x): x=x.replace('一汽-大众','一汽大众') return x df['brand']=df['brand']....
# pyre-strict # Copyright (c) The Diem Core Contributors # SPDX-License-Identifier: Apache-2.0 from functools import wraps import typing import logging, inspect from wallet.storage.logs import add_execution_log RT = typing.TypeVar("RT") TFun = typing.Callable[..., typing.Optional[RT]] def log_execution(message: s...
import random countrydict = {"Slovenia": "Ljubljana", "Croatia": "Zagreb", "Austria": "Vienna", "Italy": "Rome", "Germany": "Berlin"} def get_random_country(countrydict): country = random.choice(countrydict.keys()) return country capitalpicturedi...
import pymysql from appFlask import app from configMysql import mysql from flask import jsonify from flask import flash, request @app.route('/user') def user(): try: conn = mysql.connect() cur = conn.cursor(pymysql.cursors.DictCursor) cur.execute("select * from users") rows = cur.fe...
# if, else, elif ''' False: False None 0 0.0 '' [] () {} set() others is True ''' ''' == != < <= > >= in ... ''' a = 1 b = 2 if a>b: print("a大于b") else: print("a小于b") # \ print("hello \ world") if (a > b): print("a大于b") elif (a == b): print("a等于b") else: print("a小于b") really = True if really: prin...
#!/usr/bin/env python # -*- coding: utf-8 -*- import os from config import config _conf_file_path = os.path.abspath(os.path.dirname(__file__)) + "/" app = config(_conf_file_path + 'app.ini', raw=True) api = config(_conf_file_path + 'api.ini', raw=True) database = config(_conf_file_path + 'database.ini') redis = confi...
import mysql.connector mydb = mysql.connector.connect( host="localhost", user="root", passwd="1234free", database="eran" ) print(mydb) ids=[] def run_select(): ''' run select on customer table :return: ''' #All table cursor = mydb.cursor() ## defining the Query # query...
# W tym pliku będą znajdować się ważne funkcje dotyczące # Symulatora Julki. Zrobiłem to po to by nie zaśmiecać # głównego pliku wykonywalnego. import json configFilePath = "./config.json" loopedAnsw = False randomizeAnsw = False stoppingKeywords = None userCustomJulkaAnsw = None def initConfig(): global config...
import uuid from gevent.queue import Queue, Empty from gevent.event import Event from datetime import datetime, timedelta class Session(object): """ Base class for Session objects. Provides for different backends for queueing messages for sessions. Subclasses are expected to overload the add_message...
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Jan 11 18:11:30 2021 @author: daniel """ class Solution(object): def isPossible(self,side1,side2,side3): if side1 + side2 > side3 and side1 + side3 > side2 and side2 + side3 > side1: return True else: return ...
""" Tests for the client """ from __future__ import division from __future__ import print_function from __future__ import unicode_literals import unittest import mock import json import ga4gh.protocol as protocol import ga4gh.backend as backend import ga4gh.client as client import ga4gh.datarepo as datarepo import t...
#!/usr/bin/env python3 import os import sys import subprocess import signal import shutil import pathlib import yaml import json import time import traceback import web3 from web3 import Web3 # UTILS class Deco(): """Colors used for terminal printing.""" INFO = "\033[94m\033[1m" OK = "\033[92m\033[1m" ...
# -*- coding: utf-8 -*- from keras.models import load_model, model_from_json class Dec_Keras: def __init__(self): self.PATH = "../keras" self.MODEL_PATH = "/model/" self.WEIGHTS_PATH = "/weight/" self.ARCHITECTURE_PATH = "/architecture/" def saveArchitecture(self, model, name)...
#-*- encoding: utf-8 import os import json import sqlite3 import requests from flask import Flask, render_template, request, session from flask import redirect, url_for from lxml import etree app = Flask(__name__) app.secret_key = os.urandom(24) insert_sql = "insert into course_store values('%s', '%s')" insert_com...
# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use ...
#!/usr/bin/env python #****************************************************************************** # Name: radcal.py # Purpose: Automatic radiometric normalization # Usage: # python radcal.py # # Copyright (c) 2013, Mort Canty # This program is free software; you can redistribute it ...
import uuid from vegitablesupplychain.db.supplychainmodels.models import SellOrders, Cart from vegitablesupplychain.service_apis_handler import product_handler, \ user_handler from vegitablesupplychain.utils.exceptions import NotFoundException from vegitablesupplychain.view.sell_order_view import SellOrderView d...
#!/usr/bin/env python """statistics-subnets.py: Usage: statistics-subnets.py [options] < nets Options: -c str counts stat file -q run quietly """ import os, os.path, sys, getopt, re, math from mPATHMARK import * verbose = True outStats = False def usage(code = 0): print __doc__ if co...
import pytest from pytest import approx from pkg_resources import resource_filename import json import responses from jim import RailGrid from jim.delay import (get_delay_share, get_thresholds, to_increments, delay_segments, get_subset, get_delays) from tests.test_trains import tile_url, mock...
def remove_adjacent_dup(s): res = s loop = False while 1: tried = [] for x in res: #if weve tried this char in this string already #skip it (saves us from "abababab" strings) if x in tried: continue else: tried.a...
# -*- coding:utf-8 -*- # Author:Alfred import wx # 自定义窗口类 class MyFrame(wx.Frame): def __init__(self): super().__init__(parent = None,title = "listbox",size = (400,200)) self.Center() # 创建面板 panel = wx.Panel(self) # 创建两个水平布局管理器 hbox1 = wx.BoxSizer() hbox...
import os import torch from cil.utilities.utils import ensure_dir class CheckpointManager: def __init__(self, checkpoint_dir, keep_previous_checkpoints=True): self.keep_previous_checkpoints = keep_previous_checkpoints self.previous_path = None self.checkpoint_dir = checkpoint_dir ...
#!/usr/bin/env python3 import sys sys.path.append("./Importers") from beanmaker import Debit_or_credit, Col, Importer # Col为枚举类型,预定义了每笔交易记录所需要的内容,_config_alipay负责定义枚举内容与csv表头之间的对应关系 _config_alipay = {} _config_alipay[Col.DATE] = u"交易创建时间" _config_alipay[Col.PAYEE] = u"交易对方" _config_alipay[Col.NARRATION] = u"商品名称" _co...
# -*- coding: iso-8859-1 -*- """ Purpose of this file is to run the uv_radtrans function from radiativetransfer.py to generate the surface radiance calculations used to derive the results in our paper. This script: run for the Mars-approximate case (A=desert) """ import radiativetransfer as rt import numpy as np impo...
f1 = open('data/Training_Shuffled_Dataset.txt') f2 = open('data/cornell_nonames.txt') new = open('works/netflix/data/train/chat.txt', 'w') fl1 = f1.readlines() for line in fl1: triple = line.replace('\n', '').split('\t') for triID in range(len(triple)-1): new.write(triple[triID] + '\n') new.write(triple[triID+1]...
# Lab 10 Average Numbers # version 1 =================================================================== nums = [5, 0, 8, 3, 4, 1, 6] counter = 0 for n in nums: counter += n average = counter/len(nums) print('The average of these numbers is: ', average) # version 2 ============================================...
from node_fields import NodeFields from node_core import NodeCore from node_get_fields import NodeGetFields
""" A module that takes graphs, G=(V, E) and attributes on vertices and edges, and generates a .dot file for display with graphviz. The type of graph to be rendered is normalyy just a undirected graph. To render a directed graph, set the keyword parameter graphtype='digraph' the default is graphtype='graph' V...
from app import config from app.main import app if __name__ == '__main__': debugMode = False if(hasattr(config, 'debugMode')): if(config.debugMode == True): debugMode = True app.run(debug=debugMode)
import json as js print(js.dumps({"name": "John", "age": 30})) print(js.dumps(["apple", "bananas"])) print(js.dumps(("apple", "bananas"))) print(js.dumps("hello")) print(js.dumps(42)) print(js.dumps(31.76)) print(js.dumps(True)) print(js.dumps(False)) print(js.dumps(None))
#!usr/bin/env python3 # coding=utf-8 # @IDE :PyCharm # @File :dataargument_test.py # @Date :2019/4/3 import random from PIL import Image from dataset.data_arguments import * import numpy as np img_path = "../resource/1.png" img=Image.open(img_path) # probile = random.random() # print(probile) # img = RandomHor...
import itertools class a4q3: """ Construct cartesian product for attacker * defender and return expected value of loss of attacker. Examples: Attacker rolls 2 dice and defender rolls 1 die. >>> battle1 = a4q3(2,1) >>> battle1.e_value() ...
# -*- coding:utf-8 -*- # @Time :2019/1/2215:47 # @File :.py import unittest from ddt import ddt,data from class_loanhttp.Do_excel import Do_Excel; from class_loanhttp import files_os from class_loanhttp.request import Methed; import json @ddt class Test_Recharg(unittest.TestCase): do_excel=Do_Exc...
from django.conf.urls import url from dbom.views import * urlpatterns = [ #测试 url(r'^test_index/$', test_index, {'funid': '2'}), url(r'^test_jobs/$', test_jobs, {'funid': '2'}), #首页 url(r'^$', index, {'funid': '2'}), url(r'^test/$', test), url(r'^processindex/(\d+)/$', processindex), ...
from google.appengine.ext import ndb def datetime_to_dict(date): return {'year': date.year, 'month': date.month, 'day': date.day, 'hour': date.hour, 'minute': date.minute, 'second': date.second} def date_to_dict(date): return {'year': date.year, ...
# -*- coding:utf-8 -*- #################################################################################### # # Copyright © 2017 TU. All Rights Reserved. # #################################################################################### """ @File: event.py @Description: @Author: leiyunfei(leiyunfei@tuyoogame.c...
#Character Information #Goal is to turn all the sheets into files #def Playable():? import printCharInfo import charToFile def main(): LvLtype=False EXPtype=False print("\nYou are creating a playable character.") name=input("Enter Character Name: ") Class=input("Enter Class: ") while LvLty...
from django.utils.translation import gettext_lazy as _ from djchoices import ChoiceItem, DjangoChoices # TODO: refactor to django-countries # See also the shop.tests.factories.AddressFactory class CountryChoices(DjangoChoices): nl = ChoiceItem("N", _("The Netherlands")) be = ChoiceItem("B", _("Belgium")) ...
from sklearn.metrics.pairwise import euclidean_distances import numpy import csv coeffs = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] # здесь менять коэффициенты, ниже по ключам они же file = open('DS2019/DataScience-2019-PUKS/summary', 'r') reader = csv.DictReader(file, delimiter=';') items = list() indices = list() for ro...
#!/usr/lib/spark/bin/pyspark ## #!/usr/lib/spark/bin/spark-shell # this load a scala shell... # https://spark.apache.org/docs/latest/sql-programming-guide.html#getting-started from pyspark import SparkContext from pyspark.sql import SQLContext sc = SparkContext( 'local', 'pyspark' ) print( " *** hello world s...
import math import os import random import re import sys def findNumber(arr, k): for i in arr: if i == k: return 'YES' return 'NO' arr_count = int(input().strip()) arr = [] for _ in range(arr_count): arr_item = int(input().strip()) arr.append(arr_item) k ...
# Copyright 2016-2022. Couchbase, Inc. # All Rights Reserved. # # 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 a...
#!/usr/bin/python # -*- coding: utf-8 -*- # _\|/_ A ver..., ¿que tenemos por aqui? # (O-O) # ---oOO-(_)-OOo--------------------------------- ########################################################## # ****************************************************** # # * LABORATORIO PARA PRI...
""" defines the endpoints of the API """ import os from flask_api import FlaskAPI from flask_cors import CORS from instance.config import app_config def create_app(config_name): app = FlaskAPI(__name__, instance_relative_config=True) CORS(app) app.config.from_object(app_config[config_name]) app.conf...
# -*- coding: utf-8 -*- """ Created on Tue Nov 3 14:36:32 2020 @author: freel test_audio.linear_model.save_weights('./checkpoints/linear_model') test_audio.linear_multi_model.save_weights('./checkpoints/linear_multi_model') test_audio.dense2_model.save_weights('./checkpoints/dense2_model') test_audio.lstm_dense3_mod...
print(f'{[name[0] for name in ["Elie", "Tim", "Matt"]] =}') print(f'{[num for num in list(range(1,7)) if num % 2 == 0] =}') print(f'{[num for num in list(range(1,5)) if num in list(range(3,7))] =}') names = ["Elie", "Tim", "Matt"] print(f'{names =}') print(f'{[name[::-1].lower() for name in names] =}') print(f'{[num ...
import pyperclip import shelve import sys pwdList = shelve.open('UserPwd') if len(sys.argv) == 2 and sys.argv[1].lower() == '--help': print('Usage: ./passwordSafer.py [-l | -a | -d | -m]') print('-l : to list the entire accounts in database\n-a : to add a new account to database\n-d : to delete an existing account\...
import pandas as pd import numpy as np import matplotlib.pyplot as plt import matplotlib.cm as cm from matplotlib.colors import LogNorm, PowerNorm # %matplotlib inline from scipy import interpolate from mpl_toolkits.basemap import Basemap from mpl_toolkits.axes_grid1 import make_axes_locatable from scipy.misc import ...
# Generated by Django 2.1.7 on 2019-04-16 21:38 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('courses', '0016_auto_20190415_1610'), ] operations = [ migrations.AlterField( model_name='grade', name='file', ...
"""Dataset""" import pickle import numpy as np import tensorflow as tf import config from urdu_alphabet import URDU_ALPHABET_COMPLETE def get_vocab_mapping(): """ Loading the Urdu character mapping Returns: tuple """ vocab = sorted(URDU_ALPHABET_COMPLETE) word2idx = {word: idx for id...
#!/usr/bin/python3 # -*- coding: utf-8 -*- from Item import * class Defense(Item): """ This class Define object type Defense, it is a base for object used for defense in the application. """ def __init__(self,name,maneuverability,protection): """ Initializing the class Defense, it's the constructor, assi...
from django.shortcuts import render, redirect from django.http import HttpResponse, HttpResponseRedirect from django.urls import reverse from django.db import IntegrityError from django.http import JsonResponse from django.views.decorators.csrf import csrf_exempt from django.views.generic import ListView from django.co...
# © 2021 by Maharaj. from odoo.addons.base_jalali_convert.convert_jalali import convert_jalali, convert_jalali_wt from odoo import models, api class SaleOrder(models.Model): _inherit = 'sale.order' def convert_jalali(self, obj): self.ensure_one() return convert_jalali_wt(obj.date_order) ...
# -*- coding: utf-8 -*- class ItemGraph: """ Graph of multi edges that represents the connections between items. Is a undirected weighted multi graph """ def __init__(self, items): """ :param items: the array of db orm items :return: """ self.items = [x for...
# discord auth discordtoken = '' # reddit auth redditusername = '' redditpassword = '' client_secret = '' client_id = '' #mod emojis - use reddit username and emoji or unicode string modemojis = {'edgykitty':'🐱','Uncle_Freddy':u"\U0001F1F5",'IamOlderthanMe':'🐝','MonsterDevourer':'😂', 'FriendEater':'🤰', 's4njee': '...
# Set the alphabet alphabet = "- abcdefghijklmnopqrstuvwxyz" # Putting in our sentence sentence_randomcase = input("Enter your sentence: ") sentence = sentence_randomcase.lower() # Asking the shift length shift_random = int(input("Shift value: ")) shift = shift_random % 26 # Set the empty ciphertext ciphertext = [] ...
expected_dict_int = { 'object': '123', 'type': 'int', 'serializable_by_default': True, 'name': None, 'value': 123, 'dict_class': {}, 'args': {}, 'code': [], 'base64': 'gARLey4=' } expected_dict_class = { 'object': "<class 'formatserializer.testing.services.service_abstract_base.service.ExampleClass'>", ...
import geoalchemy2.functions as geofunc from sqlalchemy import func from models import Users class User: def __init__(self, session): self.session = session def add(self, data: dict): """ add user to database :param data: user params dict 'name', 'coord_x', 'coord_y' ...
from django.core.management.base import BaseCommand from map.models import Marker from map.signals import send_notification class Command(BaseCommand): help = 'Remove all markers' def handle(self, *args, **options): Marker.objects.all().delete() send_notification({ 'type': 'clea...