text
stringlengths
3.07k
22.1k
from io import BytesIO from django.core import mail from django.http import Http404, HttpResponse, HttpResponseRedirect from django.utils.encoding import smart_str from django.views.generic.base import TemplateView, View try: from django.core.urlresolvers import reverse except ImportError: from django.urls im...
from typing import Dict, List, Optional from copy import deepcopy import pytz from datetime import datetime, timedelta try: import MetaTrader5 as Mt5 except: pass import pandas as pd import yaml from pathlib import Path from termcolor import colored from mt5_connector.account import Account __a...
""" Ported to pytorch thanks to [tstandley](https://github.com/tstandley/Xception-PyTorch) @author: tstandley Adapted by cadene Creates an Xception Model as defined in: <NAME> Xception: Deep Learning with Depthwise Separable Convolutions https://arxiv.org/pdf/1610.02357.pdf This weights ported from the Keras imple...
""" Persist changes to the canonical record. Provides a :class:`.CanonicalStore` that stores resources in S3, using :mod:`.serialize.record` to serialize and deserialize resources. """ import gzip import io import logging import os from base64 import urlsafe_b64decode, urlsafe_b64encode from binascii import hexlify, u...
import os import numpy as np from numpy.typing import NDArray from typing import Any, Dict, Tuple, Optional from fibsem_tools.io.zarr import lock_array from fibsem_tools.metadata.cosem import COSEMGroupMetadata, SpatialTransform from fibsem_tools.metadata.neuroglancer import NeuroglancerN5GroupMetadata from xarray impo...
# user input module. Can use scripted input for testing. import time import Drawing import Util from datetime import timedelta, datetime _input_queue = [] _query_queue = [] USE_CONSOLE_MODE = False #####################################################################################################################...
#!/usr/bin/env python3 import argparse import logging import re import sys from ensembl_prodinf.rest_client import RestClient class DbCopyRestClient(RestClient): """ Client for submitting database copy jobs to the db copy REST API """ jobs = '{}' jobs_id = '{}/{}' def submit_job(self, src_h...
# Copyright 2021 Adobe # All Rights Reserved. # NOTICE: Adobe permits you to use, modify, and distribute this file in # accordance with the terms of the Adobe license agreement accompanying # it. """ automatically extract the docs from original backend libraries """ # beacon_aug from . import DEFAULT_LIBRARIES, load...
# $Id$ # # Copyright (C) 2008 <NAME> # # @@ All Rights Reserved @@ # This file is part of the RDKit. # The contents are covered by the terms of the BSD license # which is included in the file license.txt, found at the root # of the RDKit source tree. # from aggdraw import Brush, Pen #@UnresolvedImport #pylint: ...
import logging import uuid import requests import collections import json import time from pathlib import Path from typing import Dict, Any, Optional, Callable import sentry_sdk from sentry_sdk.integrations.logging import LoggingIntegration, ignore_logger import logzio.handler from logdna import LogDNAHandler # sentr...
import pickle from hashlib import md5 from datetime import datetime from elasticsearch_dsl import document, field, Mapping from elasticsearch_dsl.exceptions import ValidationException from pytest import raises class MyInner(field.InnerObjectWrapper): pass class MyDoc(document.DocType): title = field.String(...
from __future__ import print_function import argparse from math import log10 import os import torch import torch.nn as nn import torch.optim as optim from torch.autograd import Variable from torch.utils.data import DataLoader from torchvision import models import torch.backends.cudnn as cudnn from dbpn_v1 import Net a...
#!/usr/bin/env python3 """ High level functions/classes for running the Python Currency Converter CLI Official Repo: https://github.com/Privex/python-curconv License: X11 / MIT Copyright:: +===================================================+ | © 2021 Privex Inc. | | ...
""" Created on Apr 30, 2014 @author: sstober """ import os import logging log = logging.getLogger(__name__) import numpy as np from pylearn2.utils import serial from deepthought3.pylearn2ext.util import process_dataset, aggregate_classification from deepthought3.util.yaml_util import load_yaml_file from pylearn2.u...
import tkinter as tk import rendermath as rm import time from typing import List from math import cos, tan, sin from copy import copy, deepcopy # ================= Note to the Reader ============================= # # First and formost... Hi there! I dont know what you would # be doing reading this. Just wanted to cla...
from django.http import JsonResponse from django.db import transaction from django.shortcuts import render, redirect from django.urls import reverse from django.conf import settings from django.views.generic import View from django_redis import get_redis_connection from apps.user.models import Address from apps.goods.m...
import pygame import random import choicemenu import sys pygame.init() SCREEN_H = 560 SCREEN_W = 1000 SCREEN = pygame.display.set_mode((SCREEN_W, SCREEN_H)) music = pygame.mixer.Sound('Christmas Village.mp3') BG01 = pygame.image.load("IMG/runbg.png") BG02 = BG01.copy() clock = pygame.time.Clock() class MeltingSnow...
import torch import torch.nn as nn import torch.nn.functional as F def get_activation_layer(name): return { 'relu': nn.ReLU, 'elu': nn.ELU, 'softplus': nn.Softplus, 'leaky_relu': nn.LeakyReLU, 'swish': Swish }[name] class Swish(nn.Module): def __init__...
import os from typing import Union, Any, Optional, Iterable, Dict, TYPE_CHECKING, Tuple, cast if TYPE_CHECKING: from pyfileconf.main import PipelineManager from mixins.repr import ReprMixin from pyfileconf.basemodels.config import ConfigBase from pyfileconf.config.models.file import ActiveFunctionConfigFile from...
from __future__ import division import itertools import pandas as pd import numpy as np import matplotlib.pyplot as plt import matplotlib as mpl from sklearn.decomposition import PCA from sklearn import mixture from scipy import linalg from math import ceil, sqrt from sklearn.cluster import AgglomerativeClustering, Mea...
# SPDX-License-Identifier: BSD-3-Clause # <NAME> 2022 import argparse import time import tracemac_parser from getpass import getpass from netmiko import ConnectHandler from pathlib import Path from typing import Any, Callable, Dict, List, Optional, Union etherchannel_cache_current_device_id: str = "" etherchannel_pars...
""" Copyright (c) 2020, salesforce.com, inc. All rights reserved. SPDX-License-Identifier: BSD-3-Clause For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause Utility functions. """ import collections import datetime import functools import inspect import rand...
#!/usr/bin/python3 ''' File name: LOFAR_h5_to_fits.py Author: <NAME>, <NAME> Acknowledge: <NAME> Date created: 2019-Aug Python Version: 3.4 Split and down sample the dynamic spectrum of LOFAR observation Input : Huge hdf5 file of LOFAR Tied array beam formed observation Output : ...
# The piwheels project # Copyright (c) 2017 <NAME> <https://github.com/bennuttall> # Copyright (c) 2017 <NAME> <<EMAIL>> # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must ...
import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torch.autograd import Variable import torch.utils.data as data from torchvision import datasets, transforms import os import pickle import numpy as np from PIL import Image import time import math LOAD_DIR = "." BATCH_S...
import os import math from torchvision.ops import nms import torch import torch.nn as nn import torch.nn.functional as F from retinanet.model import PyramidFeatures, RegressionModel, ClassificationModel from retinanet.utils import BBoxTransform, ClipBoxes from retinanet.anchors import Anchors from retinanet import l...
# -*- coding: utf-8 -*- """ This is a custom read mapper for amplicon data. It simply places the reads at the location they were expected to come from, based on the target coordinates of their associated probe. It will perform an aligment within the target region to handle small differences but will not correctly handl...
import sys import unittest import math INPUT = """4 ZDGD, 1 HTRQV => 3 VRKNQ 15 XKZQZ, 1 MWZQ => 4 LHWX 1 WVPKL => 2 HJLX 1 LFDGN => 7 DMPX 14 HJLX, 3 KGKVK, 1 XQSVS => 6 HGSM 8 FKQS, 8 MWVCW => 3 MVSK 2 HGZLR, 2 WVPKL, 29 VRKNQ => 2 MDKZ 1 RLGBD, 22 VWFV => 6 MSGJ 24 PHLTR, 2 MWVCW => 8 JZMS 5 XSJLQ, 2 PFTM => 1 NCRJ...
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import torchvision import torchvision.transforms as transforms import neuron import linear # nearly all paramters in this simulation, but it seems no use to store them in a dict... param = {'G_min': -1.0, # the minimum (max...
#!/usr/bin/env python # Copyright 2014 The Swarming Authors. All rights reserved. # Use of this source code is governed by the Apache v2.0 license that can be # found in the LICENSE file. import datetime import sys import unittest import test_env test_env.setup_test_env() from google.appengine.ext import ndb from c...
import os import json from tasks.data_utils import build_data_loader from utils import get_sample_writer, get_log_dir, print_and_save_args from model import GLMModel from arguments import get_args """Finetune utilities.""" import torch import torch.utils.data from configure_data import prepare_tokenizer from utils ...
""" docstring needed :copyright: Copyright 2010-2017 by the NineML Python team, see AUTHORS. :license: BSD-3, see LICENSE for details. """ from past.builtins import basestring from nineml.exceptions import NineMLUsageError, NineMLDimensionError from nineml.abstraction.expressions.utils import is_valid_lhs_target from ...
# Copyright 2018 Alibaba Group. 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 o...
#! /usr/bin/env python # -*- coding: utf-8 -*- # # Interpreter version: python 2.7 # """ This module contains composers to allow creation of XML for URN:NBN, so you don't have to create XML by hand. See: - http://resolver.nkp.cz/api/v3/digDocRegistration.xsd - https://code.google.com/p/czidlo/wiki/ApiV3 """ # ...
import pygame, sys #import module pygame untuk membuat GUI game from pygame.locals import * #Kata tutorialnya karena pygame.locals sering dipake import random #Buat ngerandom jalannya computer import tkinter #Buat inisialisasi window di exception from tkinter.messagebox import showinfo #Buat bikin showinfo di exception...
import sys, getopt from skimage import io import numpy as np # python3 mdsi.py ref.png dist1.png dist2.png def pooling(mat, ksize, method='mean', pad=False): m, n = mat.shape[:2] if pad: _ceil = lambda x,y: int(np.ceil(x/float(y))) ny = _ceil(m, ksize) nx = _ceil(n, ksize) siz...
# Created by <NAME> on March, 2014 # Copyright (c) 2013-2014 BEFREE Ltd. # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to us...
# -*- coding: utf-8 -*- """ Created on Thu Mar 18 20:57:59 2021 @author: mhamz """ from datetime import datetime import socket import threading import random import string from Crypto.PublicKey import RSA from Crypto import Random from Crypto.Cipher import DES from Crypto.Cipher import DES3 from Crypto...
""" Env used in PAD. Code adapted from its github repo paper: Self-Supervised Policy Adaptation during Deployment (https://arxiv.org/abs/2007.04309) github: https://github.com/nicklashansen/policy-adaptation-during-deployment """ import numpy as np from numpy.random import randint import gym import ...
from ms_cfbf import CFBF from pdf import PDF from ms_ooxml import OOXML #from datetime import datetime import inspect import os #import jarray #import csv #import time from java.util.logging import Level from java.io import File from org.sleuthkit.datamodel import SleuthkitCase from org.sleuthkit.datamodel import Abs...
"""CSC111 Final Project Module with containing the NeuralNetGraph class, which acts as the brain of the AI controller. This module is based off the graph code from the Course Nodes and Assignment 3, though heavily modified. """ from __future__ import annotations from typing import Union import csv import random impor...
# -*- coding: utf-8 -*- # Simple Bot (SimpBot) # Copyright 2016-2017, <NAME> (kwargs) import re import sys import logging from os import path from . import workarea logging = logging.getLogger('simpbot') langsep = '-' ext = '.dat' # extension name class Error(Exception): def __init__(self, string, line=None,...
""" INFO_VERSION 1: original metadata format """ import functools import hashlib import inspect from typing import Callable, Dict import omegaconf import toolz from pydantic import validate_arguments from gdsfactory.component import Component, clean_dict from gdsfactory.name import MAX_NAME_LENGTH, clean_name, clea...
# encoding: utf-8 from __future__ import division, print_function, unicode_literals ########################################################################################################### # # # Filter without dialog Plugin # # Read the docs: # https://github.com/schriftgestalt/GlyphsSDK/tree/master/Python%20Templa...
import os import pandas as pd import numpy as np import re def extract_file_type(abspath): return os.path.basename(abspath).split('.')[-2].lower().strip() def extract_date(abspath): return re.search('[0-9]{4}-[0-9]{2}-[0-9]{2}', os.path.basename(abspath).split('.')[2]).group(0) def extract_hour(abspath):...
import logging import numpy as np import nibabel as nib import scipy.ndimage as ndimage from six import string_types from .check import check_img from nilearn._utils import check_niimg from nilearn.image.image import new_img_like, _fast_smooth_array log ...
#ref: http://connor-johnson.com/2016/01/24/using-pywavelets-to-remove-high-frequency-noise/ import time import pickle #import pywt import numpy as np import matplotlib as mpl mpl.rc('xtick', labelsize=30) mpl.rc('ytick', labelsize=30) mpl.rcParams.update({'errorbar.capsize': 2}) import matplotlib.pyplot as plt i...
from __future__ import absolute_import, division, print_function from scitbx.array_family import flex import iotbx.phil import mmtbx.polygon import libtbx, os, re, sys from libtbx.utils import Sorry from libtbx import easy_pickle from six.moves import range keys_to_show = ["r_work", "r_free", "pdb_header_r_work", "p...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Interact with Jira.""" import json import os from pathlib import Path from typing import Any, Dict, List, Union import jira import yaml from jira_freeplane.common import AUTOFIELDS, LOG USER = os.environ.get("JIRA_USER", "") PASS = os.environ.get("JIRA_PASS", "") JIR...
#!/usr/bin/env python """Produce a report of all assertions in the MongoDB server codebase. Parses .cpp files for assertions and verifies assertion codes are distinct. Optionally replaces zero codes in source code with new distinct values. """ from __future__ import absolute_import from __future__ import print_functi...
import telegram import logging from telegram.ext import CommandHandler, MessageHandler, Updater import urllib.request, json from operator import attrgetter import random import traceback import os.path import threading import tokens logging.basicConfig( format='%(asctime)s - %(name)s - %(levelname)s - %(message)s...
from collections import namedtuple from http.cookiejar import CookieJar from ssl import SSLContext from typing import IO, List, Optional import lxml.etree import random import re from string import ascii_lowercase import time from urllib.parse import urlencode import urllib.request Album = namedtuple("Album", ["id", ...
# Copyright (C) 2019 The Raphielscape Company LLC. # # Licensed under the Raphielscape Public License, Version 1.c (the "License"); # you may not use this file except in compliance with the License. # """ Userbot initialization. """ import os import sys from distutils.util import strtobool as sb from logging import DE...
# # Copyright (c) 2014, Arista Networks, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # Redistributions of source code must retain the above copyright notice, # this list of condit...
# Copyright (c) 2021, <NAME> # License: MIT License import sys from typing import Iterable import pathlib import random import ezdxf from ezdxf import zoom, print_config from ezdxf.math import Matrix44 from ezdxf.tools import fonts from ezdxf.tools import text_layout """ This example shows the usage of the internal...
import os, inspect currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) print("current_dir=" + currentdir) os.sys.path.insert(0, currentdir) import gym.utils.seeding import pybullet as p import pybullet_data from pybullet_utils import bullet_client import pybullet_data as pd urdfRoot ...
from typing import Sequence, Callable, Optional, Union, Tuple import numpy as np import copy from qcodes.data.data_set import DataSet from qcodes.data.data_array import DataArray import qtt.data # %% def process_dataarray(dataset: DataSet, input_array_name: str, output_array_name: str, proces...
import numpy as np """ 备注:本示例中所有的matrix都使用的是array来体现 实际上python中存在专门的matrix # 主要注意matrix和array的区别 # matrix 使用更加接近matlab的使用方式 简单示例如下: B = np.matrix('1,2;3,4') print(B*B) # 注意:若使用matrix,则*直接表示矩阵乘法 # 而元素对应乘积则使用 multiply() 函数 """ def vector_dot(): a = np.array([1, 3, 5, 7, 9]) ...
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. """ Implements the Generalized R-CNN framework """ import torch from torch import nn from maskrcnn_benchmark.structures.image_list import to_image_list from ..backbone import build_backbone from ..rpn.rpn import build_rpn from ..roi_heads.roi_he...
"""Training WaveRNN Model. usage: train.py [options] <data-root> options: --checkpoint-dir=<dir> Directory where to save model checkpoints [default: checkpoints]. --checkpoint=<path> Restore model from checkpoint path if given. -h, --help Show this help message and exit """ f...
#!/usr/bin/env python # -*- coding: utf-8 -*- """Base example for setting up the API client.""" import codecs import copy import csv import io import click from packaging import version as pkg_version import axonius_api_client as axonapi # noqa: F401 from axonius_api_client.cli.context import CONTEXT_SETTINGS from a...
#! /usr/bin/env python3 """Unit tests for smartcard.sw This test case can be executed individually, or with all other test cases thru testsuite_framework.py. __author__ = "http://www.gemalto.com" Copyright 2001-2012 gemalto Author: <NAME>, mailto:<EMAIL> This file is part of pyscard. pyscard is free software; you ...
from __future__ import print_function try: from collections import OrderedDict except ImportError: from ordereddict import OrderedDict from collections import Callable, defaultdict from six.moves import xrange try: # For Python 3.0 and later import urllib.request as urllib2 except ImportError: # Fal...
import os import corai from corai import create_model_by_index from corai_util.tools import function_dict from corai_util.tools import function_writer from datasets.dataset import * from hp_opti_fct import generate_estims_history from src.rc_class.full_model.ridge_models.model_esn_ridge import Model_esn_ridge from sr...
# Copyright (c) 2021 Graphcore Ltd. All rights reserved. import numpy as np import pytest import test_util as tu import popart ALL = popart.AnchorReturnType("all") FINAL = popart.AnchorReturnType("final") SUM = popart.AnchorReturnType("sum") EVERY1 = popart.AnchorReturnType("everyn", 1) EVERY2 = popart.AnchorReturnTy...
import torch.multiprocessing torch.multiprocessing.set_sharing_strategy('file_system') import csv import pickle import PIL import pprint import random import argparse import os,sys,inspect import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt from glob import glob from os.path i...
# The MIT License (MIT) # Copyright (c) 2018 by EUMETSAT # # Permission is hereby granted, free of charge, to any person obtaining a copy of # this software and associated documentation files (the "Software"), to deal in # the Software without restriction, including without limitation the rights to # use, copy, modify,...
import numpy as np import matplotlib.pyplot as plt import sys # from scipy.optimize import curve_fit np.random.seed(42) def nn_sum(x, i, j, k, L): """ Args: x: Spin configuration i, j, k: Indices describing the position of one spin L: System side length Returns: Sum of the ...
# Copyright (c) 2020, BlockProject # # All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, # this list of condition...
# Our Model import os import math import numpy as np from glob import glob import torch import torch.nn as nn import torch.nn.functional as F from collections import OrderedDict __all__ = ['CMCNN'] class SpatialAttention(nn.Module): """ ref: https://github.com/luuuyi/CBAM.PyTorch """ def __init__(sel...
""" This is PISACov, a program designed to infer quaternary structure of proteins from evolutionary covariance. """ from pisacov import __prog__, __description__, __version__ from pisacov import __author__, __date__, __copyright__ import copy import logging from pisacov import iomod as pio import xml.etree.ElementTr...
# Copyright 2019 The FastEstimator 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 appl...
import tkinter as tk from tkinter import filedialog from tkaddons import XYScrolledText from certtools import x509Cert from json import dumps import OpenSSL.crypto from tkinter import ttk SMALL = {"Text": {"X": 51, "Y": 10}, "Window": {"X": 470, "Y": 260}} MEDIUM = {"Text": {"X": 70, "Y": 25}, "Window": {"X": 581, "Y"...
# -*- coding: utf-8 -*- import wx import screens import firstnames import lastnames import towns import towncodes def AutoCompleteLastNames(prefix): pref = prefix.upper() data = [] for name in lastnames.lastnames: if name.startswith(pref): data.append(name) return data, data def Au...
# FusionPBX Plugin for the Media Server api import psycopg2 import psycopg2.extras import json import uuid # Defining a dialplan object, which allows you to define how the # dialplan within a domain behaves class cos_dialplan(): name = None dialplan_xml = None def __init__(self): self.dialplan_x...
# -*- coding: utf-8 -*- from bw2parameters import ParameterSet from bw2parameters.errors import ( CapitalizationError, DuplicateName, ParameterError, SelfReference, ) from bw2parameters.utils import get_symbols, isidentifier import numpy as np import pytest import sys def test_call_updates_exchanges()...
import csv import dataset_utils as utils import numpy as np import matplotlib.pyplot as plt import os import torch import torch.nn as nn from collections import defaultdict from typing import Any, Dict, Iterable # Directories names containing the landcover tiles and coordinates. TILES_DIR = "tiles" COORDINATES_DIR =...
""" Interface for inferencer """ # Copyright (C) 2021-2022 Intel Corporation # SPDX-License-Identifier: Apache-2.0 # import abc import logging import multiprocessing import queue import warnings from pathlib import Path from typing import Any, Iterator, List, Optional, Tuple, Union import numpy as np # pylint: disa...
#!/usr/bin/env python """ --------------------- PDF Analytics Client --------------------- The PDF Analytics Client is a high level module that enables the verification of the images and text of a local PDF file. """ from __future__ import absolute_import, division, print_function, unicode_literals import os import...
import pygame from pygame.math import Vector2 from pygame.locals import * import os.path import sys pygame.init() #initialization pygame.display.set_caption('Dazzling Dash') #window title clock = pygame.time.Clock() #clock font = pygame.font.SysFont(None, 50) #font small_font = pygame.font.SysFont(None, 30) ...
import psycopg2 import random import sys from time import time_ns TABLE_LENGTH = 1000000 def get_random_string(length): # Random string with the combination of lower and upper case letters = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','X','Y','Z','a','b','c','d','e','f','g'...
from __future__ import print_function, absolute_import, division import numpy as np np.random.seed(1) from tensorflow import set_random_seed set_random_seed(1) import os from keras.callbacks import ModelCheckpoint, TensorBoard, CSVLogger, Callback import pandas as pd from sklearn.metrics import confusion_matrix from ...
''' Transfer learning satterlite image using the crfasrnn by <NAME> ''' import tensorflow as tf import os import keras.backend as K def assignGPU(gpu): os.environ["CUDA_VISIBLE_DEVICES"]="%s" % (gpu) config = tf.ConfigProto() config.gpu_options.allow_growth = True K.set_session(tf.Session(config=config)...
from tkinter import* import tkinter.messagebox left1 = Tk() left1.geometry("1600x800+0+0") left1.title("Change Price") label4 = Label(left1, font = ('arial',50,'bold'), text ="Change Price", fg = "steel blue", bd = 10, anchor = 'w') label4.grid(row = 0) fries_inp_p = StringVar() Sandwich_inp_p = StringVar() burger...
import cv2 import os import json import numpy as np from numpy.linalg import norm SZ = 20 PROVINCE_START = 1000 def deskew(img): m = cv2.moments(img) if abs(m['mu02']) < 1e-2: return img.copy() skew = m['mu11'] / m['mu02'] M = np.float32([[1, skew, -0.5 * SZ * skew], [0, 1, 0]]) img = cv2...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # --------------------------------------------------------------------------- # author : nocturnalbeast # version : '1.1-multi' # --------------------------------------------------------------------------- """ This is a script that is used to export all the tests from a ...
#coding=utf8 import copy, math import torch import torch.nn as nn import torch.nn.utils.rnn as rnn_utils def clones(module, N): "Produce N identical layers." return nn.ModuleList([copy.deepcopy(module) for _ in range(N)]) def lens2mask(lens, idx): lens = lens[idx] bsize = lens.numel() max_len = le...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Step 3X Preprocessing: Feature Selection License_info: ISC ISC License Copyright (c) 2020, <NAME> 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...
import time from luma.core.render import canvas from luma.core.interface.serial import bitbang import RPi.GPIO as GPIO from luma.oled.device import ssd1322 import luma.oled.device from smbus2 import SMBus from gpiodefs import * def ADC128_REG_IN_MAX(nr): return (0x2a + (nr) * 2) def ADC128_REG_IN_MIN(nr): r...
# Shoddy procedural code import random options = ['rock', 'paper', 'scissors'] print('(1) Rock\n(2) Paper\n(3) Scissors') human_choice = options[int(input('Enter the number of your choice: ')) - 1] print(f'You chose {human_choice}') computer_choice = random.choice(options) print(f'The computer chose {computer_choice}'...
import requests import json import numpy as np import pandas as pd import sqlalchemy as sql import time from scripts.config import * from sqlalchemy import create_engine from utils.logger import logger from typing import * SEARCH = "https://api.twitter.com/2/tweets/search/all" class DB: @property def locati...
import sys import os from os.path import join, isdir from glob import glob from skimage.measure import label as mlabel import numpy as np from os import fsync, makedirs from PIL import Image import torch.nn.functional as F from scipy.ndimage.morphology import distance_transform_edt as edt import torch import math from ...
import abc import re from adapt.context import ContextManagerFrame from intentBox.utils import flatten, normalize, LOG from intentBox.segmenter import Segmenter from intentBox.coreference import replace_coreferences import time import enum class IntentDeterminationStrategy(str, enum.Enum): SINGLE_INTENT = "single...
""" Train a regression DCGAN """ import torch import torch.nn as nn import numpy as np import os import timeit from PIL import Image from utils import * from opts import parse_opts ''' Settings ''' args = parse_opts() NGPU = torch.cuda.device_count() device = torch.device("cuda" if torch.cuda.is_available() else "c...
""" analytic.py - Tanay's notebook in a .py file """ import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np import math from pylab import * from qutip import * from matplotlib import cm import imageio from pathos.multiprocessing import ProcessingPool as Pool def plot_points(b): # -X and Y dat...
import anti_alexnet from chess import Board import math from numpy import ones from pandas import read_csv from PlayerAi import PlayerAi from random import choice from random import seed from random import shuffle def main(): model_file_name = 'simple_dense.h5' train_simple_dense(model_file_name,...
""" Spatial binning (that is, keeping binned lines with regular length). Points are [longitude, latitude]. Unused. """ import datetime, geo from yaml import load as yload, FullLoader from psycopg2 import connect config = yload(open("./config.yaml"), Loader=FullLoader) start_time = geo.str2time(config['streamStartTim...
#!/usr/bin/env python # Filename: plot_landsat_timeseries.py """ introduction: plot the time series of landsat data authors: <NAME> email:<EMAIL> add time: 14 April, 2019 """ import sys,os from optparse import OptionParser import rasterio import numpy as np # import pandas as pd # read and write excel files HOME = ...
import tensorflow as tf import tensorlayer as tl from tensorlayer.layers import * class Generator: ''' 1. output layer 를 제외한 모든 구간에서 batch normalization 사용 2. output layer 를 제외한 모든 layer 의 activation function 은 ReLU 사용 3. output layer 의 입력값에 gaussian noise 추가 ''' def __init__(self, ...
# -*- coding: utf-8 -*- """HTTP header elements .. seealso:: :rfc:`2616#section-2.2` .. seealso:: :rfc:`2616#section-4.2` .. seealso:: :rfc:`2616#section-14` """ import re from binascii import b2a_base64 from email.errors import HeaderParseError from httoop.exceptions import InvalidHeader from httoop.six import wi...