filename stringlengths 13 19 | text stringlengths 134 1.04M |
|---|---|
the-stack_106_30895 | from torch.utils.data import Dataset
import torchvision.transforms as transforms
import h5py
import sys
import numpy as np
from helen.modules.python.TextColor import TextColor
from helen.modules.python.FileManager import FileManager
"""
WARNING: THIS IS A DEBUGGING TOOL INTENDED TO BE USED BY THE DEVELOPERS ONLY.
"""
... |
the-stack_106_30899 | from dataclasses import dataclass
from dataclasses import field
import os
import pickle
from typing import (
Dict, Optional, Mapping, Callable, Any, List, Type, Union
)
import time
import dbt.exceptions
import dbt.tracking
import dbt.flags as flags
from dbt.adapters.factory import (
get_adapter,
get_relat... |
the-stack_106_30900 | """
@author: Michael Guarino
"""
import numpy as np
np.set_printoptions(threshold=np.nan)
import tensorflow as tf
from tensorflow.contrib import rnn
import tensorflow.contrib.layers as layers
class HAN:
def __init__(self, max_seq_len, max_sent_len, num_classes, vocab_size, embedding_size, max_grad_norm, dropout... |
the-stack_106_30904 | """
Anisotropic orthogonal interpolation
"""
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from .. import utils
from . import linestring_utils, interp_4d, wkb2shp, field
from ..grid import unstructured_grid
from ..model import unstructured_diffuser
import stompy.grid.quad_laplacian as quads
f... |
the-stack_106_30905 | # Autodetecting setup.py script for building the Python extensions
import argparse
import importlib._bootstrap
import importlib.machinery
import importlib.util
import os
import re
import sys
import sysconfig
from glob import glob, escape
import _osx_support
try:
import subprocess
del subprocess
SUBPROCES... |
the-stack_106_30906 | import inspect
import logging
from functools import wraps
from json import loads
from traceback import format_exc
import paste.httpexceptions
from six import string_types
from galaxy.exceptions import error_codes, MessageException
from galaxy.util import (
parse_non_hex_float,
unicodify
)
from galaxy.util.jso... |
the-stack_106_30907 | import logging
from enum import IntEnum
from blatann.nrf import nrf_events, nrf_types
from blatann import uuid, exceptions
from blatann.waitables.connection_waitable import ClientConnectionWaitable
from blatann.event_type import Event, EventSource
logger = logging.getLogger(__name__)
class AdvertisingFla... |
the-stack_106_30908 | """413. Arithmetic Slices
https://leetcode.com/problems/arithmetic-slices/
"""
from typing import List
class Solution:
def number_of_arithmetic_slices(self, nums: List[int]) -> int:
i = 0
ans = 0
while i < len(nums) - 2:
j = i + 1
diff = nums[j] - nums[i]
... |
the-stack_106_30909 | while True:
n, *k = map(int, input().split())
if n==0: break
inp = input()
if len(inp)%n != 0:
inp += ' '*(n-len(inp)%n)
out = []
for i in range(len(inp)//n):
for j in k:
out.append(inp[i*n:i*n+n][j-1])
print("'", *out, "'", sep='') |
the-stack_106_30910 | # 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
#
# Unless required by appli... |
the-stack_106_30911 | from typing import Callable, Iterable, Mapping, Optional, Any, List, Union
from enum import Enum
from pathlib import Path
from wasabi import Printer
import srsly
import re
import sys
import itertools
from ._util import app, Arg, Opt
from ..training import docs_to_json
from ..tokens import Doc, DocBin
from ..training.c... |
the-stack_106_30912 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('cms_lab_carousel', '0003_auto_20150827_0111'),
]
operations = [
... |
the-stack_106_30914 | # Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... |
the-stack_106_30915 | import torch
import torch.nn as nn
from torch.autograd import Variable
import torch.nn.functional as F
import numpy as np
import gym
# 超参数
BATCH_SIZE = 32
LR = 0.01 # learning rate
EPSILON = 0.9 # 最优选择动作百分比
GAMMA = 0.9 # 奖励递减参数
TARGET_REPLACE_ITER = 100 # Q 现实网络的更新频率
... |
the-stack_106_30916 | import threading
import weakref
from collections import defaultdict
from dataclasses import dataclass, field
from functools import wraps
from types import FunctionType
from typing import (
Any,
Callable,
Dict,
Generic,
List,
Literal,
MutableMapping,
Optional,
Sequence,
Set,
T... |
the-stack_106_30919 | # Copyright 2018-2021 Streamlit 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... |
the-stack_106_30920 | """
Perform general agent monitoring, like:
1. Status of the agent processes
2. Status of the agent threads
3. Couchdb replication status (and status of its database)
4. Disk usage status
"""
from __future__ import division
from future.utils import viewitems
import time
import logging
import threading
from pprint ... |
the-stack_106_30921 | # 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
# distributed under t... |
the-stack_106_30922 | """
This module lets you practice one form of the ACCUMULATOR pattern,
namely, the "IN GRAPHICS" form which features:
-- DRAWING OBJECTS via ACCUMULATING positions and/or sizes,
as in: x = x + pixels
Additionally, it emphasizes that you must
** DO A CONCRETE EXAMPLE BY HAND **
before you can implement a sol... |
the-stack_106_30924 | #!/usr/bin/env python3
from setuptools import setup, find_packages
long_description = """
tropohelper is a library to speed up creating resources using tropospher
and cloudformation on AWS. Troposphere makes it much easier, but it can really
make a file for creating a stack large and repedative. Using these helper
f... |
the-stack_106_30925 | from random import *
from PD_Naive.naive_pd import *
# in1 = [(0, 000001), (0, 000010), (0, 000011), (1, 000100), (3, 000101), (3, 000110), (4, 000111), (4, 001000)]
inp_1 = [(0, '00001'), (0, '00010'), (0, '00011'), (1, '00100'),
(3, '00101'), (3, '00110'), (4, '00111'), (4, '01000')]
def coin():
retu... |
the-stack_106_30927 | # SPDX-License-Identifier: MIT
# Copyright (C) 2004-2008 Tristan Seligmann and Jonathan Jacobs
# Copyright (C) 2012-2014 Bastian Kleineidam
# Copyright (C) 2015-2020 Tobias Gruetzmacher
import re
import os
import pytest
from xdist.dsession import LoadScopeScheduling
from dosagelib.scraper import scrapers
def get_te... |
the-stack_106_30928 | import os
import telegram
from telegram.ext import Updater, CommandHandler
from telegram import InlineKeyboardMarkup, InlineKeyboardButton
def start(update, context):
Button1 = InlineKeyboardButton(
text='Github',
url='https://github.com/drewdev02'
)
Button2= InlineKey... |
the-stack_106_30930 | from leapp.libraries.actor import library
from leapp import reporting
from leapp.libraries.common.testutils import create_report_mocked
class extract_tgz64_mocked(object):
def __init__(self):
self.called = 0
self.s = None
def __call__(self, s):
self.called += 1
self.s = s
cl... |
the-stack_106_30933 | # Zulip's OpenAPI-based API documentation system is documented at
# https://zulip.readthedocs.io/en/latest/documentation/api.html
#
# This file contains helper functions for generating cURL examples
# based on Zulip's OpenAPI definitions, as well as test setup and
# fetching of appropriate parameter values to use whe... |
the-stack_106_30934 | # Copyright 2013-2022 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack.package import *
class Lmdb(MakefilePackage):
"""Symas LMDB is an extraordinarily fast, memory-efficient ... |
the-stack_106_30935 | # basic functions are inspired by Tinygrad's own implementation
import numpy as np
from .function import Function
def unbroadcast(out, in_shape):
"""Sum the gradients of the output in the case that broadcasting was performed
during the calculation of a result. This effectively avoids explicitly splitting
... |
the-stack_106_30936 | def special_for(iterable):
iterator = iter(iterable)
while True:
try:
iterator*5
next(iterator)
except StopIteration:
break
class MyGen:
current = 0
def __init__(self, first, last):
self.first = first
self.last = last
MyGen.current = self.first #this line allows us to use... |
the-stack_106_30937 | import torch
import utility
import data
import model
import loss
from option import args
from trainer import Trainer
torch.manual_seed(args.seed)
checkpoint = utility.checkpoint(args)
def main():
global model
global loss
if args.data_test == ['video']:
from videotester import VideoTester
... |
the-stack_106_30938 | import logging
import os
from airflow.models import BaseOperator
from airflow.exceptions import AirflowException
from airflow.operators.bash_operator import BashOperator
from airflow.utils.decorators import apply_defaults
from subprocess import check_output, CalledProcessError
class JavaOperator(BaseOperator):
... |
the-stack_106_30940 | """
EDIT NOTICE
File edited from original in https://github.com/castorini/hedwig
by Bernal Jimenez Gutierrez (jimenezgutierrez.1@osu.edu)
in May 2020
"""
import csv
import sys
import numpy as np
from nltk.tokenize import sent_tokenize
import torch
class InputExample(object):
"""A single training/test example fo... |
the-stack_106_30941 | # Copyright 2011 OpenStack Foundation.
# Copyright 2012, Red Hat, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# U... |
the-stack_106_30942 | #!/usr/bin/env python3
"""
This module handles all interaction with NCBI's BLAST API, including launching new
remote searches, polling for completion status, and retrieval of results.
"""
import re
import time
import logging
import requests
from cblaster import helpers
from cblaster.classes import Hit
LOG = loggin... |
the-stack_106_30943 | from typing import Set, Callable, Dict, List, Any
from structures import Point
class Vertex:
__position: Point
__children: Set['Vertex']
__parents: Set['Vertex']
__connectivity: Dict['Vertex', 'Vertex']
__aux: Dict[Any, Any]
def __init__(self, position: Point, store_connectivity: bool = False... |
the-stack_106_30944 | __version__ = '2021.12'
__url__ = 'https://github.com/Paradoxis/Flask-Unsign-Wordlist'
__author__ = 'Luke Paris (Paradoxis)'
import os, sys
from flask_unsign_wordlist.exceptions import NoSuchWordlist
def get(name: str='all') -> str:
"""
Get the path to a flask-unsign wordlist
:param name: Wordlist name ... |
the-stack_106_30945 | #
# 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 us... |
the-stack_106_30946 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 21 23:47:11 2021
@author: bruzewskis
"""
from dataclasses import dataclass, field
from astropy.coordinates import SkyCoord
import astropy.units as u
from typing import Union
@dataclass
class Resource:
'''
This class theoretically describes... |
the-stack_106_30947 | # coding: utf-8
from __future__ import division
import unicodedata, math, re, sys, string, os, ntpath, numpy as np
from time import gmtime, strftime
from io import open, StringIO
from imp import reload
from difflib import SequenceMatcher
try:
from itertools import izip
except ImportError:
izip = zip
WORD = re.... |
the-stack_106_30948 | #!/usr/bin/env python3
# Copyright (c) 2016-2017 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test various net timeouts.
- Create three sparkd nodes:
no_verack_node - we never send a verack i... |
the-stack_106_30950 | # Copyright 2020 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 agreed to... |
the-stack_106_30951 | # -*- coding: utf-8 -*-
"""
Functions for converting RCNN-derived zircon segmentation masks to polygons
viewable and editable in GUI and vice-versa.
"""
import numpy as np
from skimage import draw
import skimage.measure as measure
__all__ = ['mask_to_poly',
'poly_to_mask',
'vertex_dict_to_list'... |
the-stack_106_30952 | #/usr/bin/env python
import io
import re
from setuptools import setup, find_packages
import sys
if sys.version_info[:3] < (3, 4):
raise SystemExit("Toga requires Python 3.4+.")
with io.open('src/core/toga/__init__.py', encoding='utf8') as version_file:
version_match = re.search(r"^__version__ = ['\"]([^'\"]... |
the-stack_106_30953 | from graphnet.data.extractors.i3extractor import I3Extractor
from graphnet.data.extractors.utilities import (
frame_is_montecarlo,
frame_is_noise,
)
class I3RetroExtractor(I3Extractor):
def __init__(self, name="retro"):
super().__init__(name)
def __call__(self, frame) -> dict:
"""Extr... |
the-stack_106_30954 | from __future__ import annotations
import asyncio
import functools
import os
import random
import shutil
import signal
from typing import Any, Dict, List, Optional
import backoff
import colorama
import devtools
import httpx
import pydantic
import pyfiglet
import typer
import servo
import servo.api
import servo.confi... |
the-stack_106_30955 | #!/usr/bin/env python3
# Copyright (c) 2018-2019 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
from test_framework.test_framework import AgroCoinTestFramework
from test_framework.util import (
ass... |
the-stack_106_30956 | import copy
__author__ = 'rolandh'
class UserInfo(object):
""" Read only interface to a user info store """
def __init__(self, db=None):
self.db = db
def filter(self, userinfo, user_info_claims=None):
"""
Return only those claims that are asked for.
It's a best effort ta... |
the-stack_106_30958 | """Marks all fixed errors #34 on ruwiki's CheckWikipedia."""
import re
import pywikibot
from checkwiki import load_page_list, mark_error_done, log
NUMBER = "34"
REGEXP = r"{{{[^!]|#if:|#ifeq:|#switch:|#ifexist:|{{fullpagename}}|{{sitename}}|{{namespace}}|{{basepagename}}|{{pagename}}|{{subpagename}}|{{talkpagename}}|{... |
the-stack_106_30959 | from main.gui import Draw
from main.model import Service
def main():
# Configuring microservice structure
proxy = Service(5, 100, 'proxy')
aggregate = Service(5, 100, 'aggregate')
app = Service(5, 100, 'crud')
another_app = Service(5, 100, 'another_crud')
database = Service(5, 100, 'database')... |
the-stack_106_30960 | import requests
from legitindicators import atrpips
BINANCE_URL = "https://api.binance.com/api/v3/klines"
SYMBOL = "BTCUSDT"
INTERVAL = "5m"
PARAMS = {"symbol":SYMBOL, "interval":INTERVAL}
def test_atrpips():
response = requests.get(url=BINANCE_URL, params=PARAMS)
data = response.json()
open = [float(o[1]... |
the-stack_106_30961 | """ Advent of code 2021 day 10 / 2 """
from os import path
from collections import deque
p = {
"()": 1,
"[]": 2,
"kk": 3,
"<>": 4,
}
m = {
"(": "()",
"[": "[]",
"{": "kk",
"<": "<>",
")": "()",
"]": "[]",
"}": "kk",
">": "<>",
}
opening = set(["(", "[", "{", "<"])
clos... |
the-stack_106_30964 | # coding:utf-8
# --------------------------------------------------------
# Pytorch multi-GPU Faster R-CNN
# Licensed under The MIT License [see LICENSE for details]
# Written by Jiasen Lu, Jianwei Yang, based on code from Ross Girshick
# --------------------------------------------------------
from __future__ import a... |
the-stack_106_30966 | import sys
done = []
totalrmed = 0
fname = sys.argv[1]
lines = open(fname).read().split("\n")
output = open(fname,"w")
for line in lines:
if line.startswith("#") or line.startswith("!") or line == "":
output.write("{}\n".format(line))
else:
if line in done:
totalrmed += 1
... |
the-stack_106_30967 | # Copyright 2013-2015 ARM Limited
#
# 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 w... |
the-stack_106_30968 | # -*- coding: utf-8 -*-
# pylint: disable=E1101, C0330, C0103
# E1101: Module X has no Y member
# C0330: Wrong continued indentation
# C0103: Invalid attribute/variable/method name
"""
utils.py
=========
This is a collection of utilities used by the :mod:`wx.lib.plot` package.
"""
__docformat__ = "restructuredt... |
the-stack_106_30970 | import rmgpy.quantity as quantity
import logging
from rmgpy.species import Species
from rmgpy.data.solvation import SolventData, SoluteData, SoluteGroups, SolvationDatabase
from rmgpy.reaction import Reaction
class DiffusionLimited():
def __init__(self):
# default is false, enabled if there is a solvent
... |
the-stack_106_30971 | # coding=utf-8
# Copyright 2021 The TensorFlow Datasets Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appl... |
the-stack_106_30972 | import torch
from ..utils import box_utils
from .data_preprocessing import PredictionTransform
from ..utils.misc import Timer
class Predictor:
def __init__(self, net, size, mean=0.0, std=1.0, nms_method=None,
iou_threshold=0.45, filter_threshold=0.01, candidate_size=200, sigma=0.5, devi... |
the-stack_106_30973 | from pub_data import publish
import psutil
cpu = psutil.cpu_percent()
print(cpu)
ram = psutil.virtual_memory().percent
print(ram)
disk = psutil.disk_usage('/').percent
print(disk)
data = {
"cpu" : cpu,
"ram" : ram,
"disk": disk
}
publish("piSystemUsage", data)
|
the-stack_106_30974 | from requests import post
import os
"""
TG 消息推送模块
"""
TG_TOKEN = os.getenv("TG_TOKEN") #TG机器人的TOKEN
CHAT_ID = os.getenv("CHAT_ID") #推送消息的CHAT_ID
def post_tg(message):
telegram_message = f"{message}"
params = (
('chat_id', CHAT_ID),
('text', telegram_message),
('... |
the-stack_106_30976 | import click
from count_all_mutations_helpers import count_mutations, file_merge_algorithm
from count_all_mutations_helpers import post_analyse
import os
import pandas as pd
import threading
from queue import Queue
print_lock = threading.Lock()
url_queue = Queue()
def process_queue():
while True:
input_... |
the-stack_106_30977 | # ---
# jupyter:
# jupytext:
# formats: ipynb,py:hydrogen
# text_representation:
# extension: .py
# format_name: hydrogen
# format_version: '1.2'
# jupytext_version: 1.1.7
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# %%
import datetim... |
the-stack_106_30979 | import re
import sys
from pathlib import Path
import setuptools
LABEXTENSIONS_DIR = Path('py_src') / 'jupyter_lsp' / 'labextensions'
LABEXTENSIONS_INSTALL_DIR = Path('share') / 'jupyter' / 'labextensions'
def get_data_files():
extension_files = [
(str(LABEXTENSIONS_INSTALL_DIR / file.relative_to(LABEXT... |
the-stack_106_30980 | # -*- coding:utf8 -*-
"""
传入的key和类型,写在db_api外,当作一个小conf一起传入,db_api根据传入自行判断接受与否
db会自动创建两个时间键值:create_time,last_write_time
"""
from db.local_db import LocalDb as BaseDb
class PipeTaskInfo(BaseDb):
def __init__(self):
super(PipeTaskInfo, self).__init__()
self.table_type = "pipetask_info"
s... |
the-stack_106_30984 | """
Lift Curve Widget
-----------------
"""
from collections import namedtuple
import numpy as np
import sklearn.metrics as skl_metrics
from AnyQt import QtWidgets
from AnyQt.QtGui import QColor, QPen, QPalette, QFont
from AnyQt.QtCore import Qt
import pyqtgraph as pg
import Orange
from Orange.widgets import widge... |
the-stack_106_30986 | # --------------------------------------------------------------------------- #
# Diagnostics #
# --------------------------------------------------------------------------- #
"""Diagnostic Plots for single gradient descent optimizations. """
import dat... |
the-stack_106_30987 | ##################################################################################################
# Copyright (c) 2012 Brett Dixon
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files (the "Software"), to deal in
# the Software without ... |
the-stack_106_30988 | def to_type(o, new_type):
'''
Helper funciton that receives an object or a dict and convert it to a new given type.
:param object|dict o: The object to convert
:param Type new_type: The type to convert to.
'''
if new_type == type(o):
return o
else:
return new_type(**o)
cla... |
the-stack_106_30991 | """ResNets for Steering Prediction.
Author: Yuhuang Hu
Email : duguyue100@gmail.com
"""
from __future__ import print_function
import os
import cPickle as pickle
from sacred import Experiment
import numpy as np
import h5py
from keras.models import load_model
import spiker
from spiker.data import ddd17
exp = Experim... |
the-stack_106_30992 | from tqdm import tqdm
from concurrent.futures import ProcessPoolExecutor, as_completed
def parallel_process(array,
function,
n_jobs=16,
use_kwargs=False,
front_num=3,
tqdm=tqdm):
"""
This function was ... |
the-stack_106_30993 | cube = lambda x: pow(x,3) # complete the lambda function
def fibonacci(n):
l = [0,1]
for i in range(2, n):
temp = l[-1] + l[-2]
l.append(temp)
return l[0:n]
if __name__ == '__main__':
n = int(input())
print(list(map(cube, fibonacci(n)))) |
the-stack_106_30994 | from collections import OrderedDict
from rest_framework import serializers
from profiles.models import Project, Tag, Basemap, Spatialitedbs, Otherfiles, Profile, ProfileSet
from profiles.models import UserProject
from django.contrib.auth import get_user_model
from rest_framework.fields import SkipField
class ProjectSe... |
the-stack_106_30996 | """Code for handling downloading of HPO files used by scout from CLI"""
import logging
import pathlib
import click
from scout.utils.scout_requests import fetch_mim_files
LOG = logging.getLogger(__name__)
def print_omim(out_dir, api_key):
"""Print HPO files to a directory
Args:
out_dir(Path)
""... |
the-stack_106_30997 | from slyd.orm.exceptions import ImproperlyConfigured
__all__ = [
'get_serializer',
]
serializers = {}
def get_serializer(schema_type):
try:
return serializers[schema_type]
except KeyError:
raise ImproperlyConfigured(
u"No schema for type '{}' exists".format(schema_type))
|
the-stack_106_31000 | # -*- coding: utf-8 -*-
"""
TencentBlueKing is pleased to support the open source community by making 蓝鲸智云-用户管理(Bk-User) available.
Copyright (C) 2017-2021 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in compliance with the Lic... |
the-stack_106_31003 | import logging
import os
logging.basicConfig(
level=logging.DEBUG,
format="[%(asctime)s] %(levelname)-12s|process:%(process)-5s|thread:%"
"(thread)-5s|funcName:%(funcName)s|message:%(message)s",
handlers=[
# logging.FileHandler('fileName.log'),
logging.StreamHandler()
])
use... |
the-stack_106_31009 | # Copyright 2016 VMware 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 appli... |
the-stack_106_31010 | import firebase_admin
from firebase_admin import credentials
from firebase_admin import firestore
from google.cloud import storage
from linebot import LineBotApi
from linebot.models import TextSendMessage, ImageSendMessage, QuickReply, QuickReplyButton, MessageAction
from linebot.exceptions import LineBotApiError
impo... |
the-stack_106_31013 | import json
import threading
import time
import os
import stat
from decimal import Decimal
from typing import Union
from copy import deepcopy
from . import util
from .util import (user_dir, print_error, PrintError, make_dir,
NoDynamicFeeEstimates, format_fee_satoshis, quantize_feerate)
from .i18n i... |
the-stack_106_31014 | from pandac.PandaModules import *
from direct.showbase.DirectObject import *
from direct.interval.IntervalGlobal import *
from pirates.piratesbase import PiratesGlobals
from direct.distributed import DistributedObject
from pirates.effects.DustCloud import DustCloud
from pirates.effects.SmallSplash import SmallSplash
im... |
the-stack_106_31015 | '''
Data loader for annotated text datasets.
'''
import os
import re
import enum
import glob
import array
import random
import shutil
import struct
import tempfile
from collections import Counter
from contextlib import ExitStack
import torch
from torch import nn
import metrics
from data import preprocess
from data.te... |
the-stack_106_31016 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
@Author: chenzhen
@Date: 2020-04-10 17:04:46
@LastEditTime: 2020-04-24 15:45:41
@LastEditors: chenzhen
@Description:
'''
import sys
sys.path.append('../../')
import numpy as np
from sklearn.datasets import fetch_openml
from sklearn.preprocessing import OneHotEncoder
i... |
the-stack_106_31020 | import setuptools
with open("README.md", "r") as fh:
complete_readme = fh.read()
long_description = complete_readme.split("**System image")[0]
long_description += "\n\n**Made by Help-a-Sloth org. Check us on GitHub.**"
setuptools.setup(
name="mischief-managed",
packages=setuptools.find_packages(... |
the-stack_106_31021 |
# coding: utf-8
# In[ ]:
from __future__ import division
get_ipython().magic(u'matplotlib inline')
import numpy as np
import matplotlib.pyplot as plt
import math
import multivarlinreg
import rmse
# In[ ]:
#Linear regression
red_train = np.loadtxt('redwine_training.txt')
red_test = np.loadtxt('redwine_testing.tx... |
the-stack_106_31022 | #!/usr/bin/python
from __future__ import division
import numpy as np
import scipy as sp
from scipy.stats import gaussian_kde
from scipy.interpolate import interp1d
from scipy.integrate import quad
from scipy.special import gamma, gammaln, polygamma
from scipy.optimize import minimize_scalar
from math import pi
TINY_FL... |
the-stack_106_31023 | from time import *
from picamera import *
import numpy as np
from drawTheTableauLib import *
"""
Takes a picture from the camera and saves it in the current directory in a jpg format
prereq : resX > 0, resY > 0
resX <= 2592, resY <= 1944
param : String filename The name of the file
Int resX The X resolution... |
the-stack_106_31024 | import re
import nidigital
import nitsm.codemoduleapi
from nitsm.codemoduleapi import SemiconductorModuleContext
OPTIONS = {"Simulate": True, "driver_setup": {"Model": "6570"}}
@nitsm.codemoduleapi.code_module
def open_sessions(tsm_context: SemiconductorModuleContext):
instrument_names = tsm_context.get_all_nidi... |
the-stack_106_31026 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from datetime import datetime
import copy
import io
import logging
import os
import pickle
from six import string_types
import shutil
import tempfile
import time
import uuid
import ray
from ray.tune.logger im... |
the-stack_106_31027 |
from thingset.cansocket import CANsocket
sock = CANsocket('can0') # or other interface
while(True):
frame = sock.receive()
if isinstance(frame.cbor, float):
print("device: 0x%x data id: 0x%x value: %.2f" % (frame.source, frame.dataobjectID, frame.cbor))
else:
print("device:", hex(frame.source), " data id:"... |
the-stack_106_31030 | from __future__ import division # Use floating point for math calculations
import math
from flask import Blueprint
from CTFd.models import (
ChallengeFiles,
Challenges,
Fails,
Flags,
Hints,
Solves,
Tags,
db,
)
from CTFd.plugins import register_plugin_assets_directory
from CTFd.plugin... |
the-stack_106_31034 | import RPi.GPIO as GPIO
from lib_nrf24 import NRF24
import time
import spidev
from threading import Timer
# Define Board GPIOs
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
# needed GPIO PINS
PINS = [2,3,4,5,6,7]
# set all pins off
def allPinsOff():
for i in PINS:
GPIO.setup(i, GPIO.OUT, initial=GPIO.HI... |
the-stack_106_31035 | #!/bin/env python
# -*- coding: utf8 -*-
def shellSort(A):
def getCols(n):
cols = [1]
val = 1
while val < n:
val = int(val * 2.2)
cols.insert(0, val)
return cols
for h in getCols(len(A)):
for i in range(h, len(A)):
cur = A[i]
... |
the-stack_106_31036 | # vim: set fileencoding=utf-8 :
# Copyright (C) 2010 Google Inc. 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... |
the-stack_106_31037 | try:
from collections.abc import Sized
except ImportError:
from collections import Sized
from collections import defaultdict
from functools import partial
import numpy as np
from scipy.stats import rankdata
import sklearn
from sklearn.base import is_classifier, clone
from joblib import Parallel, delayed
from ... |
the-stack_106_31042 | # SPDX-FileCopyrightText: 2014 MicroPython & CircuitPython contributors (https://github.com/adafruit/circuitpython/graphs/contributors)
#
# SPDX-License-Identifier: MIT
import argparse
import os
import struct
import sys
sys.path.insert(0, "bitmap_font")
sys.path.insert(0, "../../tools/bitmap_font")
from adafruit_bi... |
the-stack_106_31043 | """
Author: Matheus Felinto
Description: A simple electronic circuit simulator
"""
import sys
import numpy as np
from lib.netlist import NetList
from lib import components
if __name__ == "__main__":
netlist = NetList(sys.argv[1])
netlist.read_netlist()
nodes_number, auxiliary_equations_number = netlist... |
the-stack_106_31044 | import urllib2
import hashlib
import tarfile
import random
import string
import sys
import os
import logging
import json
import socket
import shutil
import errno
import datetime as dt
import retry
INFRASTRUCTURE_ERROR = 12
def make_user_agent():
return 'fetch_from: {host}'.format(host=socket.gethostname())
de... |
the-stack_106_31045 | import os
import json
from flask import render_template, g, session, redirect, url_for, request
# noinspection PyPackageRequirements
from bson.objectid import ObjectId
from app import app, app_mongo, cdn_theme_url, app_redis
from views.navigation import Navigation
from views.auth import auth
from views.jump_freighte... |
the-stack_106_31046 | #!/usr/bin/env python
"""This plugin renders the client search page."""
import urllib
from grr.gui import renderers
from grr.gui.plugins import forms
from grr.gui.plugins import semantic
from grr.lib import aff4
from grr.lib import flow
from grr.lib import rdfvalue
from grr.lib import utils
from grr.lib.aff4_objects... |
the-stack_106_31047 | """
Web Steps
Steps file for web interactions with Selenium
For information on Waiting until elements are present in the HTML see:
https://selenium-python.readthedocs.io/waits.html
"""
import logging
from behave import when, then
from compare import expect, ensure
from selenium.webdriver.common.by import By
from se... |
the-stack_106_31049 | # Copyright (c) Microsoft. All rights reserved.
# Licensed under the MIT license. See LICENSE file in the project root for full license information
import datetime
from dictionary_object import DictionaryObject
class LonghaulConfig(DictionaryObject):
def __init__(self):
super(LonghaulConfig, self).__init_... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.