text stringlengths 3.07k 22.1k |
|---|
import autograd.numpy as np
import scipy.optimize
from quad import Control, State
class PD:
def __init__(self, P, D):
self.P = P
self.D = D
self.K = np.array((P, D))
def output(self, value, derivative, desired_value, desired_derivative):
return -self.P * (value - desired_value) - self.D * (deriva... |
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... |
from werkzeug.utils import cached_property
from app import format_notification_type
class TemplateList():
"""
Represents a list of all templates and folders for a service,
with optional filtering by "template_type", and by an ancestor
template_folder_id i.e. only return templates and folders that
... |
import seer_plugin
import seer_config
import cv2
import imutils
import imutils.video
import numpy
import os.path
import matplotlib.pyplot as plt
import numpy as np
import utils
import sys
import random
class PeopleCount(seer_plugin.DataCollectorPlugin):
"""
Data collector plugin that gathers video feed
... |
from functools import singledispatch
from hashlib import sha224
from typing import NamedTuple, Type
from pyrsistent import pmap
from pyrsistent.typing import PMap
from ksc.path import subexps_no_binds
from ksc.expr import Expr, Var, Let, Lam, Call, If, Assert, Const
from ksc.filter_term import get_filter_term
def a... |
from threading import Thread, Event
from time import time
from client.communication.messages import (
SensorDataKey,
MessageCommand,
build_command_message_with_args,
ProfilingDataKey
)
from client.interconnect.commlink import CommLink
from client.interconnect.network import NetworkLink
class OnBoard:... |
# pylint: disable=C0116
from typing import Callable, cast, List, Mapping, Union
from asts import base, typed, types_ as types
from errors import merge, UnexpectedEOFError, UnexpectedTokenError
from lex import TokenStream, TokenTypes
PrefixParser = Callable[[TokenStream], base.ASTNode]
InfixParser = Callable[[TokenStr... |
"""
Convenient access to spreadsheet-style game data files. CSV is the only
included implementation, but writing new readers is trivial.
Here's a simple example::
def f_char(val):
"Ensure *val* is a one-character string"
if isinstance(val, str) and len(val) == 1:
return val
else:
raise Value... |
"""
MIT License
Copyright (c) 2021, <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, modify, merge, publish, distr... |
# Copyright 2020 <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, softw... |
#!/usr/bin/env python
# coding=utf-8
from __future__ import division, print_function, unicode_literals
import datetime
import hashlib
import os
import tempfile
from copy import copy
import pytest
import json
from sacred.observers.file_storage import FileStorageObserver
from sacred.serializer import restore
T1 = datet... |
import json
# Exempting Bandit security issue (using subprocess)
# see notes in `MetadataRecord.validate` method.
import subprocess # nosec
from typing import Optional
from pathlib import Path
from tempfile import TemporaryDirectory
from zipfile import ZipFile
from copy import deepcopy
from importlib_resources impo... |
from __future__ import unicode_literals
from __future__ import absolute_import
# QGIS modules
from qgis.core import *
from qgis.PyQt.QtCore import Qt
from qgis.PyQt.QtWidgets import *
from qgis.PyQt import uic
# promaides modules
from .interpolate import RasterInterpolator
from .environment import get_ui_p... |
# -*- coding: utf-8 -*-
"""
Script for running nulls on simulations SERIALLY (n.b., parallelization may be
done at the level of each null method, but simulations are run individually)
"""
from argparse import ArgumentParser
import functools
from pathlib import Path
import time
from joblib import dump, load
import num... |
# Copyright (c) 2020 Huawei Technologies Co., Ltd
# Copyright (c) 2019, Facebook CORPORATION.
# All rights reserved.
#
# Licensed under the BSD 3-Clause License (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://opensource.org/lice... |
# /
# Functions to deploy replica sets to Ops Manager via the API
#
# functions:
# get: HTTPS GET method against the Ops Manager REST API
# put: HTTPS PUT method against the Ops Manager REST API
# add_missing_aa: create the automation agent version section if missing
# createProcessMember: functio... |
from __future__ import generators
import os, md5, sys
#import common.debug
class FileCache:
MAX_FILES = 8
def __init__(self):
self.cache = {}
self.time = 0
def access(self, filename, position, writing=0):
if filename in self.cache:
time, mode, f = self.cache[f... |
from kervi.hal import I2CSensorDeviceDriver
VL6180X_DEFAULT_I2C_ADDR = 0x29
VL6180X_REG_IDENTIFICATION_MODEL_ID = 0x000
VL6180X_REG_SYSTEM_INTERRUPT_CONFIG = 0x014
VL6180X_REG_SYSTEM_INTERRUPT_CLEAR = 0x015
VL6180X_REG_SYSTEM_FRESH_OUT_OF_RESET = 0x016
VL6180X_REG_SYSRANGE_START = 0x018
VL6180X_REG_SYSALS_START = 0x0... |
from typing import List, Dict, Set, Optional
from abc import ABC, abstractmethod
from spec_const import SPEC_PAGE_SIZE, SPEC_BYTESET, SPEC_RAND_SIZE_MAX
from spec_random import SPEC_RANDOM
from spec_basis import Rand, Kobj, KindSend, KindRecv, Lego, Syscall, Program, \
Executable
from util_bean import Bean
clas... |
"""
input: an image, the incomplete depth map of the image
output: predicted normal map
"""
import argparse
import datetime
import glob
import os
import cv2 as cv
import numpy as np
import torch
import config
from help_funs import mu
from workspace.svd import eval as svd
############ EVALUATION FUNCTION ###########... |
import numpy as np
import kdezero.layers as L
import kdezero.functions as F
from kdezero import utils
from kdezero import cuda
from kdezero import optimizers
from kdezero import no_grad
from kdezero import History
from kdezero.logger import CalculateHistory
class Model(L.Layer):
"""Model class
"""
def __i... |
import matplotlib
import matplotlib.pyplot as plt
from PyQt5.QtWidgets import (QDialog, QLineEdit, QApplication, QGridLayout,
QPushButton, QLabel)
from matplotlib.widgets import Button
import sys
class MultiInputDialog(QDialog):
def __init__(self, labels, vals, format_dict, parent=Non... |
def Nafion_waxs_S_edge(t=1):
dets = [pil1M]
energies = 7 + np.asarray(np.arange(2445, 2470, 5).tolist() + np.arange(2470, 2480, 0.25).tolist() + np.arange(2480, 2490, 1).tolist()+ np.arange(2490, 2501, 5).tolist())
waxs_arc = np.linspace(52, 52, 1)
names = ['70nPA', '50nPA', '30nPA', '10nPA']
x =... |
"""
Set of sample commands illustrating behaviors of runez
"""
import logging
import os
import sys
import time
import runez
from runez.ascii import AsciiAnimation
from runez.inspector import ImportTime
from runez.render import NAMED_BORDERS, PrettyTable
def cmd_colors():
"""Show a coloring sample"""
parser ... |
import gc
import json
import logging
import os
import warnings
from datetime import datetime
import numpy as np
from enum import auto, Enum
from multiprocessing import Process, Event, JoinableQueue
from multiprocessing.managers import SyncManager
from multiprocessing.queues import Empty, Full
from tqdm import tqdm
... |
from django.shortcuts import render, redirect
from django.http import HttpResponse, HttpResponseNotAllowed, HttpResponseRedirect, JsonResponse
from django.contrib.auth import login
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from .forms import UserRegisterForm
from djan... |
'''
Created on Dec 14, 2017
@author: davide
'''
import cv2
import base64
import numpy as np
import time
TYPE_IMAGE = 1
TYPE_DETECTION = 2
TYPE_ACTION = 3
verbose = True
STR_REPR_DELIM = '#$!@#'
DEFAULT_MSG_DELIM = '***'
NEW_DELIM = "$lol0l$"
DMD = DEFAULT_MSG_DELIM
HEADER_SIZE = len("Type" + DMD + "0" + DMD + "Si... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/... |
import argparse
import gym
import numpy as np
import os
import tensorflow as tf
import tempfile
import time
import json
import baselines.common.tf_util as U
from baselines import logger
from baselines import deepq
from baselines.deepq.replay_buffer import ReplayBuffer, PrioritizedReplayBuffer
from baselines.common.mi... |
import threading
import numpy as np
from PyQt5.QtCore import Qt, QTimer
from PyQt5.QtWidgets import QMainWindow, QApplication
from PyQt5.QtGui import QOpenGLShaderProgram, QOpenGLShader, QMatrix4x4, \
QVector3D, QVector4D
from OpenGL import GL
from ui.shaders import Ui_ShadersWindow
from main import pol2cart
def... |
import numpy as np
import scipy.spatial.distance as spatial
from numpy import linalg as LA
def get_dim(edgelist):
"""Given an adjacency list for a graph, returns the number of nodes in
the graph.
"""
node_dict = {}
node_count = 0
for edge in edgelist:
p, q = edge[ :2]
if p not ... |
# Show print job status with real-time updates
import time
import datetime
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
from octopyclient.common import CommonPanel, Singleton, BackgroundTask
from .print_menu import PrintMenuPanel
from octopyclient.igtk import *
from octopyclient.utils imp... |
import numpy as np
import os
import trimesh
import copy
import matplotlib.pyplot as plt
#import binvox_rw as binvox_rw
import math
import net_utils.basic as utils_basic
import ipdb
st = ipdb.set_trace
def calc_rigid_transform(XX, YY):
X = XX.copy().T
Y = YY.copy().T
mean_X = np.mean(X, 1, keepdims=True)
... |
"""
--- Day 8: Seven Segment Search ---
You barely reach the safety of the cave when the whale smashes into the
cave mouth, collapsing it. Sensors indicate another exit to this cave at
a much greater depth, so you have no choice but to press on.
As your submarine slowly makes its way through the cave system, you
notic... |
""" Database entry classes """
from html import escape
from pyulog import *
from pyulog.px4 import *
from helper import get_log_filename, load_ulog_file, get_drone_name, get_drotek_uuid
# pylint: disable=missing-docstring, too-few-public-methods
class DBData:
"""simple class that contains information from the... |
"""Vendored code from scikit-image in order to limit the number of dependencies
Extracted from scikit-image/skimage/exposure/exposure.py
"""
import numpy as np
from warnings import warn
_integer_types = (
np.byte,
np.ubyte, # 8 bits
np.short,
np.ushort, # 16 bits
np.intc,
np.uintc, # 16 or... |
""" ------------- Imports -------------
"""
import argparse
import datetime
import time
import image_classifier_constants as icc
import model as m
import load
import torch
from torch import nn, optim
import json
""" ------------- Functions -------------
"""
def get_train_arguments():
""" Fetches all necessary in... |
import csv
from collections import defaultdict
import shutil
import sys
import math
from argparse import ArgumentParser
import cv2
import torch
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import pandas as pd
from src.efficientnet import EfficientNet
from src.epth_classifier import ... |
# vi: set softtabstop=2 ts=2 sw=2 expandtab:
# pylint: disable=W0621,raise-missing-from,import-outside-toplevel
#
from flask import current_app
from flask_babel import _
from manager.db import get_db, DbEnum
from manager.log import get_log
from manager.exceptions import InvalidApiCall, DatabaseException
from manager.ca... |
#!/usr/bin/env python3
"""
Here we look at universal quantum gate sets over a finite field.
It doesn't really work because there is no concept of "unitary" here,
the finite field has no galois automorphisms.
See also: clifford.py
"""
from random import shuffle
from bruhat.argv import argv
from bruhat.element import ... |
# Copyright 2013 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 applicable law or ag... |
import requests
import urllib
from bs4 import BeautifulSoup
# WHY
# this SearchRequest module is used to contain all of the internal logic that end users will not need to use.
# Therefore the logic is contained and users can interact with libgen_search without extra junk for logic.
# USAGE
# req = search_request.Sea... |
# -*-coding: utf-8 -*-
'''
生产TFrecord文件
保存在data文件下面,有train,val,test,label文件。
'''
import random
from tools.utils import *
import tensorflow as tf
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
def decode_image(image, gray=False):
'''
解码图片,返回resize后的图片
:param image:
:return:
'''
tf_heig... |
from django.http import HttpResponseRedirect, HttpResponse, JsonResponse
from django.views.generic import DetailView
from django.views import View
from django.db.models import Q
from django.conf import settings
from django.template.loader import render_to_string
from django.shortcuts import get_object_or_404, render
fr... |
#!/usr/bin/env python3
"""Compare vocabularies from directories of text files"""
import csv
import fnmatch
import json
import os
import re
import sys
from collections import Counter, namedtuple
from getpass import getpass
from itertools import chain, zip_longest
from operator import methodcaller, itemgetter
from ros... |
'''
This file is part of PM4Py (More Info: https://pm4py.fit.fraunhofer.de).
PM4Py 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 late... |
"""CardinalityMatching.py
Find maximum cardinality matchings in general undirected graphs.
<NAME>, UC Irvine, September 6, 2003.
"""
from seqs.Util import arbitrary_item
from seqs.UnionFind import UnionFind
def matching(graph, initial_matching=None):
"""Find a maximum cardinality matching in a graph graph.
... |
"""
spaceshooter.py
Author: Sean
Credit: Tutorials
Assignment:
Write and submit a program that implements the spacewar game:
https://github.com/HHS-IntroProgramming/Spacewar
"""
from ggame import App, RectangleAsset, CircleAsset, ImageAsset, Sprite, LineStyle, Color, Frame
import math
import random
speed_limit = 10
... |
#!/usr/bin/env python
from __future__ import division
from __future__ import print_function
from past.utils import old_div
import numpy
import unittest
#import sys
#sys.path.append('/Users/nebula/Python')
#from SPD_project.lib import lib_ptrm_statistics as lib_ptrm
#from SPD_project import spd
#import SPD.spd as spd... |
# -*- coding: utf-8 -*-
from __future__ import print_function
from config import get_config
from tfutils import embedding_table
from tfutils import _init, _reg
from tfutils import batch_norm
from tfutils import conv1d
from tfutils import biGRU
from modules import attention_decoder
from modules import highway_network... |
# -*- coding: utf-8 -*-
"""
Created on Mon Aug 20 10:15:16 2018
#PLOTTER to Plot all Channels of EEG Data in realtime
@author: ayadav
"""
from scipy.cluster.vq import whiten
import serial
import matplotlib.pyplot as plt
import numpy as np
#For LSL Stream
from pylsl import StreamInlet, resolve_stream
fr... |
# 2D DVR (need to clean!)
import xlrd
import numpy as np
from scipy import interpolate
import matplotlib.pyplot as plt
workbook = xlrd.open_workbook('CO_NaCl_renew.xlsx', on_demand=True)
bdr_1 = workbook.sheet_by_index(26)
r = np.array(bdr_1.col_values(0, 30, 43))
R = np.array(bdr_1.row_values(29, 1, 17))
energy_ori ... |
import json
import os
import sys
import tempfile
import uuid
from datetime import datetime
import boto3
import requests
public_cert = tempfile.NamedTemporaryFile(delete=False, suffix=".pem")
private_key = tempfile.NamedTemporaryFile(delete=False, suffix=".key")
public_cert.write(os.environ.get('PUBLIC_CERT').replace... |
'''
Tests for the restful framework component
@author: damianhagge
'''
import json
import datetime, time, web, service
from nose.tools import eq_, ok_
not_found_auth_header = '<PASSWORD>'
expired_auth_header = '<PASSWORD>'
class TestRestful():
def setup(self):
""" init web.py """
urls = (
... |
__all__ = ['fast3tree', 'get_distance']
import os
import warnings
import numpy as np
import numpy.ctypeslib as C
from .make_lib import make_lib
try:
range = xrange
except NameError:
pass
_ptr_dtype = np.uint64
_ptr_ctype = C.ctypes.c_uint64
_results_dtype = np.dtype([ \
('num_points', np.int64), ('nu... |
import requests
import datetime
import logging
from requests.auth import HTTPBasicAuth
from requests.utils import requote_uri
from urllib.parse import urlencode, quote_plus
from enum import Enum
class MOOD_TYPE(Enum):
BAD = "BAD"
HARD = "HARD"
AVERAGE = "AVERAGE"
GOOD = "GOOD"
EXCELLENT = "EXCEL... |
#!/usr/bin/python3
"""
Author: <NAME>
Date: May 2019
Brief:
A utility to transform string translations from XML to C
Details:
The output C source and header files can be used for any C application (no dependencies)
The input XML files shall follow Android Localization format. For example:
<resources... |
import pandas as pd
import numpy as np
from PIL import Image
import torch
from torch.utils.data import Dataset
from torchvision import transforms
from torch.utils.data import DataLoader
import torch.nn.functional as F
import torch.nn as nn
import torch.optim as optim
from torch.autograd import Variable
# 自己制作数据集
class... |
import os
import time
import datetime
import pdb
import numpy as np
import pandas as pd
# type check
from pandas.api.types import is_string_dtype, is_object_dtype
from pandas.api.types import is_categorical_dtype, is_datetime64_dtype
from pandas.api.types import is_int64_dtype, is_float_dtype
# visualization
from ma... |
import flask
from flask_sqlalchemy import SQLAlchemy
from dateutil import parser as dateparser
import untangle
import json
import tweepy
import yaml
from functools import wraps
from arxiv_regex import get_arxiv_id
'''
Issue: quoting a tweet won't include it
i.e.
> My new work on RNNs: arxiv.org/...
> John's new wo... |
"""Tests the Usage class implementation."""
import tensorflow as tf
import unittest
from .. dnc import usage
from numpy.testing import assert_array_almost_equal, assert_array_equal
def suite():
"""Create testing suite for all tests in this module."""
suite = unittest.TestSuite()
suite.addTes... |
# trafcapEthernetPacket.py
#
# Copyright (c) 2013 Protectus,LLC. All Rights Reserved.
#
# Classes to help pull data off the wire and update mongo
import subprocess
import time
from trafcap import trafcap
from datetime import datetime
import traceback
import sys
class EthernetPacket(object):
"""
Parent class f... |
from collections import OrderedDict
import ConfigParser
import socket
import sys
import string
class Container(object):
pass
identity = "uninitialized"
instance_timeout_min = 500
instance_timeout_max = 600000
announcement_interval_min = 500
announcement_interval_max = 10000
client_port = 8720
udp = Container()
udp.p... |
"""
Copyright 2018 SiLeader.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writi... |
# 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
# distributed under t... |
"""Test cases for LPEG client module."""
import os
from pathlib import Path
from typing import AsyncGenerator
from typing import Optional
import pytest
import pytest_asyncio
from aioresponses import aioresponses
from aioresponses.compat import merge_params
from aioresponses.compat import normalize_url
from pytest_mock... |
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.distributions import Independent
from torch.distributions import Normal
from torch.distributions import Transform
from torch.distributions import TransformedDistribution
from torch.distributions ... |
import json
import csv
import math
import random
import matplotlib.pyplot as plt
config = {}
def sync_config():
with open('config.json', 'r') as file:
global config
config = json.load(file)
print('> Config synced.')
def clear_dataset():
print(' > Started data formatting task.')
w... |
from flask import Flask, jsonify, request
from flask_sqlalchemy import SQLAlchemy
from dataclasses import dataclass
from sqlalchemy import Column, JSON, Integer, ForeignKey, Text, Index
from flask_migrate import Migrate
from CacheEngine import LFUCache
import CacheDBWrapper
import os
import uuid
# Results per page
MAX... |
import os.path
import argparse
import numpy as np
from tqdm import tqdm
import torch
import _io
import streamlit as st
import altair as alt
import pandas as pd
from models.helper import build_generator
from utils.logger import setup_logger
from utils.editor import parse_boundary_list
from utils.editor import get_laye... |
from __future__ import print_function, unicode_literals, absolute_import, division
import numpy as np
import os, sys, json, argparse, datetime
import keras.backend as K
from scipy.signal import fftconvolve
from skimage.io import imread, imsave
from skimage import img_as_float
from pprint import pprint
from model impo... |
from telegram.ext import Updater
from telegram.ext import MessageHandler, Filters
from sklearn.feature_extraction.text import TfidfVectorizer
import string
import spacy
import numpy as np
from SQLconnection import SqlConnection
from CompareNames import sameNames
from rake_nltk import Rake
from googletrans import Transl... |
# Regular packages
from PIL import Image
import numpy as np
import glob, os
import argparse
from load_data import load_image, get_data
from tqdm import tqdm
import matplotlib
matplotlib.use('agg')
import matplotlib.pyplot as plt
import json
# Torch
from torchvision import transforms
import torch
import torch.nn as ... |
from icu import Locale, Collator, RuleBasedCollator
import pandas as pd
collation_tailorings = {
"din": "&a<<<A<<aa<<<Aa<<<AA<<ä<<<Ä<<ää<<<Ää<<<ÄÄ&d<<<D<dh<<<Dh<<<DH<e<<<E<<ee<<<Ee<<<EE<<ë<<<Ë<<ëë<<<Ëë<<<ËË<ɛ<<<Ɛ<<ɛɛ<<<Ɛɛ<<<ƐƐ<<ɛ̈<<<Ɛ̈<<ɛ̈ɛ̈<<<Ɛ̈ɛ̈<<<Ɛ̈Ɛ̈&g<<<G<ɣ<<<Ɣ&i<<<I<<ii<<<II<<ï<<<Ï<<ïï<<<Ïï<<<ÏÏ&n<<<N<nh<<<... |
#!/usr/bin/python
# encoding: utf-8
"""
@author: rainsty
@file: lxf_basis.py
@time: 2019-08-01 15:48
@description:
"""
from collections.abc import Iterator
from functools import reduce
from datetime import datetime
import functools
from enum import Enum
import os
import threading
import time
# s = input()
# s =... |
import sublime
import sublime_plugin
import os
from . import easycp_parser as Parser
from re import match as re_match, compile as re_compile
import subprocess
from urllib.parse import urlparse
from itertools import zip_longest
from threading import Thread, Lock
REGEX = {
"cf_problem": re_compile(
r"^.*[\... |
from tkinter import*
import tkinter.ttk as ttk
import tkinter.messagebox as tkMessageBox
import sqlite3
import os
#DEVELOPED by:Author <NAME>
#COURSE : BSIT-1R5
root = Tk()
root.title("Python - Save Data To Table (File Handling)")
root.iconbitmap('images/logo.ico')
screen_width = root.winfo_screenwidth()
... |
# -*- coding: utf-8 -*-
import math
import os
from collections import defaultdict
from pprint import pprint
import numpy as np
from tqdm import tqdm
from configs import total_info
from utils.misc import get_gt_pre_with_name, get_name_with_group_list, make_dir
from utils.recorders import (
CurveDrawer,
MetricE... |
#!/usr/bin/python
import random
import itertools
# ######## Words generators
def words(alphabet, min_length, max_length = None):
""" Return a generator of words over alphabet. Those words
are of min_length length to max_length length. The max_length
is set to min_length if not given. """
if not max_... |
'''
Created on Aug 24, 2017
@author: <NAME>
'''
# future must be first
from __future__ import print_function
import datetime
# Simple enum
# http://stackoverflow.com/questions/36932/how-can-i-represent-an-enum-in-python
#class Enum(set):
# def __getattr__(self, name):
# if name in self:
# ... |
import ipywidgets as ipw
import traitlets as tra
import pandas as pd
import numpy as np
import re
import time
from IPython import get_ipython, display
from threading import Thread
from collections.abc import Iterable
def usename(obj: 'Any') -> str:
'''
usename(obj: Any) -> str
Returns obj.__name__ if... |
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright 2020/10/14 MitsutaYuki
#
# Distributed under terms of the MIT license.
import os, glob, shutil, sys, re
import subprocess as sp
from SHS4py import functions
class Dihedral_info():
def __init__(self, line):
self.dihlist = line... |
import datetime
import logging
import traceback
from typing import Type, Union, Optional, Callable, List, Any
import pytz
from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.triggers.base import BaseTrigger
from django.contrib.auth.models import User
from YtManagerApp.management.appconf... |
#Copyright 2014 Center for Internet Security - Computer Emergency Response Team (CIS-CERT)
#This is part of the CIS Enumeration and Scanning Program (CIS-ESP)
#
#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 ... |
import pandas as pd
import numpy as np
import streamlit as st
import matplotlib.pyplot as plt
import seaborn as sns
#import chart_studio.plotly as py
import cufflinks as cf
import plotly.express as px
st.set_page_config(layout="wide")
container_intro = st.container()
with container_intro:
st.title('FIFA 22 Compan... |
import os
import sys
import configparser
import shutil
import logging
from tweepy import OAuthHandler
from .exceptions import HelpfulError
LOG = logging.getLogger(__name__)
class Config:
def __init__(self, config_file):
self.config_file = config_file
self.find_config()
config = config... |
from datetime import datetime, timedelta
import json
from logbook import Logger
from sqlalchemy.exc import IntegrityError
import requests
from transporter import redis_store
log = Logger(__name__)
inf = float('inf')
class DictMapper(object):
"""A dictionary mapper that transforms a map to another."""
def... |
import subprocess
import time
import signal
import sys
import os
import datetime
from PIL import Image, ImageDraw, ImageFont
import imagehash
import argparse
import mss
import pathlib
import img2pdf
from gooey import Gooey, GooeyParser
import region_selector
def init_saved_image_number(directory):
# 前回と同じディレクトリに再... |
import torch
import torch.nn as nn
import torch.optim as optim
import time
import math
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--discountFactor', dest='discountFactor', type=float, default=0.99)
parser.add_argument('--traceLength', dest='traceLength', type=int, default=5)
parser.add_ar... |
import html
import json
import os
import re
from .config import dict_languages, BASE_JSON_DIR, BASE_DIR
from .utils import SubDoc, get_encodings, EncodingError
def sublog(text, doc=None):
if doc:
doc.log(text)
print(text)
def makedir(folder):
if not os.path.exists(os.path.dirname(folder)):
... |
"""
Usage:
python test_image_lm86_with_mtcnn.py --checkpoint_dir=checkpoints/test/model.ckpt-64001
"""
#from __future__ import absolute_import
#from __future__ import division
#from __future__ import print_function
import cv2, os, importlib, math
import os.path as osp
import numpy as np
import tensorflo... |
from __future__ import division
from __future__ import print_function
import copy
import os
import re
import time
import glob
import torch
import torch.nn as nn
import torchvision
from tensorboardX import SummaryWriter
from torchvision import models
print("PyTorch Version: ", torch.__version__)
print("Torchvision Ve... |
from datetime import date
from sqlalchemy import (case, select, cast, Column, Integer, Date,
String, Sequence, ForeignKey, Unicode)
from sqlalchemy.ext.hybrid import hybrid_property, hybrid_method
from sqlalchemy.orm import relationship, backref
import enums
from common import BaseSchema
cla... |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
import logging
import random
import re
from collections import defaultdict
from typing import List, Optional
import networkx as nx
import torch
from allennlp.training.metrics import Metric
logger = logging.getLogger(__name__)
def clean_answer... |
"""ILP Solver"""
import numpy as np
from alpa.shard_parallel.auto_sharding import _call_solver_serialized_args
def call_solver(N, M, s_len, s_follow, E, A, L, c, d, m, r, v, s_init):
"""Serialize python lists to flatten numpy arraies and call solver"""
# Serialize strategy lengths
s_len_np = np.array(s_l... |
# -*- coding: utf-8 -*-
import unittest
import os
import numpy as np
try:
from karta import Point
from karta.crs import LonLatWGS84
except ImportError:
from narwhal.geo import Point, LonLatWGS84
import narwhal
from narwhal import gsw
from narwhal.cast import Cast, CTDCast, XBTCast, LADCP
from narwhal.cast... |
import random
import numpy
import math
import operation
import Helper
def f(x):
return math.ceil(float(x)/2)
def g(x):
return 2*f(x)-x
def rdei(angka_input):
angka = abs(angka_input)
if angka>3:
rd = angka - pow(2,((math.floor(math.log(angka,2)))-1)) - pow(2,(math.floor(math.log(angka,2))-... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn import init
import pickle
import pandas as pd
import numpy as np
"""
u_embedding: Embedding for center word.
v_embedding: Embedding for neighbor words.
"""
def load_augmentive_features(nodes):
PICKLE_PATH = "./input/node2fp_re... |
import re
from .event import Event
from .patterns import PATTERNS as P
# basically a regex that can be used to create an Event
class EventParser:
PARSERS= []
@staticmethod
def register_parser(parser):
assert isinstance(parser, EventParser)
EventParser.PARSERS.append(parser)
def parse... |
import os, sys
import numpy as np
import pandas as pd
from scipy.spatial import distance
from sklearn.utils import validation
from sklearn.metrics import pairwise
from scipy.sparse import issparse
def _return_float_dtype(X, Y):
"""
1. If dtype of X and Y is float32, then dtype float32 is returned.
2. El... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.