text stringlengths 3.07k 12.6k |
|---|
from asyncio import sleep
from aiogram import types
from aiogram.dispatcher import FSMContext
from aiogram.types import CallbackQuery
from aiogram.utils.exceptions import UserDeactivated
from loguru import logger
from data.config import ADMINS
from filters import IsPrivate
from keyboards.inline.admin_inline import ad... |
import numpy as np
import multiprocessing
import more_itertools
import torch
from torch.utils.data import Sampler, Dataset, DataLoader
from transformers import AutoTokenizer
from config import CONFIG
class BERTDataset(Dataset):
def __init__(self, df):
self.text = df['excerpt'].values
self.target ... |
import pytest
from cmdline_helpers import CmdLineBuilder, ArgSpec
def test_verify_bool():
assert CmdLineBuilder._verify_bool(True, "argument") is True
assert CmdLineBuilder._verify_bool(False, "argument") is False
assert CmdLineBuilder._verify_bool(None, "argument") is None
with pytest.raises(ValueEr... |
import logging
import threading
import requests
import os
import sys
try:
from ..common.corpora_orm import DbDatasetProcessingStatus, UploadStatus
from ..common.entities import Dataset
from ..common.utils.db_utils import db_session_manager
from ..common.utils.math_utils import MB
# This is necessary fo... |
"""This module contains miscellaneous functions and classes used by many
other modules of centimani.
Constants
=========
:HTTP_STATUSES: A mapping of all HTTP statuses mapped to their reason.
:HTTP_METHODS: A set of all HTTP methods.
RFC1123 datetime conversion
===========================
RFC1123 defines a date f... |
import numpy as np
from hidden_markov import hmm
# Divide function
def divide(num, denom):
if num == 0:
return 0
return num / denom
# Hidden Markov Model
class HMM:
def __init__(self, n_states, n_possible_observations):
# Number of states
self.n_states = n_states
# Numbe... |
#!/usr/bin/env python3
## This file is the main driver for conversion from DICOM to rawiv. It assumes
# that each patient's data is in a directory named by the patient ID, with
# the following subdirectory structure:
#
# -[Patient ID]
# - DICOMOBJ (for raw DICOM files from DCMCCT)
# - DICOMUNC (unco... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
from sqlalchemy import String, Integer, Float
from sqlalchemy import create_engine, MetaData, Table, Column, Index
from sqlalchemy import select
try:
from ..pkg.superjson import json
from ..pkg.fuzzywuzzy import process
except:
from cazipcode.pkg.supe... |
"""
https://github.com/shijieS/SST
"""
import os
import configparser
import numpy as np
import pandas as pd
from PIL import Image
FPS_DICT = {
"Venice-2": 30,
"KITTI-17": 10,
"KITTI-13": 10,
"ETH-Pedcross2": 14,
"ETH-Bahnhof": 14,
"ETH-Sunnyday": 14,
"TUD-Campus": 25,
"TUD-Stadtmitte... |
'''
pset-3:problem-1
Please read the Hangman Introduction before starting this problem. We'll start by writing 3 simple functions that will help us easily code the Hangman problem. First, implement the function isWordGuessed that takes in two parameters - a string, secretWord, and a list of letters, lettersGuessed. Thi... |
from IMLearn.utils import split_train_test
from IMLearn.learners.regressors import LinearRegression
from typing import NoReturn
import numpy as np
import pandas as pd
import plotly.graph_objects as go
import plotly.express as px
import plotly.io as pio
pio.templates.default = "simple_white"
from IMLearn.utils import s... |
from typing import Union
import discord
from discord import Embed
from discord.ext import commands
from discord.ext.commands import Bot, Context
from discord.ext.commands.errors import BotMissingPermissions
from discord_slash import SlashContext, ComponentContext
from datetime import datetime
from utils import how_to_u... |
"""
A parser for .ini-syntax files. INIParser should be subclassed to
create a data structure from the file. See INIParser for more
"""
class ParseError(Exception):
def __init__(self, message, filename=None, lineno=None, column=None, line=None):
# Note: right now column is not used, but in some contexts... |
"""Convert GRAR library html to OpenITI mARkdown.
This script subclasses the generic MarkdownConverter class
from the html2md module (based on python-markdownify,
https://github.com/matthewwithanm/python-markdownify),
which uses BeautifulSoup to create a flexible converter.
The subclass in this module, PtolHtmlConvert... |
# coding=utf-8
import json
import collections
class PREVIEW_SIZE(object):
SMALL = 240
MEDIUM = 600
BIG = 825
HUGE = 1240
class REQUEST_METHOD(object):
AUTO = 0
POST = 1
GET = 2
class SmallInvoiceException(Exception):
""" Base class for all exceptions raised by smallinvoice """
... |
from django.shortcuts import render,redirect
from django.views.generic import ListView,DetailView
from . import models
from django.http import Http404
from customer_app.models import ReviewBook
from django.contrib import messages
from django.urls import reverse
import math
# Create your views here.
class BookListView(... |
# Copyright (c) 2020 <NAME>. All rights reserved.
# See the file LICENSE for copying permission.
import pytest
import jax
import jax.numpy as jnp
import piper.functional as func
from piper import distributions as dist
from piper import test_util as tu
def test_sample_bernoulli():
def model1(key):
retur... |
# Copyright 2017 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... |
import time
import random
import argparse
import torch
import torch.nn as nn
from torch import optim
from nltk import bleu_score
from data_preprocess import Data_Preprocess
from embedding_google import Get_Embedding
from encoder_rnn import Encoder_RNN
from decoder_rnn import Decoder_RNN
from train_network import Tra... |
"""Find referenced images from Git commits."""
import logging
import re
import subprocess
from typing import AbstractSet, Iterable, NewType, Sequence, Set # pylint: disable=unused-import
from .config import REGISTRY_NAME, REPOSITORY_NAME
_LOGGER = logging.getLogger(__name__)
_BlobId = NewType('_BlobId', str) # pyl... |
from magma import *
from .LUT import *
from .arith import DefineSub
from .logic import Not
__all__ = ['DefineEQ', 'EQ']
__all__ += ['DefineNE', 'NE']
__all__ += ['DefineUGE']
__all__ += ['DefineULE']
__all__ += ['DefineUGT']
__all__ += ['DefineULT']
__all__ += ['DefineSGE']
__all__ += ['DefineSLE']
__all__ += ['Defin... |
import re
import os
def read_file(path):
text = open(path, encoding='utf-8').read()
titles = []
output = []
articles = []
not_truth = False
for line in text.split('\n'):
if line.startswith('>'):
articles.append(line[1:])
if not_truth:
titles.pop... |
# Copyright (c) 2021, <NAME>, <NAME>, <NAME>, <NAME>, and <NAME>
# This file is code used in Malware Makeover
"""
Code to develop/test code-displacement transformations.
"""
import random
import time
random.seed(time.time())
import sys
sys.path.append('orp')
import peLib
import copy
import func
import inp
import d... |
# Copyright 2015 Open Source Robotics Foundation, 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 applicable law... |
#!/usr/bin/env python3
# coded by <NAME> 2019
# this program is called every once in a while (user must set up a cron job)
# what it does is it takes the first item in the database not marked as "done",
# run it in a safe sandbox, and put a report on the database with the results
# of the analysis and such.
# WARNING... |
r"""
=====
Swirl
=====
Image swirling is a non-linear image deformation that creates a whirlpool
effect.
Image warping
`````````````
When applying a geometric transformation on an image, we typically make use of
a reverse mapping, i.e., for each pixel in the output image, we compute its
corresponding position in the ... |
#######################
# Author: slurpxbt
#######################
import pybit
import time
import logging
import datetime as dt
import binance_candle_data as bcd
import pandas as pd
import pickle
from pathlib import Path
import traceback
import urllib
import websockets
from dhooks import Webhook
import pickle
import ... |
"""
model.py - module for developing model
"""
# import dependencies
import numpy as np
import tensorflow as tf
from tensorflow.keras import Input, Model
from tensorflow.keras.initializers import Constant
from tensorflow.keras.layers import Reshape, GlobalAveragePooling2D, GlobalAveragePooling1D, Conv2D, Dropout, Batc... |
# -*- coding: utf-8 -*-
# Copyright (c) 2018, <NAME> and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe import utils
from frappe.model.document import Document
class SurveyData(Document):
'''
This is the controller class for Survey
D... |
"""
App endpoints for indicators/features. This handles "raw"
features only.
Projections and other feature generators are implemented with
the model.
"""
import os
import json
import pandas as pd
from flask import jsonify, request
from time import time
import logging
import numpy as np
logger = logging.getLogger(__... |
# -*- coding: utf-8 -*-
# Copyright 2014-2020 Rumma & Ko Ltd
# License: BSD (see file COPYING for details)
"""Test certain aspects of `lino_xl.lib.addresses`.
This module is part of the Lino test suite. You can test only this
module by issuing::
$ go min9
$ python manage.py test tests.test_addresses
This test u... |
import torch
from torch import nn
import torch.nn.functional as F
from base_model import xception39, CBR
class SpatialPath(nn.Module):
def __init__(self, in_channels, out_channels):
super(SpatialPath, self).__init__()
hidden_channel = 64
self.conv_7x7 = CBR(in_channels, hidden_channel, ker... |
# coding: utf-8
import csv
from pathlib import Path
"""Automate the calculations for the loan portfolio summaries."""
# List of loan costs in the portfolio
loan_costs = [500, 600, 200, 1000, 450]
"""Get the profile of loan portfolio summaries."""
#Calculate the total number of loans in the portfolio.
total_number_... |
r"""Mean Deviation Similarity Index (MDSI)
This module implements the MDSI in PyTorch.
Original:
https://www.mathworks.com/matlabcentral/fileexchange/59809-mdsi-ref-dist-combmethod
References:
.. [Nafchi2016] Mean Deviation Similarity Index: Efficient and Reliable Full-Reference Image Quality Evaluator (Nafc... |
import copy
from datetime import datetime
from io import BytesIO
import xlrd
from xlwt import Workbook, XFStyle, Borders, Pattern
from najapy.common.async_base import Utils
class ExcelRD():
"""excel读取类"""
def __init__(self, filename=None, file_contents=None, sheet_name=None):
self.filename = filenam... |
import json
from data2html import Map, generateHTML
from utils import gentypes, LoadPerCapitaByZones, LoadPerCapitaOfERCOT, zones
import numpy as np
import sys
def postprocessdata():
f = open('DatabyZIPCodesTexas.json', 'r')
data = json.load(f)
f.close()
nd = {k:v for k,v in data.items() if v['WeatherZone'] == ''}... |
# -*- coding: utf-8 -*-
# Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (MPG) is
# holder of all proprietary rights on this computer program.
# You can only use this computer program if you have closed
# a license agreement with MPG or you get the right to use the computer
# program from someone who i... |
import numpy as np
import torch
from fastNLP.core.action import Batchifier, SequentialSampler
from fastNLP.core.action import convert_to_torch_tensor
from fastNLP.core.preprocess import load_pickle, DEFAULT_UNKNOWN_LABEL
from fastNLP.modules import utils
def make_batch(iterator, use_cuda, output_length=False, max_le... |
#########################################
# Utils for running experiments
#########################################
from generate import save
from uci import save_data
from dotdic import DotDic
from comparison import compare
def create_toy_datasets(seed=123):
save(Ntrain=5000, Ntest=500, D=1, lengthscale=0.1, var... |
#########################
######## Imports ########
#########################
import matplotlib.pyplot as plt
import numpy as np
import json
import random
import networkx as nx
#########################
####### Constants #######
#########################
WEIGHT_MIN_DEFAULT = 0
WEIGHT_MAX_DEFAULT = 10
NUM_NODES_DEFAU... |
"""
filename : utilities.py
This file contains common functions which are being called throught the app.
"""
import json
import streamlit as st
from dateutil.parser import parse
from datetime import datetime
import uuid
import requests
import base64
import re
def header():
"""function to display header on every ... |
# this project is licensed under the WTFPLv2, see COPYING.wtfpl for details
from logging import getLogger
from pathlib import Path
from PyQt5.QtCore import QTimer, pyqtSlot as Slot, QThread, Qt
from lierre.utils.db_ops import open_db_rw
from lierre.utils.maildir_ops import MaildirPP
from lierre.change_watcher import ... |
import os
import sys
import torch
import argparse
from torch import nn
import numpy as np
import torch.nn.functional as F
import random
from dataclass import Data, Tokenizer
import operator
from operator import itemgetter
from transformers import AdamW, get_linear_schedule_with_warmup
from main_utlis import compute_Rn_... |
from geffnet import config
import pytorch_lightning as pl
from pytorch_lightning import callbacks
from torch.optim import optimizer
from models import Resnext, get_efficientnet
from pathlib import Path
import pandas as pd
from cassavadata import *
import torch.nn.functional as F
import torch
from argparse import Argume... |
import pickle, sys, argparse, random, io
from pprint import pprint
import numpy as np
sys.path.append(".")
from ckbc_demo.demo_bilinear import Scorer
from sklearn.metrics import pairwise_distances
from sklearn.metrics.pairwise import cosine_similarity
parser = argparse.ArgumentParser()
parser.add_argument("--print_neg... |
import torch
import torch.nn.functional as F
from typing import Sequence, Optional, Union, Tuple
from numbers import Real
from dgl.nn.pytorch.conv import GraphConv
from dgl import remove_self_loop, add_self_loop
import autogl.data
from . import register_model
from .base import BaseAutoModel, activate_func, Classificat... |
"""
This module will add a new platform to both the standards.db file and the standards
stored within the main window.
"""
import tkinter as tk
from tkinter import ttk
from tkinter import StringVar
import error_window
class AddNew(tk.Toplevel):
"""A window to prompt the user for a new platform name, max lufs valu... |
# Author: <NAME>
# Source: https://github.com/johntfoster/bspline
# The MIT License (MIT)
# Copyright (c) <2015>
# 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 wit... |
"""
Here you can create samples of your widgets by providing default parameters,
inserting them in a container widget, mixing them with other widgets, etc...
These samples will appear in the WidgetBrowser
See http://toscawidgets.org/documentation/WidgetBrowser for more information
"""
from .widgets import (
Accor... |
#!/usr/bin/env python
# coding: utf-8
import numpy as np
from iam.features_and_letters_only import IAM, Layer, load_corpus, alphabet, Connection
# Load the words
corpus = load_corpus()
print(corpus[:5])
n_words = len(corpus)
print(n_words)
# Letter-word excitation
# Letter-word inhibition
# Word-word inhibitio... |
import tensorflow as tf
#This is the Dempster-Shafer (DS) layer to construct mass functions using feature maps from a encoder-decoder architecture
#We sperate a DS layer into several layers to make it clear and easy to compute, which follows the orginal defination of the paper 'A neural network classifier based on ... |
from dcp.data_format.formats.key_value.base import JsonFormat
from commonmodel.base import Schema
from dcp.data_copy.base import CopyRequest, DataCopierBase
from dcp.data_copy.costs import (
FormatConversionCost,
MemoryToMemoryCost,
NetworkToMemoryCost,
)
from dcp.data_format.formats.database.base import Da... |
import os
import sys
import time
from ftplib import FTP
#prettify the progressbar
try:
import shutil #this module can get the terminal width
term_width = shutil.get_terminal_size()[0]
except:
print("Using 'shutil' failed, will assume console width of 80")
term_width = 80 #default terminal width
progre... |
"""S3pac command line tool.
Usage:
s3pac [--server=<url>] add <repo> <pkgfile> [<sigfile>]
s3pac [--server=<url>] remove <repo> <arch> <name>
s3pac [--server=<url>] show <repo> <arch> <name>
s3pac [--server=<url>] list [--full] <repo> [<key>=<value>]...
Options:
-h --help Show this screen.
--versi... |
# System modules
import uuid
from dataclasses import dataclass, field
from typing import Dict, Union
# 3rd party modules
from flask import make_response, abort
# local modules
from config import ma
from models.model import Model
from models.user import requires_login, requires_admin
class StoreSchema(ma.Schema):
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import json
import os
import codecs
import requests
import traceback
from dotenv import load_dotenv
import urllib.parse
import xml.etree.ElementTree as ET
# -----------------------------------
def write_json(filename, jsonData, indent=False):
"""
JSO... |
"""A class that allows human readable information (sometimes debugging) output
with a hierarchical structure.
"""
__author__ = '<NAME>'
from typing import Union, Any, Iterable
from abc import ABC, abstractmethod
import sys
import logging
from logging import Logger
import textwrap as tw
from collections import Ordered... |
"""Eze's Reports module"""
import time
from abc import ABC, abstractmethod
from typing import Callable
from eze.core.config import EzeConfig
from eze.utils.config import extract_embedded_run_type, get_config_keys, create_config_help
from eze.utils.print import pretty_print_table
from eze.utils.error import EzeConfigE... |
#!/usr/bin/env python
###############################################
# noise.py
#
# Generates correlated noise in space and/or time
# using Cholesky decomposition of a defined covariance
# matrix.
#
# @<NAME> & <NAME>
# Created : 08/10/2018
# Last updated : 03/11/2018
###############################################
i... |
# coding:utf-8
import os
from scipy.sparse import csr_matrix
import pickle
import json
import warnings
from gensim.summarization import textcleaner
from tqdm import tqdm
import unicodedata
with warnings.catch_warnings():
warnings.simplefilter(action='ignore')
from gensim import corpora, models
... |
import unittest
import inspect
from pathlib import Path
import json
import pytds
from common import (
MINDSDB_DATABASE,
CONFIG_PATH,
condition_dict_to_str,
run_environment
)
# +++ define test data
TEST_DATASET = 'home_rentals'
TO_PREDICT = {
'rental_price': float
# 'location': str
}
CONDITIO... |
# 6.0002 Problem Set 5
# Graph optimization
# Name: <NAME>
# Collaborators: None
# Time:
#
# Finding shortest paths through MIT buildings
#
import copy
import unittest
from graph import Digraph, Node, WeightedEdge
#
# PROBLEM 2: Building up the Campus Map
#
# PROBLEM 2a: Designing your graph
#
# What do the graph's n... |
# Copyright (c) 2014 ITOCHU Techno-Solutions Corporation.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required... |
###################################################################################################
# Deep Vision Project: Text Extraction from Receipts
#
# Authors: <NAME> and <NAME>
# Data: 2020
#
# Description of file:
# Utility functions for data processing.
#######################################################... |
"""
file: run.py
description:
This program finds a path between pixels provided in path file.
language: python3
"""
# imports
from collections import defaultdict
from queue import PriorityQueue
from math import sqrt, pow
from classes.PixelPriority import PixelPriority
from scripts.load import *
from classes.Pixel imp... |
from collections import OrderedDict
import json
from share.transform.chain import ctx, ChainTransformer
from share.transform.chain import links as tools
from share.transform.chain.parsers import Parser
class AgentIdentifier(Parser):
uri = tools.IRI(ctx)
class WorkIdentifier(Parser):
uri = ctx
class Orga... |
import asyncio
import hashlib
from collections.abc import AsyncGenerator, Generator
from hashlib import sha1
from typing import IO, Any, Callable, Mapping, Optional
import filetype
from streaming_form_data import StreamingFormDataParser
from streaming_form_data.targets import BaseTarget
from contaxy.schema.file impor... |
import numpy as np
import dash
import dash_bootstrap_components as dbc
import plotly.graph_objs as go
from dash import Input, Output, dcc, html, State
def ARprocess(order,c,params,y_not,mu,sigma,T):
errors_vec = np.random.normal(mu,sigma,T)
errors_vec=errors_vec.reshape(-1,1)
phis = np.reshape... |
import os, json, argparse, sys, datetime, time
import pronto, six
"""
Check all existing ChEBI items have their InChi keys and the current ChEBI
release as source.
"""
script = os.path.basename(sys.argv[0])[:-3]
def write_line_to(name, string):
f = write_line_to._hdl.get(name)
if f is None:
f = open(... |
import face_recognition
from PIL import Image, ImageDraw, ImageFont
import numpy as np
import pickle
import math
import os
import re
import multiprocessing as mp
EPS = 0.35
Textsize = 10
def Bar(args):
print(args)
def face_distance_to_conf(face_distance, face_match_threshold=EPS):
if face_distance > face_mat... |
#!/usr/bin/env python3
import os
import argparse
from pathlib import Path
from nrf5_cmake.library import Library
from nrf5_cmake.version import Version
from typing import Dict, List, Optional
from jinja2 import FileSystemLoader, Environment
from nrf5_cmake.library_description import LibraryDescription, LibraryVarian... |
from numba import jit
# fast roc_auc computation: https://www.kaggle.com/c/microsoft-malware-prediction/discussion/76013
@jit
def fast_auc(y_true, y_prob):
y_true = np.asarray(y_true)
y_true = y_true[np.argsort(y_prob)]
nfalse = 0
auc = 0
n = len(y_true)
for i in range(n):
y_i = y_true[... |
# Bayesian logistic regression in 2d for 2 class problem
# We compare MCMC to Laplace
# Dependencies:
# * !pip install git+https://github.com/blackjax-devs/blackjax.git
import jax
import jax.numpy as jnp
import matplotlib.pyplot as plt
import blackjax.rmh as rmh
from jax import random
from functools import parti... |
"""
:created: 2017-09
:author: <NAME> <<EMAIL>>
"""
from PySide2 import QtWidgets, QtCore
from pymel import core as pmc
from auri.auri_lib import AuriScriptView, AuriScriptController, AuriScriptModel, grpbox
from auri.scripts.Maya_Scripts import rig_lib
from auri.scripts.Maya_Scripts.rig_lib import RigController
rel... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# 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.
#
import json
import logging
import sys
from flask import Flask
from flask import request
f... |
import sys, os, json, itertools
import logging as log
from collections import Counter
from typing import List, Dict, Mapping, Tuple, Iterable
from .tane import Tane
class Profiler:
def get_keycol(self, rows: List[List[str]], classes: Dict[int, str]):
"""Predict the key column of a table. ``None`` means t... |
"""
In JSON-RPC it makes sense to group all server-side methods for a given
rpc channel into a "collection" that is inspected for supported method
when it comes time to handle a request.
This module contains code that allows one to have this generic collection
that supports discovery and use of the registered methods.... |
#!/usr/bin/env python
"""
@File : objective.py
@Time : 2021/12/03
@Desc : None
"""
# ==============================================================================
# Standard Python modules
# ==============================================================================
# ==============================... |
import os
import json
from flask import (
Flask, flash, render_template, redirect, request, session, url_for)
from flask_pymongo import PyMongo
from bson.objectid import ObjectId
from werkzeug.security import generate_password_hash, check_password_hash
if os.path.exists("env.py"):
import env
app = Flask(__nam... |
from discord.ext import commands
import discord
import sqlite3
from utilities import help_embed
class Moderation(commands.Cog):
def __init__(self, bot):
self.client = bot
@commands.command()
@commands.has_permissions(kick_members=True, ban_members=True)
async def mute(self, ctx, member: disc... |
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout
from tensorflow.keras.constraints import MaxNorm as maxnorm
from tensorflow.keras.models import load_model
from tensorflow.keras.wrappers.scikit_learn import KerasClassifier, KerasRegressor
from sklearn.compose import Col... |
# The MIT License (MIT)
#
# Copyright (c) 2017-2021 CNRS
#
# 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,... |
import math
import os
import random
import sys
import simpy
import yaml
from .BaseStation import BaseStation
from .Client import Client
from .Coverage import Coverage
from .Distributor import Distributor
from .Graph import Graph
from .Slice import Slice
from .Stats import Stats
from .utils import KDTree
def get_di... |
import os
from collections import OrderedDict
import matplotlib.patches as patch
import matplotlib.pyplot as plt
import numpy as np
import torch
from torchvision.ops import box_iou
from tqdm import tqdm
from src.dataset import DatasetType, DeepLesionDataset
from src.models import FasterRCNNType, faster_rcnn_model_bui... |
import pickle
import numpy as np
import matplotlib.pyplot as plt
import time
from sklearn.manifold import TSNE
# assuming we have 4-gram in our model
def load_dataset():
data_location = 'data.pk'
data = pickle.load(open(data_location, 'rb'))
return data
def log_cooccurence(word_data, V, symm=False):
... |
from torch import nn
from torch.autograd import Variable
import torch.nn.functional as F
import torch
import math
class OnlineTripletLoss(nn.Module):
def __init__(self, centers, margin, selector = 'hardest', cpu=False):
super(OnlineTripletLoss, self).__init__()
self.cpu = cpu
self.margin = ... |
from .security import check_pass
from .schema import *
from wtforms import *
import htmllaundry
import re
# Form validators
def isalpha(form, field):
if not field.data.isalpha():
raise ValidationError(
'Field must only be composed of letters in the alphabet.')
def isalnum(form, field):
... |
import pickle
import numpy as np
import tensorflow as tf
def load_data():
with open('data/dataset.pkl', 'rb') as f:
testX1 = pickle.load(f)
testX2 = pickle.load(f)
testY = pickle.load(f)
validX = pickle.load(f)
validY = pickle.load(f)
trainX = pickle.load(f)
... |
from __future__ import division
from __future__ import print_function
import math
import os
from nltk import ngrams, sent_tokenize, word_tokenize
from corpkit.constants import PYTHON_VERSION, STRINGTYPE
class LanguageModel(object):
def __init__(self, order, alpha, data):
"""
:param data: a panda... |
"""
usage: gfswind2png.py [-h] --timestamp TIMESTAMP [--output_dir OUTPUT_DIR]
[--clean]
optional arguments:
-h, --help show this help message and exit
--timestamp TIMESTAMP
Enter timestamp in YYYYMMDDhh format. hh must be 00,
06, 12, ... |
from dataclasses import dataclass
from typing import Any, Generic, TypeVar, Type, Dict, Optional, Iterator
from . import sql
from .connection import execute, WurmError
from .typemaps import from_stored, to_stored, columns_for
@dataclass(frozen=True)
class Comparison:
op: str
value: Any
def gt(value):
"... |
import os
import re
from zipfile import ZipFile
import requests
from tqdm import tqdm
PRETRAINED_WORD_EMBEDDINGS = {
"twitter-cbow-300d": "https://archive.org/download/aravec2.0/tweet_cbow_300.zip",
"twitter-skipgram-300d": "https://archive.org/download/aravec2.0/tweets_sg_300.zip",
"twitter-cbow-100d": "... |
import csv
import os
import cv2
import numpy as np
from keras.models import Sequential
from keras.layers import Flatten, Dense, Lambda, Conv2D, Cropping2D
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from math import ceil
import random
import sklearn
DATA_LOCATION = '../udacity_... |
from typing import Any, List, Optional, Tuple
from pyramid.request import Request
from sqlalchemy import distinct, func
from sqlalchemy.exc import InvalidRequestError
from sqlalchemy.orm import aliased
from sqlalchemy.orm.attributes import InstrumentedAttribute
from sqlalchemy.orm.query import Query
from .exceptions ... |
import matplotlib.pyplot as plt
from matplotlib import style
style.use('ggplot')
import pickle
import pandas as pd
import numpy as np
import math #Import Modules
import random
from sklearn import svm
df=pd.read_csv("ex8a.txt", sep=' ',
names = ["Label", "x1", "x2"])
x1=[]
x... |
import os
import re
import time
import json
from configparser import ConfigParser
from collections import defaultdict
import arxiv
cwd = os.path.abspath(os.path.dirname(__file__))
config_path = os.path.abspath(os.path.join(cwd, '..', 'config.ini'))
config = ConfigParser()
config.read(config_path)
sort_by_dict = {'... |
from typing import Optional, Union
from webdnn.graph.axis import AxisKeyDict
from webdnn.graph.graph import Graph
from webdnn.graph.operator import Operator
from webdnn.graph.operators.attributes.tensorwise import Tensorwise
from webdnn.graph.optimize_rule import OptimizeRule
from webdnn.graph.order import Order
from ... |
# -*- coding: utf-8 -*-
import numpy as np
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Dense,Input,LSTM, Conv1D,Bidirectional
from tensorflow.keras.activations import sigmoid
from tensorflow.keras import optimizers
from tenso... |
import os
import argparse
import torch
import torch.nn as nn
from torch import sigmoid
from torch.nn.init import xavier_uniform_, zeros_
parser = argparse.ArgumentParser(description='~',formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("pretrained_posenet", type=str, help="pretrained PoseNet... |
import numpy as np # type: ignore
import matplotlib.pyplot as plt # type: ignore
import argparse
import json
import copy
parser = argparse.ArgumentParser()
parser.add_argument("--data-file", type=str, default="out/survey_results.json",
help="location of JSON file containing survey results")
args = parser.parse_args... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.