text
stringlengths
3.07k
12.6k
#!/usr/bin/env python from __future__ import print_function import numpy as np import cv2 """ // // Created by nvidia on 6/18/18. // #define DEBUG #include <opencv2/opencv.hpp> #include "distance.hpp" #include "superpixel_seg.hpp" using namespace cv; using namespace std; const int DST_WIDTH = 800; const int DST_HEI...
#!/usr/bin/env python3 # ######################################################################## # Copyright (c) 2021 Advanced Micro Devices, 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 S...
""" ShadeSketch https://github.com/qyzdao/ShadeSketch Learning to Shadow Hand-drawn Sketches <NAME>, <NAME>, <NAME> Copyright (C) 2020 The respective authors and Project HAT. All rights reserved. Licensed under MIT license. """ import os import numpy as np import tensorflow as tf from model import build_generator, b...
# # General-purpose Photovoltaic Device Model - a drift diffusion base/Shockley-Read-Hall # model for 1st, 2nd and 3rd generation solar cells. # Copyright (C) 2008-2022 <NAME> r.c.i.m<EMAIL>enzie at googlemail.com # # https://www.gpvdm.com # # This program is free software; you can redistribute it and/...
# -*-coding:utf-8-*- import tensorflow as tf import numpy as np from collections import Counter import os import json import time import argparse import librosa parser = argparse.ArgumentParser() parser.add_argument('wav_list', help='wav list file') parser.add_argument('text_file', help='text file') par...
#!/usr/bin/env python3 import logging import datetime import os import os.path import sys from shutil import make_archive import subprocess import smtplib def archive_to_gdrive(mount, root_dir, base_dir, gdrive): # zip file will be temporarily stored in /data base = '/data/' + base_dir zip_file = base + '...
from django.shortcuts import render from django.http import HttpResponse from django.core import serializers from .models import Category from .models import Location from .models import Organization from .models import Address from .forms import LandingPageForm from .forms import ResultsPageForm as filterForm # inde...
""" Variational AutoEncoder ----------------------- """ # Author: <NAME> # License: BSD # The figure produced by this code is published in the textbook # "Statistics, Data Mining, and Machine Learning in Astronomy" (2019) # For more information, see http://astroML.github.com # To report a bug or issue, use the ...
# -*- coding: utf-8 -*- DESCRIPTION = """Collect precision-recall values from best models (using spark)""" import sys, os, time from datetime import datetime from timeit import default_timer as timer try: from humanfriendly import format_timespan except ImportError: def format_timespan(seconds): retur...
import os from pyblinx.tree import Tree from pyblinx.chunk import Chunk from pyblinx.texlist import Texlist from pyblinx.address import section_addresses, rawaddress, find_section from argparse import ArgumentParser from tkinter import Tk, filedialog from struct import unpack from pathlib import Path def m...
from tkinter import * from tkinter.filedialog import asksaveasfilename, askopenfilename from sys import platform import subprocess import os compiler = Tk() compiler.title("CodeIt") compiler.attributes("-fullscreen", False) compiler.configure(bg="#111111") file_path = "" outputStr = "" file_name = "" def set_file_p...
# This source code is part of the Biotite package and is distributed # under the 3-Clause BSD License. Please see 'LICENSE.rst' for further # information. import biotite.structure as struc import numpy as np import pytest @pytest.fixture def atom_list(): chain_id = ["A","A","B","B","B"] res_id = [1,1,1,1,2] ...
import os import os.path as osp import json import torch """ Logger is built to log the information during the model train like loss, accuracy ModelSaver is design to save the state_dict of model, optimizer, scheduler etc safetly Author: <NAME> """ class Logger: def __init__(self, save_path, json_name): ...
from isoweek import Week from flask import Blueprint, jsonify, g, request from app.helpers import api_error_helpers, session_helper, req_helper from app.models.util import ( user as user_util, join_token as join_token_util, schedule as schedule_util, ) bp = Blueprint("api.user", __name__) @bp.route("/<...
from typing import Set, Tuple from sklearn.ensemble import RandomForestRegressor from sklearn.decomposition import PCA from sklearn.neighbors import KNeighborsRegressor from popsicle.ml_utils.weights_tuner import WeightsTuner from popsicle.ml_utils.data_set import DataSet from popsicle.ml_utils.ml_utils import regr_sco...
""" Celery Tasks """ import logging import os import time from collections import namedtuple from typing import TYPE_CHECKING from .worker import celery from .config import BOT_NAME, BOT_EMAIL from .. import utils from ..recipe import Recipe from ..githandler import TempGitHandler from ..githubhandler import CheckRun...
from rest_framework import serializers from django.apps import apps from .models import (ArticleModel, FavoriteArticleModel, BookmarkArticleModel, TagModel, CommentHistoryModel, CommentModel, ReadStatsModel) from fluent_comments.models import FluentComment from .utils import us...
# # MythBox for XBMC - http://mythbox.googlecode.com # Copyright (C) 2011 <EMAIL> # # 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 2 # of the License, or (at your option) a...
from src.utils.split import Split import pytorch_lightning as pl from pytorch_lightning.callbacks import ModelCheckpoint import torch import webdataset as wds from src import constants from src.model.config import Config, Input, ALL_CONFIGS from src.model.model import Model from src.utils.run_once import run_once impor...
import numpy as np import os from OpenGL import GL import Op import ISCV import cv2 from UI import QGLViewer # from UI.QGLViewer import PaintOptions from PIL import Image, ImageMath from time import time from StringIO import StringIO class SkelToImg(Op.Op): def __init__(self, name='/SkelToImg', locations='', calib...
#!/usr/bin/env python3 # -*- coding:utf-8 -*- from typing import List import sys import colorsys def usage(prog: str): print("Usage: %s color1[,color2[...]] [modify1 [modify2 [...]]]" % prog) args = """Arguments: colorX: hex color code (eg. 3a2f12) modifyX: how to change color modifyX[0]: ...
#coding :utf-8 # # The MIT License (MIT) # # Copyright (c) 2016-2018 yutiansut/QUANTAXIS # # 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 th...
from django.shortcuts import render, redirect from django.urls import reverse_lazy from django.http import HttpResponseRedirect from django.contrib.auth.mixins import UserPassesTestMixin, LoginRequiredMixin from django.views import View from .models import Image, UserProfile, Comment from .forms import PostForm, Commen...
from twisted.plugin import IPlugin from twisted.words.protocols import irc from txircd.config import ConfigValidationError from txircd.module_interface import Command, ICommand, IModuleData, ModuleData from txircd.modules.xlinebase import XLineBase from txircd.utils import durationToSeconds, ircLower, now from zope.int...
""" redis.py Copyright 2021. All Rights Reserved. Created: May 23, 2021 Authors: <NAME> """ import typing import redis import numpy as np class StringStream: def __init__(self, buffer: bytes): self._buffer = buffer self._idx = 0 def getbuffer(self) -> bytes: return self._buffer[se...
import inspect import new from functools import wraps from logging import getLogger from os import environ from typing import Optional from roro_ioc.ast_injection import rewrite_ast from roro_ioc.container import IOCContainer from roro_ioc.exceptions import NoSourceForArgument, NoDefaultValueForArgument, DoubleProvid...
#!/usr/bin/env python """ Functions to train autoencoder model. """ import os import argparse import time import tensorflow as tf import numpy as np from PIL import Image from random import shuffle from tensorflow.python.keras import callbacks as cbks from utils import save_images def gen(inputdir, batch_size): ...
import os import numpy as np import torch import torch.nn as nn import torch.optim as optim from torch.utils.data import DataLoader from pytorch_datagenerator import DataGenerator from dataset import Dataset class NNModel(nn.Module): def __init__(self): super().__init__() layers = [] #VGG...
# # Copyright 2020- IBM Inc. All rights reserved # SPDX-License-Identifier: Apache2.0 # """ This module allows verifying a set of network policies against a set of baseline rules """ import argparse import subprocess import os import sys import json from dataclasses import dataclass from pathlib import Path from urll...
from tkinter import * from tkinter import ttk from tkinter import messagebox GUI = Tk() GUI.title('โปรแกรมคำนวณ Beam') GUI.geometry('500x500') ######################################## def Math_additional(): GUI2 = Toplevel() GUI2.title("หน้าต่างคณิตศาสตร์") GUI2.geometry('500x400') de...
#%% """ Runs neural network on data in folder 'Data/Training_Data_and_labels' In contrast to the equivalent scripts in folder JupyterNotebooksForGoogleColab these are meant to be run directly on a local computer. Adapted from 'main.py' on 2019-08-14 by <NAME>. Uses parameters guessed manually, without using Talos. """...
import random import sys sys.setrecursionlimit(2500) class UFDS: def __init__(self,d): a=list(d.keys()) c=[i.split('-') for i in a] s=set() for i in c: s.update(i) b=list(s) self.u=[{i} for i in b] def find(self,x): for i ...
from typing import Optional, Union import numpy as np from pyvista import MultiBlock, PolyData, UnstructuredGrid from ..models import collect_model, multiblock2model from .utils import _interactive_plotter ################################## # Picking by entering parameters # ################################## def ...
import pandas as pd from ccxt import okex3 import time from multiprocessing.dummy import Pool as ThreadPool from datetime import datetime, timedelta from pathlib import Path from concurrent.futures import ProcessPoolExecutor pd.set_option('expand_frame_repr', False) exchange = okex3() contracts = exchange.futuresGetI...
from datetime import datetime import math import sys import io import logging import numpy as np import pandas as pd def log(log_str) : api.logger.info(log_str) api.send('log',log_str) def on_input(msg): att = dict(msg.attributes) interval_width = api.config.interval_width * 60 header ...
"""An implementation of SegNet (and Bayesian alternative).""" from keras.applications.vgg16 import VGG16 from keras.layers import Activation from keras.layers import BatchNormalization from keras.layers import Conv2D from keras.layers import Dropout from keras.layers import Input from keras.layers import Lambda from ke...
from edgar_importing import db import socket import datetime import time import sqlalchemy import argparse import logging import json import urllib2 def parse_args(): parser = argparse.ArgumentParser(description='''Sends vettings to ALA when they are added, modified, or deleted.''') parser.add_argumen...
from pysat.solvers import Solver from pysat.card import * from pysat.formula import CNF import math #extracts a sudoku solution(in list of list format) from given model def get_ans(model,ans,k): model=[ele for ele in model if ele>0] fac=10**(int(math.log10(k*k)+1)) for i in model: value=i...
""" Copyright start Copyright (C) 2008 - 2020 Fortinet Inc. All rights reserved. FORTINET CONFIDENTIAL & FORTINET PROPRIETARY SOURCE CODE Copyright end """ import validators, requests, json import base64 from connectors.core.connector import get_logger, ConnectorError logger = get_logger('FortiAuthenticator')...
## @file reactionT.py # @author Aditya # @brief This file contains the ReactionT # Online citation: https://stackoverflow.com/questions/45220032/how-to-balance-a-chemical-equation-in-python-2-7-using-matrices from MoleculeT import * from ChemTypes import * from ChemEntity import * from Equality import * from ElmSe...
n=3 mat=[['.']*n for i in range(n)] win_list=[[1,2,3],[4,5,6],[7,8,9],[1,4,7],[2,5,8],[3,6,9],[1,5,9],[3,5,7]] #主函数:通过调用get_move,让两位玩家X和O交替落子 def main(): r=c=0 num_moves = 0 print_mat() print('Move are r,c,or "0" to exit') exit_flag = False while not exit_flag: num_moves += 1 i...
## This is really the Controller part of MVC. Yes this is weird. Very weird. from django.shortcuts import render from django.utils import timezone from django.http import HttpResponseRedirect, HttpResponse from .forms import * from .models import * from linkedin.linkedin import (LinkedInAuthentication, LinkedInApplicat...
import os import glob import json from numba import njit import xml.dom.minidom from xml.dom import minidom path = "F:\\0903modeldata\\labels\\" img_list = glob.glob(path + "*.json") width = 0 height = 0 # 自行填写当前文件夹,假如文件路径分割数组长度为1 folder = "" def get_annotation(labels): res = [] for i in ran...
### # Copyright (c) 2012, <NAME> # Copyright (c) 2020, oddluck <<EMAIL>> # 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 noti...
def mergesort(arr, key): if len(arr) < 2: return arr mid = len(arr) // 2 print(arr) left = arr[:mid] right = arr[mid:] mergesort(left, key) mergesort(right, key) i = j = k = 0 while i < len(left) and j < len(right): if key(left[i]) < key(right[j]): arr...
from tkinter import * import tkinter.messagebox from random import randrange # ------------------------------------------------------------------------------------------------------------------ def up(event): """ Fonction appelée quand la touche 'z' est pressée, elle définie la direction du serpent sur 'up...
''' Author : <NAME> ''' import random import time import re import datetime from gtts import gTTS import os from pygame import mixer dict = {":)": "happy", ":'(": "sad", "<3": "romantic", ":/": "unsure", ":*": "kiss", "o.O": "confused", ">:O": "upset", "(y)": "Like"} mood_che = ["happy", "sad", "ro...
from itertools import cycle import numpy as np from adapt.strategy.strategy import Strategy class DLFuzzRoundRobin(Strategy): '''A round-robin strategy that cycles 3 strategies that suggested by DLFuzz. DLFuzz suggest 4 different strategy as follows: * Select neurons that are most covered. * Select neurons...
import random import itertools from copy import deepcopy import pandas as pd import numpy as np import sqr.core.network import sqr.core.algorithm import sqr.core.distance from sqr.core.config import mean_cols, minimum_cols, years def internal_trades(df,G,in_partition,p_lookup, check_cells, unassi...
#!/usr/bin/env python """ Blast XML parser that extracts the best hits for each query sequence and presents the results in order by e-value in tab-separated format Author: <NAME> Email: <EMAIL> Copyright 2014 <NAME> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in ...
import tensorflow as tf import numpy as np from RsNet.dataset_nn import model_mnist_meta from RsNet.tf_config import CHANNELS_LAST, CHANNELS_FIRST def optimize_linear(grad, eps, ord=np.inf): """ Solves for the optimal input to a linear function under a norm constraint. Optimal_perturbation = argmax_{eta, ...
# This file contains the functions needed for solving the Stokes system. from params import rho_i,g,tol,B,rm2,rho_w,C,eps_p,eps_v,dt,quad_degree,Lngth,sigma_0,Hght,dim from boundary_conds import mark_boundary,apply_bcs from geometry import bed,s_mean0,lake_vol_0 from hydrology import Vdot import numpy as np from dolfi...
import copy import pytorch_lightning as pl import torch from torch import nn, optim from torch.nn import functional as F from GAT.model import GAT from libs import utils from TCN.model import TemporalConvNet from libs.utils import StandardScaler def clones(module, N): "Produce N identical layers." return nn...
# Copyright 2020 Dakewe Biotech Corporation. 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...
# -*- coding: utf-8 -*- """ reNamer, Author <NAME>(https://github.com/Eshleron/reNamer) Requirements: - json - os - pathlib - random - sys - time - PyQt5 Python: - 3.5.4 This file (reName.py) is part of reNamer. """ import json import os from pathlib import Path import random import sys import time...
#!/usr/bin/python """ Summary: One function assigning a palette to input values. Two functions to make correlation plots. You can use either. As for the inputs for plot_correlation_matrix, you can generate a correlation plot each for signal/background: corr = signal_df.drop(['Signal_Indicator', 'Background_Indicato...
import os.path from django.utils.translation import ugettext_lazy as _ from django.db import models from django.contrib.auth.models import User from tinymce import models as tinymce_models class Region(models.Model): ''' One region of RF''' class Meta(): ordering = ['order'] verbose_name = _...
from django.http.response import HttpResponseRedirect from django.shortcuts import render,redirect from django.contrib.auth.models import User from django.core.exceptions import ObjectDoesNotExist from django.http import Http404,JsonResponse from django.contrib import messages from django.contrib.auth.decorators import...
""" Cost model optimizer based on reinforcement learning """ import heapq import logging import time import numpy as np import tensorflow as tf from ..util import sample_ints from .model_based_tuner import ModelOptimizer, knob2point, point2knob from .reinforcement_learning import ppo_core logger = logging.getLogger...
"""predefined_gates.py - defines ultrasonic 'gate' functions (offset windows) from SciPy's built-in scipy.signal windows <NAME> (TRI/Austin, Inc.) """ __author__ = '<NAME>' from models.ultrasonicgate import UltrasonicGate import scipy.signal class Boxcar(UltrasonicGate): """Wrapper for the boxcar window functio...
import csv import numpy as np import emoji import pandas as pd import matplotlib.pyplot as plt from sklearn.metrics import confusion_matrix emoji_dictionary = {"0": "\u2764\uFE0F", # :heart: prints a black instead of red heart depending on the font "1": ":baseball:", "2": ":...
#!/usr/bin/env python from __future__ import print_function import base64 from time import sleep from datetime import date, time import ConfigParser from selenium import webdriver from selenium.common.exceptions import NoSuchElementException from selenium.webdriver.common.by import By from selenium.webdriver.support...
# -*- coding: utf-8 -*- import random from collections import deque import matplotlib.pyplot as plt import numpy as np from keras.backend import mean, max, expand_dims from keras.layers import Dense, Activation, Input, Lambda from keras.models import Model from keras.optimizers import Adam from Highlights import repl...
# by @knight_errent # Now will be used in jackzbot too.... import asyncio import datetime from datetime import datetime from telethon import events from telethon.tl import functions, types from userbot import CMD_HELP from userbot.utils import admin_cmd global USER_AFK # pylint:disable=E0602 global afk...
import collections from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.utils.functional import cached_property from django.utils.translation import ugettext_lazy as _ from cms.app_base import CMSAppConfig, CMSAppExtension from cms.models import PageContent, Placeholder...
import tensorflow as tf import numpy as np import sklearn as sk import pandas as pd class _Dataset(): """ Docstring for Dataset class used interanlly for managing our data class variables: X : features array """ def __init__(self,classification=True,y_dim=1, classes=[]): #...
#!/usr/bin/env python # encoding: utf-8 """A regex based mock generator from .h header files.""" import logging import re import typing import click __version__ = "0.5" # UPDATE setup.py when changing version. __author__ = "elmotec" __license__ = "MIT" log = logging.getLogger(__name__) class MockMethod(typing....
import datetime import tensorflow as tf import os import scipy.io as sio import numpy as np import matplotlib.pyplot as plt from nn.td_prediction_lstm_V3 import td_prediction_lstm_V3 from nn.td_prediction_lstm_V4 import td_prediction_lstm_V4 from utils import handle_trace_length, get_together_training_batch, compromise...
#!/usr/bin/env python3 # Copyright 2018 HTCondor Team, Computer Sciences Department, # University of Wisconsin-Madison, WI. # # 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....
import logging import sys import shutil import hashlib import json from unittest import TestCase from unittest import mock from ansit.environment import ( Environment, Drivers) from ansit.manifest import Manifest from ansit.util import read_yaml_file from ansit import drivers logging.basicConfig(level=loggin...
# lightly adapted from https://github.com/pyro-ppl/pyro/blob/dev/pyro/nn/auto_reg_nn.py from __future__ import absolute_import, division, print_function import numpy as onp from jax import random import jax.numpy as np from numpyro.contrib.nn.masked_dense import MaskedDense def sample_mask_indices(input_dim, hidd...
from __future__ import unicode_literals import json from datetime import date import locale import frappe import random import string import requests import pandas as pd from datetime import datetime, timedelta from bs4 import BeautifulSoup def random_string(string_length=8): letters = string.ascii_lowercase retur...
import py from pypy.rpython.rmodel import inputconst from pypy.rpython.lltypesystem import lltype, llmemory from pypy.rpython.lltypesystem.rclass import InstanceRepr from pypy.rpython.lltypesystem.rvirtualizable import VABLERTIPTR class VirtualizableAccessor(object): def initialize(self, STRUCT, redirected_field...
# -*- coding: utf-8 -*- # @Author: rishabh # @Date: 2018-02-15 04:43:40 # @Last Modified by: <NAME> # @Last Modified time: 2018-06-15 19:48:42 ''' MIT License Copyright (c) 2018 <NAME> ''' ### Basic Python modules and Pytorch imports import utils import classifier import time import torch from torch import nn,...
#!/usr/bin/python # Copyright: (c) 2019, OVH SAS # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type DOCUMENTATION = r''' --- module: vmware_vsan_health_info short_description: Gather infor...
# The MIT License (MIT) # Copyright (c) 2021-present vcokltfre & tag-epic # 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...
#----------------------------------------------------------------------------- # compare_character.py # Checks an extracted character's graphics to see what's changed between # versions #----------------------------------------------------------------------------- import getopt import hashlib import os.path import pat...
"""Code for explicit (tabular) construction on product dynamics.""" from __future__ import annotations import random from typing import Any, Iterable, Mapping, Protocol, Optional, Sequence, Union from typing import cast from uuid import uuid1 import attr import networkx as nx import numpy as np from diss import Edg...
# Copyright (c) Facebook, Inc. and its affiliates. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. # import datetime as dt import torch import numpy import pandas as pd from tqdm import tqdm from .sem import ChainEquati...
#!/usr/local/bin/python3.4 import os, sys, logging, json, argparse, time, requests, uuid from datetime import datetime from orchestrator import orchestrator as orch from database import database as db from config_files import settings def slice_event_loop(slice_event_filter, poll_interval): while True: f...
import environ import datetime import time import logging import pytz import pprint from django.conf import LazySettings from django.core.mail import EmailMultiAlternatives from django.template.loader import render_to_string from django.utils.html import strip_tags from ..taskapp.celery import app from alpha_vantage.ti...
import torch from torch.autograd import grad, Variable import numpy as np from numpy import linalg as LA import random import time from sklearn.model_selection import train_test_split from sklearn.linear_model import Ridge, RidgeClassifier from copy import deepcopy from contextlib import contextmanager def set_seeds(s...
from typing import Any, Callable, Dict, List, Tuple, TypeVar, Union # noqa from urllib.parse import quote from werkzeug.datastructures import Headers as WerkzeugHeaders from werkzeug.datastructures import ( EnvironHeaders, ImmutableDict, ImmutableHeadersMixin, ImmutableMultiDict ) from werkzeug.urls import url_de...
# This file is part of Buildbot. Buildbot is free software: you can # redistribute it and/or modify it under the terms of the GNU General Public # License as published by the Free Software Foundation, version 2. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without eve...
from dataclasses import dataclass from sqlalchemy import ( Column, String, Integer, Float, Boolean, create_engine, Binary, ) from sqlalchemy.types import Enum import uuid from newsbot.core.constant import SourceName, SourceType from newsbot.core.sql import Base class Articles(Base): __t...
#! /usr/bin/python3 import sys import os import tempfile import shutil import runpy import subprocess import pwd import pathlib import delectable.dlct as dlct def find_output_file(output_folder_path, output_file_extension) : names_of_matching_files = find_files_matching_extension(output_folder_path, output_file_e...
import os import re import json import asyncio import discord import requests from discord import utils from discord.ext import commands, tasks config_file_location = "config/config.json" sc_file_location = "config/secret_config.json" with open(config_file_location, "r") as config_file: config = json.load(config_...
#!/usr/bin/env python # Copyright (c) 2015 <NAME> (<<EMAIL>>) # # 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, mo...
from brushfire.utils import quote_string def field(x): return "field(%s)" % str(x).encode('utf-8') def ord(x): return "ord(%s)" % str(x).encode('utf-8') def rord(x): return "rord(%s)" % str(x).encode('utf-8') def sum(*args): return "sum(%s)" % ','.join([str(x).encode('utf-8') for x in args]) def su...
import logging from urllib.parse import urljoin from django import template from django.conf import settings from django.db.models.fields.files import ImageFieldFile from django.templatetags.static import static from django.utils.translation import get_language from .models import SEOPath logger = logging.getLogger...
from math import floor # given list_tuples as a parameter, this function skims double coordinates (putting them in a set) AND split them # in two different coordinates # list_tuples is a list of tuples like this: ((w-1, w), h). # Semantically a tuple expresses two coordinates: (w-1, h) e (w, h) def _get_set_coordinat...
# -*- coding: utf-8 -*- # mathtoolspy # ----------- # A fast, efficient Python library for mathematically operations, like # integration, solver, distributions and other useful functions. # # Author: sonntagsgesicht, based on a fork of Deutsche Postbank [pbrisk] # Version: 0.3, copyright Wednesday, 18 September 20...
# updated Nov 10, 2020 # load libraries from __future__ import print_function from scipy.spatial import ConvexHull from skimage.transform import downscale_local_mean from matplotlib.patches import Polygon from matplotlib.collections import PatchCollection from skimage.measure import regionprops import numpy as np imp...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2021/4/12 0012 10:20 # @Author : <NAME> # @Site : # @File : sif_model.py # @Software: import os import json import numpy as np from sklearn.decomposition import TruncatedSVD import data_preprocess SIF_HPARA_A = 1e-3 SIF_HPARA_RMPC = 1 INS_DICT_PATH = './ins_d...
# MIT License # # Copyright (c) 2021 <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 rights # to use, copy, modify, merge, publi...
"""rio_viz.raster: raster tiles object.""" from typing import Any, Dict, BinaryIO, Tuple, Union, Sequence import re from pathlib import Path from functools import partial from concurrent import futures import numpy import rasterio from rasterio.warp import transform_bounds from rio_tiler import reader from rio_til...
import time import argparse from concurrent.futures import ThreadPoolExecutor as ThreadPool import numpy as np from pathlib import Path from fastapi import FastAPI from fastapi.responses import FileResponse, RedirectResponse from fastapi.middleware.cors import CORSMiddleware from fastapi.staticfiles import StaticFiles...
import torch from . import networks from . options import Options from . UNET import UnetRenderer # from UNET import UnetRenderer # import networks # from options import Options import os import torch.nn as nn from PIL import Image import numpy as np import torchvision.transforms as transforms import pickle as pkl impo...
import logging import typing from math import ceil import numpy as np from riptide.clustering import cluster1d from riptide.timing import timing log = logging.getLogger('riptide.peak_detection') class Peak(typing.NamedTuple): """ A simple NamedTuple with the essential parameters of a peak found in a...
""" Author: <NAME> Description: Markowitz Efficient Frontier Portfolio Optimization using Python """ # import needed modules import pandas as pd import numpy as np import matplotlib.pyplot as plt import pandas_datareader.data as web import datetime as dt import sys import os from dateutil.relativedelta import rela...