text
stringlengths
3.07k
22.1k
#!/usr/bin/env python """This script shows an example of using the PyWavefront module.""" import ctypes import os import sys sys.path.append('..') import pyglet from pyglet.gl import * from pywavefront import visualization import pywavefront import numpy as np import cv2 import cv2.aruco as aruco # resource path path ...
#!/usr/bin/env python3 import logging import math import pickle from collections import Counter, defaultdict from optparse import OptionParser from typing import Dict, List, Optional, Set, Tuple logging.basicConfig(level=logging.INFO, format="%(asctime)s %(message)s") logger = logging.getLogger(__name__) def get_a...
#!/usr/bin/env python # -*- coding: utf-8 -*- # ============================================================================= ## @file # @see Ostap::StatEntity # @see Ostap::WStatEntity # @see Ostap::NStatEntity # @author <NAME> <EMAIL> # @date 2009-09-12 # =========================================================...
#!/usr/bin/env python # _*_ coding: utf-8 _*_ # @Time : 2021/6/7 下午8:50 # @Author : PH # @Version:V 0.1 # @File : inference.py # @desc : 预测并将结果保存在json文件内 import json import re import os import pickle import PIL.Image as Image import torch import torch.nn.functional as F from torchvision.transforms import Compose, ToTen...
# © <NAME> 2019, all rights reserved # Dinner Bottega Diner Have a Main Menu, and a Sides Menu You get one entree and two # side choices at regular cost. # *show them the entire menu (print out) # *User selects an entree. # *“Waitress” makes a comment based on their selection # *comment can either be a comparison of ...
# Copyright 2016 The TensorFlow Authors All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicab...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # execute in production with: nohup python3 Browser.py &> browser.log < /dev/null & ########### # Imports # ########### import re import sys import os import traceback import json from time import sleep from multiprocessing import Process from rpc_client import get_acct...
import os.path import numpy as np import keras.backend as K from keras import callbacks np.random.seed(5) def unison_shuffled_copies(arrays): """shuffle multiple arrays keeping corresponding items in same relative positions between arrays""" # print(len(arrays)) # print(len(arrays[0]...
import numpy as np import matplotlib.pyplot as plt import PyOSGPUP.wavelet as wavelet def getPlotLog(d, log, dmax=200): d = np.array(d, dtype=float) log = np.array(log, dtype=float) dplot = np.kron(d, np.ones(2)) logplot = np.kron(log, np.ones(2)) # dplot = dplot[1:] dplot = n...
import pytest from .conftest import relative_to_this_test_folder from dae.annotation.tools.score_file_io import ( ScoreFile, TabixAccess, LineAdapter, LineBufferAdapter, ) def test_regions_intersecting(): regions = [ # subset ((10918, 11018), (10958, 11018)), # overlap ...
import pprint import torch.nn.functional as F import torchvision.models as models import torchvision.transforms as transforms import torch.utils.data.distributed import torch.utils.data import torch.optim import torch.backends.cudnn as cudnn import torch.nn.parallel import torch.nn as nn import torch import pandas as p...
# Copyright 2022 Huawei Technologies Co., Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to...
# @Author : <NAME> # @Contact : <EMAIL> import numpy as np import torch from torch import nn from torch.nn import Parameter from utils import init_weights def calc_coeff(iter_num, high=1.0, low=0.0, alpha=10.0, max_iter=10000.0): return np.float(2.0 * (high - low) / (1.0 + np.exp(-alpha * iter_num / max_iter)...
import asyncio import logging from typing import AsyncIterator, Dict, List, Tuple, Optional from pathlib import Path from chia.consensus.constants import ConsensusConstants from chia.full_node.full_node_api import FullNodeAPI from chia.server.start_service import Service from chia.util.hash import std_hash from chia.u...
import os from uuid import uuid4 import shutil from time import time import logging import requests import flask import selenium from selenium.common.exceptions import NoSuchElementException, TimeoutException, InvalidArgumentException from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.supp...
#!/usr/bin/env python3 """Generic utility functions.""" from __future__ import absolute_import, division, print_function from builtins import map from past.builtins import basestring from contextlib import contextmanager import bz2 from functools import partial import gzip from io import open, TextIOWrapper import log...
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division from __future__ import print_function # stdlib imports import unittest import warnings import persistent from persistent import Persistent from persistent.wref import WeakRef as PWeakRef from nti.ext...
import numpy as np import re def update_all_tags(closest_roi): if closest_roi['Shape_type'] == 'Rectangle': closest_roi['Tags']['Center tag'] = (int(closest_roi['topLeftX'] + closest_roi['width'] / 2), int(closest_roi['topLeftY'] + closest_roi['height'] / 2)) closest_roi['Tags']['Top left tag'] = (...
from itertools import zip_longest, tee from numpy import all as np_all, arange, isin, sort, concatenate from hypothesis import given, assume, example from hypothesis.strategies import one_of from pytest import raises from ..chunking import ChunkSize from ..slice import Slice from ..tuple import Tuple from ..ndindex...
from __future__ import print_function, division import sys sys.path.append("core") from torch.utils.tensorboard import SummaryWriter import argparse import os import random import torch import torch.nn as nn import torch.optim as optim from torch.autograd import Variable import torch.nn.functional as F import core.d...
import os from data_manager import DataManager as dm import cv2 from numpy.random import randint import numpy as np from imgaug import augmenters as iaa from util import check_directory,check_cv2_imwrite ROOT_DIR = os.getcwd() if ROOT_DIR.endswith('src'): ROOT_DIR = os.path.dirname(ROOT_DIR) OLD_DATA_DIR = os.pat...
from torch.nn import LSTM, Linear, BatchNorm1d, Parameter import torch import torch.nn as nn import torch.nn.functional as F import torchaudio class NoOp(nn.Module): def __init__(self): super().__init__() def forward(self, x): return x class ISTFT(nn.Module): def __init__( self, ...
# (C) 2020 University of Colorado AES-CCAR-SEDA (Space Environment Data Analysis) Group # Written by <NAME> import pytest import datetime import numpy as np import numpy.testing as nptest from geospacepy.special_datetime import jd2datetime,datetime2jd from geospacepy.sun import greenwich_mean_siderial_time from geospac...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright (C) 2021. Huawei Technologies Co., Ltd. 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....
import os import torch import torch.nn as nn import torch.utils import torch.backends.cudnn as cudnn import xnas.core.config as config import xnas.core.meters as meters import xnas.core.logging as logging import xnas.search_space.DrNAS.utils as utils from xnas.search_algorithm.DrNAS import Architect from xnas.core.bui...
from zlib import decompress import struct """ Replicate com.ankamagames.jerakine.network.CustomDataWrapper """ class Data: def __init__(self, data=None): if data is None: data = bytearray() self.data = data self.pos = 0 def __len__(self): return len(self.data) ...
import pandas as pd import statistics import os import seaborn as sns import matplotlib # Force matplotlib to not use any Xwindows backend. matplotlib.use('Agg') import matplotlib.pyplot as plt import matplotlib.ticker as ticker # plt.rc("font", family="serif", serif="cmr10") from benchmark import fonts plt.rc("font"...
import pandas as pd import glob import os import subprocess import argparse import os import json import tempfile import ast from repnano.features.bam_tools import load_read_bam import numpy as np import h5py import re from taiyaki import alphabet, mapped_signal_files MAPPED_SIGNAL_WRITER = mapped_signal_files.HDF5Writ...
import asyncio from contextlib import contextmanager import enum import itertools import jinja2 import logging from ora import now, Time import shlex from .lib.memo import memoize from .lib.py import format_ctor, iterize log = logging.getLogger(__name__) #-----------------------------------------------------...
# -*- coding: utf-8; -*- """Break infinite recursion cycles in pure functions. The name `fix` comes from the *least fixed point* with respect to the definedness relation, which is related to Haskell's `fix` function. However, this `fix` is not that function. Our `fix` breaks recursion cycles in strict functions - th...
#!/usr/bin/env python """ This script parses a forcebalance output file and plots the data. for the future - be able to pick an iteration from an arb outfile. legend displays filename and iteration number example usage: >> ./plot_fb.py --of optimize.out --ir 0,1 --pdf_out filename """ import os import argpa...
import torch.utils.data.dataloader as dl import ISBI2012Data as ISBI import torch import torch.nn as nn import torch.optim as optim import torch.backends.cudnn as cudnn import os import numpy as np from PIL import Image import sys import time import model as md import paramssacred ex = paramssacred.ex # saves the ...
# This file is part of the scanning-squid package. # # Copyright (c) 2018 <NAME>-<NAME> # # 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...
from stemming import Stemming import math def calCosine(val1, val2): num = det1 = det2 = 0 for i in range(len(val1)): num += val1[i] * val2[i] det1 += val1[i] * val1[i] det2 += val2[i] * val2[i] det1 = math.sqrt(det1) det2 = math.sqrt(det2) return num / (det1 * det2) def pr...
import json import os import random import shutil import tkinter as tk from datetime import datetime from tkinter import filedialog, ttk import numpy as np from skimage.io import imsave from skimage.transform import resize from .partially_labelled_dataset import ( PartiallyLabelledDataset, save_annotations, ...
import random import itertools from gcs_basics import * def test_reduction_1d(): for shape in [(1,), (5,), (3, 4), (3, 4, 5, 2, 1)]: N = len(shape) for dimensions in itertools.permutations(range(N)): metadata = create_reduction_metadata(shape, dimensions, ()) for indices i...
import os import numpy as np import pytest from cloudvolume import Vec, Bbox, CloudVolume, Storage, Mesh @pytest.mark.parametrize(("use_https"),[True, False]) def test_mesh_fragment_download(use_https): vol = CloudVolume('gs://seunglab-test/test_v0/segmentation', use_https=use_https) paths = vol.mesh._get_manife...
import os import re import sys sys.path.append('../') import tensorflow import tensorflow.keras as keras from tensorflow.keras.optimizers import Adam from keras import backend as K from models.pelee import pelee from losses.keras_ssd_loss import SSDLoss from utils.object_detection_2d_data_generator import DataGenerato...
#!/usr/bin/env python2 # -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function from psychopy import locale_setup, visual, core, data, event, logging#, sound, gui from psychopy.constants import (NOT_STARTED, STARTED, PLAYING, PAUSED, STOPPED, FINISHED, PRE...
"""The card game, BlackJack, made using python. Blackjack is a comparing card game between one or more players and a dealer, where each player in turn competes against the dealer. Player and dealer are dealt 2 cards each. One of the dealer's card remains hidden until the player's turn is over. A hand's value is the s...
# -*- coding: utf-8 -*- from __future__ import division from __future__ import absolute_import from keras.engine.topology import Layer import tensorflow as tf class ProposalTF(Layer): def __init__(self, scales=(0.25, 0.5, 1.0, 2.0), aspect_ratios=(0.5, 1.0, 2.0), anchor_stride=(16, 16), max_prop...
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve. # #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...
import numpy as np from scipy import linalg from core.utils import fidelidad_vec, dot_prod_vec def bases_2_3(a, b, fase): """ Bases basicas en dimension 2 y 3. IN a: float. Coeficiente acompañando a |0>. b: float. Coeficiente acompañando a |1>. fase: float. Fase acompañando a |1>. ...
import requests import os import shutil import json import boto3 from django.conf import settings import xml.etree.cElementTree os.environ['http_proxy']='' import urllib from django.http import HttpResponseRedirect import numpy as np from ..models import DesignModel from .utils import * import encodings.idna def creat...
""" CUSTOM_LIST: False """ from binance.client import Client import numpy as np import threading import os import pandas_ta as pta import pandas as pd from datetime import date, datetime, timedelta import time client = Client("", "") TIME_TO_WAIT = 1 # Minutes to wait between analysis DEBUG = False TIC...
#-*- coding: utf-8 -*- from __future__ import division import re import sys from sys import byteorder from array import array from struct import pack import pyaudio import wave import subprocess import os import json import xml.etree.ElementTree as ET import math import io import os import time from six.moves import qu...
# # PySNMP MIB module ELTEX-MES (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ELTEX-MES # Produced by pysmi-0.3.4 at Wed May 1 12:59:59 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23...
import numpy as np import scipy.sparse as sp import torch import sys import pickle as pkl import networkx as nx def encode_onehot(labels): # The classes must be sorted before encoding to enable static class encoding. # In other words, make sure the first class always maps to index 0. classes = sorted(list(...
#!/usr/bin/env python3 """Cyberjunky's 3Commas bot helpers.""" import argparse import configparser import json import os import re import sys import time from pathlib import Path import requests from bs4 import BeautifulSoup from helpers.logging import Logger, NotificationHandler from helpers.misc import wait_time_in...
# coding: utf-8 # app/main/views.py import os from datetime import datetime import random from flask import current_app, render_template, request, redirect, url_for, flash, send_from_directory, make_response, jsonify from . import main from .. import db from ..models import User, Bug, Record, \ Product, Comment, ...
# Copyright 2018-2021 # Institute of Neuroscience and Medicine (INM-1), Forschungszentrum Jülich GmbH # 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/LICE...
""" Helper functions to simplify NY_Times_Covid_Data.py - Retrieve COVID data from New York Times API - Populate data and create PyGal histograms - cleanup of .svg graph files """ from contextlib import closing import csv import os import pygal import requests from graph_settings import GraphSettings from text_men...
# Picket. Calculate if a point is inside a fence. # Copyright (C) 2017-2018 <NAME> # This program 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, either version 3 of the License, or # (at your option) any la...
from PIL import Image, ImageDraw import numpy as np from matplotlib.colors import rgb_to_hsv, hsv_to_rgb import math def rand(a=0, b=1): return np.random.rand()*(b-a) + a def merge_bboxes(bboxes, cutx, cuty): merge_bbox = [] for i in range(len(bboxes)): for box in bboxes[i]: ...
# -- assignment 1 -- import numpy as np from urllib import request import gzip import pickle import os def load_synth(num_train = 60_000, num_val = 10_000, seed = 0): """ Load some very basic synthetic data that should be easy to classify. Two features, so that we can plot the decision boundary (which is ...
# Copyright 2019-2021 ETH Zurich and the DaCe authors. All rights reserved. """ Explicitly distributed Gesummv sample.""" import dace as dc import numpy as np import os from dace.sdfg.utils import load_precompiled_sdfg from mpi4py import MPI lM = dc.symbol('lM', dtype=dc.int64, integer=True, positive=True) lN = dc.sym...
''' Perform desired Dec_UCB simulations from standard input ''' from Dec_UCB import Dec_UCB from UCB1 import UCB1 import argparse import networkx as nx import numpy as np import scipy.stats as sps import random import matplotlib.pyplot as plt def generate_random_graph(size, type): if type == 'undirected': ...
# (C) British Crown Copyright 2011 - 2018, Met Office # # This file is part of cartopy. # # cartopy is free software: you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the # Free Software Foundation, either version 3 of the License, or # (at your option)...
########################################################################## # Copyright 2018 Kata.ai # # 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...
import logging import os import re from enum import Enum from typing import List, Tuple, Dict import docker from docker import APIClient import json from pythoncommons.file_utils import FileUtils from pythoncommons.process import SubprocessCommandRunner from pythoncommons.string_utils import auto_str MOUNT_MODE_RW = ...
from flask import Flask, request import pandas as pd import numpy as np import json from Property import Property from sklearn.model_selection import train_test_split from sklearn.linear_model import LinearRegression from flask_cors import CORS app = Flask(__name__) CORS(app) cors = CORS(app, resources={ r"/*": {...
# -*- coding: utf-8 -*- """ I/O tools for handling CCFPeat simulations. Created on Fri Jun 08 10:32:44 2018 Note: migrated to python3 - print >>out to print(file=out) @author: <NAME> """ import sys import os import pandas as pd import numpy as np import json def write_ncf(nsim=None, results=None, ncf=None...
from string import printable from typing import (Any, Callable, Generic, Iterable, NoReturn, Tuple, TypeVar, Union) from . import (Dict, Immutable, List, aio_trampoline, effect, either, maybe, trampoline) try: from hypothesis.strategies import ( booleans, builds,...
__all__ = ['atoms_to_graph','get_paths','remove_non_rings','paths_to_atoms', 'remove_dups','remove_labeled_dups','dict_to_atoms','get_vertices', 'shortest_valid_path','is_valid','all_paths','remove_geometric_dups'] ''' This module contains utilities to be used by the rings.py module. ''' import ...
# 交叉验证 import torch as t import torch.nn as nn import numpy as np import matplotlib.pyplot as plt from torch.optim import SGD import random as rd from torch.utils.data import DataLoader from torch.autograd import no_grad import os import time from modules.model.PrototypicalNet import ProtoNet from modules.model.Chan...
""" ============================================================================================ A program to compute the Ollivier-Ricci curvature of a given undirected graph. Reference: (1) <NAME>, <NAME>, <NAME>, <NAME>, <NAME> & <NAME>, Comparative analysis of two discretizations of Ricci curvature for complex netwo...
#!/usr/bin/env python # coding: utf-8 import string import sys from collections import Counter import numpy as np import pandas as pd from nltk.tokenize import word_tokenize from sklearn.model_selection import train_test_split sys.path.insert(0, '..') from lstm_vae import create_lstm_vae, inference from preprocessi...
import datetime import re import time import threading import queue from math import floor import logging import dateutil.parser from exchange import oandapy from logic.candle import Candle from logic import MarketTrend from util.watchdog import WatchDog class OandaPriceStreamer(oandapy.Streamer): def __init__(s...
# coding:utf-8 import os import cv2 import openface import numpy as np import math import base64 from PIL import Image import io import json fileDir = os.path.dirname(os.path.realpath(__file__)) modelDir = os.path.join(fileDir, '..', 'models') dlibModelDir = os.path.join(modelDir, 'dlib') openfaceModelDir = os.path.jo...
import collections import random import flowws from flowws import Argument as Arg import freud import numpy as np from .internal import ScaledMSE, ScaledMAE CoarseSystem = collections.namedtuple('CoarseSystem', ['box', 'nlist', 'positions', 'types', 'type_names', 'child_positions', 'child_types', 'child_type_...
#!/usr/bin/env python import pygame, sys, math, random from pygame.locals import * FPS = 60 MAX_X = 800 MAX_Y = 600 WHITE = (255, 255, 255) GRAY = (128, 128, 128) DARKGRAY = ( 40, 40, 40) BLACK = ( 0, 0, 0) RED = (255, 0, 0) ORANGE = (255, 128, 0) YELLOW = (255, 255, 0) GREEN...
from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy import tensorflow as tf import matplotlib.pyplot as plt import time from tfutil_deprecated import LayerManager flags = tf.app.flags FLAGS = flags.FLAGS flags.DEFINE_integer('max_steps', 100000, ...
#!/usr/bin/python3 #-*-coding:utf-8-*- import os import socketserver import shutil import utils from worker import FileWorker from worker import SockWorker from worker import DataWorker #server:监听端口,[接受]并[处理]目录和文件变动的操作请求 ''' 使用socketserver基类 ''' class FileServer(socketserver.BaseRequestHandler): '''继承一次acc...
# # authors: # <NAME> # # description: # App to read trending hashtags and develop summary of what people are talking about, related # to a given hashtag. # # STD LIB import os import re import sys import glob import argparse import traceback # EXTERNAL LIB import tweepy # PROJECT LIB import gather import puri...
import re, subprocess, boto3, json, shlex, mysql, os, urllib, logging import numpy as np import pandas as pd from pathlib import Path import importlib from mysql.connector import connect, Error # Numpy encoder for JSON from pandas series class NpEncoder(json.JSONEncoder): def default(self, obj): if isinst...
from utils import DotDic import copy import torch import torch.nn as nn from env.switch_riddle import SwitchGame from agent import CNet, DRU, Agent class Arena: def __init__(self, opt, game): self.opt = opt self.game = game self.eps = opt.eps def create_episode(self): opt = self.opt episode =...
import torch import torch.nn as nn from torch.hub import load_state_dict_from_url from .utils.grassmanian_models import ObsMatrixTokenizer from .utils.helpers import pe_check from .utils.tokenizer import Tokenizer from .utils.transformers import TransformerClassifier try: from timm.models.registry import register...
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserve. # # 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...
import datetime import unittest from huey import crontab from huey import exceptions as huey_exceptions from huey import Huey from huey.api import QueueTask from huey.backends.dummy import DummyDataStore from huey.backends.dummy import DummyQueue from huey.backends.dummy import DummySchedule from huey.registry import ...
"""Figure of merit code In general, this module contains components to implement the following flow: + add a column to the fire_events table to store the points projected into the NLCD projection. + create two fire_events_rasters serving as a fire mask for 750m and 375m fire events points. ...
from __future__ import (absolute_import, print_function, division) import copy import time from email.utils import parsedate_tz, formatdate, mktime_tz import Cookie from netlib import encoding from netlib.http import status_codes, Headers, Request, Response, CONTENT_MISSING, decoded from netlib.tcp import Address fr...
"""Classes for describing workflows.""" from hashlib import sha256 from typing import Dict, List, Mapping, Optional, Set, Tuple, Union from mahiru.definitions.identifier import Identifier class WorkflowStep: """Defines a workflow step.""" def __init__( self, name: str, inputs: Dict[st...
import matplotlib matplotlib.use('Agg') # Must be before importing matplotlib.pyplot or pylab! import matplotlib.pyplot as plt import os import argparse import sys import pickle from tqdm import tqdm import numpy as np import torch import torch.nn as nn from torch.utils.data import DataLoader, TensorDataset from tor...
# coding: utf-8 # In[1]: #this is a cross repository project for web scraping #at first, the idea was to get as much info on MENA region as possible #the initial idea was to scrape news from various websites #somehow i realized, many contents were similar #reuters, al jazeera, bbc, cnn, they all covered the major n...
use_tensorboard = True if use_tensorboard: from torch.utils.tensorboard import SummaryWriter writer = SummaryWriter() train_langevine = True mixed_sampling = True import argparse import json import logging import random from datetime import datetime from importlib import import_module from itertools import ...
# A* Implementation # By <NAME> import random import numpy as np # S for start # E for end # ' ' for empty # O for big obstacle (Blocks path) # o for small obstacle (Slows path) # x for path GRID = (('.', '.', '.', '.', '.', '.', '.', 'O', '.', '.', '.', '.', '.', '.', '.', '.', 'O', '.', '.', 'E'), ('.', '.', '....
import scipy.misc import numpy as np import os from glob import glob import imageio import tensorflow as tf import tensorflow.contrib.slim as slim from keras.datasets import cifar10, mnist import matplotlib.pyplot as plt import pickle class ImageData: def __init__(self, load_size, channels, crop_pos='center', z...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models from django.contrib.auth.models import User from base.models import (TimeStampedModel, ) # Create your models here. class Game(TimeStampedModel): # Platforms # Old School ATARI = '2600' SEGA = 'GEN' # Playstation PS =...
# ensemble ''' This script contains functions for performing Dempster-Shafer belief modelling. The intention is to take 2 or more raster / netcdf file inputs, designate each as either belief or disbelief, rescale each to 0-1 range using fuzzy sigmoidals from the canopy module, then output belief, disbelief, plausabilit...
import gc import time import numpy as np import pandas as pd from scipy.sparse import csr_matrix, hstack from sklearn.feature_extraction.text import CountVectorizer from sklearn.preprocessing import LabelBinarizer from sklearn.model_selection import train_test_split import lightgbm as lgb import sys ###Add https://w...
#! /usr/bin/env python import sys import os import logging from datetime import datetime try: from dateutil import parser USE_DATEUTIL = True except ImportError: USE_DATEUTIL = False from pig_util import write_user_exception, udf_logging FIELD_DELIMITER = ',' TUPLE_START = '(' TUPLE_END = ')' BAG_START =...
# -*- coding: utf-8 -*- """ sortedDistance: define function to measure of sortedness of permutations of [0..N-1]. - Cf. http://stevehanov.ca/blog/index.php?id=145 and https://stackoverflow.com/q/8206617 """ from __future__ import division, print_function # Python 2 compatibility __author__ = "<NAME>" __version__ = "...
""" This module abstracts page fetching from the os. It's intended to be used by a memorymanager, so don't use this directly unless you know what you're doing. To use this, call one of the following. allocator.new(pid=yourpid) allocator.new(handle=yourhandle) """ import sys, ctypes integer_types = (int, long) if sys...
import os from os.path import join import colour import cv2 import matplotlib.pyplot as plt import numpy as np import rawpy from scipy import interpolate from sklearn.metrics import mean_squared_error def read_dorf(address): with open(address) as f: lines = f.readlines() curve_name...
"""Main module.""" #Module to test nfcreader API. #Authors: <NAME> and <NAME> #MIT License import sys sys.path.insert(1, './src/') import nfcreader as nfc from datetime import datetime import time import hardware as output import RPi.GPIO as GPIO protocols = ['ISO15693', 'ISO14443-A', 'ISO14443-B', 'ISO18092'] #Protoc...
from copy import copy from math import pow from decimal import Decimal from dateutil.parser import parse from vnpy.api.oanda.const import OandaOrderState, OandaOrderType, OandaOrderPositionFill from vnpy.api.oanda.utils import str2num from vnpy.trader.vtObject import VtOrderData, VtPositionData, VtAccountData, VtCont...
# -*- coding: utf-8 -*- """ Class and functions for a 2D 2-node frame element @author: <NAME>, TU Delft Aerospace, 2019 """ import numpy as np import numpy.linalg as la from ..Materials import linear_elastic class frame2d2elem: """class for frame2d2 element, with components: - cnc_node: nodal con...
#!/usr/bin/env python3 """Checker script for veighty-machinery.""" import os import random import time from typing import Callable, Tuple # Pwntools requires this, otherwise it would complain about the missing terminal os.environ['PWNLIB_NOTERM'] = '5' import pwn from ctf_gameserver import checkerlib import utils fr...
import PySimpleGUI as sg import os,json,sys import pyperclip from scripts.algorithm import MagicMagnet from scripts.settings import Settings import argparse def resource_path(relative_path): try: base_path = sys._MEIPASS except Exception: base_path = os.path.abspath(".") return os.path.joi...
import os import time as ttime from .core import CallbackBase from ..utils import ensure_uid import numpy as np class BrokerCallbackBase(CallbackBase): """ Base class for callbacks which need filled documents Parameters ---------- fields: Iterable of str Names of data field in an Event ...