text stringlengths 3.07k 12.6k |
|---|
"""
Illumination-Based Data Augmentation for Robust Background Subtraction
Copyright (c) 2019 <NAME>, <NAME> and <NAME>.
Licensed under the Creative Commons Attribution-NonCommercial 4.0 International License (see LICENSE for details)
Originally Written by <NAME>
"""
# Updated for PyTorch by <NAME>.
from skimage.util.... |
import datetime as dt
import time
from typing import Dict, List
import pandas as pd
import pendulum
import tweepy
from tweepy import Cursor, Stream
from tweepy.models import Status
from syaroho_rating.consts import (
ACCESS_TOKEN_KEY,
ACCESS_TOKEN_SECRET,
ACCOUNT_NAME,
CONSUMER_KEY,
CONSUMER_SECRE... |
#!/usr/bin/env python3
"""
Module containing functions for loading data from local folder
"""
# Standard libraries
import logging
import numpy as np
import pathlib
logger = logging.getLogger('spiking-FT')
def get_source(dpath):
"""
Retrieve which source generated the data in the specified path
"""
if... |
#!/usr/bin/python3
import json
import logging
import chargebee
from chargebee import InvalidRequestError
from utils.sentry_wrapper import SentryInit
from utils.singleton_class import SingletonMetaClass
from utils.timer_util import MyTimer
logger = logging.getLogger("payments")
class ChargebeeManager(metaclass=Singl... |
# -*- coding: utf-8 -*-
# Copyright 2017-2019 ControlScan, Inc.
#
# This file is part of Cyphon Engine.
#
# Cyphon Engine 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, version 3 of the License.
#
# Cyphon En... |
from __future__ import print_function
import os
import numpy as np
import pdb
import cv2
from fnmatch import fnmatch
from skimage.io import imsave, imread
import pickle
import imageio
import matplotlib.pyplot as plt
#Prepare training and test set
def create_train_data(netparms):
data_path=netparms.data_path
f... |
"""
Import as:
import helpers.htimer as htimer
"""
import logging
import time
from typing import Any, Callable, Optional, Tuple, cast
import helpers.hdbg as hdbg
_LOG = logging.getLogger(__name__)
# #############################################################################
class Timer:
"""
Measure tim... |
import importlib
import re
import shutil
from html.parser import HTMLParser
from pathlib import Path
from typing import List, Tuple, Generator, Dict
import importlib.util
try:
import importlib_resources as resources
except ModuleNotFoundError:
from importlib import resources
class ImportToPackageMapper:
... |
# Memory Puzzle
# By <NAME> <EMAIL>
# http://inventwithpython.com/pygame
# Released under a "Simplified BSD" license
import random, pygame, sys
from pygame.locals import *
FPS = 30 # frames per second, the general speed of the program
WINDOWWIDTH = 640 # size of window's width in pixels
WINDOWHEIGHT = 480 # size of w... |
# Licensed to the StackStorm, Inc ('StackStorm') under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use th... |
#AUTHOR : <NAME>
#CONTACT: <EMAIL>
#GUI application developed using Tkinter and Python3
#Dreams in Text : Text game with a fantastical setting
#relies on playgame.py, game.py, interactables.py, and items.py
from interactables import *
interactionList = ['take', 'punch', 'kick', 'break', 'drop', 'climb', 'open', 'attac... |
import cv2
from utils import to_gray, has_alpha, blend_white, get_image_paths
import numpy as np
import glob
import sys
from timeit import default_timer as timer
def resize(patch):
target_height = 15 * 8
curr_height = patch.shape[0]
mul = target_height / (1.0 * curr_height)
return cv2.resize(patch, N... |
import os
import pytest
import hashlib
import time
import six
from faker import Faker
from saltcontainers.factories import ContainerFactory
from tests.common import GRAINS_EXPECTATIONS
import json
def pytest_generate_tests(metafunc):
'''
Call listed functions with the grain params.
'''
functions = [... |
from discord.ext import commands
from discord import Embed
import requests, os
class Games(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.color = 0x1f871e
@commands.command(
brief="Erhalte Aktuelles zu Fortnite",
description='Sieh dir den Shop, die Herausforderung... |
# Ch 7 - Knights Problem
# The project for this chapter is to figure out the minimal number of chess knights necessary to attack every square on a
# chess board. This means our chessboard must be at least 3x4 for some number of knights to be able to attack all squares
# on the board because a knight can only attack cer... |
# MIT License
# Copyright (c) 2022 <NAME>™
# 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 limitation the rights
# to use, copy, modify, merge, publis... |
""" Elements are mini chameleon macros, usually used to render a single
element. Sometimes it is useful to not just apply a macro, but to have an
actual object representing that code snippet. The prime example being links.
Elements are rendered in chameleon templates by calling them with the layout
object::
<tal:... |
"""
Models for Product Service
All of the models are stored in this module
Models
------
Product - A Product used in eCommerce application
Attributes:
-----------
id (integer) - The id of the product
name (string) - The name of the product
category (string) - The category of the product
price (integer) - The price o... |
import requests
import os
import re
from botoy import GroupMsg, FriendMsg
from botoy import decorators as deco
from module import config, database
from loguru import logger
from module.send import Send as send
# proxies = {"http": "socks5h://127.0.0.1:10808", "https": "socks5h://127.0.0.1:10808"}
proxies = None
clas... |
from typing import Tuple
from pytest import fixture, mark
from sanic import Sanic
from sanic.request import Request as SanicRequest
from sanic.websocket import WebSocketCommonProtocol, WebSocketProtocol
from sanic_jsonrpc import Jsonrpc, Notifier, Request
class Pair:
def __init__(self, first: int, second: int):... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
import sys
import collections
import json
import datetime
import codecs
import itertools
import keyword
try:
import regex as re
WHITESPACE_RE = re.compile(r'\p{IsPattern_White_Space}+', re.UNICODE)
excep... |
from math import sqrt, acos, pi
#####
# VECTOR CLASS
#####
class Vector(object):
CANNOT_NORMALIZE_ZERO_VECTOR = 'cannot normalize zero vector'
VECTOR_LENGTHS_NOT_EQUAL = 'vector lengths not equal'
NO_UNIQUE_PARALLEL_COMPONENT = 'no unique parallel component!'
def __init__(self, coordinates):
... |
'''
################################################################
# Functions - Losses
# @ Modern Deep Network Toolkits for Tensorflow-Keras
# <NAME> @ <EMAIL>
# Requirements: (Pay attention to version)
# python 3.6+
# tensorflow r1.13+
# Extend loss functions. These functions could serve as both
# losses and me... |
#!/usr/bin/python
#
# Copyright (c) 2019 <NAME>, (@smile37773)
#
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'statu... |
"""The Vivint integration."""
import asyncio
import logging
from aiohttp import ClientResponseError
from aiohttp.client_exceptions import ClientConnectorError
from vivintpy.devices import VivintDevice
from vivintpy.devices.alarm_panel import DEVICE_DELETED, DEVICE_DISCOVERED
from vivintpy.devices.camera import DOORBEL... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 20 15:27:02 2020
@author: philipp
"""
import gzip
from pathlib import Path
import pdb
import json
import pickle
from pymongo import MongoClient
from tqdm import tqdm
from collections import Counter
import hashlib
import numpy as np
from typing i... |
import sys
from tqdm import tqdm
import torch
import ssds.core.tools as tools
import ssds.core.visualize_funcs as vsf
from ssds.core.evaluation_metrics import MeanAveragePrecision
from ssds.modeling.layers.box import extract_targets
CURSOR_UP_ONE = "\x1b[1A"
ERASE_LINE = "\x1b[2K"
def train_anchor_based_epoch(
... |
import pandas as pd
import matplotlib.pyplot as plt
import jieba
import jieba.analyse
from sklearn.feature_extraction.text import CountVectorizer, HashingVectorizer, TfidfTransformer,TfidfVectorizer
from sklearn.linear_model import Ridge
from sklearn.metrics import mean_squared_error
from sklearn.preprocessing import O... |
from __future__ import division
import spams
import numpy as np
import MPnumbaprog as mpg
import scipy.io as sio
import math
def getDictionary(Img, patch_size, **param):
I = np.array(Img) / 255.
A = np.asfortranarray(I)
rgb = False
X = spams.im2col_sliding(A, patch_size, patch_size, rgb)
X = im2co... |
import cv2
import numpy as np
ENV_SIZE = 160
class ArmEnvironment(object):
def __init__(self, n_joints=2, max_vel=np.pi / 4, time_lim=16):
super(ArmEnvironment, self).__init__()
self.w = ENV_SIZE
self.h = ENV_SIZE
self.center = int(self.w / 2), int(self.h / 2)
self.img = np.zeros((self.h, self.w, 3), np.u... |
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.optim.lr_scheduler import StepLR
from torch.utils.data import DataLoader
from torchvision import transforms, datasets
from torchsummary import summary
import argparse
class ConvBlock(nn.Module):
d... |
# BELOW YOU WILL FIND CHALLENGES:
# APPEND SIZE
#Create a function called append_size that has one parameter named lst.
#The function should append the size of lst (inclusive) to the end of lst. The function should then return this new list.
#For example, if lst was [23, 42, 108], the function should return [23, 42, 1... |
import os
import sys
import lib_util
import lib_kbase
import lib_naming
import lib_exports
import lib_properties
from lib_properties import pc
################################################################################
# This dumps the triplestore graph to the current output socket if called
# in a HTTP server.... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from . import ... |
from jp_doodle.dual_canvas import swatch
from jp_doodle.auto_capture import embed_hidden
import inspect
DO_EMBEDDINGS = False
def final_fit(frame, file_prefix=None):
if DO_EMBEDDINGS:
if file_prefix is None:
file_prefix = inspect.stack()[1][3]
filename = file_prefix + ".png"
c... |
# pylint: skip-file
from dragonfly import Dictation, Repeat, MappingRule
from castervoice.lib.actions import Text, Key
from castervoice.lib.ctrl.mgr.rule_details import RuleDetails
import ide_shared
from castervoice.lib.merge.additions import IntegerRefST
from castervoice.lib.merge.state.short import R
class Jetbrai... |
import configparser,os,traceback
class ConfigError(Exception):
"""
定义配置类异常
"""
def __init__(self, errorinfor):
self.error = errorinfor
def __str__(self):
return self.error
class Configer:
"""
1、配置文件加载类
2、.py配置文件的优先级高于.ini配置文件的优先级
"""
def __init__(self,conf_cat... |
"""
Converts a ROOT file with up to two tuples into a tuple.
Works with TTreeFormula class to allow a user to input a list of variable names to save. Also has support
for abitrarily complicated variables to be with user defined evaluation of an event returing an array of
variables to save in the cs... |
import os
from json import JSONDecodeError
from django.db import models
from django.conf import settings
from django.urls import reverse
from guardian.shortcuts import get_objects_for_user
from spotipy import SpotifyOAuth
from spotipy.client import Spotify
from users.models import User
from venues.models import Venue
... |
from __future__ import annotations
from enum import IntEnum
from typing import TYPE_CHECKING, Any, AsyncIterable
from urllib.parse import urlparse
from anyio import sleep
from h2.events import DataReceived, ResponseReceived, StreamEnded
from h2.exceptions import NoAvailableStreamIDError, ProtocolError
from ..utils i... |
import numpy as np
import pandas as pd
def get_ds_infos():
"""
Read the file includes data subject information.
Data Columns:
0: code [1-24]
1: weight [kg]
2: height [cm]
3: age [years]
4: gender [0:Female, 1:Male]
Returns:
A pandas DataFrame that contains inforamt... |
# -*- coding: utf-8 -*-
# @Author: <NAME>
# @Created Time: 2022/2/22 8:42 PM
# @Organization: YQN
# @Email: <EMAIL>
import torch
import torch
import torch.nn as nn
import torch.nn.functional as F
from .crf import CRF
from transformers import AutoModel
from konwledge_extraction.ner.bert_crf_ner.losses import (
Focal... |
#!/usr/bin/env python3
# Author: <NAME>
# Date: 01/12/22
# License: (see MIT License at the end of this file)
# Title: make
# This script performs various utility operations on a pypi development
# project -- similar to a makefile.
# Imports
import argparse
import os
import subprocess as sp
import textwrap
import ... |
import logging
import os
import re
import time
from flask import Flask, request, jsonify
import sentry_sdk
from sentry_sdk.integrations.flask import FlaskIntegration
from deeppavlov import build_model
logging.basicConfig(format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO)
logger = loggin... |
# Copyright 2015 Google 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 applicable law or a... |
from __future__ import absolute_import
import logging
import time
import pystache
from flask import request
from flask_login import current_user, login_required
from flask_restful import abort
from redash import models, utils
from redash.handlers import routes
from redash.handlers.base import (get_object_or_404, org_... |
#-*- coding:utf-8 -*-
# Adult: <EMAIL>
# Describe: reciver input args from webjs
# Update: 2018-03-23
from tornado.options import define,options
from PRODUCECONFIG import *
from DOSSH import *
import collections
import tornado.ioloop
import tornado.web
import tornado.httpserver
import logging
import oss2
import os
de... |
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
class RepVisualization:
def __init__(self, env, obs, batch_size, n_dims, colors=None, cmap=None):
self.env = env
self.fig = plt.figure(figsize=(10, 8))
self.cmap = cmap
self.colors = colors
self.n_dims ... |
#%%
# always check the input carefully after opening and splitting
# split r and c indices for simplicity (instead of combining them into a tuple)
# when using re, be sure to thing if greedy or nongreedy parsing is necessary
# don't use re when split() suffices, whitespaces can be casted to int
# make sure to experimen... |
# -*- coding: utf-8 -*-
"""
Contains all DB models related to aggregated user state within the game
"""
from datetime import datetime
from decimal import Decimal
from enum import Enum
from typing import Iterator, Type
from bson import ObjectId
from flask_mongoengine import Document
from mongoengine import (
IntFie... |
import logging
import time
from collections import defaultdict
import numpy as np
import tensorflow as tf
from mrcnn_tf2.utils.keras import KerasCallback
CONFIDENCE_INTERVAL_Z = {
80.0: 1.282,
85.0: 1.440,
90.0: 1.645,
95.0: 1.960,
99.0: 2.576,
99.5: 2.807,
99.9: 3.291,
}
class DLLogger... |
import asyncio
import functools
import random
import time
import sys
import traceback
from functools import partial
from concurrent.futures import ThreadPoolExecutor
import requests as _requests
import statsd as _statsd
class Session(_requests.Session):
def __init__(self, verbose=False, stream=sys.stdout, stats... |
from flask import Flask
import RPi.GPIO as GPIO
import time
from flask import Flask, flash, redirect, render_template, request, session, abort
import os
GPIO.setmode(GPIO.BCM)
# init list with pin numbers
pinList = [2, 3, 4, 17, 27, 22, 10, 9, 18, 23, 24, 25, 12, 16, 20, 21]
# loop through pins and set mode and sta... |
import numpy as np
import multiprocessing as mp
from pdb import set_trace
from copy import deepcopy
from utmLib import utils
from utmLib.clses import Timer
from utmLib.parmapper import Xmap
from core.contcnet import ContCNet, nn_conf
from core.varpick import most_var, hard_max_mincorr
from core.tinylib impor... |
import uuid
from lxml import etree as ET
from ..common.taskgraph import TaskGraph
def add_artificial_outputs(root, xmlns_prefix, tasks):
for child in root.findall("{}child".format(xmlns_prefix)):
child_task = tasks[child.get("ref")]
parents = [tasks[p.get("ref")] for p in child.findall("{}paren... |
# -*- coding: utf-8 -*-
import datetime
from telegram import InlineKeyboardButton, InlineKeyboardMarkup
from data.data_api import is_driver, get_slots, get_trip, is_suspended, get_all_trips_day
from routing.filters import create_callback_data as ccd
from util import common
#
# Tastiera chiamata dal menù ... |
#!/usr/bin/python3
import boto3
from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTClient
import picamera
import time
import json
from io import BytesIO
CHANGE_THRESHOLD = 0.005
SLEEP_TIME = 3
CLIENT_ID = 'pyzcam'
PUBLISH_TOPIC = CLIENT_ID + '/out'
SUBSCRIBE_TOPIC = CLIENT_ID + '/in'
AWS_IOT_ENDPOINT = '<YOUR_AWS_IOT_E... |
import numpy as np
from traits.api import Instance, Float, Enum, Any, List, on_trait_change, Event, Str, Property, Button
from traitsui.api import View, UItem, VSplit, CustomEditor, HSplit, Group, VGroup, HGroup, Label, ListEditor, \
EnumEditor
from collections import OrderedDict
from pyqtgraph.Qt import QtGui
from... |
#!/usr/bin/env python
# -*- coding:Utf-8 -*-
import os
from collections import defaultdict
from operator import itemgetter
from django.utils.text import unescape_entities
from sulci.textutils import normalize_text
from sulci.utils import load_file, save_to_file, get_dir
from sulci.base import TextManager
from sulci... |
from utils.Dataset_writer import Dataset_writer
from Dataset_IO.Segmentation.Dataset_config_segmentation import Dataset_config_segmentation
import Dataset_IO.Segmentation.Dataset_segmentation_pb2 as proto
import tensorflow as tf
import os
import random
import cv2
import numpy as np
class label_helper(object):
def... |
from sklearn.metrics import roc_auc_score, recall_score, precision_score
import numpy as np
from rpy2.robjects.packages import importr
import rpy2.robjects as ro
from rpy2.robjects import pandas2ri
Rfast = importr('Rfast')
_ROC_AUC = 'roc_auc'
_PRECISION_OUTLIERS = 'precision_outliers'
_RECALL_OUTLIERS = 'recall_ou... |
#! -*- coding: utf-8 -*-
# bert做Seq2Seq任务,采用UNILM方案
# 介绍链接:https://kexue.fm/archives/6933
from bert4torch.models import build_transformer_model
from bert4torch.tokenizers import Tokenizer, load_vocab
from bert4torch.snippets import sequence_padding, text_segmentate
from bert4torch.snippets import AutoRegressiveDecoder... |
"""
--- Day 18: Operation Order ---
As you look out the window and notice a heavily-forested continent slowly appear over the horizon,
you are interrupted by the child sitting next to you.
They're curious if you could help them with their math homework.
Unfortunately, it seems like this "math" follows different rules... |
import torch
import torchvision
import cv2
import random
import numpy as np
from PIL import Image
from torchvision import transforms
from sourcecode.configs.make_cfg import Struct
"""
- type: RandomRotation
prob: 0.3
angle: [-10, 10]
- type: RandomRotation
prob: 0.3
angle: [90, 90]
- typ... |
import sqlite3
from discord.ext import commands
"""
Permissions are stored as an integer. These can be converted to bits.
Each bit represents a permission. Below is a list of all permissions and their int.
If you sum the ints of the permissions you want to assign you get the permission integer.
1 - public ... |
import dash
import dash_core_components as dcc
import dash_html_components as html
import plotly.express as px
import plotly.graph_objects as go
import pandas as pd
import pickle
from dash.dependencies import Input, Output, State
def generate_table(dataframe, max_rows=10):
return html.Table([
html.Thead(
... |
# coding: utf-8
import functools
from decimal import Decimal
# import mock
import pytest
from prices import (
Money, TaxedMoney, MoneyRange, TaxedMoneyRange, percentage_discount)
from django_prices_openexchangerates import exchange_currency
from django_prices_openexchangerates.models import ConversionRate, get_rat... |
import maya.cmds as mc
import glTools.tools.transformDrivenBlend
import glTools.ui.utils
def ui():
'''
'''
# Window
window = 'transformDrivenBlendUI'
if mc.window(window,q=True,ex=1): mc.deleteUI(window)
window = mc.window(window,t='Transform Driven Blend')
# Layout
cl = mc.columnLayout()
# UI Elements
... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# __author__ : stray_camel
# __description__ : 基于https://github.com/SimpleJWT/django-rest-framework-simplejwt 开发jwt-TOKEN验证脚手架
# __REFERENCES__ :
# __date__: 2020/10/10 14
import inspect
import logging
import re
from collections import OrderedDict
from datetime import date
imp... |
#!/usr/bin/env python
'''
Make sure to set the DHCP timeout in /etc/dhcp/dhclient.conf to a lower value. 5 seems to work well.
TODO: Allow a specific channel. iw seems to default to all after four channels though. Bug?
'''
import subprocess
import os
import time
import argparse
import random
import logging
import net... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Liftaway Audio Abstractions."""
import logging
import time
import pygame
from liftaway.util import data_resource_filename
logger = logging.getLogger(__name__)
# PyGame Channels
audio_channels = {
"default": 0,
"movement": 1,
"no_press": 2,
"voicemail... |
"""
Usage: obtain_external_data_files.py [-h] [-s {hgnc,orphanet,clinvar}]
Script gets source data we need from HGNC, Orphanet, or ClinVar.
optional arguments:
-h, --help show this help message and exit
-s {hgnc,orphanet,clinvar}, --source {hgnc,orphanet,clinvar}
... |
import logging
import enum
from typing import (Dict, Union, Awaitable, Optional, Callable, Set, Any, List)
log = logging.getLogger(__name__)
# Transition callbacks pass through all params from trigger call
TransitionCallback = Union[
Callable[..., Awaitable[Any]],
List[Callable[..., Awaitable[Any]]]]
# Cond... |
# This file is a part of Arjuna
# Copyright 2015-2020 <NAME>
# Website: www.RahulVerma.net
# 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
# U... |
#
# Copyright (C) [2020] Futurewei Technologies, Inc.
#
# FORCE-RISCV is 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
#
# THIS SOFTWARE IS PR... |
import random
import re
import sqlite3
import time
from discord import Color
from discord import Embed
from discord.ext import commands
from discord.ext.commands import Bot
import gally.utils as utils
add_re = re.compile(r'\\q(uote)?\s+add\s+')
look_re = re.compile(r'\\q(uote)?\s+look\s+')
class Quotes:
def ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2011 <NAME> <<EMAIL>>
# Copyright 2012 Google 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
#
# htt... |
import pandas as pd
from nba_driver import *
teams_url = 'https://www.basketball-reference.com/teams/'
def get_season_soup(driver, team, season):
return get_soup(driver, teams_url + correct_team_url(team, season) +
'/' + str(season+1) + '.html')
def get_player_ids(table):
player_ids = []
... |
import re
import random
import numpy as np
from tqdm import tqdm
from keras.preprocessing import sequence
from keras.preprocessing.text import Tokenizer
from lookup import APPO
# https://www.kaggle.com/c/jigsaw-toxic-comment-classification-challenge/discussion/46371
def substitute_repeats_fixed_len(text, nchars, ntim... |
__author__ = "<NAME>"
__organisation__ = "The Univeristy of Strathclyde"
__support__ = "https://github.com/strath-sdr/rfsoc_radio"
from pynq import DefaultIP
from pynq import allocate
import numpy as np
from random import randint
from .async_radio import AsyncRadioTx
from .quick_widgets import TransmitTerminal
class... |
import logging
import functools
VALID_COMMANDS = [
'cpy', 'inc', 'dec', 'jnz', 'tgl',
]
VALID_REGISTERS = [
'a', 'b', 'c', 'd',
]
class Halt(Exception): pass
def logexec(instruction):
if len(instruction) == 1:
logging.debug(
'%s: %s',
instruction.__class__.__name__,
... |
from simple_model import S2SAttentionModel
import tensorflow as tf
class RandRegModel(S2SAttentionModel):
def get_embeddings(self, inputs, embedding_size):
embeddings = tf.Variable(
tf.random_uniform([self.V, embedding_size], -1.0, 1.0))
embed = tf.nn.embedding_lookup(embeddings, inpu... |
# Copyright 2019 <NAME> with socket and framework by <NAME>, <NAME>
# <NAME> - 404 Assignment 1 submission
#
# 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/lice... |
from GamesKeeper.db import BaseModel
from GamesKeeper.models.guild import Guild
from peewee import (BigIntegerField, IntegerField, TextField, BooleanField,
DoesNotExist)
from playhouse.postgres_ext import BinaryJSONField, ArrayField
from disco.types.message import MessageEmbed
from datetime import d... |
import math
thisdict = { # dictionary containing all room data
}
thisdict[1]=[[3,9],[4,8],[5,5]]#first number = room number. second = distance of connection
thisdict[2]=[[4,3],[5,6]]
thisdict[3]=[[1,9],[5,10]]
thisdict[4]=[[1,8],[2,3]]
thisdict[5]=[[1,5],[2,6],[3,10]]
def findifconnect(room1,room2): # function t... |
# Copyright 2021 Huawei Technologies Co., Ltd
#
# 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... |
from abei.implements.service_basic import ServiceBasic
from abei.implements.util import (
FileLikeWrapper,
LazyProperty,
)
from abei.interfaces import (
IProcedure,
IProcedureLink,
IProcedureFactory,
IProcedureJointFactory,
IProcedureBuilder,
service_entry as _,
)
from .procedure_joint_b... |
import copy
import warnings
import numpy as np
from torch.utils.data import DataLoader
from torch.utils.data import Dataset
import torch
from .ds_Igenerator import IGenerator
from .global_constants import DATA_ID_INDEX, DATA_IMAGE_INDEX, DATA_LABEL_INDEX
import torchvision.transforms as transforms
class DataSequenc... |
from collections import Counter
import numpy as np
import torch
def convert_to_torch_tensor(data_list, use_cuda):
"""Convert lists into (cuda) Tensors.
:param data_list: 2-level lists
:param use_cuda: bool, whether to use GPU or not
:return data_list: PyTorch Tensor of shape [batch_size, max_seq_len... |
""""""
import os
import sys
import time
import random
import multiprocessing as mp
import multiprocessing.queues
import numpy as np
#os.environ['NUMBAPRO_CUDALIB'] = '/usr/local/cuda/lib64/'
# for: \numba\examples\cudajit\matmul.py
#os.environ['NUMBAPRO_NVVM'] = '/usr/local/cuda/nvvm/lib64/libnvvm.so'
#os.environ['N... |
from math import log2, sqrt
import torch
from torch import nn, einsum
import torch.nn.functional as F
from einops import rearrange
from dalle_pytorch.vae import OpenAIDiscreteVAE
from dalle_pytorch.vae import VQGanVAE1024, VQGanVAE16384
from dalle_pytorch.transformer import Transformer
from dalle_pytorch.dalle_pytorch... |
"""ocaml-in-python"""
import collections.abc
import ctypes
import os
int = int
float = float
string = str
bool = bool
bytes = bytes
def error_this_function_should_be_implemented_in_ocaml():
raise NotImplementedError("This function should be implemented in OCaml")
class __list_api:
make = None
make_from_... |
"""Quick running benchmarks for :mod:`esmf_regrid.esmf_regridder`."""
from pathlib import Path
import numpy as np
import dask.array as da
import iris
from iris.coord_systems import RotatedGeogCS
from iris.cube import Cube
from esmf_regrid.esmf_regridder import GridInfo
from esmf_regrid.schemes import ESMFAreaWeighte... |
from __future__ import print_function
import itertools
from snap import viewer
from snap.math import *
from snap.gl import *
import numpy as np
class Box(object):
def __init__(self):
self.size = np.ones(3)
self.frame = Rigid3()
def support(self, d):
local = self.frame.ori... |
import fabric
import re
import io
import subprocess
import datetime
import json
import os
from fabric import Connection, task
from string import Template
python_version = '3.8.1'
python_install_dir = 'opt'
project_dir = 'live'
# Allow fallback to server installed version.
allow_fallback = True
passenger_template = ... |
"""
This module is largely inspired by django-rest-framework settings.
This module provides the `settings` object, that is used to access
app settings, checking for user settings first, then falling
back to the defaults.
"""
from typing import Any, Dict
from django.conf import settings
from django.util... |
"""This script is to evaluate model performance over N of epoches
Given different N values, save the jaccard and dice coefficient dictionary in the output directory
"""
import os
import numpy as np
import pickle
import argparse
import time
# import maskRCNN utils
from mrcnn_config import modelConfig as MrcnnConfig
fr... |
import os
import re
import great_expectations as ge
import numpy as np
import pandas as pd
from typing import Tuple
import rad_pipeline.rad_pipeline as rp
import rad_pipeline.zipcodes as zc
def locale_aggregation(df_cleaned: pd.DataFrame, locale_field: str, source: str) -> Tuple[pd.core.groupby.generic.DataFrameGro... |
import os
import sys
import tqdm
import importlib
import torch
import numpy as np
dtype = torch.FloatTensor
# custom functions
# -----------------------------------------------------------------------------------------------------------------------------
def forward_fill(x):
for ii in range(1, x.shape[0]):
... |
import matplotlib.pyplot as plt
from matplotlib.ticker import FormatStrFormatter
import numpy as np
import torch
import json
from torch import nn
from torch import optim
import torch.nn.functional as F
from torchvision import datasets, transforms, models
from collections import OrderedDict
from PIL import Image
def d... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.