text stringlengths 3.07k 12.6k |
|---|
"""Load serialized policies of different types."""
import logging
import os
import pickle
import sys
import stable_baselines
from stable_baselines.common import vec_env
import tensorflow as tf
from aprl.envs.gym_compete import load_zoo_agent
from aprl.envs.multi_agent import FakeSingleSpacesVec
from aprl.policies.ba... |
#!/usr/bin/env python3
from matplotlib.lines import Line2D
import matplotlib.pyplot as plt
import numpy as np
import torch
# reference: https://stackoverflow.com/questions/64554658/calculate-covariance-of-torch-tensor-2d-feature-map
def cov(x, rowvar=False, bias=False, ddof=None, aweights=None):
"""Estimates cova... |
# -*- coding: utf-8 -*-
import os
import time
import json
import argparse
import datetime
import logging
import os
import random
import ssl
import time
import jwt
import paho.mqtt.client as mqtt
PROJECT_ID = os.environ.get('GOOGLE_IOT_PROJECT')
CLOUD_REGION = os.environ.get('GOOGLE_IOT_REGION')
REGISTRY_ID = os.envi... |
import numpy as np
import os
import scipy.misc
import chainer
import utils
class Iterator(chainer.dataset.Iterator):
"""
Iterator that calls self.dataset.get_random_batch at each iteration. Epoch is not used.
"""
def __init__(self, dataset, batch_size, repeat=True, shuffle=True):
self.datas... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# This file is part of "Linux Studio Installer" project
#
# Author: <NAME> <<EMAIL>>
# License: MIT License
#
# SPDX-License-Identifier: MIT
# License text is available in the LICENSE file and online:
# http://www.opensource.org/licenses/MIT
#
# Copyright (c) 2020... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from six.moves import xrange # pylint: disable=redefined-builtin
import model
from datetime import datetime
import numpy as np
import os
import time
import tensorflow as tf
FLAGS = tf.app.flags.FLAGS
tf.ap... |
import sys
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn import preprocessing
def generate_fullstats(dataset_path, filelist, targets, target_col_name='Target'):
"""
Generates single csv of all statatistics from list of files
Parameters
--------... |
"""Helpers for building Dash applications."""
from contextlib import ContextDecorator
import dataset
import pandas as pd
from .utils_data import SQLConnection, uniq_table_id, write_csv
# ----------------------------------------------------------------------------------------------------------------------
# dataset
... |
# -*- coding: utf-8 -*-
"""
Created on Fri Nov 23 01:42:00 2018
@author: Prashant
"""
import os
import sys
import mistune
from PyQt5 import QtWidgets, QtWebEngineWidgets
from PyQt5.QtWidgets import QFileDialog, QDialog
from PyQt5 import uic
from PyQt5.uic import loadUi
from pygments import highlight
from pygments.le... |
# This parameter file contains the parameters related to the primitives located
# in the primitives_ghost_spect.py file, in alphabetical order.
from gempy.library import config
from geminidr.core import parameters_ccd, parameters_visualize, parameters_preprocess
from astrodata import AstroData as ad
def arcs_valueC... |
import math
import importlib
from django.conf import settings
from django.contrib.auth.models import AnonymousUser, User
try:
from urllib.parse import urlencode
except ImportError:
from urllib import urlencode
from django.views.generic import View
from django.shortcuts import redirect, render
from django.htt... |
from disnake import Forbidden, RawReactionActionEvent
from disnake.ext.commands import Cog
from bot import Omnitron
from data import Utils, Xp_class
class Events(Cog, name="events.on_raw_reaction_add"):
def __init__(self, bot: Omnitron):
self.bot = bot
self.xp_class = Xp_class(bot)
@Cog.list... |
"""
pyProm: Copyright 2016.
This software is distributed under a license that is described in
the LICENSE file that accompanies it.
This library contains a Perimeter container class for storing GridPoints
type location objects. and various transforms.
"""
from collections import defaultdict
from .base_self_iterable i... |
import os
import sys
import unittest
from io import StringIO
from typing import NamedTuple, List, TextIO, Dict
import requests
from dict_compare import compare_dicts
from jsonasobj import loads as jao_loads
from pyjsg.jsglib import loads as jsg_loads
from pyjsg.jsglib.loader import is_valid
from ShExJSG import ShExJ,... |
import numpy as np
from PIL import Image
import time
def cal_distance(a, b, A_padding, B, p_size):
p = p_size // 2
patch_a = A_padding[a[0]:a[0]+p_size, a[1]:a[1]+p_size, :]
patch_b = B[b[0]-p:b[0]+p+1, b[1]-p:b[1]+p+1, :]
temp = patch_b - patch_a
num = np.sum(1 - np.int32(np.isnan(temp)))... |
# ==================================================================================================
# Copyright 2015 Twitter, Inc.
# --------------------------------------------------------------------------------------------------
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use thi... |
from tqdm import tqdm
import string
import copy
import numpy as np
zimu2inds = {z: i for i, z in enumerate(list(string.ascii_lowercase))}
zimu2inds['0'] = 26
def zimu2ind(zimu):
"""
'0' for the start of the sequence. Only applied in del_matrix.
"""
return zimu2inds[zimu]
def edit_distance(str1, str... |
import os
import json
import math
import random
import datetime
from decimal import Decimal
from dateutil.tz import gettz
from dateutil.relativedelta import relativedelta
import logging
import send_message
from common import (utils, line)
from validation.members_card_param_check import MembersCardParamCh... |
#!/usr/bin/env python
# created by <NAME> on 17-11-26
from inspect import signature
from pylimit.limit_error import LimitError
import functools
def check_type(value, type1):
"""
判断两个类型是否一致
:param value:
:param type1:
:return: bool
"""
if not isinstance(value, type1):
raise LimitE... |
""" igraph interface
BEFORE ADDING ANYTHING, SEE IMPORT HIERARCHY IN __init__.py!!!!
"""
import itertools
import igraph
from phydat import ptab
from automol.util import dict_
from automol.graph.base._core import from_atoms_and_bonds
from automol.graph.base._core import atoms
from automol.graph.base._core import bonds... |
from dataclasses import dataclass, astuple
from itertools import combinations
from typing import List
import numpy as np
from qanom.annotations.decode_encode_answers import Argument, Role
MATCH_IOU_THRESHOLD = 0.3
@dataclass
class Metrics:
true_positive: int
false_positive: int
false_negative: int
... |
from ._ffi import *
from ctypes import *
from wasmtime import Store, FuncType, Val, Trap, Extern
import sys
import traceback
dll.wasm_func_new_with_env.restype = P_wasm_func_t
dll.wasmtime_func_new_with_env.restype = P_wasm_func_t
dll.wasm_func_type.restype = P_wasm_functype_t
dll.wasm_func_param_arity.restype = c_siz... |
# Python packages
import os
# 3rd party packages
from sanic.response import redirect
from sanic.response import file_stream
from sanic_motor import BaseModel
from sanic import Blueprint
from sanic.response import text
import aiofiles
from uuid import uuid4
from pymongo import ReturnDocument
file_bp = Blueprint('file_... |
import mysql.connector
import requests
import datetime
import json
import sys
from mysql.connector import Error
def connectToDB(hostName, db, name, passCode):
conn = mysql.connector.connect(host= hostName,
database= db,
user= name,
... |
import numpy as np
from dowel import tabular
from garage.np import discount_cumsum
from garage import StepType
class ExpAvg:
def __init__(self, rate=1e-3, scale_target=1):
self._x = 0
self._x2 = 0
self._rate = rate
self._itr = 0
self._scale_target = scale_target
def u... |
import base64
import requests
import datetime
import hashlib
import struct
import json
import time
import os
from .rate_limited import rate_limited
class OsuApiv1Error(Exception):
pass
class OsuApiv1():
REPLAY_RATE_FETCHING_LIMIT = 10 # seconds
'''
Returns the LZMA stream containing the cursor... |
import time
from datasets import create_dataset
from modules import create_model
from utils.visdom.visualizer import Visualizer
from utils import startup
import os
import utils.tools as util
import numpy as np
import evaluation
def train(config):
dataset = create_dataset(config)
model = create_mode... |
# This aggregates the Table data from the scrapers and creates journals
# Also writes data to a file for accurate record keeping.
import json
import datetime
import time
import os
import sys
import argparse
import FilfoxScraper
import Addresses
import coingeckoScraper
import xeroAccounts as xa
import data_folders
try... |
# import keyboard
import pyaudio
import wave
import matplotlib.pyplot as plt
import librosa.display
import librosa
import numpy as np
import math
import moviepy.editor as mp
from io import BytesIO
sr1=0
sr2=0
sr3=0
sr4=0
sc1=0
sc2=0
sc3=0
sc4=0
x1=0
x2=0
x3=0
x4=0
def process_stop():
global isStop
isStop = ... |
# -*- coding: utf-8 -*-
import torch
from torch import cuda
import torch.nn.functional as F
from nltk.translate.bleu_score import sentence_bleu
from nltk.translate.bleu_score import SmoothingFunction
from utils.dataset import collate_fn
from transformers.modeling_bart import make_padding_mask
device = 'cuda' if cu... |
import torch
# import torch.nn as nn
import numpy as np
from .modules import Scale, Bias
import itertools
__all__ = ['FixUpResNet', 'fixup_resnet20', 'fixup_resnet32', 'fixup_resnet44',
'fixup_resnet56', 'fixup_resnet110', 'fixup_resnet1202']
def conv3x3(in_planes, out_planes, stride=1):
"""3x3 convol... |
# This file contains utilities specific to the homework's 4 functionalities to be implemented, e.g. for plotting data
from typing import Optional
from IPython.display import display
import pandas as pd
import networkx
from graph_utils import Graph
def functionality_1():
"""
Implements the frontend for the f... |
from tkinter import *
from tkinter import messagebox
import backend
def get_selected_row(event):
try:
global selected_tuple
index=list1.curselection()[0]
selected_tuple=list1.get(index)
e1.delete(0,END)
e1.insert(END,selected_tuple[1])
e2.delete(0,END)
e2.ins... |
# type: ignore
from __future__ import annotations
from collections import namedtuple
from math import sqrt
from typing import List, Callable, Iterator, Optional, Iterable, Tuple, TypeVar, Set
from toolz import compose, identity, first, last, get_in
from aoc2020.shared.models import NoResultFoundException
from aoc20... |
#!/usr/bin/env python
# * coding: utf8 *
'''
datatable.py
A module that reads the stewardship spreadsheet and builds the sgid index page
'''
from collections import OrderedDict
from os import rename
from os.path import dirname, join
import re
import pygsheets
#: from pydash.strings import start_case
def munge_data... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import... |
import numpy as np
from astropy.io import fits
import os
import argparse
import logging, traceback
from config import quad_dicts, EBINS0, EBINS1, drm_quad_dir
from sqlite_funcs import get_conn, append_rate_tab
from dbread_funcs import get_info_tab, guess_dbfname, get_files_tab,\
get_twinds_... |
from scipy.io import loadmat
from PIL import Image
import numpy as np
import os
import cv2
def cal_new_size_v2(im_h, im_w, min_size, max_size):
rate = 1.0 * max_size / im_h
rate_w = im_w * rate
if rate_w > max_size:
rate = 1.0 * max_size / im_w
tmp_h = int(1.0 * im_h * rate / 16) * 16
if ... |
import os
import cv2
import numpy as np
from six.moves import cPickle as Pickle
import csv
DATA_FOLDER = 'data'
image_size = 32
pixel_depth = 255
pickle_extension = '.pickle'
num_classes = 48
image_per_class = 500
def get_folders(path):
data_folders = [os.path.join(path, d) for d in sorted(os.listdir(path))
... |
# coding=utf8
import unicodedata
import json
import re
import random
import torch
from torch.autograd import Variable
from custom_token import *
with open('config.json') as config_file:
config = json.load(config_file)
USE_CUDA = config['TRAIN']['CUDA']
DATA_PATH = config['DATA']['PATH']
DIALOGUE_CORPUS = config... |
""" Class for the Sequence to sequence model for ATIS."""
import os
import torch
import torch.nn.functional as F
from . import torch_utils
from . import utils_bert
from EditSQL.data_util.vocabulary import DEL_TOK, UNK_TOK
from .encoder import Encoder
from .embedder import Embedder
from .token_predictor import const... |
"""
qc0.q
=====
Python API for querying data
"""
from __future__ import annotations
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql as sa_pg
from . import syntax
from .scope import Cardinality
from .plan import plan
from .compile import compile
__all__ = ("Q",)
class Q:
""" P... |
import asyncio
import uvicorn
import ray
from ray.experimental.async_api import _async_init
from ray.serve.constants import HTTP_ROUTER_CHECKER_INTERVAL_S
from ray.serve.context import TaskContext
from ray.serve.request_params import RequestMetadata
from ray.serve.http_util import Response
from urllib.parse import p... |
from django.views import View
from coolbeans.app.forms import QuizForm
from coolbeans.app.models.quiz import QuizModel
from coolbeans.app.models.question import MultipleChoiceModel, WordScrambleQuestionModel, WordMatchingModel, GapFillQuestionModel, CrosswordQuestionModel, BaseQuestionModel
from django.shortcuts import... |
import unittest
import getpass
from tabulate import tabulate
from wikifile.utils import Itemize, Link, Widget, Enumerate, MagicWord, Table, SubObject, TemplateParam, SetProperties, \
SwitchFunction
from wikifile.wikiRender import WikiRender
class TestUtilsTemplate(unittest.TestCase):
"""
Test the jinja tem... |
#import typer_async as typer
from typing import Optional
import uvicore
from uvicore import app, db, log
from uvicore.console import argument, click, command, option
from uvicore.support import module
from uvicore.support.dumper import dd, dump
# Commands
# create = typer.Typer()
# drop = typer.Typer()
# recreate = t... |
import json
import os.path
import math
import sys
from os import path
from pathlib import Path
PRINT_PROPS = False
USE_BLENDER = False
try:
import bpy
USE_BLENDER = True
except ImportError:
USE_BLENDER = False
hexes = []
fac_x = 0
fac_y = 0
with open('D:/Planetside2/Builder/indar_zones.txt', 'r') as f:
zones ... |
from pathlib import Path
from unittest import TestCase
import os
from is_domain_free import DomainNameAvailabilityChecker
from is_domain_free import get_tld_from_domain_name
from is_domain_free import WhoisParserBasic
from is_domain_free.exceptions import TldNotSupportedException
def get_domain_file_content(domain_... |
import pygame
import math
import DFS_generator.mazeGenerator as mazeGenerator
import DFS_generator.Controls as Controls
# rysuje koniec labiryntu oraz pozycje gracza
def drawPos(maze, x_0, y_0, radius, offset, screen):
n_fn = maze.finish_cell.x
m_fn = maze.finish_cell.y
x_fn = x_0 + radius * (abs(n_fn) +... |
import logging
from abc import ABC
from datetime import date
from io import StringIO
import pandas as pd
import requests
from adjustapi.model import parse_apps, parse_kpi
class _Api(ABC):
"""
Class that implements HTTP requests
"""
def _get(self, url, params=None, **kwargs):
logging.info(f"... |
import builtins
import warnings
from collections import OrderedDict
from ...utils import bits_for
from ..._utils import deprecated, extend
from ...hdl import ast
from ...hdl.ast import (DUID,
Shape, signed, unsigned,
Value, Const, C, Mux, Slice as _Slice, Part, Cat, Repl... |
from typing import Dict, Any, Optional
from dataclasses import dataclass
from loguru import logger, _Logger # type: ignore
import yaml
import sys
import os
from telegram_clock.exceptions import ConfigError, ProxyConfigError, LoggerConfigError
from telegram_clock.utils import get_config_from_dict_by_key, get_env_vari... |
# coding=utf-8
# Copyright 2021 DeepMind Technologies Limited.
#
# 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 applic... |
# -*- encoding: utf-8 -*-
import ast
# noinspection PyUnresolvedReferences
from six.moves import reduce
class Attribute(object):
def __init__(self, a):
self.ast = a
self._str = self.__recur_construct_str(a)
self._list = self._str.split('.')
def __recur_construct_str(self, value):
... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from . import ... |
import importlib
import re
from functools import lru_cache
from inspect import getsource
from pathlib import Path
from typing import Iterator, Optional, List
from pycaro.api.constants import BUILTIN_OBJECTS
from pycaro.api.files import find_project_root, get_path_from_root, get_absolute_path
from pycaro.api.logger imp... |
import fiducial_data
import tensorflow as tf
def add_variable_summary(tf_variable, summary_name):
with tf.name_scope(summary_name + '_summary'):
mean = tf.reduce_mean(tf_variable)
tf.summary.scalar('Mean', mean)
with tf.name_scope('standard_deviation'):
standard_deviation = tf.sqrt(tf.reduce_mean... |
import pyttsx3
import datetime
import speech_recognition as sr
import wikipedia
import webbrowser
import os
from googlesearch import *
import wolframalpha
engine = pyttsx3.init('sapi5')
voices= engine.getProperty('voices')
engine.setProperty('voice', voices[0].id)
def speak(audio):
engine.say(audio)
engine.... |
# scrape from http://www.enron-mail.com/email/
# <NAME>
import socket
import urllib.parse
import urllib.request
import re
import datetime
from random import shuffle
import dateutil.parser
import json
import os
from sphinx.util import requests
def parse_directory(url, content, check_for_folder_cached, notify_new_fol... |
import sys
import os
import numpy as np
import datetime
import subprocess
from distutils import dir_util
import _sys_init
from lib.functions.anchor_projector import project_to_image_space
def get_kitti_predictions(score_threshold, globl_epoch=-1):
# Get available prediction folders
root_dir = _sys_init.root_d... |
# -*- coding: utf-8 -*-
# Copyright 2020 <NAME>
#
# 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... |
from brick import Brick
from ball import Ball
from paddle import Paddle
marginX = 10
marginY = 16
mode = 'mouse'
dragging = True
nballs_initial = 3
game_state = 'frozen'
state_start_time = 0
def reset_game():
global game_over, nballs, dragging, bricks
game_over = False
nballs = nballs_initial
dragging... |
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.db import models
from django.db.models import Max
from django.utils import timezone
from users.models import User
class Board(models.Model):
owner_model = models.Foreign... |
from datetime import datetime
import os
from typing import Any, Callable, Dict, List, Optional, Union
from filelock import SoftFileLock
from sacred import Experiment
from tinydb import Query, TinyDB
from tinydb_serialization import SerializationMiddleware, Serializer
class ModelExistsError(Exception):
"""excepti... |
import math
import numpy as np
def newCoordFromDelta(lat1, lon1, distKm, bearing):
# bearing is north 0, and goes 0-360
R = 6378.1 #Radius of the Earth in km
brng = np.deg2rad(bearing) #Bearing is 90 degrees converted to radians.
lat1 = math.radians(lat1) #Current lat point converted to radians
lo... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#auther: @_mizumasa
import os
import time
import numpy as np
from multiprocessing import Process
from math import sin,cos
SAMPLE_CODE="""
x = sin(t*0.1) * 50 + 350
y = cos(t*0.1) * 50 + 140
"""
class TOIO_TRACER:
def __init__(self):
self.ac... |
# -*- coding: utf-8 -*-
import sys
from pathlib import Path
from typing import Callable
import pytest
project_dir: Path = Path(__file__).parent.parent.parent
sys.path.insert(0, str(project_dir))
from antarest.core.custom_types import JSON
@pytest.fixture
def ini_cleaner() -> Callable[[str], str]:
def cleaner(t... |
import numpy as np
import matplotlib.pyplot as plt
import numpy as np
import nengo
from nengo.dists import Uniform
from nengo.processes import WhiteNoise
from nengo.processes import WhiteSignal
from nengo.processes import PresentInput
from nengo.utils.matplotlib import rasterplot
#phase automata
# Creates a matrix of... |
#Copyright 2013 <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 later version.
#
#This program is distributed in the hope that it ... |
# -*- coding: utf-8 -*-
"""
Created on 09 Oct 2020 17:27:20
@author: jiahuei
"""
import logging
import torch
import torch.nn as nn
from copy import deepcopy
from argparse import ArgumentParser, _ArgumentGroup
from typing import Optional, Union
from models import register_model
from models import relation_transformer as... |
#!/usr/bin/env python
"""2-Fit_positions.py: Fits geographical positions for Bialek grid data."""
__author__ = "<NAME>"
__license__ = "MIT"
__version__ = "1.1"
__maintainer__ = "<NAME>"
__email__ = "<EMAIL>"
import numpy as np
import scipy.optimize as opt
import matplotlib.pyplot as plt
import networkx as nx
import ... |
# -*- coding: utf-8 -*-
"""
:::::::::::::::::::::::: Critical Infrastructure Cyberspace Analysis Tool (CICAT) :::::::::::::::::::::::::::::::::::::::
NOTICE
The contents of this material reflect the views of the author and/or th... |
from django.shortcuts import render
from django.urls.base import reverse_lazy
# Create your views here.
from catalog.models import Book, Author, BookInstance, Genre
def index(request):
"""View function for home page of site."""
# Generate counts of some of the main objects
num_books = Book.objects.all().count(... |
import uuid
import pytest
from flexmock import flexmock
from freezegun import freeze_time
def make_auth(
sender='Testiclient',
partner_id='xxx_yyy',
partner_key='07f94228d149a96b2f25e3edad55096e',
customer_id='Integr<NAME>',
customer_key='<KEY>',
organization_id='19675... |
__author__ = 'Carrycat'
import json
import time
import uuid
from django.db import transaction
from django.http import HttpRequest
from django.urls import NoReverseMatch
from django.utils import dateformat, timezone
from django.utils.functional import SimpleLazyObject
from jwcrypto import jwt
from jwcrypto.common imp... |
import argparse
import glob
import itertools
import os
import pickle
import random
import re
import numpy as np
import skimage.io
import tensorflow as tf
from video_prediction.datasets.base_dataset import VarLenFeatureVideoDataset
class KTHVideoDataset(VarLenFeatureVideoDataset):
def __init__(self, *args, **kwa... |
#!/usr/bin/env python
################################################################################
# AUTHORS: <NAME> <<EMAIL>>
# <NAME> <<EMAIL>>
#
# DESCRIPTION: This runs an Elastic Net or Lasso Test on wide data
################################################################################
import o... |
import matplotlib.pyplot as plt
from collections import Counter
def make_plot_one_line(plt):
years = [1950, 1960, 1970, 1980, 1990, 2000, 2010]
gdp = [300.2, 543.3, 1075.9, 2862.5, 5979.6, 10289.7, 14958.3]
#create a line chart, years on x-axis, gdp on y-axis
plt.plot(years, gdp, color='green', marker='o', li... |
"""
Helpers to build the Github comment output
"""
import functools
import inspect
import io
import textwrap
from django.db.migrations import Migration
from .github import GithubClient
class ConsoleOutput:
def no_migrations_to_apply(self) -> None:
print("No migrations to apply")
def begin(self, nu... |
# Copyright 2014: Mirantis Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required b... |
import sys
from django import template
from django.contrib.contenttypes.models import ContentType
from django.db.models import Count, Q
from django.http import HttpResponseServerError
from django.shortcuts import get_object_or_404, render
from django.template import loader
from django.template.exceptions import Templa... |
# seed_size_plantcv_analysis.py
# Imports
import os
import argparse
import posixpath
import numpy as np
import cv2
import plantcv as pcv
from plantcv.dev.color_palette import color_palette
def correct_white_background(img):
"""Corrects the background of a mostly white image by setting histogram peak to 255"""
... |
# -*- coding: utf-8 -*-
# 根据皮尔逊相关系数,找出与我相似的用户,再找这些用户最喜欢的电影
# created by 徐智沛 李晓宇 苏正棚 许都礼
# copyright USTC
# 11.29.2020
import json
from math import sqrt
import matplotlib.pyplot as plt
from math import *
import movieRecommend.user_info
sim_person = []
sim_person_data = []
sim_person_sim = []
# 计算皮尔森相似度,返回p1和p2的皮尔逊相关系... |
import poplib
import imaplib
import smtplib
import chardet
import os
from email.mime.text import MIMEText
from email.header import Header
from email.parser import Parser
from email.header import decode_header
from email.utils import parseaddr
from email.mime.application import MIMEApplication
from email.mime.multipart ... |
import json
from base64 import b64encode, b64decode
from collections import namedtuple
from connexion.exceptions import ProblemException
from itertools import product
from skyfield.api import Loader, Topos, EarthSatellite
from home.leaf import LeafPassFile
from flask import request, Response
from home.models import G... |
# Copyright (c) 2017 <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, modify, merge, publish, di... |
import argparse
import json
import os
from glob import glob
from xml.dom import minidom
from xml.etree.ElementTree import ElementTree
import numpy
from PIL import Image
from mung.node import Node
from omrdatasettools.converters.ImageColorInverter import ImageColorInverter
from omrdatasettools.converters.ImageConverter... |
from django.contrib.auth import login
from django.contrib.auth.mixins import LoginRequiredMixin
from django.db import IntegrityError
from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.urls import reverse
from django.views.generic import ListView, CreateView, DetailView
from dja... |
# -*- coding: utf-8 -*-
#
# This file is part of REANA.
# Copyright (C) 2019, 2020, 2021 CERN.
#
# REANA is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""REANA Server Workflow Execution Scheduler."""
import json
import logging
from ... |
"""
FreeSWITCH Dialogflow CX Application
This script interacts with Google Dialogflow CX API via UniMRCP server.
* Revision: 1
* Date: May 7, 2021
* Vendor: Universal Speech Solutions LLC
"""
import xml.etree.ElementTree as ET
from freeswitch import *
class GdfCxApp:
"""A clas... |
# -----------------------------------------------------------------------------
#
#
#
# -----------------------------------------------------------------------------
import re
import ply.yacc as yacc
from .parsing_classes import Var, Indic
import logging
logger = logging.getLogger(__name__)
separators = ['RE-MIN', 'RE... |
import numpy as np
import pandas as pd
from numpy import linalg as LA
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import math
from pypcd.pypcd import PointCloud
from scipy.optimize import minimize
from sklearn.neighbors import NearestNeighbors
from multiprocessing import Pool
from ... |
"""
Modify vq-wav2vec_featurize to use mimic3 pkl dataset
Returns:
[type]: [description]
"""
import pickle
import pprint
import os
import argparse
import torch
import fairseq
import pandas as pd
from icecream import ic
from torch import nn
from torch.utils.data import DataLoader
class ArgTypes:
@staticmetho... |
from sklearn import datasets
import numpy as np
from pandas_ml import ConfusionMatrix
import math
import random
from sklearn.metrics import confusion_matrix
from scipy import stats
#funcao que treina a rede
def perceptron(max_it, alpha, x, d):
#numero de saidas da rede
num_saidas = 3
# numero de atributo... |
# -*- coding: utf-8 -*-
"""
Module implementing MainWindow.
"""
import ctypes, struct
import os, configparser, time, threading
from PyQt5.QtCore import pyqtSlot
from PyQt5.QtWidgets import QMainWindow, QFileDialog
from PyQt5 import QtWidgets, QtCore
from Ui_JLink_RTT import Ui_MainWindow
class SeggerRttBuf(objec... |
import numpy as np
import quantities as pq
import sys, os
import tempfile
import scipy
try:
import cPickle
except:
import pickle as cPickle
class TestCache():
pickle_dir = None
cache = {}
def __init__(self):
self.pickle_dir = tempfile.gettempdir()
def get(self, key)... |
import configparser
import requests
import time
import json
from datetime import datetime
config = configparser.ConfigParser()
config.read("config.ini")
API_URL = config['DEFAULT']['API_URL']
USERNAME = config['DEFAULT']['API_USERNAME']
PASSWORD = config['DEFAULT']['API_PASSWORD']
API_TOKEN = None
sensor_type_meta... |
import tensorflow as tf
import numpy as np
from skimage import io
import os
import threading
from libExtractTile import getNotEmptyTiles
feature_description = {
'image': tf.io.FixedLenFeature([], tf.string),
'size': tf.io.FixedLenFeature([4], tf.int64),
}
def getTfRecordDataset(tfRecordPaths):
... |
from __future__ import print_function
from os import makedirs
# To change this license header, choose License Headers in Project Properties.
# To change this template file, choose Tools | Templates
# and open the template in the editor.
__author__ = "<NAME>"
__date__ = "$Dec 10, 2016 2:23:14 PM$"
from flask import c... |
"""General-purpose training script for image-to-image translation.
This script works for various models (with option '--model': e.g., pix2pix, cyclegan, colorization) and
different datasets (with option '--dataset_mode': e.g., aligned, unaligned, single, colorization).
You need to specify the dataset ('--dataroot'... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.