text stringlengths 3.07k 22.1k |
|---|
# -*- coding: utf-8 -*-
import re
import ast
"""
초성 중성 종성 분리 하기
유니코드 한글은 0xAC00 으로부터
초성 19개, 중상21개, 종성28개로 이루어지고
이들을 조합한 11,172개의 문자를 갖는다.
한글코드의 값 = ((초성 * 21) + 중성) * 28 + 종성 + 0xAC00
(0xAC00은 'ㄱ'의 코드값)
따라서 다음과 같은 계산 식이 구해진다.
유니코드 한글 문자 코드 값이 X일 때,
초성 = ((X - 0xAC00) / 28) / 21
... |
"""
Panda3d Extension
Author: <NAME>
"""
import functools
import numpy as np
import cv2
from panda3d.core import (Texture,
NodePath,
WindowProperties,
Vec3,
Point3,
PerspectiveLens,
... |
from queue import Queue, LifoQueue, PriorityQueue
from copy import deepcopy
# A few graph algorithms...in Python this time!
# P-cleanup
def max_flow_min_cut(adj_list, source, sink):
# Returns the integer max flow which is also the min-cut
# Using Edmonds-Karp implementation (bfs to find augmenting paths), we... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from .segbase import SegBaseModel
from .model_zoo import MODEL_REGISTRY
__all__ = ["ContextNet"]
@MODEL_REGISTRY.register()
class ContextNet(SegBaseModel):
def __init__(self):
super(ContextNet, self).__init__(need_backbone=False)
... |
import requests
from urllib.parse import urlparse, urlencode
from json import JSONDecodeError
from requests.exceptions import HTTPError
def validate_response(response):
"""
raise exception if error response occurred
"""
r = response
try:
r.raise_for_status()
except HTTPError as e:
... |
#!/usr/bin/env python3
"""
Starts a demo HTTP server to capture and transform audio
as a live demonstration of the trained model.
<NAME> 2019-07-29 <<EMAIL>> <<EMAIL>>
"""
import argparse
import falcon
import io
import librosa
import numpy as np
import os
import scipy
import soundfile
import subprocess
import tempfi... |
# -*- coding: utf-8 -*-
"""Test losses"""
import datetime
import numpy as np
import pandas as pd
from pandas.util.testing import assert_series_equal
from pvlib.soiling import hsu, kimber
from pvlib.iotools import read_tmy3
from conftest import (
requires_scipy, needs_pandas_0_22, DATA_DIR)
import pytest
@pytest.... |
# -*- coding: utf-8 -*-
from common import globals as glob
import os
from bokeh.io import output_file, show
from bokeh.models import (
GMapPlot, GMapOptions, ColumnDataSource, Circle, DataRange1d, PanTool, WheelZoomTool, BoxSelectTool,
HoverTool, ResetTool, NumeralTickFormatter, PrintfTickFormatter
)
from collectio... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Curses implementation of Conway's Game Of Life with an evolutionary twist.
Any live cell with fewer than two live neighbours dies.
Any live cell with two or three live neighbours lives on.
Any live cell with more than three live neighbours dies.
Any dead cell with exactly... |
import copy
import logging
import os
import numpy as np
import torch.utils.data
import torchvision
from PIL import Image
from .heatmap import putGaussianMaps
from .paf import putVecMaps
from . import transforms, utils
def kp_connections(keypoints):
kp_lines = [
[keypoints.index('neck'), keypoints.index('r... |
import argparse
import json
import logging
import os
import random
from builtins import ValueError
from collections import defaultdict
from io import open
import numpy as np
import torch
import yaml
from easydict import EasyDict as edict
from tqdm import tqdm
from evaluator import final_evaluate
from mmt.metrics impo... |
import pandas as pd
import numpy as np
from rex import MultiYearWaveX, WaveX
import sys
def region_selection(lat_lon):
'''
Returns the name of the predefined region in which the given coordinates reside.
Can be used to check if the passed lat/lon pair is within the WPTO hindcast dataset.
Parameters
... |
# Copyright (c) 2010-2014 openpyxl
import pytest
# package imports
from openpyxl.compat import safe_string
from openpyxl.reader.excel import load_workbook
from openpyxl.reader.style import read_style_table
from openpyxl.styles import (
numbers,
Color,
Font,
PatternFill,
GradientFill,
Border,
... |
from aiohttp import web
import psutil
import platform
from datetime import datetime
import sys
import subprocess
import asyncio
import aiohttp_cors
def get_size(bytes, suffix="B"):
"""
Scale bytes to its proper format
e.g:
1253656 => '1.20MB'
1253656678 => '1.17GB'
"""
factor = 1024
... |
# Copyright 2015 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 a... |
import logging
import os
from pathlib import Path
from typing import Any, Dict
import tabula
from django.conf import settings
from django.core.management import BaseCommand
from django.db import transaction
from associations.models import Association
from base import logic, parsing
from base.middleware import env
fro... |
#############################################################################
# A Simplified DES Program that encrypts in 4 rounds and uses 2 predetermined
# S boxes.
#
# Author: <NAME>
#
# Date: 13 Nov 2021
#############################################################################
import barrel_shift
import random
... |
#!/usr/bin/env python
# -*- coding:UTF-8 -*-
# Copyright (c) 2019 <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 us... |
import torch.utils.data as data
import nibabel as nib
import torch
import numpy as np
import os
from os import listdir
from os.path import join
from PIL import Image, ImageOps
import random
from random import randrange
from scipy.ndimage import zoom
def is_image_file(filename):
return any(filename.endswith(exte... |
"""
Package to quickly instantiate registration models by name.
"""
from __future__ import print_function
from __future__ import absolute_import
from builtins import object
from . import registration_networks as RN
def _print_models(models):
print('\nKnown registration models are:')
print('-------------------... |
import base64, datetime, discord, requests, traceback
from utils.datautils import config, data, default, save_data, set_client
from utils.discordbot import BotClient, send, get_member
from utils.errors import BotError
from utils.lol.api import lol_region, watcher
from utils.lol.utils import lol_current_embed, lol_cu... |
from django.http.response import (
HttpResponseRedirect,
HttpResponseForbidden,
Http404
)
from django.shortcuts import (
get_object_or_404,
render_to_response,
render,
redirect
)
from django.contrib.auth.models import User
from django.core.files.uploadedfile import UploadedFile, InMemor... |
from typing import List, cast
from mypy.output import TypeOutputVisitor
from mypy.nodes import (
Node, VarDef, ClassDef, FuncDef, MypyFile, CoerceExpr, TypeExpr, CallExpr,
TypeVarExpr
)
from mypy.visitor import NodeVisitor
from mypy.types import Void, TypeVisitor, Callable, Instance, Type, UnboundType
from myp... |
""" Cabrillo output generator
This is a generic cabrillo format generator which can be used by the contest
builder to create an output
"""
cbr_file = """START-OF-LOG: 3.0
{fields}
{qsos}
END-OF-LOG:"""
contests = [
"AP-SPRINT",
"ARRL-10",
"ARRL-160",
"ARRL-DX-CW",
"ARRL-DX-SSB",
"ARRL-RR-PH",
... |
import os
import gzip
import datetime
from django.db import IntegrityError, transaction
from fuzzywuzzy import fuzz
from openpyxl import load_workbook
from .transfer_settings import *
from .models import ComponentInformation, TubeInformation, CoreData, ExecutionStats
from .constants import PROJECT_STORAGE
... |
from __future__ import division
from chainer.dataset import dataset_mixin
from abc import ABCMeta, abstractmethod
import os
from PIL import Image
from PIL import ImageOps
import numpy
import six
import skimage.filters
from skimage.color import rgb2lab
from skimage import exposure
import cv2
import time
import typing
f... |
# Copyright (c) The PyAMF Project.
# See LICENSE.txt for details.
"""
Google App Engine ndb adapter module.
"""
import datetime
from google.appengine.ext import ndb
from google.appengine.ext.ndb import polymodel
import pyamf
from pyamf.adapters import util, models as adapter_models, gae_base
NDB_STUB_NAME = 'gae_... |
#!/usr/bin/env python
"""
# Author: <NAME>
# Created Time : Mon 23 Apr 2018 08:25:48 PM CST
# File Name: model.py
# Description:
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn import init
import math
import numpy as np
from itertools import repeat
from sklearn.mixture import Ga... |
#!/usr/bin/env python
"""
_git_tools_
Utils for doing git and github related business
"""
import os
import itertools
import git
import arrow
from cirrus.logger import get_logger
LOGGER = get_logger()
def checkout_and_pull(repo_dir, branch_from, pull=True):
"""
_checkout_and_pull_
Checkout a branch ... |
"""
Tests and benchmarks for this Python implementation of a sensor network.
Not counting other bottlenecks, expect less than around 10000 steps per second, which should be enough for most AI models.
```bash
python3 sensor-network/py/sensornet/test.py
```
Sample run:
```
Tests OK
With 4800 values, throughput: 21439... |
"""
sphinxcontrib.autohttp.flask
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The sphinx.ext.autodoc-style HTTP API reference builder (from Flask)
for sphinxcontrib.httpdomain.
:copyright: Copyright 2011 by <NAME>
:license: BSD, see LICENSE for details.
"""
import re
import itertools
import six
import colle... |
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.utils import weight_norm
def conv3x3(in_planes, out_planes, stride=1):
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
padding=0, bias=True)
class BasicBlock(nn.... |
#!/usr/bin/env python3
# vim: set fileencoding=utf-8 :
"""Generic language modeling with RNN."""
from __future__ import absolute_import, division, print_function
import argparse
from builtins import range
from functools import partial
import glob
import os
import shutil
import time
import numpy as np
# To get rid of... |
# Import python libraries
import argparse, binascii, csv, glob, os, re, string, subprocess
from defines import *
# Get active PE tiles from bitstream and write to file
def get_active_pes(bsfile):
bsname = bsfile[:-4] # remove the file extension
with open(bsfile) as inf, open(f'{bsname}.tiles', 'w') as outf:
... |
import unittest
from peewee import *
from wtforms import fields as wtfields
from wtfpeewee.orm import model_form
from wtfpeewee.fields import *
from wtfpeewee._compat import PY2
if not PY2:
implements_to_string = lambda x: x
else:
def implements_to_string(cls):
cls.__unicode__ = cls.__str__
cl... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Dec 14 14:04:02 2021
@author: christiansaintlouis
"""
import plotly.express as px
import pandas as pd
import streamlit as st
import numpy as np
import time
st.title('Streamlit Final Assignment')
st.write('chsaintlouis Dashboard!')
def load_hos... |
import logging
import asyncio
import pathlib
from typing import List
from uuid import UUID
from bleak.backends.device import BLEDevice
from bleak.backends.dotnet.utils import BleakDataReader
from bleak.backends.scanner import BaseBleakScanner, AdvertisementData
# Import of BleakBridge to enable loading of winrt bindi... |
import os, sys
from urllib import request
from core.exceptions import DependencesFail
def _check_pip():
import subprocess
try:
process = subprocess.Popen(['pip','-V'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
except FileNotFoundError:
if not input('pip no... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
###############################################################################
# $Id$
#
# Project: Icechart STAC Service
# Purpose: Main function - command line interface for creating Ice Chart stac catalogs
# Author: <NAME> <dcurrie at geoanalytic dot com>
#
#########... |
"""
Graph autoencoder models
6 variations:
-gae_l1_sum (aggregation by sum of the features - with 1 layer encoder)
-gae_l2_sum (aggregation by sum of the features - with 2 layers encoder)
-gae_first (aggregation by sum but with first layer output as embedding)
-gae_concat (aggregation by sum but with concatenation of t... |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
from multiprocessing.sharedctypes import Value
import numpy as np
import pandas as pd
from argparse import ArgumentTypeError
from sklearn.pipeline import Pipeline
from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import Or... |
import os
import time
import numpy as np
from PIL import Image
from dataset_loaders.parallel_loader import ThreadedDataset
floatX = 'float32'
class KITTIdataset(ThreadedDataset):
'''The KITTI Vision Benchmark Suite for semantic segmentation
KITTI Vision Benchmark is a dataset [1]_, which provides high-res... |
import argparse
import logging as log
import os
import sys
from io import StringIO
from time import time
import pandas as pd
import psycopg2 as pg
import yaml
from dotenv import load_dotenv
from lib.sql_queries import LOAD_DIM_CITY
from lib.sql_queries import LOAD_DIM_DATE
from lib.sql_queries import LOAD_FACT_DEMO
fr... |
import numpy as np
import torch
import sys
import random
from SIP.common.config import cmd_args
import SIP.debm.model.ebm as ebm
from SIP.debm.data_util.data_loader import get_from_file
from SIP.debm.experiment.rbm_sampling import mmd
from SIP.debm.sampling.sampler import get_sampler
import SIP.debm.sampling.gibbs_samp... |
'create a hierarchical subspace phone-loop model'
import argparse
import copy
import pickle
import sys
import torch
import yaml
import beer
# Create a view of the emissions (aka modelset) for each units.
def iterate_units(modelset, nunits, nstates):
for idx in range(nunits):
start, end = idx * nstates... |
#!/usr/bin/env python3
"""Fetch information about coins and tokens supported by Trezor and update it in coins_details.json."""
import os
import time
import json
import logging
import requests
import sys
import coin_info
import click
LOG = logging.getLogger(__name__)
OPTIONAL_KEYS = ("links", "notes", "wallet")
ALLOW... |
# Copyright 2016 NTT DATA
# 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 b... |
#!/usr/bin/env python3
import numpy as np
import itertools as it
import functools, operator
from itertools_extension import assignments, set_diagrams
from multibody_methods import unit_tensor, random_tensor, multibody_problem, \
sym_state, embed_operator
trans_inv = False
isotropic = False
min_spins = 4
max_spi... |
import sys
import uuid
import gam
from gam.var import *
from gam import controlflow
from gam import display
from gam import gapi
from gam.gapi import directory as gapi_directory
from gam import utils
def delete():
cd = gapi_directory.build()
resourceId = sys.argv[3]
gapi.call(cd.mobiledevices(),
... |
from __future__ import print_function
import os
import cv2
import copy
import json
import numpy as np
from tqdm import tqdm
from keras.layers import *
from keras.models import Model
from bert4keras.layers import Loss
from bert4keras.optimizers import Adam
from bert4keras.backend import keras, K
from bert4keras.models... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.modules.padding import ReplicationPad2d
def conv3x3(in_planes, out_planes, stride=1):
"3x3 convolution with padding"
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1)
class BasicBlock_ss(nn.Module)... |
# -*- coding:utf-8 -*-
"""
File Name: inferece3_RulerDivDet.py
Description : DF第三步:Retinanet工程-标尺及标尺刻度检测
Author : royce.mao
date: 2019/09/02
"""
import argparse
import skimage
import os
import cv2
import tqdm
import time
import torch
import numpy as np
import tensorflow as tf
from util... |
#!/usr/bin/env python3
import argparse
import logging
import socket
import threading
from datetime import datetime as dt
from pathlib import Path
import struct
from fractions import Fraction
import picamera
import pkg_resources
import yaml
import zmq
NUM_STREAMS = 1
PI_NAME = socket.gethostname()
threading.current_t... |
"""Functions for importing and analyzing traffic traces"""
from __future__ import division
import math
import collections
import time
import dateutil
import types
import numpy as np
from scipy.stats import chisquare
from icarus.tools import TruncatedZipfDist
__all__ = [
'frequencies',
'one_timers',
... |
# Copyright 2017. <NAME>. All rights reserved
#
# Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
# following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following
# dis... |
# -*- coding: utf-8 -*-
import logging
import os
import platform
import pprint
import re
import shutil
import copy as py_copy
from collections.abc import Iterable
from collections import OrderedDict
from enum import Enum, unique
from ordered_set import OrderedSet
from enzi.utils import flat_map, rmtree_onerror
logg... |
"""Unit test for cloc code size analysis."""
import os
from unittest.mock import patch, Mock, call, mock_open, ANY
from src.cloc.cloc_code_size import (
calculate_test_code_to_production_code_ratio,
calculate_comment_to_code_ratio,
write_code_size_header,
write_code_size_metrics,
save_code_metrics,... |
#!/bin/bash
import re
import os
import inquirer
from pwd import getpwnam
from grp import getgrnam
from libsw import file_filter, user
disabled_prefix = '''no-pty,no-port-forwarding,no-agent-forwarding,no-X11-forwarding,command="echo 'This key is disabled for this user';echo;sleep 1"'''
def get_keyfile_name(username,... |
"""
Outputing CAM of tiles
Created on 04/21/2020
@author: RH
"""
import argparse
import os
import numpy as np
import cv2
import pandas as pd
import tensorflow as tf
import Panoptes1
import saliency
from tensorflow.python.tools.inspect_checkpoint import print_tensors_in_checkpoint_file
parser = argparse.ArgumentPar... |
# -*- coding: utf-8 -*-
'''
:codeauthor: :email:`<NAME> <<EMAIL>>`
'''
# Import Python Libs
from __future__ import absolute_import, unicode_literals, print_function
# Import Salt Testing Libs
from tests.support.mixins import LoaderModuleMockMixin
from tests.support.unit import TestCase, skipIf
from tests.support.mock... |
import os
import json
import pytest
# Treat all tests as coroutines
pytestmark = pytest.mark.asyncio
SERIES = ['xenial', 'bionic']
CHARM_BUILD_DIR = os.getenv('CHARM_BUILD_DIR', '.').rstrip('/')
# Custom fixtures
@pytest.fixture(scope='module', params=SERIES)
async def osc_apps(request, model):
series = reque... |
"""
Utility classes/functions for the XSS Linter.
"""
import re
def is_skip_dir(skip_dirs, directory):
"""
Determines whether a directory should be skipped or linted.
Arguments:
skip_dirs: The configured directories to be skipped.
directory: The current directory to be tested.
Retu... |
import inspect
import warnings
from typing import Any, Callable, Dict, List, Optional, Set, Tuple, Type, Union, get_type_hints
from pydantic import BaseModel
from pydantic.fields import Undefined
from typing_extensions import TypedDict
from pait.field import BaseField, Depends
from pait.model.core import PaitCoreMode... |
#! /usr/bin/python
import sys, os
import commands
import Annotation_formats
# To enable importing from samscripts submodulew
SCRIPT_PATH = os.path.dirname(os.path.realpath(__file__))
SCRIPT_PATH = os.path.abspath(os.path.join(SCRIPT_PATH, ".."))
sys.path.append(os.path.join(SCRIPT_PATH, 'samscripts/src'))
from fastq... |
import cv2
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import openpyxl
#Get pixel/distance (using ImageJ software) to output actual diameters of circles
dp = 1
accum_ratio = 1
min_dist = 5
p1 = 40
p2 = 30
minDiam = 1
maxDiam = 30
scalebar = 10
min_range = 0
max_range = 100
intervals = 10
ra... |
"""Utilities for SimpleMonitor."""
import datetime
import os
import shutil
import socket
from enum import Enum
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
import arrow
from .envconfig import EnvironmentAwareConfigParser
class MonitorConfigurationError(ValueError):
"""A config error for... |
#!/usr/bin/env python3
"""
Copyright 2020 The Magma Authors.
This source code is licensed under the BSD-style license found in the
LICENSE file in the root directory of this source tree.
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BAS... |
from django.core.exceptions import ValidationError
from django.db import models
from django.db.models import Q
from django.utils.translation import gettext_lazy
from django.utils import timezone
from . import deliverytypes
from .abstract_is_admin import AbstractIsAdmin
from .abstract_is_candidate import AbstractIsCand... |
############## IMPORT LIBRARIES #################
# Python math library
import math
# ROS client library for Python
import rclpy
# Enables pauses in the execution of code
from time import sleep
# Used to create nodes
from rclpy.node import Node
# Enables the use of the string message type
from std_msgs.msg import St... |
import os
import asyncpg
import sqlalchemy
from discord.ext import commands
from discord.ext.commands import MissingRequiredArgument
from discord.ext import ipc
from sqlalchemy.orm import sessionmaker, aliased
import datetime
from src.util.checks import is_admin
from src.model.message import Message
from src.ut... |
# Copyright (c) 2022 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 ap... |
# -*- coding: utf8 -*-
#
# Module CACHE
#
# Part of Nutils: open source numerical utilities for Python. Jointly developed
# by HvZ Computational Engineering, TU/e Multiscale Engineering Fluid Dynamics,
# and others. More info at http://nutils.org <<EMAIL>>. (c) 2014
"""
The cache module.
"""
from __future__ import pr... |
# Copyright © 2017 anfema GmbH. All rights reserved.
import json
import os
from django.core.exceptions import ImproperlyConfigured
from django.urls import reverse
from django.utils.module_loading import import_string
from rest_framework.renderers import JSONRenderer
from wagtail_to_ion.tar import TarWriter, TarData,... |
import ast
import copy
import datetime
import pandas as pd
def smoothen_triplegs(triplegs, method='douglas-peucker', tolerance=1.0):
"""reduces number of points while retaining structure of tripleg
Parameters
----------
triplegs: shapely file
triplegs to be reduced
method: method used to ... |
from __future__ import annotations
from pathlib import Path
from typing import TYPE_CHECKING
from random import uniform, randint
from uuid import uuid4
import jinete as jit
if TYPE_CHECKING:
from typing import (
Set,
Type,
Optional,
)
def generate_one_surface(*args, **kwargs) -> jit... |
# import scipy as sp
# import matplotlib.pyplot as plt
# import numpy as np
# from mpl_toolkits.mplot3d import Axes3D
# from scipy.interpolate import splprep, splev, interp2d
# def generate_curve(x, y, z):
# tck, _ = splprep([x,y,z], s=0, k=1) # Generate function out of provided points, default k = 3
# unew =... |
import datetime
import logging
from dataclasses import dataclass
from typing import ClassVar
import geopandas as gpd
import numpy as np
import pandas as pd
import xarray as xr
from power_perceiver.consts import BatchKey, Location
from power_perceiver.load_prepared_batches.data_sources.prepared_data_source import Nump... |
import os
import shutil
import unittest
from mock import MagicMock, call
from malcolm.compat import OrderedDict
from malcolm.core import (
Context,
Part,
PartRegistrar,
Process,
StringMeta,
Widget,
config_tag,
)
from malcolm.modules.builtin.controllers import ManagerController, StatefulCon... |
#
# Copyright 2020 GoPro Inc.
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 ... |
#!/usr/bin/env python3
## compiler.py
# A compiler to convert renderer function calls into a compact, ASCII-printable,
# bitstream.
#
# The instructionset which is used is as follows:
# * 1 box(down_x, down_y, down_z, up_x, up_y, up_z);
# * 000 sphere(center_x, center_y, center_z, radius);
# * 001 cilind... |
# storage.py
#
# This file is part of scqubits.
#
# Copyright (c) 2019, <NAME> and <NAME>
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
###############################################################... |
from discord.ext import commands, tasks
import asyncio
import random
from ...core import sqcs_module as sm
from ...core.db.jsonstorage import JsonApi
from ...core.db.mongodb import Mongo
from ...core.utils import Time, DiscordExt
from ...core.cog_config import CogExtension
from ...core.fluctlight_ext import Fluct
impor... |
import os
from utils.file import load_from_json
from utils.model import load_lenet
import numpy as np
from utils.model import load_pool
from utils.metrics import error_rate, get_corrections
from models.athena import Ensemble, ENSEMBLE_STRATEGY
def generate_ae(model, data, labels, attack_configs, save=False, output_d... |
import io
import zipfile
from django import forms
from django.core.exceptions import PermissionDenied
from django.http import Http404, FileResponse, HttpResponseBadRequest, HttpResponse
from django.shortcuts import render, redirect, resolve_url, get_object_or_404
from django.urls import reverse_lazy
from django.utils.c... |
import torch
import torch.nn as nn
import torch.nn.functional as F
def conv_bn_act(inp, oup, kernel_size=3, stride=1, padding=1):
return nn.Sequential(
nn.Conv2d(inp, oup, kernel_size, stride, padding, bias=False),
nn.BatchNorm2d(oup),
nn.PReLU(oup)
)
def bn_act(inp):
return nn.Se... |
import argparse
import numpy as np
import os
import pandas as pd
from tqdm import tqdm
import yaml
import torch
import torch.nn as nn
from torch.utils.data import DataLoader
from torch.utils.data.sampler import SequentialSampler, RandomSampler
from mean_average_precision import MetricBuilder
from models import SiimCo... |
from collections import OrderedDict
import torch as T
import torch.nn as nn
from torch._six import container_abcs
import sympy as sp
from .. import utils
__all__ = ['wrapper', 'Sequential', 'Lambda', 'Module', 'MultiSingleInputModule', 'MultiMultiInputModule',
'SingleMultiInputModule']
class _LayerMetho... |
# -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making BK-LOG 蓝鲸日志平台 available.
Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved.
BK-LOG 蓝鲸日志平台 is licensed under the MIT License.
License for BK-LOG 蓝鲸日志平台:
------------------------------------------------... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2019 Red Hat, Inc.
#
# Licensed under the Apache License, Version 2.0 (the 'License'); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requir... |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... |
import datetime
import logging
import shlex
import subprocess
import sys
import time
from typing import Sequence, Dict
import click
from lib.amazon import as_client, target_group_arn_for, get_autoscaling_group
from lib.ce_utils import describe_current_release, are_you_sure, logger, \
wait_for_autoscale_state, set... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import datetime
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.utils import timezone
from app.core.models import Customer
from app.task.models import SendTask
from app.address.models import MailList
from ... |
# The script builds the LaTeX documentation.
# Testing:
# python mklatex.py latex .. 1.0
from docstructure import SITE_STRUCTURE, BASENAME_MAP
import os, shutil, re, sys, datetime
TARGET_FILE = "lxmldoc.tex"
RST2LATEX_OPTIONS = " ".join([
# "--no-toc-backlinks",
"--strip-comments",
"--language en",
# ... |
import os
from preprocessing.caselaw_stat_corpus import preprocess_label_file, count_words
from analysis.caselaw_compare_bm25_dpr import read_in_run_from_pickle, remove_query_from_ranked_list, evaluate_weight
from analysis.diff_bm25_dpr import first_diff_analysis, write_case_lines, get_diff_query_ids, compare_overla... |
# -*- coding: utf-8 -*-
"""
TODO move permission checks to the dispatch view thingee
"""
import math
from django.contrib import messages
from django.urls import reverse
from django.forms import Form
from django.http import HttpResponseForbidden
from django.http import Http404
from django.utils.functional import cached... |
# authors: <NAME>
# date: 2020-03-02
"""
The pypuck functions are used as wrapper functions to call the NHL.com
publicly available API's.
"""
import requests
import pandas as pd
import altair as alt
from pypuck.helpers import helpers
def player_stats(start_date=None, end_date=None):
"""
Query the top 100 pl... |
#!/usr/bin/env python
import os
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider
import lmfit
import ilmfit # interactive plotting of lmfit models
fname = 'data/A344/raw/A344_GdN_FC_050_Oe_160908.rso.raw'
raw_data_fc = np.genfromtxt(fname,
delimiter = ','... |
"""
==============================
BASIN-3D REST APIs
==============================
.. currentmodule:: basin3d
:platform: Unix, Mac
:synopsis: All BASIN-3D REST API calls are read-only (GET). The browsable API may be accessed at the root URL of the application.
:module author: <NAME> <<EMAIL>>
:module author: <NAME> ... |
# coding=utf-8
# Copyright 2021 The Google Research Authors.
#
# 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 applicab... |
import random
import re
import six
from geodata.address_expansions.gazetteers import *
from geodata.encoding import safe_decode, safe_encode
from geodata.text.tokenize import tokenize_raw, token_types
from geodata.text.utils import non_breaking_dash_regex
LOWER, UPPER, TITLE, MIXED = range(4)
def token_capitalizat... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.