text
stringlengths
2
999k
# qubit number=3 # total number=48 import numpy as np from qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ from qiskit.visualization import plot_histogram from typing import * from pprint import pprint from math import log2 from collections import Counter from...
from __future__ import unicode_literals from django.apps import AppConfig class MyzapierConfig(AppConfig): name = 'myzapier'
# -*- coding: utf-8 -*- import unittest import os # noqa: F401 import json # noqa: F401 import time import requests from os import environ try: from ConfigParser import ConfigParser # py2 except: from configparser import ConfigParser # py3 from pprint import pprint # noqa: F401 from biokbase.workspace.c...
class HttpError(BaseException): pass class AccessDeniedError(BaseException): pass
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
def flatten(x): if isinstance(x, list): return [a for i in x for a in flatten(i)] else: return [x]
'''++ Copyright (C) 2019 ACT Developers This file has been generated by the Automatic Component Toolkit (ACT) version 1.6.0. Abstract: This is an autogenerated Python file in order to allow an easy use of Optional Class Library Interface version: 1.0.0 ''' import ctypes import platform import enum import os n...
# stdlib from collections import UserDict from collections.abc import ItemsView from collections.abc import KeysView from collections.abc import ValuesView from typing import Any from typing import Dict as TypeDict from typing import Iterable from typing import Optional from typing import Union # third party from goog...
"""convoterminationhandler.py -- Send signal to end the converstaion Copyright 2016 Rylan Santinon 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...
# Copyright 2010 Jacob Kaplan-Moss # Copyright 2011 OpenStack Foundation # Copyright 2011 Piston Cloud Computing, Inc. # Copyright 2011 Nebula, 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...
import tensorflow as tf slim = tf.contrib.slim def block35(net, scale=1.0, activation_fn=tf.nn.relu, scope=None, reuse=None): """Builds the 35x35 resnet block.""" with tf.variable_scope(scope, 'Block35', [net], reuse=reuse): with tf.variable_scope('Branch_0'): tower_conv = slim.conv2d(net, 32, 1, scope...
import requests from torch import Tensor, device from typing import Tuple, List from tqdm import tqdm import sys import importlib import os import torch import numpy as np import queue def pytorch_cos_sim(a: Tensor, b: Tensor): """ Computes the cosine similarity cos_sim(a[i], b[j]) for all i and j. This fu...
# --------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # --------------------------------------------------------- import uuid import logging import time import os import warnings from contextlib import suppress from typing import Optional, Dict, Any, Li...
from vivarium_gates_child_iv_iron.components.observers import BirthObserver, ResultsStratifier
def init_trainer(opt, trainloader, validloader, model): model_name = opt.model if model_name.startswith('ssd'): from trainer.train_ssd import Trainer trainer = Trainer(opt, train_dataloader=trainloader, valid_dataloader=validloader, ...
#-*- encoding: utf8 __doc__ = """Tree GRU aka Recursive Neural Networks.""" import sys import numpy as np import torch import torch.nn as nn import torch.nn.functional as F class Node_tweet(object): def __init__(self, idx=None): self.children = [] self.idx = idx self.word = []...
from django.conf import settings from django.db import connections from django.db.models import Count, Q from django_filters.rest_framework import DjangoFilterBackend from nc import serializers from nc.filters import DriverStopsFilter from nc.models import SEARCH_TYPE_CHOICES as SEARCH_TYPE_CHOICES_TUPLES from nc.model...
# -*- encoding: utf-8 -*- """On this module are defined the interfaces to explore a pycparser AST.""" from . import pycparser class FuncDefVisitor(pycparser.c_ast.NodeVisitor): """Interface to function definitions in Syntax Abtract Tree.""" @staticmethod def funcdef_data(funcdef): """Extract dat...
"""TODO.""" from testplan.common.utils.sockets import Server, Client def test_basic_server_client(): # Start server server = Server() server.bind() assert server._listening is False server.serve() assert server._listening is True assert server.active_connections == 0 assert server.acc...
# Implement an algorithm to find the kth to last element of a singly linked list. class Node: next = None def __init__(self, value): self.value = value class LinkedList: tail = None head = None def insert(self,value): node = Node(value) if (self.tail is None) and (self.head...
import seaborn as sns import numpy as np import matplotlib.pyplot as plt sns.set_style("whitegrid") def train_plot(training_logger, validation_logger, order=None): keys = list(training_logger.keys()) keys.remove("Process Time") keys.remove("Load Time") if order is not None: keys = order ...
""" =================== Bioscrape Connector =================== run with: > python -m vivarium_bioscrape.composites.bioscrape_connector """ import os import numpy as np # vivarium core imports from vivarium.library.schema import array_from, array_to from vivarium.core.engine import pp from vivarium.core.composer imp...
""" The :mod:`rl_agents.agents.mab` submodule includes: * Epsilon Greedy * Decreasing Epsilon Greedy * UCBs: UCB, UCB1, UCB2 * Softmax * Pursuit """ from rl_agents.agents.mab.egreedy import DecayEpsilon # noqa: F401 from rl_agents.agents.mab.egreedy import EpsilonGreedy # noqa: F401 from rl_agents.agents.mab.pursu...
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
import responses from django.conf import settings from django.core.exceptions import ValidationError from olympia.amo.tests import TestCase, reverse_ns from olympia.shelves.forms import ShelfForm class TestShelfForm(TestCase): def setUp(self): self.criteria_sea = '?promoted=recommended&sort=random&type=...
# -*- coding: utf-8 -*- # Generated by Django 1.9 on 2016-10-16 04:55 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('App', '0007_auto_20161016_0454'), ] operations = [ migrations.AlterField( ...
# Copyright (c) OpenMMLab. All rights reserved. from itertools import chain from torch.nn.parallel import DataParallel from .scatter_gather import scatter_kwargs class MMDataParallel(DataParallel): """The DataParallel module that supports DataContainer. MMDataParallel has two main differences with PyTorch ...
from __future__ import annotations import code import os from unittest.mock import Mock import pytest from _pytest.monkeypatch import MonkeyPatch from click.testing import CliRunner import quart.cli from quart.__about__ import __version__ from quart.app import Quart from quart.cli import AppGroup, cli, NoAppExceptio...
#!/usr/bin/python3 # # Copyright (c) 2021 Mikkel Schubert <MikkelSch@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights ...
from elasticsearch_dsl.connections import connections def connect(app_config, mode): elastic_host = app_config["ELASTICSEARCH_HOST"] if mode == "local": connections.create_connection(hosts=[elastic_host]) else: elastic_auth = "{username}:{password}".format(username=app_config["ELASTIC_USER...
from dealWithLexicons_afinn_nrc_ import * import numpy as np import matplotlib.pyplot as plt from tqdm import tqdm from nltk.tokenize import word_tokenize from keras.models import Sequential from keras.layers import Dense, Dropout from sklearn.model_selection import train_test_split from sklearn.metrics import f1_score...
import pytest from spacy_pytorch_transformers import PyTT_WordPiecer from spacy.tokens import Doc from spacy.vocab import Vocab @pytest.fixture def vocab(): return Vocab() @pytest.fixture def wordpiecer(name): return PyTT_WordPiecer.from_pretrained(vocab, pytt_name=name) def test_alignment_extension_attr(...
"""This module contains the general information for MgmtControllerFsm ManagedObject.""" from ...ucsmo import ManagedObject from ...ucscoremeta import MoPropertyMeta, MoMeta from ...ucsmeta import VersionMeta class MgmtControllerFsmConsts: COMPLETION_TIME_ = "" CURRENT_FSM_ACTIVATE_ADAPTOR = "ActivateAdaptor"...
__author__ = 'hawk' import MySQLdb def getDbConn(dbhost,dbuser,dbpasswd,dbname): connection = MySQLdb.connect(host=dbhost,user=dbuser,passwd=dbpasswd,db=dbname,port=3306,charset='utf8') return connection def getMany(dbconn,sql): print(sql) try: cur = dbconn.cursor(MySQLdb.cursors.DictCursor) ...
"""kxds_32498 URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.2/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-ba...
from backbone import ResNetBackbone, VGGBackbone, ResNetBackboneGN, DarkNetBackbone from math import sqrt import torch # for making bounding boxes pretty COLORS = ((244, 67, 54), (233, 30, 99), (156, 39, 176), (103, 58, 183), ( 63, 81, 181), ( 33, 150, 243), ...
import logging import re import pytest import yaml from natsort import natsorted from tests.common.helpers.assertions import pytest_assert from tests.common.helpers.platform_api import chassis, module from tests.common.fixtures.conn_graph_facts import conn_graph_facts from tests.common.utilities import get_inventory...
# SPDX-FileCopyrightText: 2018 Kevin Townsend for Adafruit Industries # # SPDX-License-Identifier: MIT """ `adafruit_bluefruitspi` ==================================================== Helper class to work with the Adafruit Bluefruit LE SPI friend breakout. * Author(s): Kevin Townsend Implementation Notes ----------...
# coding: utf-8 # Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved. # This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may c...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on 15/04/18 """ from Base.Recommender import Recommender from Base.Recommender_utils import check_matrix, similarityMatrixTopK from Base.SimilarityMatrixRecommender import SimilarityMatrixRecommender from sklearn.preprocessing import normalize #Tunato migli...
from tensorflow.keras import backend as K from tensorflow import keras def get_metrics(framework, config): """Load model training metrics from a config file for a specific framework. """ training_metrics = [] validation_metrics = [] # TODO: enable passing kwargs to these metrics. This will requir...
# -*- coding: utf-8 -*- # (C) Copyright 2016 Hewlett Packard Enterprise Development LP # 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.a...
# -*- coding: utf-8 -*- # @Time : 2018/12/21 11:12 # @Author : Alan # @Email : xiezhengwen2013@163.com # @File : Utils.py # @Software: PyCharm import tensorflow as tf import time from datetime import timedelta import numpy as np from collections import defaultdict import pickle import os from collections impo...
# -*- coding:utf-8 -*- # Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved. # This program is free software; you can redistribute it and/or modify # it under the terms of the MIT License. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the ...
from typing import Union, Tuple, Dict import pygame from pygame_gui.core import ObjectID from pygame_gui.core.interfaces import IContainerLikeInterface, IUIManagerInterface from pygame_gui.core import UIElement, UIContainer from pygame_gui.core.drawable_shapes import RectDrawableShape, RoundedRectangleShape from pyg...
import numpy as np from scipy.sparse import coo_matrix def crosstab(*args, levels=None, sparse=False): """ Return table of counts for each possible unique combination in ``*args``. When ``len(args) > 1``, the array computed by this function is often referred to as a *contingency table* [1]_. The...
import astropy.units as u import numpy as np import pytest import xarray as xr from psipy.model import base, mas def test_mas_model(mas_model): # Check that loading a single file works assert isinstance(mas_model, base.ModelOutput) assert "MAS output in directory" in str(mas_model) assert 'rho' in st...
'''初始化''' from .food import Apple from .snake import Snake from .endInterface import endInterface from .utils import drawGameGrid, showScore
# # Copyright 2021 Red Hat Inc. # SPDX-License-Identifier: Apache-2.0 # """Query Handling for all APIs.""" import datetime import logging from dateutil import parser from dateutil import relativedelta from django.core.exceptions import FieldDoesNotExist from django.db.models.functions import TruncDay from django.db.mo...
####################################################################################################### # AUTHOR : aswin.pradeep@tarento.com # AIM : Script to initiate alignment for two text files # USAGE : python3 exec_alignfiles.py -sc "./mal.txt" -l "ml" -tg "./eng.txt" #######################################...
import json import os from shutil import copyfile import sys if (len(sys.argv)!=3): print ('Please provide two args <url of archived_releases.json> and <url of latest_releases.json>') sys.exit() # path of archived_releases.json path_archived = sys.argv[1] # path of latest_release.json path_latest = sys.arg...
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may ...
from talon import noise, ctrl, settings from talon_plugins import eye_mouse, eye_zoom_mouse def on_pop(active): if not settings.get("user.noise_enabled"): return # # for pop active = False always if not eye_zoom_mouse.zoom_mouse.enabled: ctrl.mouse_click(button=1) # ctrl.mouse_clic...
# Licensed under a 3-clause BSD style license - see LICENSE.rst import os import pytest PYFILE_CONTENTS = """ import pytest from six.moves.urllib.request import urlopen def test_config_setting(pytestconfig): assert pytestconfig.getini('remote_data_strict') == {} {} def test_internet_acce...
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class Makedepend(AutotoolsPackage, XorgPackage): """makedepend - create dependencies in makefile...
from flask_restful import Resource from flask_apispec import MethodResource, marshal_with, doc from .serializers.healthcheck import HealthcheckResponseSchema class HealthcheckResource(Resource, MethodResource): @doc( summary="Check the app's health status", tags=["Healthcheck"] ) @marshal...
import torch from overrides import overrides from reclib.training.metrics.average import Average from reclib.training.metrics.metric import Metric @Metric.register("perplexity") class Perplexity(Average): """ Perplexity is a common metric used for evaluating how well a language model predicts a sample. ...
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import math import torch import t...
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright: Gencebay Demir from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} import time try: ...
# -*- coding: utf-8 -* import numpy as np import torch import torch.nn.functional as F from ...module_base import ModuleBase from ..loss_base import TRACK_LOSSES from .utils import SafeLog eps = np.finfo(np.float32).tiny @TRACK_LOSSES.register class SigmoidCrossEntropyCenterness(ModuleBase): default_hyper_para...
# -*- coding: utf-8 -*- from nose.plugins.attrib import attr from unittest import TestCase import os class BookTestCase(TestCase): @attr("skip") def test_scaffold(self): assert False # create temp directory directory = "../var/tests/book" if not os.path.exists(directory): ...
from django.conf.urls import url from django.contrib.auth.decorators import login_required, permission_required from . import views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ url(r'^$', views.users, name='customers'), url(r'^add/$', permission_...
"""andytest URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.1/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-base...
import warnings from django.conf import settings class AuthenticationMethod: USERNAME = 'username' EMAIL = 'email' USERNAME_EMAIL = 'username_email' # Determines the expiration date of e-mail confirmation mails (# of days) EMAIL_CONFIRMATION_EXPIRE_DAYS \ = getattr(settings, "ACCOUNT_EMAIL_CONFIRMATIO...
from flask import Flask, request from flask.helpers import url_for from werkzeug import redirect from urllib.parse import urljoin, urlparse app = Flask(__name__) @app.route('/hello') def hello(): return 'Hello, world' @app.route('/foo') def foo(): return '<h1>Foo page<a href="{href}">Do something</a></h1>'...
# coding: utf-8 import pprint import re import six class CreateCustomerV2Req: """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the valu...
import unittest import os import logging import re from oeqa.selftest.base import oeSelfTest from oeqa.selftest.buildhistory import BuildhistoryBase from oeqa.utils.commands import runCmd, bitbake, get_bb_var import oeqa.utils.ftools as ftools from oeqa.utils.decorators import testcase class LayerAppendTests(oeSelfTe...
from interrogatio.validators import RequiredValidator from connect.cli.plugins.project.cookiehelpers import slugify from connect.cli.plugins.project.validators import PythonIdentifierValidator REPORT_BOOTSTRAP_WIZARD_INTRO = ( 'Welcome to the Connect Reports Project Bootstrap utility.\n' 'Using this utility m...
#!/usr/bin/python from __future__ import absolute_import from __future__ import division from __future__ import print_function import argparse,random import time import matplotlib.pyplot as plt import numpy as np import tensorflow as tf #for removing CPU problem import os os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' de...
# Copyright 2018 Google 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 applicable law or a...
"""Top-level package for EpiBOX.""" __author__ = """Ana Sofia Carmo""" __email__ = 'anascacais@gmail.com' __version__ = '1.0.0'
import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable import numpy as np import scipy import colorsys import random import torchvision.models as models from model.utils.config import cfg from model.roi_crop.functions.roi_crop import RoICropFunction import cv2 import pdb ...
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. from collator import collator from wrapper import ( MyGraphPropPredDataset, MyPygPCQM4MDataset, MyZINCDataset, MyCoraDataset, ) import numpy as np from pytorch_lightning import LightningDataModule import torch from torch.nn impo...
#!/usr/bin/env python import mock import math import time import robocar from position import Position TEST_ROUTE = [Position(0.0, 0.0), Position(2.0, 0.0), Position(2.0, 2.0), Position(0.0, 2.0)] class TestRobocar: @mock.patch('robocar.PositioningService', autospec=True) def test_start(self, PositioningServiceM...
import csv import os import numpy as np from ..base import BaseDataset from ..utils import image_loader from .schemas import SegmentationDatasetSchema LABELS = ['sky', 'building', 'column_pole', 'road', 'sidewalk', 'tree', 'sign', 'fence', 'car', 'pedestrian', 'byciclist', 'void'] """ For the CamVid datase...
# coding=utf-8 # ------------------------------------ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. # ------------------------------------ from typing import Any from azure.core.credentials import AzureKeyCredential from azure.core.pipeline.policies import AzureKeyCredentialPolicy from .._gen...
#Check number """ Given an integer n, find if n is positive, negative or 0. If n is positive, print "Positive" If n is negative, print "Negative" And if n is equal to 0, print "Zero". """ Input Format : Integer n Output Format : "Positive" or "Negative" or "Zero" (without double quotes) Solution : n = int(input()) if ...
#encoding:utf-8 from system.models import * from store.classes import * class Administrator_class: #管理员ID编号 AdministratorID = 0 #管理员帐号 AdministratorAccount = "" #管理员密码 AdministratorPassword = "" #管理员昵称 AdministratorName = "" #管理员电话 AdministratorTelephone = 0 #管理员邮件 AdministratorEmail = "" #主页店铺广告 ...
from __future__ import print_function, absolute_import from reid.snatch import * from reid import datasets from reid import models import numpy as np import torch import argparse import os from reid.utils.logging import Logger import os.path as osp import sys from torch.backends import cudnn from reid.utils.serializat...
import attr from openapi_core.schema.exceptions import OpenAPIMappingError class OpenAPIParameterError(OpenAPIMappingError): pass class MissingParameterError(OpenAPIParameterError): """Missing parameter error""" pass @attr.s(hash=True) class MissingParameter(MissingParameterError): name = attr.ib...
from typing import Dict, Tuple import pytest # store history of failures per test class name and per index # in parametrize (if parametrize used) _test_failed_incremental: Dict[str, Dict[Tuple[int, ...], str]] = {} def pytest_runtest_makereport(item, call): if "incremental" in item.keywords: # increment...
# # htmlTableParser.py # # Example of parsing a simple HTML table into a list of rows, and optionally into a little database # # Copyright 2019, Paul McGuire # import pyparsing as pp import urllib.request # define basic HTML tags, and compose into a Table table, table_end = pp.makeHTMLTags("table") thead, thead_end ...
# if using tensorflow, import keras as tf.keras import os import numpy as np #import keras import tensorflow as tf from tensorflow import keras import numpy as np from tensorflow import keras from matplotlib import pyplot as plt # print some info print('backend:', keras.backend.backend() ,', version:'...
from __future__ import absolute_import, division, print_function from cctbx.array_family import flex from mmtbx.geometry_restraints import c_beta import mmtbx.model import iotbx pdb_str_1 = """\ CRYST1 26.960 29.455 29.841 90.00 90.00 90.00 P 21 21 21 ATOM 1 N TYR A 20 10.702 10.331 8.954 1....
# Copyright (C) 2016 Nokia Corporation and/or its subsidiary(-ies).
#!/usr/bin/env python3 # Copyright (c) 2014-2017 The Bytcoyn Core Developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test the wallet accounts properly when there is a double-spend conflict.""" from test_framework.test_f...
# Copyright 2021 The TensorFlow Authors. 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 applica...
# Copyright 2021, Altinity Inc. All Rights Reserved. # # All information contained herein is, and remains the property # of Altinity Inc. Any dissemination of this information or # reproduction of this material is strictly forbidden unless # prior written permission is obtained from Altinity Inc. from re import S ...
#!/usr/bin/env python import os import argparse from pyaam.muct import MuctDataset from pyaam.shape import ShapeModel from pyaam.patches import PatchesModel from pyaam.texture import TextureModel from pyaam.combined import CombinedModel from pyaam.detector import FaceDetector def parse_args(): parser = argparse...
# Copyright 2019 The TensorNetwork Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed ...
# list of numbers list1 = [11, -21, 0, 45, 66, -93] # iterating each number in list for num in list1: # checking condition if num >= 0: print(num, end = " ")
# -*- coding: utf-8 -*- import numpy as np from scipy import sparse from pygsp import utils from . import Graph # prevent circular import in Python < 3.5 class Minnesota(Graph): r"""Minnesota road network (from MatlabBGL). Parameters ---------- connected : bool If True, the adjacency matri...
from __future__ import print_function import sys if len(sys.argv) != 2: print('ERROR: pass solver prototxt as argument') sys.exit(1) print("Loading libraries") import matplotlib matplotlib.use("Agg") import os import caffe import numpy as np ## ADD PATHS def addPath(path): if path not in sys.path: ...
#!/usr/bin/python from ABE_ADCPi import ADCPi from ABE_helpers import ABEHelpers import time import os """ ================================================ ABElectronics ADC Pi 8-Channel ADC demo Version 1.0 Created 09/05/2014 Version 1.1 16/11/2014 updated code and functions to PEP8 format Requires python smbus to ...
import os.path as osp import pickle import shutil import tempfile import time import mmcv import torch import torch.distributed as dist from mmcv.runner import get_dist_info from mmdet.core import encode_mask_results, tensor2imgs def single_gpu_test(model, data_loader, show=F...
from liu import * # construct CFG cfg = ControlFlowGraph() n2 = cfg.new_block(Assign(Var('i'), Subtract(Var('m'), Const('1')))) n3 = cfg.new_block(Assign(Var('j'), Var('n'))) n4 = cfg.new_block(Assign(Var('a'), Var('u1'))) n5 = cfg.new_block(Assign(Var('i'), Add(Var('i'), Const('1')))) n6 = cfg.new_block(Assign(Var('j...
'''Copyright 2018 Paul Carino 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 https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writi...
import math #ANSWER: always returns 5, no matter what x is. def clearBox1(x): return int(((1.0-math.cos(2.0*x))/2.0)**2 + math.sin(math.pi/2.0 - x)**2)+5 #ANSWER: returns the larger of a and b def clearBox2(a, b): if(a > b): return a else: return b #ANSWER: returns the remainder of a divi...
version = "12.1"
import numpy as np from b3px_gym.b3px_env.singleton.valkyrie_gym_env.filter import FilterClass, EMAFilter, KalmanFilter class PDController: def __init__(self, gains = [0,0], u_max = 0, v_max = 0, name = None, is_filter = [False, False, False], T = None, cutoff = None, N = None): self.Kp = gains[0] ...