text stringlengths 3.07k 22.1k |
|---|
import src
import src.models
from src.models import init_app
from src import create_app
from flask import session, jsonify
from src.sessionManagement import users
from src.models import Session, AnswerQuestion
from config import TestingConfig
import pytest
from . import init_test_db
@pytest.fixture # (scope='module'... |
#!/usr/bin/env python3
import pybullet as p
import pybullet_data
import os
import time
import numpy as np
import cv2
import tempfile
#BASEDIR = os.path.dirname(__file__)
from lib.pyb.urdf_printer import URDFPrinter
# W, H, FOVX
#CAMERA_SPECS = (1920, 1080, 64) # https://www.chiefdelphi.com/t/horizontal-fov-of-mic... |
"""
Polls the SEL RESTful API for water data
for the Salford Living Lab.
"""
__author__ = "<NAME>"
__version__ = "0.1"
from os import read
import pandas as pd
import requests
from datetime import datetime
from decouple import config
from living_lab_functions.db import db_connect, execute_procedure, execute_proced... |
##############################################################################
#
# Copyright (c) 2008 Zope Foundation and Contributors.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS I... |
#!/usr/bin/env python
# coding=utf-8
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
from plaidcloud.utilities.remote.dimension import Dimensions
from plaidcloud.utilities.remote.dimension import Dimension
__author__ = '<NAME>'
__copyright__ = 'Cop... |
from typing import Dict, Union, List
from torch import Tensor
import os
from box import Box
import torch
from torch.utils.data import DataLoader
from torchvision.transforms import Compose
import matplotlib.pyplot as plt
import numpy as np
import consts
from experiments.default_lightning_model import (
DefaultLight... |
#starting
#print('Hello world!')
#to simulate needing a short period of time to process
import time
#####let us set some variables#####
###################################
#player icons
p1_icon = ""
p2_icon = ""
#player names
p1_name = "Player 1"
p2_name = "Player 2"
#while loop variables
keepGoing = True
global k... |
import networkx as nx
import numpy as np
from networkx.algorithms.bipartite.matrix import from_biadjacency_matrix
from scipy.sparse import csr_matrix
def generate_sim_mat_via_l1(gt_word_list, jason_word_feature):
# L1 distance (in seconds) between center of each gt and Jason's word segments
#
# gt_word_l... |
#!/usr/bin/python -u
'''
Copyright 2009, The Android Open Source Project
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... |
from imutils.video import VideoStream
from imutils import resize
from time import sleep, strftime, time as getCurrentTime, localtime as getLocalTime
from Lcd import lcddriver
from Model.LastPersonEntry import LastPersonEntry
from faceSize import getBiggestBoxInList
import face_recognition
import pickle
import cv2
impor... |
########################################################################
## Imports
########################################################################
from __future__ import division
import sqlite3
import os
import datetime
import math
import re
from DBAccess import DBAccess
from DBWriter import DBWriter
from DBR... |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2020 CERN.
#
# invenio-app-ils is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""Location closures tests."""
import json
import arrow
from flask import url_for
from invenio_app_ils.closures... |
import os
import sys
import argparse
from tempest_parser import const
from tempest_parser.reports import reporter
from tempest_parser.reports.csv_reporter import CSVReporter
from tempest_parser.manager.test_manager import TestsManager
from tempest_parser.parser.tempest_log_parser import TempestLogParser
from tempest_p... |
import re
import dash_bootstrap_components as dbc
import dash_core_components as dcc
import dash_html_components as html
import dash_loading_spinners as dls
from dash.dependencies import Input, Output
__all__ = ["get_component_details"]
HEADER_PATTERN = re.compile(r"---.*---", flags=re.DOTALL)
SPLIT_PATTERN = re.com... |
"""https://www.dndbeyond.com/monsters/ghast"""
import unittest
from unittest.mock import patch
import colors
from pycs.arena import Arena
from pycs.attack import MeleeAttack
from pycs.constant import Condition
from pycs.constant import DamageType
from pycs.constant import MonsterType
from pycs.constant import Stat
from... |
import weakref
from functools import wraps
from typing import Sequence
import numpy as np
from torch.optim.lr_scheduler import _LRScheduler, CosineAnnealingLR as CosineAnnealingLR_
from torch.optim import Optimizer
__all__ = [
"BaseLRScheduler", "LinearLR",
"ExponentialLR", "TriangularLR",
"GradualWarmupS... |
"""
--- Day 10: Adapter Array ---
Patched into the aircraft's data port, you discover weather forecasts of a massive tropical storm. Before you can figure out whether it will impact your vacation plans, however, your device suddenly turns off!
Its battery is dead.
You'll need to plug it in. There's only one problem:... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
Widget to display simulation data of a CSDF graph.
author: <NAME>
"""
import sys
from PyQt5.QtWidgets import QWidget, QGraphicsView, QGraphicsScene, QHBoxLayout, QFrame
from PyQt5.QtCore import Qt, QRectF, QPointF
from PyQt5.QtGui import QTransform, QPaint... |
"""
Utility functions for the getrv.py script
"""
import os
import re
import yaml
import argparse
import numpy as np
from astropy.io import fits
DEFAULT_CFG = {
'pattern': None,
'outdir': None,
'path': '.',
'object': ['all'],
'mask': ['all'],
'sanitize': ['all'],
... |
#!/usr/bin/env python3
# -*- CoDing: utf-8 -*-
"""
Created on May 22 2019
Last Update May 22 2019
@author: simonvanvliet
Department of Zoology
University of Britisch Columbia
<EMAIL>
This recreates the data and figure for figure 5
By default data is loaded unless parameters have changes, to rerun model set override_... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import math
import numpy as np
from matplotlib import pyplot as plt
import stimuli
import plots
import utils as local_utils
def get_active_rfc(xs_on, ys_on, xs_off, ys_off, time, total_rfc):
# Returns the number of the active RF centers, i.e. ON on light and
# O... |
# Pinout Manager: management and utility functions
import argparse
import importlib
import os
from pathlib import Path
import pkg_resources
import sys
from pinout import core
try:
import cairosvg
except ImportError as e:
pass
# export as other (non svg) formats is not available
# user variables
# C:\Pro... |
import transformers
from torch.utils.data import DataLoader, TensorDataset, random_split, RandomSampler, Dataset
import pandas as pd
import numpy as np
import torch.nn.functional as F
import pytorch_lightning as pl
import torch
from pytorch_lightning.callbacks import ModelCheckpoint
import math
import random
import r... |
# -*- coding: utf-8 -*-
"""Volume scanner for artifact definitions."""
import logging
import os
import yaml
from dfimagetools import artifact_filters
from dfimagetools import environment_variables
from dfimagetools import windows_registry
from dfvfs.helpers import file_system_searcher as dfvfs_file_system_searcher
f... |
from obstacle_tower_env import ObstacleTowerEnv
import numpy as np
import tensorflow as tf
import os
import cv2
# 使用第一張GPU 卡 1080
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
# TF_CPP_MIN_LOG_LEVEL, 1隱藏通知, 2隱藏通知和警告, 3隱藏通知、警告和錯誤
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '1'
GAMMA = 0.6
class Actor(object):
d... |
import re
import io
import html
import logging
import collections
import collections.abc
from piecrust import APP_VERSION, PIECRUST_URL
from piecrust.page import FLAG_RAW_CACHE_VALID
logger = logging.getLogger(__name__)
css_id_re = re.compile(r'[^\w\d\-]+')
CSS_DATA = 'piecrust-debug-info-data'
CSS_DATABLOCK = 'p... |
import os
import subprocess
import sys
import threading
import time
sys.path.insert(0, "../../../util/python")
import Cons
import Util
import Conf
# Note: Redirecting output to memory file system may have a lower overhead. Not
# a big deal though.
class Mon:
mon_interval = 0.1
def __init__(self, test_name):
s... |
from enum import Enum
from ._ingenialink import ffi, lib
from ._utils import cstr, pstr, INT_SIZES
from .dict_labels import LabelsDictionary
# CANOPEN DTYPES
IL_REG_DTYPE_DOMAIN = 15
class REG_DTYPE(Enum):
""" Data Type. """
U8 = lib.IL_REG_DTYPE_U8
""" Unsigned 8-bit integer. """
S8 = lib.IL_REG_... |
# -*- coding:utf-8 -*-
import bottle
from bottle import run, template
from bottle import route, get, static_file, HTTPError
from bottle import HTTPResponse
import zipfile
import base64
import os
from PIL import Image
import io
import math
from urllib import parse
from contextlib import closing
from hashlib import sha1... |
from django.shortcuts import render
# Permissions
from django.contrib.auth.mixins import PermissionRequiredMixin
from django.contrib.auth.decorators import permission_required
# Create your views here.
from .models import Book, Author, BookInstance, Genre
def index(request):
"""
View function for home page ... |
"""
A work manager which uses MPI to distribute tasks and collect results.
"""
import sys
import time
import traceback
import logging
import threading
from collections import deque
from mpi4py import MPI
from westpa.work_managers import WorkManager, WMFuture
log = logging.getLogger(__name__)
# +------+
# | Task |
#... |
import sys, getopt
def parseArgs(argv):
inputfile = ''
outputfile = ''
dim = ''
size=700
try:
opts, args = getopt.getopt(argv,"d:hi:o:s:",["input=","dimension=","output=","size="])
except getopt.GetoptError:
print('Usage: st_sample_merge.py -i <inputfile of data folders> -o <out... |
# -*- coding: utf-8 -*-
import requests
import json
from enum import Enum
from typing import List
from functools import lru_cache
from . import dates
from .config import config
from .models import create_record
class RequestAction(Enum):
"""Represents one of the possible api services the Kimai API supports."""... |
from llvm.core import Builder, Constant, FCMP_ONE, FCMP_ULT, Type
from llvm.core import Function as Func
def create_alloca_block(function, name):
entry = function.get_entry_basic_block()
builder = Builder.new(entry)
builder.position_at_beginning(entry)
return builder.alloca(Type.double(), name=name)
... |
import sys
import math
sys.path.append(
"../../carla/PythonAPI/carla/dist/carla-0.9.10-py3.7-linux-x86_64.egg"
)
import toml
import carla
from constants import CAMERA_IMAGE_X, CAMERA_IMAGE_Y, CAMERA_HEIGHT_POS
class LiDARSetup(object):
def __init__(self, param_file, world, ego, callback_handler, setup=False... |
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright 2020 <NAME> (Nagoya University)
# Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
import os
import sys
import numpy as np
import yaml
import scipy.stats
import copy
from openpyxl import Workbook
from openpyxl import load_workbook
# STATISTICAL RESUL... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 1 10:22:37 2018
@author: inti.pedroso
"""
import numpy as np
import schwimmbad
import pandas as pd
from tqdm import tqdm
from scipy.stats import pareto, gamma, beta
from scipy.special import gammaln, expit
from scipy import logaddexp
from conflat... |
# SPDX-FileCopyrightText: 2020 <NAME> <<EMAIL>>
#
# SPDX-License-Identifier: Apache-2.0
import logging
import os
from typing import Optional, Dict, Callable, Tuple, List
import regex
import sys
import time
from codeprep.bpepkg.bpe_config import BpeConfig
from codeprep.bpepkg.bpe_encode import read_merges
from codepr... |
import os.path
import tensorflow as tf
import helper
import warnings
from distutils.version import LooseVersion
import project_tests as tests
# Check TensorFlow Version
assert LooseVersion(tf.__version__) >= LooseVersion('1.0'), 'Please use TensorFlow version 1.0 or newer. You are using {}'.format(tf.__version__)
pr... |
import argparse
import os
import numpy as np
from PIL import Image
import kitti_util
import sys
sys.path.append('../')
import object3d_utils.kitti_utils as od_utils
def generate_rect_from_velo(pc_velo, height, width, calib):
pts_2d = calib.project_velo_to_image(pc_velo)
fov_inds = (pts_2d[:, 0] < width - 1)... |
import os
#from qtpy.QtCore import Qt
from qtpy.QtWidgets import (
QApplication, QLabel, QPushButton, QLineEdit,
QGridLayout, QHBoxLayout, QVBoxLayout,
QComboBox, )
#from qtpy.compat import getexistingdirectory
from qtpy.QtWidgets import QLabel, QGridLayout, QVBoxLayout, QLineEdit
from pyNastran.gui.utils... |
from .. import utils
from .._lazyload import matplotlib as mpl
from .utils import _get_figure
from .utils import parse_fontsize
from .utils import temp_fontsize
import numpy as np
import warnings
plt = mpl.pyplot
@utils._with_pkg(pkg="matplotlib", min_version=3)
def create_colormap(colors, name="scprep_custom_cmap"... |
import re
import os
import sys
from Bio import Seq
from Bio import SeqIO
from Bio import SeqUtils
import pandas as pd
import numpy as np
from functools import partial
# for plotting ...
import matplotlib.pyplot as plt
import matplotlib as mpl
# font = {'family' : 'sans-serif',
# #'weight' : 'bold',
# 's... |
import pytest
from pyopenapi3 import OpenApiBuilder, create_schema
from pyopenapi3.builders import (
InfoBuilder,
ServerBuilder,
PathsBuilder,
ComponentBuilder,
)
from pyopenapi3.objects import (
Response,
Op,
JSONMediaType,
)
from pyopenapi3.data_types import (
Array,
Int32,
In... |
"""
fingerprints.py
---------------
Factories that take a Structure or multiple structures and produce
an interaction fingerprint.
"""
from collections import defaultdict, Counter
from tempfile import TemporaryDirectory
from pathlib import Path
import numpy as np
import pandas as pd
from Bio.AlignIO.FastaIO import ... |
import itertools
import numpy
import pytest
import time
from helpers import *
from .cbrng_ref import philox as philox_ref
from .cbrng_ref import threefry as threefry_ref
from reikna.core import Type
from reikna.helpers import product
from reikna.cbrng import CBRNG
from reikna.cbrng.bijections import threefry, philox
... |
import copy
import logging
import sys
logging.basicConfig(level=logging.INFO, stream=sys.stdout)
LOG = logging.getLogger(name="events")
class Singleton(object):
def __new__(type):
if not '_the_instance' in type.__dict__:
type._the_instance = object.__new__(type)
return type._the_insta... |
import os
import array
import copy
#1. check if a string has unique characters
# -> count chars in string, if a char occur more than two times, then it is not unique
# * should ask whether ASCII or Unicode. Case-sensitive or not
def is_unique(input):
# standard ascii has 128 chars (extended has 256 chars)
if l... |
import re
import tqdm
import pysam
import itertools
import pandas as pd
import numpy as np
from dohlee.genome import Region
from collections import defaultdict, Counter
def get_binary_string_representation(read):
"""Returns a binary representation string of methylation state of a read.
Unmethylated state = 0... |
from flax.training import checkpoints, lr_schedule
from jax import jit, value_and_grad
from jax import numpy as jnp
import numpy as np
import time
from .data import load_data, train_batches
from .forgetting import init_forget_stats, update_forget_stats, save_forget_scores
from .metrics import accuracy, correct, cross_e... |
from pycoingecko import CoinGeckoAPI
import datetime
import time
from prices import *
cg = CoinGeckoAPI()
# Useful functions
# bitcoin = cg.get_price(ids='bitcoin', vs_currencies='usd')
# datetime.datetime.now()
# datetime.datetime(2020, 5, 17)
# Pull prices for a cryptocurrency from CoinGecko
def get_prices... |
import pandas as pd
from output.helpers import *
from datetime import datetime
import emoji
import re
import string
import nltk
from nltk import ngrams, FreqDist
from nltk.sentiment import SentimentIntensityAnalyzer
from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer
from sklearn.feature_select... |
#!/usr/bin/env python
"""----------------------------------------------------
Helper functions for scikit-learn
: score_model
returns mean sq err, variance score
: autotune_alpha
finds alpha in range that maximizes the variance score
returns best_alpha, best_model
: train_withou... |
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compli... |
# Copyright 2021 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wr... |
import sqlite3
import pandas as pd
import os
schemata = {
'publication_basicinfo': [
{'field': 'publication_ppn', 'dtype': str, 'type': 'TEXT', 'constraints': 'NOT NULL PRIMARY KEY'},
{'field': 'isbn', 'dtype': str, 'type': 'TEXT', 'constraints': ''},
{'field': 'titelvermelding', 'dtype': str, 'type': 'TEXT', '... |
from typing import Counter, Optional, Union, Sequence
from .._compat import Literal
from anndata import AnnData
import pandas as pd
import itertools
from ._clonotypes import (
_common_doc,
_common_doc_parallelism,
_validate_parameters,
_doc_clonotype_definition,
)
from ..util import _doc_params, _is_na... |
# Future import build
from __future__ import print_function
# Import built-in module
import os
import argparse
# Import torch
import torch
import torchvision
import torch.nn as nn
import torch.optim as optim
import torch.distributed as dist
from tqdm import tqdm
# Import Custom Utils
from utils.fas... |
#!/usr/bin/env python
"""Prerequisite steps:
1. Check if the vpc_id exists in specified region.
2. Delete EC2 and RDS instances/clusters.
If there are running EC2 or RDS instances, you aren't ready to delete VPC.
Note: This script doesn't remove any VPN or TGW attachments/connections,
so it'... |
from cmath import inf
import time
import numpy as np
import torch
from onpolicy.runner.shared.base_runner import Runner
from tqdm import tqdm
def _t2n(x):
return x.detach().cpu().numpy()
class DroneRunner(Runner):
def __init__(self, config):
super().__init__(config)
self.eval_episodes = self.a... |
import argparse
import copy
import json
import pdb
import random
import re
import traceback
from collections import defaultdict, namedtuple
from itertools import product
import numpy as np
import torch
import torch.multiprocessing as mp
from pytorch_pretrained_bert.file_utils import PYTORCH_PRETRAINED_BERT_CACHE
from ... |
import json
import os
import random
import subprocess
from typing import Tuple, List
from unittest import TestCase
def _run_subprocess(args: List[str], check: bool = True) -> Tuple[str, str]:
prefix: str = "SUBPROCESS: "
for arg in args:
prefix += arg + " "
process = subprocess.run(
args, ... |
import collections
import logging
import os
import queue
import subprocess
import threading
import time
from pykube.config import KubeConfig
from pykube.http import HTTPClient
from pykube.objects import Pod
Host = collections.namedtuple('Host', 'action,name,ip')
class MultipleFilesHostsManager:
def __init__(se... |
"""A collection of helpful objects for DearPyGui.
"""
from contextlib import contextmanager
from typing import Union, Callable, Any, List, Dict, Tuple
from dearpygui import dearpygui as dpg, _dearpygui as internal_dpg
ItemT = Union[int, str]
@contextmanager
def push_container(item: ItemT) -> ItemT:
"""Push an e... |
# Enumerate or sample minimal solution to a monotone CNF
# Clauses can only contain positive literals
import random
# Dynamic management of clause
class Clause:
listStack = []
activeList = []
isTrue = False
isFalse = False
def __init__(self, clause):
self.listStack = []
self.a... |
# vim: set encoding=utf-8
# Copyright (c) 2016 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless require... |
#
# Copyright 2018-2022 Elyra 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 law or agreed to in writ... |
# 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 torch
from torch.utils.data import DataLoader, WeightedRandomSampler
import os
from sklearn.metrics import roc_auc_score
from models.nfm import NeuralFactorizationMachineModel
from models.hen import HENModel
from models.m3r import SeqM3RModel
from models.wd import WideAndDeepModel
from models.lstm4fd import LST... |
import cv2 # state of the art computer vision algorithms library
import numpy as np # fundamental package for scientific computing
import matplotlib.pyplot as plt # 2D plotting library producing publication quality figures
import pyrealsense2 as rs ... |
# Evaluate error metrics for model or submodel for a specified set of test
# dates. Output is stored in eval/metrics/MODEL_NAME/SUBMODEL_NAME. If no
# submodel is provided, the selected submodel for a model is evaluated.
#
# Example usage:
# python -m subseasonal_toolkit.batch_metrics contest_tmp2m 34w -mn climpp -t ... |
from flask import render_template, jsonify, request, current_app, session
from retrobiocat_web.app.retrobiocat import bp, forms
from rq import get_current_job
import networkx as nx
import json
from flask import current_app
from rq.job import Job
from retrobiocat_web.retro.generation.network_generation.network import Ne... |
# !pip3 install streamlit
from io import BytesIO
import base64
import datetime
import streamlit as st
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import yfinance as yf # https://pypi.org/project/yfinance/
##############################
# Technical Analysis Classes #
########################... |
import PySimpleGUI as sg
from tkinter import *
from tkinter import simpledialog
from tkinter import messagebox
from PIL import ImageTk, Image,ImageFilter
import os
import math
import cv2
from os import listdir
from os.path import isfile, join
import numpy as np
from itertools import cycle
import json
def writeToJSONFi... |
import json
import os
import subprocess
import tempfile
import unittest
import yaml
from .. import *
from mopack.iterutils import listify
from mopack.platforms import platform_name
# Also supported: 'apt', 'mingw-cross'
test_features = {'boost'}
for i in os.getenv('MOPACK_EXTRA_TESTS', '').split(' '):
if i:
... |
import yt
import numpy as np
import matplotlib.pyplot as plt
from yt.visualization.image_writer import map_to_colors as mtoc
class TFsegment(object):
def __init__(self,TFob,**kwargs):
bnds=kwargs.get('bounds',None)
if bnds is None:
self.dvbins=TFob.dvbins
self.dvbins_c=TFo... |
#!/usr/bin/python3
"""
Convert json string to golang struct.
"""
import os, json
space = " "
fmt = "{0}{1:25s}{2:15s}`json:\"{3}\"`\n"
list_fmt = "{0}{1:25s}[]{2:13s}`json:\"{3}\"`\n"
structs = {}
def normallize(name) :
return name.capitalize()
def conv_list(jlist, struct_name, key_name, old_key) :
"""
Conver... |
import os
import random
import torch
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.pylab as mp
from scipy.io import loadmat
from torch.utils.data import Dataset, DataLoader, random_split
def sample_plot(dataset_name, obs_name, n, ind, cnd):
'''
读取单个mat文件并查看结果
'''
data = loadma... |
# -*- coding:utf-8 -*-
# @Time: 2021/1/18 8:49
# @Author: <NAME>
# @Email: <EMAIL>
# @File: syntaxana.py
# -*- coding: utf-8 -*-
'''
powered by NovalIDE
来自NovalIDE的词法分析模块
作者:侯展意
词法分析模块的重要组成单元、
依靠各种正则表达式进行特征的提取。
'''
from typing import List, Tuple, Dict
import re
def getReplacingDic() -> Dict:
dic = {}
dic[','... |
import logging
import os
import shutil
import numpy as np
import torch
from pytorch_metric_learning.utils import common_functions as pml_cf
from sklearn.model_selection import train_test_split
from torchmetrics.functional import accuracy as tmf_accuracy
from ..adapters import Finetuner
from ..containers import Models... |
from lxml import html
import requests
import pandas as pd
from datetime import datetime
pd.set_option('display.max_columns', 20)
pd.set_option('display.width', 1000)
headers = {
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'... |
from flask import render_template, flash, redirect, url_for
from app import app
from app.forms import LoginForm
from flask_login import current_user, login_user ,logout_user
from app.models import User, Info, Problem, Commit
from flask import request
from werkzeug.urls import url_parse
from flask_login import login_req... |
import ast
import logging
from bisect import bisect
from .evaluator import Evaluator
from .names import NameExtractor, create_name, ArgumentName, VarargName
from .names import ClassName, FunctionName, ImportedName, PostponedName
from .common import ListHolder, create_object_from_class_name, create_object_from_expr
de... |
import torch
import torch.nn as nn
def add_layer(seq, ix, n_inputs, n_outputs, nonlin, normalization):
seq.add_module('L'+str(ix), nn.Linear(n_inputs, n_outputs))
if ix > 0 and normalization: # only LN/IN after first layer.
if normalization == 'LN':
seq.main.add_module('A'+str(ix), nn.Laye... |
"""
calc2tex.calc_formula
~~~~~~~~~~~~~~~~~~~~~
Processes a formula into valid LaTeX and
calculates its value.
:copyright: 2020 by <NAME>
:license: MIT
"""
from .helpers import is_float, intfloat
from .settings import quotation_marks
import re
from calc2tex import calc_formula
search_co... |
##################################################
# Copyright (c) <NAME> [GitHub D-X-Y], 2019 #
##################################################
import os, sys, time
from copy import deepcopy
import torch
import torchvision.transforms as transforms
from shutil import copyfile
from utils import print_log, obtain_acc... |
import itertools
import os
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
from common.collector import Collector
from common.network import Container
from common.utils import clone_network, sync_params, init_optimizer, clip_grad_norm
from .network import StateEncoderWrapper, Actor, ... |
#Name: Status Melodies 15.03
#Info: Add status melodies for print started, heat up finished, and print finished.
#Depend: GCode
#Type: postprocess
#Param: print_started_string(string:fifth:d=4,o=5,b=63:8P,8G5,8G5,8G5,2D#5) Print started (RTTTL)
#Param: heat_up_finished_string(string:fifth:d=4,o=5,b=63:8P,8G5,8G5,8... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
import random
from furl import furl
from httmock import all_requests, response
from surveymonkey.tests.utils import weighted_choice
from surveymonkey.tests.mocks.utils import create_quota_headers, BaseListMock
from surveymonkey.collectors.configs import ... |
import dataclasses
from typing import List
import discord
import genshin.errors
from discord import (
Option,
ApplicationContext,
SlashCommandGroup,
SelectOption,
)
from discord.ext import commands
from genshin.models import GenshinAccount
from sqlalchemy import select, delete, func
from tenacity impor... |
#!/usr/bin/env python3
import argparse
import grpc # type: ignore
import helloworld_pb2
import helloworld_pb2_grpc
import logging
import random
import threading
import time
import typing
import typing_extensions
_CONNECTIVITY_CODE_MAP = {
grpc.ChannelConnectivity.IDLE.value[0]: grpc.ChannelConnectivity.IDLE,
... |
# -*- coding: utf-8 -*-
import os, cv2, sys, random, warnings
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from tqdm import tqdm
from skimage.io import imread, imshow, imread_collection, concatenate_images
from skimage.transform import resize
from skimage.morphology import label
f... |
from __future__ import absolute_import, unicode_literals
from contextlib import contextmanager
import pytest
from case import Mock, mock, patch
from celery.fixups.django import (DjangoFixup, DjangoWorkerFixup,
FixupWarning, _maybe_close_fd, fixup)
class FixupCase:
Fixup = None... |
from os import remove
import h5py
import numpy as np
from pytest import fixture, raises
import trcdproc.compute.absorp as compute
@fixture(scope='function')
def delta_a_clean_input_data():
"""Constructs an HDF5 file with specific values for the different signals for the sake of
testing the correctness of th... |
# coding=utf-8
from sklearn import metrics
from keras.layers import Reshape
from keras.callbacks import EarlyStopping
from keras import Input, Model
from keras.layers import Dense, Conv1D, GlobalMaxPooling1D, Concatenate
import pandas as pd
import numpy as np
import gensim
from sklearn import preprocessing
from sklearn... |
""" Copyright 2016-2022 by Bitmain Technologies Inc. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applica... |
# -*- coding: utf8 -*-
from ircBase import *
from random import randint
import MySQLdb as mdb
import ConfigParser
import os, sys, subprocess, time, datetime
config = ConfigParser.SafeConfigParser()
config.read('configs/ircBase.conf')
CONST_DB_USER = config.get('MySql', 'username')
CONST_DB_PASSWORD = config.get('MySq... |
#!/usr/bin/python3
from sys import stdout
__all__ = ["Chromos"]
"""Package for getting colored text output in Python terminal
"""
class Chromos():
"""Chromos provides colored-text terminal output.
Colors:
Black -- black
Red -- red
Green -- green
Yellow ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jun 20 10:51:54 2019
@author: xiayezi
"""
from utils.conf import *
import pandas as pd
import os
#vocab_table_full = [chr(97+int(v)) for v in range(26)]
vocab_table_full = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t... |
"""
Finds faces of 3d form, given the perimeter and foldlines
"""
#From http://stackoverflow.com/questions/2827393/angles-between-two-n-dimensional-vectors-in-python
import math
import numpy
def dotproduct(v1, v2):
return sum((a*b) for a, b in zip(v1, v2))
def length(v):
return math.sqrt(dotproduct(v, v))
def c... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.