text stringlengths 3.07k 12.6k |
|---|
import pytest
from pydent.models import Plan
def test_plan_constructor(fake_session):
g = fake_session.Plan.new()
assert g.name is not None
print(g.plan_associations)
assert g.operations is None
assert g.wires == []
g = Plan(name="MyPlan", status="running")
assert g.name == "MyPlan"
... |
"""
Copyright (c) Facebook, Inc. and its affiliates.
"""
import logging
import queue
from multiprocessing import Queue, Process
import sys
import os
from mc_memory_nodes import InstSegNode, PropSegNode
from heuristic_perception import all_nearby_objects
from shapes import get_bounds
VISION_DIR = os.path.dirname(os.pa... |
import pytest
import datetime
import json
import functools
from urllib.parse import urlencode, parse_qs
from descarteslabs.common.graft import client as graft_client
from ... import types
from .. import tile_url
def test_url():
base = "foo"
base_q = base + "?"
url = functools.partial(tile_url.tile_url... |
"""Click parameter types for osxphotos CLI"""
import datetime
import os
import pathlib
import re
import bitmath
import click
import pytimeparse2
from osxphotos.export_db_utils import export_db_get_version
from osxphotos.photoinfo import PhotoInfoNone
from osxphotos.phototemplate import PhotoTemplate, RenderOptions
fr... |
import datetime
import decimal
import enum
import typing as T
import uuid
import graphene
import graphene.types
import pydantic
import pytest
from pydantic import BaseModel, create_model
import graphene_pydantic.converters as converters
from graphene_pydantic.converters import ConversionError, convert_pydantic_field
... |
# Standard library
import atexit
import os
os.environ["OMP_NUM_THREADS"] = "1"
import sys
import traceback
# Third-party
from astropy.utils import iers
iers.conf.auto_download = False
import astropy.table as at
import numpy as np
# This project
from totoro.config import cache_path
from totoro.data import datasets, el... |
# Copyright (c) 2012 <NAME> <<EMAIL>>
#
# This is free software released under the MIT license.
# See COPYING file for details, or visit:
# http://www.opensource.org/licenses/mit-license.php
#
# The file is part of FSMonitor, a file-system monitoring library.
# https://github.com/shaurz/fsmonitor
import sys, os, time,... |
import torch
from torch import nn
import torch.nn.functional as F
#from helper_functions import process_image
class DeepNetworkClassifier(nn.Module):
def __init__(self, input_units, output_units, hidden_units,p_drop=0.2):
'''
Builds a classifier for a pretrained deep neural network for the flower d... |
# 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, ... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""*******************************************************************************
* MIT License
* Copyright (c) <NAME> 2021
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the... |
from django.db import models
from django.urls import reverse
from django.contrib.auth.models import User
from django.utils import timezone
import uuid
ANNOTATION = (
('asm', 'Asymmetry'),
('dst', 'Dystonia'),
('dsk', 'Dyskensia'),
('ebt', 'En Bloc Turning'),
('str', 'Short Stride Length'),
('mo... |
# encoding: utf-8
'''
@author: <NAME>
@contact: <EMAIL>
@software: basenef
@file: doc_generator.py
@date: 4/13/2019
@desc:
'''
import os
import sys
import time
from getpass import getuser
import matplotlib
import numpy as np
import json
from srfnef import Image, MlemFull
matplotlib.use('Agg')
author = getuser()
de... |
from pandas.core.algorithms import mode
import torch
import torch.nn as nn
from albumentations import Compose,Resize,Normalize
from albumentations.pytorch import ToTensorV2
import wandb
import time
import torchvision
import torch.nn.functional as F
import torch.optim as optim
from torch.cuda.amp import autocast,GradSc... |
import torch
import torch.nn as nn
import torchvision.models as models
from torch.nn.utils.rnn import pack_padded_sequence as pack
from torch.nn.utils.rnn import pad_packed_sequence as unpack
from torch.autograd import Variable
class EncoderCNN(nn.Module):
def __init__(self, embed_size):
"""Load the pretr... |
# -*- coding: utf-8 -*-
################################################################################
# _____ _ _____ _ #
# / ____(_) / ____| | | #
# | | _ ___ ___ ___ | (___ _ _ ___... |
""" Identify low-level jets in wind profile data.
<NAME>
December 2020
"""
import numpy as np
import xarray as xr
def detect_llj(x, axis=None, falloff=0, output='strength', inverse=False):
""" Identify maxima in wind profiles.
args:
- x : ndarray with wind profile data
- axis ... |
"""
:filename transformations.py
:author <NAME>
:email <EMAIL>
from
Classes of custom transformations that are applied during the training as additional augmentation of the depth maps.
"""
import torch
import random
import numpy as np
import torch.nn.functional as F
from random import randrange
from s... |
import random
import shutil
import sys
from argparse import ArgumentParser
from os import path
from pathlib import Path
from threading import Thread
from PySide6 import __version__ as PySideVer
from PySide6.QtCore import (Property, QCoreApplication, QObject, Qt, QTimer,
Signal, Slot)
from P... |
import json
import operator
import logging
import re
import time
from socket import socket, AF_INET, SOCK_DGRAM
from functools import reduce
logger = logging.getLogger(__name__)
def ip():
"""Find default IP"""
ip = None
s = socket(AF_INET, SOCK_DGRAM)
try:
s.connect(('172.16.31.10', 9))
... |
#!/usr/bin/env python3
#
import sys
import os
sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__))))
import argparse
import Libraries.arguments as ar
import Libraries.tools.general as gt
import Libraries.tools.zabbix as zt
import Classes.AppConfig as AppConfig
import requests
import copy
def r... |
import pandas as pd
import numpy as numpy
from env import host, user, password
import os
from sklearn.model_selection import train_test_split
import sklearn.preprocessing
############################# Acquire Zillow #############################
# defines function to create a sql url using personal credentials... |
"""
Path Converter.
pymdownx.pathconverter
An extension for Python Markdown.
An extension to covert tag paths to relative or absolute:
Given an absolute base and a target relative path, this extension searches for file
references that are relative and converts them to a path relative
to the base path.
-or-
Given a... |
# this file is to store all custom classes
import tkinter as tk
# class to store tkinter window properties
# font: tk font dictionary {family, size, weight, slant, underline, overstrike}
# font color: string
# nrows: the number of rows of lyric displayed (integer greater than 0)
# width: window width (int greater tha... |
from stheno import (
B, # Linear algebra backend
Graph, # Graph that keep track of the graphical model
GP, # Gaussian process
EQ, # Squared-exponential kernel
Matern12, # Matern-1/2 kernel
Matern52, # Matern-5/2 kernel
Delta, # Noise kernel
Normal, # Gaussian distribution
Dia... |
#
# Copyright 2017 <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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... |
""""
File : kombu_messaging.py
Author : ian
Created : 09-28-2016
Last Modified By : ian
Last Modified On : 09-28-2016
***********************************************************************
The MIT License (MIT)
Copyright © 2016 <NAME> <<EMAIL>>
Permission is hereby granted, free of charge, t... |
import pandas as pd
import numpy as np
from pathlib import Path
from sklearn.preprocessing import MinMaxScaler
from sklearn.model_selection import train_test_split
class AccidentsData:
def __init__(self):
filename = Path('../data/accidents.csv')
if not filename.exists():
print('\nERROR... |
import torch
from torch import nn
from configs import ANCHOR_SIZES
class PostRes(nn.Module):
def __init__(self, n_in, n_out, stride=1):
super(PostRes, self).__init__()
self.conv1 = nn.Conv3d(n_in, n_out, kernel_size=3, stride=stride, padding=1)
self.bn1 = nn.BatchNorm3d(n_out)
self... |
from __future__ import print_function
import os
import argparse
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.utils.data import DataLoader, Dataset
from collections import OrderedDict
import numpy as np
from edgeml_pytorch.trainer.drocc_trainer import DROCCTra... |
#!/usr/bin/env python
# coding: utf-8
# # Lab 02
#
# ## Solving a system of nonlinear equations
#
# ### <NAME>, Б01-818
#
# IV.12.7.д
# $$\begin{cases} x^7 - 5x^2y^4 + 1510 = 0 \\ y^3 - 3x^4y - 105 = 0 \end{cases}$$
# $$\begin{cases} x_{n+1} = \sqrt{\frac{x_n^7 + 1510}{5y_n^4}} \\ y_{n+1} = \sqrt[3]{3x_{n}^4y_{n}... |
import os
import json
from flask_sqlalchemy import SQLAlchemy
from flask import Flask, request, jsonify
from flask.views import MethodView
from flask.ext.cors import CORS
from database import ElasticStorage, RedisClient
from article import Article as ESArticle
app = Flask(__name__)
CORS(app)
#sql_config = json.loads(... |
from Dialogflow_Api import rispondimi
from collegamentoSito import inserisci_utente
from Nutrition import get_food, traduzione
import re
tipo_cibo = ["frutta", "carne", "verdure", "ortaggi", "primi_piatti", "legumi"]
"""
controllo_intent(query_result, utente)--> text_respose
prende il risultato della query e lo confr... |
# menu.py
# 维护暂停界面
import pygame
from pygame.locals import *
import sys
from utility import globe
from process.scene import menu_confirm
from PIL import Image, ImageFilter
class Pause_Menu(object):
# 暂停页面
def __init__(self):
self.button_rect = []
self.rs = globe.destiny.rsManager.image
... |
__author__ = 'multiangle'
# 这是实现 霍夫曼树相关的文件, 主要用于 针对层次softmax进行 word2vec 优化方案的一种
'''
至于 为什么要进行层次softmax 可以简单理解 因为词表很大 针对上完个类别单词进行softmax 计算量大 更新参数过多 无法训练,而采用softmax 层次化 只需要 计算几个有限单词的sigmod 就可以 更新参数也非常少
提高训练速度
什么是霍夫曼树 简单理解就是 将训练文本 进行词频统计 通过构建加权最短路径来构造二叉树 这样 词频高的 位置在前 词频低的位置在后 每一个 霍夫曼编码代表一个词 路径 并且是唯一 不是其他词的前缀
'''
impo... |
import copy
#from enum import IntFlag
from time import sleep
# I tried to use enum here, but I was having a problem with packages in the image, so I gave up as I just want to get it done
class FieldValue:
Empty = 0
Wall = 1
Player = 2
Box = 4
Goal = 8
class SenseHATColour:
Red = (204, 4, 4)
... |
import nifty.tools as nt
import numpy as np
import z5py
from elf.label_multiset import deserialize_multiset
from tqdm import trange
def check_serialization(mset1, mset2):
if len(mset1) != len(mset2):
print("Serialization sizes disagree:", len(mset1), len(mset2))
return False
if not np.array_... |
import random
import os
import subprocess
import shutil
from google.cloud import storage, logging as glogging
from core.framework import levels
from core.framework.cloudhelpers import deployments, iam, gcstorage, ssh_keys
LEVEL_PATH = 'thunder/a2finance'
RESOURCE_PREFIX = 'a2'
LOG_NAME = 'transactions'
def create(... |
import cv2
import os
from os import listdir, makedirs
from os.path import isfile, join, exists
import numpy as np
import time
import math
DEBUG = True
FACTOR = 2
RESO_X = int(576 / FACTOR)
RESO_Y = int(640 / FACTOR)
CONF_VAL = 0
THRESHOLD = 0
UPPER_BOUND = 230
LOWER_BOUND = 150
def get_file_index(filename):
i... |
import os
import logging
import json
from nnattack.variables import auto_var, get_file_name
from params import (
compare_attacks,
compare_defense,
#compare_nns,
nn_k1_robustness,
nn_k3_robustness,
nn_k1_approx_robustness_figs,
dt_robustness_figs,
rf_robustness_figs,
nn_k1_robustn... |
#encoding: utf-8
from __future__ import print_function
from builtins import str
import ipaddress
import datetime
import os
import sys
from twisted.names import client, dns, server, hosts as hosts_module, root, cache, resolve
from twisted.internet import reactor
from twisted.python.runtime import platform
TTL = 0
dict ... |
from django.shortcuts import render
import datetime
from datetime import date
import calendar
from schedule.models import Event, period_choices, cart_choice
from django.views.generic import UpdateView, TemplateView, ListView
from schedule.forms import ReservationForm
from django.http import HttpResponseRedirect, HttpRe... |
import os
from fixtures import TempDir
from testtools import ExpectedException, TestCase, run_test_with
from testtools.assertions import assert_that
from testtools.matchers import (
Contains, DirExists, Equals, FileContains, FileExists, MatchesStructure)
from testtools.twistedsupport import (
AsynchronousDefe... |
# Copyright 2018 Amazon.com, Inc. or its affiliates.
# 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.
# A copy of the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file ac... |
import os
import matplotlib.pyplot as plt
from keras import applications
from keras.preprocessing.image import ImageDataGenerator, load_img
from keras import optimizers
from keras.models import Sequential, Model, load_model
from keras.layers import Dropout, Flatten, Dense, MaxPooling2D
from keras.regularizers import ... |
#!/usr/bin/env python3
# coding: utf-8
# Copyright 2016 <NAME>, https://github.com/tywtyw2002, and https://github.com/treedust
#
# 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:/... |
# Copyright 2014 OpenCore 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 agreed to in writing,... |
#! /usr/bin/env python
"""
.. module:: bug0
:platform: Unix
:synopsis: Python module for implementing the bug0 path planning algorithm
.. moduleauthor:: <NAME> <EMAIL>
This node implements the bug0 path planning algorithm for moving a robot from its current
position to some target position.
Subscribe... |
import abc
import itertools
from oslo_utils import reflection
import six
from padre import exceptions as excp
from padre import utils
@six.add_metaclass(abc.ABCMeta)
class auth_base(object):
"""Base of all authorizers."""
def __and__(self, other):
return all_must_pass(self, other)
def __or__(s... |
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import Select
import unittest
import re
import sys
import os
# first thing first. We have to create product, just to make sure there is atleast 1 product available
# to assign endpoints to when crea... |
"""Virtualna mašina za rad s listama; kolokvij 31. siječnja 2011. (Puljić).
9 registara (L1 do L9) koji drže liste cijelih brojeva (počinju od prazne),
2 naredbe (ubacivanje i izbacivanje elementa po indeksu),
3 upita (duljina i praznost liste, dohvaćanje elementa po indeksu)."""
from vepar import *
class T(... |
import random
import torch
import numpy as np
import time
import os
from model.net import Net
from model.loss import Loss
from torch.autograd import Variable
import itertools
import pandas as pd
from main.dataset import LunaDataSet
from torch.utils.data import DataLoader
from configs import VAL_PCT, TOTAL_EPOCHS, DEFA... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author: Alex
# @Date: 2015-11-16 19:15:59
# @Last Modified by: Alex
# @Last Modified time: 2015-12-28 22:28:23
from django.db import models
from Inventationery.core.models import TimeStampedModel
from Inventationery.apps.Customer.models import CustomerModel
from Inve... |
# a module that wraps some of the S3 commands
import boto3
from botocore.exceptions import ClientError
from boto3.s3.transfer import S3Transfer
import re
import os
# check for existance of bucket
def list_bucket(bucket_name, region):
s3 = boto3.resource('s3', region)
bucket = s3.Bucket(bucket_name)
object_... |
'''
utils.py
General utility functions: unit conversions, great-circle
distances, CSV queries, platform-independent web browsing.
'''
import csv
import math
import webbrowser
# UNIT CONVERSIONS
MPS_TO_KTS = 1.944
class units:
def mps_to_kts(mps):
return mps*MPS_TO_KTS
def enforceTwoDigi... |
class T:
WORK_REQUEST = 1
WORK_REPLY = 2
REDUCE = 3
BARRIER = 4
TOKEN = 7
class Tally:
total_dirs = 0
total_files = 0
total_filesize = 0
total_stat_filesize = 0
total_symlinks = 0
total_skipped = 0
total_sparse = 0
max_files = 0
total_nlinks = 0
total_nlinke... |
# Copyright (c) 2020, <NAME>, University of Washington
# This file is part of rcwa_tf
# Written by <NAME> (Email: <EMAIL>)
import tensorflow as tf
import numpy as np
def convmat(A, P, Q):
'''
This function computes a convolution matrix for a real space matrix `A` that
represents either a relative per... |
# Copyright (c) 2013, 9T9IT and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe import _
from frappe.utils import fmt_money
from toolz.curried import compose, groupby, valmap, first, reduce, unique, pluck, count, partial
def execute(fil... |
from django.core import exceptions
from django.http import FileResponse
from django.utils.text import format_lazy
from django.utils.translation import gettext_lazy as _
from rest_framework import status
from rest_framework.decorators import action
from rest_framework.exceptions import ValidationError
from rest_framewor... |
"""Tests for thread_async_queue."""
from __future__ import annotations
import asyncio
from concurrent.futures import ThreadPoolExecutor
from itertools import chain
from typing import List, NamedTuple
import pytest
from opentrons.protocol_runner.thread_async_queue import (
ThreadAsyncQueue,
QueueClosed,
)
... |
# -*- coding: utf-8 -*-
"""
TencentBlueKing is pleased to support the open source community by making 蓝鲸智云-用户管理(Bk-User) available.
Copyright (C) 2017-2021 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in compliance with the Lic... |
# This file is part of Indico.
# Copyright (C) 2002 - 2019 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
from datetime import datetime, timedelta
from uuid import uuid4
import pytest
from flask import session
f... |
import json
import os
class Notifyer():
def __init__(self):
self.subscribers = []
def add_subscriber(self, subscriber):
self.subscribers.append(subscriber)
def notify(self, triggerId):
for sub in self.subscribers:
sub.notify(triggerId)
global_characters = []
global_it... |
"""
Copyright (c) Django Software Foundation and individual contributors.
Copyright (c) Dependable Systems Laboratory, EPFL
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of sour... |
import keyboard
from logparser import parselog, validate_log
import os
from psutil import process_iter
from pyautogui import click
import subprocess
from turnhandler import backupturn, clonegame, cleanturns, delete_log, delete_temp
import yaml
from time import sleep
import threading
import time
import win32gui
import w... |
"""
Model definition adapted from: https://github.com/pytorch/vision/blob/master/torchvision/models/resnet.py
"""
import math
from typing import Optional, List, Union, Type
import torch.nn as nn
model_urls = {
'resnet18': 'https://download.pytorch.org/models/resnet18-5c106cde.pth',
'resnet34': 'https://downlo... |
from sysu_dataset import SYSU
import numpy as np
import scipy
import itertools
import cv2
import torch
from torch.utils.data import Dataset
import torchvision.transforms as transforms
from config import *
vox_size=54
all_tups = np.array(list(itertools.product(range(vox_size), repeat=2)))
rot_array = np.arange(vox_... |
import os
import json
import numpy as np
import matplotlib.pyplot as plt
def compute_iou(box_1, box_2):
'''
This function takes a pair of bounding boxes and returns intersection-over-
union (IoU) of two bounding boxes.
'''
intersection = 0
tlr1, tlc1, brr1, brc1 = box_1[0], box_1[1], box_1[2], ... |
#TODO: use only one (RGB) channel
import numpy as np
import pandas as pd
import os
from torch.utils import data
from torch.utils.data.dataloader import DataLoader as DataLoader
import torch
from torchvision import transforms
from natsort import natsorted, ns
import cv2
from PIL import Image
import matplotlib.pyplot as ... |
#!/usr/bin/env python3
import sys
import json
import time
import subprocess
cats = {
"any": { "id": "vdoq4xvk", "output_file": "all.json", "output_file2": "all2.json", },
"100": { "id": "xk9jv4gd", "output_file": "100.json", "output_file2": "1002.json", },
'amq': { "id": "n2yj3r82", "output_file": "amq.j... |
import numpy as np
from gym import spaces
from agents import SimpleAgentClass
# Create agents for the CMA-ES, NEAT and WANN agents
# defined in the weight-agnostic paper repo:
# https://github.com/google/brain-tokyo-workshop/tree/master/WANNRelease/
# ---------------------------------------------------------------... |
from typing import Any, List
import factom_core.blocks as blocks
from factom_core.db import FactomdLevelDB
from .pending_block import PendingBlock
class BaseBlockchain:
"""The base class for all Blockchain objects"""
network_id: bytes = None
vms: List[Any] = None
data_path: str = None
db: Fact... |
from builtins import isinstance
from typing import Any, Dict, Tuple
from fugue import (
DataFrame,
FugueWorkflow,
WorkflowDataFrame,
WorkflowDataFrames,
Yielded,
)
from fugue.constants import FUGUE_CONF_SQL_IGNORE_CASE
from fugue.workflow import is_acceptable_raw_df
from fugue_sql._parse import Fug... |
import argparse
import i18n
import logging
import os
import rdflib
import sys
from termcolor import colored
from timeit import default_timer as timer
__VERSION__ = '0.2.0'
__LOG__ = None
FORMATS = ['nt', 'n3', 'turtle', 'rdfa', 'xml', 'pretty-xml']
HEADER_SEP = '='
COLUMN_SEP = '|'
EMPTY_LINE = ''
COLUMN_SPEC = '{:... |
from torchvision.datasets import VisionDataset
from datamodules.dsfunction import imread
from torch.utils.data import Dataset, RandomSampler, Sampler, DataLoader, TensorDataset, random_split, ConcatDataset
import os
import glob
from typing import List, Sequence, Tuple
from itertools import cycle, islice
import torch
fr... |
import datetime
from pychpp import ht_model
from pychpp import ht_xml
from pychpp import ht_team, ht_match, ht_datetime
class HTMatchesArchive(ht_model.HTModel):
"""
Hattrick matches archive
"""
_SOURCE_FILE = "matchesarchive"
_SOURCE_FILE_VERSION = "1.4"
# URL PATH with several params avai... |
import os
import re
import subprocess
from ..segment import BasicSegment
class Repo(object):
symbols = {
"detached": "\u2693",
"ahead": "\u2B06",
"behind": "\u2B07",
"staged": "\u2714",
"changed": "\u270E",
"new": "\uf128",
"conflicted": "\u2... |
import owlready2
import yaml
import urllib.request
import os
import gzip
import json
import sys
sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), "../cellxgene_schema"))
import env
from typing import List
import os
def _download_owls(
owl_info_yml: str = env.OWL_INFO_YAML, output_dir: str ... |
import numpy as np
import random as random
def move_to_sample(Rover):
delX = 0; delY = 0;
if len(Rover.rock_angles) > 0:
dist_to_rock = np.mean(np.abs(Rover.rock_dist))
angle_to_rock = np.mean(Rover.rock_angles);
Rover.steer = np.clip(angle_to_rock* 180/np.pi, -15, 15)
if Rove... |
#<NAME>
#ICS4U-01
#November 24 2016
#1D_2D_arrays.py
#Creates 1D arrays, for the variables to be placed in
characteristics = []
num = []
#Creates a percentage value for the numbers to be calculated with
base = 20
percentage = 100
#2d Arrays
#Ugly Arrays
ugly_one_D = []
ugly_one_D_two = []
ugly_two_D = []
#Nice Arra... |
#!/usr/bin/env python
# from google.cloud import speech
from google.cloud import speech_v1p1beta1 as speech
from google.cloud.speech_v1p1beta1 import enums
from google.cloud.speech_v1p1beta1 import types
from google.api_core.exceptions import InvalidArgument, OutOfRange
import pyaudio
import Queue
import rospy
import ... |
# mypy: ignore-errors
import inspect
from typing import Tuple
import warnings
import torch
class LazyInitializationMixin:
"""A mixin for modules that lazily initialize buffers and parameters.
Unlike regular modules, subclasses of this module can initialize
buffers and parameters outside of the constru... |
import base64
import dataclasses
import gzip
import json
from collections import defaultdict
from typing import DefaultDict, Dict, Generator, List, Optional
from sentry_sdk.api import capture_exception, capture_message
from posthog.models import utils
Event = Dict
SnapshotData = Dict
@dataclasses.dataclass
class P... |
"""
BEHAVIOR demo batch analysis script
"""
import argparse
import json
import logging
import os
from pathlib import Path
import pandas as pd
import igibson
from igibson.examples.learning.demo_replaying_example import replay_demo
def replay_demo_batch(
demo_dir,
demo_manifest,
out_dir,
get_callbacks... |
""" Unit tests for the HR solver. """
import pytest
from matching import Matching
from matching import Player as Resident
from matching.games import HospitalResident
from matching.players import Hospital
from .params import HOSPITAL_RESIDENT, make_game, make_prefs
@HOSPITAL_RESIDENT
def test_init(resident_names, h... |
import os.path
from typing import Sequence, Optional, Dict
import numpy as np
import pandas as pd
from nk_sent2vec import Sent2Vec as _Sent2Vec
from d3m import container, utils
from d3m.primitive_interfaces.transformer import TransformerPrimitiveBase
from d3m.primitive_interfaces.base import CallResult
from d3m.contai... |
import time
from signal import pause
import logging
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
logger = logging.getLogger(__name__)
map_edge_parse = {'falling':GPIO.FALLING, 'rising':GPIO.RISING, 'both':GPIO.BOTH}
map_pull_parse = {'pull_up':GPIO.PUD_UP, 'pull_down':GPIO.PUD_DOWN, 'pull_off':GPIO.PUD_OFF}
map_edg... |
import os
from pathlib import Path
import pandas as pd
from lime.lime_tabular import LimeTabularExplainer
from ml_editor.data_processing import get_split_by_author
FEATURE_DISPLAY_NAMES = {
"num_questions": "물음표 빈도",
"num_periods": "마침표 빈도",
"num_commas": "쉼표 빈도",
"num_exclam": "느낌표 빈도",
"num_quot... |
from gpiozero import Button
from time import sleep, time
import blinkt
import random
import requests
import sys
from constants import *
FNT_URL = "https://api.fortnitetracker.com/v1/profile/{}/{}"
FNT_REFRESH_TIME_SECS = 30
# debug shorter refresh
# FNT_REFRESH_TIME_SECS = 10
class FortniteAPIError(Exception):
pa... |
import os
import sys
import shutil
import csv
import subprocess ... |
"""
Modeling Relational Data with Graph Convolutional Networks
Paper: https://arxiv.org/abs/1703.06103
Code: https://github.com/tkipf/relational-gcn
Difference compared to tkipf/relation-gcn
* l2norm applied to all weights
* remove nodes that won't be touched
"""
import argparse
import numpy as np
import time
import ... |
# -----------------------------------------------------------------------------
#
# P A G E B O T E X A M P L E S
#
# Copyright (c) 2017 <NAME> <https://github.com/thomgb>
# www.pagebot.io
# Licensed under MIT conditions
#
# Supporting DrawBot, www.drawbot.com
# Supporting Flat, xxyxyz.org/flat... |
# coding=utf-8
# Copyright 2021 The OneFlow 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 require... |
# -*- coding: utf-8 -*-
# https://github.com/Kodi-vStream/venom-xbmc-addons
import xbmcaddon, xbmcgui, xbmc
"""System d'importation
from resources.lib.comaddon import addon, dialog, VSlog, xbmcgui, xbmc
"""
"""
from resources.lib.comaddon import addon
addons = addon() en haut de page.
utiliser une fonction comad... |
from keras.models import load_model
import numpy as np
import pandas as pd
from keras.preprocessing.image import ImageDataGenerator
from sklearn.cluster import KMeans
from time import time
# Takes a pandas dataframe containing the cluster assignment and ground truth for each data point
# and returns the purity of the ... |
__author__ = ("<NAME> <mrost AT inet.tu-berlin.de>, "
"<NAME> <aelvers AT inet.tu-berlin.de>")
__all__ = ["Data"]
from collections import OrderedDict
from typing import Dict, List, Optional
from . import tutor
from . import rooms
from ..util import converter
from ..util.settings import settings
class... |
import torch
import torch.nn as nn
from torchvision import transforms
from torch.utils.data import DataLoader, TensorDataset, Dataset
from torch.utils.data.sampler import SubsetRandomSampler
from torch import optim
import pandas as pd
import sys
sys.path.append('./proto')
import trainer_pb2
import trainer_pb2_grpc
impo... |
# Tkinter is Python's de-facto standard GUI (Graphical User Interface) package.
import tkinter as tk
import keras as kr
import numpy as np
import matplotlib.pyplot as plt
import math
import sklearn.preprocessing as pre
import gzip
import PIL
from PIL import Image, ImageDraw
import os.path
width = 280
height = 280
ce... |
import os
from tqdm import tqdm
from joblib import Parallel, delayed
try:
import seaborn as sns
except:
pass
import numpy as np
import cv2
from lost_ds.util import get_fs
from lost_ds.geometry.lost_geom import LOSTGeometries
from lost_ds.functional.api import remove_empty
def get_fontscale(fontscale, thic... |
#!/usr/bin/env python
"""
_selfupdate_
Util command for updating the cirrus install itself
Supports getting a spefified branch or tag, or defaults to
looking up the latest release and using that instead.
"""
import sys
import argparse
import arrow
import os
import requests
import inspect
import contextlib
from cirru... |
from typing import Mapping, Any, Sequence
import numpy as np
import heapq
import math
from tqdm import tqdm
import scipy.optimize
import cvxpy as cvx
def n_bias(x_count: np.ndarray, bias: float):
# return np.sum(x_count[x_count >= bias])
clipped = np.clip(x_count - bias, a_min=0, a_max=None)
return n... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.