text stringlengths 3.07k 12.6k |
|---|
# Copyright (c) 2016-2019 <NAME>
#
# SPDX-License-Identifier: Apache-2.0
#
# 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... |
# roster.py - manages a dictionary of locos
"""
roster.py - helper class to process loco roster definitions
the MIT License (MIT)
Copyright © 2020 <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 i... |
#!/usr/bin/env python3
import socket
import struct
import threading
import time
import ipaddress # kjw
import pickle
from collections import namedtuple
class Ascii(object):
"""Simple ASCII format to send info"""
def dumps(self, data):
return "|".join(data).encode('utf-8')
def loads(self, msg):
... |
from space import Box
import numpy as np
import seeding
class Env(object):
"""The main OpenAI Gym class. It encapsulates an environment with
arbitrary behind-the-scenes dynamics. An environment can be
partially or fully observed.
The main API methods that users of this class need to know are:
... |
# import pylab
from PyQt5.QtWidgets import *
from PyQt5.QtGui import QIcon
import time
import socket
import sys
import matplotlib.animation as anim
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
import matplotlib.pyplot as plt
import numpy as np
im... |
# -*- coding: utf-8 -*-
import os
import sys
import copy
import random
import numpy as np
from PIL import Image
from collections import Counter
import pickle
import torch
import torch.nn as nn
import torchvision
from torchvision import datasets, transforms
from torch.utils.data.sampler import SubsetRandomSampler, Weigh... |
# -*- coding: utf-8 -*-
# Copyright (c) 2012, <NAME>
# All rights reserved.
# This file is part of PyDSM.
# PyDSM 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 yo... |
# 9.6
class Restaurant:
'''Restaurant object'''
def __init__(self, name, cook_type):
self.name = name
self.type = cook_type
self.number_served = 0
def describe_restaurant(self):
'''Print name and food type of the restaurant'''
print(f'{self.name.title()} make {self.... |
# GUI Events
#
# FIXME: Fix ids (to wx.NewId()s).
# FIXME: Use wx's built in method for creating events?
#import wxversion
#wxversion.select([x for x in wxversion.getInstalled()
# if x.find('unicode') != -1])
import wx
#from util import wx
_ID_EVT_TRACK_CHANGE = wx.NewIdRef()
def EV... |
#######################################################################
# Copyright (C) 2017 <NAME>(<EMAIL>) #
# Permission given to modify the code as long as you keep this #
# declaration at the top #
##############################################################... |
import unittest
import requests
import joblib
import hassbrainapi.algorithm as api
from hassbrainapi.settings import *
class TestFile(object):
def __init__(self, num):
self._num = num
class AlgorithmTest(unittest.TestCase):
def setUp(self):
pass
def test_download_model(self):
li... |
"""
Hash tables :: Day 2 notes - Hash tables
* Hash tables have an underlying Array structure
* This is why they are as hast at accessing elements as arrays
* The main difference is that hash tables are indexed using a hash function
in an unordered fashion, whereas arrays are indexed via contiguous ordered... |
'''
Twisted utilities
Copyright (c) 2015 - 2021 Rob "N3X15" Nelson <<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 without limitation the rights
to use, ... |
"""
Submodule to load all input data for SEAS
serve as main controller
We need to add checking the molecule availability database
"""
import os
import sys
import hashlib
import numpy as np
DIR = os.path.abspath(os.path.dirname(__file__))
sys.path.insert(0, os.path.join(DIR, '../..'))
from SEAS_Utils.Common_Uti... |
from pathlib import Path
import itertools
import pandas as pd
import numpy as np
pd.set_option('display.max_columns', None)
pd.set_option('display.width', 1000)
DATA_FOLDER = Path("data-ic")
def get_timeline():
df = pd.read_csv(Path("data", "nice_ic_by_day.csv"))
dates = sorted(df["Datum"].unique())
r... |
import json
import time
import random
nSensors = 10
sensorMissedPassCount = [0]*(nSensors+1)
nObjects = 300
objectMissedPassCount = [0]*(nObjects+1)
runningMissedPassCount = 0
minSize = -60 # dBsm: 1 square millimeter
maxSize = 60 # dBsm: 1 million square meters
# Expert system approach to monitoring SSA events ... |
'''
LEW-20210-1, Python Ground Station for a Core Flight System with CCSDS Electronic Data Sheets Support
Copyright (c) 2020 United States Government as represented by
the Administrator of the National Aeronautics and Space Administration.
All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "Lice... |
import Jassen as js
import multiprocessing #*NOTE Multiprocessing ?usually? does not work in iPython (Spyder). To use MP, run file through Anaconda: navigate to folder and type: `python JassRNN.py`
import numpy as np
from tqdm import tqdm #using anaconda/pip: pip install tqdm
import time
def TrainArrayInputRaw():
... |
import datetime
import face_model
import argparse
import cv2
import sys
import os
import numpy as np
from skimage.transform import resize
def show_images(person_name, image_dir):
image_nams = os.listdir(os.path.join(image_dir, person_name))
image_path1 = os.path.join(data_dir, person, image_nams[0])
imag... |
import numpy as np
import matplotlib.pyplot as plt
from numpy import random, linalg, histogram
from scipy.stats import norm
from .numpy_log_likelihood import (theta_from_GMM_params, sigma_arr_with_noise,
convert_1d_eta_to_2d_eta, calculate_a_b,
cal... |
from glob import glob
import os
import numpy as np
import fitsio
import commish_paths
def write_astrometry_for_gfa_expnum(expnum, out_dir, **kwargs):
#gnums=[0,2,3,5,7,8]):
return write_astrometry_for_gfa_file(gfa_filename(expnum), out_dir, **kwargs) #gnums=gnums)
def write_astrometry_for_gfa_file(fn, out_di... |
# from __future__ import absolute_import
# from __future__ import division
# from __future__ import print_function
import random
import time
import numpy as np
import tensorflow as tf
from data_io import tpn_iterator, tpn_raw_data
import cPickle
import os
import os.path as osp
import glog as log
from model import TPN... |
# -*- coding: utf-8 -*-
from sys import stdout
import numpy as np
import datetime
import os
import csv
import uuid
import json
import platform as pl
from networkx.readwrite import json_graph
def folder_id():
return datetime.datetime.today().strftime('%Y%m%d_%H%M%S%f')
def file_id(prefix='',extension='.csv'):
... |
# flake8: noqa
import logging
import os
import sys
import atexit
logger = logging.getLogger(__name__)
# user code can override this null handler
logger.addHandler(logging.NullHandler())
# pull in our module version number, see also setup.py
from .version import __version__
# try to import our binary interface ... ... |
from django.shortcuts import render
from django.http import HttpResponse
from django.http import Http404
from django.shortcuts import render,redirect
from django.core.exceptions import ValidationError
from django import forms
from django.http import HttpResponse,HttpResponseRedirect
from django.shortcuts import render
... |
from osgeo import gdal, gdalnumeric, ogr, gdal_array
#import sys
#sys.path.append(r'C:\Program Files\GDAL')
# import ogr
# import gdal_array
from skimage import measure
import numpy as np
import json
import os
import datetime
from shapely.geometry import Polygon
# Disabling speedups because of error when using Cytho... |
from __future__ import print_function
import sys, os
sys.path.insert(1, os.path.join("..", "..", ".."))
import h2o
from tests import pyunit_utils
from h2o.estimators import H2OUpliftRandomForestEstimator
import numpy as np
def uplift_train_predict(uplift_metric, x_names, treatment_column, response_column, train_h2o,... |
import sys, os, math, json
from scipy import spatial
from collections import Counter
import numpy as np
from wordextract import *
from protbased import *
OutputDir = "outputs/"
SMIFile = sys.argv[3]
SMILESDict = json.load(open(SMIFile))
maccspath="data/a50fam.se.filtered.tab.seperated.maccs.binary"
maccsDict = {}
... |
# Copyright (C) 2017 Open Information Security Foundation
#
# You can copy, redistribute or modify this Program under the terms of
# the GNU General Public License version 2 as published by the Free
# Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; wi... |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
from collections import OrderedDict
from pprint import pprint
import logging
import json
from pathlib import Path
import ruamel.yaml
import jsonschema
import jinja2
import numpy as np
from astropy.coordinates import SkyCoord
import astropy.units as u
from ... |
import json
import plotly
import re
import pandas as pd
from nltk.stem import WordNetLemmatizer
from nltk.tokenize import word_tokenize, sent_tokenize
from flask import Flask
from flask import render_template, request, jsonify
from plotly.graph_objs import Bar, Scatter
from sklearn.externals import joblib
from sklear... |
from os.path import join, split
import pandas as pd
from surprise import Dataset, Reader
from surprise import KNNBasic
from fuzzywuzzy import fuzz
def get_movie_index(movie_name):
return _movies.loc[_movies['title'] == movie_name, 'movieId'].values.tolist()[0]
def get_movie_name(movie_id):
return _movies... |
from requests import get
from config import (state, include_rep, propublica_header, twitter_config,
district, tweet_age_limit, use_govtrack, tag_member)
from datetime import date
from time import localtime
from tweepy import OAuthHandler, API
from requests_oauthlib import OAuth1
ltime = localtime(... |
import time
import tensorflow as tf
from absl import app, flags
from tensorflow.python.client import device_lib
import constants
import helpers
from data.dataset import Dataset
from models import custom_callbacks
from models import train
from models.detection.yolov3 import YOLOv3
FLAGS = flags.FLAGS
# Strings
flags.... |
# -*- coding: utf-8 -*-
# @Time : 2019/10/11 0:03
# @Author : Esbiya
# @Email : <EMAIL>
# @File : geetest.py
# @Software: PyCharm
import re
import json
import random
import requests
import execjs
from bs4 import BeautifulSoup
from luosimao import img_locate
import time
from luosimao.lsm_crypt import aes_encry... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Script to get protein coding models from GFF3 file based on biotype
# Monday, 17 February 2020, 10:36AM
"""
# authorship and License information
__author__ = "<NAME>"
__copyright__ = "Copyright 2020"
__license__ = "MIT"
__maintainer__ = "<NAME>"
__email__ = "<EMAIL>"
... |
import os
import numpy as np
import rospy
from std_msgs.msg import Bool
from geometry_msgs.msg import Twist, Point, Vector3
# Global variables
red_center = Point()
red_flag = False
red_base = Point()
blue_base = Point()
game_over = False
red_twist = Twist()
Q_table = {}
yaw_actions = np.array(list(range(8))) * np.pi... |
"""Based on code by <NAME>. "Phantasm"
"""
__author__ = "<NAME>"
__credits__ = ["<NAME>", "<NAME>. 'Phantasm'", "<NAME> (hash key implementation)"]
from debug import log
from io import BytesIO
WINDOW_SIZE = 256
MAX_UNENCODED = 2
MAX_CODED = MAX_UNENCODED + 256
HASH_SIZE = 1024
class FlagData:
def __init__(sel... |
import datetime
import os
import pickle
from concurrent.futures.process import ProcessPoolExecutor
from dataclasses import dataclass
from pathlib import Path
from typing import List, Callable, Optional, Dict
import numpy as np
from ether.core import Node
from sim.benchmark import Benchmark
from sim.core import Environ... |
"""
Generate basic waveforms of a classical analog synthesizer.
Author: <NAME>
"""
import numpy as np
import scipy.signal
TWO_PI = 2 * np.pi
def generate_pulse_wave(xs: np.ndarray, xs_step: float, duty_cycle: float = 0.5) -> np.ndarray:
"""
Generate band-limited pulse wave.
PolyBLEP method is applie... |
import numpy as np
from typing import Type
import librosa
from pydub import AudioSegment
import random
def int_samples_to_float(y: np.ndarray, dtype: Type):
assert isinstance(y, np.ndarray)
assert issubclass(y.dtype.type, np.integer)
assert issubclass(dtype, np.floating)
y = y.astype(dtype) / np.iin... |
# -*- coding:utf-8 -*-
# Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the MIT License.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the ... |
#!/usr/bin/python3
"""
Creates Github Releases and uploads assets
"""
import argparse
import logging
import os
import shutil
import hashlib
import requests
import tarfile
from os import listdir
from os.path import isfile, join
import re
from github import Github, GithubException, UnknownObjectException
FORMAT = "%(l... |
# Copyright (c) 2013, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe import _
def execute(filters=None):
columns, data = [], []
columns=get_columns()
data=get_data(filters,columns)
return columns, ... |
# -*- coding: utf-8 -*-
"""
Viriyothai (2009) Variance Minimization Light Probe Sampling
============================================================
Defines the *Viriyothai (2009)* variance minimization light probe sampling
objects:
- :func:`colour_hdri.\
light_probe_sampling_variance_minimization_Viriyothai2009`
... |
#!/usr/bin/env python
# coding: utf-8
import inspect
import json
import os
import urllib.request
from functools import reduce
from glob import glob
from time import sleep
from urllib.parse import quote
import jieba
import numpy as np
import pandas as pd
import seaborn as sns
from icecream import ic
from snorkel.labeli... |
"""
Aggregate results and organize them into one dict.
"""
import os
import sys
import time
import argparse
from datetime import datetime
from itertools import product
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy.stats import sem
from scipy.stats import gmean
from tqdm import tqdm
... |
# -*- coding: utf-8 -*-
from django.http import HttpResponse, Http404
from django.template import Template, Context
from django.template.loader import get_template
from django.shortcuts import render
import logging
from htmllib import HTMLParser
from django_weixin.api_errors import *
import json, xml.etree.ElementTree ... |
"""Handle connecting to the HUE Eventstream and distribute events."""
from __future__ import annotations
import asyncio
import json
from enum import Enum
from typing import TYPE_CHECKING, Callable, List, NoReturn, Tuple
from aiohttp.client_exceptions import ClientError
from asyncio.coroutines import iscoroutinefunctio... |
import pandas as pd
from typing import Tuple, Dict
from .template import Processor
from .fasta import FastaParser, FastaWriter
from .importing import ImportFeatureTable, ImportFeatureSequence
from .exporting import ExportFeatureTable, ExportFeatureSequence, ExportTaxonomy
class FeatureLabeling(Processor):
ASV_PR... |
import os
import disnake as discord
import numpy
import requests
from PIL import Image
from colormap import rgb2hex
from disnake.ext import commands
from dotenv import load_dotenv
from utils.functions import *
if os.name != "nt":
try:
import uvloop
uvloop.install()
except Modu... |
#!/usr/bin/env python
# encoding: utf-8
'''
-- Checks the FITS header for DATE-OBS, EXPTIME, and FILTER values, then
renames FITS files to match the ESA/PSA and NASA/PDS archive fielname format
@author: <NAME>
@author: <NAME>
@copyright: Copyright 2015 <NAME> - Licensed under the Apache License 2.0
@lice... |
"""Implementation of the AbstractRepository.
Implements the AbstractRepository interface to use the
SQLAlchemy ORM as a data store.
"""
from sqlalchemy.orm import mapper, relationship
from sqlalchemy.event import listen
from sqlalchemy import or_
from experimentum.Storage import AbstractRepository
import logging
def... |
import pickle
import numpy as np
import matplotlib as mpl# ; mpl.use('agg')
import matplotlib.pyplot as plt
import imageio
nframes = 320
nframe_per_second = 20
nframepost = 2*nframe_per_second
nsources = 80
np.random.seed(4321)
photon_path_length = 100
photon_path_length_dl = 3
photon_path_jump = 10
run_with_plotting ... |
import networkx as nx
import numpy as np
from queueing_tool.graph.graph_functions import _test_graph, _calculate_distance
from queueing_tool.graph.graph_wrapper import (
adjacency2graph,
QueueNetworkDiGraph
)
def add_edge_lengths(g):
"""Add add the edge lengths as a :any:`DiGraph<networkx.DiGraph>`
f... |
from dotmap import DotMap
import numpy as np
from typing import List, Tuple, Any
def aggregate_over_seeds(result_dict: DotMap, batch_case: bool = False) -> DotMap:
"""Mean all individual runs over their respective seeds.
BATCH EVAL CASE:
IN: {'b_1_eval_0': {'seed_0': {'meta': {}, 'stats': {}, 'time': {}}
... |
"""Entry point to evolving the neural network. Start here."""
import logging
from optimizer import Optimizer
from tqdm import tqdm
import sys
from keras.datasets import mnist, cifar10
from keras.models import Sequential
from keras.layers import Dense, Dropout
from keras.utils.np_utils import to_categorical
from keras.c... |
# coding=utf-8
# @Time : 2020/12/16 17:16
# @Auto : zzf-jeff
from .base_backbone import BaseBackbone
from ..builder import BACKBONES
import torch
from torch.nn import init
import torch.nn as nn
import torch.nn.functional as F
# conv+bn+relu
class ConvBnRelu(nn.Module):
def __init__(self, in_channels, out... |
import numpy as np
import os
import re
import pandas as pd
import glob
from matplotlib import pyplot as plt
import seaborn as sns
from sklearn.calibration import calibration_curve
plt.rcParams['pdf.fonttype'] = 42
plt.rcParams['font.size'] = 7.0
def process_dirname(name):
match = re.match("([a-zA-Z]+)(\d+)([a-zA... |
import numpy as np
from .estimators import AISEstimator, BaseEstimatorWithVariance
from .pools import BasePool
from .measures import BaseMeasure
from .proposals import BaseProposal, AdaptiveBaseProposal
from .estimators import BaseEstimator
from typing import Optional, Union, List, KeysView, Iterable
from numpy impo... |
from penalty_function import penalty
import numpy as np
from numba import njit
# interchange two slots of a professor
@njit(cache=True)
def neighbourhood_structure1(candidate, presentation_supervisor):
supervisor_no = presentation_supervisor.shape[1]
while True:
random_supervisor = np.random.randint(... |
""" simdatamatch.py
Defines the SimDataMatch class which is used to map simulation data onto
components under an assembly tree
"""
#pythom 2+3 compatibility
from __future__ import (absolute_import, division,
print_function, unicode_literals)
from builtins import super
from functools import wra... |
#!/usr/bin/env python
"""
Generates a Wishbone multiplexer with the specified number of ports
"""
from __future__ import print_function
import argparse
import math
from jinja2 import Template
def main():
parser = argparse.ArgumentParser(description=__doc__.strip())
parser.add_argument('-p', '--ports', type=... |
"""
Definitions of frames for update_csv. Kept separate to isolate Tkinter.
There is some overlap of business logic and GUI code that could probably
be cleaned up.
"""
from __future__ import absolute_import, division, print_function, unicode_literals
import Tkinter
import tkMessageBox
import tkFont
min_central = 1
ma... |
import sys
from flask import Flask, redirect, request, jsonify, render_template
import soundfile as sf
import librosa
import numpy as np
from os import system
import speechmetrics
import math
app = Flask(__name__, static_url_path='/', static_folder='static')
texts = ['Alla tiger och undviker varandra med blicken',
... |
# Copyright 2020-2021 Huawei Technologies Co., Ltd
#
# 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 agre... |
# DATASET LAST UPDATED AS OF 03/18/19
#%%
from nba_py import game
from nba_py import constants
from nba_py import team
import nba_py
import requests
import requests_cache
import numpy as np
import pandas as pd
import os
pd.set_option('display.max_columns', None)
#%%
# Get ID of most recent game played in the data
X = ... |
from sqlalchemy import Column, String, Integer, Float, Boolean, Date, ForeignKey
from sqlalchemy.dialects.postgresql import ARRAY
from sqlalchemy.orm import relationship
from .db import db
# generated with the assistance of sqlacodegen
class Budget(db.Model):
__tablename__ = 'budget'
code = Column(String, p... |
#! /usr/bin/env python2
#
#
# Written by Rupe 11-22-2015
from __future__ import print_function
from logging import getLogger, ERROR
getLogger("scapy.runtime").setLevel(ERROR)
from scapy.all import *
from commands import getoutput
from multiprocessing import Process
from subprocess import call
from os import system
fro... |
# import os
# import requests
from django.views.generic import TemplateView, ListView
from django.shortcuts import render
from vertical_multi_columns.views import EvenVMCView, CriteriaVMCView, DefinedVMCView
from . import simulate
# An API call is being simulated here to avoid complexity in this demo program.
# Inst... |
"""
This module implements the BW differentials adaptive countermeasure.
"""
import time
# WFPadTools imports
import obfsproxy.common.log as logging
from obfsproxy.transports.wfpadtools import common as cm
from obfsproxy.transports.wfpadtools import histo as hs
from obfsproxy.transports.wfpadtools import const
from ob... |
from operator import add, mul, sub
square = lambda x: x * x
identity = lambda x: x
triple = lambda x: 3 * x
increment = lambda x: x + 1
HW_SOURCE_FILE = __file__
from operator import add, sub
def a_plus_abs_b(a, b):
"""Return a+abs(b), but without calling abs.
>>> a_plus_abs_b(2, 3)
5
>>> a_p... |
from django.db.models import Max, Sum, Count
from django.urls import reverse
from django.contrib import messages
from django.contrib.sites.models import Site
from django.shortcuts import get_object_or_404
from django.utils.translation import gettext as _
from django.views.generic import View, ListView, DetailView, Temp... |
import numpy as np
import pytest
from nengo import params
from nengo.utils.compat import PY2
def test_default():
"""A default value is immediately available, but can be overridden."""
class Test(object):
p = params.Parameter(default=1)
inst1 = Test()
inst2 = Test()
assert inst1.p == 1
... |
import torch
from torch import nn
from contrib.model.unet_tile_se_norm import StyleEncoder
from util.util import repeat_interleave
class AlphaLossNV2(torch.nn.Module):
"""
Implement Neural Volumes alpha loss 2
"""
def __init__(self, lambda_alpha, clamp_alpha, init_epoch, force_opaque=False):
s... |
"""
Custom API exception reponses.
API specification requires custom messages upon error.
"""
import json
import logging
from aiohttp import web
from .. import __apiVersion__
from ..conf import CONFIG_INFO
LOG = logging.getLogger(__name__)
class BeaconError(Exception):
"""BeaconError Exception specific class.
... |
import os
import utils
from time import sleep
import argparse
import secrets
import string
import base64
from waiting import wait, TimeoutExpired
parser = argparse.ArgumentParser()
parser.add_argument("--target")
args = parser.parse_args()
if args.target != "oc-ingress":
CMD_BIN = 'kubectl'
olm_ns = 'olm'
... |
import argparse
import logging
import sys
import json
from typing import TextIO, List, Optional
from master.api_client import MasterApiClient
from common.models.graph import GraphStruct, ExtendedTaskStruct
from plugins.executors.shell import ShellExecutorConfig
SUPPORTED_FORMATS = {
'script', 'makefile', 'raw'
}
... |
import enum
import itertools
from typing import Callable, Dict, Generator, List, Optional
import importlib
class Symbol:
def __init__(self, name: str):
self._name = name
@property
def name(self):
return self._name
def __hash__(self):
return hash(self._name)
def __eq__(se... |
from __future__ import print_function
import unittest
import basicTypes
import symbolify
import algebra
Context = symbolify.Context
class TestContexts(unittest.TestCase):
def test_basicBranching(self):
base = symbolify.Branch().branchOff(0,True)
left = Context([base.branchOff(1,True)])
ri... |
# Functions to compute properties of 3d vectors, including angles,
# torsions, out-of-plane angles. Several return False if the operation
# cannot be completed numerically, as for example a torsion in which 3
# points are collinear.
import numpy as np
from math import sqrt, fabs, sin, acos, asin, fsum
from . import op... |
# Python notes:
# string to datetime format : dateutil.parser.parse(my_string)
# what day is it?: calendar.weekday(libdt.year, libdt.month, libdt.day) (0=monday, 1=tuesday)
import datetime as libdt
import pytz
import pandas as pd
def build_timestamp_list(start, end, time_step_second=15*60):
"""
Build ... |
import random
RANK_MAP = {
1: 'Ace',
11: 'Jack',
12: 'Queen',
13: 'King'
}
SUIT_MAP = {
'C': 'Clubs',
'S': 'Spades',
'H': 'Hearts',
'D': 'Diamonds',
}
SUIT_VAL = {
'C': 0,
'S': 1,
'H': 2,
'D': 3,
}
REVERSE_SUIT_VAL = {
0: 'C',
1: 'S',
2: 'H',
3: 'D',
}... |
from LR1 import createItems, createLR_sheeet
from utils import getFirst, getFirstSet, getFollow, getFollowSet
from extract_word import parseString
import pickle
all_g, all_sheet = pickle.load(open('data/all_sheetLR14.pkl', 'rb'))
all_item = pickle.load(open('data/all_LR1_items4.pkl', 'rb'))
follow = getFollow(... |
"""submissions.py: Utils that help dealing with submissions"""
import os
from typing import Callable
from datetime import datetime
from dateutil.relativedelta import relativedelta
from pytz import timezone
import git
import common.printing as printing
def check_late(deadline_path, iso_timestamp):
"""Checks if iso... |
import os.path
import sys
import tkinter as tk
from tkinter import ttk
from tkinter import *
from tkinter.ttk import *
from PIL import Image, ImageTk
LARGE_FONT = ("Ubuntu", 12)
VERY_LARGE_FONT = ("Ubuntu", 15)
# Define Functions
def documentation():
print("access the documentation in html and pdf format !!!")... |
# -*- coding: utf-8 -*-
# This repo is licensed under the Apache License, Version 2.0 (the "License")
#
# Copyright (c) 2014-2021 Megvii Inc. All rights reserved.
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT ARRANTI... |
import contextlib
import functools
import itertools
import sys
import time
import typing
from importlib.util import find_spec
import numpy as np
import torch
from . import cuda, hooks, module, performance
from ._base import Base
from ._dev_utils._general import _cuda_info, _general_info
from ._version import __versio... |
from django.utils import timezone
from jsonschema import Draft7Validator
from rest_framework import serializers
from .models import Registration
REGISTRATION_SCHEMA = {
"$schema": "http://json-schema.org/draft-07/schema#",
"definitions": {
"nonzero_money": {
"anyOf": [
{"t... |
import numpy as np
from imagededup.handlers.metrics.classification import (
_get_unique_ordered_tuples,
_make_all_unique_possible_pairs,
_make_positive_duplicate_pairs,
_prepare_labels,
classification_metrics,
)
def test__get_unique_ordered_tuples():
non_unique_pairs = [('1', '3'), ('1', '4')... |
"""Light Neural Architecture Search."""
from __future__ import print_function
import json
import argparse
import subprocess
from paddle.fluid.contrib.slim.search import Searcher
from paddle.fluid.contrib.slim.search import SaController
NAS_FILTER_SIZE = [[18, 24, 30], [24, 32, 40], [48, 64, 80], [72, 96, 120],
... |
#!/usr/bin/env python
"""
Author: <NAME>
"""
import json
import os
import traceback
from enum import Enum
from time import sleep
import logging
from cassandra import ConsistencyLevel
from cassandra.cluster import Cluster, BatchStatement
from cassandra.policies import RoundRobinPolicy
from cassandra.query import Simpl... |
from multiprocessing import cpu_count
import numpy as np
import tensorflow as tf
from . import mixup
from .mixmatch import sharpen, guess_labels
from ..libml.data_augmentations import weak_augment, medium_augment, strong_augment, random_rotate
def compute_rot_loss(x, model, w_rot=0.5):
"""
Compute auxiliary... |
#!/usr/bin/env python
# PYTHON_ARGCOMPLETE_OK
# -*- coding: utf-8 -*-
"""
FISCO BCOS/Python-SDK is a python client for FISCO BCOS2.0 (https://github.com/FISCO-BCOS/)
FISCO BCOS/Python-SDK is free software: you can redistribute it and/or modify it under the
terms of the MIT License as published by the Free Softwar... |
import frappe
import shutil
def get_table_serial_key(table_name):
#table_serial = frappe.db.get_value('Bank CSSRLCOD', table_name, ['table_serial'])
serial_doc = frappe.get_doc('Bank CSSRLCOD', table_name)
table_serial = serial_doc.table_serial
#frappe.db.set_value('Bank CSSRLCOD', table_name, {"table_serial" : ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = 'Wandao123'
__date__ = '2020/6/21'
import datetime
import math
import matplotlib.pyplot as plt
import numpy as np
from typing import Dict, List, Tuple
import simulator
#import simulatorWithCpp as simulator
MaxTrials = int(1.e3)
MaxNodes = 6... |
from functools import partial
from pkg_resources import resource_filename
import os
import numpy as np
import pandas
from unittest import mock
import nose.tools as nt
import matplotlib
matplotlib.rcParams['backend'] = 'agg'
from matplotlib import pyplot
from matplotlib.testing.decorators import image_comparison, cle... |
#!/usr/bin/env python3
# Copyright (C) 2021 The Android Open Source Project
#
# 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 requ... |
from __future__ import division, print_function, absolute_import
# LIBTBX_SET_DISPATCHER_NAME iota.run
'''
Author : Lyubimov, A.Y.
Created : 10/12/2014
Last Changed: 11/05/2018
Description : IOTA command-line module.
'''
import os
from iota import iota_version
from iota.components.iota_init import XInitAll
f... |
from keras.models import load_model
import numpy as np
import cv2
from collections import deque
model_simple = load_model('Simple_Autoencoder.h5')
model_deep = load_model('Deep_Autoencoder.h5')
model_conv = load_model('Convolutional_Autoencoder.h5')
def keras_predict(image):
processed = keras_process_image(image... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.