text stringlengths 3.07k 12.6k |
|---|
import torch
from torch import nn, optim
import torch.nn.functional as F
from torch import nn, optim
from baseline_config import setup_seed
setup_seed(667)
class Encoder(nn.Module):
def __init__(self):
super(Encoder, self).__init__()
self.embedding = nn.Embedding(10, 5)
self.gr... |
# -*- coding: utf-8 -*-
#
# This file is part of PyBuilder
#
# Copyright 2011-2020 PyBuilder Team
#
# 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/l... |
#!/usr/bin/env python
from pygecko.Messages import Twist, Image, IMU, Joystick, Vector, Array, Dictionary
from pygecko.Messages import Pose, Compass, Range, Quaternion
from pygecko.Messages import Buttons, Axes
from pygecko.Messages import serialize, deserialize
# from pygecko.lib.ZmqClass import Pub, Sub
import numpy... |
"""
BSD 3-Clause License
Copyright (c) 2018, <NAME>, Aalto University, Finland
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, t... |
import cv2
import csv
import numpy as np
import os
from datetime import datetime
import sys
import pyrebase
from getTotalLectureCount import *
from RealTimeDB import *
from get_yml import *
from fractions import Fraction
firebaseConfig = {
'apiKey': "<KEY>",
'authDomain': "proxy-detection-1df22.firebaseapp.c... |
import os
import json
import multiprocessing
from tqdm import tqdm
import numpy as np
from PIL import Image
import functools
def label_iterator(label):
for floor_id, floor_data in label['merger'].items():
for complete_room_id, complete_room_data in floor_data.items():
for partial_room_id, part... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import json
import tldextract
from urlparse import urlparse
import re
magic_number = "df6fa1abb58549287111ba8d776733e9"
def make_full_path(crawl, folder, filename):
return "https://aws-publicdatasets.s3.amazonaws.com/" +\
"common-crawl/crawl-dat... |
"""
Encrypted Credentials Manager
"""
from tokenize import group
import toga
from toga.style import Pack
from toga.style.pack import COLUMN, ROW, CENTER
from lockin.manager import CredentialsManager
from lockin.styles import Styles
from lockin.validators import not_null
from lockin.exceptions import ServiceAlreadyExis... |
#!/usr/bin/env python
import os
from distutils.dep_util import newer_group, newer
from os.path import join
#-------------------
# To skip wrapping single precision atlas/lapack/blas routines, set
# the following flag to True:
skip_single_routines = 0
# Some OS distributions (e.g. Redhat, Suse) provide a blas library... |
import os
from pathlib import Path
from typing import Tuple
import click
import numpy as np
import pandas as pd
import pytorch_lightning as pl
import torch
from box import Box
from models.dataset import CustomDataModule, CustomDataset
from models.model import Model, inference
from pytorch_lightning import callbacks
fr... |
import tensorflow as tf
import tensorlayer as tl
from tensorlayer.layers import *
EPSILON = 1e-20
def get_initialized_session():
sess = tf.Session()
sess.run(tf.global_variables_initializer())
return sess
def TFBinaryCrossEntropy(predict, label, epsilon=EPSILON):
assert label.shape == predict.shape
... |
import json
import os
import re
from itertools import groupby
from pathlib import Path
def run(spec_path):
with open(spec_path) as f:
spec = json.load(f)
out_path = (
Path(os.path.abspath(__file__)).parents[1] / "analysis" / "add_groupings.py"
)
with open(out_path, "w") as f:
... |
from future.moves.urllib.parse import urlparse
import re
import scrapy
from astatsscraper.items import AstatsSteamappItem
from astatsscraper.items import OwnedAppItem
from astatsscraper.items import SteampoweredSteamappItem
def parse_app_page(response):
# Extract app id from URL
app_id = int(response.url[len(... |
# -*- coding:utf-8 -*-
from encodings import utf_8
from pickle import FALSE
from select import select
from telegram import Update
from telegram.ext import CallbackContext
import redis
import random
c_OPPORTUNITIES: int = 2
c_TIMEOUT: int = 120
c_WORDS: list[str] = ['很', '非常', '超', '超级', '想变得']
def welcome(update: Up... |
import ast
import os
from flask import json
class Config(object):
DEBUG = True
REGIONS = json.loads(os.getenv('REGIONS', '{}'))
BATCH_NODE = ast.literal_eval(os.getenv('BATCH_NODE', 'False'))
SQLALCHEMY_DATABASE_URI = os.getenv('SQLALCHEMY_DATABASE_URI')
SQLALCHEMY_TRACK_MODIFICATIONS = ast.lite... |
import paddle
import paddle.fluid as fluid
def get_strategy(args):
"""
根据配置,返回相应的学习率变化策略
:return: 学习率变量(Vars)
"""
STRATEGY = args["learning_rate_strategy"]
strategies = {
"exponential_decay": get_exponential_decay_lr,
"natural_exp_decay": get_natural_exp_decay_lr,
"noa... |
from nose.tools import assert_raises
from kernel_exp_family.estimators.lite.gaussian import KernelExpLiteGaussian
from kernel_hmc.densities.gaussian import IsotropicZeroMeanGaussian
from kernel_hmc.proposals.hmc import HMCBase
from kernel_hmc.proposals.kmc import KMCStatic
from kernel_hmc.tools.assertions import asse... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
test_pyspd
----------------------------------
Tests for `pyspd` module.
"""
import pytest
from pyspd import *
def setup_function(function):
operator = SystemOperator()
company = Company("company")
RZ = ReserveZone("RZ", operator)
node = Node("node", ... |
# Copyright (c) 2018, MD2K Center of Excellence
# - <NAME> <<EMAIL>>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, th... |
from pathlib import Path
import math
import numpy as np
import matplotlib.pyplot as plt
import torch
import torchvision
import pytorch_lightning as pl
from typing import Tuple, Iterable, Optional, Union, List
import warnings
from reprlearn.utils.misc import info
from reprlearn.data.transforms.functional import unnorma... |
import os
import numpy as np
import copy
import math
from ase.md.md import MolecularDynamics
from ase.optimize.optimize import Dynamics
from ase.md.npt import NPT
from ase import units
from ase.md.velocitydistribution import (MaxwellBoltzmannDistribution,
Stationary, ZeroRotatio... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Mar 23 10:06:33 2020
@author: tsuyogbasnet
"""
import os
from tqdm import tqdm
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from scipy.io import wavfile
from python_speech_features import mfcc, logfbank
import librosa
#calcu... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Utils: Various utilities methods.
"""
__author__ = "<NAME>"
__copyright__ = "Copyright 2014"
__license__ = ""
__version__ = "0.1"
__maintainer__ = ""
__email__ = ""
__date__ = "December 2014"
__status__ = "Development"
import logging
import math
import re
def _init_lo... |
# Copyright (C) 2020-2020 <NAME>. All rights reserved.
# Copyright (C) 2016-2019 Semtech (International) AG. All rights reserved.
#
# This file is subject to the terms and conditions defined in file 'LICENSE',
# which is part of this source code package.
from typing import cast, Any, Dict, Generator, List, Optional, S... |
# -*- coding: UTF-8 -*-
import os
import codecs
import numpy as np
from keras.models import Input, Model
# from keras_bert.layers import Extract
from keras.layers import Add, Embedding, Average, Maximum, Concatenate, Lambda
# https://github.com/CyberZHG/keras-xlnet
# https://github.com/CyberZHG/keras-transf... |
import pdb
import cv2
import torch
import torch.nn as nn
import torch.nn.functional as F
import math
import numpy as np
def flatten_two(x):
return x.view(-1, *x.shape[2:])
def unflatten_two(x, sh1, sh2):
return x.view(sh1, sh2, *x.shape[1:])
def get_camera_parameters(env_name, obs_shape):
# Note: obs_sh... |
#!/usr/bin/python3
#-*- coding: utf-8 -*-
# This code is PEP8-compliant. See http://www.python.org/dev/peps/pep-0008/.
"""
Wyrd In: Time tracker and task manager
CC-Share Alike 2012 © The Wyrd In team
https://github.com/WyrdIn
This module implements parsers for entities used in the program. A parser is
understood as ... |
#!/usr/bin/env python3
import cbor
class DirtyBlocks:
def __init__(self):
self.dirty_blocks = []
def put(self, value):
self.dirty_blocks.append(value)
return len(self.dirty_blocks) - 1
def get(self, offset):
return self.dirty_blocks[offset]
def __len__(self):
... |
#!/usr/bin/env python3
# -*- coding: utf-8
"""
Created on 2018/12/9
@author yrh
"""
import torch
import torch.nn as nn
from deepxml.modules import *
from deepxml.lib.embeddings import get_vectors
from deepxml.lib.mathops import get_appx_inv, circular_conv, complexMagProj
__all__ = ['AttentionRNN', 'FastAttentionRN... |
# -*- coding: utf-8 -*-
#
# Copyright 2017-2019 - Swiss Data Science Center (SDSC)
# A partnership between École Polytechnique Fédérale de Lausanne (EPFL) and
# Eidgenössische Technische Hochschule Zürich (ETHZ).
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in c... |
import torch
import numpy as np
from typing import Union, List
from scipy.linalg import inv
from ...utils import get_device, GraphInput
def compute_ppr(edge_index, alpha=0.2, self_loop=True):
adj = torch.sparse_coo_tensor(edge_index, torch.ones(edge_index.shape[1])).to_dense()
if adj.shape[0] > 20000:
... |
'''
Created on 23.01.2020
@author: <NAME>
'''
import smbus2
from threading import Lock
class Tca9548A(object):
'''
handles communication and setup of a TCA9548A
'''
def __init__(self, i2cBus = None, address = 0x70):
'''
Constructor
'''
self.address = address
if... |
import numpy as np
from sklearn import metrics, preprocessing
from sklearn.preprocessing import MinMaxScaler
from sklearn.decomposition import PCA
from sklearn.model_selection import train_test_split
from sklearn.metrics import confusion_matrix, accuracy_score, classification_report, cohen_kappa_score
from operator imp... |
from chromedriverService import BrowserFromService, Keys, msg
from copypaste import write_to_clipboard, read_from_clipboard
from time import sleep
from selenium.webdriver import ActionChains
import requests
#B = BrowserFromService(headless = True)
#B.get('http://localhost:8080/_ah/login')
def login():
B.get('htt... |
#!/usr/bin/env python
# coding: utf-8
"""
Process citations and retrieve metadata
"""
import json
import re
import os
import pathlib
import subprocess
import textwrap
import pandas
from citations import (
citation_to_metadata,
citeproc_passthrough,
get_brackets_without_reference,
get_references_from_... |
from __future__ import absolute_import, division, print_function
import os
from mmtbx.command_line import geometry_minimization
from libtbx.utils import Usage
from six.moves import cStringIO as StringIO
def parse_user_mods(filename):
flipped_residues = []
f = open(filename, 'rb')
for line in f.readlines():
... |
from django.db import models
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
from django.core.exceptions import ValidationError
from respa_outlook.manager import store, ToEWSDateTime
from exchangelib import CalendarItem, Mailbox, Attendee, EWSTimeZone
from exchangelib.propertie... |
from fields import Field, RelatedObject, _novalue
from stdnet.exceptions import *
from stdnet import pipelines
from stdnet.utils import ModelFieldPickler
class MultiField(Field):
'''Virtual class for data-structure fields:
* *model* optional :ref:`StdModel <model-model>` class.
* *related... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import utils, branching, reduction, compression
from time import time
import networkx as nx
import sys
import os
def eprint(*args, **kwargs):
#return
print(*args, file=sys.stderr, **kwargs)
start = time()
def timestamp(s):
eprint("time({}): {}".format(s, time()... |
import json
import logging
import sys
from os import path
from random import Random
from pathlib import Path
sys.path.append(path.abspath('..'))
from DataHandler.ApiClient import ApiClientClass
from DataGenerator.Distributions import days_random_distribution
from DataGenerator.Generator import data_generation
from Mo... |
from matplotlib import pyplot
from python_speech_features import mfcc, logfbank
import numpy
class Segment:
"""Segment represents an interval within a longer recording in which a speaker
can be identified. This object provides several methods of acoustic analysis."""
def __init__(self, recording, speaker... |
'''
Generate markdown documentation from code source.
python code_parser.py repo --in_path parser/test3 --out_path parser/output/output_repo.csv
python generate_doc.py markdown --repo_stat_file parser/output/output_repo.csv --output parser/output/doc_repo.md --prefix "https://github.com/... |
"""adds models 2.0
Revision ID: a7882a87de99
Revises: <PASSWORD>
Create Date: 2022-03-03 21:50:30.137666
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
# revision identifiers, used by Alembic.
revision = 'a7882a87de99'
down_revision = '<PASSWORD>'
branch_labels = None
d... |
import numpy as np
import json
import os
import itertools
import trimesh
from matplotlib.path import Path
from collections import Counter
from sklearn.neighbors import KNeighborsClassifier
def load_segmentation(path, shape):
"""
Get a segmentation mask for a given image
Arguments:
path: path to th... |
import numpy as np
from PIL import Image
import torch
from torch import nn
import torch.nn.functional as F
from torchvision import transforms, datasets, models
from torch import optim
class Network(nn.Module):
"""Neural Network"""
def __init__(self, input_units, output_units, hidden_units, drop_p=0.5):
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# <NAME> 2013-12-20
# 获取并整合 CssGaGa 更新日志
#
# 2014-04-10
# 改为 python 3.4
#
from __future__ import unicode_literals
import os
import sys
import subprocess
import re
import codecs
import json
import argparse
changelog = 'CHANGELOG.txt' # 整合的日志
currenttxt = 'current.txt' ... |
"""Python implementation of Fatigue state transition."""
from dataclasses import dataclass
import numpy as np
@dataclass
class FatigueParams:
"""Parameters for Fatigue dynamics."""
action_tolerance: float = 0.05
amplification: float = 1.1
amplification_max: float = 5.0
amplification_start: float... |
import os
import torch
import pretrainedmodels
import albumentations
import numpy as np
import pandas as pd
import torch.nn as nn
from apex import amp
from sklearn import metrics
from torch.nn import functional as F
from wtfml.data_loader.image import ClassificationLoader
from wtfml.engine import Engine
from wtfml... |
from helper import *
def filter_on_cat(cands, act_cat):
idx = -1
for k, (umls, scr) in enumerate(cands):
pred_cat = umls2type.get(umls, set())
if len(pred_cat & act_cat) != 0:
idx = k
sel_cand = cands[idx][0]
return sel_cand, idx, pred_cat
return None, idx, None
def get_pred(model_res, _id):
if ... |
from flask import Flask, escape, Response, json
import requests
import time
import datetime
import os
import csv
home_file_dir=str(os.path.expanduser("~"))+"/.cache/"
if not os.path.isdir(home_file_dir):
try:
os.mkdir(home_file_dir)
except OSError:
print("ERROR: cant create Directory "+str(home... |
from pymt_cshore import cshoremodel
import numpy as np
import traceback
import sys
import csv
def CollectIndividualVarInfo(model_bmi, var_name):
data_type = model_bmi.get_var_type(var_name)
grid_id = model_bmi.get_var_grid(var_name)
grid_rank = model_bmi.get_grid_rank(grid_id)
grid_shape = np.ndarray(... |
# Runs our pruning method on a hierarchical SBM with 3 and 9 block ground truths
import igraph as ig
import matplotlib.pyplot as plt
import numpy as np
import louvain
from modularitypruning.champ_utilities import CHAMP_2D
from modularitypruning.louvain_utilities import repeated_parallel_louvain_from_gammas
from modula... |
import os
import sys
import uuid
import json
import pickle
import base64
import types
import functools
import cloudpickle
import requests
PROXY_URL = os.environ.get('PYSPARK_PROXY_URL', 'http://127.0.0.1:8765')
def _copy_func(f):
g = types.FunctionType(f.func_code, f.func_globals, name=f.func_name,
... |
from distutils.command.clean import clean
import os
import sys
import re
import codecs
import numpy
from setuptools import setup, Extension, find_packages
try:
import mpi4py
except ImportError:
sys.stderr.write('You must install mpi4py first!\n')
sys.stderr.flush()
sys.exit(-1)
if sys.version_info[:2] ... |
# Copyright (c) 2016 Rackspace, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wr... |
"""
These are where the water balance calcuations take place
"""
from __future__ import absolute_import, division, print_function, unicode_literals
import arcpy
from arcpy.sa import *
def calc_avail_water(path, path2, months='' ,years=''):
arcpy.env.workspace = path
arcpy.env.overwriteOutput = True
if ... |
# -*- coding: utf-8 -*-
"""
Created on Mon Mar 2 20:10:35 2020
@author: khaled.ghobashy
"""
import numpy as np
import numba
class integrator(object):
def __init__(self, SSODE, y0, t0, t_end, h, **kwargs):
self.SSODE = SSODE
self.h = h
self.t = t0
def step(self):
raise NotI... |
import os.path as osp
import sys
from tqdm import tqdm
import math
import numpy as np
import random
import mmcv
cur_dir = osp.dirname(osp.abspath(__file__))
sys.path.insert(0, osp.join(cur_dir, "../../../../"))
from lib.pysixd import inout, misc, transform
import ref
from lib.utils.utils import dprint
random.seed(23... |
"""
Training, evaluation and visualization functions
"""
import math
import os
#import sys
from typing import Iterable
from PIL import Image
import numpy as np
import torch
def train_one_epoch(model: torch.nn.Module, criterion: torch.nn.Module,
data_loader: Iterable, optimizer: torch.... |
#!/usr/bin/env python3
import argparse
import logging
import re
import time
import aniffinity
import unicodecsv as csv
from . import const
from . import sources
DEFAULTS = const.DEFAULTS
# Version
__version__ = const.VERSION
# Set up the logger
logging.basicConfig(format=const.LOGGING_FORMAT, level=logging.INFO... |
"""This script generates the plots for the invocation patterns experiment (exp3).
Formerly called workload types.
It is based on workload_types.py which plots many more aspects."""
# %% Imports
from sb_importer import *
# %% Helper methods
def app_request_type_label(app, request_type) -> str:
return f"{app}\n({r... |
## @file aquamentus.py
# @title Aquamentus Boss
# @author <NAME>, <NAME>, <NAME>
# @date November 8 2018
import random
from .boss import *
from .constants import *
from .fireball import *
from .spritesheet import *
from .item import *
from config.window import *
# Sets spritemap to the proper sprite file for the bos... |
from __future__ import annotations
from enum import Enum
from typing import TYPE_CHECKING, Tuple
from sqlalchemy import (
NUMERIC,
Boolean,
Column,
DateTime,
ForeignKey,
Index,
Integer,
PrimaryKeyConstraint,
String,
func,
)
from sqlalchemy.dialects.postgresql import JSONB, UUID... |
# -*-*- encoding: utf-8 -*-*-
#
# gateway4labs is free software: you can redistribute it and/or modify
# it under the terms of the BSD 2-Clause License
# gateway4labs is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PA... |
"""Functions to convert tabular data to popular python graph structures
"""
import os
def to_igraph(vdf, edf, pmax, comms=None, peak=None, save_dir=None, ext='gml'):
"""Convert Data from (Geo)DataFrames to python-igraph's Graph class
Each commodity gets its own graph.
Weights are derived from built capaci... |
# Copyright (c) 2013-2016 <NAME>
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from ._pylib import ffi, lib
from .arm import ARMCore
from .core import Core, needsRes... |
import logging
from log import logging_conf
import numpy as np
import matplotlib.pyplot as plt
from brica import Component, VirtualTimeScheduler, Timing
from matchernet.ekf import BundleEKFContinuousTime, MatcherEKF
from matchernet import fn
from matchernet import observer
from matchernet.state_space_model_2d import S... |
from itertools import zip_longest
from openpyxl.utils import get_column_letter, column_index_from_string
from openpyxl.styles import Border, Side, PatternFill, Font, GradientFill, Alignment
from global_variables import *
THIN = Side(border_style="thin", color="000000")
def insert_pa_np_row(sheet_obj, provider, iov_t... |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import time
from typing import Any, Dict, List, Tuple
from parlai.core.worlds import validate
from parlai.crowdsourcing... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Mar 29 10:34:44 2021
@author: Pablo
"""
import requests
import json
import os
import requests.exceptions
from Authorizer import TokenGenarator
TokenGen = TokenGenarator('identifier','password')
'''
enTranslationModelId=smt-4eafabb9-7cd6-4ae6... |
# cache hit -> read, renew counter
# cache miss -> read from memory and write cache
# cache update(upon memory update) -> renew
# cache write(upon store to memory) -> write to cache
# cache full -> kick LRU line
# read through cache
# write through cache
# fifo
import datetime
import logging
from .mfr import OpCodeErr... |
"""
Copyright (C) 2018-2020 Intel Corporation
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 i... |
#!/usr/bin/python
# Copyright (c) 2018, Oracle and/or its affiliates.
# This software is made available to you under the terms of the GPL 3.0 license or the Apache 2.0 license.
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# Apache License v2.0
# See LICENSE.TXT for detail... |
import os
from random import randint
from subprocess import Popen, PIPE, STDOUT
from xml.etree import ElementTree
from django.conf import settings
from video_upload import utils
from video_upload.utils import VideoUtils, TimeUtils, ImageUtils
class ProcessState(object):
def __init__(self, name, process):
... |
from api import send_message, send_chat_action
import requests
import json
PLAYERS = {
14160874: "bertoncio",
16631085: "beaea",
85867003: "raulg0bbi",
52451934: "xthedgehog",
10549434: "axasdas",
123123862: "MeroFabio",
569341881: "burnovisk",
299335806: "springl3s"
}
... |
"""Custom Django FILE_STORAGE that saves files in the database."""
# python
import base64
import os
# third party
from django.apps import apps
from django.core.files.base import ContentFile
from django.core.files.storage import Storage
from django.db.models import BinaryField
from django.utils.crypto import get_random... |
import firedrake as fe
import sapphire.test
import sapphire_ice.simulation
datadir = sapphire.test.datadir
def heat_driven_cavity_variational_form_residual(sim, solution):
mass = sapphire.simulations.convection_coupled_phasechange.\
mass(sim, solution)
stabilization = sapphire.simulations.... |
#!/usr/bin/env python3
# coding: utf-8
#
# $Id: testcli_2.py 1306 $
# SPDX-License-Identifier: BSD-2-Clause
"""
some tests
"""
import collections
import random
import math
from dataclasses import dataclass
from pprint import pprint
import constants
MIN_DISTANCE = 20
class PriceSlip:
""" for each good, calcul... |
# coding=utf-8
import datetime
import calendar
from django.db.models import Count, Sum
from apps.core.models import CustomerSummary
from apps.mail.models import get_mail_model
from apps.collect_mail.models import get_mail_model as get_mail_model2
# 邮件实际状态和显示给用户的状态不同
STATE_RELATE = {
'check': 'analysis',
'revi... |
"""
generate plate numbers
"""
import numpy as np
import cv2, os
from glob import glob
# 车牌中包含的所有省份汉字
provinces = ["京", "津", "冀", "晋", "蒙", "辽", "吉", "黑", "沪",
"苏", "浙", "皖", "闽", "赣", "鲁", "豫", "鄂", "湘",
"粤", "桂", "琼", "渝", "川", "贵", "云", "藏", "陕",
"甘", "青", "宁", "新", "港", "澳",... |
'''
central location for audio manipulation library.
requires mutagen to be installed (see pypi mutagen)
kjg190622: check if LoadMetaData works with AAC or non mp3 files. - just mp3 (190701)
kjg190623: gonna need to make a custom library for m4a files, in order to
convert without issue
'''
import os,sys
from shut... |
# -*- coding: utf-8 -*-
# Copyright (c) 2021, <NAME>
# All rights reserved.
#
# This software may be modified and distributed under the terms
# of the BSD license. See the LICENSE file for details.
from aniso8601.builders import TupleBuilder
from aniso8601.builders.python import PythonTimeBuilder
from aniso8601.comp... |
"""
Copyright 2019 <NAME>.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distribut... |
#!/usr/bin/python
# 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
# "Licens... |
"""
time: 2020/7/3
author: best_yzw
aim: 逐条检测网盘分享链接的可用性,如果不可用,输出相关提示
"""
# 网黑哥资源合集: https://mp.weixin.qq.com/s/hPgmL2WOU9iJWAqnl8CMsQ
# 某资源
# 百度云: https://pan.baidu.com/s/1PDxlvzYu9QOaMOY7ekFi1Q
# 密码: <PASSWORD>
# 蓝奏云: https://www.lanzous.com/b384810/
# 密码: <PASSWORD>
# 百度云失效链接: https://pan.baidu.com/s... |
import unittest # Importing the unittest module
from user import User,Credential # Importing the user class
class TestUser(unittest.TestCase):
'''
Test class that defines test cases for the user class behaviours.
Args:
unittest.TestCase: TestCase class that helps in creating test cases
'''
def tearDown(self):... |
#!/usr/bin/env dls-python2.7
"""
A simulation of the I10 fast chicane straight.
Simulates the effect of the chicane magnets on the electron beam, and the
resultant photon beams.
The straight is controller by eithier a SimModeController or a
RealModeController.
"""
import numpy as np
import scipy.constants
import s... |
import re
from helpers import *
KNOWN_DECODERS = [
'maybe',
'list' ,
'int' ,
'float' ,
'bool',
'string' ]
JSON_DECODE = 'Json.Decode.'
JSON_ENCODE = 'Json.Encode.'
def get_type_alias_name(string):
grab_type_name = re.search('type alias(.+)\=', string)
if grab_type_name is None or l... |
import re
import time
import uuid
from datetime import datetime, timedelta
from django.db import models
from django.conf import settings
from django.utils import timezone
import pylast
import pytz
from apiclient.discovery import build # pylint: disable=import-error
import log
DEFAULT_LOCATION = (-48.876667, -123.3... |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import os
import argparse
from time import time
import numpy as np
import scipy as sp
import scipy.misc as spm
import cma
from cma.constraints_handler import BoundTransform
from cma import fitness_transformations as ft
from keras.applications import ResNet50
from keras.models ... |
import os
import cv2
import numpy as np
from math import exp, sqrt
import sys
from charts import draw_comp_hist
def _def_operation(window, *args, **kwargs):
return round(window.sum() / window.size)
def basic_filter(src, window_size, operation=_def_operation):
rows, cols = src.shape[:2]
out = np.empty(... |
"""
Copyright Declaration (C)
From: https://github.com/leeykang/
Use and modification of information, comment(s) or code provided in this document
is granted if and only if this copyright declaration, located between lines 1 to
9 of this document, is preserved at the top of any document where such
information, co... |
import math
from os import set_inheritable
ex1 = [
'[[[[4,3],4],4],[7,[[8,4],9]]]',
'[1,1]'
]
ex2 = [
'[1,1]',
'[2,2]',
'[3,3]',
'[4,4]'
]
ex3 = [
'[1,1]',
'[2,2]',
'[3,3]',
'[4,4]',
'[5,5]'
]
ex4 = [
'[1,1]',
'[2,2]',
'[3,3]',
'[4,4]',
'[5,5]'... |
#!python3
import argparse
import matplotlib.cm as cm
import matplotlib.pyplot as plt
import os
import pandas as pd
import warnings
plt.style.use(os.path.join('scripts', 'matplotlibrc'))
# Ignore warnings
warnings.filterwarnings( "ignore")
# Argparse
parser = argparse.ArgumentParser()
parser.add_argument('-p', '--pap... |
# -*- coding: utf-8 -*-
from lxml import etree
import datetime
import tzlocal
import dateutil.parser
from . import soxtimestamp
from bs4 import BeautifulSoup
SENSOR_META_ATTRS = ('name', 'id', 'type', 'description', 'serialNumber')
META_TRANSDUCER_ATTRS = (
'name', 'id', 'units', 'unitScalar', 'c... |
"""Wizit directory tree comparison report
Given a base path and a delta path produce a report that shows new files, removed files and differences in
same files.
Usage: wizit.py [options] {base path} {delta path}
Options:
-h, --help show this help message and exit
-o HTMLPATH, --output=HTMLPATH
... |
import argparse
import os
import zipfile
import cv2
import flwr as fl
import numpy as np
import sklearn
import tensorflow as tf
import wget
from tensorflow.keras.utils import to_categorical
# Make TensorFlow logs less verbose
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3"
class_encoding = {'COVID': 0, 'Normal': 1, 'Viral... |
# coding utf-8
import argparse
import prettytable
import WorkToolkitDB
import re
import datetime
#get opt
parser = argparse.ArgumentParser()
parser.add_argument('operate', metavar='operate_type', type=str, choices=['s','u','a','d'], default='s', help='s: show ; u: update ; a: add ; d: delete')
parser.add_argument('-... |
#!/bin/env/python
# -*- encoding: utf-8 -*-
"""
Ray helper functions
"""
from __future__ import division, print_function
import os
import subprocess
import time
import ray
ray_args = {
"redis_address" : ("--redis-address", str),
"num_cpus" : ("--num-cpus", int),
"num_gpus" ... |
import os
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
from tensorflow.keras.preprocessing.image import load_img, img_to_array
import math
import numpy as np
def get_files(folder_path):
file_names= os.listdir(folder_path)
count= len(file_names)
file_paths= [os.path.join(folder_path,... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.