content
stringlengths
5
1.05M
import traceback as tb from colored import fg, attr def save_traceback(): try: raise TracebackException("Could not register Variable.") except TracebackException: full_tb = tb.extract_stack() # ignore this very function in the traceback return full_tb[:-1] class RegisterErr...
from typing import List, Optional import uvicorn from fastapi import Body, Depends, FastAPI, Query from pydantic import SecretStr from fastapi_keycloak import ( FastAPIKeycloak, HTTPMethod, KeycloakUser, OIDCUser, UsernamePassword, ) app = FastAPI() idp = FastAPIKeycloak( server_url="http://l...
# -*- coding: utf-8 -*- """ Production Configurations - Use Amazon's S3 for storing static files and uploaded media - Use mailgun to send emails - Use Redis for cache - Use sentry for error logging """ from __future__ import absolute_import, unicode_literals from django.utils import six import logging from .bas...
import unittest from biicode.test.testing_mem_server_store import TestingMemServerStore from biicode.server.model.user import User from biicode.common.model.symbolic.block_version import BlockVersion from biicode.common.model.brl.brl_block import BRLBlock from biicode.common.model.brl.brl_user import BRLUser from biico...
""" This module contains classes intended to parse and deal with data from Roblox badge information endpoints. """ from __future__ import annotations from typing import TYPE_CHECKING from datetime import datetime from dateutil.parser import parse from .bases.baseasset import BaseAsset from .bases.basebadge import B...
from django.test import TestCase from .models import Project class ProjectTestCase(TestCase): def test_creation_of_projects(self): Project.objects.create(project_name='Test Website 1', project_description='This is website made through a test', project_url='https://www.google...
#!/usr/bin/env python3 import os from aws_cdk import core as cdk app = cdk.App() # Stacks are intentionally not created here -- this application isn't meant to # be deployed. app.synth()
import os, sys, json from datetime import datetime """ Create BPE lookup: 1. create object (will init special tokens) 2. create BPE model with sentencepiece.train 3. lookup.load(path to model (prefix only, without .model)), this will shift special tokens up the vocab 4. lookup.save_special_tokens()...
from pathlib import Path import imageio DEFAULT_DIR = str(Path.home().joinpath('debug')) DEFAULT_PATH = 'test.gif' class Dummy(object): images = dict() @classmethod def add(cls, key, image): if key not in cls.images: cls.images[key] = list() cls.images[key].append(image.co...
# Alien Language Solution # Google Code Jam 2009, Qualification, Question A # tr@nsistor from collections import defaultdict specs = input().split() ltrs = int(specs[0]) words = int(specs[1]) cases = int(specs[2]) wdict = [] for word in range(words): wdict.append(input()) for case in range(cases): patte...
import multiprocessing as mp import csv class QueueLogger(object): """ Records data from a multiprocessing.Queue to an output file Attributes ---------- filename : string Name of the output file to write to buffersize : unsigned int Number of results to collect from the queue ...
# -*- coding: utf-8 -*- from sklearn import svm import numpy as np import matplotlib.pyplot as plt from utils.FScore import F1Score from Identification.LoadDescriptors import loadAllDescriptors from Identification.PreprocessingDescriptors import preprocessDescriptors from Identification.TrainCvTest import separateDat...
#!/usr/bin/python # # Copyright 2017 Google 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 ag...
from usim800.Request.Request import request
from __future__ import absolute_import from __future__ import unicode_literals from webfriend.scripting.parser import to_value class MetaModel(object): def __init__(self, parent, **kwargs): self.parent = parent for k, v in kwargs.items(): if isinstance(v, list): v = tu...
__author__ = 'hanhanwu' import numpy as np from pyspark import SparkConf, SparkContext import matplotlib.pyplot as plt import sys import caffe import os import glob conf = SparkConf().setAppName("image classification") sc = SparkContext(conf=conf) assert sc.version >= '1.5.1' caffe_root = sys.argv[1] images_folder_...
import threading import time import utils from config import cfg FOLLOWER = 0 CANDIDATE = 1 LEADER = 2 class Node(): def __init__(self, fellow, my_ip): self.addr = my_ip self.fellow = fellow self.lock = threading.Lock() self.DB = {} self.log = [] self.staged = None...
# Project: GBS Tool # Author: Jeremy VanderMeer, jbvandermeer@alaska.edu # Date: February 16, 2018 # License: MIT License (see LICENSE file of this package for more information) # imports import numpy as np # calculate a short term future load class predictLoad: def __init__(self): self.futureLoad = 0 ...
import numpy.testing from refnx._lib.util import (TemporaryDirectory, preserve_cwd, possibly_open_file, MapWrapper) from refnx._lib._numdiff import approx_hess2 from refnx._lib._testutils import PytestTester try: from refnx._lib._cutil import c_unique as unique from refnx._lib._c...
"""File lookup.""" # pylint: disable=arguments-differ # pyright: reportIncompatibleMethodOverride=none from __future__ import annotations import base64 import collections.abc import json import re from typing import Any, Callable, Dict, List, Mapping, Sequence, Union, overload import yaml from troposphere import Base...
# Licensed to the StackStorm, Inc ('StackStorm') 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 th...
import cv2 import numpy as np from picamera.array import PiRGBArray from picamera import PiCamera camera = PiCamera() camera.resolution = (640, 480) camera.framerate = 10 rawCapture = PiRGBArray(camera, size=(640, 480)) for frame in camera.capture_continuous(rawCapture, format="bgr", use_video_port=True): image =...
# -*- coding: utf-8 -*- import sys from pathlib import Path import pysam import re from collections import defaultdict from .report import Reporter from .utils import getlogger, CommandWrapper logger = getlogger(__name__) logger.setLevel(10) class GeneName(object): def __init__(self, annot): self.gtf_...
"""exercism card games (lists) module.""" def get_rounds(number): """ Get list of current and next rounds :param number: int - current round number. :return: list - current round and the two that follow. """ return [number, number + 1, number + 2] def concatenate_rounds(rounds_1, rounds_2):...
import pickle import sys import timeit from datetime import datetime from os import path import numpy as np from sklearn.preprocessing import OneHotEncoder def read_batch(src): '''Unpack the pickle files ''' with open(src, 'rb') as f: if sys.version_info.major == 2: data = pickle.load...
import multiprocessing as mp from itertools import repeat import pickle from pathlib import Path import typing from tqdm import tqdm import pygraphviz as pgv import networkx as nx from recurse_words.corpi import get_corpus from recurse_words import Recurser class Graph_Recurser(Recurser): """ Turns out its a...
import argparse import os import json import glob from os.path import join as pjoin from others.vocab_wrapper import VocabWrapper def train_emb(args): data_dir = os.path.abspath(args.data_path) print("Preparing to process %s ..." % data_dir) raw_files = glob.glob(pjoin(data_dir, '*.json')) ex_num = 0...
"Tests for twisted.names"
def dijkstra(graph, start, end): shortest_distance = {} non_visited_nodes = {} for i in graph: non_visited_nodes[i] = graph[i] infinit = float('inf') for no in non_visited_nodes: shortest_distance[no] = infinit shortest_distance[start] = 0 while non...
from socket import * import sys conn = socket(AF_INET, SOCK_STREAM) conn.connect(("127.0.0.1", 14900)) print("We are going to solve quadratic equation: a*x^2 + b*x + c = 0") a = input("Enter a: ") b = input("Enter b: ") c = input("Enter c: ") if not a: conn.close() sys.exit(1) data = str.encode(','.join([a,b,c]))...
# using hash table # Time complexity : O(n). We do search() and insert() for nnn times and each operation takes constant time. #Space complexity : O(n). The space used by a hash table is linear with the number of elements in it. def solution(s): dic = set() lst = s.split() for item in lst : if item ...
# Stars in Hipparcos catalogue whose magnitudes are <=6 # or are present in constellationship.fab hip_stars = """ hip,ra,dec,Vmag 71683,219.90206584,-60.83397468,-0.01 53253,163.37356736,-58.8531708,3.78 8198,26.34846064,9.15773579,4.26 26634,84.91224946,-34.07410786,2.65 79882,244.58037087,-4.69251067,3.23 92175,281.7...
#!/usr/bin/env python # # sub20_to_binary.py - Python code to pack SUB-20 output as binary event data # (to make use of STEIN data collected via the SUB20 interface) # # # Usage: # log.log - data collected via SUB-20 # binary.log - binary-packed event data, created from "log.log" via the python script "sub20_to_b...
""" Initializes the database of cea """ # HISTORY: # J. A. Fonseca script development 03.02.20 import cea.config import cea.inputlocator import os from distutils.dir_util import copy_tree __author__ = "Jimeno A. Fonseca" __copyright__ = "Copyright 2015, Architecture and Building Systems - ETH Zurich" _...
import torch import torch.distributed as dist from multiprocessing.pool import ThreadPool class Reducer(object): def __init__(self): super(Reducer, self).__init__() self._data_cpu = {} self._pool = None self._handles = [] self._stream = None def init(self, model): ...
from spacy.matcher import Matcher pattern_amounts = [{'LOWER': 'payment'}, {'LOWER': 'information'}, {'IS_PUNCT': True}] pattern_singleDay = [{'LOWER': 'date'}, {'LOWER': 'of'}, {'LOWER': 'transaction'}, {'IS_PUNCT': True}] pattern_date = [{"label": "DATE", "pattern": [{'IS_TITLE': True}]}] def find_dates(nlp, doc, ...
# Generated by the protocol buffer compiler. DO NOT EDIT! # sources: steammessages_useraccount.proto # plugin: python-betterproto from dataclasses import dataclass from typing import List import betterproto class EInternalAccountType(betterproto.Enum): SteamAccountType = 1 ClanType = 2 AppType = 3 ...
class MinHeap: def __init__(self, capacity): self.storage = [0] * capacity self.capacity = capacity self.size = 0 def get_parent_index(self, index): return (index - 1) // 2 def get_left_child_index(self, index): return 2 * index + 1 def get_right_child_index(se...
""" .. _ref_create_unstructured: Creating an Unstructured Grid ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Create an irregular, unstructured grid from NumPy arrays. """ import pyvista as pv import vtk import numpy as np ############################################################################### # An unstructured grid can be ...
# This file is part of Indico. # Copyright (C) 2002 - 2021 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 sqlalchemy.dialects.postgresql import ARRAY from sqlalchemy.ext.hybrid import hybrid_property from i...
from flask import Flask from flask_sqlalchemy import SQLAlchemy from os import environ, sys from .log import accesslogger import logging db = SQLAlchemy() def create_app(): """Construct the core application.""" app = Flask(__name__) app.logger.addHandler(logging.StreamHandler(sys.stdout)) app.logger.s...
""" Django settings for incredibus 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 inside the project like this: os.path.join(BASE_DIR, ...)...
from unittest.mock import patch from corehq.apps.case_search.utils import get_expanded_case_results from corehq.form_processor.models import CommCareCaseSQL @patch("corehq.apps.case_search.utils._get_case_search_cases") def test_get_expanded_case_results(get_cases_mock): cases = [ CommCareCaseSQL(case_js...
import pandas as pd import numpy as np import sklearn.neural_network.multilayer_perceptron import os import data_preprocessing as dp df_dict = dp.rd.read_data_to_dict() train_df = dp.preprocess(df_dict) y = train_df.pop('Score') X = train_df
import copy import json import logging from collections import defaultdict from typing import Any, Dict, List, Optional, Sequence, Tuple, TypeVar, Union import math import numpy import torch from allennlp.common.checks import ConfigurationError logger = logging.getLogger(__name__) T = TypeVar("T") def has_tensor(...
import logging from collections import OrderedDict from datetime import datetime from extractionSteps.JobStepBase import JobStepBase from util.stdlib_utils import get_recursively class DashboardsAPM(JobStepBase): def __init__(self): super().__init__("apm") async def extract(self, controllerData): ...
from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^fitbitredirect$', views.fitbit_redirect, name='fitbit_redirect'), url(r'^postmessage$', views.post_weight_to_slack, name='post_message'), url(r'^postmessagediscord$', views.post_weight_to...
import functools import re import mm_param class RootNode(object): def __init__(self, parameters): self._p = parameters for v in parameters.values(): v.parent = self def child(self, key): if key in self._p: return self._p[key] raise Exception("no chil...
from .CRF import *
import discord import random import asyncio from discord import Client from discord.ext import commands from discord.ext.commands import Bot from discord.utils import get bot = commands.Bot(command_prefix = '.') bot.remove_command('help') @bot.event async def on_ready(): print('duck1 is online!') @bot.command(pa...
# --- # jupyter: # jupytext: # formats: ipynb,py:percent # text_representation: # extension: .py # format_name: percent # format_version: '1.3' # jupytext_version: 1.13.7 # kernelspec: # display_name: Python [default] # language: python # name: python2 # --- # %% from py...
import datetime import collada from collada.util import unittest from collada.xmlutil import etree fromstring = etree.fromstring tostring = etree.tostring class TestAsset(unittest.TestCase): def setUp(self): self.dummy = collada.Collada(validate_output=True) def test_asset_contributor(self): ...
import info class subinfo(info.infoclass): def setTargets(self): self.versionInfo.setDefaultValues() self.displayName = "JuK" self.patchToApply["18.08.1"] = [("juk-18.08.1-20181029.diff", 1)] self.description = "JuK is a simple music player and helps manage your music collection" ...
""" Cisco_IOS_XR_Ethernet_SPAN_subscriber_cfg This module contains a collection of YANG definitions for Cisco IOS\-XR Ethernet\-SPAN\-subscriber package configuration. This YANG module augments the Cisco\-IOS\-XR\-subscriber\-infra\-tmplmgr\-cfg module with configuration data. Copyright (c) 2013\-2018 by Cisco Sy...
import pytest from unittest import TestCase from flask import url_for, json from web.server import create_app from web.db import db from web.status import status from web.models import User from tests.integration_tests.post_helpers import PostHelper class UsersTests(TestCase): @pytest.fixture(autouse=True) ...
# Copyright (c) 2009-2010, Cloud Matrix Pty. Ltd. # All rights reserved; available under the terms of the BSD License. """ myppy.util: misc utility functions for myppy """ from __future__ import with_statement import os import sys import errno import tempfile import subprocess import shutil import hashlib impo...
######################################################### # This file is part of the MultilayerOptics package. # # Version 0.1.0 # # Copyright (c) 2016 and later, Kanglin Xiong. # ######################################################### import random ''' Th...
import pygame as p import dice import buttonPanel import StatisticsPanel WIDTH = 900 HEIGHT = 600 BACKGROUND_COLOR = 'white' MAX_FPS = 5 def main(): p.init() screen = p.display.set_mode([WIDTH, HEIGHT]) p.display.set_caption('Dice Sim V. 1') screen.fill(p.Color(BACKGROUND_COLOR)) clock = p.ti...
from aws_cdk import ( Duration, Stack, aws_logs as logs, aws_sns as sns, aws_lambda as lambda_, ) from constructs import Construct class LambdaSnsPublishStack(Stack): def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None: super().__init__(scope, construct_id, **kwar...
"""Submit jobs to Sun Grid Engine.""" # pylint: disable=invalid-name import os import subprocess from . import tracker def submit(args): """Job submission script for SGE.""" if args.jobname is None: args.jobname = ('dmlc%d.' % args.num_workers) + args.command[0].split('/')[-1] if args.sge_log_dir...
import os from cluster_func import Arguments alphabet = 'abcdefghijklmnopqrst' args = zip(range(20), alphabet) my_args1 = zip(range(20), reversed(alphabet)) my_args2 = [Arguments(number=n, letter=l) for n,l in my_args1] def my_func(number, letter): print os.environ['MYENV'] print letter, number def target(number,...
import math from decimal import Decimal class Transaction: def __init__( self, transaction: dict, ): """ type: buy / sell block_number: number of ETH block tx occurred in totx_digg_supply: time of tx total digg supply totx_digg_price: { wbtc:...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Implementation of extraction. Usage: >>> from extract_pdf import extract >>> extract('/path/of/pdf', 3, 7) """ import os from PyPDF2 import PdfFileReader, PdfFileWriter __all__ = ['extract'] def extract(file_path, first_page, last_page): """ ...
import logging import os import jinja2 from IPython.core.display import display, HTML from pyspark.ml.feature import SQLTransformer from pyspark.ml.stat import Correlation from pyspark.serializers import PickleSerializer, AutoBatchedSerializer from pyspark.sql import DataFrame from pyspark.sql import functions as F f...
from ._ScanAngle import *
class GameContainer: def __init__(self, lowest_level, high_score, stat_diffs, points_available): self.lowest_level = lowest_level self.high_score = high_score self.stat_diffs = stat_diffs self.points_available = points_available
#coding:utf-8 import time,datetime import os,os.path import json import traceback from threading import Thread,Condition from Queue import Queue from collections import OrderedDict from mantis.fundamental.utils.timeutils import timestamp_current, timestamp_to_str,datetime_to_timestamp,\ current_datetim...
jogador = {} atletas = [] gols = [] total = [] while True: jogador['nome'] = str(input('Nome: ')) partidas = int(input(f'Quantas partidas {jogador["nome"]} jogou? ')) for c in range(0,partidas): gols.append(int(input(f'Quantos gols na partida {c+1}? '))) jogador['gols'] = gols[:] jogador['total'] = sum(...
# -*- coding: utf-8 -*- # 门店装修服务 class DecorationService: __client = None def __init__(self, client): self.__client = client def create_sign(self, sign): """ 创建招贴 :param sign:招贴信息和其关联门店ID集合 """ return self.__client.call("eleme.decoration.sign.createSign",...
# ============================================================================ # FILE: project.py # AUTHOR: Qiming Zhao <chemzqm@gmail.com> # License: MIT license # ============================================================================ # pylint: disable=E0401,C0411 import os from .base import Base from denite imp...
import json from datetime import datetime from json.decoder import JSONDecodeError from django.db.models import Q from django.http import JsonResponse, Http404 from django.shortcuts import get_object_or_404 from django.utils import timezone from django.views.decorators.csrf import csrf_exempt from django.views.decorat...
# coding: utf-8 """ Train a model. How to use: train_model.py <MODEL> <DATA> <BINS> <EPOCH> - MODEL: model directory - DATA: directory path to images - BINS: bins per color channel - EPOCH: total number of epoch (1 batch per epoch) """ import sys # Parse cmd line a...
#!/usr/bin/env python # -*- coding: utf-8 -*- import socket # UDP通信用 import threading # マルチスレッド用 import time # ウェイト時間用 import numpy as np # 画像データの配列用 # import libh264decoder # H.264のデコード用(自分でビルドしたlibh264decoder.so) class Tello: """Telloドローンと通信するラッパークラス""" def __init__(self,...
name = "PwnedPy" import requests import json headers = { 'User-Agent': 'PwnedPy v1.0-May-2019' } def getBreaches(account, Truncated=False, Unverified=False): params = (("truncateResponse", Truncated),("includeUnverified",Unverified)) account = str(account) baseURL = "https://haveibeenpwned.com/api/v2/breachedacc...
import struct import unittest import json from manticore.platforms import evm from manticore.core import state from manticore.core.smtlib import Operators, ConstraintSet import os class EVMTest_SLT(unittest.TestCase): _multiprocess_can_split_ = True maxDiff = None def _execute(self, new_vm): last...
import numpy as np class ExternalIndex: def __init__(self, groundtruth, clusters): self.ground = groundtruth self.clusters = clusters self.ground_incidence_matrix = self.incidence_matrix(self.ground) self.cluster_incidence_matrix = self.incidence_matrix(self.clusters) self...
from Mementos import Memento, EflowMemento from Originators import Originator, EflowOriginator from Memento_models import Eflow class Caretaker: def __init__(self): self.store = {} def add(self, key="", memento=Memento): self.store[key] = memento print("儲存一張表單! 建立日期{0},內容: {1}".format...
#!/usr/bin/env python import glob, os path_data = "/home/sj/Desktop/Logs/Labeled/current/" # Percentage of images to be used for the test set percentage_test = 5; file_train = open(path_data+'train.txt', 'w') file_test = open(path_data+'test.txt', 'w') # Populate train.txt and test.txt counter = 1 index_test = rou...
# (c) 2021 Ruggero Rossi # Load a Robosoc2d game state log # supported version: 1.0.0 def load_state_log(file_name): history = None with open(file_name, 'r') as f: game={} version=f.readline() if len(version)==0 : return None game['ver']=version game['team1...
# Modified by Microsoft Corporation. # Licensed under the MIT license. import json import random import sys import torch from torch.autograd import Variable class DatasetWoz(object): ''' data container for woz dataset ''' def __init__(self, config, percentage=1.0, use_cuda=False): # setup feat_file = config...
#!/usr/bin/env python3 import tpmdata import multiprocessing import pprint import numpy as np import matplotlib.pyplot as plt from matplotlib import dates from astropy.time import Time from argparse import ArgumentParser from matplotlib import animation import astropy.units as u __version__ = '3.0.1' tpmdata.tinit()...
#!/usr/bin/python # -*- coding: utf-8 -*- import re import operator base = "L4, R2, R4, L5, L3, L1, R4, R5, R1, R3, L3, L2, L2, R5, R1, L1, L2, R2, R2, L5, R5, R5, L2, R1, R2, L2, L4, L1, R5, R2, R1, R1, L2, L3, R2, L5, L186, L5, L3, R3, L5, R4, R2, L5, R1, R4, L1, L3, R3, R1, L1, R4, R2, L1, L4, R5, L1, R50, L4, R3,...
import sys import os import pytest import pandas as pd import arcus.ml.timeseries.timeops as tops import arcus.ml.dataframes as adf import logging from unittest.mock import patch logging.basicConfig(level=logging.DEBUG) mylogger = logging.getLogger() time_series_df = pd.read_csv('tests/resources/datasets/sunspots.c...
import geopandas as gpd # GeoDataFrame creation file = 'constituencies.shp' poly = gpd.read_file(file) points = poly.copy() # change the geometry # points.geometry = points['geometry'].centroid points.to_crs(epsg=4326, inplace=True) # same crs #points.crs =poly.crs # print(points['geometry']) for index, row in points....
import unittest import kpf from textwrap import dedent from kpf.patch import sha256 def readBinary(fn): with open(fn,"rb") as f: return bytearray(f.read()) class KPFTests(unittest.TestCase): def test_record_parse(self): r = kpf.Record.fromLine("00000002=02") self.assertEqual(type(r),kpf.Record) self.asser...
#!/usr/bin/env python3 # # Copyright (C) 2021 Intel Corporation # SPDX-License-Identifier: Apache-2.0 # # import logging import os import sys from argparse import ArgumentParser, SUPPRESS import matplotlib.pyplot as plt import numpy as np def build_argparser(): parser = ArgumentParser(add_help=False) args =...
# Generated by Django 3.1.3 on 2021-06-27 12:01 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('auctions', '0012_comment'), ] operations = [ migrations.DeleteModel( name='bids', ), ]
print("Here is simple_substract test:") a = 456 b = 123 substract = a - b print("456 - 123 =", substract) print('') a = eval(input("Please enter an integer 'a':")) b = eval(input("Please enter another integer 'b':")) substract = a - b print("a - b =", substract) print('')
import sys from numba import vectorize, guvectorize, float64, complex128, void import numpy as np import warnings import xarray as xr from ..utils import timing from .utils import logger from .models import get_model @timing(logger.info) def invert_from_model(inc, sigma0, sigma0_dual=None, /, ancillary_wind=None, dsig...
__version__ = '6.1.1'
from typing import get_args from .mission_generator_constants import MissionGeneratorConstants as con from .mission import Mission from .data_gateway import DataGateway import random def _can_use_mission_type(mission_type, available_mission_types): return mission_type in [con.SPECIAL,con.COMMANDER_FOCUS, con.GM_CH...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.contrib import admin from mptt.admin import MPTTModelAdmin from .models import VocabularyNodeType, Term, Node, NodeRevision class VocabularyNodeTypeAdmin(admin.ModelAdmin): list_display = ('name',) class TermAdmin(MPTTModelAdmin): list_...
import extract_global, config import os, argparse def parse_arguments(): parser = argparse.ArgumentParser(description='Extract frame FVs') parser.add_argument( '--sift_mode', # mode = 0 -> SIFT detector; 1 -> Hessian affine detector type=int, required=False, default=1 ) ...
# -*- coding: utf-8 -*- ############################################################################################################################ # # # ############################################################################################################################ class stats(object): def __init__(se...
# A Python program for Prims's MST for # adjacency list representation of graph import math import numpy as np from collections import defaultdict # Converts from adjacency matrix to adjacency list def convert_matrix_to_list(matrix): adjList = defaultdict(list) for i in range(len(matrix)): for ...
from google_nest_sdm.structure import Structure def test_no_traits() -> None: raw = { "name": "my/structure/name", } structure = Structure.MakeStructure(raw) assert "my/structure/name" == structure.name assert not ("sdm.structures.traits.Info" in structure.traits) def test_empty_traits()...
# <Copyright 2019, Argo AI, LLC. Released under the MIT license.> import os import pathlib import pytest from argoverse.data_loading.simple_track_dataloader import SimpleArgoverseTrackingDataLoader _TEST_DATA = pathlib.Path(__file__).parent / "test_data" / "tracking" _LOG_ID = "1" @pytest.fixture # type: ignore ...
### 3d_tools.py import pyassimp as pas def model_geom(file_root, w, nextId, opt): ## Read TINs from the DAE global bid dir_parts = file_root.split("/") if ( len(dir_parts) > 0 ): bid = dir_parts[len(dir_parts)-1] else: bid = "unknown" myProcessing = pas.postprocess.aiPro...
# coding: UTF-8 print(r''' 【程序18】题目:两个乒乓球队进行比赛,各出三人。甲队为a,b,c三人,乙队为x,y,z三人。已抽签决定比赛名单。有人向队员打听比赛的名单。a说他不和x比,c说他不和x,z比,请编程序找出三队赛手的名单。 ''') import random # random.randint(0, 2) def isCanGame(Jname, Yname): if Jname == 'a' and Yname == 'x': return False if Jname == 'c' and Yname == 'x': return Fals...
import FWCore.ParameterSet.Config as cms import sys process = cms.Process("TestElectrons") process.load("FWCore.MessageService.MessageLogger_cfi") process.MessageLogger.cerr.FwkReport.reportEvery = 100 process.load("Configuration.StandardSequences.GeometryDB_cff") process.load("Configuration.StandardSequences.Magne...