text stringlengths 3.07k 22.1k |
|---|
from matplotlib import pyplot as plt
import pickle
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, confusion_matrix, \
classification_report
from sklearn.utils import shuffle
from sklearn.preprocessing import MinMaxScaler
import numpy as np
import pandas as pd
import seaborn as ... |
'''
This program implements a Function Approximation Agent with a Convolutional Neural Network.
'''
from __future__ import print_function
import os, sys
sys.path.append('../game')
sys.path.append('../utils')
from collections import defaultdict, deque
import json
import random
import numpy as np
import gym
from Temp... |
# -*- coding: utf-8 -*-
# Copyright (c) 2021 Intel Corporation
#
# 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... |
#!/usr/bin/env python
# coding: utf-8
import sys
import numpy as np
import pandas
import tensorflow as tf
import collections
import six
import copy
import unicodedata
import re
from operator import itemgetter
from nltk.stem.wordnet import WordNetLemmatizer
from bert_serving.client import BertClient
from nltk.corpus ... |
"""
训练MAE模型
MAE模型作为一个特征抽取器仅仅用作对于各个Patch的特征捕获 提前训练好模型即可
"""
import os, random
import cv2
import numpy as np
import torch
import torch.optim as optim
import torch.nn as nn
import tqdm
from torchvision.transforms import transforms
from torchvision.utils import make_grid
from torch.utils.data import dataloader
from lib... |
# Create Custom Mesh for Ground surface
# Author: <NAME>
# Modified By: <NAME>, <NAME>
# University of Maryland. College Park
# MIT License (c) 2021
# Import Libraries
import bpy
import bmesh
import ant_landscape
import math
import numpy as np
import random
import os
# Force Enter the Object Mode
try:
bpy.ops.o... |
#!/usr/bin/env python3
# Copyright (c) 2015 <NAME>, <NAME>
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import mimetypes
import os
import re
import subprocess
import sys
import tempfile
from enum import Enum
from functools import reduce
from urllib.parse import... |
import os
import logging
from collections import defaultdict
from datetime import datetime, timedelta
from calendar import monthrange
import pandas as PD
from ..util.fortran import descriptor2colspecs
logger = logging.getLogger('pyrsss.l1.omni')
"""
From http://omniweb.gsfc.nasa.gov/html/HROdocum.html, retrieved
2... |
import argparse
import logging
import sys
import xml.etree.ElementTree as ET
from urllib.parse import urlparse, parse_qs, unquote
from http.server import BaseHTTPRequestHandler, HTTPServer
from socketserver import ThreadingMixIn
from actions import delete_item, delete_items, delete_bucket, get_acl, get_item, list_buck... |
import schedule
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.common.exceptions import NoSuchElementExceptio... |
"""
Written languages use sentences, paragraphs, punctuation and
other structural forms to help readers understand the writting.
Code is no different. We can use whitespace, empty lines, and similar
punctuation marks to improve the readabillity of our code. Consider this
chunk of machine learning code as an example:
"... |
"""
Capstone Team Project. Code to run on a ROBOT (NOT a laptop).
This module is for testing STAND-ALONE code running on the ROBOT
(WITHOUT having LAPTOP GUI code running on the LAPTOP at the same time).
Authors: Your professors (for the framework)
and PUT_YOUR_NAME_HERE.
Winter term, 2019-2020.
"""
# TODO: 1. ... |
# coding: utf-8
from __future__ import absolute_import, print_function, division
from typing import *
from six import *
import functools
import maya.cmds as _cmds
import maya.api.OpenMaya as _om2
from .internal import graphs as _graphs
from .internal import plugs as _plugs
def deprecated(message):
def _depreca... |
import pandas as pd
import matplotlib.pyplot as plt
import mlrun.feature_store as fs
import seaborn as sns
import numpy as np
import os
import json
import mlrun
# Feature selection strategies
from sklearn.feature_selection import SelectKBest
from sklearn.feature_selection import SelectFromModel
from sklearn.linear_mod... |
import os.path as op
import os
import time
import lxml.etree as et
import json
import errno
import csv
from collections import OrderedDict
from Profiler import Profiler
class Trepn(Profiler):
DEVICE_PATH = '/sdcard/trepn/'
def dependencies(self):
return ['com.quicinc.trepn']
def __init__(self, ... |
#!/usr/bin/env python
#Encoding: utf-8
#========================================================================================
# title : main.py
# description : Kivy GUI for android.
# author : CMRM.
# usage : Compile with buildozer.spec.
# python_version : 2.7
# license : P... |
import signal
import rospy
import smach
import smach_ros
import math
import time
import cv2
from math import tanh
from geometry_msgs.msg import Twist
from sensor_msgs.msg import Image
import numpy as np
from sensor_msgs.msg import LaserScan
from sensor_msgs.msg import Joy
from kobuki_msgs.msg import Sound
import event_... |
import PANDORA
import pickle
from PANDORA.PMHC import PMHC
from PANDORA.Database import Database_functions
import os
class Database:
def __init__(self):
self.MHCI_data = {}
self.MHCII_data = {}
self.ref_MHCI_sequences = {}
self.__IDs_list_MHCI = []
self.__IDs_list_MHCII = [... |
# Copyright (c) 2015 Riverbed Technology, Inc.
#
# This software is licensed under the terms and conditions of the MIT License
# accompanying the software ("License"). This software is distributed "AS IS"
# as set forth in the License.
from functools import partial
from _settings4 import Settings4, getted, \
Bas... |
import os, re, string, random
import openpyxl
import datetime, pytz
import requests
from django.conf import settings
from backend.models import *
from backend.utils.email import send_activation_email
VERSION = '0.1.1'
REGISTRATION_API = settings.REGISTRATION_API
IMPORT_TEMPLATE_FILE_PATH = os.path.join(settings.FILES... |
"Main application for scraping comic book covers and metadata from htpps://www.comics.org"
import argparse
import configparser
import datetime
import logging
import os
import pickle
import random
import urllib
from time import sleep
from uuid import uuid4
import jsonlines
import comics_net.webscraper as webscraper
... |
from nonebot import on_command, CommandSession
import random, sqlite3, nonebot, time
from config import groupID, GoodAnsList, badAnsList, blockedGroupID, allowMsgList, blockMsgList
bot = nonebot.get_bot()
def db_write(addCount, groupID, userID):
con = sqlite3.connect('asbot.db')
cur = con.cursor()
if len(... |
"""Module defining the base class and static func for interfaces."""
from abc import ABCMeta
from abc import abstractmethod
from dataclasses import dataclass
from dataclasses import field
from functools import lru_cache
from typing import Dict
from typing import List
from typing import Tuple
from uosinterface import U... |
# encoding: utf-8
# author: <NAME>
"""
Using this module user can merge cobertura XML reports.
Package contains Class CoverageMerge and simple iface to class (single method)
"""
import sys
import os
import xml.etree.ElementTree as ET
import logging
import re
# constants
PACKAGES_LIST = 'packages/package'
PACKAGES_... |
# Copyright (c) 2019-2020 AT&T Intellectual Property.
# All rights reserved.
# SPDX-License-Identifier: GPL-2.0-only
import json
import logging
import subprocess
from typing import Any, Dict, List
import pydbus
import vci # pylint: disable=import-error
import vyatta.vrrp_vci.keepalived.util as util
from vyatta.vr... |
#! /bin/python
import os
import sys
import json
# this is a task called by multiple processes,
# so we need to restrict the number of threads used by numpy
from elf.util import set_numpy_threads
set_numpy_threads(1)
import numpy as np
import luigi
import nifty.tools as nt
from elf.wrapper.resized_volume import Resiz... |
#!/usr/bin/env python
import os,sys
import argparse
from collections import defaultdict,Counter
import copy
import sqlite3
import time
from time import gmtime, strftime
import numpy as np
def create_table(cursor): #id text PRIMARY KEY
sql = """ CREATE TABLE IF NOT EXISTS
locations (
chr text NOT NULL,
pos... |
import pdb
import struct
import sys
import gzip
from io import BufferedReader
from collections import Counter, defaultdict
import collections.abc
from .gr import Gr, Entry
MAX_LEN = 2**29-1 # As defined by max size supported by bai indexes.
def bisect_left(a, x):
lo = 0
hi = len(a)
while lo < hi:
... |
from __future__ import print_function
import sys
import os
import lldb
import logging
import traceback
import ctypes
from ctypes import CFUNCTYPE, POINTER, pointer, py_object, sizeof, byref, memmove,\
c_bool, c_char, c_char_p, c_int, c_int64, c_double, c_size_t, c_void_p, py_object
from value import ... |
import pandas as pd
import os
import yaml
import json
import hashlib
import concurrent.futures
from itertools import product
from fastbt.datasource import DataSource
from fastbt.rapid import backtest
def transform(data):
"""
Apply the necessary transformation to the given data
"""
ds = DataSource(data,... |
# -*- coding: utf-8 -*-
"""
Created on Thu May 23 10:51:03 2019
@author: dhias426
"""
"""
File defines the PCFG and other helper functions
Naming Convention:
Non-Terminal Symbols are Capitalized
1st letter of label is capitalized
Terminal Symbols are in small-case
rule_dict[non-terminal]={label1:[set of Nhk],label2... |
import collections
import inspect
import math
import os
from typing import Optional
import numpy
import torch
import onnxruntime
from sparseml.pytorch.optim.manager import ScheduledModifierManager
from sparseml.pytorch.optim.optimizer import ScheduledOptimizer
from sparseml.pytorch.utils import logger
from transforme... |
from PyCmdMessenger import CmdMessenger
from PyCmdMessenger import ArduinoBoard
from enum import Enum
import dis
import signal
import logging
if __name__ == "__main__": # Stupid python stuff
from ourlogging import setup_logging # This is the main script
else:
from .ourlogging import setup_log... |
# Copyright 2017 University of Cincinnati
# All rights reserved. See LICENSE file at:
# https://github.com/MatthewVerbryke/uxas_zone_generation
# Additional copyright may be held by others, as reflected in the commit history.
import math
import os
import urllib2
import zipfile
import numpy as np
from visualization ... |
"""
.. _two_poschl_teller:
Poschl-Teller potentials
########################
Summary:
Calculates a system with two Poschl-Teller wells
"""
import sys
import os
currentpath = os.path.abspath('.')
sys.path.insert(0, os.path.dirname(currentpath))
import numpy as np
from ext_potentials import poschl_teller
from no... |
#!/usr/bin/env python3
# it is a python >3.6 like DSL, but long lines are allowed! ;-)
import logging
import os
import socket
import slos.ceph
import slos.cinder
import slos.glance
import slos.haproxy
import slos.keystone
import slos.mariadb
import slos.memcached
import slos.neutron
import slos.nova
import slos.oscl... |
'''
这一版使用pytorch的自动微分来对模型进行改造
'''
import torch
import torch.optim as optim
import torch.nn.functional as F
import codecs
import numpy as np
import copy
import time
import random
entity2id = {}
relation2id = {}
relation_tph = {}
relation_hpt = {}
def data_loader(file):
print("load file...")
file1 = file + "... |
# Copyright (c) 2015 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 agreed to in writi... |
# Copyright 2017 PerfKitBenchmarker 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 numpy as np
from scipy import special
class pdf_hist(object):
"""A handy class for managing numerical
histograms for pdfs"""
def __init__(self, x0, xn, cells, logcells=False):
"""Defines necessary variables and divides the x interval"""
self.x0 = x0
self.xn = xn
sel... |
# copyright (c) 2021 PaddlePaddle Authors. All Rights Reserve.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
import unittest
from incidents import process_incidents
from conditions import process_conditions
from traffic import process_throughput
from oandm import process_oandm
from util import most_common
import pandas as pd
class TestUtil(unittest.TestCase):
testData = {'row_1': [5, 3, 2, 1, 0, 0, 0, 1],
... |
import csv
import sys
import math
import os
import time
from datetime import datetime
"""
@begin simulate_data_collection @desc Workflow for collecting diffraction data from high quality crystals in a cassette.
@param cassette_id @desc The unique ID of the cassette containing the crystals.
@param sample_score... |
# Copyright 2019 Intel, Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by a... |
from datetime import date, datetime, timedelta
from django.contrib.auth.models import User
from django.utils import timezone
from django.shortcuts import render, get_object_or_404
from django.contrib.auth.decorators import login_required
from django.contrib.admin.views.decorators import staff_member_required
from djan... |
import copy
import json
import os
from collections import OrderedDict
from shutil import copyfile, SameFileError
import jinja2
import nbformat
from nbconvert import HTMLExporter
from traitlets.config import Config as TraitletsConfig
from blogger_cli.converter.extractor import (
extract_and_write_static,
extra... |
# Copyright 2019 IBM Corporation
#
# 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 writing, ... |
from os import kill, system as sys
from getpass import getuser as ge
import re
class File:
def __init__(self, name):
self.name = name #NOMBRE DEL ARCHIVO
self.status = 0 # SI ESTA ABIERTO O NO {0: CERRADO, 1: ABIERTO}
self.mode = '' #MODO
self.position = 0 #DESDE DONDE APUNTA EL... |
#!/usr/bin/env python3
#python3-dbus
#python3-gi
import time
# import signal
import dbus
import dbus.service
import dbus.mainloop.glib
from gi.repository import GObject
SERVICE_NAME = "org.bluez"
AGENT_IFACE = SERVICE_NAME + '.Agent1'
ADAPTER_IFACE = SERVICE_NAME + ".Adapter1"
DEVICE_IFACE = SERVICE_NAME + ".Device1... |
import itertools
from more_itertools import replace
import collections
import functools
import operator
def existent(iterable):
for element in iterable:
if element:
yield element
def flatten(iterable):
for el in iterable:
if isinstance(el, collections.Iterable) and not isinstance(... |
#!/usr/bin/python
# Copyright (c) 2020, 2021 Oracle and/or its affiliates.
# This software is made available to you under the terms of the GPL 3.0 license or the Apache 2.0 license.
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# Apache License v2.0
# See LICENSE.TXT for d... |
"""Python host AST builder for integration with PyOpenCL."""
from __future__ import division, absolute_import
__copyright__ = "Copyright (C) 2016 <NAME>"
__license__ = """
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software")... |
import time
from os.path import join
import logging
import numpy as np
import shutil
from pbc.bragg_peak import BraggPeak
from pbc.helpers import calculate_number_of_peaks_gottschalk_80_rule, diff_max_from_left_99, diff_max_from_range_90, \
make_precise_end_calculations, load_data_from_dump, create_output_dir, du... |
# !/usr/bin/env python
# title :LSTM
# description :LSTM Model That Predicts Closing Price of Stock at T+1
# author :<NAME>
# date :5/2/19
# version :1.0
# usage :python3 LSTM.py
# notes :SEE README.txt for list of dependencies
# python_version :3.6... |
#!/usr/local/bin/python3.7
from PyQt5.QtWidgets import *
from PyQt5 import QtCore
from os.path import expanduser
import sys, os, re, subprocess, signal, configparser
# Reads configuration from file or use reasonable default values
class Configuration:
def __init__(self):
self.options = {}
self.co... |
from typing import Any, Union, Dict, Callable, Optional, Type, Tuple
import asyncio
import json
import uuid
import logging
from urllib.parse import urlparse
from grpclib.client import Channel, Stream
from grpclib.exceptions import StreamTerminatedError
import jointrpc.pb.jointrpc_pb2 as pb2 # type: ignore
import joi... |
from collections import defaultdict
import astroid
class TypeTags(object):
NONE = -1
OBJECT = 11
class SimpleField(object):
__slots__ = ('name',)
def __init__(self, name):
self.name = name
class ClassDef(object): # XXX
def __init__(self, fields, qualname):
self.fields = fiel... |
import discord
from discord.ext import commands
from discord.ext.commands.cooldowns import BucketType
import asyncio
import colorsys
import random
import platform
from discord import Game, Embed, Color, Status, ChannelType
from discord import Spotify
import os
import functools
import time
import datetime
f... |
"""manual:
https://gist.github.com/taruma/e250ab2685ba5b4c8facbf498cfb5cd8"""
import numpy as np
import pandas as pd
from scipy import stats
from hidrokit.contrib.taruma import hk172, hk124, hk127, hk126
frek_normal, frek_lognormal, frek_gumbel, frek_logpearson3 = hk172, hk124, hk127, hk126
# tabel dari limantara h... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
from builtins import object
import numpy as np
# from scipy import optimize # DON'T. It's slow and crashes on some machines
class _baseFunctionFit(object):
"""Not needed by most users except as a supe... |
import os, sys, time, shutil, tempfile, datetime, pathlib, subprocess
import numpy as np
import torch
import torch.nn as nn
from torch import optim
import torch.nn.functional as F
import datetime
from . import transforms, io, dynamics, utils
sz = 3
def convbatchrelu(in_channels, out_channels, sz):
return nn.Seq... |
import time
import numpy as np
from threading import Thread
from ..utils import CameraFacing
from PARAMETERS import *
from .pyplot_vis import plot_birds_eye
from filterpy.kalman import KalmanFilter
from filterpy.common import Q_discrete_white_noise
class KalmanPointObject:
'''
This class represents the in... |
"""
Copyright (c) 2017 Dependable Systems Laboratory, EPFL
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge,... |
# coding=utf-8
# Copyright 2020 The Google Research 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 applicab... |
# -*- coding: utf-8 -*-
#########################################################################
#
# Copyright (C) 2016 OSGeo
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 ... |
from attrdict import AttrDict
from dataclasses import dataclass
from enum import auto, Enum
from io import BytesIO, StringIO
import os
import random
from typing import Callable, Dict, List, Tuple
from determined.util import download_gcs_blob_with_backoff
from filelock import FileLock
from google.cloud import storage
f... |
# Copyright (C) 2005 Joint Institute for VLBI in Europe
# Copyright (C) 2005 Associated Universities, Inc. Washington DC, USA.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 ... |
"""Manages multi-node job coordination"""
import logging
import os
import shutil
import socket
import time
from pathlib import Path
import click
import psutil
from jade.common import CONFIG_FILE, JOBS_OUTPUT_DIR
from jade.jobs.job_configuration_factory import create_config_from_file
from jade.loggers import setup_lo... |
# mypy: ignore-errors
from pytorch_pfn_extras.dataset.tabular import tabular_dataset
from pytorch_pfn_extras.dataset.tabular import _utils
class _TransformBase(tabular_dataset.TabularDataset):
def __init__(self, dataset, keys, transforms):
self._dataset = dataset
key_set = set()
self._tr... |
"""Model fitting and cross-validation."""
import argparse
import copy
import numpy as np
import pandas as pd
import scipy
from scipy.optimize import least_squares
from models import calc_cs, get_b2, get_init, get_radius
N_NORM_PARAMS = 31 # Number of normalization parameters
BEAM_ENERGIES = [180, 315, 450, 585, 72... |
# -*- coding: utf-8 -*-
# The MIT License (MIT)
#
# Copyright (c) 2014-2018 <NAME>(<NAME>)
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation... |
# Copyright (C) 2020 Onepanel Inc.
#
# SPDX-License-Identifier: MIT
from __future__ import print_function
import os
import yaml
import tempfile
from datetime import datetime
from django.http import JsonResponse
from rest_framework.response import Response
from rest_framework import status
from rest_framework.decora... |
import numpy as np
from scipy.spatial import cKDTree
def connex(vertices: np.ndarray) -> list:
""" make vertex edges for vispy Line """
return [True] * (vertices.shape[0] - 1) + [False]
def check_track_dimensionality(data: list):
""" check the dimensionality of the data
TODO(arl): we could allow a ... |
from netCDF4 import Dataset
import numpy as np
from datetime import datetime, timedelta
from copy import deepcopy
import math
import dask.array as da
from distributed import Client, LocalCluster
from dask import delayed, compute
import time
import sys
from scipy import ndimage
import pandas
import time_procedures
impor... |
# Copyright (c) 2020 University of Chicago.
#
# 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... |
# Copyright (c) 2020 zfit
from typing import Union
import numpy as np
import tensorflow as tf
import tensorflow_probability as tfp
from tensorflow_probability.python import distributions as tfd
from .dist_tfp import WrapDistribution
from .. import z, ztypes
from ..core.interfaces import ZfitData, ZfitSpace
from ..ut... |
#!/usr/bin/env python3
import random
import statistics
import time
from pyln.client import Plugin, Millisatoshi, RpcError
from threading import Lock
plugin = Plugin()
# Our amount and the total amount in each of our channel, indexed by scid
plugin.adj_balances = {}
# Cache to avoid loads of RPC calls
plugin.our_node_... |
import socket
import asyncio
import urllib.parse
import collections.abc
try:
import ssl
try:
import certifi
except ImportError:
certifi = None
except ImportError:
ssl = None
from . import raw
class Channel (collections.abc.AsyncIterator, asyncio.Queue):
closed = False
def cl... |
from __future__ import division, print_function, absolute_import
import sys
from perf._cli import display_title, format_result_value
from perf._utils import is_significant
def is_significant_benchs(bench1, bench2):
values1 = bench1.get_values()
values2 = bench2.get_values()
if len(values1) == 1 and len... |
from pyTsetlinMachine.tm import MultiClassConvolutionalTsetlinMachine2D
import numpy as np
from time import time
import csv
import time as stime
def StartMachine(clauses,epoch,Threshold,S,Window_X,Window_Y,Shape_X,Shape_Y,Shape_Z,inndata):
counter = 0
timestr = stime.strftime("%Y%m%d-%H%M%S")
results = op... |
import json
from typing import Optional
from typing import cast as typecast
import pandas as pd # type: ignore
from arkouda.alignment import in1dmulti
from arkouda.client import generic_msg
from arkouda.dtypes import bool as akbool
from arkouda.dtypes import float64 as akfloat64
from arkouda.dtypes import int64 as a... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
from torch.optim.lr_scheduler import StepLR
import numpy as np
import os
import math
import argparse
import random
import models
import torchvision
from torch.utils.data import Dataset, DataLoader
from torchvision imp... |
"""
A minimal character-based n-layer Vanilla RNN model.
This is derived from the following scripts:
- https://gist.github.com/karpathy/d4dee566867f8291f086
- https://github.com/eliben/deep-learning-samples/blob/master/min-char-rnn/min-char-rnn.py
And you might find the following materials helpful:
- http://karpathy.gi... |
from kivy.clock import Clock
from kivy.config import Config
from kivy.cache import Cache
from kivy.uix.image import AsyncImage
from kivy.uix.togglebutton import ToggleButton
from kivy.uix.filechooser import *
from .utils import *
import os
import random
import gc
class PictureDatabase(FileSystemAbstract):
picture... |
import nnlibrary as nn
from models import *
import data_utils5 as data_utils
import numpy as np
import random
import pickle as pickle
'''
This loads the data sets and stores them as a global variable
Yes, it's probably ta bad idea. No, I don't care.
The individual data will each be a tuple (tree, hyps, correct)
... |
import requests
from flask import (abort, flash, redirect, render_template, request, session,
url_for)
from globus_sdk import (RefreshTokenAuthorizer, TransferAPIError,
TransferClient, TransferData)
from portal import app, database, datasets
from portal.decorators import auth... |
import numpy as np
import matplotlib.pyplot as plt
def generate_paths(times, N, hazard0, fx0, vol_haz, vol_fx, rho, jump):
W = np.random.multivariate_normal([0,0], [[1, rho],[rho,1]],size=(N,len(times)))
prob = np.zeros((N,))
hazard = np.zeros((N, len(times)))
hazard[:,0] = hazard0
for i ... |
# -*- coding: utf-8 -*-
import hashlib
import json
import os
from django.conf import settings
import mock
from nose.tools import eq_, ok_
import mkt
import mkt.site.tests
from mkt.files.models import File, FileUpload, FileValidation, nfd_str
from mkt.site.fixtures import fixture
from mkt.site.storage_utils import (c... |
import random
import numpy as np
from model.model_manager import ModelManager
from model.input_pipeline import ALInputPipeline
from model.monte_carlo_evaluation import get_monte_carlo_metric
from preprocessing.dataset import load
def get_al_manager(al_type):
if al_type == 'common':
return ActiveLearning... |
"""
Copyright 2021, CCL Forensics
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, subl... |
# IPython log file
get_ipython().run_line_magic('run', 'ipython_log.py')
get_ipython().run_line_magic('logon', '')
get_ipython().run_line_magic('logstart', '')
x = 5
get_ipython().run_line_magic('logoff', '')
x = 7
get_ipython().run_line_magic('magic', '')
get_ipython().run_line_magic('pwd', '')
get_ipython().run_line... |
# Collect the Blocks
# by KidsCanCode 2015
# Run around and collect the blocks
# For educational purposes only
# TODO: time bonus
# TODO: powerups
# TODO: more mob features (different types, etc)
# TODO: Level designs (walls, gravity (black holes?))
import pygame
import sys
import os
import random
# define some colo... |
# pylint: disable=no-member,redefined-outer-name,unused-argument
# pylint: disable=unused-variable
"""Unit tests for pandera API extensions."""
from typing import Any, Optional
import pandas as pd
import pytest
import pandera as pa
import pandera.strategies as st
from pandera import PandasDtype, extensions
from pand... |
# The Blender Python API
import bpy
# Gives access to Blender's internal mesh editing API
import bmesh
# Provides access to mathematical functions
import math
def get_name():
"""Get the name for the currently active object"""
return bpy.context.active_object.name
def degToRadian(angle):
"""Convert angle ... |
"""Apply a function (or functions) across multiple columns
See source https://github.com/tidyverse/dplyr/blob/master/R/across.R
"""
from abc import ABC, abstractmethod
from typing import Any, Callable, Iterable, List, Mapping, Tuple, Union
import numpy
from pandas import DataFrame, Series
from pipda import register_f... |
# coding:utf-8
from torch.optim.lr_scheduler import _LRScheduler
from torch.optim.lr_scheduler import ReduceLROnPlateau
class WarmUpLR(_LRScheduler):
"""warmup_training learning rate scheduler
Args:
optimizer: optimzier(e.g. SGD)
total_iters: totoal_iters of warmup phase
"""
def __init__(self, optimizer, tot... |
#! /usr/bin/env python3
#
# SPDX-FileCopyrightText: 2018 <NAME> <<EMAIL>>
# SPDX-License-Identifier: BSD-2-Clause
#
# Uses the Transifex API to get a list of enabled languages,
# and outputs CMake settings for inclusion into CMakeLists.txt.
#
# This is a Python3 script.
#
# Run it with a -v command-line option to g... |
#!/bin/python3
import re
import os
import sys
from rdflib.plugins.sparql import *
from clean import csvwParser as csvwParser
import traceback
def addNormalizedTablesToCsvw(csvw, mapping, query, parsedQuery):
newTables = []
# query = queryPrefixRewritter(query, mapping['prefixes'])
for i,table in enumerate(cs... |
import heapq
import itertools
from collections import defaultdict
import pandas as pd
import numpy as np
import plotly.express as px
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.multioutput import MultiOutputRegressor
from utils.theoretical_approximation import cartesian_cross_product
def get_... |
import logging
import socket
from functools import wraps
import time
from dataclasses import dataclass
from functools import wraps
from rcon.connection import HLLConnection
logger = logging.getLogger(__name__)
def escape_string(s):
""" Logic taken from the official rcon client.
There's probably plenty of ni... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.