content stringlengths 5 1.05M |
|---|
# Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0
# For details: https://github.com/gaogaotiantian/progshot/blob/master/NOTICE.txt
import io
from progshot import shoot, dump
class BenchmarkCase:
def __init__(self):
self.s = io.StringIO()
self.big_string = "abc"*1000... |
"""
```append_question``` is used to change the current flow, like booklink2reply
```append_unused``` is used to add questions that lead to the concrete_book_flow,
e.g. should be responded by a bookname.
"""
import logging
import sentry_sdk
from os import getenv
import random
from common.constants import CAN_CONTINUE_... |
from flask import abort, request, render_template, jsonify, send_file
import psycopg2
import sys
import os
import time
import glob
import json
import re
import subprocess
import tempfile
import math
from utils.jsonp import jsonp
from shapely.geometry import shape
from shapely.ops import cascaded_union
from geojson imp... |
# Write a program in the language of your choice
# that will remove the grade of type "homework"
# with the lowest score for each student from the dataset in the handout.
# Since each document is one grade, it should remove one document per student.
# This will use the same data set as the last problem, but if you... |
#
# Copyright 2019 The FATE Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... |
import abc
class ValidationRule(abc.ABC):
message: dict = None
@abc.abstractmethod
def is_valid(self) -> bool:
raise NotImplementedError("Not Implemented Yet")
|
import tensorflow as tf
from tensorflow.python.framework import ops
'''
Wrap the module
'''
_nknn_op = tf.load_op_library('slicing_knn.so')
def check_tuple(in_tuple, tuple_name: str, tuple_type: type):
if in_tuple is None:
raise ValueError("<", tuple_name, "> argument is not specified!")
if len(in_t... |
import unittest, time, sys, random
sys.path.extend(['.','..','../..','py'])
import h2o2 as h2o
import h2o_cmd, h2o_import as h2i, h2o_jobs, h2o_glm
from h2o_test import verboseprint, dump_json, OutputObj
def write_syn_dataset(csvPathname, rowCount, colCount, SEED):
r1 = random.Random(SEED)
dsf = open(csvPathna... |
import re
from pycoda.fields import (
BalanceField,
BooleanField,
DateField,
EmptyField,
NumericField,
StringField,
ZeroesField,
)
class RecordIdentification(object):
INITIAL = 0
OLD_BALANCE = 1
TRANSACTION = 2
INFORMATION = 3
EXTRA_MESSAGE = 4
NEW_BALANCE = 8
... |
"""
This module provides classes for interfacing with a PCA9685 PWM extension.
"""
import time
from myDevices.devices.i2c import I2C
from myDevices.devices.analog import PWM
from myDevices.plugins.analog import AnalogOutput
class PCA9685(PWM, I2C):
"""Base class for interacting with a PCA9685 extension."""
... |
import os
import pathlib
import numpy as np
import keras_tuner as kt
from sklearn.preprocessing import OneHotEncoder
from sklearn import ensemble
from sklearn import metrics
from sklearn import model_selection
from sklearn import pipeline
from sklearn.metrics import accuracy_score
PATH = pathlib.Path(__file__).resolv... |
'''
It can be seen that the number, 125874, and its double, 251748, contain exactly the same digits, but in a different order.
Find the smallest positive integer, x, such that 2x, 3x, 4x, 5x, and 6x, contain the same digits.
'''
from functions import *
def allSameDigits(two, three, four, five, six):
'''Pre: the 5 ar... |
#!/usr/bin/env python
# Copyright (c) 2009-2013 Simon van Heeringen <s.vanheeringen@ncmls.ru.nl>
#
# This module is free software. You can redistribute it and/or modify it under
# the terms of the MIT License, see the file COPYING included with this
# distribution.
import sys
import os
from gimmemotifs.genome_index... |
import matplotlib.pyplot as plt
import numpy as np
from scipy import stats
from sklearn.model_selection import train_test_split
from tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint
from model_unet import unet
from data_tools import scaled_in, scaled_ou
def training(path_save_spectrogram, weights_path,... |
#!/usr/bin/python3
#
# Wi-Fi DeAuth attack
# by GramThanos
#
# Dependancies
# pip3 install scapy
# pip3 install mac-vendor-lookup
# Libraries
import os
import re
import sys
import getopt
import subprocess
import logging
from scapy.all import *
from mac_vendor_lookup import MacLookup
# Global Variables
VERBOSE = Fa... |
from .potongan_absen_karyawan import MxPotonganAbsenKaryawan
from .rekap_absen_karyawan import MxRekapAbsenKaryawan
from .rekap_gaji_departemen import MxRekapGajiDepartemen
from .rekap_lembur_karyawan import MxRekapLemburKaryawan
from .slip_gaji_karyawan import MxSlipGajiKaryawan
from .upah_lembur_karyawan import MxUpa... |
def teardown_function(function):
raise Exception('teardown failed')
def test():
pass
|
"""Module Implements General Trees using linked lists
Author: Rajan Subramanian
Date: -
"""
from __future__ import annotations
from typing import Any, Iterator, List, Union
from marketlearn.algorithms.trees import tree_base as tb
class GeneralTree(tb._GeneralTreeBase):
"""Class representing general tree struct... |
import os
import sys
import random
import numpy as np
import pandas as pd
# Please modify to fit your environment
import tensorflow as tf
import tensorflow.contrib.keras.api.keras as keras
from tensorflow.contrib.keras.api.keras import backend, callbacks
from tensorflow.contrib.keras.api.keras.models impor... |
'''
@Author: Gordon Lee
@Date: 2019-08-12 21:53:17
@LastEditors: Gordon Lee
@LastEditTime: 2019-08-13 17:58:30
@Description:
'''
class Config(object):
'''
全局配置参数
'''
status = 'train' # 执行 train_eval or test, 默认执行train_eval
use_model = 'TextCNN' # 使用何种模型, 默认使用TextCNN
output_folder... |
import json
from dataclasses import dataclass
from typing import List, NamedTuple
import pytorch_lightning as pl
import torch
from sentencepiece import SentencePieceProcessor
from torch.nn.functional import pad
from torch.utils.data import DataLoader
from src.config import ConveRTTrainConfig
config = ConveRTTrainCon... |
#Desafio:Faça um programa em Python que abra e reproduza um arquivo de mp3.
#import pygame
#pygame.mixer.init()
#pygame.mixer.music.load('Ex021.mp3')
#pygame.mixer.music.play()
#while(pygame.mixer.music.get_busy()): pass
import playsound
playsound.playsound('Ex021.mp3')
|
from __future__ import print_function
import lemon
class MyWorkflow(lemon.Workflow):
def __init__(self):
import lemon
lemon.Workflow.__init__(self)
self.rnc = {}
def worker(self, entry, pdbid):
import lemon
self.rnc = lemon.count_residues(entry, self.rnc)
return ... |
import json
import os
from collections import OrderedDict
import wx
from core.src.frame_classes.design_frame import MyDialogKetValueSetting
class NamesEditFrame(MyDialogKetValueSetting):
def __init__(self, parent, names, path):
super(NamesEditFrame, self).__init__(parent)
self.names ... |
"""
Classes of building properties
"""
import numpy as np
import pandas as pd
from geopandas import GeoDataFrame as Gdf
from datetime import datetime
from collections import namedtuple
from cea.demand import constants
import cea.config
from cea.utilities.dbf import dbf_to_dataframe
from cea.technologies import blinds
... |
from setuptools import setup
with open("README.md", "r") as fh:
long_description = fh.read()
setup(
name='propius',
packages=['propius'],
version='0.1.2',
license='apache-2.0',
description='Extracts similar items over a big data using correlation between items over sparse data structures',
... |
# Initialise the gpio package.
# Raspberry Pi (initial) model B (and A) GPIO modules
# Developed by R.E. McArdell / Dibase Limited.
# Copyright (c) 2012 Dibase Limited
# License: dual: GPL or BSD.
|
USER_PRESENCE_TEMPLATE = '{"last_update": ${last_update}, "network_to_users": ${network_to_users}}'
|
# usbpi.service.py
# requires python 3.9
import subprocess
import re
# replace device_id with your own device
device_id = '10c4:8a2a'
result = subprocess.run(['usbip', 'list', '-l'], capture_output=True)
m = re.findall(r'busid\s+([\d\.-]+)\s+\(([\w:]+)\)', result.stdout.decode('utf-8'))
for device in m:
if devic... |
#from django.shortcuts import render
from django.views import generic
from django.contrib.auth.mixins import LoginRequiredMixin
# Create your views here.
class Home(LoginRequiredMixin, generic.TemplateView):
template_name = 'bases/home.html'
login_url = 'bases-space:login'
#login_url = 'admin:index'
|
# Natural Language Toolkit: Reader for Grammar Files
#
# Copyright (C) 2001-2006 University of Pennsylvania
# Author: Rob Speer <rspeer@mit.edu>
# URL: <http://nltk.sf.net>
# For license information, see LICENSE.TXT
#
# $Id: grammarfile.py 3588 2006-10-20 06:13:57Z ehk $
"""
A module to read a grammar from a *.cfg fil... |
# Generated by Django 2.2.4 on 2019-08-11 14:47
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [("user", "0006_add_company_information")]
operations = [
migrations.AlterField(
model_name="department",
name="type",
f... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.6 on 2016-07-05 10:19
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.Creat... |
def CHECK_ER(ret):
if ret['errors']:
raise ValueError(f'Failed to modify data: {ret["first_error"]}')
if ret['skipped']:
raise ValueError(f'Failed to modify data: skipped - {ret["skipped"]}') |
from __future__ import absolute_import
from octavious.parallelizer import Parallelizer
class DummyParallelizer(Parallelizer):
"""This class is a dummy implementation so it runs processors one by one in
a sequence.
"""
def parallelize(self, processors, input=None, callback=None):
"""Convenien... |
# noinspection PyPackageRequirements
from tap import Tap
from typing import List
import os
LMDB_DATA_ROOT = os.environ.get('LMDB_DATA_ROOT', './data')
# noinspection LongLine
class ParamsBase(Tap):
"""
All default parameters should be set here
"""
"""------General------"""
experiment_name: str... |
# Copyright 2017 Insurance Australia Group Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... |
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distribu... |
#
# PySNMP MIB module NGWASYNC (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/NGWASYNC
# Produced by pysmi-0.3.4 at Mon Apr 29 20:11:26 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:1... |
#!/usr/bin/env python2.7
"""Identify files which contain the same data (duplicates) based on md5sum of file
Caveats:
- This method is likely to be quite slow and resource heavy
- Empty files will be listed as duplicates of each other.
- Python's 'open' method follows symlinks, so they wil be identified as duplicate... |
# Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Path setup --------------------------------------------------------------
# If ex... |
# coding: utf-8
"""
Isilon SDK
Isilon SDK - Language bindings for the OneFS API # noqa: E501
OpenAPI spec version: 4
Contact: sdk@isilon.com
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
import six
class ClusterOwner(object):
... |
from . import m_module_template
class MicroarrayGeneMapping(m_module_template.MicroarrayModule):
def __init__(self, owner):
self.owner = owner
def add_tag(self):
self.data = None #Fake
def map_gene(self):
self.data = None #Fake
def merge_different_platform... |
#!/usr/bin/env python
"""Monitor BOSS temperatures and LN2 levels
History:
2012-04-23 Elena Malanushenko, converted from a script to a window by Russell Owen
2012-06-04 ROwen Fix clear button.
2015-11-03 ROwen Replace "== None" with "is None" and "!= None" with "is not None" to modernize the code.
"""
import Tki... |
import torch
def inv_softplus(x):
return x + torch.log(-torch.expm1(-x))
def inv_sigmoid(x):
return torch.log(x) - torch.log(1 - x)
|
# This class uses API to interact with netdot and Saolarwind Orion NPm server
import re
import requests
from orionsdk import SwisClient
import pynetdot
import ipaddress
import ipaddr
__author__ = "Paul S.I. Basondole"
__version__ = "Code 2.0 Python 3.7"
__maintainer__ = "Paul S.I. Basondole"
__email__... |
# -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community
Edition) available.
Copyright (C) 2017-2021 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in co... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2011 Radim Rehurek <radimrehurek@seznam.cz>
# Licensed under the GNU LGPL v2.1 - http://www.gnu.org/licenses/lgpl.html
"""
Scikit learn interface for gensim for easy use of gensim with scikit-learn
Follows scikit-learn API conventions
"""
import numpy as... |
# This file is part of Scapy
# Scapy is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# any later version.
#
# Scapy is distributed in the hope that it will be useful,
# but ... |
import importlib
import logging
import os
import sys
import google.api_core.exceptions
from google.cloud import secretmanager
from octue.cloud.credentials import GCPCredentialsManager
from octue.log_handlers import apply_log_handler, get_formatter
from octue.resources import Child
from octue.resources.analysis import ... |
'''
This script runs through a range of shots and toggles the state of the data nodes associated with antenna and source voltage and current.
'''
import sys
from MDSplus import *
s1=int(sys.argv[1])
#Get shot range
if(len(sys.argv)>2) :
s2=int(sys.argv[2])
else :
s2=s1
def toggleNode(n) :
n.setOn(not n.isOn())
... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.3 on 2018-02-02 00:32
from __future__ import unicode_literals
import django.core.validators
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateM... |
# -*- coding: utf-8 -*-
import os
import typing
import insanity
from collections import abc
from reldata import io
from reldata.data import individual
from reldata.data import knowledge_graph
__author__ = "Patrick Hohenecker"
__copyright__ = (
"Copyright (c) 2017, Patrick Hohenecker\n"
"All right... |
"""This problem was asked by Two Sigma.
Alice wants to join her school's Probability Student Club.
Membership dues are computed via one of two simple probabilistic games.
The first game: roll a die repeatedly. Stop rolling once you get a five
followed by a six. Your number of rolls is the amount you pay, in dollars... |
"""
Wigets (purdy.wigets.py)
========================
Widgets for displaying. These are called and managed through the Screen
classes in :mod:`purdy.ui`.
"""
import urwid
# =============================================================================
# Widgets
# ======================================================... |
__author__ = 'jaap'
|
#%%
# 画像・バウンディングボックス・ラベルのセットを準備する
import torch
import torch.nn as nn
image = torch.zeros((1, 3, 800, 800)).float()
bbox = torch.FloatTensor([[20, 30, 400, 500], [300, 400, 500, 600]]) # [y1, x1, y2, x2] format
labels = torch.LongTensor([6, 8]) # 0 represents background
sub_sample = 16
#%%
# VGG16を、バックボーンに使用する
# VG... |
#!python
class Node(object):
def __init__(self, data):
"""Initialize this node with the given data."""
self.data = data
self.next = None
def __repr__(self):
"""Return a string representation of this node."""
return 'Node({!r})'.format(self.data)
class LinkedList(obj... |
import hashlib
import json
import logging
import os
import pathlib
import shutil
import sys
import tempfile
import pytest
import numpy as np
import soundfile as sf
from scipy.signal.windows import get_window
from numbers import Real
from birdvoxclassify import *
from birdvoxclassify.core import apply_hierarchical_cons... |
"""Private module; avoid importing from directly.
"""
import abc
from typing import Tuple
import torch
import torch.nn as nn
from overrides import overrides
from .. import types
class KalmanFilterMeasurementModel(abc.ABC, nn.Module):
def __init__(self, *, state_dim, observation_dim):
super().__init__()... |
# AWS Lambda function for returning list of landsat scenes ids for input path/row
import json
import boto3
event = {
"queryStringParameters": {
"path": "143",
"row": "37"
}
}
def landsat_handler(event):
# parse event
path = event['queryStringParameters']['path']
row = event['... |
import requests
import json
HOSTER_NAME = "openload"
HOSTER_HAS_DIRECT_LINKS = False
HOSTER_KEEP_UNAVAILABLE_UPLOADS = False
OPENLOAD_CO_UPLOAD_URL = "https://api.openload.co/1/file/ul"
def linkFromId(id):
return "https://openload.co/embed/" + id
def upload(filename):
print("[openload] Requesting upload slo... |
from googletrans import Translator
from BingTTS import TTS
#翻譯
def translate(input,language_to):
translate = Translator()
if language_to in lan:
#say = '你好嗎'
result = translate.translate(input ,dest=lan.get(language_to))
#result = translate.translate(say ,dest=lan.g... |
# -*- coding: utf-8 -*-
"""
Copyright (C) 2021 Stefano Gottardo (script.appcast)
An interface to provide a communication between Kodi and a DIAL app
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
import json
import threading
from copy import deepcopy
import xbmc
import res... |
from rest_framework import authentication
from task_profile.models import TaskerProfile, CustomerProfile, Notification, InviteCode
from .serializers import (
TaskerProfileSerializer,
CustomerProfileSerializer,
NotificationSerializer,
InviteCodeSerializer,
)
from rest_framework import viewsets
class No... |
import scrapy
from webscraper.scrape import get_content
class EntSpider(scrapy.Spider):
name = "ent"
allowed_domains = ["reddit.com", "twitter.com", "gamepedia.com", "fandom.com"]
start_urls = [
"https://www.reddit.com",
# "https://www.facebook.com",
"https://www.twitter.com",
... |
#!/usr/local/bin/python3
# I used a couple of different random data generators to
# get some of this data. Including fakenamegenerator.com
# and mockaroo.com
# The URLs supplied by mockaroo.com had a whole ton of
# lorem=ipsum&dingdong=hoohaw&bob=loblaw type args.
# In fact, they were too many for a human (me) to ... |
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under ... |
import re
from ClusterSImilarity import FuzzyClusterSimilarity
import pprint
class RoleDictionary:
actor_filenames= ['Phoenix.Countries.actors.txt',
'Phoenix.International.actors.txt',
'Phoenix.MilNonState.actors.txt']
folder = 'data/dictionaries'
actor_set = ... |
import os
import os.path as osp
import cv2
import numpy as np
import json
import trimesh
import argparse
# os.environ["PYOPENGL_PLATFORM"] = "egl"
# os.environ["PYOPENGL_PLATFORM"] = "osmesa"
import pyrender
import PIL.Image as pil_img
import pickle
import smplx
import torch
def main(args):
fitting_dir = args.fitt... |
import logging
from urllib.parse import urljoin
import requests
import requests_cache
from requests.auth import HTTPBasicAuth
from army_ant.reader import Document, Entity, Reader
logger = logging.getLogger(__name__)
class LivingLabsReader(Reader):
def __init__(self, source_path, limit=None):
super(Livi... |
#!/usr/bin/env python
# SPDX-FileCopyrightText: 2022 Espressif Systems (Shanghai) CO LTD
#
# SPDX-License-Identifier: Apache-2.0
# This script is used from the $IDF_PATH/install.* scripts. This way the argument parsing can be done at one place and
# doesn't have to be implemented for all shells.
import argparse
from... |
import win32com.client
import os
#from pathvalidate import sanitize_filename
class AutomatePh:
app = None
psd_file = None
def __init__(self):
self.app = win32com.client.Dispatch("Photoshop.Application")
self.app.Visible = False
def closePhotoshop(self):
self.app.Quit()
def openPSD(self, fi... |
import collections
import contextlib
import curses
from typing import Dict
from typing import Generator
from babi.buf import Buf
from babi.hl.interface import HL
from babi.hl.interface import HLs
class Replace:
include_edge = True
def __init__(self) -> None:
self.regions: Dict[int, HLs] = collection... |
import argparse
from datetime import date
import os
import sys
import tensorflow as tf
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
os.environ['CUDA_VISIBLE_DEVICES']='6'
# import keras
# import keras.preprocessing.image
# import keras.backend as K
# from keras.optimizers import Adam, SGD
from tensorflow import keras
imp... |
#!/bin/python3
import sys
from itertools import combinations
def pythagoreanTriple(a):
if a%2==0:
b = (a//2)**2 -1
c = b+2
else:
b = (a**2-1)//2
c = b + 1
return [a,b,c]
# if a%2==0:#even
# mn = a//2
# l = list(range(1,10))
# for i in combinatio... |
import pytest
from kpm.manifest_jsonnet import ManifestJsonnet
@pytest.fixture()
def manifest(kubeui_package, package_dir):
return ManifestJsonnet(kubeui_package)
@pytest.fixture()
def empty_manifest(empty_package_dir):
return ManifestJsonnet(package=None)
@pytest.fixture()
def bad_manifest():
return Ma... |
from __future__ import division
import numpy as np
from menpo.shape import TriMesh
from menpofit.base import DeformableModel, name_of_callable
from .builder import build_patch_reference_frame, build_reference_frame
class AAM(DeformableModel):
r"""
Active Appearance Model class.
Parameters
---------... |
#!/usr/bin/env python
# -*- coding: iso-8859-15 -*-
# -*- Mode: python -*-
from __future__ import division
from __future__ import print_function
import random
import string
import sys
import time
from lib.logger import logger
try:
from impacket.dcerpc.v5 import tsch, transport
from impacket.dcerpc.v5.dtypes... |
'''
Created on May 13, 2019
@author: KJNETHER
trying to set up the fixtures so that they:
- test for 'test' data
- remove 'test' data if it already exists
- re-create test data
'''
import json
import logging
import os.path
import pytest
# pylint: disable=redefined-outer-name
from .config_fixture import test_packa... |
#!/usr/bin/env python
from Bio import AlignIO
import sys
#This script takes a sequential phylip alignment and converts is to a
#FASTA alignment
# check for correct arguments
if len(sys.argv) != 3:
print("Usage: PhylipSequentialToFasta.py <inputfile> <outputfile>")
sys.exit(0)
input_name = sys.argv[1]
outpu... |
from django.contrib.auth.models import User
from guardian.shortcuts import assign_perm
from permissions.services import APIPermissionClassFactory
from post.models import Post
from post.serializers import PostSerializer
from rest_framework import viewsets
from rest_framework.decorators import action
from rest_framework.... |
from dataclasses import dataclass
from typing import List
from pydantic import BaseModel
class DeckIn(BaseModel):
name: str
class DeckOut(BaseModel):
id: int # From database
name: str # From database
notes_total: int # Calculated
cards_total: int # Calculated
time_created: int # From d... |
# Copyright 2013 OpenStack Foundation
#
# 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 ... |
import sys
from _pydevd_bundle.pydevd_constants import IS_PY38_OR_GREATER
import pytest
SOME_LST = ["foo", "bar"]
BAR = "bar"
FOO = "foo"
global_frame = sys._getframe()
def obtain_frame():
yield sys._getframe()
@pytest.fixture
def disable_critical_log():
# We want to hide the logging related to _evaluate_w... |
def readSurface(name):
"""Read the files 'name'.vertices and 'name'.triangles and returns
lists of 6-floats for vertices x,y,z,nx,ny,nz and a list of 3-ints
for triangles"""
import string
f = open(name + ".vertices")
vdata = f.readlines()
f.close()
vdata = map(string.split, vdata)
... |
from . import AWSObject, AWSProperty
from .validators import *
from .constants import *
# -------------------------------------------
class KMSKey(AWSObject):
"""# AWS::KMS::Key - CloudFormationResourceSpecification version: 1.4.0
{
"Attributes": {
"Arn": {
"PrimitiveType": "String"
... |
"""arsenal.app - application factory"""
from flask import Flask
from flask_gravatar import Gravatar
from flask_moment import Moment
from flask_pure import Pure
from flask_simplemde import SimpleMDE
from .forum import forum
from .user import user, init_app as user_init_app
from .models import init_app as models_init_ap... |
from abc import ABC, abstractmethod
from typing import NamedTuple, Optional
import numpy as np
from scipy import special
from scipy.special import beta, digamma, erf, erfinv, hyp2f1
from scipy.stats import uniform
def check_is_probability(x):
raise NotImplementedError()
class Interval:
pass
class Continu... |
"""Logging tools and PII scrubber."""
|
# Copyright 2015 OpenStack Foundation
#
# 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 ... |
import numpy as np
def R_cam_imu_matrix():
# IMU origo/pos given in camera coordinate
imuOrigo_cam = np.array([0.71, 1.34, -3.53])
print("See geogebra sketch\n")
# Rotation matrix to rotation IMU to camera
# First rotate yaw of 8.303 degrees
def R_z(yaw_deg):
y = yaw_deg * np.pi / 180... |
from procedural.calculadora import calcular, calcular_prefixa
if __name__ == '__main__':
print(calcular()) # infixa
print(calcular_prefixa())
|
from slacky.attachment import SlackAttachment
from slacky.base import SlackObject
from .sender import SlackMessageSender
class SlackMessage(SlackObject):
def __init__(self, text=None, attachments=None):
self.text = text or ''
self.attachments = attachments or []
def send(self, channel, token... |
import os
import pandas as pd
import numpy as np
import torch
import random
from HPAutils import *
import cv2
import imgaug as ia
from imgaug import augmenters as iaa
ia.seed(0)
import sys
def mAP(PREDS='', DATASET='custom', XLS=True, return_details=False):
#ROOT = 'D:\\HPA\\test'
if XLS:
... |
from typing import NewType
from motor.motor_asyncio import AsyncIOMotorClient
from chat_room.core.config import settings as s
DBClient = NewType("DBClient", AsyncIOMotorClient)
class DataBase:
client: DBClient = None
db = DataBase()
async def get_database() -> DBClient:
return db.client
async def con... |
class Solution:
def maximumProduct(self, nums):
nums.sort()
a, b, c = nums[:3] # 前三个
e, d, f = nums[-3:] # 后三个
return max(e * d * f, a * b * f)
slu = Solution()
print(slu.maximumProduct([1, 2, 2, 3]))
|
import base64
import json
from http import HTTPStatus
import httpx
from fastapi import Request
from fastapi.param_functions import Query
from fastapi.params import Depends
from starlette.exceptions import HTTPException
from starlette.responses import HTMLResponse # type: ignore
from lnbits.core.services import creat... |
from __future__ import annotations
from abc import abstractmethod
from typing import Iterable
from cowait.tasks import TaskDefinition, RemoteTask
from cowait.utils import EventEmitter
from .const import ENV_TASK_CLUSTER, ENV_TASK_DEFINITION, ENV_GZIP_ENABLED, MAX_ENV_LENGTH
from .errors import ProviderError
from .utils... |
# -*- coding: utf-8; -*-
from __future__ import unicode_literals
import json
# TODO: update with more specific exceptions
class RegistryException(Exception):
def __init__(self, response):
self.response = response
if hasattr(response, 'content'):
try:
data = json.loads(... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.