content
stringlengths
5
1.05M
import json from django.conf import settings import os from csv import reader from mechanism.reactions import reaction_musica_names from dashboard.save import initial_conditions_file_to_dictionary config_path = os.path.join(settings.BASE_DIR, "dashboard/static/config") def option_setup(): with open(os.path.join(c...
from __future__ import absolute_import from __future__ import unicode_literals from builtins import str from builtins import object from django import forms from django.http import QueryDict from isisdata.models import * from isisdata import export # This never gets old... from isisdata import export_authority fro...
# see https://github.com/rtfd/CommonMark-py/blob/master/CommonMark/render/html.py # for the HTML renderer -- this is just a riff on that. import re import commonmark import commonmark.render.renderer class RawHtmlNotAllowed(ValueError): def __init__(self): super(RawHtmlNotAllowed, self).__init__("Raw HT...
import maya.cmds as cmds import maya.OpenMaya as om from keychain.api.utils import matrix as matrix_utils def get_xform_relation(driver, target): # get parent rotOrder = cmds.getAttr("{}.rotateOrder".format(target)) # get driver matrix driverInverseMatrix = matrix_utils.get_matrix_from_xform( ...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ ----------------------------------------- @Author: zhaocy @Email: 19110240027@fudan.edu.cn @Created: 2020/6/22 ------------------------------------------ @Modify: 2020/6/22 ------------------------------------------ @Description: """ from chardet import detect from de...
from nodeconductor.oracle import views def register_in(router): router.register(r'oracle', views.OracleServiceViewSet, base_name='oracle') router.register(r'oracle-zones', views.ZoneViewSet, base_name='oracle-zone') router.register(r'oracle-templates', views.TemplateViewSet, base_name='oracle-template') ...
import pytest import time from common.serializers.serialization import domain_state_serializer from indy_common.authorize.auth_actions import AuthActionAdd, AuthActionEdit from indy_common.authorize.auth_constraints import ConstraintsSerializer from indy_common.authorize.auth_map import auth_map from indy_common.autho...
from argparse import ArgumentParser import codecs import os """ To encode: python /home/david/Escritorio/encoding2multitask.py \ --input /home/david/Escritorio/dataset/ptb/ptb-dev.seq_lu \ --output /tmp/ptb-dev.multitask \ --status encode To decode: python /home/david/Escritorio/encoding2multitask.py \ --input /tmp...
""" This module defines the default metadata and data dictionaries for each explanation method. Note that the "name" field is automatically populated upon initialization of the corresponding Explainer class. """ # Anchors DEFAULT_META_ANCHOR = {"name": None, "type": ["blackbox"], ...
import random from abc import ABC from typing import Optional import gym from rld.rollout import Trajectory, Timestep, Rollout from rld.tests.resources.spaces import ( BOX_OBS_SPACE, IMAGE_OBS_SPACE, DICT_OBS_SPACE, DISCRETE_ACTION_SPACE, MULTI_DISCRETE_ACTION_SPACE, TUPLE_ACTION_SPACE, ) cl...
import numpy as np import matplotlib.pyplot as plt def mystep(x,y, ax=None, where='post', **kwargs): # https://stackoverflow.com/questions/44961184/matplotlib-plot-only-horizontal-lines-in-step-plot assert where in ['post', 'pre'] x = np.array(x) y = np.array(y) if where=='post': y_slice = y[:-1] ...
# 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 ...
from golem import actions from golem.core.exceptions import ElementNotFound description = 'Verify the webdriver.find method throws error when element is not found' def test(data): actions.navigate(data.env.url+'elements/') browser = actions.get_browser() selector = '.invalid-selector-value' actions.st...
from itertools import cycle import glfw import numpy as np import OpenGL.GL as GL from PIL import Image from mesh import Mesh from texture import Texture from transform import normalized from node import Node import config # -------------- Example texture plane class ---------------------------------- class Texture...
from pathlib import Path from fastapi import FastAPI from fastapi import staticfiles from fastapi.staticfiles import StaticFiles from fastapi_static_digest import StaticDigest, StaticDigestCompiler app_root = Path(__file__).parent static_input_dir = app_root / "static" def create_app(output_dir=None): app = Fa...
import threading import socket # Now this Host is the IP address of the Server, over which it is running. # I've user my localhost. host = "127.0.0.1" port = 5555 # Choose any random port which is not so common (like 80) server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #Bind the server to IP Address server.b...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Setuptools build system configuration file for Faker Wi-Fi ESSID. See https://setuptools.readthedocs.io. """ try: from setuptools import setup, find_packages except Exception as setuptools_not_present: raise ImportError( "Setuptools is required to in...
from pylinlin.matrix import Matrix from pylinlin.matrix_view import MatrixView from pylinlin.householder import Householder def compute_qr_factorization(mat: Matrix) -> (Matrix, Matrix): # Do not overwrite original matrix mat = mat.copy() householders = [] # store householder transformations iteratio...
"""Exceptions for artifact I/O""" from altimeter.core.exceptions import AltimeterException class InvalidS3URIException(AltimeterException): """An S3 uri could not be parsed."""
from torch.utils.data import Sampler class GroupLengthBatchSampler(Sampler): def __init__(self, data_source, batch_size, batches_per_group=20): super().__init__(data_source) # TODO: your code here (optional) raise NotImplementedError def __iter__(self): raise NotImplementedErr...
from tornado.websocket import WebSocketHandler class SocketHandler(WebSocketHandler): def __init__(self): print("") users = set() # 用来存放在线用户的容器 def open(self): self.users.add(self) # 建立连接后添加用户到容器中 for u in self.users: # 向已在线用户发送消息 u.write_message("hello") def...
from sqlalchemy import create_engine, MetaData, Table from tabref.searcher import TableSearcher def connect_db(uri): db = create_engine(uri) meta = MetaData(bind=db) meta.reflect(bind=db) return meta class SqlTableSearcher(TableSearcher): def __init__(self, matcher, out_dir, db, table): ...
import uuid from datetime import datetime from django.shortcuts import render, redirect from .models import Classroom, ClassroomStudents, ClassComments from users.decorators import faculty_required, student_required from django.core.exceptions import ObjectDoesNotExist from django.contrib.auth.decorators import login_...
import matplotlib.pyplot as plt from pytest import mark, raises from orbital_diagrams.api import EnergyOrbital from orbital_diagrams.orbitals._base_orbital import BaseOrbital from orbital_diagrams.plot import cycle_values, plotter, setup_axis, subplots def test_setup_axis(): fig, ax = plt.subplots() setup_a...
""" Author: Rômulo do Carmo Sousa Description: Remove todos os arquivos terminados em '(1)' Date: 12-11-2020 """ import os import re import time # Cores ASCII ciano_claro = "\033[1;96m" verde = "\033[1;32m" vermelho = "\033[1;31m" reset = "\033[0;0m" def repeated_files(files): """Retrona uma lista com os arquivo...
#!/usr/bin/env python3 import datetime from common.params import Params from selfdrive.data_collection import gps_uploader print("Don't forget to pray!") params = Params() t = datetime.datetime.utcnow().isoformat() params.put("LastUpdateTime", t.encode('utf8')) if params.get("IsOffroad") == b"1": print("Please wai...
# 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...
""" ci """ from sandboxes.scripts.creators.ci.create_answers import * from sandboxes.scripts.creators.ci.create_questions import * from utils.logger import logger def create_sandbox(): logger.info('create_ci_sandbox...') create_questions() create_answers() logger.info('create_ci_sandbox...Done.')
""" A wrap python class of 'pbsnodes -N "note" node' command The purpose of this class is to provide a simple API to write some attribute and its value pairs to note attribute of cluster nodes. """ from __future__ import print_function from sh import ssh from ast import literal_eval from types import * from copy import...
#repaso a = int(input("Ingrese un numero ")) b = int(input("ingrese otro numero ")) c = a + b if c < 10: print('Su numero es menor que 10 ') elif c > 10: print('Su numero es mayor que 10 ') elif c == 10: print('Su numero es 10 ') print('Su numero es: ', c) input('Pulse enter para continuar...') ...
""" https://leetcode-cn.com/problems/open-the-lock/ https://leetcode-cn.com/problems/open-the-lock/solution/da-kai-zhuan-pan-suo-by-leetcode/ https://leetcode-cn.com/problems/open-the-lock/solution/python-bfs-qing-xi-ti-jie-by-knifezhu/ """ from queue import Queue from typing import List class Solution: def openL...
"""Functions for graph-level featurization of the sequence of a protein. This submodule is focussed on physicochemical proporties of the sequence.""" # %% # Graphein # Author: Arian Jamasb <arian@jamasb.io>, Eric Ma # License: MIT # Project Website: https://github.com/a-r-j/graphein # Code Repository: https://github.co...
from .WS2801Wrapper import WS2801Wrapper from threading import Thread, Event def __wait_for__input(event: Event): input() event.set() def run_effect(target, additional_args=None): event = Event() pixels = WS2801Wrapper() pixels.clear() pixels.show() args = (...
from __future__ import absolute_import from elixir import Entity, ManyToOne, OneToMany, ManyToMany, using_options class A1(Entity): using_options(resolve_root='tests.db1') a2s = OneToMany('A2') bs = ManyToMany('b.B') class A2(Entity): a1 = ManyToOne('A1')
#!/usr/bin/env python """ The appropriate bookmarklet for testing is therefore: javascript:( function(){ var script = document.createElement('script'); var child = document.body.appendChild(script); child.src = 'http://127.0.0.1:8001/bookmarklet.js'; } )(); o...
import copy import theano import numpy from theano import tensor, scalar from theano.compile import optdb from theano.gof import (local_optimizer, EquilibriumDB, SequenceDB, ProxyDB, Optimizer, toolbox, DestroyHandler, InconsistencyError, Equilibri...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ :mod:`fit` ================== .. module:: fit :synopsis: .. moduleauthor:: hbldh <henrik.blidh@swedwise.com> Created on 2015-09-24, 07:18:22 """ from __future__ import division from __future__ import print_function from __future__ import unicode_literals from _...
from django.core.exceptions import PermissionDenied from django.utils.crypto import get_random_string from rest_framework_jwt.settings import api_settings from utils.constants import AUTO_GENERATED_PASSWORD_LENGTH # binding.pry equivalent # import code; code.interact(local=locals()) def get_hustler_data(hustler_obj...
from .handlers import bp __all__ = ("bp",)
import traceback from typing import Union, Callable from functools import wraps, partial from asyncio import iscoroutinefunction from lite_tools.utils_jar.logs import my_logger, logger, handle_exception __ALL__ = ["try_catch"] def try_catch(func=None, *, default=None, log: Union[bool, str] = True, ca...
""" Code that goes along with the Airflow located at: http://airflow.readthedocs.org/en/latest/tutorial.html """ from airflow import DAG from airflow.operators.bash_operator import BashOperator from datetime import datetime, timedelta from airflow.operators.python_operator import PythonOperator import calcul import ini...
# This file is part of Indico. # Copyright (C) 2002 - 2020 CERN # # Indico is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see the # LICENSE file for more details. from __future__ import unicode_literals from indico.modules.events.controllers.admin import (RHCreateEven...
from .conversions import (get_interaction_operator, get_diagonal_coulomb_hamiltonian, get_molecular_data, get_quadratic_hamiltonian) from .fourier_transforms import fourier_transform, inverse_fourier_transform from .operator_tapering import freeze_orbitals, prune_un...
import BaseClass from AModule import aFunc, bFunc class AClass( BaseClass.ABaseClass ): def __init__( self, val1, val2 ): super( ABaseClass, self ).__init__( val1 ) self.val2 = val2 def meth1( self, aval ): val = self.val1 * self.val2 + aval return super( ABaseClass, self ).me...
import hashlib import re from trac.config import * from trac.core import * from userpictures import IUserPicturesProvider class UserPicturesGravatarProvider(Component): implements(IUserPicturesProvider) # from trac source _long_author_re = re.compile(r'.*<([^@]+)@([^@]+)>\s*|([^@]+)@([^@]+)') @pro...
import os import json from keras.models import Model STORE_DIR = os.path.dirname(__file__) def save_model( model: Model, name: str, embedding_size: int, epochs: int, batch_size: int, validation_split: float) -> None: """ save the keras model to the storage directory. :param model: Model :param name : st...
# Copyright 2021 Sheng Wang. # Affiliation: Mathematical Institute, University of Oxford # Email: sheng.wang@maths.ox.ac.uk import os import random import numpy as np import marketmodel.loader as loader import marketmodel.utils as utils from marketmodel.loader import DataHestonSlv from marketmodel.factors import Pre...
# Generated by Django 3.2 on 2021-11-17 23:57 from django.db import migrations, models import django.db.models.deletion import news.models class Migration(migrations.Migration): dependencies = [ ('events', '0011_auto_20211117_2214'), ('news', '0006_auto_20211117_2219'), ] operations = [...
#!/usr/bin/env python import scapy.all as scapy import time import sys import argparse def get_range(): parser = argparse.ArgumentParser() parser.add_argument("-t", "--target", dest="target", help="use this to set the target ip") parser.add_argument("-r", "--spoof", dest="gateway", help="use this to set...
def process(self): self.edit("PRESENTATION FORM FOR") self.edit("LOW LINE", "underscore") self.edit("LEFT PARENTHESIS", "parenleft") self.edit("RIGHT PARENTHESIS", "parenright") self.edit("LEFT CURLY BRACKET", "braceleft") self.edit("RIGHT CURLY BRACKET", "braceright") self.edit("DOUBLE WAV...
import pytest from wazimap_ng.profile.serializers import ProfileSerializer, FullProfileSerializer from tests.cms.factories import PageFactory, ContentFactory from tests.profile.factories import ProfileFactory @pytest.fixture def profile(): return ProfileFactory(name="Test Profile") @pytest.fixture def page(prof...
import pickle from revscoring.datasources import revision_oriented from revscoring.dependencies import solve from revscoring.languages import dutch from .util import compare_extraction BAD = [ # Curses "aars", # ass "anaal", "anus", # anal, anus "balhaar", # ball hair (testicular hair) "debiel...
# ====================================================================== # Crab Combat # Advent of Code 2020 Day 22 -- Eric Wastl -- https://adventofcode.com # # Python implementation by Dr. Dean Earl Wright III # ====================================================================== # ==============================...
# -*- coding: utf-8 -*- """ Problem Statement You have 4 types of lego blocks, of sizes (1 x 1 x 1), (1 x 1 x 2), (1 x 1 x 3), and (1 x 1 x 4). Assume that you have an infinite number of blocks of each type. Using these blocks, you want to make a wall of height N and width M. The wall should not have any holes in it....
import datetime from server.ShiftManagerService import db import json '''' STILL NOT IN USE ''' class shift: def __init__(self, company_id, shift_id): shift_from_db = db.get_shift(company_id,shift_id) if shift_from_db is not None: self.__dict__.update(shift_from_db) def __delete_f...
# ! Testes de concatenação com atribuição de valores #n1 = int(input('Digite o primeiro numero \n')) #n2 = int(input('Digite o segundo numero \n')) #n3 = n1 + n2 #print('A soma dos numeros é ', n1 + n2) #print('A soma entre ', n1, ' e ', n2, 'é ', n3) #print('A soma dos numeros é {}'.format(n3)) #print('A soma entre {...
"""Terminal input and output prompts.""" from __future__ import print_function from pygments.token import Token import sys from IPython.core.displayhook import DisplayHook from prompt_toolkit.layout.utils import token_list_width class Prompts(object): def __init__(self, shell): self.shell = shell d...
from py42.services import BaseService class AlertRulesService(BaseService): """A service to manage Alert Rules.""" _version = u"v1" _resource = u"Rules/" _api_prefix = u"/svc/api/{}/{}".format(_version, _resource) def __init__(self, connection, user_context, user_profile_service): super(...
import json from config.config import data_path_config import numpy as np from collections import defaultdict import pickle import datetime def build_vocab_emb(data_path): # opt = data_path_config(data_path) # data_path = opt["data"]["embedding_weight"] vec_tabs = {} vec_size = 0 UNK = 0...
# /* # * Copyright (c) 2019,2020,2021 Xilinx Inc. All rights reserved. # * # * Author: # * Ben Levinsky <ben.levinsky@xilinx.com> # * Izhar Shaikh <izhar.ameer.shaikh@xilinx.com> # * # * SPDX-License-Identifier: BSD-3-Clause # */ from enum import IntEnum class REQ_USAGE(IntEnum): REQ_NO_RESTRICTION = 0 ...
#!/usr/bin/python # -*- coding: UTF-8 -*- import requests from bs4 import BeautifulSoup import re from urlparse import urlparse from urlparse import urljoin from urlparse import urlunsplit from urlparse import parse_qs import os, sys import timeit import hashlib import random import sqlite3 import base64 im...
class Solution: def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]: dic = [0]*101 for n in nums: dic[n] += 1 return [sum(dic[0:n]) for n in nums]
# -*- coding:utf-8 -*- # by:kracer import re import requests import time from threading import * from multiprocessing import Process from bs4 import BeautifulSoup as bs import matplotlib.pyplot as plt url0 = "https://src.sjtu.edu.cn/list/?page=" submitter_index_dic, edu_index_dic = {}, {} datas = [] #承载爬虫...
import logging import os import cv2 import matplotlib.pyplot as plt import numpy as np from citlab_python_util.geometry.rectangle import Rectangle from citlab_python_util.image_processing.image_stats import get_rotation_angle from scipy.ndimage import interpolation as inter logger = logging.getLogger("TextBlockNetPos...
import sys import requests from chooseplayer import * if sys.version_info[0] < 3: import Tkinter as Tk import ttk else: import tkinter as Tk from tkinter import ttk, tkMessageBox API_BASE_URL = "https://mocktesisasobiguaapi.azurewebsites.net/v1" # API_BASE_URL = "https://localhost:5001/v1" HEADER = {"...
month = input() nights = int(input()) total_price_apartment = 0 total_price_studio = 0 discount_studio = 0 discount_apartment = 0 if month == 'May' or month == 'October': total_price_studio = nights * 50 total_price_apartment = nights * 65 if nights > 14: discount_studio = 0.30 ...
#!/usr/bin/env python3 """ This module prepares reference tables for other modules Inputs: -------------------------------------------------------------- 1. Gencode gtf file 2. Gencode fasta file -------------------------------------------------------------- Output Tables: --------------------...
#!/usr/bin/env python3 from ast import literal_eval from subprocess import Popen, PIPE, STDOUT import hashlib import json import os.path import shlex import subprocess import sys binstub = "bandit3" include_paths = ["."] # severity converts the severity of a bandit issue # to the severity accepted by CodeClimate d...
from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask import request, jsonify from flask_cors import CORS from twilio.rest import TwilioRestClient from flask_apscheduler import APScheduler from flask.ext.session import Session from flask_login import LoginManager, login_required, login_user, logout...
from discord.ext import commands, tasks from src.decorators import needsDatabase from DO.game import GameDO from singleton.game import Game class GameCog(commands.Cog): instance = None @staticmethod def getInstance(): """Returns the instance of the singleton Returns: GameC...
from dataclasses import dataclass import datetime @dataclass class Learning: """The main model in the TIL""" title: str description: str timestamp: datetime.date
from django.urls import re_path from .views import SingleSignOn urlpatterns = [re_path(r"^sso/$", SingleSignOn.as_view())]
import requests from optimizely_platform import exceptions from optimizely_platform import objects def get_dynamic_audience_conditions(integration_settings): AUDIENCE_OPTIONS_ENDPOINT = ( 'https://integrations.optimizely.how/api/{0}/campaigns.json') account_id = integration_settings['account_id'] request_...
from typing import Iterable, List, Tuple, Any from dataclasses import dataclass, field import logging import sys from abc import abstractmethod, ABCMeta import itertools as it import pandas as pd from zensols.persist import Stash, PrimeableStash from zensols.multi import MultiProcessStash from zensols.nlp import Featur...
import sympy from graphviz import Digraph from markov_solver.core.model.markov_link import MarkovLink from markov_solver.core.model.markov_state import MarkovState FLOATING_POINT_PRECISION = 12 class MarkovChain: def __init__(self): self.states = set() self.links = set() self.symbols = d...
# Write a Python program to get the users environment import os print('\n' .join(os.environ))
#!/usr/bin/env python from argparse import ArgumentParser from greengraph import Greengraph from matplotlib import pyplot as plt def process(): parser = ArgumentParser(description = "Plot the 'green-ness' of satellite images between two places") parser.add_argument('--start', help='Choose a start location') ...
# from _thread import start_new_thread import simpleaudio as sa def play_note_by_key_place(piano_key: int) -> None: notes = { 1: "C", 2: "D", 3: "E", 4: "F", 5: "G", 6: "A", 7: "B" } wave_obj = sa.WaveObject.from_wave_file(f"sounds/{notes.get(piano_key, 'C')}.wav") wave_obj.play()
""" @author: Viet Nguyen (nhviet1009@gmail.com) """ import torch from torchvision.datasets import CocoDetection from torch.utils.data.dataloader import default_collate import os def collate_fn(batch): items = list(zip(*batch)) items[0] = default_collate([i for i in items[0] if torch.is_tensor(i)]) items[1]...
from copy import deepcopy import numpy as np class Collage(): def __init__(self, key): self.key = key self.negative_space = None self.positive_space = None def __str__(self): return self.key def set_negative_space(self, custom_image): self.negative_space = custom_i...
#!/usr/bin/python # -*- coding: utf-8 -*- import re,os,json # ############################################################################# # Copyright (C) 2018 manatlan manatlan[at]gmail(dot)com # # MIT licence # # https://github.com/manatlan/vbuild # ################################################################...
import openpyxl files = [r'C:\Users\roman\Documents\Testes excel_python/january.xlsx'] values = [] for file in files: wb = openpyxl.load_workbook(file) sheet = wb['Sheet1'] value = sheet['B5'].value values.append(value) print(values)
import json import logging from marshmallow import Schema, ValidationError from .request import Request from .client import Client from .jsonrpc import jrpc_accept, jrpc_response, validate_jrpc_request from .errors import ( CorvusException, NotFound, UnknownAsgiAction, ParseError, InvalidRequest, Unauthorize...
# Copyright 2019-2020 the ProGraML authors. # # Contact Chris Cummins <chrisc.101@gmail.com>. # # 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...
''' Author : ZHP Date : 2021-12-07 16:29:47 LastEditors : ZHP LastEditTime : 2022-01-14 20:11:55 FilePath : /models/pointnet/PointNetModel.py Description : Copyright 2021 ZHP, All Rights Reserved. 2021-12-07 16:29:47 ''' import torch import torch.nn as nn import torch.nn.functional as F from .poin...
from typing import List from app.models.experiment import ExperimentModel from app.models.slate_config import SlateConfigModel class SlateLineupExperimentModel(ExperimentModel): """ Models a slate_lineup experiment """ def __init__(self, experiment_id: str, description: str, rankers: List[str],slates...
########################################################################## # Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # Licensed under the Amazon Software License (the "License"). You may not use this file # except in compliance with the License. A copy of the License is located a...
#!/usr/bin/env python # Standard library imports import argparse import collections import logging import os import time # Additional library imports import requests # Named logger for this module _logger = logging.getLogger(__name__) # Parse the command line arguments _parser = argparse.ArgumentParser('') _parser...
from .stgcn import STConv, TemporalConv from .astgcn import ASTGCN, ChebConvAttention from .mstgcn import MSTGCN from .gman import GMAN, SpatioTemporalEmbedding, SpatioTemporalAttention from .mtgnn import MTGNN, MixProp, GraphConstructor from .tsagcn import GraphAAGCN, AAGCN from .dnntsp import DNNTSP
""" This example shows how to connect events in one window, for example, a mouse press, to another figure window. If you click on a point in the first window, the z and y limits of the second will be adjusted so that the center of the zoom in the second window will be the x,y coordinates of the clicked point. Note th...
# USAGE # python stress_test.py # import the necessary packages from threading import Thread import requests import time import cv2 import base64 # initialize the Keras REST API endpoint URL along with the input # image path KERAS_REST_API_URL = "https://127.0.0.1/dododo/" IMAGE_PATH = "jemma.png" # initialize the nu...
from ..schemas import CategoryBaseSchema, CategorySchema, CategoryUpdateSchema from ...forum.models import Category from app.core.exceptions import ValidationError class CategoryManager(): def __init__(self): self.category_create_schema = CategoryBaseSchema() self.category_update_schema = Category...
from flask import Flask, abort, make_response, request, jsonify from flask_restful import Resource, Api import yaml import logging from logging.handlers import RotatingFileHandler from src.vec_similarity import vec_search from src.utils.logger import init_logging app = Flask(__name__) api = Api(app) init_logging() @...
from rest_framework import serializers from .models import PurchaseOrder, PurchaseOrderLine class PurchaseOrderSerializer(serializers.HyperlinkedModelSerializer): purchase_order_lines = serializers.HyperlinkedRelatedField( many=True, read_only=True, view_name="purchaseorderline-detail" ) class Me...
""" The ``zen.drawing.ubigraph`` module provides support for rendering Zen graphs in the `Ubigraph visualization environment <http://ubietylab.net/ubigraph/>`_. The renderer will update the visualization in real time as changes are made to the underlying graph. Furthermore, edges and nodes can be visually highlighted...
#%% from HelmertTool.transform import * from HelmertTool.regression import * from HelmertTool.load import * import numpy as np #%% b = load_sta("C:/Users/Adrian/Documents/NVI/HelmertTool/data/2020d.sta") a = load_sta("C:/Users/Adrian/Documents/NVI/HelmertTool/data/2020d_off_0_0_10p_rate_0_0_0.sta") n = len(a.index) ...
from ..utils.groupby_func import groupby_func def df_to_groupby(data, by, func): '''Takes in a dataframe and returns it in a grouped by format. data : dataframe A pandas dataframe by : str The column by which the grouping is done func : str The function to be used for groupin...
from socket import * def send_packet(src, dst, eth_type, payload, interface = "eth0"): """Send raw Ethernet packet on interface.""" assert(len(src) == len(dst) == 6) # 48-bit ethernet addresses assert(len(eth_type) == 2) # 16-bit ethernet type s = socket(AF_PACKET, SOCK_RAW) # From the docs: "For raw pack...
from django.shortcuts import render, get_object_or_404 from django.http import HttpResponseRedirect from django.contrib.auth.decorators import login_required from django.core.urlresolvers import reverse #from django.contrib import messages from apps.apies.models import Api from apps.apies.forms import ApiForm def cl...
import tensorflow as tf import json import numpy import os import sys params = {} def load(filename, shape, dtype): with open(filename, 'r') as f: s = f.read() d = eval(s) t = tf.convert_to_tensor(d, dtype=dtype) t = tf.reshape(t, shape) return t def loadAnNumpyArray(filename, shape, ...