text stringlengths 3.07k 12.6k |
|---|
from __future__ import print_function
from __future__ import division
import time
import numpy as np
from scipy.ndimage.filters import gaussian_filter1d
import config
import microphone
import dsp
from midi import MidiConnector
from midi import NoteOn
from midi import Message
"""Needed variables for calculations"""
co... |
#!/usr/bin/python
# Some simple placement algorithms for MininetCluster
from mininet.util import quietRun, errRun
from mininet.log import setLogLevel, debug, info, error
import networkx
import os
from random import randrange
class Placer( object ):
"Node placement algorithm for MininetCluster"
def __init__... |
import numpy as np
import torch
from torch.autograd import Variable
from torch.autograd import grad
# Auxiliar function to standarize dataset
def stand(x, mean, std):
x = x - mean
x = x/std
return(x)
# Root Mean Squared Error
def rmse(y, pred):
return torch.sqrt( torch.mean( (pred - y )**2 ) )
## Lin... |
import numpy as np
from cvxpy import *
from cvxopt import matrix, solvers
from mosek import iparam
solvers.options['mosek'] = {iparam.log: 0}
import time
class SolverFailedException(Exception):
def __init__(self, message):
self.message = message
class CuttingPlaneModel:
def __init__(self, dim, bound... |
# <NAME> 180401104
# nxn matris hespalama
def nnMatris(matrisHesapla):
list = matrisHesapla.copy()
satir = len(matrisHesapla)
sutun = len(matrisHesapla[0])
#Sol üçgensel matris
for k in range(satir-1):
for i in range(satir-1-k): ... |
# -*- coding: UTF-8 -*-
"""
Copyright 2021 Tianshu AI Platform. 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 req... |
import numpy as np
import os
import torch
import pickle
import pytorch_lightning as pl
import torchvision.transforms as T
from torch.utils.data import DataLoader, Dataset
import data.ade20k.utils_ade20k as utils
from typing import Optional
from PIL import Image
from PIL.Image import NEAREST
class Ade20kDataModule(... |
import dash
from dash.dependencies import Input, Output, State
import dash_core_components as dcc
import dash_html_components as html
import dash_table_experiments as dt
import json
import pandas as pd
import numpy as np
import colorlover as cl
import plotly
import os
import pdb
import itertools
app = dash.Dash()
app... |
#Energy functions
import numba
import numpy as np
def pH_to_mu(a,pH,pK = 7):
mu_ha = a + np.log(1/(1+ 10**(pH - pK))) #Low pH more negative (HA) This is accounting for the werid sign and species flipping in the latter code
mu_a = a + np.log((10**(pH-pK))/(1+ 10**(pH - pK))) #High pH more negative (A-)
retu... |
__licence__ = 'MIT'
__author__ = 'lyriccoder'
__credits__ = ['lyriccoder, kuyaki']
__maintainer__ = 'lyriccoder'
__date__ = '2021/05/20'
from itertools import combinations_with_replacement
from typing import Iterator, List, Tuple
from program_slicing.decomposition.program_slice import ProgramSlice
from program_slicin... |
import os
import shutil
import pytest
import numpy as np
import tensorflow as tf
import torch
from torch_mimicry.metrics import compute_fid
from torch_mimicry.metrics.inception_model import inception_utils
from torch_mimicry.nets.gan import gan
class ExampleGen(gan.BaseGenerator):
def __init__(self,
... |
"""
Copyright (C) 2022 <NAME>
This work is released under the MIT License.
See the file LICENSE for details
Simple script to get the position and orientation of camera written to the terminal.
This script was used to create the default scenarios.
"""
import carla
from carla import VehicleLightS... |
# 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... |
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score, confusion_matrix
from datasets import load_dataset
from sklearn.svm import LinearSVC
import numpy as np
import pan... |
#!/usr/bin/env python2.7
# -*- coding:UTF-8 -*-2
u"""window.py
Copyright (c) 2019 <NAME>
This software is released under BSD license.
セルウィンドウモジュール。
"""
import pygame as _pygame
import utils.const as _const
import sprites as __sprites
class __Cell(__sprites.Window):
u"""セルウィンドウ。
"""
@property
def pie... |
from multidop_time import do_multidop_for_time
from ipyparallel import Client
import time_procedures
from time import sleep
import time
from datetime import datetime
import numpy as np
from netCDF4 import Dataset
from datetime import datetime
import sys
import os
import math
from copy import deepcopy
from scipy import ... |
import re
import string
import os
from gensim.parsing.preprocessing import remove_stopwords
# import custom process display
from util import show_progress
#######################################################
#################### PATH PARSING #####################
################################################... |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import os
import xlsxwriter
from io import BytesIO
SMALL_SIZE = 7
plt.rc('font',size = SMALL_SIZE)
plt.rc('axes',titlesize = SMALL_SIZE)
def data_import(path):
data =pd.read_csv(path)
return data
def data_prep(df):
... |
"""Quick utils for files and plotting used by the adjacent notebooks."""
import logging
import zipfile
from pathlib import Path
import matplotlib.pyplot as plt
import pretty_midi
import requests
from matplotlib.collections import PatchCollection
from matplotlib.patches import Patch, Rectangle
from matplotlib.ticker im... |
import numpy as np
import torch
from pytorch3d.transforms import so3_relative_angle, so3_rotation_angle
from torch.nn import functional as F
from .transformations import transform_points_Rt
def evaluate_pose_Rt(pr, gt, scaled=False):
assert pr.shape[1] == 3 and pr.shape[2] == 4, "pose should be Rt (3x4)"
ass... |
class Morph(object):
def __init__(self, surface, base, pos, pos1):
self.surface = surface
self.base = base
self.pos = pos
self.pos1 = pos1
class Chunk(object):
def __init__(self, idx=-1, morphs=[], dst=-1, srcs=[]):
self.idx = idx
self.morphs = morphs
se... |
import contextlib
import copy
import itertools
import math
class Config(object):
def __init__(self):
self.cjk_opening = {
0x3008, 0x300A, 0x300C, 0x300E, 0x3010, 0x3014, 0x3016, 0x3018,
0x301A, 0x301D, 0xFF08, 0xFF3B, 0xFF5B, 0xFF5F
}
self.cjk_closing = {
... |
import re
from datetime import datetime
import codecs
try:
# for Python2
from Tkinter import *
import tkMessageBox
except ImportError:
# for Python3
from tkinter import *
from tkinter import messagebox as tkMessageBox
class EvernoteFile():
notes = []
def add_book_quote(self, title, author,... |
import warnings
import torch
from meshreg.datasets.queries import TransQueries, BaseQueries
def recover_back(joints_trans, affinetrans):
"""
Given 2d point coordinates and an affine transform, recovers original pixel points
(locations before translation, rotation, crop, scaling... are applied during dat... |
from dmmath.utils import Problem, RunStatus, StackStatus, ExecStatus
from dmmath.math_env.ops import Actions
from typing import Iterable
import numpy as np
import timeout_decorator
import re
from sympy.core import numbers
from dmmath.math_env.defined_ops import expr2func, eq_transform, assign, myexpand
from sympy.parsi... |
import attr
import torch
import os
import tempfile
import subprocess
from tensor2struct.utils import registry, dataset
@attr.s
class Stat:
sketch_cor_num = attr.ib(default=0)
lf_cor_num = attr.ib(default=0)
denotation_cor_num = attr.ib(default=0)
num_examples = attr.ib(default=0)
def __str__(sel... |
from json import load as json_load
from requests import get as requests_get
from random import choice, randint
from django.conf import settings
from django.utils.timezone import get_current_timezone
from faker import Faker
from apps.blog.models import CategoryTypes
CURRENT_TZ = get_current_timezone()
FAKE = Faker(... |
'''
PyNumeral
Author: <NAME>
Version : 1.0.0
License: MIT
'''
import math
def format(num, form):
if form == "0.0":
print(float(num))
elif form == "||":
print(abs(num))
elif form == "0.!0":
print(int(num))
elif form == "0,0t":
build = ",000"
print... |
import typing
import collections
import torch
from torch import nn
from atari_wrappers import wrap_deepmind, wrap_pytorch, make_atari
import random
import ray
from core.model import AtariNet
Buffers = typing.Dict[str, typing.List[torch.Tensor]]
Trajectory = collections.namedtuple(
'Trajectory',
[
'fram... |
import copy
import numpy as np
import time
import torch
import torch.nn as nn
import torch.nn.functional as F
class Actor(nn.Module):
def __init__(self, state_dim, action_dim, max_action, hidden_sizes=[400, 300]):
super(Actor, self).__init__()
self.l1 = nn.Linear(state_dim, hidden_sizes[0])
self.l2 = nn.Line... |
#!/usr/bin/env python
from plynx.constants import NodeRunningStatus
import plynx.db.node
import plynx.utils.file_handler as file_handler
import plynx.plugins.executors.local as local
import plynx.plugins.executors.dag as dag
import plynx.plugins.resources.common as common
SEQ_OUTPUT = 'seq_o'
GREP_INPUT = 'grep_i'
GR... |
"""
R/W *.polycos files.
The polynomial ephemerides file written by the TEMPO program has
the following format:
Line Columns Item
---- ------- -----------------------------------
1 1-10 Pulsar Name
11-19 Date (dd-mmm-yy)
20-31 UTC (hhmmss.ss)
32-51 TMID (MJD)
52-... |
# Copyright 2013 <NAME>
#
# 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
... |
import argparse
parser = argparse.ArgumentParser(formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument('--depsPath')
parser.add_argument('--esHost')
parser.add_argument('--esPort')
parser.add_argument('--modelPath')
args = parser.parse_args()
DEPS_PATH = args.depsPath
ES_HOST = args.esHost
ES_PORT ... |
# SPDX-License-Identifier: MIT
# Copyright (C) 2021 <NAME>
#
# Project: Buildnis
# File: execute.py
# Date: 21.Feb.2021
###############################################################################
from __future__ import annotations
import re
import subprocess # nosec
from typing import List, NamedTuple
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jun 9 15:44:58 2021
@author: <NAME> <<EMAIL>>
"""
import unittest
import pathlib
import datetime
from click.testing import CliRunner
from src.data.import_affymetrix import main as import_affymetrix
from src.features.smarterdb import VariantSheep, Su... |
from ophyd import (PVPositioner, Component as Cpt, EpicsSignal, EpicsSignalRO,
Signal, EpicsMotor)
from ophyd.utils import ReadOnlyError
import time as ttime
class UVDoneMOVN(Signal):
# borrowed from srx's startup config
"""Signal for use as done signal for use in individual mode undulator
... |
import argparse
import io
import os
import subprocess
import ray
import tensorflow.compat.v1 as tf
from PIL import Image
from psutil import cpu_count
from waymo_open_dataset import dataset_pb2 as open_dataset
from utils import get_module_logger, parse_frame, int64_feature, int64_list_feature, \
bytes_list_feature... |
from pathlib import Path
from typing import Iterable
import tensorflow as tf
import numpy as np
import setags.data.input as di
import setags.data.utils as du
from setags.model import model_fn, DEFAULT_PARAMS
EPOCHS_BEFORE_EVAL = 5
class Estimator:
def __init__(self, model_dir: Path, data_dir: Path, param_over... |
# Copyright (c) 2006-2013 Regents of the University of Minnesota.
# For licensing terms, see the file LICENSE.
import conf
import g
import os
import sys
from gwis.exception.gwis_error import GWIS_Error
from item import item_base
from item import nonwiki_item
#from item.jobsq import job_base
from item.jobsq import wo... |
from datetime import datetime, timezone
import errno
from urllib.parse import urljoin, quote
from sorl.thumbnail_standalone.abc.storage import Storage
import os, io
from sorl.thumbnail_standalone.conf import settings
import filelock
class cached_property(object):
def __init__(self, func):
self.func = func... |
#%%
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from scipy.optimize import fsolve
import phd.viz
colors, palette = phd.viz.phd_style()
# Define functions to be used in figure
def pact(IPTG, K_A, K_I, e_AI):
'''
Computes the probability that a repressor is active
Parameters
... |
import numpy as np
from qtpy import QtWidgets, QtCore, QtGui
import flika
from flika import global_vars as g
from flika.window import Window
from flika.utils.io import tifffile
from flika.process.file_ import get_permutation_tuple
from flika.utils.misc import open_file_gui
import pyqtgraph as pg
import time
import os
f... |
from collections import namedtuple
import tensorflow as tf
def get_cityscapes():
Label = namedtuple('Label', ['name', 'id', 'trainId', 'category', 'categoryId', 'hasInstances', 'ignoreInEval', 'color'])
labels = [
# name id trainId category catId hasInstances ... |
# -*- coding:utf-8 -*-
from django.utils.translation import ugettext_lazy as _
from django.db import models
from mezzanine.core.fields import RichTextField, FileField
from mezzanine.core.managers import SearchableManager
from mezzanine.core.models import Displayable, RichText, Slugged
from mezzanine.pages.models impor... |
#!/Library/Frameworks/Python.framework/Versions/3.6/bin/python3
from toolbox.AirWatchAPI import AirWatchAPI as airwatch
import argparse
import sys
""" CONSTANTS """
SUPERVISED_TAG = 'Supervised'
""" Accepted Arguments """
parser = argparse.ArgumentParser(description='Add tag to specified devices',
epilog="--s... |
import os
import sys
import warnings
import datetime
import numpy as np
from skimage import measure
np.set_printoptions(threshold=sys.maxsize)
class PostprocessUtils:
@staticmethod
def apply_postprocessing(mat_in, cfg=None):
_pp_method = cfg.get('post_process', None)
mat_out = eval('Postproc... |
from rest_framework import generics, permissions, status
from rest_framework.response import Response
from .models import Game, Team, Contingent
from .serializers import (
GameSerializer,
TeamSerializer,
TeamUpdateSerializer,
ContingentSerializer,
)
from drf_yasg.utils import swagger_auto_schema
from sc... |
"""
This module specifies the admin mode model for SKA LMC Tango devices. It
consists of a single public class: :py:class:`.AdminModeModel`. This
uses a state machine to device device adminMode, represented as a
:py:class:`ska_tango_base.control_model.AdminMode` enum value, and
reported by Tango devices through the ``A... |
# coding: utf-8
import datetime
import re
import requests
from typing import List
from decimal import Decimal
REST_URL = 'https://integrationapi.net/rest'
SESSION_URL = '/user/sessionId'
BALANCE_URL = '/user/balance'
SEND_ONE_URL = '/sms/send'
SEND_BULK_URL = '/sms/sendBulk'
STATE_URL = '/sms/state'
METHOD_GET = 'get... |
import numpy as np
import math
from typing import Dict
from scipy.linalg import block_diag
def wigner_d(j, beta) -> np.ndarray:
dim = int(2 * j + 1)
mat = np.zeros((dim, dim))
m_prime_list = np.linspace(-j, j, dim)
m_list = np.linspace(-j, j, dim)
for row, m_prime in enumerate(m_prime_list):
... |
import json
import requests
from base import ServiceError
OSRM_DRIVING_URL = 'https://router.project-osrm.org/route/v1/driving/{src[long]},{src[lat]};{dest[long]},{dest[lat]}'
def split(durations, distances, coordinates, interval=1):
len_durations = len(durations)
len_distances = len(distances)
assert ... |
# Copyright (c) MONAI Consortium
# 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... |
#!/usr/bin/env python
import gzip
import pandas as pd
from fact.io import write_data, read_data
import h5py
import click
import logging
import numpy as np
import os
from tqdm import tqdm
from gridmap import Job, process_jobs
from ..utils import *
from ..io import readJsonLtoDf
from ..features import *
log = logging... |
#!/usr/bin/env python
__doc__ = '''Make changes needed to a UFO following processing by FontLab 7.
Various items are reset using the backup of the original font that Fontlab creates
'''
__url__ = 'http://github.com/silnrsi/pysilfont'
__copyright__ = 'Copyright (c) 2021 SIL International (http://www.sil.org)'
__license_... |
from .util import get_cached
__all__ = ("continents", "map_names", "maps", "map_floor")
def continents():
"""This resource returns static information about the continents used with
the map_floor resource.
The response is a dictionary where the key is the continent id, and the
value is a dictionary ... |
import torch
import numpy as np
from torch import nn
from torch.autograd import grad
from torch.nn.modules.utils import _pair
def weights_init_normal(m):
classname = m.__class__.__name__
if classname.find("Conv") != -1:
torch.nn.init.normal_(m.weight.data, 0.0, 0.02)
elif classname.find("BatchNorm2... |
"""
Aqara Client
A client implementation to receive Aqara events and send control messages.
Feature includes:
- Discover gateways
- Discover devices of a gateway
- Subscribe to updates for devices
- Read values from a device (async)
- Send control command to a device (async)
- Heartbeat
"""
import asyncio
import jso... |
#! /home/rance/anaconda3/bin/python
# this script is intended to be run once a day, you could automate it with a software like cron
import os
from ftplib import FTP
import psycopg2
from psycopg2 import sql
from datetime import date, timedelta
# replaces North and South for + and minus to make it easy to calculate di... |
import wx, os, platform, shutil
from PIL import Image
import wx.lib.scrolledpanel as scrolled
import sys
from packages.lang.Localizer import *
BASE_PATH = ""
################################################################################
# SCROLLABLE SELECTABLE IMAGE VIEW ############################################... |
# manually build and launch your instances
# remember that the ip field deals with a private ip
def _get_parameter(node_id, private_ip, min_key, max_key):
p = {"id": node_id, "ip": private_ip, "min_key": min_key, "max_key": max_key}
return p
def create_instances_parameters():
"""
first = _get_param... |
#!/usr/bin/python3
#
# CrapLab SmartPlug simple backend server
#
# Copyright (c) 2017 <NAME> <<EMAIL>>
#
# 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 witho... |
#! /usr/bin/env python
from __future__ import print_function, division
import numpy as np
import pickle
from read_input import read_input
def main(filename, x=None, y=None, z=None, sep=0.01):
import pyscf
from matplotlib import pyplot as plt
import os
from matplotlib.colors import LogNorm
import ... |
from kivy.config import Config
from kivy.lang import Builder
from kivy.properties import *
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button
from kivy.uix.label import Label
from kivy.uix.popup import Popup
from kivy.uix.slider import Slider
from kivy.uix.widget import Widget
Builder.load_fil... |
import copy
import threading
import queue
class SingleTaskListener():
def __init__(self):
self.ev = threading.Event()
def wait(self):
self.ev.wait()
def notify(self, _id, _data):
self.ev.set()
class MultipleTaskListener():
def __init__(self, count):
self.count = 0
self.expected = co... |
#encoding:utf-8
import random
import numpy as np
import glob
import matplotlib as mpl
mpl.use('Agg')# AGG(Anti-Grain Geometry engine)
import matplotlib.pyplot as plt
import torch
import torch.nn as nn
import torch.optim as optim
import torch.utils.data as data
import torchvision
from torchvision import models,transfo... |
# coding=utf-8
try:
from PyInquirer import print_json, prompt
except ImportError:
print('PyInquirer is needed for this script, please install it using pip install pyinquirer...')
raise
try:
from pyfiglet import Figlet
except ImportError:
print('PyFiglet is needed for this script, please install it... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
import torch
import numpy as np
import math
try:
from .chamfer_distance import ChamferDistance
except (ModuleNotFoundError, ImportError) as err:
from chamfer_distance import ChamferDistance
# Part of the code is referred fro... |
import requests
from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.http import StreamingHttpResponse, JsonResponse
from django.shortcuts import render, get_object_or_404
from django.utils import timezone
from django.views.decorators.http import condition
from minos.m... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from itertools import chain
from django import forms
from django.core.validators import RegexValidator
from myforms import MyCheckboxSelectMultiple, MyRadioFieldRenderer
from app.models import *
class UserCreteForm(forms.ModelForm):
mobile_phone_regex = '^1\d{10}$|^... |
from dolfin import FunctionSpace, Function, dof_to_vertex_map, interpolate
from dolfin import Mesh, MeshEditor, cells
from itertools import izip, count
import networkx as nx
import numpy as np
def assertions_hold(mesh):
'''Line mesh in R^d, d > 1'''
return mesh.topology().dim() == 1 and mesh.geometry().dim() ... |
import os
import argparse
import logging
from matplotlib import pyplot as plt
import pandas as pd
import seaborn as sns
logging.basicConfig(level=logging.INFO)
def iterate_through_directory(directory, file_ending):
"""
go through the specified the specified directory, and look for all the files
with a specific ... |
def set_question_node(ungrounded_nodes):
'''recogniatize question node'''
#1. overlap
is_has = False
for ungrounded_node in ungrounded_nodes:
if ungrounded_node.node_type == 'class' and is_question_node_by_words(ungrounded_node.friendly_name):
ungrounded_node.question_node = 1
... |
# pylint: disable=missing-docstring, not-an-iterable, invalid-name
import numpy as np
from numba import njit, prange # type: ignore
from simulation.constants import G
from .typing import DoubleArray
@njit()
def norm(vector: DoubleArray) -> float:
return np.sqrt(
vector[0] * vector[0] + vector[1] * ve... |
#!/usr/bin/python3
import json
import socket
import urllib.request
import urllib.error
import urllib.parse
import requests
import config
global _ogninfo_ # the OGN info data
_ogninfo_ = {} # the OGN info data
NOinfo = {"return": "NOinfo"}
########################... |
from argparse import Namespace
from dataclasses import dataclass
from enum import Enum
import logging
from typing import ClassVar, Optional
import numpy as np
from sklearn.metrics import confusion_matrix, average_precision_score, f1_score
from fastai.metrics import auc_roc_score
import torch
from torch import Tensor
... |
# -*- coding: utf-8 -*-
#
# Copyright (c) 2016 <NAME>, Synapticon GmbH
# Copyright (c) 2019 Open Source Robotics Foundation, Inc.
#
#
# 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 ... |
from dronekit import connect, VehicleMode, LocationGlobal, LocationGlobalRelative
from pymavlink import mavutil # Needed for command message definitions
from openmv_pi_threading import openMV
from dt_controller import dt_controller
import time
import math
import serial
import threading
# Connect to the Vehicle
print(... |
#!/usr/bin/env python
# based on https://github.com/mikecunha/pygeo_heatmap/blob/master/geo_heatmap.ipynb
import os, glob
import pandas as pd
import datetime, time
import folium
from folium.plugins import HeatMap
from folium.features import MacroElement, Template
from selenium import webdriver
debug = False
SCALING_... |
#******************************************************************************
#
# MantaGen
# Copyright 2018 <NAME>, <NAME>, <NAME>
#
# This program is free software, distributed under the terms of the
# Apache License, Version 2.0
# http://www.apache.org/licenses/LICENSE-2.0
#
#**************************************... |
# Basic imports
import numpy as np
import pandas as pd
# Data Formatting
import xarray as xr
import netCDF4 as nc4
from pathlib import Path
#Plotting
import holoviews as hv
from holoviews import opts
hv.extension('bokeh')
import matplotlib
from matplotlib import pyplot as plt
import matplotlib.gridspec as gridspec
im... |
import warnings
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
from umap import UMAP
from graspologic.embed import select_dimension
from .utils import legend_upper_right, soft_axis_off
def simple_scatterplot(
X,
labels=None,
palette="deep",
ax=None,
... |
#!/usr/bin/python3
from os import path, getuid
from typing import List
from getpass import getpass
from inspect import getfullargspec
import sys
import subprocess
def getDirectory():
return path.dirname(__file__)
dbPath: str
auth = getuid() == 0
class OptionHandler:
options: str
action: any
descript... |
import dash
import dash_bootstrap_components as dbc
import dash_html_components as html
from dash.dependencies import Input, Output
import dash_html_components as html
import dash_core_components as dcc
import dash_daq as daq
import MySQLdb
import plotly.express as px
import plotly.graph_objs as go
from plotly.subp... |
import numpy as np
from .boundingbox import truncate_bbox, round_bbox
def tracking_by_optflow(curr_bbox, flow):
curr_bbox = truncate_bbox(curr_bbox, flow.shape[0], flow.shape[1])
rcb = round_bbox(curr_bbox)
cmin = np.median(flow[rcb[1]: rcb[1] + rcb[3] + 1, rcb[0], 0]) \
+ curr_bbox[0]
cmax = np.median... |
import numpy as np
def one_step_lookahead(environment, state, V, discount_factor):
"""
Helper function to calculate the value function.
PARAMETERS
----------
environment: Initialized OpenAI environment object.
state: Agent's state to consider.
V: The value to use as an estimator. Vector of length nS.
disco... |
# # WAP Input a welcome message and display it
from math import gcd, lcm
inp = input("Enter Welcome message: ")
print(inp)
# # Input two numbers and display the largest/smallest number.
num1 = int(input("Enter number1: "))
num2 = int(input("Enter number2: "))
print(max(num2, num1))
print(min(num2, num1))
# # Input t... |
import requests
import json
import codecs
import random
#GoogleAPI
#PlacesAPI
# タイプ,レートでスポットを絞る
# 朝,昼,晩に合わせて移動可能距離を考える
# 朝:8:00~11:00
# 昼:11:00~15:00
# 夕:15:00~18:00
# 晩:18:00~22:00
# APIキーの指定 むき出し...
apikey = "<KEY>"
# 近隣
# api = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location={latitude},{l... |
import os
from util.utils import ensure_dirs
import argparse
import json
import shutil
def get_config(phase):
config = Config(phase)
return config
class Config(object):
"""Base class of Config, provide necessary hyperparameters.
"""
def __init__(self, phase):
self.is_train = phase == "t... |
import random
import numpy as np
import torch
import torchvision
from PIL import Image
import matplotlib.pyplot as plt
##############################################################################
# Plotting Helper Function
##############################################################################
def get_image... |
# Copyright (c) 2013, veena and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe import _
from datetime import datetime as dt
def execute(filters=None):
data= []
work_h = []
late_e = []
early_e = []
present = []
absent = []
column... |
#%%
from torch.utils.data import DataLoader
from l5kit.configs import load_config_data
from l5kit.data import LocalDataManager, ChunkedDataset
from l5kit.dataset import AgentDataset, EgoDataset
from l5kit.rasterization import build_rasterizer
from l5kit.configs import load_config_data
from l5kit.data.labels import PE... |
import bpy
import bpy.utils.previews
import os
import plugin
import reference_asset
import scene_setup
from wizard.vars import defaults
bl_info = {
"name": "Wizard",
"author": "<NAME>",
"version": (1, 0),
"blender": (2, 90, 0),
"location": "View3D > Wizard",
"description": "Provide Wizard's too... |
"""
BotManagement
---
Commands that give information about a discord.py bot.
For more details, see below.
"""
import discord
import utils.utils as util
from config import REPO_LINK
from discord.enums import ActivityType
from discord.ext import commands
from discord.ext.commands import Cog
class BotManagement(Cog):
... |
# importing required dependencies
import re
import unicodedata
import nltk
from nltk.stem.lancaster import LancasterStemmer
from nltk.corpus import stopwords
from nltk.stem import wordnet
from sklearn.feature_extraction.text import TfidfVectorizer
from nltk import pos_tag
from sklearn.metrics import pairw... |
# Copyright 2016-2017 Workonline Communications (Pty) Ltd. All rights reserved.
#
# The contents of this file are 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/license... |
import warnings
import django
from django.db import models
from django.core.exceptions import ImproperlyConfigured
from mptt.models import MPTTModel
from mptt.managers import TreeManager
from mptt.fields import TreeForeignKey
from armstrong.utils.backends import GenericBackend
from .utils import get_section_many_to_ma... |
"""Meta-targets
Module to compute meta-targets, i.e., feature importance regarding to different base models
and feature importance-measures.
"""
from abc import ABCMeta, abstractmethod
from typing import Any, Callable, Collection, Dict
import warnings
import lime.lime_tabular
import numpy as np
import pandas as pd
i... |
import pdb
import pprint
from colorama import init, Fore, Back, Style
init()
import re
import csv
import json
import sql
import os
from os import walk
import logging
import datetime
import sqlalchemy
from sqlalchemy import inspect, create_engine
from sqlalchemy import exc
from sqlalchemy.ext.automap import automap_base... |
from sqlalchemy.schema import CreateColumn
from .models import DColumn, DTable
class TableExistException(Exception):
pass
class Registry(object):
""" storage for dynamically created classes """
def __init__(self, base, session):
self._base = base
self.session = session
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.