text stringlengths 3.07k 12.6k |
|---|
# Copyright 2019 ZTE 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 in ... |
import re,json
from google.cloud import bigquery
from google.cloud import storage
from google.cloud.storage.blob import Blob
from google.cloud import language_v1
import google.cloud.dlp
import nltk
nltk.download('stopwords')
from nltk.corpus import stopwords
nltk.download('punkt')
gcp_project = 'dz-apps'
bq_sentimen... |
import os
import json
import requests
import tqdm
def get_json_filename(year: str, month: str) -> str:
return f'{year}_{month}.json'
def load_json_files(year: str, input_folder: str) -> [json]:
# 1. Load all monthly json files
monthly_json_files = []
months = [str(month) for month in range(1, 13)]
... |
import numpy as np
from numba import cuda, int32, float32
from numba.cuda.testing import unittest, CUDATestCase
from numba.core.config import ENABLE_CUDASIM
def useless_sync(ary):
i = cuda.grid(1)
cuda.syncthreads()
ary[i] = i
def simple_smem(ary):
N = 100
sm = cuda.shared.array(N, int32)
i ... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2017, <NAME> <<EMAIL>>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
... |
import random
import re
from itertools import izip
import numpy as np
import torch
from onmt.Utils import use_gpu
from cocoa.model.vocab import Vocabulary
from cocoa.core.entity import is_entity, Entity
from core.event import Event
from session import Session
from neural.preprocess import markers, Dialogue
from neura... |
"""Dejittering nodes"""
import numpy as np
import pandas as pd
from timeflux.core.node import Node
from timeflux.core.exceptions import WorkerInterrupt
class Reindex(Node):
"""A simple dejittering node that will reindex the data according to the sampling rate.
This node is useful when datetime indices are n... |
"""This module contains the general information for LstorageRecurrWindow ManagedObject."""
from ...ucscentralmo import ManagedObject
from ...ucscentralcoremeta import UcsCentralVersion, MoPropertyMeta, MoMeta
from ...ucscentralmeta import VersionMeta
class LstorageRecurrWindowConsts():
CONCUR_CAP_UNLIMITED = "un... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
# __author__ = 'Liantian'
# __email__ = "<EMAIL>"
#
# MIT License
#
# Copyright (c) 2018 liantian
#
# 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 Softw... |
# -*- coding: UTF-8 -*-
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#... |
import asyncio
import logging
import sys
import click
import click_log
from click_log import ClickHandler
from pysonofflanr3 import SonoffSwitch, Discover
if sys.version_info < (3, 6): # pragma: no cover
print(
"To use this script you need python 3.6 or newer! got %s"
% sys.version_info
)
... |
#!/usr/bin/env python
"""
oletimes.py
oletimes is a script to parse OLE files such as MS Office documents (e.g. Word,
Excel), to extract creation and modification times of all streams and storages
in the OLE file.
Usage: oletimes.py <file>
oletimes project website: http://www.decalage.info/python/oletimes
oletimes ... |
import json
import os
import os.path as op
from heudiconv.utils import (
get_known_heuristics_with_descriptions,
get_heuristic_description,
load_heuristic,
json_dumps_pretty,
load_json,
create_tree,
save_json,
update_json,
get_datetime,
remove_suffix,
remove_prefix,
JSON... |
"""Support for IPP sensors."""
from __future__ import annotations
from datetime import timedelta
from typing import Any, Callable
from homeassistant.components.sensor import SensorEntity
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import ATTR_LOCATION, DEVICE_CLASS_TIMESTAMP, PERCENT... |
# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Handles generating profiles and transferring them to/from mobile devices."""
import logging
import optparse
import os
import shutil
import stat
import sy... |
#!/usr/bin/env python3
# Applies greedy weighted set cover to select a set of small molecules that
# cover as many parameters as possible in the smirnoff force field. Run with -h
# flag for usage.
import argparse
import json
import logging
import operator
from copy import deepcopy
from functools import reduce
from op... |
# coding: utf-8
# © Copyright IBM Corporation 2020, 2021.
#
# 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 applicabl... |
# Copyright 2018, <NAME>, mailto:<EMAIL>
#
# Part of "Nuitka", an optimizing Python compiler that is compatible and
# integrates with CPython, but also works on its own.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the Lice... |
from test.vim_test_case import VimTestCase as _VimTest
from test.constant import *
def check_required_vim_version(test):
if test.vim_flavor == 'neovim':
return None
if not test.vim.has_version(7, 4, 1):
return 'Vim newer than 7.4.1 is required'
else:
return None
# Undo of Snippet... |
from dataclasses import dataclass, field
from enum import Enum
from typing import Dict, List, Optional, Union
import pandas as pd
from plotly.colors import DEFAULT_PLOTLY_COLORS
import plotly.graph_objs as go
import plotly.io as pio
Stat = Union[pd.Series, pd.DataFrame]
class Level(Enum):
ERROR = 2
WARNING ... |
import mock
import pytest
from ddtrace import Pin
from ddtrace import Tracer
from ddtrace import config
from ddtrace.compat import stringify
from ddtrace.contrib import trace_utils
from ddtrace.ext import http
from ddtrace.propagation.http import HTTP_HEADER_PARENT_ID
from ddtrace.propagation.http import HTTP_HEADER_T... |
#!/usr/bin/env python3
#
# Advent of Code 2018 - Day 11
#
import re
import json
from datetime import datetime, timedelta
from collections import namedtuple, defaultdict
from itertools import chain
import logging
logging.basicConfig(format="%(asctime)s %(message)s", level=logging.INFO)
logger = logging.getLogger()
I... |
from pathlib import Path
from typing import Tuple
import numpy as np
import pandas as pd
import pytest
import xarray as xr
from pandas import DataFrame
from xarray import DataArray, Dataset
from sgkit.stats.hwe import hardy_weinberg_p_value as hwep
from sgkit.stats.hwe import hardy_weinberg_p_value_jit as hwep_jit
fr... |
import logging
import unittest
from gensim.corpora.dictionary import Dictionary
from gensim.topic_coherence.text_analysis import \
InvertedIndexAccumulator, WordOccurrenceAccumulator, ParallelWordOccurrenceAccumulator, \
CorpusAccumulator
class BaseTestCases(object):
class TextAnalyzerTestBase(unittest.... |
#!/usr/bin/python2.7
# Copyright 2011 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 requi... |
#!/usr/bin/python3
'''
* Copyright (C) 2019-2020 Intel Corporation.
*
* SPDX-License-Identifier: BSD-3-Clause
'''
from urllib.parse import urljoin
import argparse
import json
import time
import os
import statistics
import sys
import requests
VIDEO_ANALYTICS_SERVING = "http://localhost:8080/pipelines/"
TIMEOUT = 30
S... |
# Apache License, Version 2.0
# ./blender.bin --background -noaudio --factory-startup --python tests/python/bl_rna_defaults.py
import bpy
DUMMY_NAME = "Untitled"
DUMMY_PATH = __file__
GLOBALS = {
"error_num": 0,
}
def as_float_32(f):
from struct import pack, unpack
return unpack("f", pack("f", f))[0]
... |
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 Nebula, 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
#
# ... |
from invoke import task
import os
import re
import sys
import tempfile
import shutil
import glob
ACTIVATE = ". ./venv/bin/activate;"
PACKAGE = "tarproc"
VENV = "venv"
PYTHON3 = f"{VENV}/bin/python3"
PIP = f"{VENV}/bin/pip"
TEMP = "tarproc.yaml tarproc.yml"
DOCKER = "tarproctest"
commands = (
"tar2tsv tarcats tarf... |
import numpy as np
import pandas as pd
from itertools import product
from scipy.stats import entropy
from contest.strategies import NeutralScooterCompany, AggressiveScooterCompany
class ProposalCleaner:
""" Utilities for cleaning generated proposals.
"""
def __init__(self):
pass
def add_n... |
#!/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.
# pyre-strict
import functools
import warnings
from typing import Any, Dict, List, Optional
from fbpcp.entity.contai... |
import warnings
from collections import OrderedDict
from django.apps import apps
from django.core import serializers
from django.core.management.base import BaseCommand, CommandError
from django.db import DEFAULT_DB_ALIAS, router
class ProxyModelWarning(Warning):
pass
class Command(BaseCommand):
help = ("O... |
import numpy as np
import pytest
import rlberry.seeding as seeding
from rlberry.agents.dynprog import ValueIterationAgent
from rlberry.agents.dynprog.utils import backward_induction
from rlberry.agents.dynprog.utils import backward_induction_in_place
from rlberry.agents.dynprog.utils import backward_induction_sd
from ... |
# Copyright 2004-2005 Elemental Security, Inc. All Rights Reserved.
# Licensed to PSF under a Contributor Agreement.
#
# Modifications:
# Copyright <NAME> and Contributors
# Modifications are dual-licensed: MIT and PSF.
# 99% of the code is different from pgen2, now.
#
# A fork of `parso.pgen2.grammar_parser`.
# https:... |
# coding: utf-8
from __future__ import unicode_literals
import json
import hashlib
import re
from .aws import AWSIE
from .anvato import AnvatoIE
from .common import InfoExtractor
from ..utils import (
smuggle_url,
urlencode_postdata,
xpath_text,
)
class ScrippsNetworksWatchIE(AWSIE):
IE_NAME = "scri... |
###
# Copyright (c) 2021, <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:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions, and t... |
# Copyright 2019 The Cirq Developers
#
# 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 ... |
# Learn a dataset that is modeled by a polynomial using SGD.
#
# We start with a model that is able to represent all possible polynomials up
# to degree 10.
#
# Model: y = w_i x_i^i + w_0 for i in [0, 10]
# w_i being model weights.
#
# This model is capable of representing all possible lines and thus,
# it should be a... |
#!/usr/bin/env python3
"""
Check for presence of Terraform (TF) or CloudFormation (CFM) IAC code within a repo.
If found, create the appropriate default configuration to enable Prisma IAC scanning
delivered via Palo Alto's Prisma Scan Github App.
If no supported IAC code is found, create a default TF configuration and... |
# modified from https://github.com/facebookresearch/maskrcnn-benchmark/blob/master/maskrcnn_benchmark/engine/inference.py
import logging
import os
import torch
from tqdm import tqdm
import time
import datetime
from alphaction.dataset.datasets.evaluation import evaluate
from alphaction.utils.comm import get_rank, is_m... |
import numpy as np
import sys
from pathlib import Path
cwd = Path.cwd()
for dirname in tuple(cwd.parents):
if dirname.name == '3D-CG':
sim_root_dir = dirname
continue
sys.path.append(str(sim_root_dir.joinpath('master')))
sys.path.append(str(sim_root_dir.joinpath('CG')))
sys.path.append(str(sim_root... |
"""Entry point for the ``shell`` Flask-RESTy CLI commmand."""
# Code adapted from flask-konch
from pathlib import Path
import click
import flask
import konch
from flask.cli import with_appcontext
LOGO = r"""
_____ _ _ ____ _____ ____ _____
| ___| | __ _ ___| | __ | _ \| ____/ ___|_ _| _... |
from timemachines.skatertools.utilities.conventions import Y_TYPE, A_TYPE, E_TYPE, T_TYPE, wrap
from typing import Any
import numpy as np
import math
from timemachines.skatertools.components import observance
from timemachines.skatertools.components.parade import parade
def regress_change_on_first_known(y:Y_TYPE, s:d... |
import datetime
from typing import Optional
import halogen
from openapi_builder.constants import HIDDEN_ATTR_NAME
from openapi_builder.documentation import SchemaOptions
from openapi_builder.specification import Discriminator, Reference, Schema
from .base import SchemaConverter
ALL_HALOGEN_CONVERTER_CLASSES = []
... |
# -*- encoding: utf-8 -*-
#
# Copyright © 2021 Mergify SAS
#
# 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 applicabl... |
# 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,... |
#!/usr/bin/env python
# -*- mode: pymode; coding: latin1; -*-
from __future__ import print_function
from builtins import object
import sys
import re
#
# You must include the following class definition at the top of
# your method specification file.
#
class MethodSpec(object):
def __init__(self, name='', source=... |
#!/usr/bin/env sage-system-python
#
# Determine the number of threads to be used by Sage.
#
# Outputs three space-separated numbers:
# 1) The number of threads to use for Sage, based on MAKE, MAKEFLAGS
# and SAGE_NUM_THREADS
# 2) The number of threads to use when parallel execution is explicitly
# asked for (e.g.... |
# 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 tkinter as tk
from tkinter import ttk
_basePrint = print
def print(*args, **kwargs):
kwargs["flush"] = True
_basePrint(*args, **kwargs)
class Entry(tk.Entry):
'''An Entry with a .text property. Also supports "placeholderText".'''
# Note: For the sake of EntryValidate, never use self.textVar.set... |
"""
Tests of errors that are common across a wide group of pywbemcli groups and
commands.
This includes:
1. Tests of connection timeout on bad server with all commands. Note that the
command options in these tests are just sufficient to pass command parsing
since all tests should fail with connection error.
2. Test... |
# Webhooks for external integrations.
from typing import Any, Dict, Sequence
from django.http import HttpRequest, HttpResponse
from zerver.decorator import webhook_view
from zerver.lib.exceptions import UnsupportedWebhookEventType
from zerver.lib.request import REQ, has_request_variables
from zerver.lib.response impo... |
#!/usr/bin/env python3
import chess
import chess.svg
import chess.polyglot
import time
import traceback
import chess.pgn
import time
from piece_values import pawntable, knightstable, bishopstable, queenstable, rookstable,kingstable
from fen2pil import draw
import PIL
depth, number_of_moves = 3, 20
moves = []
def e... |
from __future__ import print_function
import math
import sys
import argparse
import numpy as np
import paddle
import paddle.fluid as fluid
import paddle.fluid.layers as layers
import paddle.fluid.nets as nets
from milvus import Milvus, IndexType, MetricType
from functools import reduce
import time
import getopt
PASS_N... |
# Copyright (c) 2015, Nordic Semiconductor
# 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, this
# list of cond... |
import matplotlib
import matplotlib.pyplot as plt
from techminer.core import explode
import pandas as pd
import numpy as np
import ipywidgets as widgets
from ipywidgets import GridspecLayout, Layout
from IPython.display import display
from techminer.core import Dashboard
import techminer.core.dashboard as dash
from t... |
from django.db.models.functions import TruncDate
from django.shortcuts import render
from django.http import HttpResponse
from django.db.models import Count, Max, Avg
from django.utils import timezone
from shared.models import Test, ContactContacted
from datetime import date, timedelta
from government.hooks.dbscan imp... |
# Initial imports
import csv
from pathlib import Path
# This function loads a CVS file from the filepath defined in `csvpath`
def load_csv(csvpath):
with open(csvpath, "r") as csvfile:
data = []
csvreader = csv.reader(csvfile, delimiter=",")
# Skip the CSV Header
next(csvreader)
... |
import dataclasses
import enum
import typing
from vkmodels.bases.object import ObjectBase
@dataclasses.dataclass
class ClickableArea(
ObjectBase,
):
x: int
y: int
@dataclasses.dataclass
class ClickableSticker(
ObjectBase,
):
clickable_area: typing.List[ClickableArea]
id: int
type: str
... |
"""Task definitions for language modeling tasks."""
import math
import os
from typing import Iterable, Sequence, Type
# Fields for instance processing
from allennlp.data import Instance
from allennlp.data.token_indexers import SingleIdTokenIndexer
from allennlp.training.metrics import Average
from jiant.utils.data_lo... |
import logging
import os
import cv2
import fitz
import numpy as np
import pkg_resources
from PyQt5 import QtCore, QtGui, QtWidgets, uic
from PyQt5.QtCore import QObject, QThread
from pagerange import PageRange
from godr.backend.board import Board
from godr.backend.recognizer import Recognizer
from godr.frontend.misce... |
# -*- coding: utf-8 -*-
class Token(object):
ident = 1
integer =2
char = 3
string = 4
graphic = 5
NL = 6
EOF = 7
def __init__(self, line, row, col):
self.line, self.row, self.col = line, row, col
self.__buf = []
self.__str = None
self.t_type = None
... |
import os
from PIL import Image
TEMPLATE = """# suppress inspection "UnusedProperty" for whole file
name = {name}
default = {default}
default_bg = {default_bg}
# unimportant stuff
chat_time = {unimportant}
chat_prefix_more = {unimportant}
chat_prefix_action = {unimportant}
chat_inactive_buffer = {unimportant}
chat_r... |
import math
import torch
from torch.nn import functional as F
def init_weights(m, mean=0.0, std=0.01):
classname = m.__class__.__name__
if classname.find("Conv") != -1:
m.weight.data.normal_(mean, std)
def get_padding(kernel_size, dilation=1):
return int((kernel_size * dilation - dilation) / 2)... |
from typing import Generator, Callable, Tuple, List
from enum import Enum
DEBUG: bool = False
TEST_RUNS: Tuple[Tuple[str]] = (
(
"5 6",
".....P",
"......",
"...B..",
"......",
"......",
"ULDDDR",
),
(
"4 5",
".....",
".....",
... |
###SSH key-management toolkit for multiple hosts by Greedo###
import json
import paramiko
import argparse
import os
import os.path
import sys
from connector import execute_command_readlines
#SSH Config Directories
ssh_dir = "~/.ssh/"
ssh_auth_keys = "~/.ssh/authorized_keys"
ssh_known_hosts = "~/.ssh/known_hosts"
#Set... |
from __future__ import print_function
import copy, os, serial, sys, time
from ... import PY3
from ...uarm import UArm
from ..list_uarms import get_uarm_port_cli
from ...protocol import *
from ..firmware import flash, get_uarm_port_cli, download, default_config
from ...util import printf
if PY3:
izip = zip
else:... |
import torch
from math import log10
from datetime import datetime
import copy
from eval_utils import multiclass_accuracy, Average_Tracker
from tensorboardX import SummaryWriter
def train_eval(dataloader, model, criterion, optimizer, epoch, end_epoch,
mode='train', report_freq=10, device=torch.device(... |
import re
import os
from codalab.common import precondition, UsageError
INSTANCE_SEPARATOR = "::"
WORKSHEET_SEPARATOR = "//"
TARGET_KEY_REGEX = r"(?<=^)(?:([^:]*?)\:(?!:))?(.*(?=$))"
TARGET_REGEX = r"(?<=^)(?:(.*?)\:\:)?(?:(.*?)\/\/)?(.+?)(?:\/(.*?))?(?=$)"
# Formatting Constants
ADDRESS_SPEC_FORMAT = "(<alias>|<ad... |
import imaplib, re, sys, os, shutil
from imap_tools.imap_utf7 import decode as decodeUTF7
##############################
########### CONFIG ###########
##############################
HOST = "imap.example.com" # imap server address
USERNAME = "<EMAIL>" # email account username
PASSWORD = "password" # email account pass... |
import json
import socket
import struct
import pytz
from collections import namedtuple
from datetime import date, datetime
Thermo = namedtuple('Thermo', 'set_temp current_temp heat_on time error_code')
HEADER = namedtuple('HEADER', ['frame_head', 'frame_length', 'start_address', 'number_of_bytes'])
def json_serial(... |
#!/usr/bin/env python
"""Test out HMMs using the Occasionally Dishonest Casino.
This uses the ocassionally dishonest casino example from Biological
Sequence Analysis by Durbin et al.
In this example, we are dealing with a casino that has two types of
dice, a fair dice that has 1/6 probability of rolling any number an... |
import asyncio
import logging
import shlex
import subprocess
from aioimaplib import aioimaplib
from boltons.cacheutils import cachedproperty
class Error(Exception):
def __str__(self):
return str(self.message)
class AuthError(Error):
def __init__(self, host, port, login, password):
self.host = host
... |
# -*- coding: utf-8 -*-
"""
KFE
* http://www.koneksys.com/
*
* Copyright 2016 Koneksys
* Released under the MIT license
*
* @author <NAME> (<EMAIL>)
*/
"""
from sympy import*
from femaths.funreq import Funreq, Fieldtype, Doftype, Meshobjecttype
from scipy.special import comb
from sympy.physics.quantum import T... |
from ..torch_core import *
from ..basic_data import *
from ..basic_train import *
from .image import *
from ..train import Interpretation
from textwrap import wrap
__all__ = ['SegmentationInterpretation', 'ObjectDetectionInterpretation', 'MultiLabelClassificationInterpretation']
class SegmentationInterpretation(Inter... |
from math import inf
from itertools import zip_longest, chain
from numpy import linspace, array, fromiter, nan_to_num, ndarray
from operator import mul, not_, truth
from functools import wraps
from collections.abc import Sequence
def equal(x, y):
return all(i == j for i, j in zip_longest(x, y))
def call(val, x)... |
from __future__ import division
import numpy as np
from sympy.parsing.sympy_parser import parse_expr
import sympy as sp
import itertools
from six import string_types
from pandas import DataFrame, Series
from collections import OrderedDict
from matminer.featurizers.base import BaseFeaturizer
from sklearn.exceptions i... |
'''
Created on 2019/03/16
@author: tom_uda
'''
# -*- coding: utf-8 -*-
import os,sys
import re
funclist = []
skip_flag = 0
path_w ="PySourceAnalyxer_result.txt"
flow_path_w = "py_flow.md"
depth_list = []
depth_line_list = []
def com_skip(line):
global skip_flag
e_num = 0
c_num = 0
if line.find("#") > -... |
import logging
from operator import itemgetter
from django.dispatch import receiver
from django.contrib.auth.models import AbstractUser
from django.urls import reverse
from django.db import models
from django.db.models.signals import post_save
from django.utils.encoding import python_2_unicode_compatible
from django.ut... |
from __future__ import generator_stop
import hashlib
import time
import psutil
import socket
from threading import Thread, Event
import webbrowser
import subprocess
import sys
import os
import logging
stream_handler = logging.StreamHandler(sys.stdout)
stream_handler.setLevel(logging.INFO) # TODO: let this be configur... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
"""
from __future__ import annotations
import functools
from typing import Callable
from typing import Optional
import torch
import torch.nn.functional as F
from torch import Tensor
from onevision.type import Tensors
from onevision.type import Weights
__all__ = [
... |
from typing import Union, Set
from itertools import product
import matplotlib.pyplot as plt
import numpy as np
from numpy import ndarray
import pandas as pd
from pandas import DataFrame, Series
from sklearn.metrics import roc_auc_score, roc_curve, precision_recall_fscore_support
from sklearn.preprocessing import Labe... |
#!/usr/bin/env python
# Copyright (C) 2020-2021 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
"""CLI module."""
from click import argument
from click import command
from click import echo
from click import Group
from click import group
from click import option
from click import pass_context
from click import... |
# pylint: disable=abstract-method,unused-argument,arguments-differ
"""Customized Layers.
"""
from __future__ import absolute_import
from mxnet import initializer
from mxnet.gluon import nn, contrib
from mxnet.gluon.nn import BatchNorm, HybridBlock
__all__ = ['BatchNormCudnnOff', 'Consensus', 'ReLU6', 'HardSigmoid', 'H... |
''' test '''
"""""""""
授权界面:
https://bgm.tv/oauth/authorize?client_id=bgm22106232fa6225d8a&response_type=code&redirect_url=http://127.0.0.1:5000/oauth/redirect
https://bgm.tv/oauth/authorize?client_id=bgm22106232fa6225d8a&response_type=code&redirect_uri=http%3A%2F%2Fhttp%3A%2F%2F127.0.0.1%3A5000%2Foauth_callback
回调界... |
import json
from pathlib import Path
from typing import Union, Optional
from kirsche.utils.constants import UNIQUE_ID_PRECEDENCE, UNIQUE_ID_PREFIX
from loguru import logger
def load_json(data_file: Union[str, Path]) -> dict:
"""load dict/list of dict data from json file
:param data_file: json file path
... |
# -*- coding: utf-8 -*-
# @Author : Abner
# @Time : 2018/12/19
import os
import imageio
import cv2
import numpy as np
from warnings import warn
from time import sleep
import argparse
from multiprocessing import Pool
from multiprocessing import TimeoutError as MP_TimeoutError
START = "START"
FINISH = "FINISH"
WAR... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# auth: jessen
# purpose: redis-cluster-test
## 准备步骤 ##
# 1. 下载 redis源码, 解压, 目录名称改为redis
# 2. 将此脚本放在 redis 同级目录中
# 3. 执行脚本
# 自动创建 redis-cluster 目录 ,生成配置文件, 启动集群, 并进行集群配置
## 脚本逻辑说明 ##
# 0.默认会创建一个 9 个节点的集群 (3个master, 每个 master 2个slave )
# genConf.首先会根据端口号自动创建 相应的目录, 每个... |
from flask import Flask
from flask import request
import json
import logging
import flask
import dare_settings
import requests
from pathlib import Path
from dateutil.parser import parse
import io
import hdfs3
import hdfs3.compatibility
app = flask.Flask('dare_connector')
def get_hdfs_connect_handle():
fs = hdfs3... |
from typing import Any, Callable, Dict, Iterable, List, Optional, Tuple
from fastjsonschema import JsonSchemaException # type: ignore
from mypy_extensions import TypedDict
from ..models.base import Model
from ..models.fields import RelationMixin
from ..shared.exceptions import ActionException
from ..shared.interface... |
import operator
import time
import queue
import statistics
import curses
from typing import Collection
from pynput import keyboard
import nstroke
import layout
import gui_util
from corpus import default_lower, default_upper
key_events = queue.Queue()
def on_press(key):
global key_events
key_events.put((key, ... |
import os
import glob
import numpy as np
import os
import six.moves.urllib as urllib
import sys
import tarfile
import tensorflow as tf
import zipfile
import cv2
from collections import defaultdict
from io import StringIO
# This is needed to display the images.
import matplotlib.pyplot as plt
from PIL import Image
fr... |
import sys
import ujson as json
import re
import string
from collections import Counter
import pickle
from os import listdir
from os.path import isfile, join
def normalize_answer(s):
def remove_articles(text):
return re.sub(r'\b(a|an|the)\b', ' ', text)
def white_space_fix(text):
return ' '.j... |
import tensorflow as tf
import numpy as np
import nibabel as nib
import os
from utils.myfuncs import *
from utils.hausdorff_util import *
# Compute Accuracy
from sklearn.metrics import accuracy_score
from data_loader.data_loader import DataGenerator
from models.lvae_mlp import lvae_mlp
from utils.config import process... |
from src.helper import load, save, print_json
from src.path_finder import path_cost, get_disconnected_keys
from src.algo_shortest_path import shortest_path
from src.algo_extra_loops import extra_loops
from src.algo_random_routing import random_routing
from src.distance import dist_d, cost_d
from src.collect_data import... |
#=============================================================================
# Script to plot some basic rasters
#
# Authors:
# <NAME>, <NAME>, <NAME>
#=============================================================================
#=============================================================================
# IMP... |
# Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserve.
#
# 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... |
# -*- coding: utf-8 -*-
"""
Created on Sun Oct 24 14:33:41 2021
@author: kenhu
"""
from sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier, ExtraTreesClassifier, VotingClassifier, StackingClassifier
from sklearn.tree import DecisionTreeClassifier
from sklearn.svm import SVC
from sklearn.neig... |
#!/usr/bin/env python
# * coding: utf8 *
'''
state-campus
Usage:
state_campus merge-from <input> to <output>
state_campus list-folders <input>
state_campus create-map <input> to <output> with <mxd> [--recalculate|-r]
state_campus extract-symbology <input>
state_campus -h | --help
Options:
--recalculate, -... |
import numpy as np, torch, torch.nn as nn, torch.optim as optim
import argparse, time, pandas as pd, os
from tqdm import tqdm
from torch.utils.tensorboard import SummaryWriter
from torch.utils.data import DataLoader
from torch.utils.data.sampler import SubsetRandomSampler
from sklearn.metrics import mean_absolute... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.