text stringlengths 3.07k 22.1k |
|---|
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--trainset', default="./catdf.csv")
parser.add_argument('--testset', default="./testcatdf.csv")
parser.add_argument('model_filename')
parser.add_argument('-l', '--hidden_layer_index', type=int, default=-5)
parser.add_argument('-m', '--train_month',... |
"""Functions for validating data file formats and contents
"""
from typing import List, Optional, cast, Union, Iterator
from shapely.geometry import MultiPolygon, Polygon, Point # type: ignore
from shapely.ops import unary_union # type: ignore
import numpy as np # type: ignore
from data_interface import (
TOWE... |
"""Loading data functions
This script contains the function load_data needed to make the interface
with the user and also the associated functions for the check.
This file can be imported as a module and contains the following
functions:
"""
import datetime
import xarray as xr
from astropy.time import Time
import wa... |
import numpy as np
import os
import pickle
import random
import argparse
import time
import torch
import torch.nn as nn
import torch.backends.cudnn as cudnn
import torchvision.transforms as trn
import torchvision.transforms.functional as trnF
import torchvision.datasets as dset
from torchvision.utils import save_image
... |
# <NAME> (a Sokoban clone)
# the original work is by <NAME>: <EMAIL> |
# http://inventwithpython.com/pygame
import random, sys, copy, os
from pygame import *
#from pygame.locals import *
FPS = 30 # frames per secon to update the screen
WIN_WIDTH = 800
WIN_HEIGHT = 700
HALF_W = int(WIN_WIDTH / 2)
HAL... |
#!/usr/bin/python
#
# 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... |
#!/usr/bin/env python
#-*- coding:utf-8 -*-
"""
*.py: Description of what * does.
Last Modified:
"""
__author__ = "<NAME>"
__email__ = "<EMAIL>"
__version__ = "0.0.1"
from .dbManager import ESWrapper
from . import GeoPoint, blacklist, loc_default, CountryDB, AdminDB, FEATURE_WEIGHTS, isempty
from .loc_config... |
"""
Image reading tests against the dials_regression suite
"""
from __future__ import division, print_function
import os
import re
import pytest
import py.path
from dxtbx.format.Registry import Registry
import libtbx.load_env
from iotbx.command_line.detector_image_as_png import convert_image
# from iotbx.command_lin... |
# Parse the data from the dat file -> Points vs Horizontal Position = how many rows per column in the 2D array
# -> Points vs Vertical Position = how many columns in the 2D array
# Create a dictionary and populate it with other dictionaries based on the data in the dat file
# ... |
import os
import sys
import torch
import torch.autograd as autograd
import torch.nn.functional as F
import torch.nn as nn
import torch.utils.data as data
import torch.optim as optim
import data_utils as data_utils
import datetime
import sklearn.metrics as metrics
import time
import numpy as np
from termcolor import col... |
##############################################################################
# Copyright (C) 2019, UW REACT
#
# 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 co... |
"""
The controller for altering arena lighting provided by a DirectionalLight and a Background
Currently doesn't support:
- Timed pre-match lighting changes
"""
import sys
from typing import Dict, List, Tuple, Optional, NamedTuple
from pathlib import Path
from dataclasses import dataclass
from controller import Node, ... |
import json
import os
import requests
from boto.ec2.instancetype import InstanceType
from data_libs.aws_data_dal import AWS_OLD_INSTANCES_DATA_URL, AWS_INSTANCES_DATA_URL
from data_libs.aws_data_dal import get_aws_per_region_data, get_fresh_region_data, update_aws_data_region
# full file AWS_INSTANCES_DATA_URL =
# 'ht... |
import json
import os
import shutil
import uuid
import logging
import datetime
import settings
from bgtask import bgt
from helpers import get_sha1_hash
from storage import storage_factory
os.environ['PYTHONHASHSEED'] = str(settings.RANDOM_SEED)
import random
random.seed(settings.RANDOM_SEED)
import numpy as np
np.... |
"""Defines the GUI IO file for Tecplot."""
from collections import OrderedDict
import numpy as np
#from numpy import arange, mean, amax, amin, array
from vtk import vtkHexahedron, vtkQuad, vtkTriangle, vtkTetra
from pyNastran.converters.tecplot.tecplot import read_tecplot
#from pyNastran.converters.tecplot.utils impo... |
#!/usr/bin/env python
# http://rnacentral.org/api
import sys, os, optparse, requests, json
### app ###
__version__ = '1.0.0'
#### RNAcentral ####
__rnacentral_api_url__ = 'http://rnacentral.org/api/v1/rna/'
__rnacentral_api_xrefs_url__ = 'http://rnacentral.org/api/v1/rna/__ID__/xrefs'
__rnacentral_api_version__ = 'v... |
import os
import subprocess
import unittest
import re
from sympy.printing.tests.test_numpy import np
from TS.Edge import Edge
from TS.TransitionSystem import TransitionSystem
from Core.Structure import StructureAgent
from Core.Complex import Complex
from Parsing.ParseBCSL import Parser
from TS.State import Vector, St... |
# encoding: utf-8
# calibrate.py
# by <NAME>
# Modification history:
# 2021-11-25: extract from valence.py
# 2021-12-01: convert to use pandas, keeping legacy i/o wrapper function
# Code to calibrate valence values; used in conjunction with valence.py
# ****************************************** Calibration *******... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# File: multigpu.py
# Author: <NAME> <<EMAIL>>
import tensorflow as tf
import itertools
import operator
import re
from six.moves import zip, range
from ..utils import logger
from ..utils.naming import TOWER_FREEZE_KEYS
from ..utils.concurrency import LoopThread
from ..tfu... |
from fabric.colors import green as _green, yellow as _yellow, red as _red
from settings import cloud_connections, DEFAULT_PROVIDER
from ghost_log import log
from ghost_tools import get_aws_connection_data, GCallException, boolify
from ghost_tools import b64decode_utf8, get_ghost_env_variables
from ghost_tools import ... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import xml.etree.ElementTree as ET
import numpy as np
import re
import math
FILE_PATH = os.path.dirname(os.path.realpath(__file__))
DATA_PATH = os.path.join(FILE_PATH, "../data/")
LABEL_DATA_PATH = ... |
import torch
import torch.nn as nn
from models.backbone import PointNet2,PointNet
from models.common import compute_proposal,in_side,compute_target,Box_branch,IOU_branch,compute_box,compute_reg
from utils.anchor import NMS,align_anchor,assign_anchor,NMS_proposal
from models.group_pointcloud import preprocess,PointsPool... |
import json
import re
from datetime import datetime
from eve.io.base import DataLayer
from eve.utils import str_to_date
from arango import ArangoClient
VALID_OPS = [
'==', '!=', '<', '<=', '>', '>=',
'IN', 'NOT IN', 'LIKE', '=~', '!~'
]
VALID_SEPS = ['', ',', 'AND', 'OR', 'NOT']
def date_hook(json_data):
... |
# -*- coding:utf-8 -*-
import collections
import sys
import time
import numpy as np
import scipy.sparse as sp
from anneal.models import ClassicalIsingModel, QuantumIsingModel
from anneal.annealers import SimulatedAnnealer, QuantumAnnealer
POSITIONS = [
(24050.0000, 123783),
(24216.6667, 123933),
(24233... |
import numpy as np
import pandas as pd
import argparse
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.svm import SVC
from sklearn.linear_model import LinearRegression
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import AdaBoo... |
# -*- coding: utf-8 -*-
"""
Created on Wed Jun 9 14:55:36 2021
@author: libon
"""
import matplotlib.pyplot as plt
from functools import reduce
import datetime
import numpy as np
import pandas as pd
import copy
import os
'''This script read in the keelinged output files and
generate the flag... |
from utils.edit_msg import edit_msg
from utils.emojis import ERROR
from utils.request_url import request
from filters import ForEveryoneRule
from typing import Optional
from PIL import Image, ImageFont, ImageDraw, ImageOps
from vkbottle.tools import PhotoMessageUploader
from vkbottle.user import Blueprint, Mes... |
import numpy as np
import scipy.special as special
def loopbrz( Ra, I0, Nturns, R, Z ):
# Input
# Ra [m] Loop radius
# I0 [A] Loop current
# Nturns Loop number of turns (windings)
# R [m] Radial coordinate of the point
# Z [m] Axial coordinate of... |
import numpy as np
import concurrent.futures
from operator import itemgetter
from sim_exp import arrival_rate_upperbound
from mapper import *
from policygrad_learning import *
from q_learning import *
# ############################################ Scher ########################################### #
class Scher(obje... |
import os
import cv2
import random
import argparse
import importlib
import numpy as np
from tqdm import tqdm
from matplotlib import pyplot as plt
from PIL import Image
import clip
import torch
import torch.nn.functional as F
from torch.utils.data import DataLoader
from clip_model import CLIPVisionEncoder, CLIPTextEnc... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import logging
from collections import namedtuple
from typing import Optional
import numpy as np
import pyspiel
from open_spiel.python.algorithms import get_all_states
from open_spiel.python.algorithms.best_re... |
###################
# qspace - spf.py #
###################
# This file contains the implementation of the spherical harmonic basis. #
##########################################################################
import numpy as np
import sh, utils
from scipy.special import lpmv, gamma, hyp1f1, legendre
from scipy.specia... |
'''
Author: <NAME>
Momenter python library
Version: 1.2.2
License: MIT
All rights reserved (c) 2021
'''
import datetime
import calendar
from time import time, ctime, strftime
from datetime import date
def format(value):
if value == "YYYY MM DD HH MM SS":
x = datetime.datetime.now()
... |
import numpy as np
import scipy.stats as stats
import pandas as pd
import math
"""
Obtain 39 sleep feats, following https://www.nature.com/articles/s41598-020-79217-x.pdf
"""
def get_pre_mean_diff(data, index, num_ele):
pre_eles = data[index - num_ele : index]
pre_mean = np.mean(pre_eles)
return pre_mean... |
"""
Pre-processing for cleaning the text data
"""
import re
import string
from nltk import word_tokenize
from nltk.corpus import stopwords
from nltk.stem.snowball import SnowballStemmer
def get_contractions():
contraction_dict = {"ain't": "is not", "aren't": "are not", "can't": "cannot", "'cause": "because",
... |
import logging
import warnings
from typing import Optional, Dict, Tuple, Any, Callable
import numpy as np
from autofit.graphical.laplace.line_search import line_search, OptimisationState
from autofit.graphical.utils import Status, StatusFlag, LogWarnings
from autofit.mapper.variable_operator import VariableData
## ... |
import enum
import re
from dataclasses import dataclass
from itertools import groupby
from typing import (Any, Callable, Dict, Iterable, List, Optional, Tuple,
Union, cast)
from docutils import nodes
from docutils.parsers.rst.directives import flag, unchanged, unchanged_required
from sphinx import ... |
import base64
import datetime
import io
import json
from dataclasses import asdict, dataclass, field, is_dataclass
from textwrap import indent
from typing import Any, Dict, List, Optional, Union
from cryptography import x509
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetr... |
# 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 writing, so... |
import copy
import gzip
import os
import shutil
from datetime import datetime
import sunpy
from PyQt5 import QtWidgets, QtCore
from PyQt5.QtCore import pyqtSignal
from PyQt5.QtGui import QCursor
from PyQt5.QtWidgets import QTableWidgetItem
from dateutil import parser
from sunpy.database import Database, tables
from su... |
from __future__ import print_function, absolute_import, division
from future.builtins import *
from future import standard_library
standard_library.install_aliases()
# Copyright 2017 Autodesk Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with ... |
# Copyright 2020 ByteDance 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 writin... |
from parse import Encoder
import argparse
import ast
from vol import VComp
from z3 import *
from z3extra import *
from threading import Thread
from redlogInterface import *
from simulate import *
import time
from probcomp import ProbComp
from logwriter import LogWriter
from plotter import Plotter
from functools import ... |
#!/usr/bin/env python3
import numpy as np
import requests
from pwn import *
import shutil
import os
import cv2
import pytesseract
from PIL import Image
import matplotlib.pyplot as plt
from time import sleep, time
import pytesseract
from multiprocessing import Process, Manager
from ocr import predict
WHITE = 255
BLA... |
import matplotlib.pyplot as plt
import networkx as nx
from matplotlib.animation import FuncAnimation
import numpy as np
import time
import os
__author__ = 'Rainer.Kuj<EMAIL>'
class SI_AnimHelper(object):
def __init__(self, infection_times):
event_fname = "events_US_air_traffic_GMT.txt"
if not os.... |
import argparse
import yaml
import json
import os
from Simulation.TP_with_recovery import TokenPassingRecovery
import RoothPath
from Simulation.simulation_new_recovery import SimulationNewRecovery
from Simulation.tasks_and_delays_maker import *
from statistics import *
import matplotlib.pyplot as plt
from Utils.pool_wi... |
# -*- coding: utf-8 -*-
# Copyright 2019 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Sysroot controller."""
from __future__ import print_function
import os
from chromite.api import controller
from chromite.api... |
import os
import torch
import numpy as np
import cv2
import math
import random
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
class FaceLandmarksDataset(torch.utils.data.Dataset):
def __init__(self, root, transform=None, train=False, model='onet'):
self.root = root
self.tran... |
# main imports
import numpy as np
import pandas as pd
import sys, os, argparse
# image processing
from PIL import Image
from ipfml import utils
from ipfml.processing import transform, segmentation
import matplotlib.pyplot as plt
# model imports
import joblib
# modules and config imports
sys.path.insert(0, '') # tri... |
# Copyright 2019 IBM Corp.
#
# 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, sof... |
import io
from lxml import objectify, etree
import pathlib
import pytest
import tempfile
import re
from hescorehpxml import (
HPXMLtoHEScoreTranslator,
main
)
both_hescore_min = [
'hescore_min_v3',
'hescore_min'
]
def get_example_xml_tree_elementmaker(filebase):
rootdir = pathlib.Path(__file__).... |
"""
Implements pipelines to track a sequence: Obtain costs, solve the instance (global or instance wise)
"""
import torch
import numpy as np
from scipy.sparse import csc_matrix
from tqdm import tqdm
import math
import os
from src.TrackingModel import TrackingModel
from src.datasets import Data, SplittedDataloader
fro... |
import matplotlib.pyplot as plt
import copy
import sys
import math
import numpy as np
def brnhms(x1, y1, x2, y2):
x_data = []
y_data = []
x_data.append(x1)
y_data.append(y1)
dx = abs(x2 - x1)
dy = abs(y2 - y1)
if (x2 > x1):
xs = 1
else:
xs = -1
if (y2 > y1):
... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from . import ... |
import time
import sys, os
import sysfs_paths as sysfs
import atexit
import psutil
# Userspace cpu frequency governor
# Based on:
# https://stackoverflow.com/questions/1296703/getting-system-status-in-python#1296816
# On the exynos 5422, cluster 0 is the low-power (LITTLE) cluster and
# cluster 1 is the high-power (... |
# from parser import myDict
import gc
import os,math
from tqdm import tqdm
import nltk
from multiprocessing import Pool, cpu_count
nltk.download('punkt', quiet=True)
nltk.download('stopwords', quiet=True)
import dependancyManager as dm
def getStats(mailboxes):
emailCount = count = tosCount = 0
addresses ... |
"""
Interface for function management.
"""
from __future__ import annotations
from typing import List
import logging
import dragodis.interface
from dragodis import Disassembler, NotExistError
from dragodis.interface import (
StackLocation, RelativeRegisterLocation, StaticLocation, RegisterLocation,
RegisterP... |
#!/usr/bin/env python
"""TechArts3D tso file exporter for blender 2.78
"""
from itertools import groupby
import os
import shutil
import bpy
from io_scene_tso_tmo.io.tso import TSOFile, TSONode, TSOMesh, TSOSubMesh, Vertex, TSOSubScript, TSOTexture
from io_scene_tso_tmo.utils.heap import Heap
from io_scene_tso_tmo.uti... |
import numpy
from sklearn.model_selection import GridSearchCV
from sklearn.metrics import SCORERS
from keras.models import Sequential
from keras.layers import Dense, Dropout
from keras.wrappers.scikit_learn import KerasRegressor
import pandas as pd
import calendar
from datetime import datetime
from keras import callba... |
"""
词法分析
"""
import re
import os
class Error:
"""
错误
"""
def __init__(self, error_info):
"""
构造
:param error_info: 错误信息
"""
self.info = error_info
class LexicalError(Error):
"""
词法错误
"""
def __init__(self, error_info, error_line,error_value=None):... |
import torch
import mmcv
import logging
import torch.multiprocessing as mp
import numpy as np
import cv2
import os
import scipy
from time import time
from mmcv.utils import ProgressBar
from .pose_demo import inference as pose_inference
from mmskeleton.apis.estimation import inference_pose_estimator, init_pos... |
from functools import partial
from hat import aio
from hat import util
from typing import Dict, Callable, Any
import asyncio
import itertools
import logging
from aimm import plugins
from aimm.server import common
from aimm.server import mprocess
mlog = logging.getLogger(__name__)
async def create(conf: Dict,
... |
# -*- coding: utf-8 -*-
# -------------------------------------------------------------------------
# This scaffolding model makes your app work on Google App Engine too
# File is released under public domain and you can use without limitations
# -------------------------------------------------------------------... |
import copy
import typing
from pathlib import Path
import click
import vpype as vp
# Load the default config
vp.CONFIG_MANAGER.load_config_file(str(Path(__file__).parent / "bundled_configs.toml"))
def invert_axis(document: vp.Document, invert_x: bool, invert_y: bool):
"""Inverts none, one or both axis of the d... |
'''VGG11/13/16/19 in Pytorch.
We perturb the weight and bias parameters for convolutional, linear and batch
normalization layers.
'''
import torch.nn as nn
import torch
import torch.nn.functional as F
from torch.nn.modules.utils import _pair
from cnns.nnlib.pytorch_architecture import layer
Noise = layer.Noise
Noise... |
"""Run the mni to bold transformation on an fmriprep output"""
import os
def get_parser():
"""Build parser object."""
from argparse import ArgumentParser
from argparse import RawTextHelpFormatter, RawDescriptionHelpFormatter
parser = ArgumentParser(
description="""NiWorkflows Utilities""", for... |
import warnings
import exceptions
import functools
from selection import Selection, ScalarSelector, OrClause, AndClause
from selection import Compound, DictSelectable
from functions import *
from tempoiq.protocol.rule import Rule
from tempoiq.tempo_exceptions import TempoIQDeprecationWarning
PIPEMSG = 'Pipeline funct... |
import tensorflow as tf
import numpy as np
import math
from tensorflow.python.util import nest
tf.set_random_seed(20160408)
# log probability
def probability(min_embed, max_embed):
# min_embed: batchsize * embed_size
# max_embed: batchsize * embed_size
# log_prob: batch_size
# numerically stable log pr... |
#!/usr/bin/env python
#########################################################################################
#
# Perform various types of processing from the spinal cord segmentation (e.g. extract centerline, compute CSA, etc.).
# (extract_centerline) extract the spinal cord centerline from the segmentation. Output ... |
# <NAME> 2017
# GMM implementation I made for a computer vision course during my honours degree at Wits
import numpy as np
from sklearn.mixture import GaussianMixture
from scipy.stats import multivariate_normal
# These are functions which can be run on GMMs
class fn():
def zero_init(data, K):
lambda_vect = np.full... |
# Lab 10 MNIST and Dropout
# SELU implementation from https://github.com/bioinf-jku/SNNs/blob/master/selu.py
import tensorflow as tf
import random
# import matplotlib.pyplot as plt
# -*- coding: utf-8 -*-
'''
Tensorflow Implementation of the Scaled ELU function and Dropout
'''
import numbers
from tensorflow.contrib im... |
#D:\Python\Python35\python
# -*- coding:utf-8 -*-
import requests,re,csv
def get_sina():
api='http://m.weibo.cn/index/my?format=cards&page=%s'
cookies = {
"ALF": "xxxx",
"SCF": "xxxxxx.",
"SUBP": "xxxxx",
"SUB": "xxxx",
"SUHB": "xxx-", "xx": "xx", "_T_WM": "xxx",
... |
import logging
from uuid import UUID
from typing import List
from sqlalchemy import select, func, desc, update
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import selectinload
from acapy_client.api.revocation_api import RevocationApi
from acapy_client.model.revoke_request import RevokeRequest
f... |
from functools import partial
from PyQt5 import QtCore, QtGui, QtWidgets
import numpy as np
import scipy.linalg
from pyqtgraph import ImageItem, ColorMap, graphicsItems, HistogramLUTItem
from .DataItem import ExtendedDataItem
from .PlotWindow import ExtendedPlotWindow
from .ViewBox import CustomViewBox
from .colors i... |
from enum import IntEnum
"""
Usage is:
* call init()
* call process(mag_x, mag_y, mag_z, timestamp) # timestap assumed to be in seconds
* access the "moving" parameter to determine if the pumpjack is operating
** 1 => haven't decided yet
** 2 => not moving
** 3 => moving
* access the "rotating" parameter ... |
#!/usr/bin/env python
##################################################################
# Copyright (C) 2019-2020 LevelOps Inc <<EMAIL>>
#
# This file is part of the LevelOps Inc Tools.
#
# This tool is licensed under Apache License, Version 2.0
#################################################################... |
from flask import Flask
from flask import request
from flask import Response
import msgpack
import time
import json
form="""<!DOCTYPE html> \
<html> \
<body> \
\
<form action="/data" method="post">\
new datablock: <textarea\
cols="100" \
rows... |
#! /usr/bin/env python3
import logging
logging.basicConfig(format="%(levelname)s:%(message)s", level=logging.ERROR)
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
import click
import getpy as gp
import numpy as np
from xbin import XformBinner as xb
import pandas as pd
from hashed_loop import (
... |
import itertools
import json
import logging
import random
import string
from time import time
from enum import Enum
from tornado.ioloop import IOLoop
from tornado.web import MissingArgumentError
from tornado.websocket import WebSocketHandler
from tables import async_db_call, player_stats
MAX_NAME_LENGTH = 22
_game_m... |
# -*- coding: utf-8 -*-
"""Operations on pLDDT statistics."""
from pathlib import Path
from typing import List
from typing import Optional
from typing import Tuple
import Bio.PDB # type: ignore
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns # type: ignore
from loguru imp... |
from math import *
class Vec3:
def __init__(self, x, y, z):
self.x, self.y, self.z = x, y, z
def __add__(self, v):
return Vec3(self.x+v.x, self.y+v.y, self.z+v.z)
def __sub__(self, v):
return Vec3(self.x-v.x, self.y-v.y, self.z-v.z)
def __mul__(self, v):
i... |
# This file is part of GridCal.
#
# GridCal 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 of the License, or
# (at your option) any later version.
#
# GridCal is distributed in the hope that... |
# -*- coding: utf-8 -*-
# Minio Python Library for Amazon S3 Compatible Cloud Storage, (C) 2015 Minio, 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/licen... |
# Analyze an audio file, or all audio files in a directory.
# For each audio file, extract spectrograms, analyze them and output an Audacity label file
# with the class predictions.
import argparse
import os
import sys
import time
import warnings
warnings.filterwarnings('ignore') # suppress librosa warnings
os.enviro... |
import numpy as np
import glob
#code from cameracongig.xml
import copy
import xml.etree.ElementTree as ET
DEFAULT_CONFIGFILE="""<?xml version="1.0" ?>
<file>
<CameraConfig version="2">
<system />
<skeleton />
<postprocessing height_min="0" height_max="0" radius_filter="0" greenscreenremova... |
from subprocess import call
import cv2
from matplotlib import pyplot as plt
import numpy as np
import time
import math
import queue
import util
import random
chessman_base_color = [102, 59, 55]
# scan line for next block
# left <-
#cv2.line(cur_img, (0, 1300), (1080, 650), (255, 0, 0), 1)
# rignt ->
#cv2.line(cur_im... |
#!/usr/bin/env python3
"""utils tests"""
import numpy as np
import tensorflow as tf
from lm_human_preferences.utils import core as utils
def test_exact_div():
assert utils.exact_div(12, 4) == 3
assert utils.exact_div(12, 3) == 4
try:
utils.exact_div(7, 3)
assert False
except ValueErr... |
import argparse
import math
import random
import sys
import os
import json
import numpy as np
import time
import operator
scatter_word_list = ['scatter', "'scatter'", '"scatter"', 'scatter_kws', "'o'", "'bo'", "'r+'", '"o"', '"bo"', '"r+"']
hist_word_list = ['hist', "'hist'", '"hist"', 'bar', "'bar'", '"bar"', 'count... |
import argparse
from collections import namedtuple
from functools import partial
import hashlib
import urllib.request
import os
from os import path
import string
import sys
import zipfile
import json
import subprocess
from cv2 import imread, imwrite, VideoCapture, resize
import cv2
import keras.backend as K
from keras.... |
import datetime
import os
import subprocess
import numpy
from scipy.stats import norm
from . import romannumerals
# ToDo: Bring back scale bar
# ToDo: Add option for solid fill of vectors
def roundto(num, nearest):
"""
Rounds :param:`num` to the nearest increment of :param:`nearest`
"""
return int... |
import multiprocessing
import argparse
from distutils.util import strtobool
import json
import softlearning.environments.utils as env_utils
from softlearning.misc.utils import datetimestamp
DEFAULT_UNIVERSE = 'gym'
DEFAULT_TASK = 'Default'
TASKS_BY_DOMAIN_BY_UNIVERSE = {
universe: {
domain: tuple(tasks.... |
import hlt
import logging
from collections import OrderedDict
import numpy as np
import random
import os
VERSION = 1
HM_ENT_FEATURES = 5
PCT_CHANGE_CHANCE = 30
DESIRED_SHIP_COUNT = 20
game = hlt.Game("Charles{}".format(VERSION))
logging.info("CharlesBot-{} Start".format(VERSION))
ship_plans = {}
... |
import pickle
import numpy as np
import os
import scipy.sparse as sp
import torch
from scipy.sparse import linalg
class DataLoader(object):
def __init__(self, xs, ys, batch_size, pad_with_last_sample=True, irregularity=None):
"""
:param xs:
:param ys:
:param batch_size:
:pa... |
import json
from openbrokerapi.service_broker import (
ProvisionedServiceSpec,
UpdateServiceSpec,
Binding,
DeprovisionServiceSpec,
LastOperation,
UnbindDetails,
ProvisionState,
ProvisionDetails,
UpdateDetails,
BindResource,
BindDetails,
DeprovisionDetails
)
from opcua i... |
from metrics import calculate_metrics
import torch
from torch import nn
import sklearn
import sklearn.metrics
import numpy as np
from tqdm import tqdm
import wandb
import datetime
import pickle
from PIL import Image
import PIL
from collections import defaultdict
import mxnet as mx
from mxnet import ndarray as nd
#devi... |
#!/usr/bin/env python3
"""
Creates a graph showing the pandemic course of selected german counties.
Based on data from <NAME>: https://pavelmayer.de/covid/risks/
Copyright 2021 <NAME>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You... |
#!@PYTHON@ -tt
#
#############################################################################
# Copyright 2011 <NAME>
# This file is part of fence-xenserver
#
# fence-xenserver 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 Soft... |
import logging
import sys
import os
import re
import collections
import pathlib
import json
from nuaal.definitions import LOG_PATH, ROOT_DIR, OUTPUT_PATH
def get_logger(name, DEBUG=False, verbosity=4, handle=["stderr"], with_threads=False):
"""
This function provides common logging facility by creating instan... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import cgi
import re
from ccg2lambda_tools import build_ccg_tree
from lxml import etree
from semantic_index import find_node_by_id
## Conversion to vertical notation
from nltk.sem.logic import *
from logic_parser import lexpr
from vertical_mathml import convert_to_vertical
... |
# coding=utf8
"""
Copyright © 2018, <NAME>, <<EMAIL>>
Licensed under the MIT License.
"""
from __future__ import absolute_import, unicode_literals
import time
import sys
import cv2
import socket
import logging
import numpy as np
from livechat import environ as env
from livechat.conncls import command, conn, bin
from... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.