text stringlengths 3.07k 12.6k |
|---|
#TODO
#Give Pokémon experience for battling other Pokémon. A Pokémon’s level should increase once it gets enough experience points.
#Create specific Classes that inherit from the general Pokémon class. For example, could you create a Charmander class that has all of the functionality of a Pokémon plus some extra feat... |
#Twitter preprocessing and cleaning
import re
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import string
import nltk
import warnings
from nltk.stem.porter import *
from wordcloud import WordCloud
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.fe... |
pkgname = "boost1.79"
pkgver = "1.79.0"
pkgrel = 0
hostmakedepends = ["pkgconf"]
makedepends = [
"zlib-devel", "libbz2-devel", "liblzma-devel", "libzstd-devel",
"icu-devel", "python-devel", "linux-headers"
]
pkgdesc = "Free peer-reviewed portable C++ source libraries"
maintainer = "q66 <<EMAIL>>"
license = "BSL... |
# -*- coding: utf-8 -*-
import os
import pytest
from numpy.testing import assert_allclose
import apexpy
from apexpy import fortranapex as fa
##############################################################################
# NOTE: the test results (numbers) were obtained by running the code that is #
# tested, therefo... |
"""Common runtime ctypes."""
# pylint: disable=invalid-name
from __future__ import absolute_import
import ctypes
import numpy as np
from .base import _LIB, check_call
from .. import _api_internal
tvm_shape_index_t = ctypes.c_int64
class TypeCode(object):
"""Type code used in API calls"""
INT = 0
UINT = 1... |
#!/usr/bin/env python3
# noqa pylint: disable=line-too-long
"""genie cli"""
import argparse
import logging
import synapseclient
from synapsegenie import (bootstrap, config, input_to_database,
process_functions, validate, write_invalid_reasons)
from .__version__ import __version__
logger =... |
import os.path
import time
import numpy as np
import pickle
import PC2ImageConverter
import matplotlib.pyplot as plt
from visualizer import Vis
def decomposeCloud(rawCloud, verbose=False):
# decompose cloud
backgrdPoints = []
roadPoints = []
vehPoints = []
pedPoints = []
cycPoints = []
... |
# -*- coding: utf-8 -*-
# Modified by Microsoft Corporation.
# Licensed under the MIT license.
"""
"""
import configparser
import os
import zipfile
from copy import deepcopy
import torch
from convlab.lib.file_util import cached_path
from convlab.modules.nlg.multiwoz.sc_lstm.loader.dataset_woz import SimpleDatasetWo... |
import os
import collections
import numpy as np
import torch.utils.data
from utils.text import text_to_sequence, phoneme_to_sequence, pad_with_eos_bos
class TTSDataset(torch.utils.data.Dataset):
def __init__(self, data_root, target_list, outputs_per_step):
self.data_root = data_root
self.target_... |
# midi2vjoy.py
#
# Copyright 2017 <c0redumb>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This pr... |
#
# Copyright 2014 Cisco Systems,Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writ... |
#!/usr/bin/env python
"""
Utility script for efficiently unpacking a tarball to an S3 bucket.
The script can load most tar files (e.g. .tar, .tar.gz) and uploads all files to an S3 bucket with an optional
prefix.
The script will automatically gzip certain file types, and will add a 'Cache-Control' header.
Requiremen... |
"""
The MIT License (MIT)
Copyright (c) 2015-present Rapptz
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, merg... |
"""
This is a module for getting various data from PubChem using it's amazing
PUG REST API. More info can be found within functions docs.
Copyright 2017 <NAME> <<EMAIL>>
For details about PubChem's PUG REST API please visit
https://pubchem.ncbi.nlm.nih.gov/pug_rest/PUG_REST.html
"""
import urllib.request, json
... |
# built-in
import re
import sys
import traceback
from argparse import ArgumentParser
from contextlib import contextmanager
from functools import update_wrapper
from importlib import import_module
from pathlib import Path
from textwrap import indent
from typing import Dict, Iterable, Iterator, Sequence, TextIO, TypeVar
... |
import os
import sys
import defbuild.bob as _bob
import time
import shutil
import logging
import requests
from subprocess import call
from distutils.version import StrictVersion
def build(project):
if not project.bob:
logging.error("Can't find a bob version, download with 'builder bob --update'")
... |
import os
import numpy as np
from torchvision.datasets import MNIST
from torchvision import transforms
from torch.utils.data import Dataset
# grab the data. This will create a data/ folder in your working directory the
# first time it is run.
mnist_train = MNIST(
'data/MNIST',
download=True,
transform=t... |
"""
Adapted from https://github.com/openai/baselines/
"""
import multiprocessing as mp
import numpy as np
from .vec_env import VecEnv, CloudpickleWrapper, clear_mpi_env_vars
def worker(remote, parent_remote, env_fn_wrappers):
parent_remote.close()
envs = [env_fn_wrapper() for env_fn_wrapper in env_fn_wrappe... |
# vim: expandtab:ts=4:sw=4
from __future__ import absolute_import
import numpy as np
# from sklearn.utils.linear_assignment_ import linear_assignment
from scipy.optimize import linear_sum_assignment as linear_assignment
from . import kalman_filter
INFTY_COST = 1e+5
def min_cost_matching(
dista... |
from tinygrad.tensor import Tensor
import tinygrad.nn as nn
from extra.utils import fetch, fake_torch_load
from torch.hub import load_state_dict_from_url
import numpy as np
model_urls = {
'resnet18': 'https://download.pytorch.org/models/resnet18-5c106cde.pth',
'resnet34': 'https://download.pytorch.org/models/resne... |
# divid by osm edge points and nodes
import pymongo
import json
import pandas as pd
import geopandas as gpd
import hashids
from hashids import Hashids
from shapely.geometry import LineString, Polygon, Point
import shapely
import osmnx
import geojson
import geopy.distance
myclient = pymongo.MongoClient("mongodb://192.1... |
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... |
from __future__ import unicode_literals
from colorama import init, deinit, Fore, Style
from colorama.ansi import Cursor
from colorama.initialise import wrap_stream
import logging
import os
import platform
import re
import sys
from unidecode import unidecode
global debug_level
debug_level = 0
if sys.version_info[0] ==... |
# MIT license
#
# Copyright (C) 2018 by XESS Corporation / <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy... |
#!/usr/bin/env python3
#
# Copyright 2019 <NAME> <<EMAIL>>
#
# This file is part of Salus
# (see https://github.com/SymbioticLab/Salus).
#
# 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
#
#... |
# 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, software
# d... |
import numpy as np
from .. import config, camera_config, file_writer_config
from ..utils.iterables import list_update
from ..utils.exceptions import EndSceneEarlyException
from ..constants import DEFAULT_WAIT_TIME
from ..scene.scene_file_writer import SceneFileWriter
from ..utils.caching import handle_caching_play, han... |
"""
Written by <NAME> <<EMAIL>> 2017-2018
"""
from PIL import Image
import imageio
import json
import os
import time
import numpy as np
from progressbar import ProgressBar
import torch
from torch import nn
from torch.autograd import Variable
from plot import plot_stats
def _clearline():
C... |
"""Application configuration."""
import logging
from typing import Tuple
import appdirs
import os
import toml
import stat
from pathlib import Path
import platform
APP_NAME = 'remass'
def _backup_filename(filename: str, backup_folder: str, return_latest: bool) -> str:
froot, fext = os.path.splitext(filename)
... |
import random
import math
from input_output import io, matrice_data_reader
from algorithm import genetic
# CONST
MIN_CUT_SIZE = 3
MAX_CUT_SIZE_COEFFICIENT = .5
DISTANCE = io(matrice_data_reader, '.\\assets\\data1.txt')
class Chromosome:
def __init__(self, chromosome, evaluate=False):
self.chromosome = ch... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""YOLO_v4 Model Defined in Keras."""
from keras_applications.imagenet_utils import _obtain_input_shape
from tensorflow.keras.utils import get_source_inputs, get_file
from tensorflow.keras.layers import Add, ZeroPadding2D, UpSampling2D, Concatenate
from tensorflow.keras.l... |
from functools import total_ordering
import collections
from typing import *
from crosshair import register_type
from crosshair.core import CrossHairValue
from crosshair.core import realize
from crosshair.tracers import ResumedTracing
from crosshair.util import is_iterable
T = TypeVar("T")
class ListBasedDeque(coll... |
# -*- coding: utf8 -*-
# import packages needed
from tkinter import *
from pymysql import cursors
import tkinter.font as tkFont
# import configuration in parent dir
import os, sys, inspect, view_CLI
current_dir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parent_dir = os.path.dirname(cu... |
from typing import NewType, Dict, List, Optional, Tuple
import pandas as pd
from bpdfr_simulation_engine.resource_calendar import CalendarFactory
from simod.configuration import CalendarType
from simod.discovery.resource_pool_discoverer import ResourcePoolDiscoverer
UNDIFFERENTIATED_RESOURCE_POOL_KEY = "undifferenti... |
## @package app
# Module caffe2.python.mint.app
import argparse
import flask
import glob
import numpy as np
import nvd3
import os
import sys
# pyre-fixme[21]: Could not find module `tornado.httpserver`.
import tornado.httpserver
# pyre-fixme[21]: Could not find a module corresponding to import `tornado.wsgi`
import tor... |
import logging
import os
from datetime import datetime
import traceback
import shutil
import zipfile
import librosa
import resampy # noqa
from main import socketio
from dataset.audio_processing import convert_audio
from dataset.analysis import save_dataset_info
from dataset.clip_generator import CHARACTER_ENCODING
... |
from pyasn1.type import univ, namedtype, tag, namedval, constraint, char, useful
from pyasn1_modules.rfc2459 import AlgorithmIdentifier, Extensions, MAX, Name
from pyasn1_modules.rfc2315 import ContentInfo, signedData, SignedData
from pyasn1.codec.ber import decoder
__all__ = (
'TimeStampReq', 'MessageImprint', 'P... |
"""CheckingProxy derived from jsonrpc.proxy due to subclassing problems
w/getattr. Converts service errors into ServiceError exceptions, otherwise
call returns the jsonrpc "result" field.
"""
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
import sys
impo... |
import os
from vodka import get_instance
import vodka.plugins
import vodka.config
import vodka.config.validators
def application():
return WSGIPlugin.wsgi_application
class SSLConfiguration(vodka.config.Handler):
"""
Allows you to configure the ssl context of a wsgi
plugin
"""
enabled = vo... |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
"""
@author:LXM
@file:DeepRNN.py
@time:2020/10/13
"""
import numpy as np
import tensorflow.compat.v1 as tf
import matplotlib.pyplot as plt
import tensorflow.keras as keras
# 定义RNN参数
HIDDEN_SIZE = 30 # LSTM中隐藏节点的个数。
NUM_LAYERS = 2 ... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: <NAME>(<EMAIL>)
import torch
import torch.nn as nn
import torch.nn.functional as F
from collections import OrderedDict
from model.backbones.backbone_selector import BackboneSelector
from model.det.layers.yolo_detection_layer import YOLODetectionLayer
class Dar... |
from __future__ import annotations
import filecmp
import inspect
import logging
import os
import shutil
import sys
from collections.abc import Iterable
from importlib import import_module
from types import ModuleType
from typing import TYPE_CHECKING, cast
import click
import urllib3
from dask.utils import tmpfile
f... |
"""
DespyNumPyramidGenerator - Sequences
Script responsible for printing number triangles
Initial Version
Start Date: March 18, 2021
End Date: April 17, 2021
File Name: number_triangles.py
"""
from generator import generateNumberTriangle, getListOfNumberTriangleNames
from inputs import (
... |
from functools import lru_cache
import json
import re
from django.conf import settings
from django.contrib.contenttypes.models import ContentType
from django.core.exceptions import SuspiciousOperation
from django.db import transaction
from django.utils import timezone
from reversion import revisions
from reversion.mo... |
"""WaveNet Training and Fast WaveNet Decoding.
From the following paper
------------------------
<NAME>., <NAME>., <NAME>., <NAME>., <NAME>.,
<NAME>., … <NAME>. (2017). Fast Generation For Convolutional
Autoregressive Models, 1–5.
"""
"""
WaveNet Training code and utilities are licensed under APL from the
Google Mage... |
#!/usr/bin/env python
import os
import datetime
from flask import Flask, abort, request, jsonify, g, url_for
from flask_cors import CORS
from flask_sqlalchemy import SQLAlchemy
from flask_httpauth import HTTPBasicAuth
from passlib.apps import custom_app_context as pwd_context
from itsdangerous import (TimedJSONWebSigna... |
# -*- coding: utf-8 -*-
# Copyright (c) 2012-2015, <NAME>
#
# This module is part of anima-tools and is released under the BSD 2
# License: http://www.opensource.org/licenses/BSD-2-Clause
import os
import subprocess
import tempfile
import threading
from anima.env import nukeEnv
import nuke
from anima import logger
fr... |
# Copyright 2019 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from dataclasses import dataclass
from typing import Tuple
from pants.backend.python.lint.black.skip_field import SkipBlackField
from pants.backend.python.lint.black.subsystem import Blac... |
from json import load
from pathlib import Path
from shutil import rmtree
from typing import List, Union
def delete_files_and_folders(paths: Union[Path, str, List[Path], List[str]]) -> None:
"""Delete files and folders for given file and/or folder paths.
Args:
paths: A ``pathlib.Path`` object or strin... |
from helper_evaluate import compute_accuracy
from helper_evaluate import compute_epoch_loss
import time
import torch
import torch.nn.functional as F
from collections import OrderedDict
import json
import subprocess
import sys
import xml.etree.ElementTree
def train_classifier_simple_v1(num_epochs, model, optimiz... |
# futures
from __future__ import division
from itertools import groupby
# external
import numpy
from scipy.sparse import hstack
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
class EMEstimate(object):
pass
class ECMEstimate(EMEstimate):
"""
Algorithm to compute the Expectation/Condit... |
__author__ = '<NAME>, <EMAIL>'
# $Id$
from scipy import ravel, r_
from random import sample
from pybrain.datasets.supervised import SupervisedDataSet
class EmptySequenceError(Exception): pass
class SequentialDataSet(SupervisedDataSet):
"""A SequentialDataSet is like a SupervisedDataSet except that it can kee... |
import argparse
import numpy as np
import os
import scipy.stats as stats
from sklearn.metrics import f1_score
import torch
import torch.nn as nn
from features import getLabel
from utils import *
def parse_args():
parser = argparse.ArgumentParser(description='^-^')
parser.add_argument('--task', '-t', type=st... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Define the recorder classes.
The recorders allow to record the data from a source at a certain rate.
For instance, it can record the robot states and actions. This can be useful for imitation learning tasks where
the user demonstrates a certain skill through teleoperati... |
# Copyright (C) 2017 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
"""
Assessment generator hooks
We are applying assessment template properties and make
new relationships and custom attributes
"""
import logging
from itertools import izip
from collections import def... |
import os
import pathlib
from itertools import product
from funcy import lsplit, rpartial
from dvc import dependency, output
from dvc.utils.fs import path_isin
from ..dependency import ParamsDependency
from ..hash_info import HashInfo
from ..tree.local import LocalTree
from ..tree.s3 import S3Tree
from ..utils impor... |
import os
import json
import tempfile
import webbrowser
import designer
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import ObjectProperty, ConfigParser, StringProperty
from kivy.uix.settings import Settings, InterfaceWithSidebar, MenuSidebar,\
ContentPanel, SettingsPanel
... |
from walt.common.tcp import Requests
from walt.server.threads.main.parallel import ParallelProcessSocketListener
from walt.server.const import SSH_COMMAND
import os, random
TYPE_CLIENT = 0
TYPE_IMAGE = 1
HELP_INVALID = """\
Usage:
$ walt $(image_or_node_label) cp <local_file_path> <$(image_or_node_label)>:<file_path... |
""" this will read the goes_r data"""
import pandas as pd
import xarray as xr
try:
import s3fs
has_s3fs = True
except ImportError:
print(
"Please install s3fs if retrieving from the Amazon S3 Servers. Otherwise continue with local data"
)
has_s3fs = False
try:
import h5py # noqa: F4... |
# -*- coding: utf-8 -*-
"""
Created on Mon May 26 21:11:18 2014
@author: <NAME>
A good explanation of quadradic programming in cvxopt is in
http://courses.csail.mit.edu/6.867/wiki/images/a/a7/Qp-cvxopt.pdf
This exampel calculates the efficient forntier in a small example
the example is based on a mean variance mod... |
import collections
from collections import defaultdict
import numpy as np
import torch
import torch.nn.functional as F
from torch.utils.data.dataloader import default_collate
from .data_container import DataContainer
def collate(batch, samples_per_gpu=1):
"""Puts each data field into a tensor/DataContainer with... |
import win32com.client
import win32process
import win32pdh
import win32pdhquery
import win32pdhutil
import pywintypes
import ctypes
import time
import os
import math
__version__ = '1.0.1'
# NT4 does not have WMI by default
try:
import wmi
except:
wmi_found = False
else:
wmi_found = True... |
from PolyAModel import *
import re
import os, sys, copy, getopt, re, argparse
import random
import pandas as pd
import numpy as np
from Bio.Seq import Seq
from TrimmedMean import TrimmedMean
import gc
#from extract_coverage_from_scanGenome import check
def check(line1,line2,window):
#_,pos1,_ = line1[... |
from __future__ import absolute_import
import re
import six
from sentry_sdk.hub import Hub
from sentry_sdk.integrations import Integration
from sentry_sdk.scope import add_global_event_processor
from sentry.utils.safe import get_path
SYSTEM_FRAMES = [
"std::",
"core::",
"alloc::",
"backtrace::",
... |
# Copyright 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 accompanyin... |
import io
from functools import partial
from tlz import concat
from fsspec.core import open_files
from ..bytes import read_bytes
from ..delayed import delayed
from ..utils import parse_bytes, system_encoding
from .core import from_delayed
delayed = delayed(pure=True)
def read_text(
urlpath,
blocksize=None,... |
#!/usr/bin/env python3
"""
TODO
USAGE:
yb_wl_profiler_heatmap.py [options]
PURPOSE:
Creates a 35 day Excel heatmap of Work Loads on a Yellowbrick Cluster.
OPTIONS:
See the command line help message for all options.
(yb_wl_profiler_heatmap.py --help)
Output:
Excel heatmap
"""
import csv... |
def df_filter_row_sum(df, threshold, take_abs=True):
''' filter rows in matrix at some threshold
and remove columns that have a sum below this threshold '''
from copy import deepcopy
from __init__ import Network
net = Network()
if take_abs is True:
df_copy = deepcopy(df['mat'].abs())
else:
df_co... |
import numpy as np
from maci.core.serializable import Serializable
class PoolBase(object):
def __init__(self, env_spec):
self._observation_dim = env_spec.observation_space.flat_dim
self._action_dim = env_spec.action_space.flat_dim
@property
def observation_dim(self):
return self.... |
#
# Copyright 2015-2019, Institute for Systems Biology
#
# 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 ... |
# -*- coding: utf-8 -*-
import base64
import logging
import os
import time
from concurrent.futures import ThreadPoolExecutor, wait, ALL_COMPLETED
from django.utils.translation import ugettext_lazy as _
from gcloud.conf import settings
from pipeline_plugins.components.utils import cc_get_ips_info_by_str
get_client_by... |
# coding: utf-8
import maya.cmds as cmds
import random
import math
# 거리를 계산하는 함수
def getDistance(pos1, pos2):
'''
pos1 = (x1, y1, z1)
pos2 = (x2, y2, z2)
'''
# pos 을 x, y, z 형식으로 분해
x1, y1, z1 = pos1
x2, y2, z2 = pos2
# 거리 공식을 적용해서 거리 값을 계산
distance = math.sqrt(math.pow(x2-x1, 2)
... |
# Copyright 2020 Google LLC
#
# 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 agreed to in writing, ... |
import numpy as np
from lettuce.unit import UnitConversion
from lettuce.boundary import EquilibriumBoundaryPU, BounceBackBoundary, AntiBounceBackOutlet
class Obstacle2D(object):
"""
Flow class to simulate the flow around an object (mask) in 2D.
It consists off one inflow (equilibrium boundary)
and one... |
"""
Script to remap coordinates into a 3 and 6 Gpc cuboid
here is how to get the transofrmation coefficients :
import numpy as n
from astropy.cosmology import FlatLambdaCDM
import astropy.units as u
cosmoMD = FlatLambdaCDM(H0=67.77*u.km/u.s/u.Mpc, Om0=0.307115)#, Ob0=0.048206)
data = n.loadtxt("/data17s/darksim/softw... |
import numpy as np
import visual_dynamics.utils.transformations as tf
from visual_dynamics.policies import TargetPolicy
def hra_to_xyz(hra):
height, radius, angle = hra
return np.array([radius * np.sin(angle), -radius * np.cos(angle), height])
def xyz_to_hra(xyz):
return np.array([xyz[2], np.linalg.nor... |
import argparse
import os
import torch
import _init_paths # pylint: disable=unused-import
from lib.utils.analyser import Analyser
from lib.utils.checkpointer import get_weights, load_weights
from lib.utils.comm import all_gather, is_main_process, synchronize
from lib.utils.logger import build_test_hooks
fr... |
import discord
from discord.ext import commands
import random
import datetime
from PIL import Image
from io import BytesIO
import random
client = discord.Client()
class games(commands.Cog):
def __init__(self, client):
self.client = client
async def editimage(self, embed, first, target):... |
import coloredlogs, logging
from typing import Union
# Create a logger object.
logger = logging.getLogger(__name__)
from bs4 import BeautifulSoup
import os
import urllib
#BASE_URL和BASE_DIR末尾一定是斜杠
BASE_URL = "https://www.haskell.org/"
BASE_DIR = "E:\Temp\practice_scrapy\\tutorial\src\storeScrapy_Documentation\\"
html_hi... |
import numpy as np
import glob
import struct
import time
from ANN.LeNet_5 import *
import matplotlib.pyplot as plt
def normalization(x):
"""
:param x:输入的数据维度可能是[N,C,H,W]或[N,m]
:return: 归一化后的结果
"""
eps = 1e-5
if x.ndim > 2:
mean = np.mean(x, axis=(0, 2, 3))[:, np.newaxis,... |
"""
.. module:: _h5write
:synopsis: Write Python values into an MAT file for Octave.
Strives to preserve both value and type in transit.
.. moduleauthor:: <NAME> <<EMAIL>>
"""
import sys
import os
from scipy.io import savemat
import numpy as np
from scipy.sparse import csr_matrix, csc_mat... |
####################
# Author: <NAME>
# Title: PositivityCheck
####################
####################
# Index:
# 1. Imports and Readme
# 2. Functions
# 3. Main
# 4. Testing
####################
###################################################################
# 1. IMPORTS AND README
#############... |
import re
from django.utils.safestring import mark_safe
from django.template.context import Context
from smartlinks.models import IndexEntry
class Parser(object):
"""
Abstract base class for smartlink-type functionality.
"""
# To be overridden by subclasses.
finder = None
def __init__(self,... |
try:
from unittest import mock
except ImportError:
import mock
import pytest
from selenium.webdriver.common.by import By
from selenium.webdriver.remote.webdriver import WebDriver, WebElement
from selenium.common.exceptions import NoSuchElementException
from poium import Page, PageElement, PageElements
@pyte... |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... |
from otree.api import Currency as c, currency_range
from ._builtin import Page, WaitPage
from .models import Constants
import random
import inflect
from django.conf import settings
# wait page before game 1
class Game2WaitPage(WaitPage):
def after_all_players_arrive(self):
p1 = self.group.get_player_b... |
from gensim.models.doc2vec import Doc2Vec, TaggedDocument
import nltk
nltk.download("popular", quiet=True)
from nltk.tokenize import word_tokenize
from get_data import get_final_file_path, csv_to_df
import sentence_tokenizer
import sys
import filepath as fp
sys.path.append("./src/Data_process")
import remove_punctuatio... |
# -*- coding: utf-8 -*-
from wcics import app, db, md, md_no_mj
from wcics.auth.manage_user import user
from wcics.database.models import AttendanceCodes, AttendanceRecords, News, OrganizationUsers, Roles, Users, Lessons
from wcics.database.models.roles import UserRoles
from wcics.database.models.roles.consts import... |
from math import floor
from pathlib import Path
from typing import Optional, List, Union, Tuple
import pandas as pd
import plotly
def plot_dataframe(
df: Union[pd.Series, pd.DataFrame],
print_index: bool = True,
title: Optional[dict] = None,
tbl_header_visible: bool = True,
tbl_header: Optional[d... |
import csv
import operator
import re
import copy
import sys
from operator import attrgetter
#####################
# Parameters
#####################
result_file_name = 'Result.csv'
#####################
# Start process
#####################
def main(code_smell_file_name, ia_file_name, alpha=1, cut_point='40'):
... |
# -*- coding: utf-8 -*-
import numpy as np
import numpy.polynomial.laguerre as la
import numpy.polynomial.legendre as le
import scipy
import scipy.special
import scipy.optimize
from renormalizer.model import Phonon, Mol, SpinBosonModel
from renormalizer.utils import Quantity
class DebyeSpectralDensityFunction:
... |
# This file is the same as ICP07 with the exception that it doesn't interpolate the
# first array.
import numpy as np
from convertScanToXY import convertScanToXY
from scipy.spatial.distance import pdist,cdist
import operator
import pdb
import math
import time
# def distance(x1,y1,x2,y2):
# dist=math.sqrt(((flo... |
#!/usr/bin/env python3
"""
** Jamf Extension Attribute Upload Script
by <NAME>
Credentials can be supplied from the command line as arguments, or inputted, or
from an existing PLIST containing values for JSS_URL, API_USERNAME and API_PASSWORD,
for example an AutoPkg preferences file which has been configured for u... |
## @file gameservices.py
# @author <NAME>
#
# @brief This app contains the app logic
# @{
## Import modules
from flask import *
import json
import _pickle as pickle
from net import *
from genetic import *
from database import Database
##connect database
database = Database()
## Running parameters as global vari... |
import sys
width = int(input())
height = int(input())
players = int(input())
class Player:
def __init__(self, x, y):
self.x = x
self.y = y
DIR = {'UP' : 'C', 'RIGHT' : 'A', 'DOWN' : 'D', 'LEFT' : 'E', 'STAY' : 'B'}
grid = [['?' for x in range(width)] for y in range(height)]
enemies = [Player(-1,... |
import demistomock as demisto
from CommonServerPython import * # noqa # pylint: disable=unused-wildcard-import
from CommonServerUserPython import * # noqa
import requests
import traceback
from typing import Dict
import jwt
import uuid
# Disable insecure warnings
requests.packages.urllib3.disable_warnings() # pylin... |
import numpy as np
import torch
from torch.autograd import Variable
from .python_utils import delayed_keyboard_interrupt
from .exceptions import assert_, ShapeError, NotUnwrappableError
def unwrap(tensor_or_variable, to_cpu=True, as_numpy=False, extract_item=False):
if isinstance(tensor_or_variable, (list, tuple... |
# coding=utf-8
"""
Problem 61
16 January 2014
Triangle, square, pentagonal, hexagonal, heptagonal, and octagonal numbers are all figurate (polygonal)
numbers and are generated by the following formulae:
Triangle P3,n=n(n+1)/2 1, 3, 6, 10, 15, ...
Square P4,n=n2 1, 4, 9, 16, 25, ...
Pentagonal P5,n... |
import json
import logging
import os
import platform
from urllib.parse import urlparse
from django.conf import settings
from kubi_ecs_logger import Logger
from kubi_ecs_logger.models import BaseSchema, Severity
# Event categories - https://www.elastic.co/guide/en/ecs/current/ecs-allowed-values-event-category.html #... |
from contextlib import contextmanager
from sqlalchemy.schema import MetaData, CreateTable, DropTable
from sqlalchemy import Table, Column, PrimaryKeyConstraint
from sqlalchemy.types import BigInteger, Integer, Float, Text, Boolean, DateTime, Date, Time
from ..api.spec import FieldType
async def create_table(mo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.