text
stringlengths
3.07k
12.6k
import json import os from pathlib import Path from django.contrib.gis.geos import Point from django.contrib.gis.geos.polygon import Polygon import djclick as click from jsonschema import validate from rest_framework.serializers import ValidationError from atlascope.core.models import ( Dataset, DatasetEmbedd...
import logging from typing import Optional import json from fastapi import APIRouter, Depends, HTTPException from pydantic import BaseModel from sqlalchemy.ext.asyncio import AsyncSession from api.endpoints.dependencies.db import get_db from api.endpoints.dependencies.tenant_security import get_from_context from api....
''' Inspired from https://github.com/holyseven/TransferLearningClassification https://keras.io/guides/customizing_what_happens_in_fit/ https://towardsdatascience.com/tensorflow-2-2-and-a-custom-training-logic-16fa72934ac3 # https://stackoverflow.com/a/62440411 class Model: github.com/tensorflow/tensorflow/blob/582c8d2...
from SublimeLinter.lint import Linter from SublimeLinter.lint.linter import PermanentError from threading import Lock import os import sublime import logging import requests import time import subprocess logger = logging.getLogger('SublimeLinter.plugin.checkstyle') lock = Lock() CURRENT_LATEST_CS_VERSION = None DOWN...
from django.core.exceptions import ValidationError from formation.render_base import Renderable class Unset: """A class that allows us to differentiate between None (or null) and a value that has not been set. """ def __bool__(self): return False UNSET = Unset() DEFAULT_CONTEXT_KEY = "...
""" Copyright (c) 2020 Aiven Ltd See LICENSE for details Test that RohmuStorage works as advertised. TBD: Test with something else than local files? """ from astacus.common import exceptions from astacus.common.cachingjsonstorage import CachingJsonStorage from astacus.common.rohmustorage import RohmuConfig, RohmuSt...
""" VDF (de)serialization Copyright (c) 2010-2012, <NAME> <<EMAIL>> Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND TH...
import time as ttime import subprocess import asyncio import pytest from bluesky_queueserver.manager.qserver_cli import CliClient @pytest.fixture def re_manager(): """ Start RE Manager as a subprocess. Tests will communicate with RE Manager via ZeroMQ. """ p = subprocess.Popen(["start-re-manager"], u...
import click import io import logging import os import random import re import sys import yaml import zipfile from oslo_concurrency import processutils logging.basicConfig(level=logging.INFO) LOG = logging.getLogger(__name__) LOG.setLevel(logging.INFO) # Read simple command blocks from stdin and execute them. Comma...
import datetime import random from collections import Counter from typing import List, Union from logzero import logger as log from const import MONTHS from core import Context from core.dialogmanager import StopPropagation from core.planningagent import IPlanningAgent from core.routing import Router from corpus.resp...
""" Test the func_inspect module. """ # Author: <NAME> <gael dot varoquaux at normalesup dot org> # Copyright (c) 2009 <NAME> # License: BSD Style, 3 clauses. import os import shutil import nose import tempfile import functools from ..func_inspect import filter_args, get_func_name, get_func_code, \ _clean_wi...
import numpy as np import tensorflow import datetime # Load the TensorBoard notebook extension import tensorboard import glob import os import cv2 from tensorflow.keras.layers import Conv2D, Add, Input, Dense, Dropout, Flatten, GlobalAveragePooling2D, DepthwiseConv2D, BatchNormalization, LeakyReLU, MaxPooling2D from te...
#!/usr/bin/env python3 # Copyright 2021 Battelle Energy Alliance, LLC # Python std library imports import argparse import os import pkg_resources import pickle import sys from math import ceil # package imports from navv import utilities from navv import spreadsheet_tools from navv import _version DATA_PATH = pkg_r...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import json from pamogk import config from pamogk.data_processor import node2vec_processor from pamogk.gene_mapper import uniprot_mapper from pamogk.kernels import center_product_kernel from pamogk.kernels import lmkkmeans_train from pamogk.lib.sutils import * from pamogk...
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
# This is a sample commands.py. You can add your own commands here. # # Please refer to commands_full.py for all the default commands and a complete # documentation. Do NOT add them all here, or you may end up with defunct # commands when upgrading ranger. # A simple command for demonstration purposes follows. # ---...
from flask import Flask, request, send_file from io import BytesIO from staticmap import CircleMarker, IconMarker, Line, Polygon, StaticMap import re app = Flask(__name__) app.config.from_pyfile('config.py') @app.route('/') def create_map(): """Main method where map is put together""" # Holds the amount of p...
# HTTP-Triggered Azure Function, implemented in Python, for CosmosDB # performance testing. # <NAME>, Microsoft, October 2021 import json import logging import os import time from datetime import datetime import azure.functions as func import azure.cosmos.cosmos_client as cosmos_client import azure.co...
""" Allow for easy navigation in your files by toggling on/off anchorpoints, and jumping back and forth between them. """ from __future__ import annotations import time import tkinter from porcupine import get_tab_manager, menubar, settings, tabs from porcupine.plugins.linenumbers import LineNumbers # Dependent on c...
import subprocess from tkinter import * import hashlib def getWifiPasswords(): global wifis, passList data = subprocess.check_output(['netsh', 'wlan', 'show', 'profiles']).decode('utf-8').split('\n') wifis = sorted([line.split(':')[1][1:-1] for line in data if "All User Profile" in line], key=str.lower) ...
# Author: <NAME> # October 2018 import requests import base64 def get_org_info(org_name, token): if org_name == "": print("No organization name passed in.") return if token == "": print("No token passed in.") return # Define starting parameters url = "https://api.git...
from scipy.stats import binom, rv_discrete, truncnorm import numpy as np from math import ceil, floor import torch.nn.functional as F import torch def randomSample(iObs, siTran, irTran, initCond, theta, T, D, B): N = np.sum(initCond) H = len(irTran) PA = D*theta[3]/T mu = theta[2] alpha =...
"""\ Augment the "bgen" package with definitions that are useful on the Apple Macintosh. Intended usage is "from macsupport import *" -- this implies all bgen's goodies. """ # Import everything from bgen (for ourselves as well as for re-export) from bgen import * # Simple types Boolean = Type("Boolean", "b") Signe...
# This code was contributed by Christof, DJ4CM. Many Thanks!! import threading import time import telnetlib import sys import quisk_conf_defaults as conf class DxEntry(): def __init__(self): self.info = [] def getFreq(self): return self.freq def getDX(self): return self.dx def getSpo...
# -*- coding: utf-8 -*- import fnmatch import os import sys from six.moves.queue import Queue from qcloud_cos import CosServiceError if sys.version > '3': from coscmd.cos_comm import * else: from cos_comm import * logger = logging.getLogger("coscmd") def is_include_file(path, rules): for rule in rules: ...
# Copyright (c) 2014 The Johns Hopkins University/Applied Physics Laboratory # 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/LICEN...
""" Python script to collect the VPlex logs """ from __future__ import (absolute_import, division, print_function) import os import subprocess import platform import datetime import sys import re import urllib3 __metaclass__ = type urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) # Check if Vplex...
#!/usr/bin/python3 import os import numpy as np import pylab as P import sys import copy from os import path from scipy.optimize import leastsq from FELion_normline import norm_line_felix from FELion_normline import felix_binning from matplotlib.ticker import MultipleLocator, FormatStrFormatter, NullFormatter, NullLoc...
# -*- coding: utf-8 -*- from django.urls import reverse from django.http import HttpResponseRedirect, HttpResponse from django.shortcuts import get_object_or_404 from django.template import loader from django.forms import inlineformset_factory from django.db.models import Count from Instanssi.common.http import Http4...
import torch import torch.optim import matplotlib.pyplot as plt import draw import voxel from utils import argmin, argmax, partial, map_range from models import LossType, SphereModel, AxisAlignedCuboid, CuboidModel, CapsuleModel import math from PSOptimizer import ParticleSwarmOptimizer class NumericalInstabilityExcep...
###################### # OPTPARSE FUNCTIONS # ###################### import optparse def single_input(parser): """ Function that defines options and help for a single input file. """ parser.add_option("-i", "--input", dest = "input_file", help = "Input file name.") parser.add_option("--input_type"...
#!/usr/bin/env python # # Copyright (C) 2019 The Android Open Source Project # # 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 req...
class double_buffer: def __init__(self, cls): self.__name__ = cls.__name__ self.__doc__ = cls.__doc__ try: self._transition_hook = getattr(cls, 'on_transition') except AttributeError: self._transition_hook = lambda self: None try: self._c...
import os import shutil import random import string from subprocess import call, Popen, PIPE, STDOUT import pytest # FIXTURES BASE_DIR = None session_testdir = {} session_project = {} def get_base_dir(): global BASE_DIR if not BASE_DIR: BASE_DIR = os.getcwd() return BASE_DIR @pytest.fixtur...
import math import torch import torch.nn.functional as F from torch import nn from typing import List from timm.models.layers import trunc_normal_ from .grained_sample import ( grained_sample_compress, grained_sample_decompress, grained_sample_index_to_patch, grained_sample_compress_dense, grained...
import pdb import pprint from collections import OrderedDict import numpy as np import scipy as sp from scipy import sparse from sklearn import svm def bag_of_words_frm_str(string,delim=" "): bag_of_words_str = {} for word in string.strip().split(delim): try: bag_of_words_str[word] += 1 ...
"""meta.py Represent persistence structures which allow the usage of Beaker caching with SQLAlchemy. The three new concepts introduced here are: * CachingQuery - a Query subclass that caches and retrieves results in/from Beaker. * FromCache - a query option that establishes caching parameters on a Query * R...
#!/usr/bin/env python """ Python code for performing calculations related to Daf Yomi Supports Python 2 and Python 3 Copyright (c) 2014, <NAME> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redis...
import os import json import copy import xml.etree.ElementTree as etree from collections import OrderedDict num = 0 help_list = [] def parse_data(root, all_list): """ 由于用的是单列表的方式, 层级关系用一个变量即可控制, 若以字典的形式保存,则会出现同级多层列表,无法使用这种方式来控制 递归的实现,则是建立在当前的父问题的角度考虑,假设子问题已经实现,所以该法会在子问题结束时返回, 即[[...[key, value]...
"""IMAP migration tests.""" import os import shutil import tempfile from unittest import mock from six.moves import configparser from django.core.management import call_command from django.urls import reverse from modoboa.admin import factories as admin_factories from modoboa.admin import models as admin_models fro...
import posixpath from contextlib import contextmanager from functools import partial from urllib.parse import urlparse import pytest from dvc_ssh.tests.cloud import TEST_SSH_KEY_PATH, TEST_SSH_USER from dvc.fs.ssh import SSHFileSystem from dvc.repo.experiments.base import EXEC_HEAD, EXEC_MERGE from dvc.repo.experimen...
import numpy as np import json import pathlib def readJsonLog(*out_files, extract='acc1'): train_log = [] for out_file in out_files: with open(out_file) as fn: train_log += json.load(fn) dataset_list = [k for k in train_log[0].keys() if not k == "epoch"] pro...
import uuid from pyramid.httpexceptions import HTTPFound from pyramid.security import NO_PERMISSION_REQUIRED import requests from ..api import ( AuthenticationComplete, AuthenticationDenied, register_provider, ) from ..exceptions import CSRFError from ..exceptions import ThirdPartyFailure from ..settings...
import pandas as pd import numpy as np import os import json import typing as tp from brownie import network, Contract from datetime import datetime from scipy.stats import norm from influxdb_client import InfluxDBClient, Point, WritePrecision from influxdb_client.client.write_api import SYNCHRONOUS, PointSettings ...
import base64 import json import logging import sys import traceback from django.contrib.auth.decorators import login_required from django.http import JsonResponse from django.shortcuts import render from cpovc_forms.forms import OVCF1AForm, CasePlanTemplate from cpovc_forms.functions import create_fields, create_for...
import MatterSim import os import json from collections import namedtuple import numpy as np from tqdm import tqdm Location = namedtuple( "Location", ["vp_id", "abs_heading", "abs_elevation", "view_index", "rel_heading", "rel_elevation", "forward"] ) rad30 = np.deg2rad(30) skybox_dir = '/root/mount/AVAST_R2R/...
"""Perform streaming post-alignment preparation -- de-duplication and sorting. Centralizes a pipelined approach to generating sorted, de-duplicated BAM output from sequencer results. sambamba: https://github.com/lomereiter/sambamba samblaster: http://arxiv.org/pdf/1403.7486v1.pdf biobambam bammarkduplicates: http://a...
#!/usr/bin/python # -*- coding: ascii -*- from sys import * intro = """ ==================================================================================================================== ### OTPython2 v. 1.4 ASCII ### -- A fast and lightweight Gilbert Vernam's One Time Pad cipher implementation in Python 2 -- Code...
import pandas from flask import Flask, Response, redirect, url_for, request, render_template, send_file, send_from_directory from flask_ngrok import run_with_ngrok from connect_sql_db import build_engine from pprint import pprint import os import json import time from ML_Classifier import nueral_network_classifier eng...
import random from lxml import etree from typing import List, Tuple from PIL import ImageDraw from urllib.parse import unquote from nonebot.log import logger from .base_handle import BaseHandle, BaseData from ..config import draw_config from ..util import remove_prohibited_str, cn2py, load_font from ..build_image impo...
import json import keras import numpy as np import keras.backend as K from data.vocab import TextEncoder from transformer.embedding import Embedding from keras.layers import Conv1D, Dropout, Add, Input from transformer.layers import MultiHeadAttention, Gelu, LayerNormalization class MultiHeadSelfAttention: def __...
# ================================================================ # MIT License # Copyright (c) 2021 edwardyehuang (https://github.com/edwardyehuang) # ================================================================ # This code is motified from offical TensorFlow repo, may be deleted in future (since a bug is fixed)...
#!/usr/bin/env python """ Copyright 2017-2019 Fizyr (https://fizyr.com) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable l...
import numpy as np import pytest import kaczmarz @pytest.fixture() def DummyStrategy(): class _DummyStrategy(kaczmarz.Base): def _select_row_index(self, xk): return 0 return _DummyStrategy @pytest.fixture() def NonStrategy(): class _NonStrategy(kaczmarz.Base): pass ret...
from flask import Blueprint, Response, jsonify, request from chaos_genius.controllers.kpi_controller import get_kpi_data_from_id from chaos_genius.core.rca.rca_utils.api_utils import ( kpi_line_data, rca_analysis, rca_hierarchical_data_all_dims, ) from chaos_genius.utils.utils import iter_csv from chaos_ge...
import sys import argparse import subprocess import shutil import os import glob import time import xml.etree.ElementTree as ET # Version 2.0.0 # Published under MIT license. Copyright (c) 2020 sunfl0w def main(): build(sys.argv) def build(argv): print("Starting CPPBuildAid") startTime = time.time_ns(...
# -*- coding: utf-8 -*- """ @contact: <EMAIL> @time: 2018/7/21 下午3:15 """ # import json import requests import os from multiprocessing.pool import ThreadPool path = os.path.dirname(__file__) url = "https://leetcode-cn.com/graphql" pool = ThreadPool(10) headers = { 'content-type': "application/json", 'cook...
from collections import OrderedDict from pathlib import Path import tensorflow as tf import numpy as np from tqdm import tqdm from .data import create_mnist_dataset from .model import mnist_model # for reproducibility SEED = 42 def model_fn(features, labels, mode, params): """ Model function for the Estima...
#! /usr/bin/env python from __future__ import print_function import argparse import subprocess as sp import os import sys import shutil import random import time import re def mp_blat(reference_file, fasta_file, output_file, num_of_process=1, tmp_path=".", blat_bin="blat", blat_opt=""): blat_opt = re.findall("(...
#!/usr/bin/python3 import os import sys import time import logging import logging.handlers from os.path import expanduser from optparse import OptionParser from src import MangaBase from src.plugins import MangaFoxPlugin, MangaParkPlugin APP_NAME = 'MangaLoader' APP_VERSION = 'v0.2' # ----------------------------...
""" Implement one-pixel attack, adapted from https://github.com/Hyperparticle/one-pixel-attack-keras/blob/master/1_one-pixel-attack-cifar10.ipynb @author: <NAME> (y(dot)meng201011(at)gmail(dot)com) """ import numpy as np from scipy.optimize import differential_evolution np_dtype = np.dtype('float32') class OnePixel(...
"""Context-free recognizers for graphs""" from typing import Set, Tuple import networkx as nx from pyformlang.cfg import CFG from scipy import sparse from project import ( cfg_to_wcnf, ecfg_to_rsm, cfg_to_ecfg, FABooleanMatricesDok, graph_to_nfa, ) __all__ = ["hellings", "matrix_based", "tensor_b...
import datetime import itertools from django.conf import settings from django.db import connection, models from django.db.models.expressions import RawSQL from django.utils import timezone from django.utils.translation import gettext_lazy as _ from core import dictfetchall, mean class DigitalTakeupManager(models.Ma...
import os import sys import logging from collections import OrderedDict, namedtuple from typing import Dict, List, Tuple from entrypoints import EntryPoint TASKS_DIRECTORY = "firex_tasks_directory" logger = logging.getLogger(__name__) _loaded_firex_bundles = {} class PkgVersionInfo(namedtuple('PkgVersionInfo', ('...
# coding=utf-8 import pymysql import pandas as pd import math import re from time import time import os import json # 连接数据库 config = {'host': 'localhost', 'port': 3306, 'user': 'root', 'passwd': '<PASSWORD>', 'charset': 'utf8mb4', 'local_infile': 1 } conn = p...
""" TEST_PIX2PIX_TRAINER Unit tests for Pix2PixTrainer module <NAME> 2019 """ import os import torch import torchvision from torchvision import transforms # units under test # I suppose that this unit test can almost serve as a model test as well from lernomatic.models.gan.cycle_gan import resnet_gen from lernomatic....
import numpy as np import matplotlib.pyplot as plt from matplotlib.image import imread from mpl_toolkits.mplot3d import Axes3D # 与门 权重偏置 AND_W = np.array([0.5, 0.5]) AND_B = -0.7 # 与非门 权重偏置 NAND_W = np.array([-0.5, -0.5]) NAND_B = 0.7 # 或门 权重偏置 OR_W = np.array([0.5, 0.5]) OR_B = -0.3 # 感知机 def Perceptron(x): re...
from collections import namedtuple from unittest import main, TestCase from midi import ControlChange, ProgramChange from modes import JackRoute, MidiRoute, MidiState, RouteImpl, Routing, StateVec class FakeSequencer(object): class Port(object): def __init__(self, name): self.name = name ...
from __future__ import print_function, division import math from math import cos, sin, pi from parameter import * # Lalwani 2009 # ============== other control parameter=============== #different way to cal def get_friction_heat_source(): angle_F = math.atan2(F_thrush, F_cutting)*180/math.pi # atan2(y, x) an...
''' module for reading in different BGS spectral simulations. Currently the module includes: * `simulated_GAMA_source_spectra`: read simulated GAMA-matched fiber-magnitude scaled BGS source spectra author: <NAME> ''' import os import h5py import numpy as np # --- feasibgs --- from . import util as UT...
from flask import Blueprint, render_template, request, redirect, session, jsonify, flash, url_for, abort from functools import wraps from flask import session import hashlib import json from datetime import datetime #custom imports from .models import Users, Shortlist from admin.models import Jobs user_object = Users(...
import os from enum import IntEnum from pathlib import Path import pygame from models.mcuSensorModel import UPSStatus from utils.airTime import AirTime from utils.anamolyDetection import Anomaly, check_for_anomalies from utils.internationalization import Internationalization from utils.config import ConfigValues ROO...
# Python 3 script for parsing data from json and uploading the data to a NextCloud deck application via API import json import requests import os from dateutil import parser # Configuration from config.json with open('config.json') as f: data = json.load(f) apiUser = data['user'] apiPword = data['pas...
import os from collections import Counter import numpy as np import tensorflow as tf flags = tf.compat.v1.app.flags flags.DEFINE_string('train_file', 'oliver.txt', 'text file to train LSTM') flags.DEFINE_integer('seq_size', 32, 'sequence length') flags.DEFINE_integer('batch_size', 16, 'batch size') flags.DEFINE_inte...
""" Demo command line for chevah-keycert. Usage: * ssh-gen-key - Generate key, various formats, with or without password. * ssh-load-key - Load key, various formats, with or without password. Exit code: * 1 - Expected error raised by keycert * 2 - Unexpected error raised by keycert * 3 - Error raised by demo code i...
import datetime import numbers import django from django.db.models.fields import FieldDoesNotExist from django.utils import tree from django.core.exceptions import FieldError try: from django.db.models.sql.constants import LOOKUP_SEP except: from django.db.models.constants import LOOKUP_SEP class HStoreConstr...
import time import subprocess import os import sdi_utils.gensolution as gs import sdi_utils.set_logging as slog import sdi_utils.textfield_parser as tfp import sdi_utils.tprogress as tp try: api except NameError: class api: class Message: def __init__(self, body=None, attributes=""): ...
#!/usr/bin/env python # -*- coding: utf-8 -*- __all__ = ['remove_duplicate_namespaces_declaration', 'remove_useless_namespaces_decalaration', 'fetch_child', 'fetch_children', 'element_children', 'lookup'] import re import bridge from bridge.common import XMLNS_NS def fetch_child(element, child...
import django from django import template from django.template.base import Node, NodeList, TemplateSyntaxError, token_kwargs from django.template.library import parse_bits from django.utils.safestring import mark_safe from django_components.component import registry # Django < 2.1 compatibility try: from django.t...
# Copyright 2019 Alibaba Cloud 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 la...
import boto3 from botocore.exceptions import ClientError from boto3.dynamodb.conditions import Key import json import os import logging import datetime from dateutil import tz from pprint import pprint from msrestazure.azure_active_directory import ServicePrincipalCredentials from azure.mgmt.compute import ComputeMana...
import numpy as np from flopter.core import constants as c from flopter.core.constants import EPSILON_0, ELEM_CHARGE, ELECTRON_MASS, DEUTERIUM_MASS from flopter.core.ivdata import IVData from flopter.core.normalise import Converter from flopter.spice.inputparser import InputParser class Denormaliser(Converter): "...
import mini lcd = mini.lcd() key = mini.key() sys = mini.sys() colors = [0x404040, 0x55ff55, 0xff5555, 0x5555ff] block_square = [0b0000011001100000] block_line = [0b0000000011110000, 0b0010001000100010] block_l = [0b0000010001000110, 0b00000001011100000, 0b0000011000100010, 0b0000111010000000] block_l2 = [0b0100010001...
import datetime import os from os import listdir from os.path import expanduser from os.path import isfile, join, splitext import yaml from .keygen import autYr, makeunique from .cleanup import clean_all from .IO import serializer class library: def __init__(self, cfile=None): """ Creates a librar...
# -*- coding: utf-8 -*- # # This file is part of Karesansui. # # Copyright (C) 2009-2012 HDE, Inc. # # 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 lim...
from hypothesis import given from hypothesis.strategies import integers from enginelib.level.reload import Loader, reloadable_class import sys import os # sometimes the path doesnt contain the current directory, so importing the locally created files breaks sys.path.append(os.getcwd()) TEXT = '''import enginelib.le...
import numpy as np import tensorflow as tf def conv(layer_name, x, out_channels, kernel_size=[3,3], stride=[1,1,1,1], is_pretrain=True): ''' 定义卷积层 :param layer_name: 卷积层名称 :param x: 输入 :param out_channels: 输出通道 :param kernel_size: 卷积核大小 :param stride: 步长 :param is_pretrain: :return:...
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import os import functools from torch.autograd import Variable from util.image_pool import ImagePool from .base_model import BaseModel from . import networks im...
from collections import Counter from typing import List, Dict, Tuple import numpy as np from sklearn.utils.linear_assignment_ import linear_assignment class PerDocumentScorer: def __init__(self, document_id_by_markable_id: Dict[int, int], metric: str) -> None: self.document_id_by_markable_id = document_i...
import ui import console import objc_util class TransferManagementView (object): def __init__(self, install_action, refresh_main_view, delete_action, refresh_transfer_action, theme_manager, transfer_manager, tv): self.data = refresh_transfer_action() self.delete_action = delete_action self.install_action = insta...
import warnings warnings.filterwarnings("ignore", category=FutureWarning) from flask import abort, render_template, Flask import logging import db APP = Flask(__name__) # Start page @APP.route('/') def index(): stats = {} x = db.execute('SELECT COUNT(*) AS products FROM PRODUTO').fetchone() stats.update(x...
# coding: utf8 from __future__ import unicode_literals, print_function, division from clldutils.dsv import UnicodeReader from pylexibank.util import xls2csv from pylexibank.dataset import CldfDataset, valid_Value as vv_base from pylexibank.lingpy_util import clean_string, iter_alignments, getEvoBibAsSource import lin...
import time import hikari import lightbulb import platform import asyncio import logging import os import sys from functools import wraps from pathlib import Path from watchgod import Change, awatch class Watcher : def __init__(self, bot: lightbulb.BotApp, path: str = "plugi...
# Author: <NAME> import io import os import re import nltk import spacy import pandas as pd import docx2txt from . import constants as cs from spacy.matcher import Matcher from pdfminer.converter import TextConverter from pdfminer.pdfinterp import PDFPageInterpreter from pdfminer.pdfinterp import PDFResourceManager fr...
# A python-based importer for iolite 4 starts with some metadata #/ Type: Importer #/ Name: NuPlasma .run importer #/ Authors: <NAME> and <NAME> #/ Description: An importer for loading Nu Plasma .run files #/ References: None #/ Version: 1.0 #/ Contact: <EMAIL> import time import numpy as np import pandas as pd import...
from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import os.path as osp import sys import json import numpy as np import h5py import time from pprint import pprint import argparse # model import _init_paths from layers.model import Actor from layers...
# -*- coding: utf-8 -*- import tkinter as tk from tkinter import ttk class Rekenmachine(tk.Frame): """Deze class bouwt een Rekenmachine. Het venster wordt geïnitialiseerd.""" def __init__(self, master=None): tk.Frame.__init__(self, master) self.grid() self.createWidgets() # Zor...
#! /usr/bin/python3 # Copyright (c) <NAME> July 2018 # Copyright (c) Government of Canada July 2018 import ogr import os def getFieldInfoFromIndex(index): # This function returns a dictionary containing as key the # fields and as values the max lenght contaign by the field ## The first step is to define a recurs...
# metadata.py (flowsa) # !/usr/bin/env python3 # coding=utf-8 """ Functions for creating and loading metadata files for FlowByActivity (FBA) and FlowBySector (FBS) datasets """ import pandas as pd from esupy.processed_data_mgmt import FileMeta, write_metadata_to_file, read_source_metadata from flowsa.common import pat...
import datetime import logging import os from datetime import datetime import pandas as pd import quandl from pandas import DataFrame from config import QUANDL_KEY quandl.ApiConfig.api_key = QUANDL_KEY DATA_FOLDER = 'crypto_data' EXCHANGES = ['COINBASE', 'BITSTAMP', 'KRAKEN', 'OKCOIN'] ALTCOIN_TICKERS = ['ETH', '...