text stringlengths 3.07k 22.1k |
|---|
import numpy as np
from functools import partial
from keras import backend as K
from keras.losses import categorical_crossentropy
from brats.config import config
from unet3d.utils import metrics_utils as utils
K.set_image_data_format("channels_first")
def dice_coefficient(y_true, y_pred, smooth=0.00001):
y_true_... |
"""
Distributions of the kind:
1. \alpha_0 * \delta(x) + (1 - \alpha_0) * f(x) [0 < x < 1]
2. \alpha_0 * \delta(x) + \alpha_1 * \delta(1-x) + (1 - \alpha_0 - \alpha_1) * f(x) [0 < x < 1]
where \alpha_i \in (0, 1)
and f(x) is a properly normalised density in the open (0, 1)
"""
import torch
from torch.d... |
# -*- coding: utf-8 -*-
import abc
import importlib
import math
import os
try:
import cPickle as pickle
except ImportError:
import pickle
import typing
import joblib
from sklearn.base import ClassifierMixin
from sklearn.pipeline import Pipeline, FeatureUnion
from sklearn.utils.metaestimators import _BaseCompo... |
import os
from collections import defaultdict
from datetime import datetime
import pandas as pd
import pyarrow as pa
import pyarrow.parquet as pq
import requests
from bs4 import BeautifulSoup
from config import *
from extractor import extract
from utils import create_client_engine, validate_df
# from sqlalchemy impo... |
import ctypes;
from .iBaseType import iBaseType;
cCTypesPrimitiveMetaType = type(ctypes.c_byte);
class tCreateArrayMetaType(object):
_type_ = "X"; # Placeholder to satisfy ctypes
def __getitem__(cSelf, uIndex):
return iArrayBaseType.fcCreateClass(cSelf, uIndex);
class iPrimitiveBaseType(iBaseType, metaclass=... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jul 15 14:04:43 2019
@author: avelinojaver
"""
import torch
from torch import nn
import torch.nn.functional as F
import math
from functools import partial
def init_weights(net, init_type='xavier', init_gain=0.02):
"""Initialize network weights.
... |
#from itertools import zip
import copy
from functools import reduce
import numpy
import matplotlib.pyplot as plt
import os
import pdb
from scipy import stats, optimize
import sys
from matplotlib import rc
import time
sys.path.insert(0,'..')
import accelerated_functions as af
import constants as c
from mesh import Mes... |
from snownlp import SnowNLP
from wordcloud import WordCloud, ImageColorGenerator, STOPWORDS
from gensim import corpora, models
from collections import Counter
from PIL import Image
from io import BytesIO
import pandas as pd
import numpy as np
import sqlite3
import jieba
import base64
import matplotlib.pyplot as plt
imp... |
#!/usr/bin/env python3
import subprocess
import os
import re
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any, Iterator, List, Mapping, Optional, Tuple
from argparse import ArgumentParser
from contextlib import contextmanager
import libtmux
from path_utils import get_exclusive... |
# -*- coding:utf-8 -*-
"""Reader and writer for collada format
:Organization:
AIST
Requirements
------------
* numpy
* lxml xml parser
* pycollada
Examples
--------
Read collada model data given the file path
>>> r = ColladaReader()
>>> from . import utils
>>> m = r.read(utils.resolveFile('package://atlas_descri... |
import asyncio
import functools
import typing
from datetime import datetime
from enum import Enum
import esipy
import tinydb
import discord
from discord.ext import commands
from utils.esicog import EsiCog
from utils.kvtable import KeyValueTable
from utils.log import get_logger
ZKILLBOARD_BASE_URL = "https://zkillboa... |
#!/usr/bin/env -S python3
# SPDX-License-Identifier: MIT
# Copyright 2022 hirmiura <https://github.com/hirmiura>
#
# Bitmap Font Generator Configuration file class
from __future__ import annotations
import inspect
import io
import re
import sys
from dataclasses import dataclass, field
from functools import total_order... |
__author__ = 'adeb'
import numpy as np
import theano
from theano.tensor.signal import downsample
from theano.tensor.nnet import conv, conv3d2d
from theano.tensor.shared_randomstreams import RandomStreams
from spynet.utils.utilities import share, get_h5file_data
from spynet.models.max_pool_3d import max_pool_3d
cl... |
# -*- coding: utf-8 -*-
from flask import current_app
# from sqlalchemy import false
# from datetime import timedelta
# from jinrui.config.enums import ActivityStatus, UserActivityStatus, OrderMainStatus, CourseStatus, CouponStatus, \
# CouponUserStatus, ProductType, ProductStatus
from jinrui.extensions.register_ex... |
from django.shortcuts import render
from django.http import HttpResponseRedirect
from django.urls import reverse
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.models import User
import re, os
from . import NNdupe as nnd
from users.models import UserProfile
import requests, ast
fro... |
# Copyright (c) 2020 PaddlePaddle 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 appli... |
import sys
from django.template.defaultfilters import slugify
from django.utils.datastructures import SortedDict
from .utils import get_verbose_name, is_iterable
class FacetLabel(object):
def __init__(
self,
facet,
name,
slug=None,
is_all=False,
is_selected=False,
... |
import os, time, math
from pprint import pprint
from random import randrange
class Board:
def __init__(self, size=[15, 40]):
self.size = size
def get_status(self, position):
if position.x >= self.size[1] or position.y >= self.size[0]:
return "NaN"
else:
r... |
# -*- coding: utf-8 -*-
# The contents of this file are subject to the Python Software Foundation
# License Version 2.3 (the License). You may not copy or use this file, in
# either source code or executable form, except in compliance with the License.
# You may obtain a copy of the License at http://www.python.org/l... |
from __future__ import unicode_literals
import math
import frappe
from frappe.utils import cstr, add_days, date_diff, getdate, format_date
from frappe import _, bold
from frappe.utils.csvutils import UnicodeWriter, read_csv_content
from frappe.utils.data import format_date
from frappe.utils.file_manager import get_file... |
# coding: utf-8
# In[1]:
'''Example script to generate text from Nietzsche's writings.
At least 20 epochs are required before the generated text
starts sounding coherent.
It is recommended to run this script on GPU, as recurrent
networks are quite computationally intensive.
If you try this script on new data, mak... |
import struct
class Header:
start_byte = 0xAF
header_size = 15 # WARNING: This has to match with the size in packets.h!!!!
def __init__(self, packet_type: int,
src_interface: int = 0, packet_len: int = 0,
uid: int = 0, source: int = 0,
destination: int = 0, ttl: int = 10):
self.packet_len = p... |
from __future__ import absolute_import
import os,sys
import socket
from argparse import ArgumentParser, SUPPRESS
PROYECT_ROOT= os.path.dirname(os.path.realpath(__file__))
def loadConfig(configFilesList):
paramsDict= {}
for configFile in configFilesList:
if not os.path.isfile(configFile):
raise ValueErro... |
import json
import requests
import time
class ExplorationTestCase(object):
'''Wrapper for the test case part of an Exploration.'''
def __init__(self, names, test_case):
self._names = names
# See https://api.codehunt.com/ for documentation on interface TestCase
self.test_case = test_ca... |
# encoding:utf-8
from django.shortcuts import render
import sys
import os
import time
import datetime
import paramiko
import multiprocessing
import django
import random
import logging
sys.path.extend(['/home/liu/PycharmProjects/USMP'])
os.environ["DJANGO_SETTINGS_MODULE"] = "USMP.settings"
django.setup()
... |
# Copyright 2020 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://aws.amazon.com/apache2.0/
#
# or in the "license" file acc... |
"""
Models for ``icekit_events`` app.
"""
# Compose concrete models from abstract models and mixins, to facilitate reuse.
from collections import OrderedDict
from datetime import datetime, timedelta, time
from django.db.models import F
from django.utils.timezone import make_aware
from icekit.publishing.managers impor... |
import warnings
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
from sklearn.decomposition import TruncatedSVD, PCA
from sklearn.manifold import TSNE
from sklearn.model_selection import StratifiedKFold
from sklearn.preprocessing import StandardScaler, RobustScaler
warnings... |
import json
import sys
class Lane:
def __init__(self, laneid, peids):
self.laneid = laneid
self.peids = peids
def get_relpeid(self, peid):
if peid in self.peids:
return self.peids.index(peid)
else:
raise Exception("PE ID {:d} not in this lane!".format(pe... |
from django.contrib.contenttypes.models import ContentType
from django.db.models import F
from django.shortcuts import get_object_or_404
from django_comments.views.moderation import perform_flag
from rest_framework import generics, mixins, permissions, renderers, status
from rest_framework.pagination import PageNumbe... |
import gym
from random import randint
from sigma_graph.envs.figure8.action_lookup import MOVE_LOOKUP, TURN_90_LOOKUP
import argparse
def print_lookup():
print("'Move' actions: ", MOVE_LOOKUP)
print("'Turn' actions: ", TURN_90_LOOKUP)
def print_agents(env):
# print("Step #{}/{}".format(env.st... |
import numpy as np
from vtk.util.numpy_support import numpy_to_vtk, vtk_to_numpy
from .permutation_test import *
from .test_statistics import *
from .clustering import Cluster
class MonteCarloThreshold(object):
def __init__(self,
ref_mesh,
data, #M = participants, N = vertices, ... |
import re
import numpy as np
from libzmx import UnknownSurface, Property, AuxParameter
# It's hard to handle Nonsequential object references as gracefully as
# sequential surface references because there is no Set/Get/FindLabel
# method for them. Still, there's probably a better approach than the
# one taken here.
... |
#!/usr/bin/python
# ex:set fileencoding=utf-8:
from __future__ import unicode_literals
from django.conf import settings
from django.contrib.contenttypes.fields import GenericRelation
from django.contrib.contenttypes.models import ContentType
from django.core.exceptions import AppRegistryNotReady
from django.core.exce... |
"""
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions ... |
import math
from datetime import datetime
import torch
import tqdm
from common.utils import saver
from common.utils.early_stopper import EarlyStopper
from common.utils.logger import PerformanceLogger
from common.utils.optim import get_optimizer
from common.utils.seed import set_seed
from .dataset.dataset import Datas... |
import torch
import numpy as np
from itertools import product
def decode(loc, priors, variances):
"""Decode locations from predictions using priors to undo
the encoding we did for offset regression at train time.
Args:
loc (tensor): location predictions for loc layers,
Shape: [num_prio... |
import argparse
import glob
import logging
import sys
import os
import torch
from torch_scatter import scatter_add
from tqdm import tqdm
import torch.nn.functional as F
import torch.nn as nn
from torch_geometric.nn import GCNConv
from complete import Complete, convert_edge2adj, normalize, _complete_acc
from utils impor... |
#!/bin/env python
# -*- coding: utf-8 -*-
# !!!!! Reference from: https://blog.csdn.net/sinat_38682860/article/details/81036402
import random
import win32api
import win32gui
import pytesseract
import win32con
import sys
import os
import time
from PIL import ImageGrab
class_name = "SunAwtFrame"
title_... |
__author__ = 'thor'
"""
Utilities to measure binary classification performance based on the confusion matrix.
Definitions taken from http://en.wikipedia.org/wiki/Confusion_matrix.
Author: <NAME>
"""
from numpy import *
import sklearn as sk
import matplotlib.pyplot as plt
# metric_mat: dict of matrices which produc... |
import os
import sys
import csv
import time
import pygame
import keyboard
from pydub import AudioSegment
songStructure = []
transitionQueue = []
musicQueue = []
songLoaded = False
# smaller buffer for less latency
pygame.mixer.pre_init(frequency=44100, buffer=512)
pygame.mixer.init()
pygame.init()
# thank you https:... |
#!/usr/bin/env python
# Copyright (c) 2018, DIANA-HEP
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# list ... |
#!/usr/bin/env python
''' ---------------- About the script ----------------
Self-assigned project: Emotion recognition using transfer learning
The script takes a face images FER-2013 dataset as an input, instantiates a pre-trained VGG-Face deep CNN model and adds a fully-connected classifier relevant to the new... |
__all__ = ('EncryptedBlockStorage',)
import struct
import hmac
import hashlib
from pyoram.storage.block_storage import (BlockStorageInterface,
BlockStorageTypeFactory)
from pyoram.crypto.aes import AES
import six
class EncryptedBlockStorageInterface(BlockStorageInterface):
... |
# Copyright 2014 Mirantis, 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 ... |
import json
import pytest
from datetime import datetime
from random import randint
from models import Patient, OnPathway, DecisionPoint, Milestone
from trustadapter.trustadapter import Patient_IE, TestResult_IE
from SdTypes import DecisionTypes, MilestoneState
from hamcrest import assert_that, equal_to, not_none, none,... |
#!/usr/bin/env python3
import json
import models
import utils
import argparse,random,logging,numpy,os
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from torch.autograd import Variable
from torch.utils.data import DataLoader
from torch.nn.utils import clip_grad_norm
... |
import argparse
import os
import glob
import numpy as np
np.random.seed(2016)
from keras import backend as K
from keras.callbacks import ModelCheckpoint
from keras.models import Model, Sequential
from keras.layers import Input
from keras.layers import Conv2D, MaxPooling2D, UpSampling2D, Dense
# from keras.layers impor... |
import os
import cv2
import glob
import re
import math
import numpy as np
from bbox_utils import xywh_to_xyxy
from os.path import basename, splitext
def tryint(s):
try:
return int(s)
except:
return s
def alphanum_key(s):
""" Turn a string into a list of string and number chunks.
"... |
import copy
import timeit
from django.core.exceptions import ValidationError
from django.db.utils import IntegrityError
from base.tests import BaseTestCase
from company.tests.tests_models import get_or_create_company
from document.tests.tests_models import get_or_create_document
from inventory.models import (Item, It... |
#
# 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 us... |
import os
from os.path import join, exists
import shutil
from utils import rm_force
import logging
from utils import DefectClass as DC
from typing import List, Tuple, Dict
logger = logging.getLogger(__name__)
class Dump:
def _json_to_dump(self, json):
for test, data in json.items():
test_dir... |
#!/usr/bin/env python
import os
from CP2K_kit.tools import traj_tools
from CP2K_kit.tools import traj_info
mulliken_pop_file_pre_num = 5
mulliken_pop_file_late_num = 3
def restart_history(restart_id, proj_name, QMMM, QM_num, data_dir):
pos_file = ''.join((data_dir, '/', proj_name, '-pos-1.xyz'))
if os.path.exis... |
import torch
import torch.nn as nn
from .utils import InitWeights_He
class conv(nn.Module):
def __init__(self, in_c, out_c, dp=0):
super(conv, self).__init__()
self.in_c = in_c
self.out_c = out_c
self.conv = nn.Sequential(
nn.Conv2d(out_c, out_c, kernel_size=3, padding=... |
#import
import re, os
from collections import Counter
from symspellpy.symspellpy import SymSpell as SymSpellPy, Verbosity
from gensim.models import Word2Vec
from sklearn.datasets import fetch_20newsgroups
import re
import nltk
import string
from nltk.corpus import stopwords
from gensim.test.utils import datapath
import... |
#!/usr/bin/python
"""
User chooses preferred DBMS and test scenario,
a tmux window opens and the transaction steps run in the specified order.
Transaction steps are to be found in mvcc_tests.yml file.
Up to three concurrent transactions are supported.
Supported DBMSs are: MySQL | Oracle | SQL Server | PostgreSQL
Can r... |
# This file is Copyright 2021 Volatility Foundation and licensed under the Volatility Software License 1.0
# which is available at https://www.volatilityfoundation.org/license/vsl-v1.0
#
import logging
import struct
from typing import Tuple, Optional
from volatility3.framework import constants, exceptions, interfaces
... |
from flask import Blueprint
from flask import Response, send_file
from app import app
from time import sleep
import merakiapi
import os
import shutil
import sys
import xlrd
configure_blueprint = Blueprint('configure', __name__, template_folder='templates')
# Route to step 3 with progress bar
@app.route('/step3')
d... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from .build_my_library import *
if sys.version_info[0] > 2:
from tkinter import *
import tkinter.filedialog as tkFileDialog
import tkinter.messagebox as tkMessageBox
import tkinter.simpledialog... |
from __future__ import annotations
from typing import TYPE_CHECKING
import ba
import _ba
import random
import weakref
from bastd.ui import popup
from bastd.ui.popup import PopupWindow
if TYPE_CHECKING: pass
class NewPopupMenuWindow(PopupWindow):
def __init__(self,
position: Tuple... |
import os
import logging
import argparse
import yaml
import json
import ast
import base64
import sys
import numpy as np
from importlib import import_module
from inspect import getmembers, isclass
import struct
from array import array
if sys.version_info < (3, 0):
import cPickle as pickle
import imp
def fr... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2019 <NAME> <<EMAIL>>
# and the Talkowski Laboratory
# Distributed under terms of the MIT license.
"""
Gather lists of genes with evidence of expression variability in GTEx
"""
import pandas as pd
import numpy as np
from os import path
import gzip
impo... |
import argparse
import json
from collections import defaultdict
from multiprocessing.dummy import Pool
import requests
import logging
from ya_courier_helpers.util import chunks, get_duplicates, post_request, \
get_request, delete_request, get_mvrp_request, get_mvrp_solution, valid_date
FORMAT = '%(asctime)-15s %... |
from typing import Dict
import zarr
from skimage.transform import pyramid_gaussian
import numpy as np
from numcodecs import Blosc
from pathlib import Path
import functools
import operator
from tqdm import tqdm
import json
import dask.array as da
import dask
import tifffile
import zipfile
from glob import glob
import os... |
bl_info = {
"name": "Texture Bakery",
"author": "<NAME>",
"version": (1, 0, 3),
"blender": (2, 93, 0),
"location": "Properties > Scene > Texture Bakery",
"description": "Helps shortcut the rigorous process of baking textures with some helpful UI",
"warning": "",
"doc_url": "",
"categ... |
import psycopg2
import copy
import cPickle
import re
from operator import itemgetter
# convert float (0 to 1) to 8 bit web color (e.g. 00 to ff)
def f2c(x):
if x > 1.0: x = 1.0
if x < 0.0: x = 0.0
c = hex(int(255*x))[2:]
if len(c) == 1:
c = '0' + c
return c
# Faster than copy.deepcopy, but... |
import lxml.etree as ET
from collections import namedtuple
import re
import pandas
def load_infa_log_to_df(xml_file):
parsed_xml = ET.parse(xml_file)
log_entries = parsed_xml.findall(".//logEvent")
print("Log entries read:" + str(len(log_entries)))
def get_fields(l):
from datetime import dat... |
'''
Single-GPU training code
'''
import argparse
import numpy as np
import tensorflow as tf
import importlib
# import glob
import os
import sys
import natsort
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
sys.path.append(BASE_DIR)
import time
from random import shuffle
parser = argparse.ArgumentParser()
p... |
import tensorflow as tf
import numpy as np
from scvelo.tools.utils import make_unique_list
from tqdm.notebook import tqdm
import scvelo as scv
from .optimize_utils import Model_Utils, exp_args
from .utils import save_vars, new_adata_col, min_max
from .pl import plot_phase_portrait, plot_loss
exp = tf.math.exp
log = tf... |
# -*- coding: utf-8 -*-
"""
PEP 8 -- Style Guide for Python Code
https://www.python.org/dev/peps/pep-0008/
@author: <NAME>
"""
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
def GPR(X_train,y_train,X_val,r2,s2):
""" Estimates the output y_val given the input X_val, using the training data... |
# BLE iBeaconScanner based on https://github.com/adamf/BLE/blob/master/ble-scanner.py
# JCS 06/07/14
# BLE scanner based on https://github.com/adamf/BLE/blob/master/ble-scanner.py
# BLE scanner, based on https://code.google.com/p/pybluez/source/browse/trunk/examples/advanced/inquiry-with-rssi.py
# https://github.com/... |
import argparse
import pandas as pd
import os
import itertools
import math
import numpy as np
import logging
logging.basicConfig (format="%(asctime)s %(levelname)s: %(message)s", level=logging.INFO)
from helpful_functions import readEmbeddings, normalize, sigmoid, logsigmoid, MAIN_FEAT
def readArgs ():
parser = argpa... |
from math import radians, cos, sin, asin, sqrt
from django.db import models
from django.db.models import DO_NOTHING, DateTimeField
from iso3166 import countries
from geo_ez.constants import ACCURACY_CHOICES
from geo_ez.us_census_class import USCensus
from geo_ez.usps_class import USPS
class GISPoint(models.Model):
... |
#
# =================================================================
# =================================================================
import copy
from nova.openstack.common import log as logging
from powervc_nova.network.powerkvm import agent
from powervc_nova.network.powerkvm.agent import commandlet
from powervc_... |
import logging
import math
import numpy as np
import scyjava
from jpype import JException, JImplements, JOverride
from . import accesses
from . import caches
from . import types
from . import util
from .reference_store import ReferenceStore
_global_reference_store = ReferenceStore()
_logger = logging.getLogger(__n... |
from simpletransformers.classification import ClassificationModel
from pprint import pprint
import numpy as np
import csv
import os
from operator import itemgetter
from sklearn.metrics import classification_report
from scipy.special import softmax
SAVE_DIR = 'simple_models'
d_list = []
def predict(outpu... |
from django.shortcuts import render
from django.http import HttpRequest, HttpResponseRedirect, HttpResponse
from chat.models import *
from chat.pirate import chat_like_a_pirate
from django.contrib.auth.decorators import login_required
from django.contrib.auth import logout
import datetime
from django.template.loader im... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 19 11:44:17 2018
@author: isaaclera
"""
import matplotlib
matplotlib.use('agg')
import csv
def autolabel2(rects,hshift,a,b):
i = 0
for rect in rects:
h = rect.get_height()
ax.text(rect.get_x()+rect.get_width()/2., 1.05*h+h... |
import re
import abc
import logging
import subprocess as sp
from pathlib import Path
from typing import Union
from pyntcloud import PyntCloud
from utils._version import __version__
from evaluator.gdiam_wrapper import findMaxNNdistance
logger = logging.getLogger(__name__)
class BaseMetrics(metaclass=abc.ABCMeta):
... |
'''
Created on 2013-04-03
@author: Noobie
'''
import traceback
from urllib import urlencode, quote
from datetime import datetime
import simplejson
from twisted.web.http_headers import Headers
from twisted.web import http
from twisted.web import client
from twisted.python import log
from txriakdb import objectid
cl... |
# -----------------------------------------------------------------------------------------------------
'''
&usage: CNN-CTC的中文语音识别模型
@author: <NAME>
#net_str: cnn32 -> cnn64 -> cnn128 -> dense -> softmax -> ctc_cost
'''
# -------------------------------------------------------------------------------------------------... |
# random seed instantiated here for reproducibility
RANDOM_SEED = 1337
import numpy as np
np.random.seed(RANDOM_SEED)
import tensorflow as tf
tf.set_random_seed(RANDOM_SEED)
from keras.layers import Input, Conv2D, MaxPooling2D, Conv2DTranspose
from keras.layers import concatenate, BatchNormalization, Dropout, UpSamplin... |
#=============================================================================
#
# ALLSorts v2 - Pre-processing Stage
# Author: <NAME>
# License: MIT
#
#=============================================================================
''' --------------------------------------------------------------------------
Imp... |
import attr
import typing
import pathlib
import importlib.util as imputil
import collections
import pygtrie
import itertools
import functools
import ruamel.yaml as yaml
@attr.s(
slots = True,
cmp = True,
frozen = True,
cache_hash = True
)
class Entry:
"""
Represents a lexical entry.
... |
#!/usr/bin/env python3
import random
import copy
import time
from collections import defaultdict
import signal
import sys
##########################################################
## The base class of a pattern, the basis of the game
class pattern:
#subelems: the subelements of this pattern
#mutators: list of... |
#!/usr/bin/python3
# default python version used : 3.9
# follow this link to change your python version if you have
# a different version installed
# https://stackoverflow.com/questions/52584907/how-to-downgrade-python-from-3-7-to-3-6
# ######################################
# ############# Notes #################
# ... |
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# Copyright (c) 2021. by <NAME>, UC3M. +
# All rights reserved. This file is part of the Shi-VAE, and is released under the +
# "MIT License Agreement". Please see the LICENSE file ... |
from pytest import fixture, mark, xfail
import numpy as np
from beyond.orbits import Orbit, Ephem
from beyond.dates import Date, timedelta
from beyond.propagators.cw import ClohessyWiltshire
from beyond.orbits.man import ImpulsiveMan, ContinuousMan
from beyond.frames.frames import HillFrame
def plot_ephem(ephem):
... |
#
#
# Copyright 2019 <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>
#
# This file is part of acados.
#
# The 2-Clause BSD License
#
# Redistribution and use in source and binary forms, with or without modification, are permitted provided th... |
"""ZStorm integrates Storm with Zope 3.
@var global_zstorm: A global L{ZStorm} instance. It used the
L{IZStorm} utility registered in C{configure.zcml}.
"""
#
# Copyright (c) 2006-2009 Canonical
#
# Written by <NAME> <<EMAIL>>
#
# This file is part of Storm Object Relational Mapper.
#
# Storm is free software; y... |
# Copyright (c) 2013, 2014 <NAME>
# Licensed under the BSD 3-clause license (see LICENSE.txt)
#
#Parts of this file were influenced by the Matlab GPML framework written by
#<NAME> & <NAME>, however all bugs are our own.
#
#The GPML code is released under the FreeBSD License.
#Copyright (c) 2005-2013 <NAME> & <NAME>. Al... |
#!/usr/bin/env python
'''
Created on October 5, 2021
@author: kumykov
Copyright (C) 2021 Synopsys, Inc.
http://www.blackducksoftware.com/
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
regar... |
import numpy as np
import pandas as pd
def sample_SynthA(treat_prob=0.5, sample_no=1000):
"""
Generate synthetic data from Athey and Imbens
"""
noise1 = np.random.normal(0, 0.01, sample_no)
noise0 = np.random.normal(0, 0.01, sample_no)
w = np.random.uniform(0, 1, sample_no)
w = w <= t... |
import os
import numpy as np
import tensorflow as tf
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Input, Concatenate, Layer
from tensorflow.keras.layers import Activation, ReLU, LeakyReLU
from tensorflow.keras.layers import Conv2D, UpSampling2D
from tensorflow.keras.layers import TimeD... |
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
import os
import numpy as np
from pathlib import Path
from torch.nn import TransformerEncoder, TransformerEncoderLayer
from ..util import get_grads
class TransformerEncoderModel(nn.Module):
def __init__(self, ntoken, ninp, nhead, nhid... |
## Todo:
## add sanity check for init_swap function.
from sklearn.cluster import KMeans
import numpy as np
import igraph
import partitions
# import sampler_single
# graph coloring
def greedyColoring(g, nColors):
"""
Greedy coloring of g using nColors using the 0,1,2,... ordering of vertices.
If colo... |
'''
Created on 14.04.2014
@author: afedynitch
'''
import numpy as np
from impy.common import MCRun, MCEvent
from impy import impy_config, pdata
from impy.util import standard_particles, info
class DpmjetIIIEvent(MCEvent):
"""Wrapper class around DPMJET-III HEPEVT-style particle stack."""
def __init__(self, ... |
from django.db import connection
import numbers
import math
from functools import reduce
style_type_2_legend_shape = {
"fill-extrusion": "square",
"fill": "square",
"circle": "circle",
"symbol": "symbol",
"line": "line",
}
stroke_color_props = ["line_color", "stroke_color", "outline_color"]
stroke... |
# TODO(ariw): Some sort of registration interface so others can add their own
# games?
# TODO(ariw): Support for numeric, non-"username", and non-"account_token"
# requests is for legacy pre-Pebble 2.0 clients. Remove once most people have
# upgraded!
import base64
import hashlib
import hmac
import json
import logging... |
# -*- coding: utf-8 -*-
'''
otsu.fun - Website Api Utils
@version: 1.1
@author: PurePeace
@time: 2019-12-26
@describe: a treasure house!!!
'''
from imp import reload
import time, datetime, os, requests
from kawaiis import hi
from hashlib import sha512, sha256
from ast import literal_eval
from bs4 imp... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.