text stringlengths 3.07k 12.6k |
|---|
#python
import lx, lxu, modo, traceback
NAME_CMD = "neatFreak.cleanupShaderTree"
# Returns a list of all mesh layers containing any of the provided pTag(s)
# of type i_POLYTAG, e.g. lx.symbol.i_POLYTAG_MATERIAL.
# pTag can be a tag or list of tags.
def get_layers_by_pTag(pTags,i_POLYTAG=lx.symbol.i_POLYTAG_MATERIAL)... |
from binance_f import RequestClient
from binance_f.model import *
from binance_f.constant.test import *
from binance_f.constant.system import Proxies
from datetime import datetime
from dateutil.relativedelta import relativedelta
import requests
import pandas as pd
from pprint import pprint
RECORDS_DIR = 'records'
CA... |
#!/usr/bin/python3
import chess
from chess import Board
import math
import pieceMap
# Adjusts evaluation of piece positions according hard-coded heat map
def pieceLocationModifier(board=None):
modifier = 0
# These are arrays representing piece locations on the board
# and the value associated with those ... |
import sys
import pytest as pytest
from ripper import context
from ripper.context import Context
from ripper.common import get_ipv4
from ripper.health_check import classify_host_status, count_host_statuses, fetch_host_statuses, construct_request_url
from ripper.constants import HOST_IN_PROGRESS_STATUS, HOST_FAILED_STA... |
from django.shortcuts import render
from django.shortcuts import redirect
from django.contrib.auth.decorators import login_required
from django.http import JsonResponse
from django.core import serializers
# Create your views here.
from django.http import HttpResponse
from django.template import loader
from django.views... |
import logging
from typing import Any
from typing import Dict
from typing import Optional
from typing import Tuple
import numpy
import torch
from allennlp.common.checks import ConfigurationError
from allennlp.data import Instance
from allennlp.data import TextFieldTensors
from allennlp.modules import SoftmaxLoss
from ... |
"""Test the MQTT Wrapper class."""
import asyncio
from typing import Match
import gmqtt
import pytest
from pydantic import BaseModel
from astoria.common.config import MQTTBrokerInfo
from astoria.common.messages.base import ManagerMessage
from astoria.common.mqtt.topic import Topic
from astoria.common.mqtt.wrapper im... |
from bayes_opt import DiscreteBayesianOptimization
from bayes_opt.event import Events
import bayes_opt
import time
import numpy as np
from bayes_opt import UtilityFunction
from tests.test_functions import GPVirtualModel
import pandas as pd
import os, shutil
N_THREADS = 7
CAPITALIST_ARGS = {'multiprocessing': N_THREADS... |
"""
PureMVC Python Port by <NAME> <<EMAIL>>
PureMVC - Copyright(c) 2006-08 Futurescale, Inc., Some rights reserved.
Your reuse is governed by the Creative Commons Attribution 3.0 License
"""
import puremvc.interfaces
import puremvc.patterns.facade
class Observer(puremvc.interfaces.IObserver):
"""
A base C{... |
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from collections import OrderedDict
import os
WEIGHTS_PATH = os.path.dirname(os.path.realpath(__file__))+"/weights/"
class FlattenTensorCustom(nn.Module):
def __init__(self):
super(FlattenTensorCustom, se... |
# Copyright (c) Microsoft Corporation
# Licensed under the MIT License.
import copy
from typing import List, Tuple
import numpy as np
import pandas as pd
import pytest
import shap
from sklearn.model_selection import train_test_split
from ..common_utils import create_adult_income_dataset, create_housing_data
@pytest... |
"""Rules for testing our own Bazel rules."""
"""Toolchains we're using for our test scripts."""
TOOLCHAINS = []
_bazelrc = """
startup --batch
build --verbose_failures
build --sandbox_debug
build --test_output=errors
build --spawn_strategy=standalone
build --genrule_strategy=standalone
test --test_strategy=standal... |
import os
import json
import shutil
import threading
import cv2
from app.controller import MySqlUtil as DBUtil, Connection
from app.controller import Utils
from app.controller import VideoDBManage
from app.models.TaskManager import taskManager
import config
upload_folder = config.UPLOAD_FOLDER
videoBase = config.VID... |
import tensorflow.keras.backend as K
import tensorflow.compat.v1 as tf
from tensorflow.keras.layers import Input, Conv2D, UpSampling2D, BatchNormalization, ZeroPadding2D, MaxPooling2D, Reshape, \
Concatenate, Lambda
from tensorflow.keras.models import Model
from tensorflow.keras.utils import multi_gpu_model
from te... |
# Copyright 2015 The TensorFlow 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 applica... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Author: <NAME>
# @Date: Friday, November 15th 2019, 12:05:29 pm
import logging
import sys
import time
import numpy as np
import usb
from ibllib.graphic import popup
from pybpodapi.protocol import Bpod, StateMachine
import iblrig.bonsai as bonsai
import ibl... |
import logging
import requests
logger = logging.getLogger(__name__)
class Nanoleaf(object):
"""Nanoleaf API wrapper"""
def __init__(self, host, token=None, port=16021, protocol='http',
timeout=2):
self.host = host
self.token = token
self.port = port
self.proto... |
import time
import os
def is_yes(choice):
return choice in ('Y', 'y')
def is_no(choice):
return choice in ('N', 'n')
def make_file(filename):
print("Đang tạo file " + filename + "...")
file = open(filename, "w", encoding="utf8")
file.close()
time.sleep(1.5)
print("Đã tạo!\n")
time.sle... |
import logging
import re
from typing import Dict, Set, List, Callable, Any, Optional, Union
from queue import Queue
from dataclasses import dataclass
from toolkit.ev3.simulation.block.block import Block
from toolkit.ev3.simulation.block.source import BlockSource
log = logging.getLogger(__name__)
@dataclass
class E... |
# Copyright (c) 2019-2020 SAP SE or an SAP affiliate company. All rights reserved. This file is
# licensed under the Apache Software License, v. 2 except as noted otherwise in the LICENSE file
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the L... |
#!/usr/bin/env python
from amara.xpath import datatypes, context
from amara.xpath.expressions.basics import number_literal, string_literal
from amara.xpath.expressions.numbers import additive_expr, multiplicative_expr, unary_expr
from test_expressions import (
# expression TestCase
base_expression,
# IEEE ... |
# coding=utf-8
"""
Copyright 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 agree... |
# Python Module for import Date : 2017-02-06
# vim: set fileencoding=utf-8 ff=unix tw=78 ai syn=python : per Python PEP 0263
'''
_______________| yi_stocks.py : Access stock quotes.
We define procedures to access stock quotes FREELY and directly from
Yahoo Finance or Google Finance. (Qu... |
from collections import OrderedDict, namedtuple
from django.views.decorators.http import require_http_methods
from django.shortcuts import render, redirect
from django.utils.timezone import now
from core.sort_and_filter import Sorter, Filter
from core.csv_export import CSV_EXPORT_FORMATS, EXPORT_FORMATS, csv_response... |
from __future__ import print_function
import os
import argparse
import socket
import time
import sys
import torch
import torch.backends.cudnn as cudnn
from torch.utils.data import DataLoader
from models import model_dict, model_pool
from models.util import create_model
from dataset.mini_imagenet import ImageNet, Me... |
import argparse
import Dataset
from utils import AverageMeter, get_transform
from torch.utils.data import DataLoader
import Network
import torch
import time
from torch.nn import functional as F
import os
os.environ['CUDA_VISIBLE_DEVICES'] = '1'
def parse_arguments():
parser = argparse.ArgumentParser()
parser... |
import torch
from torch import nn
from torch_geometric.utils import softmax
import torch_sparse
from torch_geometric.utils.loop import add_remaining_self_loops
import numpy as np
from data import get_dataset
from utils import MaxNFEException
from base_classes import ODEFunc
class ODEFuncTransformerAtt(ODEFunc):
de... |
import keras
import numpy as np
from keras import layers
from keras import backend as K
from keras.models import Model
### VAE encoder network ###
img_shape = (28, 28, 1)
batch_size = 16
# Dimensionality of the latent space: a 2D plane
latent_dim = 2
input_img = keras.Input(shape=img_shape)
x = layers.Conv2D(
3... |
"""
Yolo v2 loss function.
"""
import numpy as np
import tensorflow as tf
from keras import backend as K
from .netparams import YoloParams
EPSILON = 1e-7
def calculate_ious(A1, A2, use_iou=True):
if not use_iou:
return A1[..., 4]
def process_boxes(A):
# ALign x-w, y-h
A_xy = A[...... |
import re
import sys
from enum import Enum
from typing import Optional, Tuple, Any, Generator, NamedTuple
from publicsuffix2 import get_sld
from urllib3.util import Url
def is_ip(string: str) -> bool:
return re.match(
r'^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$',
s... |
from inspect import isclass
from fnmatch import filter
try:
import Image
import ImageColor
import ImageFile
import ImageFilter
import ImageEnhance
except ImportError:
try:
from PIL import Image
from PIL import ImageColor
from PIL import ImageFile
from PIL import I... |
"""
Crear una programa que contenga:
-ventana (hecho)
-tamaño fijo (hecho)
-ventana no redimensionable (hecho)
-Un Menu (Inicio, Añadir, Informacion, Salir) (hecho)
-Diferentes Pantallas (Hecho)
-Formulario de Añadir Productos (Hecho)
-Guardar datos temporalmente (Hecho)
-Listar datos en pantalla principal
-Opcion de ... |
import os, sys
import numpy as np, torch
from tqdm import tqdm
from mrl.import_all import *
from mrl.configs.make_continuous_agents import *
from experiments.coda.coda_module import CodaOldBuffer
from experiments.coda.sandy_module import CodaAttentionBasedMask, SimpleStackedAttn, PongClassifierRewardModel, SimpleMLP
... |
from django.contrib import messages
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
from django.http import Http404
from django.urls import reverse_lazy
from django.shortcuts import get_object_or_404
from django.views.generic import DetailView, UpdateView
from .forms import ProfileForm, ... |
class pipeline:
# Main class - Is in charge od the orchestry of processes.
from datetime import datetime
from multiprocessing import Pool
from normandy.engine.logger import main_logger, logger
def __init__(self, env, tags, global_params, log_level, threads):
from yaml import load
... |
"""
Visualisation module.
"""
# Copyright (C) 2021 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 app... |
#!/usr/bin/env python3
"""A little score-keeper app.
This shows **very** fixed interactions.
Based (partially) on this list of old Solaris commands:
ckdate(1)
ckgid(1)
ckint(1)
ckitem(1)
ckkeywd(1)
ckpath(1)
ckrange(1)
ckstr(1)
cksum(1)
cktime(1)
ckuid(1)
ckyorn(1)
"""
import shelve
from contextlib import closing
im... |
# Copyright 2019 VIA Technologies, 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 applicab... |
# @file
# Split a file into two pieces at the request offset.
#
# Copyright (c) 2021, Intel Corporation. All rights reserved.<BR>
#
# SPDX-License-Identifier: BSD-2-Clause-Patent
#
##
# Import Modules
#
import argparse
import os
import io
import shutil
import logging
import sys
import tempfile
parser = argparse.Ar... |
"""
Copyright 2020 The OneFlow 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 applicable law or agr... |
"""
Order Manager Interface - deribit API client wrapper, with my own custom-built features/functions
"""
from extras.deribit_api_async import RestClient
from extras.orders_async import *
from utils import log
# Logging
logger = log.setup_custom_logger(__name__)
# Constants
DEFAULT_INSTRUMENT = 'BTC-PERPETUAL'
# in... |
# Copyright 2018,2019,2020,2021 Sony Corporation.
# Copyright 2021 Sony Group 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
#... |
from zeit.cms.i18n import MessageFactory as _
import inspect
import zeit.cms.interfaces
import zope.container.interfaces
import zope.file.interfaces
import zope.interface
import zope.lifecycleevent
import zope.schema
class IBeforeObjectAddEvent(zope.interface.interfaces.IObjectEvent):
"""An event sent before an o... |
import argparse
import torch
import numpy as np
import time as tm
from torch.autograd import Variable
# Compute error
def compute_error(A, sA):
normA = torch.sqrt(torch.sum(torch.sum(A * A, dim=1),dim=1))
error = A - torch.bmm(sA, sA)
error = torch.sqrt((error * error).sum(dim=1).sum(dim=1)) / normA
re... |
# Copyright The IETF Trust 2016-2019, All Rights Reserved
# -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function, unicode_literals
import re
import six
import textwrap
import unicodedata
from django.utils.functional import keep_lazy
from django.utils.safestring import mark_safe
import debug... |
import argparse
import json
import logging
from typing import Tuple
from flopz.core.shellcode import Shellcode
from flopz.core.target import Target
from flopz.target.all_targets import get_target_by_name
from flopz.util.parsing import get_int_from_str, get_bytes_from_hex_str
def get_arg_parser():
parser = argpar... |
from __future__ import print_function
import os
from os import path
import shlex, subprocess, sys, errno
# set-up workspace
Debug=int(os.getenv("RVT_DEBUG", 0)) != 0
libRV="../lib/libRV.so"
def assureDir(path):
try:
os.makedirs(path)
except OSError as exception:
if exception.errno != errno.EEXIST:
... |
#!/usr/bin/env python3
# What this file does:
# + It creates the files 'dependencies.md' and 'services.md' based on the 'package.json' files
# + It adjusts the number for the 'services implemented' field in 'index.md'
#
# Requirements:
# + python3 in your PATH
# + executed from root of nodecg-io repo
# + docs re... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
Created on Sun Feb 4 12:51:20 2018
@author:glauberrleite
lfelipev
"""
from FirstOrderMethods import *
from SecondOrderMethods import *
from ClosedLoopMethods import *
from LeastSquares import *
import numpy
import matplotlib.pyplot as pyplot
import matplotlib.... |
import torch
import torch.nn as nn
import torch.nn.functional as F
class ConvBnRelu(nn.Module):
def __init__(
self,
in_channels: int,
out_channels: int,
kernel_size: int,
stride: int = 1,
padding: int = 0,
dilation: int = 1,
... |
"""Interface with GekoS-Bau software."""
import gws
import gws.common.action
import gws.common.db
import gws.common.template
import gws.ext.db.provider.postgres
import gws.ext.helper.alkis
import gws.gis.proj
import gws.gis.shape
import gws.web.error
import gws.types as t
from . import request
"""
see https://... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jul 20 21:07:18 2017
@author: shenda
"""
import ReadData
from collections import Counter
import pickle
import hickle
import numpy as np
from sklearn.model_selection import StratifiedKFold
def slide_and_cut(tmp_data, tmp_label, tmp_pid):
'''
s... |
import matplotlib
matplotlib.use('Agg')
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rcParams
from collections import defaultdict
import brewer2mpl
# brewer2mpl.get_map args: set name set type number of colors
bmap = brewer2mpl.get_map('Paired', 'qualitative', 12)
colors = bmap.mpl_colo... |
"""Test the NemSettlementPeriod object."""
from datetime import date, datetime
from pytz import timezone
import pytest
from electric_units import NemSettlementPeriod
def test_can_create():
"""We can create a NemSettlementPeriod."""
feb = datetime(2020, 2, 25, 12, 15, 12)
set_per = NemSettlementPeriod(mom... |
# -*- coding: utf-8 -*-
import pkg_resources
import pytest
from pathlib import Path
from shutil import move, copy, rmtree
import numpy as np
import pandas as pd
from fluxdataqaqc import Data
from fluxdataqaqc import QaQc
from fluxdataqaqc import Plot
from fluxdataqaqc import Convert
from fluxdataqaqc import util
@p... |
'''
* @author Waileinsamkeit
* @email <EMAIL>
* @create date 2020-08-07 15:51:58
* @modify date 2020-08-07 15:51:58
'''
from sklearn.metrics import confusion_matrix
import numpy as np
import pandas as pd
from utils import flatten_lists
class Eval_unit(object):
def __init__(self,tp,fp,fn,tn,label):
su... |
"""This module contains the general information for EquipmentStorageControllerConfig ManagedObject."""
from ...ucsmo import ManagedObject
from ...ucscoremeta import MoPropertyMeta, MoMeta
from ...ucsmeta import VersionMeta
class EquipmentStorageControllerConfigConsts:
INT_ID_NONE = "none"
PNUOS_SUPPORTED_FAL... |
###############################################################################
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
###############################################################################
imp... |
# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# Copyright (c) 2016, Anaconda, Inc. All rights reserved.
#
# Licensed under the terms of the BSD 3-Clause License.
# The full license is in the file LICENSE.txt, distributed with this software.
# -------------------... |
# -*- coding: utf-8 -*-
from requests_oauthlib import OAuth1Session
from artifact_tracker import celery, tracker_app
# from artifact_tracker.user.utils import decrypt
from artifact_tracker.utils.message import post_to_ldn_inbox, template_as2
from artifact_tracker.tracker.tracker import Tracker
from datetime import dat... |
"""PyMC4 test configuration."""
import pytest
import pymc4 as pm
import numpy as np
import tensorflow as tf
import itertools
# Tensor shapes on which the GP model will be tested
BATCH_AND_FEATURE_SHAPES = [
(1,),
(2,),
(2, 2,),
]
SAMPLE_SHAPE = [(1,), (3,)]
@pytest.fixture(scope="function", autouse=True)... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.utils import spectral_norm
class Generator(nn.Module):
# initializers
def __init__(self, d=64):
super(Generator, self).__init__()
# Unet encoder
self.conv1 = nn.Conv2d(1, d, 4, 2, 1)
self.conv2 = nn... |
import chardet
def detect_encoding(file):
"""This function attempts to detect the character encoding of a file."""
encoding = None
bom = tuple(map(ord, file.read(4)))
encoding = {
( 0x00, 0x00, 0xFE, 0xFF ) : "utf_32", #BE
( 0xFF, 0xFE, 0x00, 0x00 ) : "utf_32", #LE
}.get(bom, None... |
import os
from datetime import datetime
import shutil
import pandas as pd
import matplotlib.pyplot as plt
def set_password(filepath: str = "wydyf-password.xlsx", prefix: str = "./public/"):
data = pd.read_excel(filepath)
for index, row in data.iterrows():
name = row["1、您的姓名"]
dir_path = os.pa... |
#!/usr/bin/env python
# Copyright 2018 Google LLC
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ... |
#https://open.fda.gov/
#self.path es mi url
#ul=unlimited list
#https://github.com/tylucaskelley/licenser/blob/master/LICENSE
#accion parecida a recieve: atribute
import http.server
import http.client
import json
# HTTPRequestHandler class
class OpenFDAClient():
OPENFDA_API_URL='api.fda.gov'
OPENFDA_API_EVENT='/drug... |
'''
Created By ILMARE
@Date 2019-3-3
'''
import re
import os
import numpy as np
import cv2
from matplotlib import pyplot as plt
random_transform_args = {
'rotation_range': 10,
'zoom_range': 0.05,
'shift_range': 0.05,
'random_flip': 0.4,
}
def umeyama(src, dst, estimate_scale):
num = src.shape[0]
... |
from lark import Lark
from lark.visitors import Transformer, v_args
from dataclasses import dataclass
from typing import List, TypeVar, Union, Any
import re
import json
import itertools
GRAMMAR = r"""
start: var+ section+
var: IDENT "=" (WORD|ARRAY) _NL+
section: "++" IDENT "++" _NL pattern+
pattern: (WORD+ | match)+... |
"""
Contributors can be viewed at:
http://svn.secondlife.com/svn/linden/projects/2008/pyogp/lib/base/trunk/CONTRIBUTORS.txt
$LicenseInfo:firstyear=2009&license=apachev2$
Copyright 2009, Linden Research, Inc.
Licensed under the Apache License, Version 2.0.
You may obtain a copy of the License at:
http://www.apa... |
from bs4 import BeautifulSoup
import argparse
import svgwrite
import os
import random
import colorsys
def main(name, output):
name_to_files_map = get_name_to_files_map(name)
name_to_data_map = parse_name_to_files_map(name_to_files_map)
bounds = get_universal_bounds(name_to_data_map)
dwg = svgwrite.Dra... |
import torch
import torch.nn.functional as F
from torch import nn, Tensor
from .MultiHeadAttention import DeformableHeadAttention
import copy
class DeformableTransformerEncoderLayer(nn.Module):
def __init__(self,C, M, K, n_levels, last_feat_height, last_feat_width, d_ffn=2048,
dropout=0.1, normaliz... |
"""Train GAIL or AIRL."""
import logging
import os
import os.path as osp
from typing import Any, Mapping, Type
import sacred.commands
import torch as th
from sacred.observers import FileStorageObserver
from imitation.algorithms.adversarial import airl as airl_algo
from imitation.algorithms.adversarial import common
... |
from socket import *
from server_mysql import Mysql_conn
import select
import time
import sys
def do_addfriend(data, r):
mysql_obj = Mysql_conn()
data1 = data.split('##A')
friend_name = data1[1]
my_name = data1[2]
print('添加好友时,给服务器发的信息:', data1)
if mysql_obj.check_friend(friend_name, my_name)... |
"""
Like described in the :mod:`parso.python.tree` module,
there's a need for an ast like module to represent the states of parsed
modules.
But now there are also structures in Python that need a little bit more than
that. An ``Instance`` for example is only a ``Class`` before it is
instantiated. This class represents... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import json
import warnings
import pulumi
import pulumi.runtime
from typing import Union
from . import utilities, tables
class GetClus... |
# Copyright 2020 Google LLC
#
# 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, ... |
import shlex
from subprocess import Popen
from threading import Thread
import time
import socket
from robocluster import Device
class RoboProcess:
"""Manages and keeps track of a process."""
class RunnerThread(Thread):
"""Waits for the process to exit, and calls the on_exit callback."""
def ... |
# coding=utf-8
# 清空地址库
def deleteAddress(cr, tablename, list_id):
sql = u"DELETE FROM {0} WHERE list_id={1}".format(tablename, list_id)
cr.execute(sql)
return
# 设置分类为:id, 合并订阅地址
def updateAddressListID(cr, tablename, list_id, list_ids_str):
sql = u"UPDATE {0} SET list_id={1} WHERE list_id in ({2})".fo... |
# -*- encoding: utf-8 -*-
# Date: 27/Jan/2022
# Author: <NAME>, Auckland, NZ
# License: MIT License
"""
Description: math functions
"""
import numpy as np
def get_distance(pt1, pt2):
"""get distance of two points"""
return np.sqrt(np.power(pt1[0] - pt2[0], 2) + np.power(pt1[1] - pt2[1], 2))
def get_line(pt1... |
import os
import sys
from collections import defaultdict, OrderedDict
from geodata.encoding import safe_decode, safe_encode
from geodata.i18n.unicode_paths import DATA_DIR
from geodata.text.normalize import normalized_tokens, normalize_string
from geodata.text.tokenize import tokenize, token_types
from geodata.text.p... |
# Copyright Contributors to the Pyro project.
# SPDX-License-Identifier: Apache-2.0
import numpy as np
import pytest
import funsor.ops as ops
from funsor.cnf import BACKEND_TO_EINSUM_BACKEND, BACKEND_TO_LOGSUMEXP_BACKEND
from funsor.einsum import einsum, naive_plated_einsum
from funsor.interpretations import memoize
... |
from typing import List
import numpy as np
from plist import ProbabilityList
from itertools import groupby
class SingleBlockEncoding(ProbabilityList):
def set(self, symbol, freq):
self._check_symbol(symbol)
if freq < 0:
raise ValueError('Frequency can\'t be negative')
temp = sel... |
import os
from pickle import TRUE
import numpy as np
import pandas as pd
from sklearn.linear_model import LogisticRegression
from sklearn.neighbors import KNeighborsClassifier
from sklearn.svm import SVC
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier,ExtraTreesCla... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#https://github.com/IfcOpenShell/IfcOpenShell/blob/master/src/ifcopenshell-python/ifcopenshell/guid.py#L56
from Generator import rules
from xml.sax.saxutils import escape
import numpy as np
import os
import pathlib
from Generator import xml_laden
from Generator import rule... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#------------------------------------------------------
# @ File : scene_change_detect.py
# @ Description: https://docs.opencv.org/4.4.0/db/d27/tutorial_py_table_of_contents_feature2d.html
# @ Author : <NAME>
# @ Contact : <EMAIL>
# @ License : Copyright (c)... |
"""
Загрузка и обработка ранее сохранённых шаблонов таблиц склонения и спряжения.
Loading and processing of plain text declension and conjugation tables' templates.
"""
import os
import re
import sys
import logging
logger = logging.getLogger(__name__)
from rwe.constants import *
def _create_tables(dump_file, tabl... |
import os
import re
import json
from collections import deque
def split_indx(s, indx):
if len(indx) == 0:
return [s]
else:
assert all(i < len(s) for i in indx)
res = []
c = 0
for i in indx:
res.append(s[c:i])
c = i+1
#end #for
if... |
# coding: UTF-8
### GPU 指定
import os
#os.environ["CUDA_VISIBLE_DEVICES"] = "5"
### import
# correlation より先にtorchをimport
import torch
#import correlation_cuda
device=torch.device('cuda')
import cv2
import numpy as np
import time
import torch.nn.functional as F
import matplotlib.pyplot as plt
import... |
# -*- coding: utf-8 -*-
import os
import sys
import h5py
from matplotlib import rcParams
import matplotlib.pyplot as plt
import numpy as np
from scipy.optimize import curve_fit
from presto.utils import rotate_opt
rcParams['figure.dpi'] = 108.8
if len(sys.argv) == 2:
load_filename = sys.argv[1]
print(f"Loadi... |
from graphql.core.validation import validate
from graphql.core.language.parser import parse
from graphql.core.type import (
GraphQLSchema,
GraphQLObjectType,
GraphQLField,
GraphQLArgument,
GraphQLID,
GraphQLNonNull,
GraphQLString,
GraphQLInt,
GraphQLFloat,
GraphQLBoolean,
Gra... |
import os, imageio
import numpy as np
import cv2 as cv
from sklearn.utils import shuffle
from skimage.transform import resize
from PIL import Image
def readFile(path):
fp = open(path)
lines = fp.readlines()
res = np.array([line.strip() for line in lines])
return shuffle(res)
def normalize(res):
... |
import argparse
import fnmatch
import json
import os
import sys
from PIL import Image
from boxes import box_area, clip_box_to_image, xyxy_to_xywh
try:
sys.path.append('../..')
from maskrcnn_benchmark.data.datasets.mosquitoes_utils.annotation import \
AnnotationImage
except:
raise
# train_videos ... |
import logging
import traceback
from functools import wraps
import os
import re
from django.conf import settings
from django.db import connection
from django.db.models import ManyToManyField
logger = logging.getLogger(__name__)
def debug_pg_notices(f):
@wraps(f)
def wrapped(*args, **kwargs):
r = No... |
import galaxy_analysis as gal
import numpy as np
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
import glob as glob
import os
import deepdish as dd
import sys
from galaxy_analysis.utilities import utilities
def sort_labels(l):
elements = [x for x in l if len(x) <=2]
other = [x for ... |
from typing import (
Any, Dict, Iterable, Union, Optional, List, Iterator, Mapping, Set
)
from dbt.clients.jinja import MacroGenerator, MacroStack
from dbt.contracts.graph.parsed import ParsedMacro
from dbt.include.global_project import PROJECT_NAME as GLOBAL_PROJECT_NAME
from dbt.exceptions import (
raise_dup... |
# Copyright (C) 2017-2020 New York University,
# University at Buffalo,
# Illinois Institute of Technology.
#
# 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 th... |
import collections
import numpy as np
from river import base, optim, utils
__all__ = ["PAClassifier", "PARegressor"]
class BasePA:
def __init__(self, C, mode, learn_intercept):
self.C = C
self.mode = mode
self.calc_tau = {0: self._calc_tau_0, 1: self._calc_tau_1, 2: self._calc_tau_2}[
... |
#
# Copyright (C) 2020 Arm Mbed. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
"""Utilities for retrieving Python's package information."""
import logging
import re
from typing import List, Any, Optional, cast
import pkg_resources
from mbed_tools_ci_scripts.utils.configuration import (
Configurati... |
"""
Unit test for generate_ext_tables module
Original Issues: DC-1640
The intent of this unit test is to ensure the cleaning rule is generating the extension tables with the proper fields
and populating each with the correct <table>_id and src_id data from the site_masking table.
"""
# Python imports
import json... |
"""
- 核心功能
- 订阅池清洗维护
- 识别不可用链接并剔除
"""
import base64
import warnings
import requests
from redis import exceptions as redis_error
from BusinessCentralLayer.middleware.redis_io import RedisClient
from BusinessCentralLayer.setting import (
REDIS_SECRET_KEY,
CRAWLER_SEQUENCE,
logger,
terminal_echo,... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.