text
stringlengths
6.04k
39.5k
#!/usr/bin/env python3 # coding: UTF-8 import os import sys import datetime from copy import deepcopy # import pprint import subprocess import re from optparse import OptionParser import json import yaml from collections import defaultdict __VERSION__ = '0.2.8' PYTHON_VERSION = sys.version_info[0] # major version...
# coding: utf8 import logging import time from weakref import WeakValueDictionary from octopus.dispatcher.model import FolderNode, TaskNode, Pool, RenderNode, Task, TaskGroup, Command, PoolShare from octopus.dispatcher.model.node import BaseNode from octopus.dispatcher.strategies import FifoStrategy, loadStrategyCla...
"""This module lists, validates and bootstraps sources. Context ------- Contributors describe the data sources by filling up a pseudo-datapackage file named source.description.yaml and dropping it into the national or regional source folder. This (simplified) YAML format is chosen over the JSO...
import os import sys import ssl import urllib import urllib.request import json from io import BytesIO import gzip import base64 import argparse import hashlib import datetime from .song import Song, ArtNotFound, get_album_art from .history import History from .sqlstore import SQLStore from .library import Library f...
# -*- coding: utf-8 -*- """ Extract ======= Functions to extract diagram-label pairs from schematic chemical diagrams. author: <NAME> email: <EMAIL> """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import logging ...
""" Description: This script generates figures for paper (Fig4, performance of all methods) """ import argparse import numpy as np import matplotlib as mpl mpl.use('Agg') # import seaborn as sns import matplotlib.pyplot as plt from utils.networkx_operations import * import numpy as np import pandas as pd import pickle...
import tensorflow as tf import numpy as np import matplotlib.pyplot as plt from typing import List from libs.NeuralNet import NeuralNet from libs.regulariser import ShiftedL1L2 # -- Target Networks -- def dense_ae( input_shape: tuple, layer_dims: List[int], hidden_activation="relu", p_dropout=.1, name="dense...
""" Adapted from https://github.com/kuangliu/pytorch-cifar/blob/master/models/preact_resnet.py """ import torch import torch.nn as nn import torch.nn.functional as F from torch import Tensor import pandas as pd from numbers import Number from .layers import Conv2d from .base import RegressionModel, ClassificationMode...
import torch, torch.nn as nn, torch.nn.functional as F from torch.nn.utils.rnn import pad_sequence class SimpleAttention(nn.Module): def __init__(self, input_dim): super().__init__() self.input_dim = input_dim self.scalar = nn.Linear(self.input_dim,1,bias=False) def fo...
import zlib import warnings import multiprocessing from collections import defaultdict from enum import Enum from pydantic import BaseModel, Field, BaseSettings, SecretStr, validator from typing import List, Any, Dict, Union, Optional, Tuple, Type from types import ModuleType from jinja2 import meta, Template from fast...
import random from dataclasses import dataclass from functools import reduce from math import ceil, floor from typing import Dict, List, Optional, Iterable, Union from uuid import uuid4 import numpy as np from lhotse.audio import RecordingSet from lhotse.features import Features, FeatureSet, FbankMixer from lhotse.su...
from pathlib import Path, PureWindowsPath import itertools import pandas as pd import numpy as np np.random.seed(5555) # for reproducibility from random import sample import matplotlib.pyplot as plt from numpy import mean from numpy import std from numpy import array from numpy import argmax from scipy.spars...
import asyncio import logging import json import os import time from concurrent.futures import CancelledError from pprint import pformat from urllib.parse import quote_plus as quote import aiohttp from aiohttp import hdrs from pyclda import get_mac_ver, async_MD5 from pyclda.aio_downloader import AioDownloader, Statu...
# SPADE # Copyright (c) 2021-present NAVER Corp. # Apache License v2.0 from copy import deepcopy import numpy as np import torch import spade.utils.general_utils as gu from spade.postprocess.eval import (get_init_stats_receipt, get_statistics_receipt, summary_receipt) get_statist...
from random import randrange from typing import Tuple, List, Dict, Any from itertools import zip_longest from math import ceil import logging from typing import Optional, TYPE_CHECKING import unit from powers import psychic_test from stratgey import Strategy, get_strategy_function if TYPE_CHECKING: from unit impo...
#Copyright Sorensenc 2020 - resume.conneris.me import sys import matplotlib.pyplot as plt import math from collections import Counter import statistics ''' In the section below, edit the Observations (Obs) list to reflect your team's velocity observations. Sometimes, things go awry and result in an observat...
#!/usr/bin/env python # _*_ coding: utf-8 _*_ # @Time : 2019/11/23 11:25 # @Author : Lujia (Lucia) Huang # @Contact : <EMAIL> # @File : FF3.py # @Version : # @Description: 对沪深两市房地产板块股票的FF3实证研究, # 年份: 'year_2016''year_2017''year_2018' # 对股票进行两种分组法: # 1)'name_4_gro...
#!/usr/bin/python3 import bisect import configparser import argparse import importlib import itertools import statistics import sys import time import random import re import unittest # TODO: design couple of levels # TODO: measure different algorithms # TODO: write README.md # TODO: write blogpost GO_UP = 'up' GO...
#!/usr/bin/python3 # coding=utf8 import sys sys.path.append('/home/pi/ArmPi/') import cv2 import time import Camera import threading from LABConfig import * from ArmIK.Transform import * from ArmIK.ArmMoveIK import * import HiwonderSDK.Board as Board from CameraCalibration.CalibrationConfig import * if sys.version_inf...
import numpy as np import pygame import sys,copy,random import math from random import shuffle from copy import deepcopy #gloable variable GREEN = (0,255,0) WHITE = (255, 255, 250) RED = (255,0,0) BLUE = (0,0,255) SQUARE = 80 HEIGHT = 6 WIDTH = 7 width = WIDTH * SQUARE height = HEIGHT* SQUARE+SQUARE size = (width, hei...
import matplotlib.pyplot as plt from typing import List from environments.environment_abc import Environment, State, Action from agents.agent_abc import Agent from agents.basic_mcts_agent import BasicMCTSAgent, MultiprocessingMCTSAgent from agents.alphagozero_esque_agent import AlphaGoZeroEsqueAgent, A0TinyAgent from a...
# Copyright 2012, <NAME> # Code at http://inamidst.com/duxlot/ # Apache License 2.0 import sys # Require 3.2.2 because of http://bugs.python.org/issue12576 if sys.version_info < (3, 2, 2): print("Error: Requires python 3.2.2 or later") sys.exit(1) import argparse import atexit import os import signal import...
#!/usr/bin/env python3 """Test: Test classes for Fab.""" # <--------------------------------------- 100 characters ---------------------------------------> # # Python library imports: from dataclasses import dataclass, field from typing import Any, cast, List, Tuple from pathlib import Path as PathFile # CadQuery li...
#### ----- LIBRARIES ----- #### import os import sys import time import random import shutil import time import smtplib import ssl import pandas as pd from selenium import webdriver from bs4 import BeautifulSoup #### ----- FUNCTIONS DEFINITION ----- #### ## ----- Core scraping functions ----- ## def get_profile_info...
import numpy as np import torch import threading import json import shutil import os from continual_rl.policies.impala.torchbeast.monobeast import Monobeast, Buffers from continual_rl.utils.utils import Utils class EWCTaskInfo(object): def __init__(self, model_flags, buffer_specs, entries_per_buffer, task_name): ...
from django.shortcuts import render, redirect from django.http import HttpResponse, JsonResponse, Http404 from django.contrib.auth.models import User from django.contrib.auth import login, logout import uuid import json import os import datetime from oauth2client.client import ( HttpAccessTokenRefreshError, ) fr...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import os import shutil import subprocess import argparse import numpy as np norm = np.linalg.norm inv = np.linalg.inv # read and write files def read_poscar(poscar='POSCAR', format='vasp5'): """read POSCAR""" with open(poscar, 'r') as reader: lines = r...
# Source: # https://peterroelants.github.io/posts/rnn-implementation-part01/ import matplotlib matplotlib.use('TkAgg') import sys import numpy as np import matplotlib.pyplot as plt from matplotlib import cm from matplotlib.colors import LogNorm import seaborn as sns sns.set_style('darkgrid') np.random.seed(seed=1) ...
import math import numpy as np def mulpq(p,q):#(四元数乘法)对的 没有问题 s1 = p[0] v1 = p[1:4] ###索引,多个元素,左闭右开 s2 = q[0] v2 = q[1:4] a = s1 * s2 - np.dot(v1, v2) b = s1 * v2 + s2 * v1 + np.cross(v1, v2) return np.hstack([a,b]) def muldualpq(p,q):##对偶四元数乘法 p1 = p[0:4] p2 =...
from data_multiview import Data, PadBatch import pickle import torch import torch.nn as nn import torch.nn.functional as F from torch.utils.data import DataLoader import torch.optim as optim import numpy as np from sklearn.metrics import confusion_matrix from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_s...
""" Functionality: Resample time series data with linear interplation method based on a). a fixed sampling rate, or b). a given list of sampling positions When resampling based on a given list of sampling positions, you can merge two sensors' time series data together at common sampli...
#TODO: This should be replaced with Tenjin templates similar to how Social Networks are handled ''' List of emails shown in the infobox. ''' from __future__ import with_statement import sys, wx import traceback from wx import Rect, RectS, BLACK from datetime import datetime from gui import skin from gui.textutil imp...
# -*- coding:UTF-8 -*- from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import sys import argparse import numpy as np import PIL.Image as Image import tensorflow as tf import retrain as retrain from count_ops import load_graph import average as p...
import numpy as np import tensorflow as tf from gym import spaces import argparse import sys import datetime import dateutil import dateutil.tz import uuid import ast import yaml import yaml.constructor import os import json import pprint import h5py from collections import OrderedDict from collections import namedtu...
import curses import io import math import time import urllib.request as urllib from PIL import Image class Window(object): def __init__(self, stdScreen, height, width, beginY, beginX): """ A curses window Args: stdScreen (obj) = The main curses object for the program ...
import os, re import argparse from tqdm import tqdm import torch.distributed as dist import torch.multiprocessing as mp from torch.nn.parallel import DistributedDataParallel import torch from torch.utils.data import Dataset from torch.utils.data import DataLoader, RandomSampler, SequentialSampler from fastprogress.f...
"""Tests for methods for working with dynamical systems.""" import copy import dataclasses import numpy as np import pytest import statsmodels import whynot as wn from whynot import parameter def test_baseconfig(): """Test the basic configuration object.""" @dataclasses.dataclass class Config(wn.dynami...
import copy from django.contrib.contenttypes.models import ContentType from django.utils.translation import ugettext as _ from rest_framework import serializers from structlog import get_logger from good_spot.filter import models as filter_models from good_spot.filter import serializers as filter_serializers from good...
import os import torch import numpy as np from graph.graph_utils import _sample_layer_wise, _sample_int_layer_wise, batch_bin_encode __PATH__ = os.path.abspath(os.path.dirname(__file__)) class Batch_SubtaskGraph(object): def __init__(self, args): #1. init graph param self.game_config = a...
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import os.path __all__ = ['Parser', 'IncrementalParser', 'DispatchParser'] import xml.dom as xd import xml.dom.minidom as xdm import xml.sax as xs import xml.sax.handler as xsh import xml.sax.saxutils as xss from xml.sax.saxutils import quoteattr, escape, unesc...
""" Functions used for handling and comparing multiple geometries """ import itertools import functools import numpy from phydat import ptab from phydat import bnd from automol.zmat._zmat import value_dictionary from automol.zmat._new import is_atom_closest_to_bond_atom import automol.convert.geom from automol impor...
from keras.models import Sequential, Model from keras.layers import Flatten, Dense, Lambda, Dropout, Cropping2D, Input, BatchNormalization, GlobalAveragePooling2D, Concatenate, Activation from keras.layers.convolutional import Conv2D from keras.layers.pooling import MaxPooling2D from keras.models import load_model from...
#!/usr/bin/env python3 from __future__ import print_function import sys import os from array import array import cv2 import numpy as np import time import openncc as ncc import struct import math min_score = 0.8 media_head = 'iII13I' def coordinate_is_valid(x1, y1, x2, y2): if ((x1 < 0) or (x1 >...
import json import os from dataclasses import dataclass from uuid import uuid4 import shutil import zipfile from django.conf import settings from pdp2 import pdp2 from .models import FieldDataTypeChoices, Field, Data, DatasetWatchTypeChoices from core.blockchain.projectpai.paicoin import paicoin_cli class YggUrls:...
from warnings import warn import jax.numpy as np from jax import grad from jax_optimise.list_util import list_dot, list_add_prefactor, list_conj """ CONVENTIONS: g_k = grad(f)(z_k) = (∂f/∂z*)(z_k) p_k : search direction f_k = f(z_k) alpha : step length -> z_{k+1} = z_k + alpha * p_k function on the line: phi(alpha) ...
# -*- coding: utf-8 -*- """ ReEDS Command Line Interface """ import click import logging import os from rex.utilities.loggers import init_mult from rex.utilities.cli_dtypes import STR, STRLIST, INT from rex.utilities.hpc import SLURM from rex.utilities.utilities import dict_str_load, get_class_properties from reVX.co...
import ptypes from ptypes import pstruct,parray,ptype,pbinary,pstr,dyn from .headers import IMAGE_DATA_DIRECTORY from ..headers import * class IMAGE_LOAD_CONFIG_CODE_INTEGRITY(pstruct.type): _fields_ = [ (WORD, 'Flags'), (WORD, 'Catalog'), (DWORD, 'CatalogOffset'), (DWORD, 'Reserved...
# Copyright (C) 2021 <NAME>, ETH Zürich, Information Security Group # Released under the MIT License """ Train a Catboost model. Supported data input formats are "sparse" and "LibSVM", identified by file extension. The recommended input format is pickled sparse matrix, as this is the quickest way to load data. LibSVM ...
# -*- coding: utf-8 -*- # Copyright (c) 2017 - for information on the respective copyright owner # see the NOTICE file and/or the repository https://github.com/boschresearch/statestream # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License....
# -*- coding: utf-8 -*- from aiida.engine import calcfunction bohr_to_ang = 0.52917720859 timeau_to_sec = 2.418884254E-17 from aiida import orm from aiida.engine import calcfunction from aiida_flipper.utils.utils import get_or_create_input_node import numpy as np SINGULAR_TRAJ_KEYS = ('symbols', 'atomic_species_name...
#!/usr/bin/env python import rospy from nav_msgs.msg import Odometry # to inherit te Thread class and time for delay import threading import time ## To read input (no blocking) import sys import select from plutodrone.srv import * from plutoserver.msg import floatar #custom msg type defined to get the roll ,pitch...
# -*- coding: utf-8 -*- # Copyright (C) 2014-2017 <NAME> <<EMAIL>> # Copyright (C) 2014-2017 <NAME> <<EMAIL>> # Copyright (C) 2014-2017 <NAME> <<EMAIL>> # Copyright (C) 2014-2017 <NAME> <<EMAIL>> # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public...
import copy import os import json import shutil import numpy as np import pandas as pd import skimage.io as io from scipy.ndimage import gaussian_filter from ark.utils.load_utils import load_imgs_from_tree, load_imgs_from_dir from ark.utils.io_utils import list_folders, validate_paths, list_files from ark.utils.misc...
# Copyright (c) 2020: <NAME> (<EMAIL>). # # This work is licensed under the terms of the MIT license. # For a copy, see <https://opensource.org/licenses/MIT>. from __future__ import absolute_import from __future__ import division from __future__ import print_function import functools import gin import numpy as np impo...
from ophyd.status import SubscriptionStatus from ophyd import utils as ophyd_utils from xas import xray print(__file__) class Mirror(Device): pitch = Cpt(EpicsMotor, '-Ax:P}Mtr') roll = Cpt(EpicsMotor, '-Ax:R}Mtr') xd = Cpt(EpicsMotor, '-Ax:XD}Mtr') # downstream xu = Cpt(EpicsMotor, '-Ax:XU}Mtr') ...
#!/usr/bin/env python ############################################################################ # Copyright (c) 2015-2019 Saint Petersburg State University # Copyright (c) 2011-2014 Saint Petersburg Academic University # All Rights Reserved # See file LICENSE for details. ###########################################...
from django.db import models from django.core.exceptions import ValidationError from django.conf import settings from datetime import datetime from core.encryption.encryptionFields import EncryptCharField, EncryptDateField import random import string import hashlib import json __all__ = ('Subject', 'ExternalSystem', '...
import numpy as np import pandas as pd from .fast import gen_column_filter def fillna_column(values, index, reverse=False, fillvalue=None): """ Fills the non available value sequentially with the previous available position. """ # Create the new values array new_index = np.ones(index.shape, dt...
""" Utils for scraping Instagram """ from __future__ import print_function as print3 import requests import json import numpy as np from PIL import Image from io import BytesIO import time import os import sys, select import datetime from bs4 import BeautifulSoup as bs res = 300 def saveJson(struct,file): ...
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import gc import os.path as osp import warnings from collections import deque, namedtuple from typing import Any, Dict...
# -*- coding: utf-8 -*- # Copyright 2017-2019 ControlScan, Inc. # # This file is part of Cyphon Engine. # # Cyphon Engine is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, version 3 of the License. # # Cyphon En...
#!/usr/bin/env python # -*- coding=utf-8 -*- import os import csv import sys, traceback import xml.etree.ElementTree as ET from datetime import datetime def get_optional(v): '''Get attribute text if the object is not None ''' if v is not None: return v.text else: return None def proc...
from __future__ import print_function import os import json import time import math from compas.datastructures import Mesh from compas.robots import RobotModel import compas_fab from compas_fab.backends import RosClient from compas_fab.backends.ros import JointState from compas_fab.backends.ros import Header from com...
# -*- coding: utf-8 -*- # Copyright 2020 Google LLC # # 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 o...
""" Distance Matrix """ import os import math import time import numpy as np import requests import googlemaps import utm from haversine import haversine MAX_DISTANCE_MATRIX_SIZE = 100 def pairwise_distances(X, Y=None): """Pairwise euclidean distance calculation """ if Y is None: Y = X re...
import itertools from copy import copy from enum import Enum from typing import List, Dict, Optional, cast, TypeVar from sqlalchemy.engine import Dialect from bach import SeriesAbstractMultiLevel from bach.series import Series from bach.expression import Expression, WindowFunctionExpression from bach.dataframe import...
import re import os import shutil import inspect import subprocess from pathlib import Path from miscutils.insp import isaccess import peepshow import peepshow.core.dialect as dialect import peepshow.core.trans as trans from peepshow.cmds.base import CommandsBase, command from peepshow.core import goto, probes from pee...
#! /usr/bin/env python3 # ------------------------------------------------------------------------ # CustomClean GUI # # GUI that helps user create a JSON showing a pattern of unwanted files/folders/links # that can be later applied to many directories using the main CustomClean script. # # <NAME>, January 2017 impor...
import json import os import pickle import sys import tempfile import uuid from datetime import timedelta from time import gmtime, strftime from typing import Tuple from zipfile import ZipFile import requests from dagster import ( Any, AssetMaterialization, DagsterType, EventMetadataEntry, Field, ...
"""Weight initializer.""" from __future__ import absolute_import, print_function import re import logging import warnings import json from math import sqrt import numpy as np from .base import string_types from .ndarray import NDArray, load from . import random from . import registry from . import ndarray # inherit s...
from tkinter import* import tkinter.messagebox import time import random operator = "" #### creating window and its geometry ###### root = Tk() root.geometry("1600x800+0+0") root.title("Restaurant Bill Calculator") #### creating Frame ###### top = Frame(root, width = 1600, height = 50, relief = SUNKEN) top.pack(si...
import json from pyramid.renderers import render, Response from src.sgd.frontend import config from pyramid.view import notfound_view_config from src.sgd.frontend.yeastgenome import send_message from src.sgd.tools.blast import do_blast from src.sgd.tools.patmatch import do_patmatch from src.sgd.tools.seqtools import do...
""" Various utilities for recording and embedding state in a rendered app. """ import asyncio import datetime as dt import inspect import json import logging import sys import threading import time from collections.abc import Iterator from collections import OrderedDict, defaultdict from contextlib import contextmanag...
# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use ...
# -*- coding: utf-8 -*- __license__ = \ """Copyright 2019 West University of Timisoara 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....
# Copyright (c) 2020 PaddlePaddle 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 appli...
# # Copyright (C) 2016 UAVCAN Development Team <uavcan.org> # # This software is distributed under the terms of the MIT License. # # Author: <NAME> <<EMAIL>> # import datetime import time import os from functools import partial import pyuavcan_v0 from pyuavcan_v0.driver import CANFrame from PyQt5.QtWidgets import QM...
""" Parametrization support for test cases. """ import collections import itertools import re import warnings import six from testplan.common.utils.convert import make_tuple from testplan.common.utils import callable as callable_utils from testplan.testing import tagging # Although any string will be processed as no...
import argparse import logging import os import re import subprocess import sys from collections import OrderedDict try: from ..manifest import manifest from ..manifest.utils import git as get_git_cmd except ValueError: # if we're not within the tools package, the above is an import from above # the t...
"""Files module.""" #################################################################################################### # IMPORTS ################################################################################ IMPORTS # #################################################################################################...
# Part of Spatial Math Toolbox for Python # Copyright (c) 2000 <NAME> # MIT Licence, see details in top-level file: LICENCE """ Utility functions for testing and converting passed arguments. Used in all spatialmath functions and classes to provides for flexibility in argument types that can be passed. """ # pylint...
""" Measure influence values vs. confidence/variance and/or error. """ import os import sys import time import tqdm import hashlib import argparse import resource from datetime import datetime import numpy as np import seaborn as sns import matplotlib.pyplot as plt from sklearn.base import clone from sklearn.metrics i...
from functools import reduce import operator import warnings from haystack import connection_router, connections from haystack.backends import SQ from haystack.constants import DEFAULT_OPERATOR, ITERATOR_LOAD_PER_QUERY from haystack.exceptions import NotHandled from haystack.inputs import AutoQuery, Raw from haystack....
# coding: utf-8 # In[1]: import numpy as np import pandas as pd #import pyodbc import pickle import time import itertools from joblib import Parallel, delayed from random import randint import matplotlib matplotlib.rcParams.update({'font.size': 17.5}) import math import matplotlib.pyplot as plt #get_ipython().magic(...
""" Data preproc functions: adjust_to_see: adjust image to better visualize (rotate and transpose) augmentation: apply variations to a list of images normalization: apply normalization and variations on images (if required) preproc: main function to the preprocess. Make the image: il...
"""make btrfs backups""" # TODO: Parse SI units for --bwlimit (Current code assumes number is in KB) # TODO: VT100 progress bar # TODO: Remove duplicate code import argparse import collections import logging import os import os.path import re import string import subprocess import sys import tempfile import time import...
import logging from typing import List, Any import numpy as np import pandas as pd import pyskindose.constants as c from .db_connect import db_connect from .phantom_class import Phantom logger = logging.getLogger(__name__) def calculate_field_size(field_size_mode, data_parsed, data_norm): """Calculate X-ray fie...
# -*- coding: utf-8 -*- """ Created on Wed Mar 28 15:34:18 2012 Author: <NAME> """ from statsmodels.compat.python import BytesIO, asbytes, range import warnings try: import matplotlib.pyplot as plt has_maplotlib = True except ImportError: has_maplotlib = False import numpy as np import pandas as pd fro...
r""" losses 模块定义了 fastNLP 中所需的各种损失函数,一般做为 :class:`~fastNLP.Trainer` 的参数使用。 """ __all__ = [ "LossBase", "LossFunc", "LossInForward", "CrossEntropyLoss", "BCELoss", "BCEWithLogits", "L1Loss", "NLLLoss", "MSELoss", "CMRC2018Loss" ] import inspect from collections impor...
from numpy.random import seed # seed(333) import tensorflow as tf # tf.random.set_seed(333) from tensorflow.keras import optimizers opt = optimizers.Adadelta(lr=0.0001, rho=0.9, epsilon=1e-07, name="Adadelta") #opt = optimizers.Adam(lr=0.00001, name="Adam") #opt = optimizers.RMSprop(lr=0.00003, rho=0.9, epsilon=1...
# coding=utf-8 # Copyright 2020 The Google Research 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 applicab...
# -*- coding: UTF-8 -*- from enemyBehavior import enemyControl from coreBehavior import coreControl from Box2D import b2World, b2PolygonShape import pygame, sys, math, random from pygame.locals import * from picToMap import * block_size = 10 gravity = 0 # set up pygame-box2d constants bullet_size = int(block_size /...
import copy import math import sys from io import StringIO from theano.configdefaults import config from theano.gof import opt from theano.misc.ordered_set import OrderedSet from theano.utils import DefaultOrderedDict class DB: def __hash__(self): if not hasattr(self, "_optimizer_idx"): self....
# Copyright 2018 Google LLC. 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...
from __future__ import division, unicode_literals import os import hashlib import logging from collections import defaultdict from .bencode import bencode, bdecode from .humanize import humanize_bytes from .utils import is_unsplitable, get_root_of_unsplitable, Pieces logger = logging.getLogger('autotorrent') class...
#!/usr/bin/env python # # esp-idf serial output monitor tool. Does some helpful things: # - Looks up hex addresses in ELF file with addr2line # - Reset ESP32 via serial RTS line (Ctrl-T Ctrl-R) # - Run "make flash" (Ctrl-T Ctrl-F) # - Run "make app-flash" (Ctrl-T Ctrl-A) # - If gdbstub output is detected, gdb is automa...
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # MIT License. See license.txt from __future__ import unicode_literals """build query for doclistview and return results""" import frappe, json from six.moves import range import frappe.permissions from frappe.model.db_query import DatabaseQuery fro...
from __future__ import print_function import os import sys import time import copy import base64 import json import string import time import random import hashlib import subprocess import requests from requests_toolbelt import MultipartEncoder try: # python3 from urllib.parse import urlparse, urlencode, parse_qs...
""" RetinaNet / EfficientDet Anchor Gen Adapted for PyTorch from Tensorflow impl at https://github.com/google/automl/blob/6f6694cec1a48cdb33d5d1551a2d5db8ad227798/efficientdet/anchors.py Hacked together by <NAME>, original copyright below """ # Copyright 2020 Google Research. All Rights Reserved. # # Licensed und...
from __future__ import division from cctbx.array_family import flex import math, sys from mmtbx.utils import rotatable_bonds import mmtbx.geometry_restraints.torsion_restraints.utils as torsion_utils from scitbx.matrix import rotate_point_around_axis import mmtbx.monomer_library.server from mmtbx.validation import rota...