text stringlengths 3.07k 22.1k |
|---|
import PySimpleGUI as sg
import os
import sys
import chess
import copy
from python.engine import *
import tensorflow as tf
from tensorflow import keras
PROJECT_PATH = "/Users/karan/Desktop/KobraChessAI"
CHESS_PATH = PROJECT_PATH + "/python/Play_Against_Me/Assets" # path to the chess pieces
BLANK = 0 # piece names
P... |
"""Elliptic Curve Method with Brent-Suyama Extension and Polyeval.
"""
import random
import time
from math import gcd
import numpy as np
from wheel_sieve.common import PRIME_GEN, InverseNotFound, CurveInitFail
from wheel_sieve.ecm.ecm_brent_suyama import (
apply_polynomial,
get_difference_seq,
step_differen... |
import argparse
import logging
from importlib.machinery import SourceFileLoader
from utils.pdp import *
from utils.models import *
from utils.policies import *
parser = argparse.ArgumentParser()
parser.add_argument('filename', help='scenario filename', nargs=1)
parser.add_argument("--verbose", "-v", action='store_true... |
import os
import sys
import pandas as pd
import numpy as np
from numpy.random import poisson, uniform
from numpy import mean
import time
import math
po = True
teamsheetpath = sys.path[0] + '/teamcsvs/'
compstat = {'TDF': 'TDA', 'TDA': 'TDF', #Dictionary to use to compare team stats with opponent stats
'F... |
# Author: a101269
# Date : 2020/3/24
from tqdm import tqdm
import pkuseg
from glob import glob
fr=open('owns','r',encoding='utf')
owns=fr.read().split('\n')
print(len(owns))
key_word=[
'处所', '信息', '自然物', '鸟', '量化属性', '性格', '相对时间', '器具', '电器', '药物', '自然现象', '时段', '身份', '模糊属性', '职业', '爬行动物',
'票据', '地表', '交通工具... |
import torch
import torch.nn as nn
import torchvision as tv
import torchvision.transforms as T
import pandas as pd
from PIL import Image
from pathlib import Path
from mvqag import CNF_PATH
from mvqag.utils import load_yaml, get_recent_githash, load_qa_file
from mvqag.data import VQADataset, DataLoaders
from mvqag.model... |
#!/usr/bin/env python
# Project : diafuzzer
# Copyright (C) 2017 Orange
# All rights reserved.
# This software is distributed under the terms and conditions of the 'BSD 3-Clause'
# license which can be found in the file 'LICENSE' in this package distribution.
import xml.parsers.expat
import subprocess
import sys
... |
# -*- coding: UTF-8 -*-
#
# Copyright (C) 2008-2011 <NAME> <<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) any later version.
... |
# Communicating with Modular DDS-LO (QES2) M9347A (Latest:2020/12)
from colorama import init, Fore, Back
init(autoreset=True) #to convert termcolor to wins color
from os.path import basename as bs
mdlname = bs(__file__).split('.')[0] # module's name e.g. PSG
import pyvisa as visa
from pyqum.instrument.logger import a... |
#!/usr/bin/python
# Copyright 2017 <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, and <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 ri... |
# -*- coding: utf-8 -*-
# @Time : 19-8-2 下午3:08
# @Author : zj
from classifier.nn_classifier import NN
from tests.gradient_check import eval_numerical_gradient, eval_numerical_gradient_array
import numpy as np
import pytest
def rel_error(x, y):
""" returns relative error """
return np.max(np.abs(x - y) ... |
"""version 2.0.0
Revision ID: 17cafa6e8016
Revises: <PASSWORD>
Create Date: 2017-07-07 08:28:33.876751
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
# revision identifiers, used by Alembic.
revision = '17cafa6e8016'
down_revision = '<PASSWORD>'
branch_labels = None
de... |
# This python script preps xml eComma data for manual tagging.
# It adds a tag for Chapter to each comment node
# It merges the data from 7 songs/chapters into a single file.
# It redacts data based on a list of students who did not sign consent forms.
# It anonymizes the student names in the remaining data to rand... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
/*
This file is part of Bohrium and copyright (c) 2018 the Bohrium
<http://www.bh107.org>
Bohrium 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 v... |
import atexit
import bisect
import collections
import gzip
import os
import re
import subprocess
import tempfile
import utils
from pyminisolvers import minisolvers
class MinisatSubsetSolver(object):
def __init__(self, infile, rand_seed=None, store_dimacs=False):
self.s = minisolvers.MinisatSubsetSolver()
... |
#!/usr/bin/env python
####################################################################
### This is the PYTHON version of program 5.2 from page 171 of #
### "Modeling Infectious Disease in humans and animals" #
### by Keeling & Rohani. #
### #
### It is the simple SIR ep... |
import itertools
import json
import uuid
from abc import abstractmethod, ABC
from typing import Dict, Iterable, Tuple, Callable, Optional
from websockets import connect
from qlient import helpers
from qlient.builder import GraphQLBuilder
from qlient.builder import SelectedField
from qlient.cache import Cache
from qli... |
# coding=utf-8
import dtscalibration
from dtscalibration.datastore_utils import suggest_cable_shift_double_ended, shift_double_ended, merge_double_ended
import numpy as np
import xarray as xr
def to_datastore(ds, config, double):
'''
Convert the pyfocs version of an xarray dataset into a dtscalibration
da... |
import re
from collections import OrderedDict
def _like(got, expected):
expected = expected.replace("?", ".")
expected = expected.replace("*", ".*")
# Technically we should be a bit stricter than this
return re.match(expected, str(got))
class TokenExpander:
number_token_re = r"\$\{([^}]+)\}"
... |
import sys, os
sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
from utils import load_externals
from mobilenets import *
from mobilenets import _obtain_input_shape, __conv_block, __depthwise_conv_block
from keras.layers import Lambda
def scaling_tf(X, input_range_type):... |
# Copyright 2017 Amazon.com, Inc. or its affiliates. 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.
# A copy of the License is located at
# http://www.apache.org/licenses/LICENSE-2.0
# or in the "license" file... |
#!/usr/bin/env python3
'''
Run this code as
./machine_learning.py input_data y_train y_test dimension_reduction ml_algo param_dimred param_ml out
input_data : The input dataset
y_train : The training class labels
y_test : The testing class labels
dimension_reduction : "none", "pca", "VAE", "rp"
ml_algo ... |
import pytorch_lightning as pl
from causalode.utils import DATA_DIR
#from causalode.datagen import cancer_simulation
import causalode.utils as utils
from causalode.utils import str2bool
import torch
from torch.utils.data import Dataset, DataLoader, Subset
import os
import argparse
import numpy as np
from scipy.integra... |
import os
import shutil
import subprocess
import sys
import xml.etree.ElementTree as ET
# Script to build the .apks for all consumer apps, off of the latest release build of CommCare on jenkins
# All paths are written assuming this script will be run from the PARENT directory of commcare-android/,
# unless otherwise... |
#!/QOpenSys/pkgs/bin/python3.6
# Licensed Materials - Property of IBM
# 57XX-XXX
# (c) Copyright IBM Corp. 2021
"""This module is """
import json
from pathlib import Path
import re
import signal
import sys
from typing import List, Optional
from makei.const import DEFAULT_CURLIB, DEFAULT_TGT_CCSID, DEFAULT_OBJLIB
fr... |
import subprocess, logging, winreg, requests, json, pandas, os, sys
import numpy as np
import os.path as osp
from threading import Thread
from flask import Flask, jsonify, request
from time import sleep, time
app = Flask(__name__)
log = logging.getLogger('werkzeug')
log.disabled = True
def split_data(points, times, ... |
import base64
import gzip
import hashlib
from optparse import OptionParser
import os
import shutil
import sys
import urllib2
# Python Updater For MaxMind GeoIP Subscriptions
# No Requirements Outside Standard Python Install
# If Your Python Build Does Not Support SSL, Change _proto to 'http' if still supported by MaxM... |
"""Handle registry.
In this context, registry stores `json` or `pkl` data.
File Storage
--------------------
`{Path.home()} /.fairypptx/registry`.
Key Specification
--------------------
* (category): Specify what kind of data is handled.
* (key): the key
When the `target` is stored in File Storage,
... |
# coding: utf-8
#### ====== Get authors of stories.csv ====== ####
# :param: <path to stories.csv> (str)
# :output: files <authors.csv> and <pseudos.csv>
#
# Notes
# * Add 5 second delays before requesting from AO3's server are in compliance with the AO3 terms of service.
# * Cannot scrape restricted fics, which req... |
import torch.nn as nn
from torch.utils.checkpoint import checkpoint
from collections import OrderedDict
from utils.registry import register
from config.hack import get_global_config
try:
from fast_depthwise_conv3d import DepthwiseConv3d
except ImportError as e:
print("Could not load fast depthwise 3d conv")
... |
import dill as pickle
import pandas as pd
from sklearn import model_selection
from sklearn.utils import resample
__all__ = ["Splitter", "FoldSplit", "TrainValSplit", "SSFoldSplit"]
class Splitter(object):
def __init__(self):
self.__ds_chunks = None
self.__folds_iter = None
pass
def _... |
import os
import matplotlib.pyplot as plt
import seaborn as sns
import matplotlib.patches as patches
import matplotlib
import pickle
import numpy as np
import pandas as pd
from math import pi
from matplotlib.patches import Circle, RegularPolygon
from matplotlib.path import Path
from matplotlib.projections.polar impor... |
from collections import OrderedDict
import numpy as np
import gdal
import osr
import psycopg2
import psycopg2.sql as sql
import matplotlib as mpl
import matplotlib.pyplot as plt
# somehow this is needed for conda version of proj. get rid of this if it is offending
import os
os.environ['PROJ_LIB'] = os.environ.get('P... |
# Copyright 2019 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... |
"""Infractions and related utilities."""
import textwrap
from typing import Awaitable, Optional
import arrow
import disnake
from discord_timestamps import TimestampType, format_timestamp
from disnake import Embed, Member
from disnake.ext.commands import Cog, Context, command, has_any_role
from loguru import logger
f... |
import itertools
import math
import os
import random
import time
from argparse import ArgumentParser
import numpy as np
import torch
from src import data
from src.models import utils as nnutils
from src.models.networks import MLP
from src.train import parser as opts_parser
from src.trainers import utils as tutils
fro... |
# Copyright 2017 Google Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agre... |
#!/usr/bin/env python
"""
The scaProcessMSA script conducts the basic steps in multiple sequence alignment (MSA) pre-processing for SCA, and stores the results using the python tool pickle:
1) Trim the alignment, either by truncating to a reference sequence (specified with the -t flag) or by removing
... |
# def bb_to_rect(startX, startY, endX, endY):
# rect = dlib.rectangle(1,2,2,3)
# rect.left()= startX
# rect.top() = startY
# rect.right() = endX
# rect.bottom() = endY
# return rect
def shape_to_np(shape, dtype="int"):
# initialize the list of (x, y)-coordinates
coords = np.zeros((68, 2),... |
import json
import numpy as np
import pandas as pd
import tensorflow as tf
import importlib
import datetime
import tensorflow_addons as tfa
from tensorflow.keras.losses import CategoricalCrossentropy
from tensorflow.keras.metrics import CategoricalAccuracy, Mean, Precision, Recall, AUC
import matplotlib.pyplot as plt... |
# -*- coding: utf-8 -*-
"""
This function implements the reservoir simulation model (res_sys_sim). First,
it extracts and process the regulated flows contained in the Qreg variable.
This makes the regulated flow data readable by the mass balance function
(mass_bal_func). Then, mass_bal_func links all the key variable... |
# Copyright 2021 D-Wave Systems Inc.
#
# 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... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = "<EMAIL>"
__doc__ = """ """
from pptx import Presentation
from pptx.exc import PackageNotFoundError
from poorscrum import Status, read_fields, story_points, __version__
import configparser
import argparse
import os
import sys
import logging
logging.bas... |
from logging import getLogger
logger = getLogger("__name__")
from sklearn.decomposition import PCA
import pandas as pd
import numpy as np
import matplotlib.pylab as plt
import warnings
from .plot import annotate_points, _def_label_alignment
import seaborn as sns
from matplotlib.patches import Ellipse
import matplot... |
from discord.ext import commands
from discord import Embed
import discord
import os
import json
from loguru import logger
import networkx as nx # Required for node connections
import matplotlib.pyplot as plt # Required for image processing and saving
from utils.CalculateLib import *
class Core(commands.Cog):... |
#!/usr/bin/env python3
# The MIT License
# Copyright (c) 2016 Estonian Information System Authority (RIA), Population Register Centre (VRK)
#
# 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 ... |
# -*- coding: utf-8 -*-
# ----------------------------------------------------------------------------
#
# PROJECT : JAS1101 Final Project
#
# ----------------------------------------------------------------------------
# Docstring
"""Plot Utilities.
Routine Listings
----------------
LogNorm
AsinhNorm
HistEqNorm
ran... |
#AQUÍ se implementará la búsqueda en GitHub.
#Importamos las librerías necesarias.
from github import Github
import aux_functions as aux
import ci_yml_parser as ymlp
import dataF_functions as d
import ci_tools as ci
import random
import logging
import calendar
import time
import datetime
import os
import requests
impo... |
# -*- coding: utf-8 -*-
u"""Support for unit tests
:copyright: Copyright (c) 2016 RadiaSoft LLC. All Rights Reserved.
:license: http://www.apache.org/licenses/LICENSE-2.0.html
"""
from __future__ import absolute_import, division, print_function
from pykern import pkcollections
from pykern import pkconfig
from pykern ... |
import praw
import re
from datetime import datetime
import operator
import sys, os
import sqlite3
def getDate(submission):
time = datetime.fromtimestamp(submission.created)
# return datetime.date.fromtimestamp(time)
return time.strftime('%Y-%m-%d %H:%M:%S')
def getTitle(submission):
return convertTi... |
import os
import numpy as np
from matplotlib import pyplot as plt
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg
from matplotlib.widgets import RectangleSelector
from numpy import nonzero, zeros
from numpy.random import permutation
from PyQt5.QtCore import QSettings, Qt, QThread, QTimer, pyqtSignal
f... |
# Copyright (c) 2014-2021, Camptocamp SA
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions an... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
======================================
Clustering by rotation of eigenvectors
======================================
cluster by rotating eigenvectors to align with the canonical coordinate system
usage:
nc = cluster_rotate(evecs, evals, group_num, method, verbose)
Inpu... |
"""The functions for monodepth2 model and loss
Code partially borrowed from
https://github.com/nianticlabs/monodepth2/blob/master/layers.py.
"""
# pylint: disable=unused-argument, missing-function-docstring
# Copyright Niantic 2019. Patent Pending. All rights reserved.
#
# This software is licensed under the terms of t... |
# coding=utf-8
import string
from settings import settings
from random import randint
from time import sleep
from datetime import datetime
from bson.objectid import ObjectId
from langdetect import detect
from dataaccess import dao
from bs4 import BeautifulSoup
from utilities import util
def calculate_tags(brand, mod... |
from __future__ import print_function, division, absolute_import
# Non-std. lib imports
from PySide.QtCore import Signal, QObject
from PySide.QtGui import QTabWidget, QVBoxLayout, QWidget, QLineEdit, \
QDoubleValidator, QLabel, QGridLayout
from numpy import asarray, nan
# Local imports
from ra... |
from datetime import datetime as dt
from itertools import compress
from math import ceil
from json import dumps
import requests
"""
Binary operators as functions for the song filtering
"""
def _equiv(x, y):
return x == y
def _in(x, y):
return x in y
def _and_iter(l1, l2):
if len(l1) != len(l2):
... |
import sys
import json as J
from collections import Counter
from amr import JAMR_CorpusReader
entity_rules_json = {}
verbose = True
def fix_alignments(amr):
changes = 0
for node_id in amr.nodes:
if node_id not in amr.alignments:
amr.alignments[node_id] = []
# fix false positives
... |
import datetime
from django.contrib.auth import get_user_model
from django.core import mail
from django.urls import reverse, reverse_lazy
from django.test import TestCase
from django.utils import timezone
from ..models import Calendar, Event, EventCategory, EventLocation, RecurringRule
from ..templatetags.events impo... |
#! /usr/bin/env python
import math
from random import random
from multiprocessing import Pool
from PyQt5.QtGui import QVector3D, QVector2D
from rayTracer.PPM import PPMFile
from rayTracer.Ray import Ray
from rayTracer.Auxiliary3DMath import reflect
from rayTracer.Material import Material
EPSILON = 0.0000001
def ref... |
from django.db import models
from django.conf import settings
from django.core.mail import EmailMultiAlternatives
from django.core.exceptions import ImproperlyConfigured
from django.template.loader import render_to_string
from django.template import TemplateDoesNotExist
from django.utils import translation
from six.mov... |
from urllib import parse
from apps.common.config import commonWebConfig
from apps.common.func.LanguageFunc import *
from apps.common.model.RedisDBConfig import *
from apps.data_keyword.services.main_service import MainService
from django.shortcuts import render,HttpResponse,redirect
from apps.config.services.businessLi... |
from typing import Union, Tuple
import gym
from enum import Enum
import torch
import torch.nn as nn
from ..models.torch import Model
from ..models.torch import GaussianModel
from ..models.torch import CategoricalModel
from ..models.torch import DeterministicModel
__all__ = ["categorical_model", "deterministic_model... |
"""pywizlight integration."""
import asyncio
import json
import logging
from time import time
import asyncio_dgram
from pywizlight.scenes import SCENES
_LOGGER = logging.getLogger(__name__)
class PilotBuilder:
"""Get information from the bulb."""
def __init__(
self,
warm_white=None,
... |
import numpy as np
import os
import torch
from torch.utils.data import SequentialSampler,DistributedSampler,DataLoader
from utils_glue import compute_metrics
from tqdm import tqdm
import logging
from collections import defaultdict
logger = logging.getLogger(__name__)
import datasets
from transformers import PretrainedC... |
import tkinter as tk
from tkinter import *
import math
def main():
#create the Tk root object.
root = tk.Tk()
root.geometry("800x460")
#Create a Frame object.
frame = tk.Frame(root)
frame.master.title("Scene")
frame.pack(fill=tk.BOTH, expand=1)
#Create a canvas ob... |
from .base import *
from .base.base import _PendingTask
from . import (cam, nav, view, history, scene, import_, export, create, select, transform,
transf_center, coord_sys, geom, hierarchy, helpers, texmap, material, snap, align)
class Core:
def __init__(self, app_mgr, verbose=False):
sel... |
import json
import os
import re
from typing import Union
from .file import File, canonical_fname
from .jsondetect import str_seems_like_json, bytes_seems_like_json
class DIDDoc:
def __init__(self, path_or_File: Union[str, File]):
if isinstance(path_or_File, File):
self._file = path_or_File
... |
# coding: utf-8
# # Constrained AR-HMM sampling
# Sample an autoregressive hidden Markov model subject to a constraint,
# represented as an auxiliary potential. The joint probability of the
# ARHMM and constraint is,
#
# $$\log p(x, z) = \sum_t \log p(z_t \mid z_{t-1}) + \log p(x_t \mid z_t, x_{t-1}) + c(x_t)$$
#... |
import os
import argparse
from pathlib import Path
import pandas as pd
import numpy as np
import torch
import hpbandster.core.result as hpres
from src.probability import pMOM_loglike, diag_w_Gauss_loglike, depth_categorical_VI
from src.utils import Datafeed, mkdir
from src.datasets import load_flight, load_gap_UCI
fr... |
import os.path as path
import re
import os
from rank_bm25 import BM25Okapi
from sklearn.metrics.pairwise import cosine_similarity
from sklearn.feature_extraction.text import TfidfVectorizer
from Evaluate import *
from inverted_index.VanillaInvertedIndex import *
# Configurations for benchmark datasets taken from htt... |
#!/usr/bin/env python
"""
For downloading data from the AWS pricing API and importing into mysql/mariadb
"""
from __future__ import print_function
import os
import hashlib
import csv
import json
import logging
import requests
import pymysql.cursors
class PricingImporter(object):
"""For importing aws pricing into a... |
import torch
import numpy as np
import os
import matplotlib.pyplot as plt
import PIL.Image as Image
from torch.utils.data import DataLoader
from torch import nn, optim
from torchvision.transforms import transforms
from dataset import Train_Dataset, Validation_Dataset, Test_Dataset
import skimage.io as io
impo... |
import pandas as pd
import numpy as np
from pylab import rcParams
import glob
from natsort import natsorted
import re
from numpy import linalg as LA
import matplotlib.pyplot as plt
import datetime
import os
import matplotlib.gridspec as gridspec
import seaborn as sns
def dir_check(now_time):
if not os.path.exists(... |
from flask import Flask, request
from flask import render_template
from datetime import datetime,timedelta
import pandas_datareader.data as web
from sklearn import linear_model
from sklearn.cross_validation import train_test_split
import tensorflow as tf
from keras.models import Sequential
from keras.layers import Acti... |
import pickle
import pandas as pd
import numpy as np
import xgboost as xgb
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from scipy.stats import randint as sp_randint
from scipy.stats import uniform as sp_float
from civismlext.hyperband import HyperbandSearc... |
"""
"""
from collections import OrderedDict
from jax import jit as jjit
from jax import numpy as jnp
from jax import vmap
from jax import lax
from diffmah.individual_halo_assembly import _calc_halo_history
from .utils import _jax_get_dt_array
FB = 0.156
TODAY = 13.8
LGT0 = jnp.log10(TODAY)
T_SFH_MIN = 0.1
DEFAULT_MAH... |
#!/usr/bin/env python
"""Build script for Better than Noise, the Better than Wolves texture pack created by FriedYeti.
Uses Aseprite to batch export all textures to the proper structure for a Minecraft 1.5.2 texture pack.
"""
__author__ = "<NAME>"
__copyright__ = "Copyright 2018"
__license__ = "MIT"
import argparse... |
"""
<NAME>
Creates an acyclic directed graph representing the structure any directory
that is in the same directory as this script.
"""
import os
import json
import argparse
from graphviz import Digraph
from typing import Union
# Change PATH setup for Graphviz directory here:
# --------------------------GRAPHVIZ PA... |
""" Simple MATPOWER format parser
"""
import logging
import re
import andes.io
from andes.shared import deg2rad, np
logger = logging.getLogger(__name__)
def testlines(infil):
return True # hard coded
def read(system, file):
"""
Read a MATPOWER data file into mpc, and build andes device elements.
... |
'''
func 'convert' is the main function.
It gets metadata for a hca project uuid from the datastore bundles API.
This API only returns bundes so the code iterates over bundles to build all the metadata for a DCP project.
In the future there may be better endpoints for getting metadata.
'''
# todo automatically update ... |
#!/usr/bin/env python
# Copyright 2017 Google Inc.
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applic... |
# -*- coding: utf-8 -*-
###############################################################################
###############################################################################
import logging
import numpy as np
from skimage import io
# create logger
logger = logging.getLogger('logger')
logger.setLevel(logging... |
# -*- coding: utf-8 -*-
"""
Created on Tue Nov 26 15:58:43 2019
@author: <NAME> (<EMAIL>) and <NAME> (<EMAIL>). This program was modified from the python codes
available at https://salib.readthedocs.io/en/latest/api.html, but it can be used for the level number other than 4 (the original python code
seems to ha... |
# from __future__ import print_function
import os
import psutil
import shutil
import asyncio
import math
import numpy as np
import tensorflow as tf
import tracemalloc
import argparse
import logging
from tensorflow import keras
from pathlib import Path
from time import strftime
# sys.path.append(os.path.dirname(os.path... |
from datetime import datetime
import random
from django.http import HttpResponse
import pytz
from django.contrib import messages
from django.contrib.auth import authenticate, login, logout
from django.shortcuts import redirect, render
from pushbullet import Pushbullet
from .models import User, AdminLog, AdminSecret
... |
from tkinter import ttk
import json
import tkinter as tk
import os
import re
def find_file(known_path:str=None, name:str=None) -> (bool, str):
"""
Function to find a file on the user's computer.
:param known_path: the part of the path that is constant or known by the user.
:param name: the name (with t... |
import numpy as np
from sys import stdout
import os
import time
import mediapipe as mp
from flask import Flask, render_template, Response
import cv2
from tensorflow import keras
from flask_socketio import SocketIO
app = Flask(__name__,template_folder= 'templates')
model = keras.models.load_model('act... |
import json
from copy import deepcopy
from itertools import compress
import networkx as nx
import numpy as np
import torch
import torch_geometric.utils as tgu
from scipy.sparse import csr_matrix, vstack, diags
from sklearn.model_selection import train_test_split
from torch_geometric.data import DataLoader, Data
from t... |
# python2, 3 compatibility
from __future__ import absolute_import, division, print_function
import six
import os
import inspect
from builtins import str, open, range, dict
import pickle
import numpy as np
import pandas as pd
import pybedtools
from pybedtools import BedTool
from sklearn.preprocessing import FunctionTr... |
'''
Predict Server
Create a server to accept image inputs and run them against a trained neural network.
This then sends the steering output back to the client.
Author: <NAME>, modified by <NAME>
'''
from __future__ import print_function
import os
import sys
import argparse
import time
import json
import base64
import ... |
import cv2
import numpy as np
import torch
from torch.utils.data import DataLoader
from ..misc.utils import broadcast, make_list
# Usual dtypes for common modalities
KEYS_TO_DTYPES = {
"segm": torch.long,
"mask": torch.long,
"depth": torch.float,
"normals": torch.float,
}
class Pad(object):
"""P... |
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 21 00:04:24 2021
@author: bernifoellmer
"""
import os, sys
import numpy as np
import pandas as pd
import time
import pydicom
from glob import glob
from tqdm import tqdm
def computeSliceSpacing(alldcm):
try:
if len(alldcm)>1:
ds0 = pydicom.dcmrea... |
from bacpypes.object import Object, ReadableProperty, OptionalProperty
from bacpypes.primitivedata import Atomic, BitString, Boolean, CharacterString, Date, \
Double, Integer, ObjectIdentifier, ObjectType, OctetString, Real, Time, \
Unsigned, Tag, Enumerated, Null
from bacpypes.constructeddata import AnyAtom... |
# -*- coding: utf-8 -*-
# Copyright 2014 OpenMarket 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 la... |
import logging
from itertools import product
from more_itertools import ichunked, distribute
from os.path import join
from copy import deepcopy
from math import factorial as f
from multiprocessing import Process
from tempfile import TemporaryDirectory
from contextlib import nullcontext
class Format:
@staticmethod... |
from typing import Generator
import pytest
from pypeerassets import (
Deck,
find_deck
)
from pypeerassets.provider import Cryptoid, Explorer, RpcNode
from pypeerassets.exceptions import *
from pypeerassets.paproto_pb2 import DeckSpawn
from pypeerassets.pautils import *
from pypeerassets.protocol import IssueM... |
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import numpy as np
import gc
from datetime import datetime
from time import time
def horizontal_transfer(x, tau, beta, mu):
# Do transfer in an already sorted list!!!
# x = x.sort()
n_tot = len(x)
ht_rate = tau/(beta+mu*n_tot)
... |
"""Tests for lr_scheduler.py"""
import pytest
import numpy as np
from torch.optim import SGD
from torch.optim.lr_scheduler import StepLR
from torch.optim.lr_scheduler import LambdaLR
from torch.optim.lr_scheduler import MultiStepLR
from torch.optim.lr_scheduler import ExponentialLR
from torch.optim.lr_scheduler impor... |
# 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 applica... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.