text stringlengths 3.07k 12.6k |
|---|
import pathlib
import os
import tempfile
from zipfile import ZipFile
import pytest
from pytest_mock import MockerFixture
from ark.utils.deepcell_service_utils import create_deepcell_output
def mocked_run_deepcell(in_zip_path, output_dir, host, job_type, scale, timeout):
pathlib.Path(os.path.join(output_dir, 'fov... |
from py_expression_eval import Parser
import flatdict
import re
from collections import defaultdict
from pydash.objects import get
from math import ceil
import copy
import babel.dates
from datetime import datetime
DELIM_VALUE = "D34hSK"
SPACE_VALUE = "ASIDJa"
DOT_VALUE = "DOTDOT123"
def parse_number_formula(data, var... |
def input():
input_data = list(filter(None, open('day_20/input.txt').read().split('\n\n')))
return list(map(lambda lines: Tile(lines), input_data))
class Tile:
def __init__(self, lines):
lines = lines.split('\n')
self.id = int(lines[0].split()[1].strip(':'))
self.image = [line.strip... |
from aiida.common.exceptions import InputValidationError
from aiida_lammps.calculations.lammps import BaseLammpsCalculation
from aiida_lammps.common.utils import convert_date_string, join_keywords
from aiida_lammps.validation import validate_with_json
from aiida.plugins import DataFactory
import six
def generate_lamm... |
# amara3.inputsource
"""
Utilities for managing data inputs for Amara
Copyright 2008-2015 <NAME>
"""
import zipfile
import functools
from enum import Enum
from io import StringIO, BytesIO
from amara3 import iri
from urllib.request import urlopen
class inputsourcetype(Enum):
unknown = 0
stream = 1
string... |
import os
import keras
import keras.backend as K
import tensorflow as tf
import numpy as np
from sklearn.metrics import confusion_matrix, f1_score, precision_score, recall_score
from keras.callbacks import Callback, ModelCheckpoint, EarlyStopping, ReduceLROnPlateau, TensorBoard
from keras.optimizers import Adam
def d... |
import random
import numpy as np
from cv2 import cv2
from PIL import Image
import pandas as pd
from Supermarket_class import Supermarket
class Customer:
"""Customer shops at the supermarket"""
def __init__(self, trans_matrix, starting_state_space, image):
self.trans_matrix = trans_matrix
self.... |
import requests
from bs4 import BeautifulSoup
import urllib.request
import os
from tqdm import tqdm
import sys
import platform
class KakaoEmoticonJSON:
def __init__(self, itemcode):
self.itemcode = itemcode
self.imageURL = requests.get("https://e.kakao.com/detail/thumb_url?item_code=" + ... |
import os
from StringIO import StringIO
from pegasus.service import catalogs, api, tests, users
class TestCatalog(tests.TestCase):
def test_names(self):
catalogs.validate_catalog_name("x"*99)
catalogs.validate_catalog_name("site.txt")
self.assertRaises(api.APIError, catalogs.validate_catal... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import base64
from collections import Counter
import io
import os
from django.conf import settings
from django.core.cache import cache
from django.core.management import call_command
from django.db.models import Sum, Min
from django_redis import get_red... |
import padertorch as pt
import torch
import torch.nn as nn
import torch.nn.functional as F
from einops import rearrange
import numpy as np
from padertorch.contrib.je.modules.conv import Pad, compute_pad_size, to_list
from enh_plath.module.norm import build_norm
from typing import Optional
class Conv1d(pt.Module):
... |
###############################################################################
#Non-Standard Imports
###############################################################################
from . import _utils_plot as upp
###############################################################################
#Globals
##############... |
from decimal import Decimal
import json
from typing import Any
from bidict import bidict
import dateutil.parser
from django.contrib.gis.geos import Polygon
from django.db import transaction
import pystac
from pystac.extensions.eo import Band, EOExtension
from pystac.extensions.projection import ProjectionExtension
fro... |
"""
Permet de convertir un RandomForestClassifier de sk-learn sous la forme requise par desi_target dans la classe myRF.
Contient également un petit test pour vérifier si le script fonctionne correctement !
Ce Code n'a plus de soucis avec la version de joblib et fonctionne donc avec les versions récentes ... |
import pandas as pd
from scipy.stats import binom
from typing import List, Tuple
import random
import copy
class Student:
def __init__(self, name):
self.name = name
def __str__(self):
return f"Susceptible st: {self.name}"
def __repr__(self):
return f"Susceptible st: {self.name}"
... |
import os
import time
from typing import List, Tuple
import graphviz
import matplotlib.pyplot as plt
from sklearn import tree
# from adjustText import adjust_text
from sklearn.manifold import TSNE
from analysis.clustering import cluster_data
from log import Log
from plot.plot_clusters import plot_clusters
def plot_... |
# Copyright Contributors to the Pyro-Cov project.
# SPDX-License-Identifier: Apache-2.0
"""
Preprocess Nextstrain open data.
This script aggregates the metadata.tsv.gz file available from:
https://docs.nextstrain.org/projects/ncov/en/latest/reference/remote_inputs.html
This file is mirrored on S3 and GCP:
https://dat... |
import networkx as nx
import matplotlib.pyplot as plt
import seaborn as sns
import scipy
import numpy as np
def get_jaccard_index_threshold_from_kde(input_file, target_percentile=0.97):
data_folder = "../data/"
matrix_file = data_folder + input_file
mutation_dict = dict()
with open(matrix_file, "r") a... |
import argparse
import itertools
import json
import math
from datetime import datetime
from pathlib import Path
from random import random
from torch.optim import Adam
from focal import FocalLoss
from loss import *
from main import run_training, basic_validation, basic_training
from skynet import skynet_training, skyn... |
from struct import Struct
from typing import Sized
int8 = Struct("b")
uint8 = Struct("B")
int16 = Struct("h")
int16be = Struct(">h")
uint16 = Struct("H")
uint16be = Struct(">H")
int32 = Struct("i")
int32be = Struct(">i")
uint32 = Struct("I")
uint32be = Struct(">I")
int64 = Struct("q")
int64be = Struct(">q")
uint64 = S... |
import csv
def csv_to_dict(filename):
row_data = []
f = open(filename)
reader = csv.reader(f)
for row in reader:
row_data.append(row)
f.close()
data = {}
attrs_name = row_data[0] # 第一行是属性名
for d in row_data[1:]:
single_data = {}
for i, attr_name in enumerate... |
# -----------------------------------------------------------------------------
# Copyright (c) 2009-2016 <NAME>. All rights reserved.
# Distributed under the (new) BSD License.
# -----------------------------------------------------------------------------
import re
import logging
from pathlib import Path
log = log... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import tensorflow as tf
def scale_to_new_size(box, img_shape, pad_shape):
"""Scales to new image size.
Args:
box: A [batch, 4] float tensor.
img_shape: A [2] int tensor... |
# -*- coding: utf-8 -*-
from pysignfe.xml_sped import *
from pysignfe.nfe.manual_500 import ESQUEMA_ATUAL
from .evento_base import DetEvento, InfEventoEnviado, Evento, EnvEvento, InfEventoRecebido, RetEvento, RetEnvEvento, ProcEventoNFe
import os
DIRNAME = os.path.dirname(__file__)
class DetEventoCancNFe(DetEvento... |
import uuid
import platform
import copy
import fnmatch
import logging
import os
import pathlib
import sys
import traceback
from collections.abc import Mapping
from datetime import datetime
from glob import glob
from pathlib import Path
from typing import List, Dict, Union
from pytailor.config import RUNDIR_TIME_FORMAT,... |
import logging
import os
import re
import sys
import xml.etree.ElementTree as ET
import czech_stemmer
from RDRPOSTagger_python_3.pSCRDRtagger.RDRPOSTagger import RDRPOSTagger
from RDRPOSTagger_python_3.Utility.Utils import readDictionary
os.chdir('../..') # because above modules do chdir ... :/
from rouge_2_0.rouge_... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jul 25 14:45:41 2019
@author: amaya
"""
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.lines as lines
import matplotlib.patches as patches
import matplotlib.colors as mcolors
import numpy as np
cpalette = ['#e6194B', '#3cb44b', '#4... |
import os
import sys
import numpy as np
import torch
import h5py
from tqdm import tqdm
from torch.utils import data
from torch.utils.data import DataLoader, TensorDataset
import musdb
from yacs.config import CfgNode as CN
import SharedArray as sa
import random
def norm(arr, thres=None, max_=None):
arr -= np.me... |
# --------------
from csv import reader
def explore_data(dataset, start, end, rows_and_columns=False):
"""Explore the elements of a list.
Print the elements of a list starting from the index 'start'(included) upto the index 'end' (excluded).
Keyword arguments:
dataset -- lis... |
#!/usr/bin/env python
import argparse
import html
import itertools
import sys
from datetime import datetime
from pyparsing import alphas, alphanums, delimitedList, Literal, Word, Forward, OneOrMore, ZeroOrMore, CharsNotIn, Suppress, QuotedString, Optional
class Field:
def __init__(self, loc, tok):
self.n... |
#!/usr/bin/env python
# Python script that grabs all the binaries produced when building the
# Sharpmake solution and copies them in a directory. (By default, in a
# directory named /deploy.) Without that script, you need to manually copy
# and paste the binaries of every platform implementation assembly you have
# bu... |
#
# Copyright 2019 FMR LLC <<EMAIL>>
#
# SPDX-License-Identifier: MIT
#
"""Provides additional actions and formatters for the builtin argparse module."""
import argparse
import builtins
import re
from functools import wraps
class RawAndDefaultsFormatter(
argparse.ArgumentDefaultsHelpFormatter, argparse.RawDescr... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# For each test we spin up a tiny, transient HTTP server, to make requests against. Each TestCase class can define a RequestHandler
# that specifies how the server is to respond to calls for the test.
#----------------------------------------------------------------------... |
from __future__ import print_function
from tensorboardX import SummaryWriter
import torch
from torch.optim.lr_scheduler import ReduceLROnPlateau
from utils import evaluate, get_lr, load_checkpoint, save_checkpoint, test, train
from config import TrainConfig as C
from loader.MSVD import MSVD
from loader.MSRVTT import ... |
from typing import Any, List, Optional
from fastapi.exceptions import RequestValidationError
from fastapi.responses import UJSONResponse
from pydantic import EnumError, EnumMemberError, StrRegexError
from starlette.exceptions import HTTPException as StarletteHTTPException
def parse_error(err: Any, field_names: List,... |
import discord # noqa
import asyncio
import copy
import event as evnt
from utility import saveData
from constants import Constants
from datetime import datetime
from discord.ext import tasks, commands
class Updater(commands.Cog):
# TODO: DOCUMENT COG
def __init__(self, client):
# TODO: DOCUMENT INIT
... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function, unicode_literals
import json
from collections import defaultdict
import six
try:
from pathlib import Path
except ImportError: # pragma: no cover
class Path(object):
"""
fake pathlib.Path for retro-compatiblitiy
... |
from __future__ import annotations
from dataclasses import dataclass
from typing import Generic, Tuple, TypeVar, final
from pydantic import parse_obj_as
from expression import SingleCaseUnion, Tag, TaggedUnion, match, tag
_T = TypeVar("_T")
@dataclass
class Rectangle:
width: float
length: float
@datacla... |
# C O D E A Z / Samil
""" Sistem Stats """
from asyncio import create_subprocess_shell as asyncrunapp
from asyncio.subprocess import PIPE as asyncPIPE
from platform import uname
from shutil import which
from os import remove
from userbot import CMD_HELP, COD_VERSION
from userbot.events import register
from userbot.m... |
import numpy as np
import sys
import os
"""
Supporting methods for data handling
"""
def shuffle_batch(images, labels):
"""
Return a shuffled batch of data
"""
permutation = np.random.permutation(images.shape[0])
return images[permutation], labels[permutation]
def convert_index_to_angle(i... |
import numpy
from dabam import dabam
def convert_daniele():
input = "TXI_Flat1.dat"
#
# txt = "http://ftp.esrf.eu/pub/scisoft/dabam/data/dabam-067.dat"
dm = dabam.initialize_from_external_data(input,
column_index_abscissas=0,
column_index... |
"""Module for fetching player data from afl_data service."""
from typing import List, Dict, Any
from datetime import date, datetime, timedelta
import itertools
import math
from functools import partial
import os
import json
from augury.data_import.base_data import fetch_afl_data
from augury.settings import RAW_DATA_D... |
#!/usr/bin/env python
'''
Created on Feb 16, 2015
@author: Rob
'''
import os, sys, argparse, shutil
from byond.basetypes import Atom, Proc, BYONDValue, BYONDList
from byond.script.dmscript import ParseDreamList
from byond import objtree, GetFilesFromDME
'''
/datum/chemical_reaction/honk
name = "honk"
id = "h... |
# import tensorflow as tf
import yaml
import platform
import getpass
from hparammodule.hparam import HParams
# from text import symbols
def get_root_dir(config_file, dir_tag="root_dir", default_dir = None):
"""
Read db_root entries for current user and current machine
Args:
config_file ():
... |
# -*- coding: utf-8 -*-
"""
@author: <NAME>
"""
import re
import pandas as pd
import Lexicons
import Util
import pyaramorph
analyzer = pyaramorph.Analyzer()
file = open('Util_Files/Arabic_Pos_Bigrams.txt', 'r',encoding='utf8')
Pos_ar = [line[:-1].split(' ') for line in file.readlines()]
file = open('U... |
import logging
import re
import time
import uuid
import mysql.connector as database
from flask import abort
from db.maria_database import MariaDB
from templates.four_g_lte_core import FourGLTECore
from templates.four_g_lte_core_rcc import FourGLTECoreRCC
from templates.serviceprofiles import ServiceProfiles
LOG = log... |
# Copyright 2021 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ... |
import math
import sys
import cv2
import numpy as np
import matplotlib.pyplot as plt
# To execute, do python proj.py <input1> <input2>.
# Will write to out.jpg
# Pipeline: find interest points, then create SIFT descriptor, then matching them, then find stitching line.
# Using OpenCV and SIFT to find the... |
# !/usr/bin/python
# -*- coding: utf-8 -*-
# python lib
import os
import sys
import shutil
# clarisse lib
import ix
def replace_path(path):
return path.replace("\\", "/")
class _packages:
"package api"
@staticmethod
def get_reference_project(context):
# p_item = context.get_parent_item()
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from .player import Player
import curses
import sys
class Window:
def __init__(self, stdscr, player, timeout=1500):
self.stdscr = stdscr
self.height, self.width = stdscr.getmaxyx()
self.player = player
self.scroll_pad = curses.newpad(self.player.track.length + ... |
from conans.client.tools.apple import to_apple_arch
def architecture_flag(settings):
"""
returns flags specific to the target architecture and compiler
"""
compiler = settings.get_safe("compiler")
compiler_base = settings.get_safe("compiler.base")
arch = settings.get_safe("arch")
the_os = ... |
"""
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
SPDX-License-Identifier: MIT-0
"""
#pylint: disable=cyclic-import
import cfnlint.rules
OPERATOR = [
'EQUALS',
'NOT_EQUALS',
'==',
'!=',
'IN',
'NOT_IN',
'>=',
'<=']
def CreateCustomRule(rule_id, resourceType, prop, ... |
"""spellingbee.py -- Module to help with spelling correction.
***This module exports***
Classes:
Corrector -- Class to give spelling suggestions for strings.
DictBuilder -- Class to build word dictionaries
Module-level functions:
matchScore -- Returns the matchScore of two sequences.
"""
# Public interface
__all__ ... |
#!/usr/bin/env python
import rospy
from can_msgs.msg import Frame
from celsius.msg import CelsiusReport, CelsiusControl
from struct import unpack
def parse_temperature(raw_temp):
if raw_temp[1] == 73:
temp = 'HI'
elif raw_temp[1] == 79:
temp = 'LO'
else:
lower = raw_temp[1] & 0x0F
... |
from __future__ import division
import matplotlib.pyplot as plt
import numpy as np
import math, sys
def periodic (i, limit, add):
"""
Choose correct matrix index with periodic
boundary conditions
Input:
- i: Base index
- limit: Highest \"legal\" index
- add: Number to add or subtract... |
#
# 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... |
# Copyright 2020 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
# # ⚠ Warning
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
# LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
# NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIA... |
import os
import re
import threading
import sublime
from .preferences_filename import preferences_filename
from .thread_progress import ThreadProgress
from .package_manager import PackageManager
from .upgraders.git_upgrader import GitUpgrader
from .upgraders.hg_upgrader import HgUpgrader
from .versions import version... |
import binascii
import logging
import io
import struct
from pycoin.block import Block, BlockHeader
from pycoin.encoding import double_sha256
from pycoin.serialize import b2h_rev, bitcoin_streamer
from pycoin.tx.Tx import Tx
from pycoinnet.InvItem import InvItem
from pycoinnet.PeerAddress import PeerAddress
# definit... |
from collections import defaultdict
import json
import re
import sys
from bs4 import BeautifulSoup
import dateparser
from etaprogress.progress import ProgressBar
import requests
###################
# SCRAP FILM LIST #
###################
def parse_list_page(page_url):
r = requests.get(page_url)
soup = Beauti... |
""" Promus core
This package contains the object that executes commands on your
behave as well as other utility functions.
"""
import re
import os
import sys
import socket
from promus.command import exec_cmd, date
from promus.core.ssh import (
make_key,
get_keys,
get_public_key,
read_config,
writ... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
from modules.logging import logging_decorator
from telegram.ext.dispatcher import run_async
from telegram import ChatAction
from telegram.ext import MessageHandler, PrefixHandler
from modules.utils import Caption_Filter, send_image
from PIL import Image, ImageDraw, ImageOps
fro... |
from django.conf import settings
from django.core.urlresolvers import clear_url_caches
from django.db import models
from django.db.models.signals import pre_delete, post_delete
from django.utils.encoding import smart_str
from django.utils.translation import get_language, get_language_info, ugettext_lazy, ugettext as _... |
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
"""
Utils.
"""
import os
import random
import numpy as np
import time
import torch
import torchvision
import torch.nn as... |
# -*- coding: utf-8 -*-
"""Run clang formatter on a file or directory."""
# yapf: disable
# Standard library imports
import argparse
import difflib
import os
import subprocess
import sys
# yapf: enable
PY3 = sys.version_info[0] == 3
WIN = sys.platform.startswith('win32')
CLANG_FORMAT_EXE = 'clang-format.exe' if WI... |
from typing import List, Tuple
import copy
import torch
import torchelie.nn as tnn
import torchelie.utils as tu
import torch.nn as nn
class Pix2PixHDGlobalGenerator(tnn.CondSeq):
"""
Residual generator used in `Pix2PixHD <https://arxiv.org/abs/1711.11585>`_
.
:code:`arch` is a list of strings repre... |
#!/usr/bin/python
#-*- coding: UTF-8 -*-
import sys
import os
import logging
import time
import datetime
import ftplib
import tarfile
import httplib
import json
def generate_file_name(day_str):
year = int(day_str[0:4])
month = int(day_str[5:7])
day = int(day_str[8:10])
cur_date = datetime.date(year, m... |
# For run instructions, see README.md.
import pandas as pd
import sys
# Store command-line argument (DATE)
DATE = sys.argv[1]
def clean_o365_license_list(df):
"""
This function takes in an Office 365 license list (as a DataFrame) and cleans various aspects and then returns the cleaned list.
Paramete... |
import keras
from utils.load_cifar import load_data
from keras.preprocessing.image import ImageDataGenerator
from models import resnet, VGGnet
from utils.schedules import onetenth_60_120_160
from utils.channel_pruning import freeze_SR_layer, set_compact_model_weights
import argparse
import os
import matplotlib
matplot... |
import argparse
import keras.backend.tensorflow_backend as ktf
import numpy as np
import tensorflow as tf
from bokeh.embed import server_document
from bokeh.layouts import column, gridplot
from bokeh.models import ColumnDataSource, Slider
from bokeh.plotting import figure
from bokeh.sampledata.sea_surface_temperature ... |
import tkinter as tk
index = tk.Tk()
def coded():
def a():
pass
pass
pass
pass
try:
message=e_message.get()
message_numbers=[]
for i in message:
message_numbers.append('a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z'.... |
import os
import time
import argparse
import numpy as np
import torch
import open3d as o3d
from fusion import TSDFVolumeTorch
from dataset.tum_rgbd import TUMDataset
from tracker import ICPTracker
from utils import load_config, get_volume_setting, get_time
vis_param = argparse.Namespace()
vis_param.frame_id = 0
vis_p... |
#
# Copyright 1993-2018 NVIDIA Corporation. All rights reserved.
#
# NOTICE TO LICENSEE:
#
# This source code and/or documentation ("Licensed Deliverables") are
# subject to NVIDIA intellectual property rights under U.S. and
# international Copyright laws.
#
# These Licensed Deliverables contained herein is PROPRIETAR... |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from fairseq.modules import LayerNorm
from fairseq.utils impor... |
"""
This is an example that amounts to an offline picbreeder.org without any nice features. :)
Left-click on thumbnails to pick images to breed for next generation, right-click to
render a high-resolution version of an image. Genomes and images chosen for breeding
and rendering are saved to disk.
"""
import math
impo... |
import sys
import os
import pathlib
import setuptools # noqa, importing this had some side effect?
from distutils.core import setup, Extension
from distutils.command.clean import clean as Clean
import distutils.util
import shutil
from Cython.Build import cythonize
import numpy
# The directory containing this file
HER... |
#!/usr/bin/env python
import googleapiclient.discovery
import argparse
import collections
import jinja2
import os
import os.path
import hashlib
import docker
from shutil import copyfile, copymode
zones = []
ips = {}
template_source = "haproxy.jinja2"
template_dest = "haproxy.cfg.new"
haproxy_cfg = "haproxy.cfg"
clien... |
import os
import sys
import time
import numpy as np
import tensorflow as tf
from PIL import Image, ImageDraw
from jaccard_overlap import jaccard_overlap
from playground.plan_boundingbox import create_ssd_layers, create_boxes
FLAGS = tf.flags.FLAGS
tf.flags.DEFINE_string('train_path', None, "")
tf.flags.DEFINE_strin... |
# Copyright 2020 Dakewe Biotech Corporation. All Rights Reserved.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by... |
#
# Convolutional neural network for the CIFAR-10 image classification
# https://www.cs.toronto.edu/~kriz/cifar.html
#
import pickle
import numpy as np
import matplotlib.pyplot as plt
import time
from sklearn.preprocessing import OneHotEncoder
import tensorflow as tf
from tensorflow import keras
from keras.datasets im... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# File: mnist_center.py
# Author: <NAME> <<EMAIL>>
import sys
import numpy as np
import tensorflow as tf
import platform
import scipy.misc
import argparse
import read_mnist as loader
sys.path.append('../')
from lib.dataflow.mnist import MNISTData
from lib.... |
import argparse
import os
import json
import shutil
import random
from itertools import islice
import torch
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
sns.set()
import torch.utils.data as data
from datasets import get_CIFAR10, get_SVHN, get_FashionMNIST, get_MNIST, postprocess
from mode... |
import itertools
import sys
import pytest
from odherogrid.enums import Bracket, Layout
from odherogrid.herogrid import (HeroGrid, HeroGridConfig,
detect_userdata_path,
get_hero_grid_config_path, _get_steam_path_windows)
def _get_hero_wl(hero: dict, b... |
from os import system, makedirs, chdir
from os.path import isfile, isdir
from sys import platform
from urllib.request import urlretrieve
from subprocess import check_output
class NotSupportedError(Exception):
@staticmethod
def throw(exe, version, supported):
raise NotSupportedError("version '{0}' of '... |
from tkinter import *
WD = 500
ZR = WD / 2
KF = 10
def dec_to_scr(cords):
return round(cords[0] * KF + ZR), round(ZR - cords[1] * KF)
def axis():
cnvs.create_line(0, 250, 500, 250, arrow=LAST, fill='green')
cnvs.create_line(250, 500, 250, 0, arrow=LAST, fill='green')
cnvs.create_text(WD - 20, ZR + ... |
#
# Copyright (c) 2020 Pangeanic SL.
#
# This file is part of NEC TM
# (see https://github.com/shasha79/nectm).
#
# 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 owne... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
$
"""
from __future__ import annotations # isort:skip
from __future__ import annotations
import abc
import ast
from pathlib import Path
from pickle import PicklingError
from typing import Any, Collection, Dict, Optional, Sequence, Union
import libcst as cst
from... |
import logging
import re
from os import path, mkdir, listdir
from shutil import rmtree, copytree
from string import Template
from tempfile import mkdtemp
from ..externel_executors import CompiledExecutor
from ..rpc.exceptions import MSG_CANNOT_GUESS_METHOD
logger = logging.getLogger(__name__)
class JavaExecutor(Com... |
from glumpy import app, gloo, gl
from contextlib import contextmanager
import numpy as np
try:
import pycuda.driver
from pycuda.gl import graphics_map_flags, BufferObject
_PYCUDA = True
except ImportError as err:
print('pycuda import error:', err)
_PYCUDA = False
import torch
class OffscreenRen... |
from binaryninja import Symbol, Type, log, demangle
from binaryninja.enums import SymbolType
from .utils import BinjaStruct, read_cstring, check_address, update_percentage
def check_rtti_signature(view, magic):
if view.address_size == 4:
return magic == 0
if view.address_size == 8:
return magi... |
import torch
import numpy as np
from torch import Tensor
@torch.jit.script
def stable_softmax(logits: torch.Tensor):
logits_m = logits - logits.max(dim=1)[0].unsqueeze(1)
exp = torch.exp(logits_m)
probs = exp / torch.sum(exp, dim=1).unsqueeze(1)
return probs
class ImageNet21kSemanticSoftmax:
def... |
"""
User Management Assesment process / daemon
This is being developed for the MF2C Project: http://www.mf2c-project.eu/
Copyright: <NAME>, Atos Research and Innovation, 2017.
This code is licensed under an Apache 2.0 license. Please, refer to the LICENSE.TXT file for more information
Created on 27 sept. 2017
@auth... |
#!/usr/bin/env python3
import argparse
import curses
import functools
import os
import pathlib
import signal
import subprocess
import sys
__version__ = '1.0.0'
THEME_PATH = pathlib.Path('~/.base16_theme').expanduser()
SHELL = '/bin/sh'
NUM_COLORS = 22
class Theme:
def __init__(self, path):
self.path =... |
import collections
import logging
from multiprocessing import Process, Queue, Manager
try:
# Python 3
import queue
except ImportError:
import Queue as queue
import sys
import time
import boto3
import six
log = logging.getLogger(__name__)
def sizeof(obj, seen=None):
"""Recursively and fully calculate... |
from __future__ import absolute_import
import logging
import os
import subprocess
from xml.etree import ElementTree
from six.moves import map
import six
log = logging.getLogger(__name__)
class Tool(object):
"""
Base class for tools
"""
name = ''
def __init__(self, problems, options=None, base_pa... |
"""
Author: <NAME>, Phd Student @ Ishida Laboratory, Department of Computer Science, Tokyo Institute of Technology
Created on: December 17th, 2019
Description: This file contains functions for finding and extracting reaction cores.
"""
from copy import deepcopy
from chemistry_methods.reactions import parse_reac... |
import time
from db import *
from mail import send_mail
from flask import Flask, request, jsonify, make_response, g, render_template
from flask_cors import CORS
from flask_httpauth import HTTPTokenAuth
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from flask_socketio import SocketIO, join_room,... |
from __future__ import division
import os.path
import pytest
import numpy as np
import healpy as hp
from healpy import Rotator
from healpy.rotator import euler, euler_matrix_new
path = os.path.dirname(os.path.realpath(__file__))
# A pytest fixture with autouse=True is run before each of the other tests
@pytest.fi... |
############################################################################
# #
# Copyright (c) 2021 <NAME> #
# #
# Licensed under t... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.