text stringlengths 3.07k 12.6k |
|---|
#!/usr/bin/env python
# Copyright 2021 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 ... |
"""Basic modules.
Author: <NAME> (<EMAIL>)
"""
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import tensorflow as tf
from fewshot.models.modules.weight_module import WeightModule
from fewshot.models.variable_context import variable_scope
class Conv2D(W... |
import enum
from construct import (
Adapter,
Byte,
Construct,
Enum,
FlagsEnum,
GreedyBytes,
GreedyRange,
Int32ub,
IntegerError,
Optional,
PascalString,
Prefixed,
PrefixedArray,
Struct,
Switch,
)
from construct.core import (
byte2int,
iterateints,
... |
import sys
sys.path.append('../..')
import os
import numpy as np
import tensorflow as tf
#from pgmagick import Image
import skimage as ski
import skimage.data, skimage.transform
from tqdm import trange
from cityscapes_info import class_info, class_color_map
from datasets.dataset_helper import convert_colors_to_indices... |
# -*- coding: utf-8 -*-
"""This module defines functions for handling PDB sequence clusters."""
import os.path
from numpy import array, abs
from prody import LOGGER, SETTINGS, getPackagePath
from prody.utilities import openFile, openURL
__all__ = ['fetchPDBClusters', 'loadPDBClusters', 'listPDBCluster']
PDB_CLUSTE... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This script provides a basic access to yahoo finance data.
Copyright (c) 2018, <NAME>
License: MIT (see LICENSE for details)
"""
from __future__ import division
try:
from cStringIO import StringIO
except ImportError:
from io import StringIO
import re
import t... |
"""Opp.io Add-on ingress service."""
from __future__ import annotations
import asyncio
from ipaddress import ip_address
import logging
import os
import aiohttp
from aiohttp import hdrs, web
from aiohttp.web_exceptions import HTTPBadGateway
from multidict import CIMultiDict
from openpeerpower.components.http import O... |
import time
import logging
from logging import Logger
from utils import math as m
LOG_DIR = './log'
def get_logger(level: int = None, logfile: str = '') -> Logger:
logger = logging.getLogger('analysis')
if level is None:
logger.info(f'{__name__}: Returning existing logger')
else:
logger... |
# Copyright (c) 2015 Mirantis, 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 writin... |
""" datasets """
import numpy
import torch
import torch.utils.data
import pykitti.utils as pyutils
import numpy as np
from . import globset
from . import mesh
from .. import so3
from .. import se3
from .utils import sample_IR2, R_to_angle
class ModelNet(globset.Globset):
""" [Princeton ModelNet](http://modelnet... |
"""main sim script to run sims"""
import sys
import platform
import re
import os
from os import listdir
import importlib
import yaml
from internal.weights import find_weights
from internal.sim_parser import parse_json
from internal.sim_parser import get_timestamp
from internal.analyze import analyze
from internal imp... |
import pandas as pd
import nltk
import matplotlib.pyplot as plt
from sklearn.preprocessing import LabelEncoder
import torch
from transformers import BertModel, BertTokenizer, AdamW, get_linear_schedule_with_warmup
from torch_dataset_creator import RED
from torch.utils.data import Dataset, DataLoader
import re
... |
import database
import readdata
import json
problemarray = ["20x746187641c59c168", "22x9b87945d0701947f", "42xee63922e8a2e1ec7", "49xdc32850876d23639", "51x079fb52f20782c91"]
problemid = problemarray[3]
def _getUserSequenceByProblem():
result = database.userSequenceByProblemByEventTime(problemid)
data = []
... |
# Author: <NAME> <<EMAIL>>
# License: MIT
import numpy as np_
import autograd.numpy as np
from autograd import grad
from scipy.optimize import minimize as minimize_
def _scipy_func(objective_function, gradient, x, shapes, args=()):
optim_vars = _split(x, shapes)
obj = objective_function(optim_vars, *args)... |
#
# Copyright 2016-2017 Games Creators Club
#
# MIT License
#
import sys
import pygame
import pyros
import pyros.gcc
import pyros.gccui
import pyros.agent as agent
import pyros.pygamehelper
screen = pyros.gccui.initAll((600, 600), True)
bigFont = pyros.gccui.bigFont
speeds = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, ... |
"""
Basic classes for typed wrappers over pandas dataframes
"""
from itertools import chain
import pytz
import numpy as np
import pandas as pd
try:
from pandas.api.types import CategoricalDtype
except ImportError:
from pandas.types.dtypes import CategoricalDtype
"""
dtype for datetime column
"""
DATE_TIME_DT... |
# -*- coding: utf-8 -*-
"""
@author: <NAME>
@contact: <EMAIL>
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
def _smooth_l1_loss_base(bbox_pred, bbox_targets, sigma=1.0):
'''
:param bbox_pred: [-1, 4] in RPN. [-1, cls_... |
#
# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
# its licensors.
#
# For complete copyright and license terms please see the LICENSE at the root of this
# distribution (the "License"). All use of this software is governed by the License,
# or, if provided, by the license below or th... |
# coding=utf-8
# Copyright 2019 The Google Research Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicab... |
# 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 warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import... |
# Authors: <NAME> <<EMAIL>>
# License: BSD 3 clause
import matplotlib.pyplot as plt
import dnnet.utils.numcupy as ncp
from dnnet.ext_mathlibs import cp, np
from dnnet.utils.nn_utils import prod
def pad_img(img, pad_rows, pad_cols):
"""Returns padded matrix which represents image.
1d matrix is not supported... |
#!/usr/bin/env python
# coding: utf-8
# # Seldon and TensorFlow Serving MNIST Example
#
# This example shows how you can combine Seldon with Tensorflo Serving. We will use a Seldon Tensorflow Serving proxy model image that will forward Seldon internal microservice prediction calls out to a Tensorflow serving server.
... |
import pandas as pd
import glob
import time
import csv
import sys
import os
import numpy as np
from os.path import basename
from multiprocessing import Pool
from itertools import product
_QUERY_PROCESSOR = 4
_DEBUG=False
csv_test_id, out_clas, csv_train_id2label = None, None, None
def save_output(i):
test_id = cs... |
import time
from lxml import html
# Debug is available at here
from config import driver_init, stdscr, max_y
stdscr.clear()
stdscr.refresh()
# First config, then uquery
from uquery import illust_id_list, illust_name_list
stdscr.clear()
stdscr.refresh()
class PicClass:
is_r18: bool
url: str
... |
import dash_html_components as html
import dash
import dash_core_components as dcc
from dash.dependencies import Input, Output, State
import os
from components import utilities
from app import app
def data_load():
return html.Div(className="container-div", children=[
html.H3('ETL Configuration', classNam... |
# Copyright (c) 2021, NVIDIA CORPORATION. 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... |
import uuid
from pyramid import httpexceptions
from pyramid.settings import asbool
from pyramid.security import NO_PERMISSION_REQUIRED, Authenticated
from kinto.core import get_user_info as core_get_user_info
from kinto.core.errors import raise_invalid
from kinto.core.events import ACTIONS
from kinto.core.storage.exc... |
"""
.. module:: AdminViews
:synopsis: All endpoints of the admin views are defined here.
"""
import json
import os
from flask import Blueprint
from flask import redirect
from flask import render_template
from flask import request
from flask import url_for
from flask import flash
from flask_login import login_requ... |
# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license
# Copyright (C) 2003-2017 Nominum, Inc.
#
# Permission to use, copy, modify, and distribute this software and its
# documentation for any purpose with or without fee is hereby granted,
# provided that the above copyright notice and this permis... |
#School-Age Children per Temperature Region
#count of school-Age children: 2018 and 2019 ACS-5yr
#citation:
'''<NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME> and <NAME>. IPUMS USA: Version 11.0 [dataset]. Minneapolis, MN: IPUMS, 2021.
https://doi.org/10.18128/D010.V11.0
'''
#census boundries-need, or conty boundries... |
import os
import glob
import torch
import random
import numpy as np
from tqdm import tqdm
from torch.utils.data import Dataset, DataLoader
from utils.utils import read_wav_np, cut_wav, get_length, process_blizzard
from utils.audio import MelGen
from utils.tierutil import TierUtil
from text import text_to_sequence
def... |
from flask import Flask, flash, request, render_template, redirect, url_for, Response, Blueprint
from flask import current_app as app
from werkzeug.utils import secure_filename
from traceVtt import db
from traceVtt.models import Traces
import os
from utils import DB_GeoJson
import geojson
import gpxpy
from gpxpy impor... |
import os
import errno
import argparse
import numpy as np
import cv2
import tensorflow.compat.v1 as tf
def _run_in_batches(f, data_dict, out, batch_size):
data_len = len(out)
num_batches = int(data_len / batch_size)
s, e = 0, 0
for i in range(num_batches):
s, e = i * batch_size, (i + 1) * bat... |
''' Custom application functions and processes
+ These are the instructions for custom text message commands
'''
#%% Import Packages
import os, sys
import config as config # account information
import RH.Reports.RH_functions as rh # custom RH functions
import datetime as dt
import pandas as pd
impo... |
# Copyright (c) 2014 Mirantis 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 require... |
import time
import joblib
import os
import os.path as osp
import tensorflow as tf
import torch
import gym
from spinup import EpochLogger
from spinup.utils.logx import restore_tf_graph
def load_policy_and_env(fpath, itr='last', deterministic=False):
"""
Load a policy from save, whether it's TF or PyTorch, alon... |
import datetime
import math
from typing import Iterable, Optional, List
import pandas as pd
import pd_utils
from datacode.portfolio.resample import collect_portfolios_through_time
def cumulate_buy_and_hold_portfolios(
df: pd.DataFrame,
port_var: str,
id_var: str,
date_var: str,
port_date_var: st... |
# -*- coding: utf-8 -*-
# adapted from kaggle kernel
# author: <NAME>
# This script checks the dataset's image shape, and jpeg file's error or warning.
# This script checks all dataset (stage 1, train, test, additional)
# This script is part 1 of 4, for computing in 1200 sec.
# Shape includes size (height, width) and... |
#!/usr/bin/env python2
"""
<Program Name>
hash.py
<Author>
<NAME> <<EMAIL>>
<Started>
February 28, 2012. Based on a previous version of this module.
<Copyright>
See LICENSE for licensing information.
<Purpose>
Support secure hashing and message digests. Any hash-related routines that
TUF requires shoul... |
# -*- coding: utf-8 -*-
import typing
from typing import *
"""
This is a simple commandline program to enter blood pressure readings
without a lot of fuss. It allows flexible formatting of the inputs, and
drops the time stamped records into a fact-table type database for
later analysis. These analyses are particula... |
"""Support for Met.no weather service."""
import logging
from random import randrange
import metno
import voluptuous as vol
from homeassistant.components.weather import PLATFORM_SCHEMA, WeatherEntity
from homeassistant.const import (
CONF_ELEVATION,
CONF_LATITUDE,
CONF_LONGITUDE,
CONF_NAME,
EVENT_... |
from typing import Tuple
import torch
from torch import nn
from torch.nn import functional as F
class PoolingError(Exception): pass
class UNet3dLite(nn.Module):
"""(WIP) Re-implementation of the unet3d_lite model from ELEKTRONN2
See https://github.com/ELEKTRONN/ELEKTRONN2/blob/master/examples/unet3d_lite.... |
from snappi_ixnetwork.exceptions import SnappiIxnException
def test_Bad_Request_server_side(api, b2b_raw_config, utils):
"""
Configure a raw ethernet flow with,
- counter pattern for src and dst MAC address and ether type
Validate,
- Fetch the ethernet header config via restpy and validate
ag... |
# Copyright 2019 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 agreed to in writing, ... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import cv2
import numpy as np
import os
import math
from caffe2.python import core
from caffe2.python import workspace
from detectron.core.config import cfg
from detect... |
# coding=utf-8
# Copyright 2018 The Tensor2Tensor 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 applicable... |
# -*- coding: utf-8 -*-
"""
OCBase setup FCU, OSU, EIM and LBU connection objects to Outscale Cloud.
"""
__author__ = "Heckle"
__copyright__ = "BSD"
import sys
import logging
import boto
import ConfigParser
import os.path
import os
import boto.s3.connection
from boto.vpc import VPCConnection
from boto.ec2.reg... |
import logging
import json
import yaml
import click
import click_log
from tabulate import tabulate
from diffy.filters import AWSFilter
from diffy.config import CONFIG, configure_swag
from diffy.common.utils import install_plugins
from diffy._version import __version__
from diffy.plugins.base import plugins
from diff... |
# -*- coding: utf-8 -*-
########
# Copyright (c) 2015 Fastconnect - Atost. 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/LICENS... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author : leeyoshinari
import os
import random
import base64
import urllib.request
import numpy as np
from aip import AipFace
from PIL import Image
import zhihu_spider.settings as cfg
def save_image(image_name, image):
"""Save image to local path.
:par... |
# ----------------------------------------------------------------------------
# Copyright (c) 2020, QIIME 2 development team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file LICENSE, distributed with this software.
# -----------------------------------------------------... |
import os
import glob
import json
import struct
import sqlite3
from collections import deque
class FifoMemoryQueue(object):
"""In-memory FIFO queue, API compliant with FifoDiskQueue."""
def __init__(self):
self.q = deque()
self.push = self.q.append
def pop(self):
q = self.q
... |
from django.apps import apps
from django.conf import settings
from django.core.validators import MinValueValidator
from django.db.models import (
Model, PositiveSmallIntegerField, TextField, FloatField, ForeignKey,
OneToOneField, ManyToManyField, BooleanField, DateTimeField, QuerySet,
Max, Sum, F, SET_NULL... |
import math as m
import numpy as np
import scipy.constants as sc
cte_boltz_J = sc.physical_constants["Boltzmann constant"][0] # J/K
cte_boltz_eV = sc.physical_constants["Boltzmann constant in eV/K"][0] # eV/K
permittivity = sc.epsilon_0 / 100. # F/cm
q = sc.e # C
def intrinsic_concentration(temperature, gap_ener... |
import re
def initial_token(word: str, siglum: str, index):
return {"index": f"{index}",
"siglum": siglum,
"reading": siglum,
"original": word,
"rule_match": [word],
"t": word}
def prepare_text(text: str):
text = text.replace('\n<cb> ', 'C|') #break... |
# -*- coding: utf-8 -*-
"""
Named-entity recognizer
"""
__all__ = ["ThaiNameRecognizer"]
import sklearn_crfsuite
from pythainlp.corpus import download, get_file, thai_stopwords
from pythainlp.tag import pos_tag
from pythainlp.tokenize import word_tokenize
from pythainlp.util import is_thaiword
_WORD_TOKENIZER = "newm... |
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 <NAME>
# 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... |
#Importando bibliotecas
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from pytrends.request import TrendReq
plt.style.use('ggplot')
#Buscando dados
pytrends = TrendReq(hl='en-US', tz=360)
all_keywords = ['petrobrás', 'mensalão']
keywords = []
timeframes ... |
"""For HA sensor components."""
import asyncio
import logging
import re
from time import time
from typing import Callable, Optional, Coroutine
import async_timeout
from .core import FFMPEG_STDOUT, HAFFmpegWorker
_LOGGER = logging.getLogger(__name__)
class SensorNoise(HAFFmpegWorker):
"""Implement a noise detec... |
"""Koden er udviklet af:
Navn: <NAME>
email: <EMAIL>
Gruppe: A308b
Programmet er udviklet selvstændigt og individuelt.
"""
import os
import pandas as pd
"""Global variables - path to files"""
nations_file = "data/nations.txt"
result_file = "data/results.csv"
round_files = ["data/round1.txt", "data/rou... |
# pylint: disable=E1120
import io
import logging
from math import radians, sin, cos, ceil
import os
import click
import coloredlogs
import imageio
import numpy as np
from tqdm import tqdm
coloredlogs.install(
level='DEBUG',
fmt='%(asctime)s %(module)s[%(process)d] %(levelname)s %(message)s',
datefmt='%H:%... |
import time
from datetime import datetime
import pandas as pd
from helper.config import *
from helper.help_time import time_format
def etl_loop(func):
"""
Декоратор для запуска функций преобразования
:param func:
:return:
"""
def _func(*args, **kwargs):
_max_iter_cnt = 100
fo... |
# Copyright (C) 2017 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
"""Various simple helper functions for snapshot generator"""
import collections
from logging import getLogger
from sqlalchemy.sql.expression import tuple_
from ggrc import db
from ggrc import models
from ... |
import warnings
warnings.warn("BeautifulSoup 3.x (as of 3.1) is not fully compatible with html5lib and support will be removed in the future", DeprecationWarning)
from BeautifulSoup import BeautifulSoup, Tag, NavigableString, Comment, Declaration
import _base
from html5lib.constants import namespaces, DataLossWarnin... |
"""Large scale machine learning and stochastic gradient descent"""
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
class AdalineSGD:
"""ADAptive LInear NEuron classifier.
Parameters
------------
eta : float
Learning rate (betwe... |
from ehb_client.requests.base import JsonRequestBase, IdentityBase, RequestBase
import json
from ehb_client.requests.exceptions import InvalidArguments
class Subject(IdentityBase):
def __init__(self, first_name=None, last_name=None, organization_id=-1,
organization_subject_id=-1, organization_id... |
# Concord
#
# Copyright (c) 2019 VMware, Inc. All Rights Reserved.
#
# This product is licensed to you under the Apache 2.0 license (the "License").
# You may not use this product except in compliance with the Apache 2.0 License.
#
# This product may include a number of subcomponents with separate copyright
# notices a... |
#!/usr/bin/env python
# Copyright 2015 The PDFium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from __future__ import print_function
import distutils.spawn
import itertools
import os
import shutil
import sys
# pylint: disable=rela... |
from .EmbConstant import *
from .WriteHelper import write_int_8, write_int_16le, write_int_32le
FULL_JUMP = False
ROUND = True
MAX_JUMP_DISTANCE = 124 # 0xFCFF/2 16 bit signed, FD,FE,FF reserved.
MAX_STITCH_DISTANCE = 124
def write_xxx_header_b(pattern, f):
stitches = pattern.stitches
for i in ra... |
# !/usr/bin/env python
# -*- coding: utf-8 -*-
"""
根据excel指定参数生成word 暂时只支持到AC29列
"""
import cmd
import copy
import os
import sys
import time
import xlrd
from docx import Document
from docx.shared import Pt
from docx.enum.table import WD_TABLE_ALIGNMENT, WD_CELL_VERTICAL_ALIGNMENT
class Order(cmd.Cmd):
intro = "E... |
import inspect
from functools import partial
from collections import OrderedDict
import itertools
from .util import get_attribute, DictAndList, NOT_SET, can_peek
from .util.mro import _mro
from .util.deps import sort_by_deps, breadth_first
from .marks import CollectMarksMeta
class UnitConfigError(Exception):
pas... |
from django.contrib.auth.decorators import login_required
from django.http import HttpResponseRedirect, JsonResponse
from django.shortcuts import get_object_or_404, render
from django.urls import reverse
from micro_admin.models import Group, Client, SavingsAccount, Receipts, Payments
from micro_admin.forms import Savin... |
# coding: utf-8
# In[1]:
import pandas as pd
import os
# Just use 1 GPU
#os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID" # see issue #152
#os.environ["CUDA_VISIBLE_DEVICES"] = "1"
import tensorflow as tf
from keras.backend.tensorflow_backend import set_session
config = tf.ConfigProto()
config.gpu_options.per_proce... |
import os
import pickle
import types
from .ifp_object import IFPObject
from .exceptions import DeserializationError, Unserializable
##############################################################
# SERIALIZER.PY - the save/load system for IntFicPy
# Defines the SaveState class, with methods for saving and loading game... |
# -*- coding: utf-8 -*-
import os
import math
import numpy as np
# import skimage.metrics.peak_signal_noise_ratio as psnr_skimage
import cv2
import glob
import datetime
def calc_psnr(folder_Gen, folder_GT, result_save_path, epoch):
if not os.path.exists(result_save_path):
os.makedirs(result_save_path)
... |
import ast
import unittest
import os
import subprocess
from subprocess import CalledProcessError
import sys
import re
import textwrap
from pathlib import Path
from importlib.machinery import SourceFileLoader
from importlib import util as importutil
class TestCase:
def __init__(self, testfile, **kwargs):
s... |
# GENERATED BY KOMAND SDK - DO NOT EDIT
import insightconnect_plugin_runtime
import json
class Component:
DESCRIPTION = "Search the Hybrid Analysis database"
class Input:
COUNTRY = "country"
DOMAIN = "domain"
FILENAME = "filename"
FILETYPE = "filetype"
HOST = "host"
PORT = "port"
SIM... |
"""Super Class for Dell like drivers. """
import re
import logging
from hil.ext.switches.common import parse_vlans
from hil.ext.switches import _console
logger = logging.getLogger(__name__)
class _BaseSession(_console.Session):
def enter_if_prompt(self, interface):
self._sendline('config')
sel... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import base64
import hashlib
import json
import logging
import socket
from threading import Lock, Thread
import websocket
from . import events
from .base_classes import BaseRequest
from .exceptions import ConnectionFailure, ObjectError
from .handlers import EventHandler, ... |
import asyncio
import traceback
import warnings
from datetime import datetime, timedelta
from os import environ
from platform import python_version
import discord
from discord.ext import commands
from dotenv import load_dotenv
from pkg_resources import get_distribution
import custom_classes as cc
warnings.filterwarn... |
"""
spec_lib.py
Shared between sh_spec.py (Python 2) and interactive.py (Python 3)!
"""
from __future__ import print_function
import optparse
import os
import re
import sys
def log(msg, *args):
# type: (str, *Any) -> None
if args:
msg = msg % args
print(msg, file=sys.stderr)
def MakeShellPairs(shells):
... |
import ipywidgets as widgets
from PyQt5.QtWidgets import QApplication
from PyQt5.QtWidgets import QFileDialog
import json
import dicttoxml
from ipywidgets import FileUpload, Button
import sys
import asyncio
import html
# https://ipywidgets.readthedocs.io/en/latest/examples/Widget%20Events.html#Debouncing
class Timer:
... |
# coding=utf-8
import os
import sys
import traceback
from datetime import datetime
import importlib
from termcolor import colored
import requests
import regex
from glob import glob
class Helpers:
min_log_level = 0
def escape_format(s):
return s.replace("{", "{{").replace("}", "}}")
def expand_shorthand_li... |
# encoding: UTF-8
from __future__ import print_function
'''一个简单的SINA数据客户端,主要使用requests开发'''
import requests
from time import sleep
import execjs
from datetime import datetime,timedelta
from ctaBase import CtaBarData,CtaTickData
class UtilSinaClient(object):
# ---------------------------------------... |
#!/usr/bin/env python3
##############################################
####################LOGGER####################
import logging
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
ch = logging.StreamHandler()
ch.setLevel(logging.INFO)
formatter = logging.Formatter('%(levelname)s: %(message)s')
c... |
# File: knightsTests.py
# from chapter 7 of _Genetic Algorithms with Python_
#
# Author: <NAME> <<EMAIL>>
# Copyright (c) 2016 <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
# ht... |
import torch
from torch.autograd import Variable
from skimage.transform import resize as imresize
import numpy as np
from path import Path
import argparse
from tqdm import tqdm
from models import PoseExpNet
from inverse_warp import pose_vec2mat
parser = argparse.ArgumentParser(description='Script for PoseNet testin... |
# Copyright (c) OpenMMLab. All rights reserved.
import argparse
import warnings
import mmcv
from mmcv import Config, DictAction
from mmcv.parallel import MMDataParallel
from mmdet.apis import single_gpu_test
from mmdet.datasets import (build_dataloader, build_dataset,
replace_ImageToTensor... |
#!/usr/bin/env python3
import datetime
import subprocess
import sys
import serial
import numpy as np
from config import Settings
def toMacro(name, value, k=None):
if value > 20000:
value = f"{round(value/1000):,}k"
else:
value = f"{value:,}"
value = value.replace(",", "\\,")
return f"\\newcommand{{\... |
#!/usr/bin/env python
"""
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License");... |
# coding: utf-8
from flask import g, render_template, request, jsonify
from flask_sqlalchemy import SQLAlchemy
from flask_oauthlib.provider import OAuth1Provider
db = SQLAlchemy()
def enable_log(name='flask_oauthlib'):
import logging
logger = logging.getLogger(name)
logger.addHandler(logging.StreamHandl... |
#!/usr/bin/env python3
import argparse
import sys
import string
# This is the translation code for bacteria and archaea
# It is the same as the standard code
#
translation_code = {
'TTT':'F', 'TCT':'S', 'TAT':'Y', 'TGT':'C',
'TTC':'F', 'TCC':'S', 'TAC':'Y', 'TGC':'C',
'TTA':'L', 'TCA':'S', 'TAA':'*', 'TGA':'*',
'TTG'... |
# Copyright 2019 DeepMind Technologies Ltd. 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 appl... |
#
# A widget to view images complete with navigation buttons, etc.
#
import tkinter.tix as tix
import tkinter.ttk as ttk
from .resources import Resources
from .imagelabel import ImageLabel
def _get_button_state(condition):
return tix.NORMAL if condition else tix.DISABLED
class ImageFrame(tix.Frame):
"""
... |
import json
import requests
import csv
from dotenv import load_dotenv
import os
import pprint
load_dotenv()
request_url = "https://statsapi.web.nhl.com/api/v1/teams"
response = requests.get(request_url)
parsed_response = json.loads(response.text)
current_teams = parsed_response["teams"]
# print(current_teams)
# ... |
cool_beasts = {"octopuses":"tentacles", "dolphins":"fins", "rhinos":"horns"}
for amphibian, organ in cool_beasts.items():
print("{} have {}".format(amphibian, organ))
wardrobe = {"shirt":["red","blue","white"], "jeans":["blue","black"]}
for clothing, colour_list in wardrobe.items():
for colour in colour_list:
p... |
from custom_envs.pybulletgym_custom.envs.roboschool.robots.locomotors.humanoid import Humanoid
import numpy as np
from custom_envs.pybulletgym_custom.envs import gym_utils as ObjectHelper
class HumanoidFlagrun(Humanoid):
def __init__(self, power=0.41):
self.power = power
Humanoid.__init__(self, po... |
'''
Library for Google Sheets functions.
'''
import configparser
import os
import pickle
import logging
import re
import math
from string import ascii_uppercase
from typing import List
import pandas as pd
import numpy as np
from constants import rgx_age, rgx_sex, rgx_date, rgx_lives_in_wuhan, date_columns, column... |
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
import contextlib
import os
import random
import tempfile
import subprocess
import zipfile
from textwrap import dedent
from .common import safe_mkdir, safe_rmtree
from .compatibility impo... |
class LocalFTP(object):
"""
Class adding recursive nlst() behavior to ftplib.FTP instance. The
ftplib.FTP instance is available through the connection attribute, and
is exposed through __getattr__.
The behavior added by this class (recursive directory listing) is most
appropriate for ftp connec... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.