text
stringlengths
3.07k
22.1k
# Copyright 2011 webapp2 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 to in wri...
# coding: utf-8 import io import six import logging import re import os import time from babelfish import language_converters from subzero.language import Language from requests import Session from subliminal_patch.providers import Provider from subliminal_patch.providers.mixins import ProviderSubtitleArchiveMixin f...
import random from collections import deque from itertools import count, islice from queue import deque from typing import Any, Sequence import numpy as np from imgaug.augmentables import Keypoint, KeypointsOnImage, HeatmapsOnImage, heatmaps from imgaug.augmenters import * from skimage.transform import rescale from ....
import logging from typing import Iterable, Sequence from django.apps import apps from django.conf import settings from django.contrib.humanize.templatetags.humanize import naturaltime from django.core.cache import caches from django.db import models from django.forms.widgets import RadioSelect from django.utils impor...
from misc_functions import (get_params, convert_to_grayscale, save_gradient_images, preprocess_image, save_class_activation_on_image ) import cv2 import matplotlib.pyplot as plt f...
from typing import Callable, List, Optional import torch.nn as nn from torch import Tensor from torch.utils.data import DataLoader from captum._utils.models.model import Model class LinearModel(nn.Module, Model): SUPPORTED_NORMS: List[Optional[str]] = [None, "batch_norm", "layer_norm"] def __init__(self, t...
'''VGG for CIFAR10. FC layers are removed. (c) <NAME> ''' import torch.nn as nn import torch.utils.model_zoo as model_zoo import math import torch __all__ = ['vgg19_bn_para'] class VGG(nn.Module): def __init__(self, features, gpu_num = 2, num_classes=1000, split_size=64): super(VGG, self).__init__() ...
# -*- coding: utf-8 -*- """ Created on Wed Aug 22 16:29:08 2018 @author: usuario """ """ ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ SECTION 0. loading libraries and defining some variables """ import logging logging.getLogger("tensorflow").setLevel(logging.WARNING) from numpy.rando...
import os from operator import itemgetter from os.path import join from dvc.path_info import PathInfo from dvc.repo import Repo from dvc.scm import SCM from dvc.tree.git import GitTree from dvc.tree.local import LocalTree from dvc.tree.repo import RepoTree from dvc.utils.fs import remove from tests.basic_env import Te...
""" Creates Figure 4 -- Model Interpretation """ from os.path import abspath, dirname from string import ascii_uppercase import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns from sklearn.preprocessing import scale from sklearn.utils import resample from .common import getSetup ...
#!/usr/bin/env python """ Example Usage: $ INVENTORY_DRIVER=openstack ansible -i inventory machinename -m ping ** Roadmap ** - AWS Support such as (https://github.com/ansible/ansible/blob/devel/contrib/inventory/ec2.py) - Vagrant Support """ from __future__ import print_function from novaclient import client impo...
# Copyright (c) 2017 Cisco Systems # 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 require...
# Back-Propagation Neural Network for estimated value learning # # Written in Python with Numeric python # # <NAME> <jamartin AT dia fi upm es> from Numeric import * from RandomArray import * import pickle #from numpy import * # use this if you use numpy instead of Numeric import time seed(3,3) def ...
#!/usr/bin/env python # -- Content-Encoding: UTF-8 -- """ iPOPO remote shell Provides a remote interface for the Pelix shell that can be accessed using telnet or netcat. :author: <NAME> :copyright: Copyright 2014, isandlaTech :license: Apache License 2.0 :version: 0.5.8 :status: Beta .. Copyright 2014 isandlaTe...
# Utility methods for the qsvm. import os import joblib from typing import Tuple, Dict from qiskit import IBMQ from qiskit import Aer from qiskit import QuantumCircuit from qiskit.utils import QuantumInstance from qiskit.providers.exceptions import QiskitBackendNotFoundError from qiskit.circuit import ParameterVector ...
# -*- coding: utf-8 -*- # python-holidays # --------------- # A fast, efficient Python library for generating country, province and state # specific sets of holidays on the fly. It aims to make determining whether a # specific date is a holiday as fast and flexible as possible. # # Author: ryanss <<EMAIL>> (c) ...
import typing as t from secrets import token_urlsafe from django.conf import settings from django.db import models from django.db.models import Count from django.utils.translation import ugettext_lazy as _ def generate_room_token(nbytes=20): """Generate unique token for room.""" return token_urlsafe(nbytes) ...
from pybullet_planning import INF from copy import deepcopy class LadderGraphEdge(object): def __init__(self, idx=None, cost=-INF): self.idx = idx # the id of the destination vert self.cost = cost # TODO: we ignore the timing constraint here def __repr__(self): return 'E idx{0}...
import csv import datetime from io import BytesIO, StringIO import json from urllib.parse import quote_plus from django.conf import settings from django.contrib.sites.models import Site from django.http import Http404, HttpResponse from django.shortcuts import reverse from django.template.loader import get_template fr...
def extractNlens(seq): n_lens = [] n_len = 0 i = 0 while i < len(seq): while i < len(seq) and seq[i] == 'N': n_len += 1 i += 1 if n_len > 0: n_lens.append(n_len) n_len = 0 i += 1 return n_lens def parseInputFasta(ifn): seq_lens = [] n_lens = [] seqs_with_ns_count = 0 with open(if...
"""Functions to map a wikidata entity response to an openArtBrowser model """ from pathlib import Path from typing import Dict, List, Optional import data_extraction.map_wd_attribute as map_wd_attribute from data_extraction.constants import * from shared.utils import language_config_to_list, setup_logger logger = se...
import copy import math import os import random import subprocess import sys import time import numpy as np import pudb import torch import torch.nn.functional as F import zmq import msgpack import msgpack_numpy import yaml from rmp_nav.common.utils import pprint_dict from . import networks msgpack_numpy.patch() ...
# Copyright 2018, <NAME>, mailto:<EMAIL> # # Part of "Nuitka", an optimizing Python compiler that is compatible and # integrates with CPython, but also works on its own. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the Lice...
from django.db import models from blame.models import Blame from money.models import MoneyField, Money, Price from sales.models import PriceField from tools.util import raiseif from decimal import Decimal from crm.models import User, PersonTypeField, OrganisationTypeField, Customer, PersonTypeFieldValue, \ Organisa...
import sys import importlib import dateutil.parser import six from collections import defaultdict from django.conf import settings from django.db.utils import IntegrityError from .compat import get_model from .finders import DefaultDataFinder class LoadNotConfigured(Exception): pass class RelativeKeyDoesNotExis...
from . import samtools import socket class IncompleteIOError(BlockingIOError): pass class SourceError(socket.error): pass def it_leaks(func): def f(self, *args, **kwargs): human_error = func(self, *args, **kwargs) + \ ' Calling the original method will leak your packets.' rai...
''' This program implements a Pix2Pix network. References: https://github.com/tensorflow/examples/blob/master/tensorflow_examples/models/pix2pix/pix2pix.py https://www.tensorflow.org/tutorials/generative/pix2pix ''' from __future__ import absolute_import, division, print_function, unicode_literals import ten...
""" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Make animations of 3d rotating polyhedron ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ This script computes the data of a given polyhedra and writes it into a POV-Ray .inc file, then automatically calls POV-Ray to render the frames and finally calls FFmpeg to convert the fram...
# encoding: utf-8 import logging import torchvision import torch import torch.nn as nn from ignite.engine import Engine, Events from utils.reid_metric import r1_mAP_mINP, r1_mAP_mINP_reranking from ignite.handlers import Timer import matplotlib.pyplot as plt import numpy as np import pickle import os from utils.re_rank...
import json import logging import os import pty import shlex # Manually create a TTY that we can use as the default STDIN import subprocess import tempfile from fcntl import fcntl, F_GETFL, F_SETFL from tests.waiter import util _STDIN_TTY = pty.openpty()[1] def decode(b): """Decodes as UTF-8""" return b.de...
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (c) 2020 Huawei Device Co., Ltd. # 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 ...
from os import listdir, name, system from os.path import isfile, join, exists from datetime import datetime class IdNumber: def __init__(self, year, month, day, number) -> None: self.year = year self.month = month self.day = day self.number = number def valid_date(self): ...
import os import sys import colorsys sys.path.insert(0, './') import glob import string import numpy as np import pyvista as pv import tensorflow as tf from utils import helpers, tf_utils def rotate_boxes(boxes, centers, theta): pts_out = np.zeros((boxes.shape[0], 8, 3), np.float32) for i, (b, c, r) in enumerat...
# Copyright 2015 The Switch Authors. All rights reserved. # Licensed under the Apache License, Version 2, which is in the LICENSE file. """ Defines model components to describe unit commitment of projects for the SWITCH-Pyomo model. This module is mutually exclusive with the project.no_commit module which specifies s...
#!/usr/bin/env python # -*- coding: utf-8 # Core functions dealing with centerline extraction from 3D data. import logging import numpy as np from spinalcordtoolbox.image import Image, zeros_like from spinalcordtoolbox.centerline import curve_fitting logger = logging.getLogger(__name__) class ParamCenterline: ...
import sys import pickle import subprocess import os import re import datetime import time #src/python/runGeoShapeBenches.py -compare -reindex -ant reTotHits = re.compile('totHits=(\d+)$') nightly = '-nightly' in sys.argv compareRun = '-compare' in sys.argv if nightly and compareRun: raise RuntimeError('cannot ru...
from django.contrib.gis.db import models from django.contrib.auth import get_user_model from django.contrib.gis.db.models.fields import PolygonField, MultiPolygonField from django.core.validators import MinValueValidator, MaxValueValidator from django.db import connection from django.utils.translation import ugettext_l...
import numpy as np import scipy.io as sio from scipy.signal import correlate from scipy.signal import convolve def construct_Aty_regularized(A, y, L_x, num_speakers, num_listeners, N, N_p): # The length of Hty is given by L_x*num_speakers # y contains the set of signals intended to be transmitted of tota...
#!/usr/bin/env python import numpy as np def fast_shift3d(in_array, positions, padding=0): out_array = np.zeros_like(in_array) pos0 = positions[0] pos1 = positions[1] pos2 = positions[2] if pos0 >= 0 and pos1 >= 0 and pos2 >= 0: if pos0 == 0 and pos1 > 0 and pos2 > 0: out_ar...
# -*- coding: utf-8 -*- from __future__ import unicode_literals import logging from django.http.response import HttpResponse, HttpResponseNotFound from django.shortcuts import redirect from django.utils.http import urlencode from django.views import View import six from wechatpy import WeChatOAuth as _WeChatOAuthClie...
## Orchestration Analyzer by <NAME> 2020 ## Wether to use production server or not Production = True if Production: import os from random import randint import flask import dash from dash.dependencies import Input, Output import dash_bootstrap_components as dbc import dash_html_components as html import dash_admi...
import argparse import matplotlib import attack_utils matplotlib.use('Agg') import matplotlib.pyplot as plt import os import json import numpy as np def plot_quantiles(original_mu ,original_sigma, perturbed_output_mu, perturbed_output_sigma, best_c, best_perturbation ,best_distance,...
#!/usr/bin/env python # coding: utf-8 # In[16]: import sys import pandas as pd import numpy as np from json import loads, dumps from ortools.constraint_solver import routing_enums_pb2, pywrapcp from scipy.spatial import distance_matrix import subprocess # In[17]: inf = int(1e10) max_time = (24 - 6) * 60 start = 6...
import json import logging from datetime import datetime from functools import partial from typing import Any, List, Optional, Tuple, Type, Union from uuid import UUID import httpx from leaderdata.conf import DSN, OPENAPI_PATH, ensure_openapi_exists from leaderdata.exceptions import ( APIServerError, BadReques...
# # 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 us...
#!/usr/bin/env python # coding=utf-8 ########################################### # # Dell DRAC and Chassis Scanner # Default Credential Check # UN: root PW: calvin # # Written by <NAME> (ReL1K) # Company: TrustedSec, LLC # Website: https://www.trustedsec.com # @TrustedSec # ########################################## i...
# -*- coding: utf-8 -*- """ Created on Tue Jul 31 17:38:55 2018 @author: <NAME>/spm9r """ import networkx as nx import pandas as pd # Read in updated concept relationship data including exclusivity dfRel = pd.read_csv("C:/Users/spm9r/eclipse-workspace-spm9r/TREC2018/data/exclusivity_graph_data.csv", names=['CUI1','C...
# /server/app/views.py import json from flask import jsonify, request # User file imports from app import create_app from instance import config # Need to define the variables in here yourself, inside an instance.config folder from app.errors import user_present, user_not_present, family_present, invalid_format, inv...
"""Manipulate algebraic models of bit-vector operations.""" import decimal import functools from cascada.bitvector import core from cascada.bitvector import operation from cascada.bitvector import context from cascada import abstractproperty from cascada.algebraic import value zip = functools.partial(zip, strict=T...
""" This file contains all the functions to connect to the elasticsearch server and modify it's database """ from elasticsearch import Elasticsearch import datetime es = Elasticsearch() def get_unfinished_event_count() -> int: """Determines how many unprocessed events remain""" r = es.search( index="...
#!/usr/bin/python import os import sys my_path = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, os.path.dirname(my_path)) import pytest import json from datetime import datetime import src.afqp_check as afqp_check check_fs_params_existing = [ (afqp_check.AFR_ROOT, 'rules.json', 'ti'...
import inspect from typing import Optional, Union import numpy as np from odin.ml.base import evaluate from odin.ml.cluster import fast_dbscan, fast_kmeans, fast_knn from odin.ml.tree import * from odin.ml.decompositions import * from odin.ml.fast_lda_topics import fast_lda_topics, get_topics_string from odin.ml.linea...
# pylint: disable=invalid-name # pylint: disable=too-many-arguments # pylint: disable=too-many-locals """ Module for adding layers together. Two types of starting methods are possible. import iadpython.start import iadpython.layer n=4 slab = iadpython.start.Slab(a=0.9, b=10, g=0.9, n=1.5) method...
# xeb.py # # Authors M. <NAME> & <NAME> import matplotlib.pyplot as plt from typing import List, Callable import numpy as np import functools import itertools def random_unitary(dim: int) -> np.ndarray: # follows the algorithm in https://arxiv.org/pdf/math-ph/0609050.pdf # returns a unitary of size dim x dim...
from utility import SCRYError from rdflib import Namespace from rdflib.graph import Graph from rdflib.term import Literal, URIRef SCRY = Namespace('http://www.scry.com/') A = URIRef('http://www.w3.org/1999/02/22-rdf-syntax-ns#type') STANDARD_ATTRIBUTES = ['author','descript...
import json import logging import time from typing import Any, Dict, List, Optional import boto3 from aws_orbit_sdk.common import get_workspace logging.basicConfig( format="%(asctime)s %(levelname)-8s %(message)s", level=logging.INFO, datefmt="%Y-%m-%d %H:%M:%S", ) logger = logging.getLogger() def dele...
""" A Product specifies a persistent object in disk such as a file in the local filesystem or an table in a database. Each Product is uniquely identified, for example a file can be specified using a absolute path, a table can be fully specified by specifying a database, a schema and a name. Names are lazy evaluated, th...
#*************************************************************************************************** # Copyright 2015, 2019 National Technology & Engineering Solutions of Sandia, LLC (NTESS). # Under the terms of Contract DE-NA0003525 with NTESS, the U.S. Government retains certain rights # in this software. # Licensed...
# Auto generated from reporting.yaml by pythongen.py version: 0.9.0 # Generation date: 2021-09-01 20:03 # Schema: reporting # # id: https://w3id.org/linkml/reporting # description: A datamodel for reports on data # license: https://creativecommons.org/publicdomain/zero/1.0/ import dataclasses import sys import re from...
import torch import torch.nn as nn import torchvision.models as models import torch.nn.functional as F import math from .image_proc import * from .geometry import * class L1Loss(nn.Module): def __init__(self): super(L1Loss, self).__init__() def forward(self, output, target, weight=None, mean=False): ...
#!/usr/bin/env python # coding: utf-8 # /*########################################################################## # # Copyright (c) 2016 European Synchrotron Radiation Facility # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the ...
from utils.checker import is_not_null, is_null from database.anime_database import AnimeDatabase from database.nichijou_database import NichijouDatabase from utils import echo import os import sys import json import click import editdistance @click.group() def cli(): pass @cli.command() @click.argument('target') ...
from ast import literal_eval from dataclasses import dataclass import io from typing import Any EXAMPLE1 = """[1,1] [2,2] [3,3] [4,4]""" RESULT1 = [[[[1, 1], [2, 2]], [3, 3]], [4, 4]] EXAMPLE2 = """[1,1] [2,2] [3,3] [4,4] [5,5]""" RESULT2 = [[[[3, 0], [5, 3]], [4, 4]], [5, 5]] EXAMPLE3 = """[1,1] [2,2] [3,3] [4,4] [...
import sys import pygame from bullet import Bullet from alien import Alien from time import sleep def check_keydown_events(event, ai_settings, screen, ship, bullets): """ response to key down """ if event.key == pygame.K_RIGHT: ship.moving_right = True elif event.key == pygame.K_LEFT: ...
import numpy as np from astropy.io import fits import platform import os import json import argparse from contextlib import redirect_stdout import copy from ipdb import set_trace as stop if (platform.node() == 'viga'): os.environ["THEANO_FLAGS"] = "mode=FAST_RUN,device=cpu,floatX=float32" os.environ["KERAS_BACKEN...
""" onyphe.client ~~~~~~~~~~~~~ This module implements the Onyphe API. :copyright: (c) 2017- by <NAME> """ import json import logging import requests from requests.utils import quote from six.moves.urllib.parse import urljoin from core.analytics import OneShotAnalytics from core.observables import Hostname, Ip def...
#%% ############################################################################ # IMPORTS ############################################################################ import numpy as np import tensorflow as tf import tensorflow.keras as keras import json import h5py import pickle import os from collections import def...
#!/usr/bin/env python3 import re import os import argparse import json import numpy as np import pickle from utils import encode from collections import Counter """ Preprocessing script for VQA question files. VQA问题文件的预处理 """ # according to https://github.com/Cyanogenoid/vqa-counting/blob/master/vqa-v2/data.py _speci...
########################################################################## # Spring 2020, NC State University # Course : CSC584 - Building Game AI # Instructor : Dr. <NAME> ## # Name : <NAME> # UnityID : <EMAIL> ## ##================== Assignment-2 (Part-1) Solutions ============######### ##===============...
import numpy as np import pandas as pd import torch import matplotlib.pyplot as plt class BatchSampler: """ Creates a batch sampler from raw-ish data pairs X, y. The data needed for training a siamese networks are image pairs from X and binary indicators indicating whether they are equal. Instead of...
from __future__ import print_function, division, absolute_import import os from shutil import copyfile from collections import defaultdict import numpy as np import numba as nb from odin import fuel as F from odin import preprocessing as pp from odin.utils import bidict from utils import laugh_labels win = 0.015 sh...
import socket, sys, random, os import time from multiprocessing import Process from datetime import datetime server_old_private_value, server_private_value, server_private_time = 0, 0, 0 client_old_private_value, client_private_value, client_private_time = 0, 0, 0 token = 0 common_value = 1758 old_token, ne...
from typing import List, Optional import numpy as np from scipy import stats from simple_settings import settings from .. import constants, plotting from ..utils import str_list from .base import DatasetBase, DatasetMetadata, DatasetPlottingSchema, DatasetSchemaBase class DichotomousDataset(DatasetBase): """ ...
#!/usr/bin/env python ######################################################################################### # # Create mask along z direction. # # --------------------------------------------------------------------------------------- # Copyright (c) 2014 Polytechnique Montreal <www.neuro.polymtl.ca> # Authors: <NA...
import argparse import importlib import os from collections import defaultdict import pandas as pd import torch import torch.nn as nn import tqdm from matplotlib import pyplot as plt from tensorboardX import SummaryWriter from torch.utils.data import DataLoader from torch.utils.data.dataset import ConcatDataset from ...
""" modifications: change from in import of robot_env, rotations and utils commented out and added line to set the gripper_initial_xpos to that from the FetchReach-v1 environment modified _sample_goal method to eliminate unreachable goals in table """ import numpy as np from CustomGymEnvs.envs.fetchreach.CustomFetchRe...
from __future__ import absolute_import, division, print_function from six.moves import range from scitbx.matrix import sqr,col from math import sin,cos,pi from scitbx.array_family import flex import sys class one_sensor(object): def __init__(self,image,sensor,manager): self.image = image self.sensor = sensor ...
import sys import json import numpy as np from bson.binary import Binary import pickle import requests import tensorflow as tf from tensorflow import keras import os import bson from bson.json_util import dumps from flask import Flask, request app = Flask(__name__) np.random.seed(2) class Client: client_id = 0 ...
# TODO: these tests need clean up, is a merge from two files since # StringPlaceholder was removed and its interface was implemented directly # in Placeholder import tempfile from copy import copy, deepcopy from pathlib import Path import pytest from ploomber.placeholders.placeholder import (Placeholder, ...
""" pytest PluginManager, basic initialization and tracing. (c) <NAME> 2004-2010 """ import sys, os import inspect import py from _pytest import hookspec # the extension point definitions assert py.__version__.split(".")[:2] >= ['1', '4'], ("installation problem: " "%s is too old, remove or upgrade 'py'" % (py.__v...
"""Combine code coverage files.""" from __future__ import annotations import os import json import typing as t from ...target import ( walk_compile_targets, walk_powershell_targets, ) from ...io import ( read_text_file, ) from ...util import ( ANSIBLE_TEST_TOOLS_ROOT, display, ApplicationErr...
# coding=utf-8 # Copyright 2021-present, the Recognai S.L. team. # # 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 ...
import numpy as np import os import matplotlib.pyplot as plt from numpy import array from game2048.game import Game from game2048.agents import ExpectiMaxAgent, Agent from keras.callbacks import ReduceLROnPlateau as RLRL from game2048.displays import Display from keras.callbacks import TensorBoard from keras.models imp...
# -*- coding: utf-8 -*- from __future__ import unicode_literals import re from django.db import models from django.contrib.auth.models import User from django.utils import timezone from .bancos import BANCOS ENQUADRAMENTO_FISCAL = [ ('LR', '实际利润'), ('LP', '假设利润'), ('SN', '简单的国家'), ('SE', '简单的国家过度的高收...
# Copyright 2019 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...
# -*- coding: utf-8 -*- """ 后处理,生成结果,计算F1 """ import sys import json import os import zipfile import traceback import argparse from tqdm import tqdm SUCCESS = 0 FILE_ERROR = 1 ENCODING_ERROR = 2 JSON_ERROR = 3 SCHEMA_ERROR = 4 TEXT_ERROR = 5 CODE_INFO = ['success', 'file_reading_error', 'encoding_error', 'json_parse_...
import numpy as np import pandas as pd from floris.utils.visualization.wflo_opt import wf_layout_plot # ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ # # WIND_FARMS # # ++++++++++++++++++++++++++++++++++++++++++++++++++++...
# # Copyright (c) 2019 nexB Inc. and others. All rights reserved. # http://nexb.com and https://github.com/nexB/scancode-toolkit/ # The ScanCode software is licensed under the Apache License version 2.0. # Data generated with ScanCode require an acknowledgment. # ScanCode is a trademark of nexB Inc. # # You may not use...
''' Copyright 2022 Airbus SAS 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 to in writing, software dis...
import pyvisa as visa from enum import Enum from pyTekMSO.pyTekMSOConst import * class Acq_Mode(Enum): RUNSTOP = False SEQUENCE = True pass class Source_Type(Enum): CH = 'CH' MATH = 'MATH' REF = 'REF' ALL = 'ALL' pass class TekMSO_Error(Exception): def __init__(self, msg): ...
import inspect import threading from queue import SimpleQueue from dataclasses import dataclass, astuple import numpy as np import torch import torch.cuda.amp as amp from torch.utils.data.dataloader import default_collate from skorch import NeuralNet from skorch.utils import to_device _default_nn_params = { nam...
""" This script demonstrates how to perform the KS2 discretely. Examples aren't always Pythonic, but they're easy to translate to C. """ import numpy as np import matplotlib.pyplot as plt import dataReader import scipy.stats class ksTest: def __init__(self, valuesA, valuesB, binSize=.1, displayInfo=False, crea...
# This file is used to construct and visualize critical point sets # and upper-bound sets based on a trained model and a sample. # This file only support batch_size = 1 and is modified base on file # "evalutate.py" import tensorflow as tf import numpy as np import argparse import socket import importlib import time ...
""" Test Linear Policy with RBF Features for the WAM Ball-in-a-cup task. """ import torch as to import numpy as np import matplotlib.pyplot as plt import mpl_toolkits.mplot3d import pyrado from pyrado.environment_wrappers.utils import inner_env from pyrado.environments.mujoco.wam import WAMBallInCupSim from pyrado.log...
import io from functools import partial import torch import torch.nn as nn from pytorch_models_imp.my_transformer import Transformer # from pytorch_models_imp.transformer import Transformer from torch.nn.utils.rnn import pad_sequence from torch.utils.data import DataLoader from torchtext.data.utils import get_tokenize...
import math import torch import argparse from tqdm import tqdm import pargs import onqg.dataset.Constants as Constants from onqg.dataset.Vocab import Vocab def load_vocab(filename): vocab_dict = {} with open(filename, 'r', encoding='utf-8') as f: text = f.read().strip().split('\n') text = [word.s...
#!/usr/bin/env python3 import sys, os, getopt import asyncio import aiohttp from aiohttp import web from aiohttp.web_exceptions import HTTPFound, HTTPTemporaryRedirect import secrets import struct import pickle from enum import Enum from collections import deque # communication with worker from jobmsg import JobMsg d...
from __future__ import print_function import os from ctypes import * import sys import atexit _c_libcbase = cdll.LoadLibrary("libbase.so") def c_base_func(c_lib, restype, name, argtypes): """Export C function from shared C library.""" r = getattr(c_lib, name) r.restype = restype r.argtypes = argtypes...
import warnings from warnings import warn import numpy as np import scipy as sp from scipy.sparse.linalg.isolve.utils import make_system from scipy.linalg import get_blas_funcs, get_lapack_funcs from pyamg.util.linalg import norm __all__ = ['gmres_mgs'] def apply_givens(Q, v, k): """Apply the first k Givens ro...
# -*- coding: utf-8 -*- """ Created on Fri Mar 30 00:50:41 2018 @author: aumale """ import requests from bs4 import BeautifulSoup import time import json import re import os def getAPIkey(file='./data/nyt_api.key') : """ Get New York Times API key from a file Parameters ---------- file : str...