text stringlengths 3.07k 12.6k |
|---|
import pytest
from network_analyzer.analyzer import Analyzer
from network_analyzer.csv_export import OUTPUT_FILE_BRIDGE, TLC_DIVISOR
ZERO_ADDRESS = "0x" + "0" * 40
@pytest.fixture(scope="session")
def temporary_path(tmpdir_factory):
return tmpdir_factory.getbasetemp()
@pytest.fixture(scope="session")
def anal... |
import re
import warnings
from ..dialect import Dialect
from ..parser import Parser
from ..plugin import Plugin
from ..schema import Schema
from ..field import Field
from .. import helpers
# Plugin
class SpssPlugin(Plugin):
"""Plugin for SPSS
API | Usage
-------- | --------
Public | `from fr... |
# -*- coding: utf-8 -*-
#
# Small object that can be passed around easily, that represents
# our signing credentials, and can sign data.
#
# Unfortunately the installed python OpenSSL library doesn't
# offer what we need for cms, so we also need to shell out to the openssl
# tool, and make sure it's the right version.
... |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import numpy as np
import unittest
import cv2
import torch
from cvpods.utils import benchmark
from cvpods.layers.roi_align import ROIAlign
class ROIAlignTest(unittest.TestCase):
def test_forward_output(self):
input = np.arange(25).res... |
import os
# from IPython import embed
import scipy.io as sio
import cv2
import numpy as np
from imageio import imread, imsave
import argparse
import pickle
import glob
# from scipy.misc import imread
# from scipy.misc import imread, imsave
# Convert occlusion and fold ground truth into a matlab structure which is com... |
import logging.config
import pprint
from ibmsecurity.appliance.qradarappliance import QRadarAppliance
from ibmsecurity.user.applianceuser import ApplianceUser
from ibmsecurity.user.qradaruser import QRadarUser
import pkgutil
import importlib
import yaml
import json
def import_submodules(package, recursive=True):
... |
# <NAME>, Feb 2017
# <NAME>, Apr 2017
import os, sys
import numpy as np
from PIL import Image
import random
import torch
import torch.utils.data as data
import torchvision.transforms as transforms
import pdb
dd = pdb.set_trace
views = ['200', '190', '041', '050', '051', '140', '130', '080', '090']
pi = 3.1416 # 180 ... |
## test_attack.py -- sample code to test attack procedure
##
## Copyright (C) 2016, <NAME> <<EMAIL>>.
##
## This program is licenced under the BSD 2-Clause licence,
## contained in the LICENCE file in this directory.
import tensorflow as tf
import numpy as np
import time
from PIL import Image
import matplotlib.pyplot ... |
import cv2
import numpy as np
import cv2
#
# draw text
#
def get_textsize(text, thickness, fontscale):
(text_w, text_h), baseline = cv2.getTextSize(text,
cv2.FONT_HERSHEY_SIMPLEX,
fontscale,
... |
# encoding: utf-8
"""
notification.py
Created by <NAME> on 2009-11-05.
Copyright (c) 2009-2017 Exa Networks. All rights reserved.
License: 3-clause BSD. (See the COPYRIGHT file)
"""
import string
from exabgp.util import character
from exabgp.util import ordinal
from exabgp.util import concat_bytes
from exabgp.util i... |
"""
Wolf, sheep, vegetables and farmers crossing the river
Farmers need to transport wolves, sheep, vegetables and themselves to the other side of the river. Only the farmer can
row a boat, and the boat is relatively small, except for the farmer.
If there is no farmer watching, sheep will steal food, wolves will eat ... |
# movie-recognize-tool
# The MIT License (MIT)
# Copyright (c) 2015 <NAME> 'Ezak91' <EMAIL>
#
# 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 restriction, including without limi... |
import os
import collections
import json
import torch
import torchvision
import numpy as np
import scipy.misc as m
import scipy.io as io
from glob import glob
import os.path
import re
import random
import cv2
from torch.utils import data
import pathlib
KITTI_CLASSES= [
'BG','Car','Van','Truck',
'Pedestrian','P... |
#!/usr/bin/env python
# Copyright (c) 2017 Trail of Bits, 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 applic... |
# -*- coding: UTF-8 -*-
# This file is a part of pycerberus.
# The source code contained in this file is licensed under the MIT license.
# See LICENSE.txt in the main project directory, for more information.
# SPDX-License-Identifier: MIT
from __future__ import absolute_import, print_function, unicode_literals
from p... |
#!/usr/bin/python3
"""Script to generate pprof CPU profile reports from a set of data files.
"""
import getopt
import os
import shutil
import sys
import tempfile
import script_utils as u
# Echo command before executing
flag_echo = True
# Dry run mode
flag_dryrun = False
# Input files
flag_infiles = []
# Output d... |
"""
Deals with GUI aspects of MCMC
"""
import os
import numpy as np
from PyQt5 import QtCore, QtGui, QtWidgets, uic
from refnx.analysis import (
load_chain,
process_chain,
autocorrelation_chain,
integrated_time,
GlobalObjective,
Objective,
)
from refnx.reflect import Structure
from matplotlib.b... |
import torch
import torch.nn as nn
KAMSE_WEIGHT = 10
def checkBad(label, vars, names):
for name, var in zip(names, vars):
if torch.isnan(var).any() or torch.isinf(var).any():
print("\n\n", label, "\n\n")
print(name)
print("Max", torch.max(var))
... |
# -*- coding: utf-8 -*-
from base import *
from requests import *
from service import FastCGI
from io import BytesIO
import time
import hashlib
def generate_body(seed, size):
i = 0
body = BytesIO()
while body.tell() < size:
body.write(hashlib.sha1((seed + str(i)).encode('utf-8')).digest())
i += 1
return body.... |
from larry.core import copy_non_null_keys
from larry.s3 import split_uri
from larry.types import Box
import boto3
import io
# A local instance of the boto3 session to use
__session = boto3.session.Session()
__client = __session.client('textract')
def set_session(aws_access_key_id=None,
aws_secret_acc... |
import tkinter as tk
import math
def select_k_of_n_with_duplicates(index, selections, items, results):
""" Generate combinations allowing duplicates."""
# See if we have made the last assignment.
if index == len(selections):
# Add the result to the result list.
result = ""
... |
from dataset.dataset import test_transform
import cv2
import pandas.io.clipboard as clipboard
from PIL import ImageGrab
from PIL import Image
import os
import sys
import argparse
import logging
import yaml
import re
import numpy as np
import torch
from torchvision import transforms
from munch import Munch
from transfo... |
import looker
import os
import requests
import sys
import time
import queue
import logging
import numpy as np
from concurrent.futures import ThreadPoolExecutor, wait
IGNORABLE_SQL_ERROR = 'could not devise a query plan'
def get_token_client():
"""
Authenticate user credentials and return token
{ LOOKE... |
# Copyright 2020, <NAME>, mailto:<EMAIL>
#
# Part of "Nuitka", an optimizing Python compiler that is compatible and
# integrates with CPython, but also works on its own.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the Lice... |
import numpy as np
import scipy as sc
import pandas as pd
from math import log2, log10
from collections import Counter
import math
import time
"""
All metrics will be evaluated at both the track level (exact track must match)
and the artist level (any track by that artist is a match).
"""
def timing(f):
"""
... |
# Copyright (c) 2015 <NAME>
#
# See the file license.txt for copying permission.
import logging
import asyncio
import binascii
import datetime
from passlib.apps import custom_app_context as pwd_context
from hbmqtt.plugins.secp256k1 import schnorr, ecdsa
class BaseAuthPlugin:
def __init__(self, context):
... |
import os
import pandas as pd
import luigi
import util
import aminer
import config
class PathBuilder(object):
def convert_path(self, fname, suffix):
base, ext = os.path.splitext(fname)
fname = '%s-%s' % (os.path.basename(base), suffix)
fname = '%s.csv' if not ext else '%s%s' % (fname, ex... |
# Copyright (C) 2013 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By:
# Maintained By:
import datetime
import json
from behave import given, when, then
from iso8601 import parse_date
class DateTimeEncoder(json.JSONEn... |
from elasticsearch_dsl import DocType, Completion
from elasticsearch_dsl.field import (
String, Date as ESDate, Float, Boolean
)
from elasticsearch_dsl import FacetedSearch
from elasticsearch_dsl import TermsFacet, DateHistogramFacet
from elasticsearch_dsl.query import Q
from six import itervalues
import collection... |
from collections import Counter
import glob
from lemmatizer import *
from util import *
ngram = 6
freqList = []
freqId = {}
def getFreqId(word):
if word == -1:
return 0
return freqId[word]
# Represents a sentence and its audio
class Note:
def __init__(self, original, audio, translation, lemm... |
import pytest
from ledger.util import F
from plenum.client.wallet import Wallet
from plenum.common.constants import STEWARD
from plenum.common.txn_util import get_seq_no
from sovtoken.main import integrate_plugin_in_node
from sovtoken.util import \
register_token_wallet_with_client, update_token_wallet_with_result... |
# -*- coding:utf-8 -*-
# Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the MIT License.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the ... |
# USAGE
# python ball_tracking.py --video ball_tracking_example.mp4
# python ball_tracking.py
# import the necessary packages
from collections import deque
from imutils.video import VideoStream
import numpy as np
import argparse
import cv2
import imutils
import time
import threading
from px_2_xyz import px_2_xyz
from ... |
# -*- coding: utf-8 -*-
# Imports
import os,sys
import glob
import math
import argparse as ap
# Script information
__author__ = "<NAME>"
__version__ ="1.0"
__maintainer__="<NAME>"
__email__="<EMAIL>"
def storePDBfilenames(PDBs_to_parse, parser):
"""It identifies the PDB files to add to the PDBProcessor4PELE to... |
# Licensed to the .NET Foundation under one or more agreements.
# The .NET Foundation licenses this file to you under the Apache 2.0 License.
# See the LICENSE file in the project root for more information.
import sys
import unittest
from iptest import IronPythonTestCase, is_cli, run_test
long = type(sys.maxsize + 1... |
import numpy as np
import pycuda.driver as cuda
from pycuda.compiler import SourceModule
from pycuda.tools import make_default_context, clear_context_caches
import glob
import sys
import os
from datetime import datetime
import ctypes
import atexit
import argparse
import subprocess
import psutil
import itertools
from... |
from __future__ import annotations
import logging
from datetime import datetime, timedelta
from decimal import Decimal
from typing import Any
from homeassistant.components.integration.sensor import (
TRAPEZOIDAL_METHOD,
IntegrationSensor,
)
from homeassistant.components.sensor import DOMAIN as SENSOR_DOMAIN
f... |
#!/usr/bin/env python3
'''ncbigene_tsv_to_kg_json.py: Extracts a KG2 JSON file from the NCBI human gene distribution in TSV format
Usage: ncbigene_tsv_to_kg_json.py [--test] <inputFile.tsv> <outputFile.json>
'''
__author__ = '<NAME>'
__copyright__ = 'Oregon State University'
__credits__ = ['<NAME>']
__license__ = ... |
r"""JPServer is a Python script executor running on the Python side.
JPServe receiving and executing the script from 3rd-part languages,
then send back the result as JSON format to the caller.
Usages:
- Start server
server = JPServe(("hostname", port))
server.start()
- Stop server
server.shutd... |
import psycopg2
import traceback
import re
from models.user import Users
from models.core.config import config_string
from models.conversation import ContentFinderJoin,Content,BotContents,NextMessageFinders
from models.core.pushModels import push_intent_list,push_context_list,push_trigger_list,Keyboards,Language,Langu... |
"""Contains the extension setup.
"""
from pathlib import Path
from typing import Dict, Any
from sphinx.domains import ObjType
from sphinx.application import Sphinx
from sphinxcontrib.autodoc_pydantic.directives.autodocumenters import (
PydanticValidatorDocumenter,
PydanticModelDocumenter,
PydanticConfig... |
import re
from traceback import print_exc
import requests
from django import template
from django.contrib.admin.templatetags.admin_list import result_list as _result_list
from django.contrib.staticfiles import finders
from django.core.cache import InvalidCacheBackendError, caches
from django.core.paginator import Pagi... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2020 Confluent 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 requi... |
import torch
import torch.nn as nn
import math
import torch.optim as optim
from torchvision import datasets
from torchvision.transforms import ToTensor
from torch.utils.data import DataLoader, random_split
import time
import torch.optim.lr_scheduler as lr_s
class Sparse(nn.Module):
def __init__(self, input_size ... |
#!/usr/bin/env python3
# Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
import json
import os
import subprocess
import sys
import yaml
def find(json, path, separator = "."):
if len(path) == 0: return json
head, _, rest = path.partition(separator)
ret... |
""" Contains upgrade tasks that are executed when the application is being
upgraded on the server. See :class:`onegov.core.upgrade.upgrade_task`.
"""
from collections import defaultdict
from onegov.core.upgrade import upgrade_task
from onegov.core.orm.types import JSON, UUID
from onegov.user import User, UserCollectio... |
# 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
from .. import _utilitie... |
#!/usr/bin/env python3
import click
import os
import json
from datetime import datetime
import functools
ANSIBLE_CONFIG='/etc/ansible/ansible-oi.cfg'
PLAYBOOKS='/usr/share/oi-bus/playbooks'
BACKUPDIR='/var/lib/oi-bus/golden'
opt_ask = None
opt_dry = False
default_ask = None
extra_env = {}
def should_ask(is_dangerous... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from model.layer.resnn import ResNN
from model.layer.extnn import ExtNN
from model.layer.concat_conv import ConcatConv
from model.layer.conv_lstm import ConvLSTM
class ModelConfigurationTaxiBJ:
"""
Change the class ModelConfiguration freely to ... |
import websockets
import json
import logging
import asyncio
from abc import ABC, abstractmethod
from typing import List, Callable, Any
from bitpanda.Pair import Pair
from bitpanda import enums
LOG = logging.getLogger(__name__)
class Subscription(ABC):
def __init__(self, callbacks = None):
self.callbacks = callbac... |
from pytorch_lightning.metrics.functional import accuracy, auroc, average_precision, roc, f1
import torch
import numpy as np
import dgl
import time
from utils import get_current_ts, get_args
def eval_epoch(args, logger, g, dataloader, encoder, decoder, total_updater, aggr, msg2mail, loss_fcn, device, num_samples):
... |
# coding=utf-8
# Copyright 2020 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... |
""" Solves a variation of optimization problem of targeted Pagerank.
It solves the targeted optimization problem as described
in "Fairness-Aware Link Analysis"[1] paper but for the topk of the
pagerank algorithm. It also preserve the order of these nodes compare
to simple targeted. Makes use of cvx optimization p... |
from __future__ import print_function
from keras.applications.inception_resnet_v2 import InceptionResNetV2, preprocess_input
from keras.models import Model, load_model
from keras.layers import Dense, GlobalAveragePooling2D
from keras import optimizers
from keras import metrics
import matplotlib.pyplot as plt
from ker... |
from http import HTTPStatus
import pytz
from flask import Response
from flask import abort
from flask import g
from flask_restx import Namespace
from flask_restx import Resource
from flask_restx import fields
from models import ResultTable
from models import ScanTable
from storages import Storage
from utils.scan impo... |
import logging
import os
import dazl
from dazl import create, exercise, exercise_by_key
dazl.setup_default_logger(logging.INFO)
SID = 1 # default SID, use ExberrySID contract to change while running
def get_sid() -> int:
global SID
SID = SID + 1
return SID
sid_to_order = {}
class EXBERRY:
NewOrderR... |
from .CancerModel import CancerModel
from ..plotting import create_measurement_dict
import pandas as pd
import numpy as np
# ---- TreatmentResponseExperimentObject
class TreatmentResponseExperiment:
"""
This class contains all CancerModel objects for a given treatment response experiment.
Attributes:
... |
import io
import subprocess
import os
import pandas as pd
import io
import sdi_utils.gensolution as gs
import sdi_utils.set_logging as slog
import sdi_utils.textfield_parser as tfp
import sdi_utils.tprogress as tp
try:
api
except NameError:
class api:
class Message:
def __init__(self,body ... |
# -*- coding: utf-8 -*-
import os
import sys
import copy
import pathlib
from difflib import get_close_matches
from collections import defaultdict
from configparser import ConfigParser, ExtendedInterpolation
from ast import literal_eval
TRAIN_DEFAULTS = {
'num_workers': 0, # number of workers for data... |
"""
This file is part of YAOS and is licenced under the MIT Licence.
"""
import sys, os, mmap, ctypes, stat, time, random
from ctypes import util, cdll
import ZynqScope.ZynqScope as zs
import ZynqScope.armwave.armwave as aw
import multiprocessing
DEFAULT_SCALED_INTENSITY = 5
# catch SIGSEGV, SIGABRT, etc.
import f... |
import json
import os
import re
import sys
import xml.etree.cElementTree as ET
from collections import OrderedDict
from datetime import date, timedelta
from flask import Flask, request, Response, send_file, send_from_directory
from xml.dom import minidom
def read_cache(json_path):
'''
Populate books dict from ... |
#################################################################################
# The Institute for the Design of Advanced Energy Systems Integrated Platform
# Framework (IDAES IP) was produced under the DOE Institute for the
# Design of Advanced Energy Systems (IDAES), and is copyright (c) 2018-2021
# by the softwar... |
import cv2
import torch
from model import U2NET
from torch.autograd import Variable
import numpy as np
from glob import glob
import os
def detect_single_face(face_cascade,img):
# Convert into grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Detect faces
faces = face_cascade.detectMultiScale(gr... |
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt
from __future__ import unicode_literals
"""assign/unassign to ToDo"""
import frappe
from frappe import _
from frappe.desk.form.document_follow import follow_document
from frappe.desk.doctype.notification_log.notificati... |
import os
import torch
import numpy as np
import torch.utils.data as data
import torchvision.transforms as transforms
from PIL import Image
class SalObjDataset(data.Dataset):
def __init__(self, image_roots, gt_roots, depth_roots, anno_paths, trainsize):
self.trainsize = trainsize
self.images = []
... |
import numpy as np
import numpy.matlib as nm
import matplotlib.mlab as mlab
from svgd import SVGD
class Bimodal:
def __init__(self, mu1, var1, mu2, var2):
self.mu1 = mu1
self.var1 = var1
self.mu2 = mu2
self.var2 = var2
def gaussian(self, x, mu, var):
return np.exp(-np.p... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# from __future__ import annotations # isort:skip
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from __future__ import annotations
from typi... |
import logging
import re
import dateutil
from cvss.cvss3 import CVSS3
from defusedxml import ElementTree
LOGGER = logging.getLogger(__name__)
def parse(file):
nscan = ElementTree.parse(file)
root = nscan.getroot()
namespace = get_namespace(root)
if not namespace.startswith("{http://cyclonedx.org/sch... |
# Copyright (C) 2017 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
"""The module provides service creating and manipulating GGRC's business
objects via Web UI."""
from lib.constants import element
from lib.entities.entities_factory import (
AsmtTmplFactory, AsmtFactory,... |
from dexy.filter import DexyFilter
import base64
import dexy.exceptions
import json
import urllib
try:
import nbformat
AVAILABLE = True
except ImportError:
AVAILABLE = False
class IPythonBase(DexyFilter):
"""
Base class for IPython filters which work by loading notebooks into memory.
"""
a... |
"""records by year"""
import datetime
import psycopg2.extras
import pandas as pd
from pyiem.plot.use_agg import plt
from pyiem.util import get_autoplot_context, get_dbconn
from pyiem.exceptions import NoDataFound
def get_description():
""" Return a dict describing how to call this plotter """
desc = dict()
... |
# coding=utf-8
# Copyright 2020 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 -*-
import re
from django.db import models
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext_lazy as _
from django.template.defaultfilters import slugify
from mptt.models import MPTTModel, TreeForeignKey
from cms.models.fields import PlaceholderField
from cm... |
import matplotlib.pyplot as plt
import numpy as np
def average_data(data):
num_repeats = len(data[:, 0])
num_x_vals = len(data[0, :])
y_av = np.zeros(num_x_vals)
y_std_error = np.zeros(num_x_vals)
for x in range(num_x_vals):
y_av[x] = np.mean(data[:, x])
y_std_error[x] = np.std(da... |
import logging
from itertools import islice
from ..document import PDFDocument
from ..types.content import Operator, InlineImage
from ..types.objects import StreamBasedObject
from .graphicsstate import GraphicsStateStack, GraphicsState
from .resources import Resources
class PageDoesNotExist(ValueError):
""" Exc... |
from typing import Optional, List, Union, Any
from fastapi import APIRouter, status, Cookie, UploadFile, File, Query, Security
from fastapi.responses import JSONResponse
from starlette.responses import Response
from exceptions import OutputError, CategoryNotUnique, Error, CategoryNotFound
from languages.errors.message... |
from functools import wraps
from flask import Flask, session, redirect, url_for, request, jsonify, render_template, abort, send_file
from flask_cas import CAS, login_required, login, logout
import csv
import datetime
import hashlib
import io
import json
import os
import uuid
import models
def get_pepper():
try:... |
import subprocess
import sys, threading
from subprocess import Popen
from queue import Queue
from typing import Callable, Optional, List
import os
import platform
from subprocess import PIPE, Popen
from typing import List, Optional
import threading
import tempfile
from queue import Queue
from PyQt5 import QtCore, QtWid... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 3 16:45:13 2018
@author: islab
"""
import tempfile
import os
import pickle
import random
from tensorflow.contrib.learn.python.learn.datasets.mnist import read_data_sets
from .base_provider import ImagesDataSet, DataProvider
import numpy as np
clas... |
import numbers
import time
import threading
import logging
from pcdsdaq.daq import Daq
from pcdsdaq.ext_scripts import hutch_name, get_run_number # NOQA
logger = logging.getLogger(__name__)
class SimNoDaq(Daq):
def connect(self):
logger.debug('SimNoDaq.connect()')
conn_err = None
class Control:
... |
"""For making plots."""
import matplotlib.pyplot as plt
import numpy as np
from asaplib.fit import LC_SCOREBOARD
from asaplib.fit.getscore import get_score
def plot_compare_train_pred(
by_model, model_key_now, show=True, save=True, file_prefix="benchml", histogram_bins=30
):
pred_min, pred_max = float("inf")... |
from __future__ import annotations
from collections.abc import Callable, Iterable
from typing import Any, Optional, Union
# TODO: Move this to a different file.
def format_currency(amount: int) -> str:
return f'{amount:,} 💰'
prefixes: tuple[tuple[int, str], ...] = (
(2 ** 32 - 1, '💎'),
(1_000_000_000, '... |
import functools
from django import forms
import json
from django.core.exceptions import ValidationError
from django.db import transaction
from django.utils.safestring import mark_safe
from .models import Application, Address, Guardian, Profile
APP_MAP = {
"short": forms.CharField,
"long": functools.partial(f... |
# vCloud CLI 0.1
#
# Copyright (c) 2014-2018 VMware, Inc. All Rights Reserved.
#
# This product is licensed to you under the
# Apache License, Version 2.0 (the "License").
# You may not use this product except in compliance with the License.
#
# This product may include a number of subcomponents with
# separate copyrig... |
# -*- coding: utf-8 -*-
__docformat__ = 'restructuredtext en'
from xml.etree.cElementTree import Element, parse
import os
from bitten.api import IReportChartGenerator, IReportSummarizer
from bitten.util import xmlio
from trac.core import *
from trac.web.chrome import ITemplateProvider
import pkg_resources
class Ro... |
from django.test import TestCase
from django.db import models
from ostinato.statemachine import State, StateMachine
from ostinato.statemachine import (
InvalidState,
InvalidTransition,
InvalidStateMachine)
from ..workflow import *
from ..models import TestModel
class StateTestCase(TestCase):
def te... |
from flask import jsonify
from webargs import fields
from webargs.flaskparser import use_args
from src.blueprints import host
from src.core import database, helpers
from src.core.auth_helpers import authorize_route
@host.get("/")
@use_args(
{
"uid": fields.String(missing=""),
"handle": fields.St... |
import discord
from discord.ext import commands, tasks
import random
import json
import asyncio
# Guess will be made with the /guess [word] command in dms
# Wordle 234 # The number of wordles that have passed 2/6 # Your current number of tries
# ⬛🟨⬛⬛⬛titan # The word you inputted
# ⬛🟩🟩⬛🟩 skill
# So C... |
import os
from json import load
from typing import Dict
import requests
from django.conf import settings
from django.http import HttpResponse
from django.apps import apps
from django.db import models as djangoModels
import importlib
from requests.exceptions import ConnectionError
def registerFunction():
registry... |
# ------
# THE 'PRESENTATION LAYER' OF THE PROGRAM
# ------
import time
from collections.abc import Callable
# import logging
# logging.basicConfig(level=logging.DEBUG)
# Dependencies from first-party modules.
from . import commands as commands
from .utilities import clear_screen
def format_bookmark(bookmark, fiel... |
#!/usr/bin/python
import os
from argparse import ArgumentParser
import psycopg2.extras
import requests
from requests.auth import HTTPBasicAuth
from ebi_eva_common_pyutils.logger import logging_config
from ebi_eva_common_pyutils.metadata_utils import get_metadata_connection_handle
from ebi_eva_common_pyutils.pg_utils ... |
import pytest
import db
import db_sqlite3
class DriverTests(object):
def clear_drivers(self):
db._NAMED_DRIVERS = {}
db.drivers._DRIVERS = {}
def make_driver(self, label):
class TestDriver(db.drivers.Driver):
URL_SCHEME = "test"
PARAM_STYLE = "qmark"
... |
from dataclasses import dataclass
import logging
from typing import Union, Tuple, Sequence, Any, Optional # noqa: F401
import numpy as np
import wiggin_mito.forces
import wiggin
from wiggin.core import SimAction
import looplib
import looplib.looptools
import polychrom
import polychrom.forces
logging.basicConfig(l... |
import os
import numpy as np
import pyutils.filename as fn
import pyutils.ctutils.driver as ctd
import pyutils.ctutils.flame as ctf
def counterflow_premixed_extinction(
chemistry = 'FFCM-1.cti',
fuel = {'CH4':1.},
oxidizer = {'O2':1., 'N2':3.76},
T = 300.,
p = 1.,
phi = 1.,
**kwargs):
... |
import os, sys
import copy
import glob
import yaml
import argparse
import torch
from torch import nn
from torch.utils import data
from torch.utils.tensorboard import SummaryWriter
import torch.distributed as dist
import torch.multiprocessing as mp
torch.cuda.empty_cache()
import numpy as np
import pandas as pd
from... |
import time
import numpy as np
import torch
import torch.nn as nn
from torch.autograd import Variable
import torch.optim as optim
from model import LinearPolicy, MLPPolicy
def train_dynamics_model(dynamics, dynamics_optimizer, trainset, epochs=1, batch_size=1):
# Loss
criterion = nn.MSELoss() # MSE/SmoothL... |
import torch.nn as nn
import MinkowskiEngine as ME
from models.model import Model
from models.modules.common import ConvType, NormType, get_norm, conv, sum_pool
from models.modules.resnet_block import BasicBlock, Bottleneck
class ResNetBase(Model):
BLOCK = None
LAYERS = ()
INIT_DIM = 64
PLANES = (64... |
import json
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
DATA_PATH = "data.json"
SAVED_MODEL_PATH = "audio_model.h5"
EPOCHS = 40
BATCH_SIZE = 32
PATIENCE = 5
LEARNING_RATE = 0.0001
Num_keywords = 31
def load_data(data_p... |
#!/usr/bin/env python3
"""Rotate a matrix by 90 degrees.
Usage: ./rotate_matrix [OPTION] ...
Options:
-h, --help\tPrint this message.
-m, --mode\tCreate ("create") the matrix yourself or generate an enumerated one (any other string, default).
-n, --dim\tDimension of the matrix. Will be prompted if not set... |
# 导入工具包
import numpy as np
import argparse
import imutils
import cv2
# 设置参数
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", required=True,
help="path to the input image")
args = vars(ap.parse_args())
# 正确答案
ANSWER_KEY = {0: 1, 1: 4, 2: 0, 3: 3, 4: 1}
def order_points(pts):
# 一共4个... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.