text stringlengths 3.07k 12.6k |
|---|
import json
import uuid
from datetime import datetime
from flask.views import MethodView
from flask import (
jsonify, Blueprint, request, g
)
from backend.db import CategoryNode, User
from backend.auth import login_required, user_logging
from backend.tools import extension as ext
bp = Blueprint('extension', __nam... |
import pandas as pd
import os
from decouple import config
from datetime import datetime, timedelta
import numpy as np
class Preprocessor:
def __init__(self, data_path):
self.data_path = data_path
def process_data_TT(self):
files = [
os.path.join(self.data_path, filename)
... |
import pytest
from lark import UnexpectedToken, Tree, Token
from lark.visitors import Transformer
from eunomia.config.nodes._util_lark import SUB_PARSER, SUB_RECONSTRUCTOR
# ========================================================================= #
# Test Helper ... |
__author__ = 'thor'
import numpy as np
from numpy import *
from sklearn.cluster import SpectralClustering as sk_SpectralClustering
from sklearn.cluster import MiniBatchKMeans as MiniBatchKMeans_sk
from sklearn.neighbors import NearestNeighbors
from numpy import vstack
from sklearn.cluster import KMeans
from ut.ml.ut... |
"""Macros used for represeting crates or annotations for existing crates"""
def _workspace_member(version, sha256 = None):
"""Define information for extra workspace members
Args:
version (str): The semver of the crate to download. Must be an exact version.
sha256 (str, optional): The sha256 ch... |
# Licensed to Modin Development Team under one or more contributor license agreements.
# See the NOTICE file distributed with this work for additional information regarding
# copyright ownership. The Modin Development Team licenses this file to you under the
# Apache License, Version 2.0 (the "License"); you may not u... |
"""
.. _l-example-tree-ensemble:
Benchmark Random Forests, Tree Ensemble
=======================================
The following script benchmarks different libraries
implementing random forests and boosting trees.
This benchmark can be replicated by installing the
following packages:
::
python -m vi... |
# -*- coding: utf-8 -*-
# flake8: noqa
"""
Python PKCS#5 v2.0 PBKDF2 Module
--------------------------------
This module implements the password-based key derivation function, PBKDF2,
specified in `RSA PKCS#5 v2.0 <http://www.rsa.com/rsalabs/node.asp?id=2127>`_.
Example PBKDF2 usage
====================
::
from pb... |
import os
import cx_Oracle
import re
DEFAULT_ARRAY_SIZE = 1000
def execute_statement(cursor, sql, params=None):
"""
Executes a dml or ddl statement.
If the input statement is not dml/ddl, then the statement is executed and nothing is returned.
:param cursor: The input cursor.
:param sql: The s... |
#My Take on the Vigenere Cipher
#Add Encrypt vs decrypt option
#Add User Keyword choice
#5 subkeys = 5 letter keyword
#Add key number to origanl message number to get encrypted number
#Convert encyphered numbers to alphabet to get encrypted message
#Add Dictionary with key
key = {"a": 1, "b": 2, "c": 3, "d": 4, "e": ... |
#
# 2021-03-15
# created by <NAME>
#
import os
from subprocess import check_output
import argparse
import sys
import os
import lxml.etree as ET
import subprocess
import math
sys.path.append("")
from testlibs import utils
def exec_shell_cmd(cmd):
if os.system(cmd) != 0:
print("error while executing '%s'" % ... |
import numpy as np
from typing import List, Tuple
from mph import GradedMatrix, groebner_bases, presentation_FIrep
def choose_graded_subbasis(matrix: List[List[Tuple[int, int]]], column_grades: List[List[int]], row_grades: List[List[int]]):
dense_matrix = np.zeros(shape=(len(row_grades), len(column_grades)), dtype=n... |
#
# Problem: Implement a function that takes a number of intervals,
# finds all overlapping intervals, merges the overlapping
# interval into a single interval and returns the merged
# intervals in ascending order.
#
# Output: Print the input array with all intervals and the output
# ... |
"""Parsing the molden structure"""
# Standard Library
import logging
# Third Party Libraries
import numpy as np
import ply.lex as lex
import ply.yacc as yacc
from molmod.periodic import periodic
# Local imports
LOG = logging.getLogger(__name__)
tokens = [ 'INT', 'FLOAT', 'EOL', 'SEP', 'LABEL',
'SYMBOL']... |
import numpy as np
import torch
from tqdm import tqdm
import h5py
import nibabel as nib
import sys
import os
from os import listdir
from os.path import isdir, join
# output_size is only used when do_localization=True.
# By default, do_localization is disabled. So the value here doesn't matter.
output_size =[128, 144,... |
#!/usr/bin/python
# Convert C++ commenting convention to one appropriate for automatically
# generating documentation with doxygen.
import os;
import string;
import sys;
# Get list of lines that start valid top-level (class/function) comment blocks.
#
# Top-level comment blocks are valid description blocks provided... |
#!/bin/python3
# Author: <NAME>
# Licensed under BSD 3-Clause License, see included LICENSE file
"""
names_parser.py <maxtiles>
Parses names.h and namesdyn.h of the Duke3D source and finds all actual usages of the contained tile definitions.
This is output as a pickled numpy arrays and as individual csv files. Individu... |
# -*- coding: utf-8 -*-
"""
@author: <NAME>
"""
import matplotlib.pyplot as plt
import numpy as np
from numpy import pi, sin, cos
from linear_elasticity_2d_solver import LinearElasticity2DProblem
from linear_elasticity_2d_solver.default_constants import nu_poisson_range, e_young_range
from linear_elasticity_2d_solver.... |
# encoding: utf-8
"""
@author: liaoxingyu
@contact: <EMAIL>
"""
import torch
from torch import nn
from .backbones.resnet import ResNet, BasicBlock, Bottleneck
import torch.nn.functional as F
from .backbones.resnet_ibn_a import resnet50_ibn_a
class GeM(nn.Module):
def __init__(self, p=3.0, eps=1e-6, freeze_p=Tru... |
"""
Tools for running CMake in setup phase
"""
__all__ = [
"CMakeExtension",
"CMakeBuild",
"find_package",
"WITH_CMAKE",
]
import argparse
import os
import subprocess
from tempfile import TemporaryDirectory
from setuptools import Extension
from setuptools.command.build_ext import build_ext
from .raise... |
from typing import Any, Optional, Tuple, List, Dict
import os
from glob import glob
import torch
from torch.utils.data import Dataset
import numpy as np
import nibabel as nib
from scipy.ndimage import gaussian_filter1d
def get_sample_dict(
datapath: str,
dataset: Optional[str] = 'train'
) -> Dict... |
"""
Class to convert dates to weeks and vice versa
Week to date conversion:
ws - (1-7) the week day which is the "start" of the week, which means that week 1 for a given year is counted
as the first week containing the given week day
pw - True/False, count proper weeks, i.e. week starts with monday. If this is true, ... |
import datetime
import discord
from discord.ext import commands, tasks
import peewee
from catnetbot import toml_config
import models
from catnetbot.errors import UserIsMutedError, UserIsNotMutedError
db = peewee.SqliteDatabase('catnet.db')
models.Punishment.create_table()
conf = toml_config.load_config()
SUCCESS_L... |
"""
Module for continuum models
For continuum models the underlying stochastic process is a stochastic
differential equation with learnable drift.
The shape of the data is assumed to be [batch, particle, dimension].
The Model class follows the Pytorch-Lightning format.
"""
from argparse import Namespace
import subp... |
import cv2
from enum import IntEnum
import logging
class CameraMode(IntEnum):
MJPEG_720_60 = 0
MJPEG_1080_60 = 1
MJPEG_1296_60 = 2
MJPEG_1536_48 = 3
MJPEG_480_60 = 4
MJPEG_1280_50 = 5
MJPEG_768_60 = 6
MJPEG_1536_50 = 7
MJPEG_960_58 = 8
RAW_720_60 = 9
... |
from Assembler.Assembler2 import *
from Base.EDAOBase import *
def GetOpCode(fs):
return fs.ReadByte()
def WriteOpCode(fs, op):
return fs.WriteByte(op)
edao_fa_op_table = InstructionTable(GetOpCode, WriteOpCode, DefaultGetLabelName, CODE_PAGE)
InstructionNames = {}
InstructionNames[0x00] = 'Re... |
from QQLoginTool.QQtool import OAuthQQ
from django.contrib.auth import login
from django.shortcuts import render
from django.views import View
from django.conf import settings
from django.http import JsonResponse
import json, re
from carts.utils import merge_cart_cookie_to_redis
from oauth.models import OAuthQQUser
fr... |
from aocd.models import Puzzle
from utils import get_test_input, write_solution
"""
Day 8: Seven Segment Search
"""
puzzle = Puzzle(year=2021, day=8)
SEGMENT_MAPPING = {
0: ['a', 'b', 'c', 'e', 'f', 'g'],
1: ['c', 'f'],
2: ['a', 'c', 'd', 'e', 'g'],
3: ['a', 'c', 'd', 'f', 'g'],
4: ['b', 'c', 'd'... |
from django.contrib.auth.views import LogoutView, LoginView
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.contrib.auth.mixins import LoginRequiredMixin
from django.shortcuts import redirect, render, get_object_or_404
from django.contrib import messages... |
# ABM as proposed by <NAME> (2004)
from statistics import mean
from collections import Counter
from itertools import permutations
from mesa import Agent, Model
from mesa.time import BaseScheduler
import copy
class PSAgent(Agent):
def __init__(self, problem, id, team, k = None, l = None, heuristic = None):
... |
import tensorflow as tf
def _combine_gradients(obj_to_grads):
# TODO: need to research how best to combine the gradients here...
# combine all gradients. This portion (with in the optimizer loop)
# will combine the gradients as if it were trained jointly
# TODO: this needs to be smarter.. We need to ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# pip
import numpy as np
import xarray as xr
# tk
from .util.time_operations import npdt64todatetime
# TODO: refactor con waves.py/hydrographs
class Hydrograph(object):
'Stores hydrograph data'
def __init__(self):
self.date_index = []
self.dates... |
import os
import numpy as np
import cv2
import torch
from model import TASED_v2
from scipy.ndimage.filters import gaussian_filter
from threading import Thread
from mss import mss
# From https://www.pyimagesearch.com/2015/12/21/increasing-webcam-fps-with-python-and-opencv/
# From https://stackoverflow.com/a/54246290
c... |
import os
import argparse
import random
import shutil
from shutil import copyfile
def printProgressBar (iteration, total, prefix = '', suffix = '', decimals = 1, length = 100, fill = '█'):
"""
Call in a loop to create terminal progress bar
@params:
iteration - Required : current iteration (Int... |
import pygame
from src import constants
from src.scenes.scene import Scene, DevOverlay
from src.helpers import main_to_small_display
from src.world import World
from src import enemy
class MainGame(Scene):
def __init__(self, game, world_name):
super().__init__(game, MainGameDevOverlay)
self.world... |
import pytest
from brainio_base.assemblies import DataAssembly
class TestMultiGroupby:
def test_single_dimension(self):
d = DataAssembly([[1, 2, 3], [4, 5, 6]], coords={'a': ['a', 'b'], 'b': ['x', 'y', 'z']}, dims=['a', 'b'])
g = d.multi_groupby(['a']).mean()
assert g.equals(DataAssembly(... |
import prody
import numpy as np
from .vec_3d import Vec3D
from .measure import correlation, q_value, rmsd
import consensx.graph as graph
def s2_values(
model_data, calculate_on_models, s2_records, s2_type, fit, fit_range
):
"""Returns a dictionary with the average S2 values:
s2_calced[residue] = value"""... |
#!/usr/bin/env python3
"""
.. See the NOTICE file distributed with this work for additional information
regarding copyright ownership.
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
... |
#!/usr/bin/python
'''pytest-peach extension
Copyright (c) 2016 Peach Fuzzer, LLC
Provides integration with Peach WebProxy
'''
from __future__ import print_function
import os, warnings, logging
import pytest
import peachproxy
import requests, json, sys
from requests import put, get, delete, post
logger = logging.get... |
# Copyright 2017 EasyStack, Inc
# Authors: <NAME>,
# <NAME>,
# <NAME>,
# Branty <<EMAIL>>
#
# 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
#... |
from meshrefine.layers import *
import pickle
import os
class Model(object):
def __init__(self, **kwargs):
allowed_kwargs = {'name', 'logging'}
for kwarg in kwargs.keys():
assert kwarg in allowed_kwargs, 'Invalid keyword argument: ' + kwarg
self.name = 'meshrefine'
logg... |
from carla_utils import carla
import rospy
import numpy as np
from typing import List
from std_msgs.msg import Header, ColorRGBA
from geometry_msgs.msg import Point
from visualization_msgs.msg import Marker, MarkerArray
from tf2_msgs.msg import TFMessage
from ..world_map import Role, vehicle_frame_id
from . import c... |
import logging
import matplotlib.pyplot as plt
import tensorflow as tf
from util import encoder, csv_helper, normalizer as norm
N_INPUT = 50000
N_TRAIN = int(N_INPUT / 0.9)
N_TEST = int(N_INPUT / 0.9 * 0.1)
N_CLASSES = 50
LEARNING_RATE = 0.001
N_EPOCHS = 20000
N_STEPS = 100
N_HIDDEN_NEURONS = [10, 12, 24, 48]
N_HIDD... |
""" Trains an agent with (stochastic) Policy Gradients on Pong. Uses OpenAI Gym. """
import numpy as np
import pickle
import gym
from keras.layers import Input,Dense,Flatten,Convolution2D,Activation
from keras.models import Model,Sequential
from keras.optimizers import RMSprop,Adam
import uuid
from multiprocessing imp... |
# -*- coding: utf-8 -*-
from datetime import date
from sqlalchemy import func
from flask import make_response
from fibra.models import Invoice, db
from fibra.jinjafilters import moneyfmt_filter
from fpdf import FPDF
date_fmt = '%d/%m/%Y'
class Report(FPDF):
filename = 'report.pdf'
title = 'Reporte Genéri... |
# Created by <NAME> on 2020
#
# original implemented by <NAME>, https://github.com/traveller59/spconv
# ----------------------------------------------------------------
# Copyright 2019 <NAME>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the L... |
# coding=utf-8
# Copyright (c) 2015 EMC Corporation.
# 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
#
#... |
# -*-coding:utf-8-*-
import json
import logging
from sys import exit
from pathlib import Path
import argparse
import colorful
from prettytable import PrettyTable
from lj.judger import JudgeStatus
from lj.utils import obj_json_dumps
from lj.vendors.simplediff import diff
from lj.commands.clean import lj_clean
from lj... |
# Lint as: python3
"""Script to handle file processing requests and queuing work.
This binary does two main things:
1. It listens for job requests. These contain the gcs path to portfolio and
market data files to be processed.
2. It downloads those file and queues it for downstream processing.
An example call usin... |
# -*- coding: utf-8 -*-
"""Query scientific literature through Europe PMC to identify co-occurrences (e.g., chemical + phenotype) in articles.
How to Use
----------
1. Using the cli for a single entity:
.. code-block:: sh
python -m seffnet.literature Ropinirole umls:C0015371
2. Using the cli for combinations ... |
import numpy as np
import pandas as pd
def column_above_or_below_threshold(df, column=None, above_or_below='above',
threshold=None, new_col_name=None, return_df=True):
""" Return a column with 1 if df[source_col] is above/below a certain threshold.
Parameters
----------
... |
import gc
import os
from typing import Callable
import numpy as np
from sklearn.model_selection import train_test_split
from unify_eval.model.deep_model import load_model
from unify_eval.model.mixins.stateful_classification import StatefulTextClassifier
from unify_eval.model.mixins.sequences.language_models import La... |
#!/usr/bin/env python3
#encoding: UTF-8
import os
import hashlib
import requests
import subprocess
import json
import base64
# ------ Crypto ------ #
import binascii
from Crypto.Cipher import AES
from Crypto import Random
# ------ Scripts ------ #
from .configFunctions import *
# ------ Globals ------ #
ConfigPathFi... |
# -*- coding: utf-8 -*-
from PyQt5 import QtCore, QtGui, QtQuick
from PyQt5.QtQuick import QSGImageNode, QSGNode
import squircle_renderer
class RenderThread( QtCore.QThread ):
textureReady = QtCore.pyqtSignal( int, QtCore.QSize )
def __init__( self, size ):
super().__init__()
self.surface = ... |
# -*- coding: utf-8 -*-
# 版权所有 2019 深圳米筐科技有限公司(下称“米筐科技”)
#
# 除非遵守当前许可,否则不得使用本软件。
#
# * 非商业用途(非商业用途指个人出于非商业目的使用本软件,或者高校、研究所等非营利机构出于教育、科研等目的使用本软件):
# 遵守 Apache License 2.0(下称“Apache 2.0 许可”),您可以在以下位置获得 Apache 2.0 许可的副本:http://www.apache.org/licenses/LICENSE-2.0。
# 除非法律有要求或以书面形式达成协议,否则本软件分发时需保持当前许可“原样”... |
import skil
from skil.services import Service
import skil_client
from skil_client.rest import ApiException as api_exception
import time
import os
import uuid
class Model:
"""
SKIL wrapper for DL4J, Keras and TF models
SKIL has a robust model storage, serving, and import system for supporting major
... |
import typing
from functools import partial
import numpy as np
from PySide2.QtCore import QAbstractItemModel, QAbstractTableModel, QModelIndex, Qt
from PySide2.QtWidgets import (
QAbstractItemView,
QAction,
QGridLayout,
QItemDelegate,
QLineEdit,
QStyleOptionViewItem,
QTableView,
QToolBa... |
from typing import Union, Tuple, List, Optional
import math
from torch import Tensor
from torch_geometric.data import Data
import torch
import torch.nn as nn
from gpn.distributions import Likelihood, ConjugatePrior
from gpn.utils import to_one_hot
import pyblaze.nn.functional as X
from .normalizing_flow import Normali... |
from __future__ import print_function
import pytest
from numdifftools.fornberg import (fd_weights, fd_weights_all, derivative,
fd_derivative,
CENTRAL_WEIGHTS_AND_POINTS)
import numpy as np
from numpy.testing import assert_array_almost_equal, assert_a... |
import networkx as nx
from collections import defaultdict
import itertools
import numpy as np
from scipy.stats.mstats import gmean
from scipy.stats import hmean
import time
import sys
import os
import matplotlib.pyplot as plt
from spaligner_parser import spaligner_to_df_not_ss
def filter_G_by_degree(G, filter... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from sys import exit
from subprocess import check_output
from os.path import dirname, realpath, basename, splitext
import os
import argparse
import zipfile
import opencc
class EpubChineseConvert:
# Configurations available directly from opencc
ALL_CONFIGS = ["s2t... |
import numpy as np
from gensim.models import KeyedVectors
from gensim.models import Word2Vec
import time
from collections import defaultdict
from gensim.models.word2vec import LineSentence
from gensim.models import FastText
from gensim.models import KeyedVectors
from gensim.models import Word2Vec
from sklearn.metrics.p... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
.. See the NOTICE file distributed with this work for additional information
regarding copyright ownership.
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 cop... |
#!/usr/bin/env python3
# usage:
#
# spinget.py 11/20/2021 10:00 1
# capture 1 hour show starting at 10:00pm on November 20, 2021.
#
# Requires python3 and:
# - requests `pip install requests`
# - m3u8 `pip instrall m3u8`
#
# Requires ffmpeg
#
# version 2.1, by mathias for WXOX
import argparse
from datetime ... |
import os
import numpy as np
import torch
import torch.nn as nn
from tensorboardX import SummaryWriter
from torchsummaryX import summary
import utils
from dataset import generate_loader
class Solver():
def __init__(self, module, config):
self.device = torch.device(
"cuda" if torch.cuda.is_avail... |
"""Runs a sweep over evaluation algorithms and prints results.
This experiment is far from ideal because it does not support sweeps over
different parameters for different algorithms at the moment.
"""
import functools
from typing import Callable
from typing import Sequence
import numpy as np
import time
from absl i... |
from math import sin, cos, pi
import ui
# https://ameblo.jp/bane-0604/entry-12687852122.html
# https://rskmoi.hatenablog.com/entry/2018/01/21/104029
possize = 11.140625
cellsize = 44.5625 * 2
# 玉 飛 金 桂 香 歩
# h 32.5, 31.5, 30.5, 29.5, 29.5, 28.3
# b 29.3, 28.3, 27.3, 26.3, 24.1, 23.1
# a 1.109,1.113... |
import torch
import torch.nn as nn
from stylenet import vgg, decoder
class StyleTransferModule(nn.Module):
def __init__(self, preserve_colour=True, alpha=1.0, cuda=True):
super(StyleTransferModule, self).__init__()
self.cuda = cuda if torch.cuda.is_available() else False
self.decoder = de... |
#!/usr/bin/env python3
'''
Utilities for the video data loading pipeline.
Assumes that videos are already downloaded and preprocessed.
'''
from __future__ import division
import numpy as np
import csv,pickle,os
from glob import glob
from config import *
def _to_absolute_path(fn):
'''Convert timestamped... |
#!/usr/bin/env python
# coding: utf-8
# # Generate Long Audio Sample records file
# ## Boilerplate
# In[ ]:
import os, sys
root_dir, _ = os.path.split(os.getcwd())
script_dir = os.path.join(root_dir, 'scripts')
sys.path.append(script_dir)
os.environ['CUDA_VISIBLE_DEVICES'] = '0'
# In[ ]:
import tensorflow as t... |
import torch
from PIL import Image
from torch.nn import functional as F
import types
import torchvision.transforms as transforms
import functools
import pdb
import numpy as np
import torchvision.transforms.functional as TF
import random
class UnNormalize(object):
def __init__(self, mean, std):
se... |
# -*- coding: utf-8 -*-
"""The standard fram log library.
This library provides the following arguments.
--all_loggers # Apply the handlers to all non fram loggers also.
--console # Logs to the CLI. If you don't specify a handler this is
# default.
--debug # Logs all ... |
# from enum import Enum
from itertools import product
from helpers.misc_functions import flatten_list_1_level, flatten_list_n_levels
RUN_TEST = False
TEST_SOLUTION = 848
TEST_INPUT_FILE = 'test_input_day_17.txt'
INPUT_FILE = 'input_day_17.txt'
RULES = {'#': [2, 3], '.': [3]}
ITERATIONS = 6
ARGS = [RULES, ITERATIONS... |
# 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... |
from rest_framework import serializers
from comments.models import Comment
from users.models import User, Node, NodeSetting
from posts.models import Post
import requests
from requests.auth import HTTPBasicAuth
class UserSerializer(serializers.ModelSerializer):
friends = serializers.SerializerMethodField('_frie... |
import abc
import dataclasses
import json
from typing import List
from xml.etree import ElementTree
import bs4
import redis
import requests
from model.show import Show, ShowMeta
from service.static import *
class AnimeListService(abc.ABC):
@abc.abstractmethod
def get_last_update(self) -> int:
"""Get... |
import os
import copy
from yggdrasil import platform
from yggdrasil.drivers.CModelDriver import (
CCompilerBase, CModelDriver, GCCCompiler, ClangCompiler)
class CPPCompilerBase(CCompilerBase):
r"""Base class for C++ compilers."""
languages = ['c++']
default_executable_env = 'CXX'
default_flags_env... |
import base64
import boto3
from botocore.exceptions import ClientError
import logging
import json
from flatten_json import flatten
import os
# logging.basicConfig(format='%(asctime)s,%(msecs)d %(levelname)-8s [%(filename)s:%(lineno)d] [function: %(funcName)s] %(message)s',
# datefmt='%Y-%m-%d:%H:%... |
import os
import copy
import json
import hashlib
from typing import Any, Dict # noqa
from chalice.deploy.swagger import CFNSwaggerGenerator
from chalice.deploy.swagger import SwaggerGenerator # noqa
from chalice.deploy.packager import LambdaDeploymentPackager
from chalice.deploy.deployer import ApplicationPolicyHan... |
import json
from asyncio import TimeoutError
from math import floor, trunc
from typing import Literal, Union
from discord import Embed, Message
from discord.ext import commands
from discord.ext.commands.context import Context
from discord.utils import oauth_url
from discord_slash import SlashContext, cog_ext
from disc... |
import unittest
import scipy.sparse as sp
import numpy as np
from indexed_sparse_matrix import IndexedSparseMatrix
def _random_ism(num_rows, num_cols, sp_type):
"""
Return an instance of IndexedSparseMatrix of the specified shape with random values.
sp_type is e.g. sp.csr_matrix
row keys are "row0", .... |
# Copyright 2008-2018 pydicom authors. See LICENSE file for details.
"""Define Tag class to hold a DICOM (group, element) tag and related functions.
The 4 bytes of the DICOM tag are stored as an arbitrary length 'long' for
Python 2 and as an 'int' for Python 3. Tags are stored as a single number and
separated to (grou... |
''' Advent of code 2019 Day 4: Secure Container'''
import math
INPUT_FILE=__file__.replace('.py', '.dat')
# returns -1 if the digits are fine (not decreasing)
# otherwise returns the index of the right-most digit that is not ok
def find_issue_digit(digits: list, length: int) -> int:
pos = length - 1
... |
# -*- coding: utf-8 -*-
"""
@create: 2020-04-01 06:07:29.
@author: ppolxda
@desc: task
"""
import six
import uuid
import json
import datetime
# from minio import Minio
class EnumStatus(object):
WAITTING = 'WAITTING'
DOING = 'DOING'
CANCEL = 'CANCEL'
FINISH = 'FINISH'
enum_list = [
WAIT... |
import pdb
import sys
import Pipelines as pl
import pandas as pd
from datetime import datetime
import numpy as np
import time
import tempfile
import os
# saving the models for the iteration tests:
# to save the models for the iteration tests, we will save a dataframe (in the form of the final dataframe from Analyzer..... |
"""Roles/directives for evaluating variables in the notebook."""
from __future__ import annotations
from functools import partial
from typing import TYPE_CHECKING, Any
from docutils import nodes
from docutils.parsers.rst import directives as spec
from myst_nb.core.execute.base import EvalNameError
from myst_nb.core.... |
#!/usr/bin/python
# Copyright 2018 The Batfish Open Source Project
#
# 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 re... |
# Sanitize a dependency so that it works correctly from code that includes
# TensorFlow as a submodule.
def clean_dep(dep):
return str(Label(dep))
# Ref: bazel-skylib@lib/paths.bzl
def basename(p):
"""Returns the basename (i.e., the file portion) of a path.
Note that if `p` ends with a slash, this function... |
# -*- cpy-indent-level: 4; indent-tabs-mode: nil -*-
# ex: set expandtab softtabstop=4 shiftwidth=4:
#
# Copyright (C) 2010,2011,2012,2013,2014,2015,2016,2017 Contributor
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obt... |
import tkinter
import math
# ----- CONSTANTS ----- #
PINK = "#e2979c"
RED = "#C84B31"
GREEN = "#dce0cd"
GREEN_MSG = "#125C13"
YELLOW = "#ECDBBA"
FONT_NAME = "Lucida Console"
WORK_MIN = 25
SHORT_BREAK_MIN = 5
LONG_BREAK_MIN = 20
repetition = 0
timer = None
# --- UI FUNCTIONS: Countdown Clock --- #
def start_timer():... |
import os
import numpy as np
from scipy.io import loadmat, whosmat
from mindaffectBCI.decoder.utils import block_randomize, butter_sosfilt, upsample_codebook, lab2ind, window_axis
marker2stim=dict(lh=(1,3),rh=(2,4))
def load_twofinger(datadir, sessdir=None, sessfn=None, fs_out=60, stopband=((45,65),(0,1),(25,-1)), su... |
from matplotlib import pyplot as plt
import torch
use_cuda = True
from IPython.display import SVG, display
import numpy as np
import svgwrite
from six.moves import xrange
import math
import torch.nn as nn
import torchvision
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
import torch.nn.functional... |
#!/usr/bin/env micropython
import sys
import time
from ev3dev2.sensor.lego import GyroSensor
from ev3dev2.sensor import INPUT_2
from line import Line_Flowering, square2line
from color import *
from move import *
ml=get_left_drive_motor()
mr=get_right_drive_motor()
mmL=get_left_action_motor()
gyro = GyroSensor(INPUT... |
#!/usr/bin/env python
# Copyright 2017 F5 Networks 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... |
from dataclasses import dataclass
from ficdl.scrapers.types import StoryMetadata
from pathlib import Path
import queue
from typing import Optional, Union
import threading
import tkinter as tk
import tkinter.ttk as ttk
import tkinter.filedialog as filedialog
import tkinter.messagebox as messagebox
from bs4 import PageE... |
#Copyright (c) <NAME>
#Released under MIT License
import sys
import json
import os
from subprocess import Popen, PIPE
from math import log, sqrt
from collections import defaultdict
from sklearn.feature_extraction import DictVectorizer
def lines_to_feature_dict(lines, df):
d = defaultdict(float)
features = s... |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... |
import numpy as np
from matplotlib.patches import Ellipse
def generate_bounding_box_from_mask(mask):
"""
Function for generating a bounding box around a mask.
Bounding box covers the extremes of the mask inclusively such that the far left box aligns
with the far left of the mask.
:param mask: 2D ma... |
"""Convert a v0 formatted notebook to a v1 formatted notebook"""
import copy
import nbformat
import re
from ..assignment import is_assignment_cell
from ..constants import BEGIN_TEST_CONFIG_REGEX, BLOCK_QUOTE
from ..questions import is_question_cell, read_question_metadata
from ..solutions import is_markdown_solution_... |
# License: BSD 3 clause
import matplotlib.pyplot as plt
import numpy as np
def plot_point_process(point_process, plot_intensity=None, n_points=10000,
plot_nodes=None, t_min=None, t_max=None, max_jumps=None,
show=True, ax=None):
"""Plot point process realization
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.