text stringlengths 3.07k 12.6k |
|---|
from __future__ import annotations
import lark
import numpy as np
from pathlib import Path
from typing import Callable, Dict, List, Optional, Set
from dnnv.properties.expressions.terms import symbol
from .errors import VNNLIBParserError
from ..utils import LimitQuantifiers, parse_cli
from ...expressions import *
#... |
import logging
from abc import ABCMeta
from dataclasses import dataclass
from typing import List, Optional, Dict, Set
from brain_brew.configuration.global_config import GlobalConfig
from brain_brew.interfaces.media_container import MediaContainer
from brain_brew.representation.yaml.yaml_object import YamlObject
from b... |
# Resource object code (Python 3)
# Created by: object code
# Created by: The Resource Compiler for Qt version 6.0.4
# WARNING! All changes made in this file will be lost!
from PySide6 import QtCore
qt_resource_data = b"\
\x00\x00\x06\xca\
T\
EMPLATE = app\x0d\x0aL\
ANGUAGE = C++\x0d\x0aT\
ARGET = \
assistant... |
import discord
from discord.ext import commands
import os
import sys
from dotenv import load_dotenv
def logError(content):
print(content)
intents = discord.Intents.all()
intents.members = True
load_dotenv()
config = os.environ
client = commands.Bot(command_prefix=config.get('PREFIX'), intents=intents)
... |
import numpy as np
import tensorflow as tf
import itertools,time
import sys, os
from collections import OrderedDict
from copy import deepcopy
from time import time
# import matplotlib.pyplot as plt
import pickle
def xavier_init(fan_in, fan_out, constant=1):
low = -constant*np.sqrt(6.0/(fan_in + fan_out))
high =... |
#!/usr/bin/env python
# Copyright 2018 Division of Medical Image Computing, German Cancer Research Center (DKFZ).
#
# 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... |
# Copyright 2017 The Abseil Authors.
#
# 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 in ... |
####################################################################################################
#
# main.py
#
# Authors:
# <NAME>
# <NAME>
# <NAME>
#
# Contains the main module for running the Polya inequality prover, with some prepackaged
# solving methods.
#
######################################################... |
import glob
import random
import time
import chainer
import numpy as np
from PIL import Image
# imgs , bboxes ,labels がデータセットの中身なので毎回作るくらいならデータ上で簡潔させる
folder_path='fill_moji'
input_size = 300
# 全データを取得する
def input():
alp_data = []
alp_size = []
for x in range(ord('A'),ord('Z')+1):
... |
import tkinter as tk
from typing import List, Tuple
from tqdm import tqdm
from dataset import Dataset, PointFloat
from main import TRAIN_DATASET_PATH, Model, train
from tensor import tensor as ts
from tensor import nn
from visualization import Colors
import numpy as np
COLOR_MAP = [Colors.color1, Colors.color2, Colo... |
from __future__ import absolute_import
import os
import gzip
import shutil
import tempfile
import unittest
from django.core.cache import cache
from django.core.files import File
from django.core.files.move import file_move_safe
from django.core.files.base import ContentFile
from django.core.files.uploadedfile import ... |
import k4net.LockedSocket as LockedSocket
import k4net.utils as utils
from Crypto.Cipher import PKCS1_OAEP
from Crypto.PublicKey import RSA
from Crypto.Random import get_random_bytes
import os
import socket
from Crypto.Cipher import AES
class HandshakeError(Exception):
def __init__(self):
pass
class Enc... |
import unittest
from AccessControl import Unauthorized
def addPythonScript(folder, id, params='', body=''):
"""Add a PythonScript to folder."""
from Products.PythonScripts.PythonScript import manage_addPythonScript
# clean up any 'ps' that's already here..
if id in folder:
del folder[id]
... |
"""Top-level package for unasync."""
from __future__ import print_function
import collections
import errno
import os
import sys
import tokenize as std_tokenize
from setuptools.command import build_py as orig
from ._version import __version__ # NOQA
__all__ = [
"Rule",
"unasync_files",
"cmdclass_build_... |
import numpy as np
import sys, os
sys.path.append(os.path.abspath(os.path.join('..')))
from tqdm import tqdm
from scipy.stats import truncnorm
import csv
import REBA.body_part_reba_calculator.Degree_to_REBA.neck_reba_score as REBA_neck
import REBA.body_part_reba_calculator.Degree_to_REBA.trunk_reba_score as REBA_trunk... |
"""
Copyright 2017-2018 Fizyr (https://fizyr.com)
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 in w... |
#!/usr/bin/env python
# coding: utf-8
import dataclasses
import json
import os
import uuid
import base64
from dataclasses import asdict
from typing import List, Callable, Dict, Optional, Sequence
import pandas
import evidently
from evidently.model.dashboard import DashboardInfo
from evidently.pipeline.pipeline impor... |
#!/usr/bin/env python3
# encoding: utf-8
"""
fake-registration-server.py
Created by nano on 2018-11-22.
Copyright (c) 2018 VTRUST. All rights reserved.
"""
import tornado.web
import os
import hashlib
def file_as_bytes(file):
with file:
return file.read()
from tornado.options import define, options, parse_... |
import torch
import os
import math
from torch.autograd import Variable
import numpy as np
from PIL import Image
from util import util
import numpy as np
def color_map(i):
colors = [
[255,0,0],
[0,255,0],
[0,0,255],
[128,128,0],
[0,128,128]
]
if i < 5:
return... |
from math import gcd
from math import log
from fractions import Fraction
from qiskit import QuantumCircuit
from core.algorithms.qft import create_qft_circuit
class Shor:
def shor(self, run_values, task_log):
number_input = run_values.get('number')
precision_input = run_values.get(... |
import pytest
from parameterized import parameterized
from core.config import CannotLoadConfiguration
from core.mirror import MirrorUploader
from core.model import ExternalIntegration
from core.model.configuration import ExternalIntegrationLink
from core.s3 import (
MinIOUploader,
MinIOUploaderConfiguration,
... |
import os
import sys
import torch
from ncc import LOGGER
from ncc import tasks
from ncc.utils import checkpoint_utils
from ncc.utils import utils
from ncc.utils.file_ops.yaml_io import load_yaml
from ncc.utils.logging import progress_bar
def main(args):
return _main(args, sys.stdout)
def _main(args, output_fi... |
# -*- coding: utf-8 -*-
"""VGG16 model for Keras.
# Reference
- [Very Deep Convolutional Networks for Large-Scale Image Recognition](https://arxiv.org/abs/1409.1556)
"""
from __future__ import print_function
from __future__ import absolute_import
from __future__ import division
import warnings
from keras.models impor... |
__author__ = "<NAME>, <NAME>"
__copyright__ = "Copyright 2012-2013, The SAGA Project"
__license__ = "MIT"
import radical.utils.signatures as rus
from .. import attributes as sa
from .. import exceptions as se
from . import constants as c
# ------------------------------------------------... |
import json
import re
from lib.rendering import render
class Race:
def __init__(self, name: str, source: str, page: int, size: str, speed, asi, entries, srd: bool = False,
darkvision: int = 0):
self.name = name
self.source = source
self.page = page
self.size = siz... |
"""TTS Inference script."""
import configargparse
import logging
import os
import torch
import sys
from utils.util import set_deterministic_pytorch
from fastspeech import FeedForwardTransformer
from dataset.texts import phonemes_to_sequence
import time
from dataset.audio_processing import griffin_lim
import numpy as n... |
# Copyright 2017 Neural Networks and Deep Learning lab, MIPT
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicab... |
import glob
import logging
import os
import re
import shutil
import tempfile
import hydra
import numpy as np
import pyparsing as pp
from edalize import *
from hydra.core.hydra_config import HydraConfig
from hydra.utils import get_original_cwd
from omegaconf import DictConfig, OmegaConf
from do_blink.edalize.vivado im... |
# -*- coding: utf-8 -*-
'''
NAPALM Users
============
Manages the configuration of the users on network devices.
:codeauthor: <NAME> <<EMAIL>>
:maturity: new
:depends: napalm
:platform: unix
Dependencies
------------
- :mod:`NAPALM proxy minion <salt.proxy.napalm>`
.. seealso::
:mod:`Users management sta... |
import numpy as np
import torch as T
from torch.nn import ReLU, GRU, Sequential, Linear
from torch import sigmoid, softmax, relu, tanh
from collections import namedtuple, deque
from torch_geometric.nn import TAGConv
import random
import scipy as sp
import time
import Batch_Graph as bg
from itertools impor... |
# -*- coding:uft-8 -*-
import json
from datetime import datetime, timedelta
from os import path
import numpy as np
import pandas as pd
from more_itertools import chunked
from netCDF4 import Dataset, date2num
from yaml import full_load
from .util import create_meta_grp, offset_from_utc
from ..util import time_round, S... |
from basehandler import BaseHandler
from oracle.oracle_db import KeyValue
import json
import logging
import time
from shared.liburl_wrapper import safe_pushtx
TURN_LENGTH_TIME = 60 * 1
class TransactionVerificationError(Exception):
pass
class TransactionSigner(BaseHandler):
def __init__(self, oracle):
sel... |
#!/usr/bin/env python
# Copyright (c) 2012 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""
Verifies that device and simulator bundles are built correctly.
"""
from __future__ import print_function
import plistlib
import TestG... |
import numpy as np
import tensorflow as tf
from helper_functions import *
import time
def get_q_theta_params():
t_vars = tf.trainable_variables()
var_list = [var for var in t_vars if 'gen_shared' in var.name]
param_dict = {}
for var in var_list:
param_dict[var.name] = var # make sure here is no... |
from copy import copy
from distutils.spawn import find_executable
import os
import re
import subprocess
import sys
import sipconfig
from PyQt5 import QtCore
libqt5_rename = False
class Configuration(sipconfig.Configuration):
def __init__(self):
env = copy(os.environ)
env['QT_SELECT'] = '5'
... |
import pytest
import json
from werkzeug.datastructures import Headers
from cinp.server_common import Response, Namespace, Model, AnonymousUser
from cinp.server_werkzeug import WerkzeugServer, WerkzeugRequest, WerkzeugResponse
def getUser( auth_id, auth_token ):
return AnonymousUser()
class FakeBody(): # set ws... |
#encoding=utf-8
import os, time, copy
from flask import Flask, render_template, session, redirect, url_for, request, flash
from flask_script import Manager, Shell
from flask_bootstrap import Bootstrap
from flask_moment import Moment
from flask_wtf import Form
from wtforms import StringField, SubmitField
from wtforms.va... |
from utils import input_poly_basis
import numpy as np
from random_data_generater import poly_data_gen
import matplotlib.pyplot as plt
def get_poly(X, w, n):
X_mat = []
for x in X:
X_mat.append([(x ** deg) for deg in range(n)])
X_mat = np.array(X_mat)
W = np.array(w).reshape(-1)
Y = X_mat @... |
# Copyright 2020 Google LLC. 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 a... |
import time
import hmac
import base64
import hashlib
import json
import urllib.parse
import http.client
class Notification:
def __init__(self, notification_format=None, payload=None, debug=0):
valid_formats = ['template', 'apple', 'gcm', 'windows', 'windowsphone', "adm", "baidu"]
if not any(x in n... |
from pyquaternion import Quaternion
import numpy as np
import pybullet as pb
class Script(object):
def __init__(self, scene):
self._dt = scene.dt
self._max_tool_velocity = scene.max_tool_velocity
self._max_gripper_velocity = scene.max_gripper_velocity
# report used scripts to the... |
"""
Send Receipt StepFunction
:license: MIT
"""
import datetime
import json
import os
from typing import List
from src.dependencies.dependency_typing import (PynamoDBCheckIn,
PynamoDBCustomers, Requests)
from src.dependencies.pynamodb_checkin_provider import get_... |
import itertools
from functools import wraps
import numpy as np
import pandas as pd
import matplotlib as mpl
import matplotlib.pyplot as plt
import seaborn as sns
def add_styles(dirname):
mpl.style.core.USER_LIBRARY_PATHS.append(dirname)
mpl.style.core.update_user_library(mpl.style.library)
mpl.style.re... |
from math import factorial
# index of value of a card
VALUE = 0
# index of suit of a card
SUIT = 1
# value of Ace
ACE = 'A'
# dictionary of scores of individual cards
card_score = {
'2': 2,
'3': 3,
'4': 4,
'5': 5,
'6': 6,
'7': 7,
'8': 8,
'9': 9,
'0': 10,
'J': 11,
'Q': 12,... |
import matplotlib.pyplot as plt
import numpy as np
import cv2
from skimage import img_as_ubyte
from icecream import ic
import czi_image_handling as handler
def detect_params(detect_img, distance_from_border = 5, timepoint = 5, dp = 2, minDist = 10, minRadius = 5, maxRadius = 50, param1top = 50, param2top = 300):
#... |
import datetime
import random
import markdown
import os
from flask import Flask, request, jsonify, send_from_directory, send_file
from flask import Markup
from flask_autodoc.autodoc import Autodoc
from peewee import fn
import settings
from models import Bot
from models import Category
from models.apiaccess import API... |
#!/usr/bin/env python3
r"""
This module is the python counterpart to openbmc_ffdc.robot..
"""
import os
import gen_print as gp
import gen_valid as gv
import gen_robot_keyword as grk
import state as st
from robot.libraries.BuiltIn import BuiltIn
redfish_support_trans_state = int(os.environ.get('REDFISH_SUPPORT_TRAN... |
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import six
import os
import sys
import tempfile
import numpy as np
import pytest
import matplotlib as mpl
from matplotlib import pyplot as plt
from matplotlib import animation
class NullMovieWriter(animati... |
from qutip import *
import numpy as np
import scipy
from scipy import stats
import itertools
import random
import matplotlib.pyplot as plt
import pickle
from time import time
from plot_settings import *
#Pauli matrices
s = [sigmax(), sigmay(), sigmaz()]
#General qubit state, input as list of Bloch vector components,... |
from itertools import chain
import re
WORDS_TO_ROLLUP = {
'rollup-': 0,
'rollup': 1,
'rollup=maybe': 0,
'rollup=never': -2,
'rollup=iffy': -1,
'rollup=always': 1,
}
class IssueCommentCommand:
"""
A command that has been parsed out of a GitHub issue comment.
E.g., `@bors r+` => an... |
"""GaussianPolicy."""
from collections import OrderedDict
import numpy as np
import tensorflow as tf
import tensorflow_probability as tfp
from softlearning.models.feedforward import feedforward_model
from .base_policy import LatentSpacePolicy
SCALE_DIAG_MIN_MAX = (-20, 2)
class GaussianPolicy(LatentSpacePolicy):
... |
from datetime import datetime
from typing import NoReturn
import numpy as np
import hashlib
import json
from binascii import hexlify
def double_sha256(data):
return hashlib.sha256(hashlib.sha256(data).digest()).digest()
def format_hash(hash_):
return str(hexlify(hash_[::-1]).decode("utf-8"))
def jprint(s)... |
import io
import pytest
import re
import os
import ctypes
from .ProtoParser import BadParameter, UnknownType, BadParameterName, Prototype, Parameter, ProtoParser
class CLikeProtoParser(ProtoParser):
def can_parse_file(self, filename):
_, file_extension = os.path.splitext(filename.strip())
return f... |
# Copyright 2018 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... |
'''
lanhuage: python
Descripttion:
version: beta
Author: xiaoshuyui
Date: 2020-09-03 07:58:48
LastEditors: xiaoshuyui
LastEditTime: 2020-11-25 11:35:28
'''
import glob
import os
import xml.etree.ElementTree as ET
import numpy as np
import yaml
from convertmask.utils.methods.logger import logger
from convertmask.utils... |
"""
.. versionadded:: 0.0.2
The :mod:`fatf.utils.testing.transparency` module holds transparency testing
assets.
"""
# Author: <NAME> <<EMAIL>>
# License: new BSD
from typing import Dict, Iterable, List, Tuple, Union
import numpy as np
__all__ = ['LABELS',
'NUMERICAL_NP_ARRAY',
'NUMERICAL_STRU... |
# PyAlgoTrade
#
# Copyright 2011-2015 <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 or agreed t... |
from omnibelt import unspecified_argument, agnosticmethod
import torch
from torch import nn
import piq
from piq import IS, FID, GS, KID, MSID, PR
try:
from pytorch_fid import fid_score as backup_fid_score
except ImportError:
backup_fid_score = None
from piq import inception_score
from piq.fid import _comput... |
# -*- coding: utf-8 -*-
'''
Copyright (c) 2016, Virginia Tech
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 o... |
import graphene
from graphene_django import DjangoObjectType
from graphene_django.debug import DjangoDebug
from django.contrib.auth import get_user_model
from pontoon.api.util import get_fields
from pontoon.base.models import (
Comment as CommentModel,
Entity as EntityModel,
Locale as LocaleModel,
Pro... |
import ast
from collections import defaultdict
from typing import Any, Dict, List, Optional, Union
from flake8_plugin_utils import Visitor
from .errors import (
ImplicitReturn,
ImplicitReturnValue,
UnnecessaryAssign,
UnnecessaryReturnNone,
)
from .utils import is_false, is_none
NameToLines = Dict[str... |
def get_new_direction(current_direction, turn_to):
directions = ['N', 'E', 'S', 'W']
dir_index = {'L': -1, 'R': 1}
new_direction = (directions.index(current_direction) + dir_index[turn_to]) % len(directions)
return directions[new_direction]
def get_new_position(current_position, direction, distan... |
from core.arissploit import *
from core import colors
import os
from core import getpath
from scapy.all import *
import threading, queue
import time
import traceback
importerror = False
try:
from netfilterqueue import NetfilterQueue
except:
importerror = True
terror = traceback.format_exc()
printError("Cannot impo... |
import json
import ntpath
import os
import sys
import logging
from itertools import combinations
from tqdm import tqdm
logging.basicConfig(
format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
datefmt="%m/%d/%Y %H:%M:%S",
level=logging.INFO,
)
logger = logging.getLogger(__name__)
def get_end... |
import os
import sqlalchemy
import datetime
from sqlalchemy import Column, VARCHAR, Integer, String, DateTime, ForeignKey, Boolean
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, relationship
from sqlalchemy.sql import exists
from dot... |
'''
REDUCER Coordinator
Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
SPDX-License-Identifier: MIT-0
'''
import boto3
import json
import lambdautils
import random
import re
from io import StringIO
import time
import urllib
DEFAULT_REGION = "us-east-1";
### STATES
MAPPERS_DONE = 0;
REDUCER... |
#!/usr/bin/env python3
#
# Software License Agreement (Apache 2.0 License)
# Copyright (c) 2022, The Ohio State University
#
# Author: <NAME>
#
# Description:
# Support class offering tools for robot kinematics and other related calculations.
import numpy as np
class ROBOT_KINEMATICS():
"""
This is the clas... |
import requests
import urllib
import json
import os
from os.path import isfile, join
from bs4 import BeautifulSoup as BS
from constants import PONS_KEYS, NOTCODE_DIR
BASE_URL = 'https://api.pons.com/v1/dictionary?'
HISTORY_PATH = join(NOTCODE_DIR, 'pons_responses_history.json')
def generateankinotes(maindict):
... |
#!/usr/bin/env python3
import os
from migen import *
from litex.soc.interconnect import wishbone
from litex.soc.integration.soc_core import mem_decoder
from litex.soc.cores.spi_flash import SpiFlash
from litex.soc.cores.gpio import GPIOOut, GPIOIn
from litex.soc.cores.spi import SPIMaster
from litex.soc.cores.bitba... |
# --------------------------------------------------------------------------------
# Copyright (c) 2017-2020, <NAME>, All rights reserved.
#
# Implements some prototype selection algorithms based on a dissimilarity matrix.
# --------------------------------------------------------------------------------
import numpy a... |
import numpy as np
import scipy.stats
import subprocess
import os
import warnings
from genome_integration import simulate_mr
from genome_integration import utils
from genome_integration.association import GeneticAssociation
def read_assocs_from_plink_qassoc(assoc_file):
assocs = {}
with open(assoc_file, "r") ... |
import zipfile
from torch.utils.data import Dataset
import torch
import os
import pandas as pd
import numpy as np
from zipfile import ZipFile
import requests
import sklearn
import random
class Download():
def __init__(self,
root: str,
file_size: str = '100k',
dow... |
import os
import SimpleITK as sitk
import matplotlib.pyplot as plt
import seaborn as sns
import torch
from ..utils.utils import read_meta, split_data, plot_preds
import os.path as osp
from ..main.train_validate import train_validate, save_to_log
from ..main.train_test import train_test, save_to_log_test
from torch.util... |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... |
import re
import numpy as np
import pandas as pd
def read_file(path):
with open(path, 'r') as f:
content = f.read()
return content
def tosec(t):
return round(float(re.findall(r'.*(?=s)', t)[0]), 3)
def minsec2sec(t):
m = re.findall(r'\d+(?=min)', t)[0]
_s = re.findall(r'\d+(?=s)', t)
... |
import ntpath
from datetime import datetime as dt
import os
import pandas as pd
import numpy as np
import math
import sqlite3
# clean the original raw data by storing only the columns that we need, and removing the rest.
def clean(from_path, to_path, columns):
def convert_date(date):
if date == '':
... |
# Converting the Jupyter Notebook into a function
# Each scraping section was separated from the main function
# which is scrape()
# libraries
from splinter import Browser
from bs4 import BeautifulSoup as bs
import pandas as pd
import time
# == Initialize browser ==
def init_browser():
executable_path = {"executa... |
from spacepy.pybats import PbData
import math
import numpy as np
import matplotlib.pyplot as plt
# from mayavi import mlab
__author__ = 'artem'
import Parameters
import Utils
params = Parameters.Parameters
def findCloasestIndex(array, value):
return (np.abs(array - value)).argmin()
class Model(PbData):
d... |
import os
import math
import time
from tqdm import tqdm
import torch
import torch.nn as nn
from torch.utils.data import Dataset
DEVICE = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
class Vocabulary:
def __init__(self, pad_token="<pad>", unk_token='<unk>', eos_token='<eos>', sos_token='<sos>'):... |
# This file makes use of the InferSent, SentEval and CoVe libraries, and may contain adapted code from the repositories
# containing these libraries. Their licenses can be found in <this-repository>/Licenses.
#
# CoVe:
# Copyright (c) 2017, Salesforce.com, Inc. All rights reserved.
# Repository: https://github.com/... |
# coding: utf-8
# # Deep MNIST
# #### Construct a deep convolutional MNIST classifier
# #### from https://www.tensorflow.org/versions/r0.9/tutorials/mnist/pros/index.html
# ## Load MNIST Data
# In[2]:
from tensorflow.examples.tutorials.mnist import input_data
# In[3]:
# Load training, validation, and testing ... |
from functools import partial
from textwrap import dedent
from unittest import skip, expectedFailure # noqa: F401
import sublime
from SublimeLinter.lint import (
backend,
Linter,
linter as linter_module,
util,
)
from unittesting import DeferrableTestCase
from SublimeLinter.tests.parameterized import ... |
#
#Copyright Odin Solutions S.L. All Rights Reserved.
#
#SPDX-License-Identifier: Apache-2.0
#
import json
import uuid
#import os
from subprocess import Popen, PIPE
def processUri(uri):
try:
if(str(uri).upper().startswith("/v2".upper()) == False ):
uri = "/v2"+uri
return uri
excep... |
# coding: utf-8
# In[6]:
# This file contains various helper functions that will be useful in creating the network architecture and in training of the network
import torch
import os
import pdb
import pickle
import argparse
import numpy as np
import scipy
import scipy.misc
import warnings
warnings.filterwarnings("ign... |
from sklearn.cluster import KMeans
from sklearn.preprocessing import scale
from copy import deepcopy
import nibabel as nib
import numpy as np
import pandas as pd
import h5sparse
from .cluster import dti_cluster
def mask_img(img,val):
"""masks an image at a given value - borrowed from de la Vega"""
img = de... |
import sys
import traceback
import threading
from queue import Queue
import numpy
import cv2
import gi
gi.require_version('Gst', '1.0')
from gi.repository import Gst, GObject, GLib
def on_message(bus: Gst.Bus, message: Gst.Message, loop: GObject.MainLoop):
mtype = message.type
if mtype == Gst.MessageType.EO... |
# Copyright 2014 Open Source Robotics Foundation, 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 ... |
from ..baseclass.DragBehaviour import DraggableObjectBehavior, DraggableController
from kivy.uix.boxlayout import BoxLayout
from kivy.graphics import Color, Line
from kivy.uix.togglebutton import ToggleButton
from kivy.uix.behaviors import ToggleButtonBehavior
from kivymd.toast import toast
from kivy.lang import Builde... |
"""Test add_text bot module."""
#
# (C) Pywikibot team, 2016-2021
#
# Distributed under the terms of the MIT license.
#
import unittest
from unittest.mock import ANY, MagicMock, Mock, mock_open, patch
import pywikibot
import pywikibot.pagegenerators
from scripts.add_text import AddTextBot, main, parse
from tests.asp... |
# GENERATED BY KOMAND SDK - DO NOT EDIT
import komand
import json
class Input:
GROUPID = "groupid"
HOSTNAME = "hostname"
ID = "id"
IP = "ip"
class Output:
SENSORS = "sensors"
class ListSensorsInput(komand.Input):
schema = json.loads("""
{
"type": "object",
"title": "Variable... |
#-*- coding:utf-8 _*-
"""
@author:charlesXu
@file: get_data.py
@desc: 连接数据库
@time: 2018/08/08
"""
import pymysql
import pprint
import json
import split_sentence
from pymongo import MongoClient
def get_addr():
conn = pymysql.connect(host='localhost',
# host='192.168.11.251',
... |
### plotting TE's
import matplotlib
matplotlib.use('Agg') # set backend for matplotlib
import matplotlib.pyplot as plt
plt.rcParams['pdf.fonttype'] = 42 # this keeps most text as actual text in PDFs, not outlines
import sys
import os
import math
from scipy import stats
import matplotlib.pyplot as plt
plt.rcParams['... |
from __future__ import unicode_literals, absolute_import
from django.db import models, connection
from django.utils.translation import ugettext_lazy as _
from django.core.exceptions import ImproperlyConfigured
from django import get_version
from .descriptors import *
from .dict import *
from .virtual import *
from . ... |
import dill as dill
import torch
import time
from evaluation_metrics.accuracy import dice_coefficient
#Training & Testing Loops
from tqdm.notebook import tqdm
from tqdm import tqdm_notebook
# MODEL STATS
train_losses = []
test_losses = []
train_acc = []
test_acc = []
running_mask_loss=0.0
# running_depth_loss=0.0
#... |
#!/usr/bin/python
from struct import *
import math
## Calculating error , we compere targeted value with expected ### value
def error_fun(t,out,cl):
total=0.0
print("-----------come to error_fun()---------------")
e=[]
#e=[0.5*((t[i]-out[i])*(t[i]-out[i]))for i in range(0,cl,1)]
#e=[if(out[i]!=0.0): -t[i]*(math.... |
"""
Define the recurrent entity network model.
"""
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
from functools import partial
import tensorflow as tf
from entity_networks.dynamic_memory_cell import DynamicMemoryCell
from entity_networks.model_ops import... |
from collections import defaultdict, deque
from tool.runners.python import SubmissionPy
N_COMPUTERS = 50
class ThoreSubmission(SubmissionPy):
def run(self, s):
# :param s: input in string format
# :return: solution flag
program = [int(c) for c in s.split(",")]
computers = [VM(pro... |
"""Utility module."""
import datetime
import typing as t
import numpy as np
import pint
import xarray as xr
from .units import ureg
@ureg.wraps(
ret=None,
args=(
"Pa",
"K",
"m^-3",
"",
"km",
"",
None,
None,
None,
None,
N... |
from __future__ import print_function
import lime
import sklearn
import numpy as np
import sklearn
import sklearn.ensemble
import sklearn.metrics
from sklearn import model_selection, naive_bayes, svm
import numpy as np
import random
from keras.models import Sequential, Model
from keras.layers import Dense,GlobalMaxPool... |
from Evie import xbot, CMD_HELP
import os
import subprocess
import Evie.modules.sql.chatbot_sql as ly
import requests
from gtts import gTTS
from gtts import gTTSError
from requests import get
import requests
from telethon import *
from telethon.tl import functions
from telethon.tl import types
from telethon import ev... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.