text stringlengths 3.07k 22.1k |
|---|
from Tkinter import Frame, BOTTOM, LEFT, S, NW, X, BitmapImage, Button, \
Scale, YES, BOTH, Canvas
from math import log10, pow, floor, degrees
#####################
# TRANSPORT BUTTONS
DATA_BITMAP_BEGIN = """
#define Xbitmap_width 20
#define Xbitmap_height 21
static unsigned char Xbitmap_bits[] = {
0x00,... |
#!/usr/bin/env python3
# Copyright (c) 2021 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test bip8 activation
"""
import random
import time
from test_framework.test_framework import BitcoinTestFr... |
import os
import json
import time
from multiprocessing import Pool
import numpy as np
import pandas as pd
from utils.file_functions import get_subfolder_names
from utils import settings
from utils.Recording import Recording
from loader.XSensRecordingReader import XSensRecordingReader
def initialize_dataconfig(data_c... |
#!/usr/bin/env python
# license removed for brevity
import rospy
#from std_msgs.msg import String
import std_msgs.msg as msg
import numpy as np
import matplotlib.pyplot as plt
import scipy.io as sio
import math
from swiftnav_piksi.msg import loc
from swiftnav_piksi.msg import fil
from nav_msgs.msg import Odometry
#Ini... |
# -*- coding: utf-8 -*-
"""
AppDaemon App to create a Time-Weighted Moving Average sensor over another one.
Conceived for those sensors without a periodic update interval,
where the more common moving averages based on a number of samples
are not a valid solution, nor is the one with the stats sensor with max_age,
whi... |
import pytz
from pytz.exceptions import UnknownTimeZoneError
from unittest import TestCase
from unittest.mock import MagicMock,call
from datetime import datetime
import iso8601
from bumblebee.config import LoadMethod, TaskFiles, AppConfig, TaskConfigFromEnv, parse_date
from bumblebee.datehelper import localise_datet... |
from candidatesBasedAlgorithm import *
import copy
from heapq import *
class AbstractElection(object):
##State access
def getResult(self):raise NotImplementedError()
def getNumberOfCandidates(self):raise NotImplementedError()
##Pruning heuristics management
def getUtility(self):raise... |
""" Tests for the AtomNumber class """
import numpy as np
from openmc.deplete import atom_number
def test_indexing():
"""Tests the __getitem__ and __setitem__ routines simultaneously."""
local_mats = ["10000", "10001"]
nuclides = ["U238", "U235", "U234"]
volume = {"10000" : 0.38, "10001" : 0.21}
... |
import os
import json
import webbrowser
import logging
import threading
import select
from datetime import datetime
import psycopg2
from flask import Flask, render_template, request, jsonify
from flask_socketio import SocketIO
from flask_cors import CORS
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow i... |
"""Communicable disease outbreak simulator"""
import logging
import numpy as np
logger = logging.getLogger(__name__)
class Simulator:
"""
Attributes
----------
time : float
Time passed so far in years
"""
def __init__(self, burden, trans, death, trans_non_c, death_non_c, p_compli... |
import threading
import multiprocessing
import functools
import time
from time import perf_counter
from random import randint
import tkinter as tk
from collections import defaultdict
def benchmark(functionCallback):
""" Returns the start and end time of a function block in addition to its return value
:param ... |
from dataclasses import dataclass
import itertools
from e2cnn.kernels.basis import EmptyBasisException
import numpy as np
from typing import Iterable, List, Optional, Type, Union, Tuple
from e2cnn.kernels import Basis
from e2cnn.group import SO2, Representation
# we need SteerableDiffopBasis, but importing that direc... |
# -*- coding: utf-8 -*-
"""
Air conditioning equipment component models
"""
from __future__ import division
import numpy as np
from cea.demand import control_heating_cooling_systems, constants
from cea.demand.latent_loads import convert_rh_to_moisture_content, total_moisture_in_zone
__author__ = "<NAME>"
__copyright... |
from itertools import islice
import logging
from scipy import stats
import h5py
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from mpl_toolkits.axes_grid1 import make_axes_locatable
import torch
from torch.utils.data import DataLoader
from torchvision.utils import make_grid
from uncertify.v... |
# Ref: https://raw.githubusercontent.com/rbgirshick/py-faster-rcnn/master/lib/datasets/voc_eval.py
import numpy as np
import time
from .box_utils import box3d_iou
class APCalculator(object):
""" Calculating Average Precision """
def __init__(
self,
ap_iou_thresh=0.25,
class2type_map... |
from builtins import str
from builtins import object
import json
import argparse
import os.path
import cgi
import sys
from LogManager import logger
from DataTableHtml import outputDataTableHeader, outputDataTableFooter
from DataTableHtml import writeTableListInfo, outputDataListTableHeader
from DataTableHtml import ou... |
#!/usr/bin/python
"""
Compute the Zernike moments of a collection of points.
Authors:
- <NAME>, 2013, Columbia University (original MATLAB code)
- <NAME>, 2013, Tank Think Labs, LLC (port to Python)
- <NAME>, 2013 (<EMAIL>) http://binarybottle.com
Copyright 2013, Mindboggle team (http://mindboggle.inf... |
# Copyright 2015 Cray 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, softwa... |
#!/usr/bin/python
# Copyright 2018 Google 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 appli... |
# -*- coding: utf-8 -*-
import time
import pynvml
from pynvml.nvml import NVMLError_LibraryNotFound
from platform import platform, node, machine
from asyncio import get_event_loop
from aiohttp import ClientSession
from aiohttp.client_exceptions import ClientConnectorError
from socket import socket, AF_INET, SOCK_DGRAM,... |
import requests
import csv
from os import path
import pandas as pd
from io import TextIOWrapper, BytesIO
from zipfile import ZipFile
from pprint import pprint
import xml.etree.ElementTree as ET
from scipy.interpolate import interp1d
import numpy as np
from nelson_siegel_svensson.calibrate import calibrate_ns_ols
# m... |
#!/usr/bin/env python
# coding=utf-8
#####################################################
# ghtoc : markdown folder toc generator
# Author : sinlov <<EMAIL>>
# Usage : toc.py <markdown file>
# Date : 2016-10-24
# License : see https://github.com/sinlov/markdown-folder-toc
# Copyright (C) 2016 sinlov
#
# Permi... |
#!/usr/bin/env python3
# encoding: utf-8
"""
.. invisible:
_ _ _____ _ _____ _____
| | | | ___| | | ___/ ___|
| | | | |__ | | | |__ \ `--.
| | | | __|| | | __| `--. \
\ \_/ / |___| |___| |___/\__/ /
\___/\____/\_____|____/\____/
Created on Sept 14, 2014
This scripts generate... |
# Imports
from datetime import timedelta
from typing import List, Tuple
import hypothesis.strategies as st
import numpy as np
import numpy.testing as npt
import pandas as pd
import pyarrow as pa
import pytest
from hypothesis import given, settings
from fletcher._algorithms import (
_extract_data_buffer_as_np_arra... |
"""Project management functionality for Annif"""
import collections
import configparser
import enum
import os.path
from flask import current_app
from shutil import rmtree
import annif
import annif.analyzer
import annif.corpus
import annif.suggestion
import annif.backend
import annif.util
import annif.vocab
from annif.... |
import json
from datetime import datetime, time
from typing import TYPE_CHECKING, Any
import flux
from flask_login import UserMixin
from flask_security import RoleMixin
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.orm import backref
from sqlalchemy.orm import relationship as sqlalchemy_relationship
db = SQ... |
from functools import reduce
from collections import Counter
# [852] https://leetcode.com/problems/peak-index-in-a-mountain-array/
# Given an array that is definitely a mountain, return any i such that A[0] < A[1] < ... A[i-1] < A[i] > A[i+1] > ... > A[A.length - 1].
#
# linear search
def peakIndexInMountainArray1(A)... |
import os
import pickle
from typing import List, Union, Tuple, Any, Dict, Optional
import cv2
import numpy as np
import qrcode
from PIL import Image
from matplotlib import pyplot as plt
from pyzbar import pyzbar
from config import *
# * Filter and loader
def name_filter(name: str) -> bool:
return name.split('.'... |
import asyncio
import contextlib
import datetime
import json
import math
from io import BytesIO
from pathlib import Path
from typing import Optional
import aiohttp
from bs4 import BeautifulSoup
from fastapi import FastAPI, Header, HTTPException, status
from fastapi.encoders import jsonable_encoder
from fastapi.respons... |
# Standard Python modules
# =======================
# from collections import namedtuple
# External modules
# ================
# DICE modules
# ============
from dice_tools import wizard, DICEObject, diceProperty, diceSignal, diceSlot
from dice_tools.helpers.xmodel import modelRole, modelMethod, ModelItem
... |
import os, sys
sys.path.append('../..')
import json
import os.path
from utils.eval_metrics import moses_multi_bleu, huggingface_bertscore
import glob as glob
import numpy as np
import jsonlines
from tabulate import tabulate
import json
import matplotlib
import matplotlib.pyplot as plt
import re
def compute_prf(pred, ... |
import pandas as pd
import numpy as np
from sklearn.utils import shuffle
from sklearn.model_selection import train_test_split
from tensorflow.python.keras.preprocessing.text import Tokenizer
from tensorflow.python.keras.preprocessing.sequence import pad_sequences
from keras.models import Sequential
from keras.layers im... |
import numpy.polynomial.polynomial as poly
import numpy.linalg as linalg
import numpy as np
import integrate
def find_sigmas_with_signs_from_roots(roots):
"""Find (-1)^k * sigma_k, k = 0, ..., n,
where sigma_k = \\sum_{1 <= i_1 < ... < i_k <= n} z_{i_1} * ... * z_{i_k}
for k = 0, ..., n using 'roots' ... |
"""Submodule containing classes for time-based data."""
from scipy.signal import welch, get_window
import numpy as np
import matplotlib.pyplot as plt
import allantools
from .freq_data import OscillatorNoise
class CounterData:
"""
Counter data, i.e. a time series of frequency data.
Parameters
------... |
## @package TimeLines
# This module contains classes (Rve Modelers) that are used
# to handle the generation, assignment and tracking of
# RveConstitutiveLaws.
#
# More details
from __future__ import print_function, absolute_import, division #makes KratosMultiphysics backward compatible with python 2.6 and... |
import os
from busco.BuscoPlacer import BuscoPlacer
from busco.BuscoLogger import BuscoLogger
from busco.BuscoLogger import LogDecorator as log
from busco.BuscoRunner import AnalysisRunner
from busco.Exceptions import BuscoError
import numpy as np
logger = BuscoLogger.get_logger(__name__)
class NoGenesError(BuscoErr... |
import os
import operator as op
import logging
from lib.typecheck import *
import lib.const as C
from .. import util
from ..meta import class_lookup
from ..meta.template import Template
from ..meta.clazz import Clazz
from ..meta.method import Method
from ..analysis.empty import EmptyFinder
from accessor_uni import A... |
#!/usr/bin/env python
from Bio import SeqIO
import urllib.request
import subprocess
import argparse
import tempfile
import logging
import glob
import csv
import os
def main():
logging.basicConfig(format='\033[92m \033[1m %(asctime)s \033[0m %(message)s ',
level=logging.INFO,
... |
# -*- coding: utf-8 -*-
import datetime
import socket
import logging
import os
import pprint # noqa
import string
import threading
import time
from pytg.utils import coroutine
from pytg.receiver import Receiver
from pytg.sender import Sender
from pytg.exceptions import ConnectionError
from storage import Storage
... |
"""
Set up everything permission-related for QuickSight:
a. Pull user information from S3 location
b. Iterate through users, determine if they already exist in QuickSight.
c. if the user's namespace doesn't exist, create it
d. if user doesn't exist in the namespace, register them
e. update the users... |
import random
from datetime import datetime
import humanize
import pytz
from flask import url_for
from flask_scrypt import generate_password_hash, generate_random_salt
from sqlalchemy import event, desc
from sqlalchemy.ext.hybrid import hybrid_property
from sqlalchemy.sql import func
from sqlalchemy.orm.exc import Mul... |
#!/usr/bin/env python
# Licensed to Cloudera, Inc. under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. Cloudera, Inc. licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you ma... |
# **About** : This notebook is used to train models.
# - Use the `DEBUG` parameter to launch the code in debug mode (single fold, no logging)
# - Specify the training parameters in the `Config` class. Feel free to experiment with the parameters, here are the main ones :
# - `tile_size` : Tile size
# - `redu... |
import torch
from transformers import AutoTokenizer, GPTJForCausalLM
print("Dependencies imported")
# configurations for GPT-J
#tokenizer = AutoTokenizer.from_pretrained("gpt2")
tokenizer = AutoTokenizer.from_pretrained("EleutherAI/gpt-j-6B")
print("Loaded tokenizer")
#model = GPTJForCausalLM.from_pretrained("Eleuth... |
import argparse
import os
from itertools import izip
import cv2
from skimage import io
from data_collection.collect_data import render_equation, mk_template
from postprocessing.augmentation_utils import select_random_augmentation
from utils import run_command
def parse_args():
parser = argparse.ArgumentParser()... |
import sys
import zerorpc
import time
from math import *
from socket import *
from PyQt5.QtCore import pyqtSlot, QThread, pyqtSignal
from PyQt5.QtWidgets import QApplication, QDialog, QWidget
from PyQt5.QtGui import QPixmap
from PyQt5.uic import loadUi
from joystick import *
from raspibot import *
class JoystickThr... |
# monolithic simple module to convert IEX json to ELK json format
# IEX Attribution:
# https://iextrading.com/trading/market-data/
# in middle of this module within transform function
# simple convervsion to DF - DataFrame
# TBD DataFrame Normalization and Naive Correlation functions TBD
# Within ELK this enables seei... |
import numpy as np
from numpy import array
import pandas as pd
from keras.preprocessing import text, sequence
from keras.preprocessing.text import Tokenizer
from keras.utils import to_categorical
from keras.models import Model, Input
from keras.layers import LSTM, Embedding, Dense, TimeDistributed, Bidirectional, GRU, ... |
""" This is my rewrite of the anytree library """
from __future__ import annotations
import typing as tp
from itertools import takewhile
from blox.core.events import NodePreRename, NodePostRename, \
NodePreAttach, NodePostAttach, NodePostDetach, NodePreDetach
from blox.etc.utils import camel_to_snake
from blox.et... |
import math
import random
import os
# Synapse
class Synapse(object):
def __init__(self):
self.inpuT = 0
self.output = 0
self.weight = 0.0
self.enabled = True
self.innovation = 0
def clone(self):
synapse = Synapse()
synapse.inpuT = self.inpuT
syn... |
from idaapi import *
import idautils
#import pandas as pd
import struct
#import lief
import pefile
ori_op = [] #初始操作码(字符串)
ori_address = [] #初始地址
ori_length = [] #操作码长度
#call | # mov |#jz
args0 = [] #EIP | #operand1 |不跳转下一地址
args1 = [] #调用地... |
# метод улучшенный комбинированный
# -9 5 3
from math import sin, cos, pi, ceil
import matplotlib.pyplot as plt
import numpy as np
def f(x, key):
if key == 1:
return x ** 2 - 1
if key == 0:
return sin(x)
if key == 2:
return x ** 2 + 1
if key == 3:
return ... |
import json
import logging
import multiprocessing
import os
import queue
import select
import signal
import socket
import subprocess
import sys
import time
from ctf_gameserver.lib.checkresult import CheckResult
from . import metrics
ACTION_FLAG = 'FLAG'
ACTION_FLAGID = 'FLAGID'
ACTION_LOAD = 'LOAD'
ACTION_STORE = '... |
import numpy as np
from os.path import join
import os
import pandas as pd
import glob
import cv2 as cv
import json
from skimage.io import imread
import gdown
import sys
import requests
def make_dir(save_dir):
if not os.path.exists(save_dir):
os.makedirs(save_dir)
def laplacian_variance(img):
return np.var(cv.La... |
import math
import pickle
import sys
from dataclasses import dataclass
from os import path
from typing import Dict, List, Tuple
import logging
from enum import Enum
from wpilib.controller import SimpleMotorFeedforwardMeters
from wpilib.geometry import Pose2d, Rotation2d, Translation2d
from wpilib.kinematics import Dif... |
from .functions import FunctionRtoR
import numpy as np
from sympy import abc
from typing import List
class Circles:
"""
Graph of the rotating complex exponentials.
"""
def __init__(self, ax) -> None:
"""
The initializer.
"""
self._pts_per_circle = 50
self._data ... |
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.admin.views.main import ChangeList
from django.db.models import Count, Sum, F
import datetime
from .admin_views import ReportingView
from django.conf.urls import url
# Register your models here.
from .models import U... |
from __future__ import annotations
from abc import ABC, abstractmethod
import json
import os
import time
import time, sys
from IPython.display import clear_output
from pyspark.sql.types import *
class Connection(ABC):
@abstractmethod
def render_table(self, table: Table):
pass
@abstractmethod
... |
from __future__ import print_function
import torch
import torch.utils.data as data
import torchvision
from torchvision import transforms
import numpy as np
import torch.nn as nn
# from models.vgg import vgg16, vgg19
# from models.resnet import resnet50
from torchvision.models import resnet50, vgg16, densen... |
from rest_framework import permissions,status,views,viewsets
from rest_framework.response import Response
from rest_framework import generics
from django.core.mail import send_mail
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth import get_user_model
User = get_user_model()
from d... |
import cma
import numpy as np
import pandas as pd
from sklearn.preprocessing import StandardScaler
from functools import reduce
from data_model import DataModel, CaseStudyDataModel
import draw
from experimentdatabase import Database
from logger import Logger
import logging
from sampler import bounding_sphere
from clus... |
# -*- coding: utf-8 -*-
"""Runs featurization and computes feature statistics"""
import os
import warnings
import matplotlib.cm as cm
import matplotlib.colors
import matplotlib.pyplot as plt
import numpy as np
from pymatgen import Structure
from scipy import stats
from .predict import RUNNER
THIS_DIR = os.path.dirna... |
import argparse
import os
from collections import defaultdict
from BCBio import GFF
def strandardize(strand):
if str(strand) == '-1':
strand = '-'
elif str(strand) == '1':
strand = '+'
return strand
def gff_to_dict(f_gff, feat_type, idattr, txattr, attributes, input_type):
"""
I... |
from flask import Flask,jsonify,request
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import Column,Integer,Float,String
from flask_mail import Mail, Message
import os
from flask_marshmallow import Marshmallow
from flask_jwt_extended import JWTManager,jwt_required,create_access_token
app = Flask(__name__)
ba... |
import os
import time
import subprocess
import pathlib
import enum
import logging
import shutil
import random
import threading
import json
from http.server import HTTPServer, BaseHTTPRequestHandler
# TODO(breakds): Embed a web service in it.
# Following https://paste.readthedocs.io/en/latest/do-it-yourself-framework.h... |
"""
<NAME>
Python 3
Sudoku creator, solver and validator v2
"""
import numpy as np
class Sudoku:
@classmethod
def __backtracking__ (cls, board, cols, box, places, mode = False):
'''
core program to create/ solve a sudoku by in-place modify
cols and box: dict, record used numbers in col... |
# encoding:utf-8
from __future__ import unicode_literals
import json
import re
import string
from django.contrib.postgres.fields import ArrayField
from django.contrib.sites.shortcuts import get_current_site
from django.db import models
from django.db.models import permalink
from taggit.managers import TaggableManager... |
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
import tensorflow as tf
import attention_rnn
import rnn
import tfutils
class ModelBase(object):
def __init__(self, is_training, config):
self.config = config
self.is_training = is_training... |
"""
Copyright 2017-present, Airbnb 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, sof... |
#!/usr/bin/env python3
import argparse
import fcntl
from flask import Flask, render_template
from flask_socketio import SocketIO
import logging
import os
import pty
import select
import shlex
import struct
import subprocess
import sys
import termios
__all__ = []
__version__ = "1.2.0" # See https://www.python.org/dev... |
# TODO: introduce better object naming system for logging
# e.g. <Sound object at 0x7fa535d23870> -> Sound X
import logging
import time
from numpy import exp
from typing import List
from .braillify import H_STEP, V_STEP
from .common import Vec2
from .events import AnimationEndedEvent, CollisionEvent, Event, Collisio... |
#!/usr/bin/env python
'''
Name : Functions, function.py
Author: <NAME>
Date : Fall 2017
Misc : Holds the highly used and general functions
'''
# import standard modules
from collections import Iterable
import math
# import custom modules
from ..version import *
from . import constants as constant
# checking pytho... |
# -*- coding: utf-8 -*-
import numpy as np
from scipy.optimize import curve_fit
import attr
import matplotlib.pyplot as plt
import matplotlib
import yaml
matplotlib.rc('font', family='DejaVu Sans')
#TODO: use ODR instead of curve_fit to include z-error: http://stackoverflow.com/questions/26058792/correct-fitting-wit... |
#<NAME>
#CSCI 3202 Assignment 5
import sys #For getting command line arguments
import math
#Function to create list of lists that holds a graph
#Takes in name of text file
#Returns list of lists that is 2d graph
def create_graph(text_file):
#List to hold lists for each line of graph input file
graph = []
#Open file... |
from torch.utils.data import Dataset, DataLoader
from utils import *
import torchvision
import torch.nn as nn
from torch import optim
from termcolor import colored
# extra tools for data augmentation, this is not mine...
import utils.custom_transforms as custom
# from Networks.StyleNet import StyleAugmentation
import... |
# -*- coding: utf-8 -*-
from maths.lib import basic
from util import translate
from util.math import mod, mods
from .docs import *
__desc__ = translate("Docs", "Trigonometry")
doc_c("pi", "π", "Perimeter of a circle of diameter 1")
c_pi = 3.14159265358979323846264338327950288419716939937511
doc_c("tau", "τ", "Doubl... |
"""
Module parse to/from Excel
"""
#----------------------------------------------------------------------
# ExcelFile class
import datetime
from itertools import izip
import numpy as np
from pandas.io.parsers import TextParser
from pandas.tseries.period import Period
from pandas import json
def read_excel(path_or_... |
"""
Title: Creating TFRecords
Author: [<NAME>](https://www.linkedin.com/in/dimitre-oliveira-7a1a0113a/)
Date created: 2021/02/27
Last modified: 2021/02/27
Description: Converting data to the TFRecord format.
"""
"""
## Introduction
The TFRecord format is a simple format for storing a sequence of binary records.
Conve... |
import os, argparse, json, time
from utils import rl, dataset
import numpy as np
SORT_BY = ["date", "ts_id"]
def prefill_config(data, config):
if "feature_cols" not in config:
feature_cols = [col for col in data if col.startswith(
config["feature_prefix"])]
config["feature_cols"] = feature_cols
episode = con... |
import cv2
import numpy as np
import time
import torch
# todo
# change quality in a tile
def tile_disturber(images,rows,cols,r):
pass
def get_edge_feature(frame, edge_blur_rad=11, edge_blur_var=0, edge_canny_low=101, edge_canny_high=255):
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
start = time.perf_counter()
... |
#importing required packages
import matplotlib.pyplot as plt
import tensorflow as tf
import numpy as np
from sklearn.metrics import confusion_matrix
import time
from datetime import timedelta
import math
#Defining the hyper parameters of the 2 convolution layers and fully connected layer
# first convolution layer
fil... |
""" Data fusion for OSMsc objects"""
import numpy as np
import pandas as pd
import geopandas as gpd
import osmnx as ox
from .feature import add_gdf_elevation_features
from .grid import Grid
def add_building_height(OSMscBuilding_gdf, externalBuilding_gdf, extColName = None ):
"""
Add building height featur... |
import glob
import random
import os
from functools import reduce
from itertools import chain
from typing import Any, Callable, List, Optional, Tuple
import numpy as np
import pandas as pd
import torch
from PIL import Image
from torchvision.datasets import VisionDataset
from torchvision.io import read_image
class Che... |
#!/usr/bin/env python
# coding: utf-8
'''
PG解决Pong
作业4 PolicyGradient作业、评分标准(需要保留notebook上每个cell运行之后的log信息):
1、完全没有log信息,59分
2、完成部分函数的编写,有部分log信息,但代码运行失败,70分
3、代码运行成功,但Test reward收敛效果不好(所有分数均低于0),80分
4、代码运行成功,分数有上涨趋势,且最后(Episode 2800、2900、3000)输出的3个Test reward的最高分在[0, 10]之间,90分
5、代码运行成功,分数有上涨趋势,且最后(Episode 2800、2900、... |
import os
import argparse
import cv2
import numpy as np
import matplotlib.pyplot as plt
from skimage.morphology import skeletonize
from statistics import median
import pandas as pd
import config
#defining the kernel to perform various operations like opening, closing etc
kernel = np.array([[0, 0, 1, 0, 0],
... |
import os,sys,pickle,multiprocessing,datetime
import numpy as np, pandas as pd
import tarfile,json,rasterio
from pathlib import Path
from radiant_mlhub.client import _download as download_file
from collections import OrderedDict
from tqdm.auto import tqdm
os.environ['MLHUB_API_KEY'] = sys.argv[1] #
OUTPUT_DIR = sys.arg... |
#!/usr/bin/env python3
# Copyright (c) 2018-2022 <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 the rights
# to use, copy,... |
import resource
import socket
import sys
import time
from contextlib import suppress
from multiprocessing.managers import MakeProxyType
import _pytest.fixtures
from multiprocessing import JoinableQueue, Process, Queue
from multiprocessing.managers import SyncManager, RemoteError
from typing import List, Any, Optional,... |
# CS Seminar Quarter Project: A Game of UNO
# Author: <NAME>
# Date: 3/14/2021
import random
# Allows the user to play UNO with the computer -- through the terminal!
class Uno:
user_turn = True
user_cards = []
comp_cards = []
discard_pile = []
turns = 0
current_card = list()
... |
from random import random
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
class InitializationError(Exception):
def __init__(self, message):
self.message = message
class Particle(object):
def __init__(self, x, y, z, vx=0, vy=0, vz=0, ax=0, ay=0, az=0):
self.x = [x, y, ... |
"""
This router handles the dashboard endpoints.
"""
import os
import statistics
from asyncio import gather
from typing import Any, AsyncGenerator, Dict, List, Mapping, Sequence
from itertools import combinations, groupby
import aiofiles
from aiocache import caches
from databases import Database
from fastapi import AP... |
# -*- coding: utf-8 -*-
"""Data structures.
.. seealso:: https://pydantic-docs.helpmanual.io/usage/dataclasses/#convert-stdlib-dataclasses-into-pydantic-dataclasses
"""
import json
import pathlib
from functools import lru_cache
from typing import Any, Dict, List, Mapping, Optional, Sequence
import pydantic.schema
i... |
# -*- coding: utf-8 -*-
"""
Reliably benchmarking npstreams performance.
"""
import inspect
import sys
import timeit
from collections import namedtuple
from contextlib import redirect_stdout
from functools import partial
from shutil import get_terminal_size
import numpy as np
from . import __version__
from .reduce i... |
import psycopg2
import math
import json
import datetime
import os
from random import randrange, shuffle
from collections import defaultdict
from os import path
uniq_p_feat = ["gender", "age", "white", "asian", "hispanic", "black", "multi", "portuguese",
"american", "mideast", "hawaiian", "other"]
seq_p... |
# Copyright (c) 2018 <NAME>
# See LICENSE for copyright/license details.
"""
Point distributions on the ellipsoid.
"""
import numpy as np
import abc
import l3py.utilities
class Grid(metaclass=abc.ABCMeta):
"""
Base interface for point collections.
Subclasses must implement a deep copy, getter for radiu... |
#!/usr/bin/env python3
from shutil import copyfile
import os
import json
# 'headers_dir' option in SConstruct must be correct: 'godot-cpp/godot-headers'
# 'binding_generator' should be commented out or replaced by 'pass'
# in GDNative this method must be placed instead of Help generation line
def setup_options(env, ... |
import os
import sys
from random import choice, randint
from shutil import get_terminal_size
from time import sleep
import numpy
from numpy import zeros
term_width, term_height = get_terminal_size()
class Rule(object):
def __init__(self, shape, generations, sleep_time, **kwargs):
self.shape = shape # ... |
# -*- coding: utf-8 -*-
import numpy as np
from sklearn.neighbors import NearestNeighbors
from sklearn.utils import shuffle
import os
import sys
sys.path.append(os.path.dirname(os.path.realpath(__file__))) # models subdir
from utils import rem_dupl # NOQA
from metrics import acck, mapk # NOQA
def evaluate_1_vs_... |
import sys
import os
import re
import time
import csv
import json
import math
from pathlib import Path
from enum import Enum, IntEnum
from typing import List, Iterator
import random
import logging
import argparse
from abc import ABC, abstractmethod
from .models import (
VTraceTx,
STraceTx,
SliceType,
... |
"""
for f in sorted(glob('*.py')):
# print(f'nohup python -u {f} 0 > LOG/log_{f}.txt &')
print(f'python -u {f} > LOG/log_{f}.txt')
"""
import warnings
warnings.filterwarnings("ignore")
import pandas as pd
import numpy as np
from glob import glob
import os
from socket import gethostname
HOSTNAME = gethostname... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.