text stringlengths 3.07k 12.6k |
|---|
from functools import wraps
from collections import namedtuple
from django.conf.urls import url
from django.template.loader import render_to_string
from django.shortcuts import render
class Steps:
'''
The `Steps` class makes it easier to consolidate the view logic of
multi-step workflows.
The `Steps`... |
"""
Exercise 6: SR Euler equations with the Godunov scheme, Rusanov.
"""
import numpy
from matplotlib import pyplot
from lib import grids, boundary_conditions
from systems.euler_sr import EulerSR
from ex05_euler import initial_data_sod, godunov_rusanov_step
def initial_data_blast(system, x):
"""
Sod shock t... |
from datetime import date
from decimal import Decimal
from itertools import groupby
from model import Cash, Currency, Stock, Bond, Option, OptionType, Position, Trade, TradeFlags
from pathlib import Path
import fidelity
import helpers
import unittest
class TestFidelityPositions(unittest.TestCase):
def setUp(self... |
"""Test replication of key results in [1]_ and [2]_.
For [1]_, we test the following replications:
- Table 6: Only means and standard deviations for the exact solution.
For [2]_, we test the following replications:
- Tables 2.1-2.3: Choice probabilities per period.
References
----------
.. [1] <NAME>. and <NAME>.... |
# coding:utf-8
# --author-- lanhua.zhou
""" zfused maya 检查机制 """
from __future__ import print_function
import os
import logging
import maya.cmds as cmds
import zfused_api
import zfused_maya.core.record as record
import texture
class Check(object):
""" check base object
"""
value = False
def camera_... |
import logging
from django.template import RequestContext
from django.urls import reverse
from django.utils.encoding import force_text
from django.utils.translation import ugettext_lazy as _
from mayan.apps.common.generics import (
AddRemoveView, SingleObjectCreateView, SingleObjectDeleteView,
SingleObjectLis... |
# -*- coding: utf-8 -*-
"""
human VS AI models
Input your move in the format: 2,3
@author: <NAME>
"""
from __future__ import print_function
import os
import re
import sys
import random
import itertools
import math
import pandas as pd
import pickle
from trueskill import Rating, quality_1vs1, rate_1vs1, rate
from gam... |
from iot_device import DeviceRegistry
from iot_device import RemoteError
import iot_device
from .nb_conf import NbConf
from .kernel_logger import logger
from .magics.magic import LINE_MAGIC, CELL_MAGIC
from .version import __version__
from serial import SerialException
from websocket import WebSocketException
from ip... |
from netbox_agent.raid.base import Raid, RaidController
from netbox_agent.misc import get_vendor
from netbox_agent.config import config
import subprocess
import logging
import re
REGEXP_CONTROLLER_HP = re.compile(r'Smart Array ([a-zA-Z0-9- ]+) in Slot ([0-9]+)')
class HPRaidControllerError(Exception):
pass
def ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys, os
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, Text, Boolean, String, ForeignKey, create_engine
from sqlalchemy.orm import sessionmaker, relationship, scoped_session
from flask_sqlalchemy import SQLAlchemy
fro... |
import os
import numpy as np
import pandas as pd
import rampwf as rw
from rampwf.score_types.base import BaseScoreType
class Mechanics(object):
def __init__(self, workflow_element_names=[
'feature_extractor', 'classifier', 'regressor']):
self.element_names = workflow_element_names
self... |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""Process tutorials notebooks for publication in documentation."""
import argparse
import logging
import os
import shutil
import subprocess
import sys
from configparser import ConfigParser
from distutils.util import strtobool
from pathlib import Path
impo... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: <NAME> <<EMAIL>>
"""
This module converts `DGParentedTree`s into .dis files.
"""
import codecs
import os
import re
from rstconverter.tree import DGParentedTree, t, is_leaf
class DisFileWriter(object):
def __init__(self, dgtree, output_filepath=None):
... |
# -*- coding: utf-8 -*-
import numpy as np
import itertools
from utils import cost, addgap
def align_nw_2by2(seq1, seq2):
""" Perform 2 by 2 sequence alignment with the Needleman and Wunsch algorithm.
Parameters:
----------
seq1: string of characters of len=n1
sequence of nucleotides
seq... |
import spacy
from nltk import download
from nltk.corpus import wordnet
from nltk.data import find
from initialize import spacy_nlp
from interfaces.SentenceOperation import SentenceOperation
from interfaces.SentencePairOperation import SentencePairOperation
from tasks.TaskTypes import TaskType
"""
Adjectives Antonyms ... |
import os
import urllib.request
import logging
from django.db import models
from django.contrib.auth.models import User
from django.core.files import File
from django.contrib.contenttypes.fields import GenericRelation
from django.utils import timezone
from .tag import TaggedItem, SeenItem
from .media import CachedIma... |
__author__ = u'schmatz'
import errors
import configuration
import mongo
import node
import repositoryInstaller
import ruby
import shutil
import os
import glob
import subprocess
def print_computer_information(os_name,address_width):
print(os_name + " detected, architecture: " + str(address_width) + " bit")
def constr... |
# -*- coding: utf-8 -*-
"""Provider for HTML documents
This provider is a little bit special, in that it isn't simply pulling an
academic paper from a site, but instead aims to pull a HTML article.
Author: <NAME>
License: See LICENSE file.
Copyright: 2020, <NAME>
"""
import re
import urllib
import html2text
impo... |
import logging
import os
from typing import Dict, Optional
import torch
from d3m import container, utils
from d3m.metadata import base as metadata_base, hyperparams, params
from d3m.primitive_interfaces import base
from d3m.primitive_interfaces.supervised_learning import PrimitiveBase
from distil.modeling.bert_models ... |
# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Run the first page of one benchmark for every module.
Only benchmarks that have a composable measurement are included.
Ideally this test would be compreh... |
import random
import time
import signal
from testgraphs import nPuzzleGraph
from testgraphs import nPuzzleGraphValued
from testgraphs import State
import math
from search import BFS
from search import DFS
from search import UCS
from search import IDS
from search import DLS
from search import Astar
from search import ma... |
import re
from typing import List, Optional
from word2number import w2n
from ._custom_types import *
from ._languages import Languages, Language
class WordsNumbersConverterException(Exception):
"""Exception thrown when the text representation of the number cannot be converted."""
pass
class WordsNumbersCo... |
#!/usr/bin/env python3
import json
import re
import urllib.parse
import urllib.request
import sys
import os
import datetime
import gzip
import subprocess as sp
import html
################################################################################
##### C O N F I G U R A T I O N ... |
"""
Tests for forwarding exceptions from child to parent processes.
"""
import platform
import re
import textwrap
import traceback
import pytest
def test_error_forwarding(env):
"""Exceptions are forwarded from child to parent processes if there
are any.
"""
def child(env):
raise ValueError(... |
from keras.models import Model
from keras.layers import (
Input,
Dense,
Flatten,
Dropout
)
from keras.layers.convolutional import (
AveragePooling3D,
Conv3D
)
from keras.layers.normalization import BatchNormalization
from keras.layers.advanced_activations import PReLU, LeakyReLU, ELU, Thresholde... |
"""Cover for Shelly."""
from __future__ import annotations
from typing import Any, cast
from aioshelly.block_device import Block
from homeassistant.components.cover import (
ATTR_POSITION,
SUPPORT_CLOSE,
SUPPORT_OPEN,
SUPPORT_SET_POSITION,
SUPPORT_STOP,
CoverDeviceClass,
CoverEntity,
)
fr... |
# coding=utf-8
# Copyright 2015 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import logging
impor... |
#!/usr/bin/env python3
"""
Generate PDFs from DNS data
"""
# ========================================================================
#
# Imports
#
# ========================================================================
import os
import io
import itertools
import numpy as np
import pandas as pd
from scipy import st... |
""" Solutions for https://adventofcode.com/2020/day/24 """
# import modules used below.
from collections import Counter, UserDict
from copy import deepcopy
from dataclasses import dataclass
# Part 1: After flipping the tiles in a hexagonal grid specified in the
# provided data file, how many tiles will be black-side... |
# coding=utf-8
# Copyright 2022 The TensorFlow Datasets Authors.
#
# 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 appl... |
from __future__ import print_function
from itertools import product
import numpy as np
from numba import cuda
from numba.cuda.testing import unittest
class CudaArrayIndexing(unittest.TestCase):
def test_index_1d(self):
arr = np.arange(10)
darr = cuda.to_device(arr)
for i in range(arr.si... |
# Copyright (c) 2010-2013, Regents of the University of California.
# All rights reserved.
#
# Released under the BSD 3-Clause license as published at the link below.
# https://openwsn.atlassian.net/wiki/display/OW/License
import abc
import logging
import sys
import threading
import time
from pydispatch import dispat... |
# Copyright (c) 2013 Mirantis 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 or agreed to in writi... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import argparse
import pandas as pd
import rdkit
from rdkit import Chem
from rdkit.Chem import Descriptors
from dglt.contrib.moses.moses.metrics.utils import get_n_rings, get_mol
#_mcf = pd.read_excel("MCF_all.xlsx", names=['smarts'])
#_filters = list(set([Chem.MolFromSmar... |
from affine import Affine
import pytest
from datacube.utils.documents import parse_yaml
from datacube.testutils import mk_sample_product
from datacube.model import Dataset
from datacube.index.eo3 import (
prep_eo3,
eo3_lonlat_bbox,
add_eo3_parts,
is_doc_eo3,
grid2points,
)
SAMPLE_DOC = '''---
$sch... |
import functools
import inspect
import os
from typing import Dict, Tuple
import pytest
from monitoring.prober import utils
_test_results = dict()
def add_test_result(item, result):
global _test_results
_test_results[item] = result
def depends_on(*args):
"""Test decorator that skips a test if a dependent t... |
###########################################################################
#
# Copyright 2018 Google 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
#
# https://www.apache.org... |
# -*- coding: utf-8 -*-
import numpy as np
from utils.core import Env, World, Agent, Landmark, Map
class Exp1_Env(Env):
def __init__(self, config):
super(Exp1_Env, self).__init__()
self.world = self.make_world(config)
self.agents = self.world.agents
self.num_agents = len(self.world... |
# 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... |
import setup_path
import airsim
import numpy as np
import os
import tempfile
import pprint
import cv2
import random
import math
import shutil
import argparse
########################################################################
#input is the depth 2d np array (h,w) float, fov
#
def savePointCloud(fi... |
from applications.timeflow.pages.utils import switch_state
from idom import html, use_state, component, event
from idom.backend import fastapi
import requests
from datetime import datetime
from uiflow.components.input import Input, Selector2
from uiflow.components.layout import Row, Column, Container
from uiflow.compo... |
import argparse
import torch
import torch.nn.functional as F
from pytorch_transformers import BertConfig, BertForMaskedLM, BertTokenizer
def batch_list(l, batch_size):
for i in range(0, len(l), batch_size):
yield l[i : i + batch_size]
def encode_batch(batch, tokenizer, config):
# Truncate input bas... |
#!/usr/bin/env python
"""Tests for the linalg.isolve.gcrotmk module
"""
from numpy.testing import (assert_, assert_allclose, assert_equal,
suppress_warnings)
import numpy as np
from numpy import zeros, array, allclose
from scipy.linalg import norm
from scipy.sparse import csr_matrix, eye, r... |
"""Zhang Gradient Projection Debiasing Baseline Model."""
from __future__ import annotations
from typing import NamedTuple, cast
import ethicml as em
from kit import implements
from kit.torch import CrossEntropyLoss, TrainingMode
import pandas as pd
import pytorch_lightning as pl
from pytorch_lightning.utilities.types... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Apr 29 12:03:54 2018
@author: Young
"""
# Import modules
import os
import sys
import numpy as np
import pandas as pd
# Import custom functions
utilities_dir = '/Users/Young/Documents/Capgemini/Learning/Machine Learning/NN/Functions'
sys.path.append(u... |
"""A mypy_ plugin for managing a number of platform-specific annotations.
Its functionality can be split into three distinct parts:
* Assigning the (platform-dependent) precisions of certain `~numpy.number`
subclasses, including the likes of `~numpy.int_`, `~numpy.intp` and
`~numpy.longlong`. See the documentation... |
"""
Runs a bi-directional breadth-first search between two Wikipedia articles and returns a list of
the shortest paths between them.
"""
def get_paths(page_ids, visited_dict):
"""Returns a list of paths which go from the provided pages to either the source or target pages.
Args:
page_ids: The list of page ID... |
# Based on code from https://github.com/tensorflow/cleverhans
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from distutils.version import LooseVersion
from tensorflow.python import keras
from tensorflow.python.keras... |
import torch.nn as nn
import torch.nn.functional as F
import torch
import numpy as np
def load_embedding_model(pt_file, embedding_size):
"""Return an EmbeddingNet model with saved model weights, usable for inference only."""
model = EmbeddingNet(embedding_size)
# Explicitly map CUDA-trained models to CPU ... |
import logging
from typing import Optional
import xbmcaddon
import os
from .kodi_rpc import get_item_info, get_properties
from .periodic_updater import PeriodicUpdater
from .preferences import Preferences
ADDON = xbmcaddon.Addon()
logger = logging.getLogger(ADDON.getAddonInfo('id'))
def same_audio(audio1, audio2) ... |
""" Chunk and Pre-process the Raw Data for Silent (Vocally Inactive Times)"""
from src.sanity_checks.data_check_first_pass import _get_true_starts
import BirdSongToolbox.GetBirdData as gbd
import BirdSongToolbox.epoch_raw_data as erd
from BirdSongToolbox.file_utility_functions import _save_pckl_data
from pathlib impo... |
from aiogram import types
from aiogram.utils.exceptions import MessageNotModified
from aiogram.dispatcher import FSMContext
from data import config
from keyboards.inline import (back_callback, courses, faculties, groups,
languages, subgroups)
from loader import dp, bot
from middlewares imp... |
import socket
import inspect
import os
import ntpath
import errno
from tqdm import tqdm
from mysocks.utilities import mapcount
import time
from math import floor, ceil
from . import Model
class file_transfer(Model):
"""This class is parent class to file transfer module.
:param host: IP Address of the socket... |
from config_interface import *
k_B = 1.38064852 * 10**(-23) #Boltzmann constant
def N_Y_inf(phi): #longterm annealing amplitude
return g_y * phi
def tau_Y(T): #Time constant
return 1/(k_0y *np.exp(-E_y/(k_B*(T+273.15))))
def tau_... |
# coding=utf-8
# main codes, call functions at stokes_flow.py
# <NAME>, 20170518
import sys
import petsc4py
petsc4py.init(sys.argv)
# from scipy.io import savemat, loadmat
# from src.ref_solution import *
# import warnings
# from memory_profiler import profile
# from time import time
import pickle
import numpy as np... |
"""referencerenderer -- Generates string representations of appscript references from aem object specifiers. """
import struct
from .terminology import kProperty, kElement
from aem import Query
######################################################################
# PRIVATE
###########################################... |
"""
Helper functions.
"""
from __future__ import absolute_import
from __future__ import unicode_literals
import operator
from .models.variants import Position
from .models.transcript import Transcript, CDNA_Match, Exon
def read_refgene(infile):
""" refGene = genePred with extra column at front (and ignored ones... |
import numpy as np
import cupy as cp
from numba import cuda, float32
import numba
import math
import scipy.signal as signal
import matplotlib.pyplot as plt
from scipy.io import loadmat
import pickle
from cupyx.scipy import fftpack
def create_grid(x_mm, z_mm, nx=128, nz=128):
xgrid = np.linspace(x_mm[0] * 1e-3, x_... |
import cv2
import numpy as np
from scipy.sparse import diags
luminance_threshold = 30
chroma_threshold = 10
scale_percent = 20
beta = 30
alpha = 2
drawing = False
ix = -1
iy = -1
points_data = []
def draw(event, x, y, flags, param):
global drawing, ix, iy, points_data, begin, end
if event == cv2.EVENT_LBUT... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#import pytest
from masci_tools.io.modify_potential import modify_potential
from masci_tools.io.parsers.kkrimp_parser_functions import KkrimpParserFunctions
class Test_modify_potential(object):
""" Tests for the modify_potential class functions. """
def test_sh... |
import os
import copy
import json
import numpy as np
import pandas as pd
from pathlib import Path
from flask import Flask , jsonify
from flask import render_template
from flask import send_file , request
from flask_login import LoginManager
from rubix_cube.cube import Cube
from rubix_cube.cube_game import Cube_Gam... |
#!/usr/bin/env python3
###
#
# MIT License
#
# Copyright (c) 2016 <NAME>, <NAME>, <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 t... |
from werkzeug.wrappers import Request, Response
from werkzeug.serving import run_simple
from threading import Thread, Lock
from time import sleep
import requests
import argparse
import json
from jsonrpc import JSONRPCResponseManager, dispatcher
notification_dict = {}
ntf_service = None
verbose = 0
counter = 1
lock =... |
import re
import json
import logging
import datetime
import aiohttp
from gear import Database
from hailtop import aiotools
from hailtop.aiocloud import aiogoogle
from hailtop.utils import periodically_call, time_msecs, parse_timestamp_msecs
from ..batch_configuration import PROJECT, DEFAULT_NAMESPACE
from .zone_monit... |
# -*- coding: utf-8 -*-
"""
Created on Fri Apr 5 07:13:15 2019
@author: steve
"""
from __future__ import print_function
import sys,re,os,json
import PySimpleGUI27 as sg
import subprocess,threading,Queue
ON_POSIX = 'posix' in sys.builtin_module_names
def enqueue_output(out, queue):
for line in iter(out.r... |
import pytest
from bundle.GraphObjects.Graph import Graph, MutableGraph
from bundle.GraphObjects.Node import Node
from bundle.GraphObjects.Edge import Edge
from .utils import path_join, TEST_PATH
@pytest.fixture()
def simple_graph_js():
with open(path_join(TEST_PATH, 'test_files', 'graphs', 'simple_graph.cyjs')) ... |
# SPDX-FileCopyrightText: <NAME> <<EMAIL>>
#
# SPDX-License-Identifier: MIT
"""Watcher function and helpers."""
import sys
import time
from datetime import datetime
from typing import Any, Dict, Optional
import zenity
from aw_client import ActivityWatchClient
from aw_core.models import Event
from croniter import c... |
# -*- coding: utf-8 -*-
"""
longboxed.api.users
~~~~~~~~~~~~~~~~~~~~
Users endpoints
"""
from datetime import datetime
from datetime import date as _date
from flask import abort, current_app, Blueprint, g, jsonify, request
from flask.ext.security.registerable import register_user
from werkzeug.datastructu... |
import numpy as np
import random
from os import path, environ
import sys
environ['TF_CPP_MIN_LOG_LEVEL'] = '2' #1 to filter logs, 2 warnings, 3 for errors
from keras.layers import Dense
from keras.models import Sequential, save_model, load_model
from keras.optimizers import Adam
class Network(object):
"""
This... |
import os
import sys
import shutil
import click
from podmena.fetcher import SimpleFetcher
from podmena.parser import RegexParser
from podmena.utils import (
_warn,
_note,
_info,
force_symlink,
get_git_root_dir,
set_git_global_hooks_path,
get_git_config_hooks_value,
unset_git_global_hoo... |
'''
rev_sistematica.py
Um programa criado para a última atividade de Metodologia de Pesquisa/Ifes Campus Serra 2021/2
Recebe:
str -> caminho de um diretório com artigos .pdf
str -> caminho de um arquivo JSON com termos a serem encontrados nos arquivos
Exporta:
Imagens de tabela e gráfico de pizza + relat... |
""" This module contains functions for loading data. """
from collections import OrderedDict
import csv
from typing import Tuple, Optional, Dict, List
import arff
import pandas as pd
from gama.data_formatting import infer_categoricals_inplace
CSV_SNIFF_SIZE = 2 ** 12
def sniff_csv_meta(file_path: str) -> Tuple[str... |
#
# Copyright (C) 2020 IBM. All Rights Reserved.
#
# See LICENSE.txt file in the root directory
# of this source tree for licensing information.
#
import argparse
import logging
import re
from typing import Dict, Iterable, Optional, Sequence, Tuple, Union
import cv2
import numpy as np
def to_grayscale(img: np.array... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Python Camel and SnaKe Case : https://towardsdatascience.com/why-does-python-recommend-the-snake-case-nomenclature-bf908777c2dc#:~:text=It%20should%20be%20noted%20that,%2Dshaped%20naming%20(lower_case_with_underscores).
Reverse Python code to UML :
sudo apt install... |
#custom_models_ablation.py
#Copyright (c) 2020 <NAME>
#MIT License
#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, m... |
"""Module that provides schema for GeoJSON data structures."""
import geojson
import geomet.wkt as wkt
import geomet.wkb as wkb
import roax.schema as s
class _Object(s.type):
"""Base class for all GeoJSON objects."""
def __init__(
self,
*,
python_type,
content_type="applicati... |
#!/usr/bin/env python3.8
# Copyright 2018 The Fuchsia Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import argparse
import re
import sys
import subprocess
_FILE_HEADER = """// Copyright 2018 The Fuchsia Authors. All rights reserved.... |
#!/usr/bin/env python
import wx
#----------------------------------------------------------------------
class TestPanel(wx.Panel):
def __init__(self, parent, log):
self.log = log
wx.Panel.__init__(self, parent, -1)
box = wx.BoxSizer(wx.VERTICAL)
title = wx.StaticText(self, -1, "P... |
r"""Observables in lepton flavour violating decays $B\to V\ell\ell^\prime$"""
import flavio
import scipy.integrate
from flavio.classes import Observable, Prediction
from math import sqrt, pi
def prefactor(q2, par, B, V, l1, l2):
GF = par['GF']
ml1 = par['m_'+l1]
ml2 = par['m_'+l2]
scale = flavio.conf... |
from __future__ import division, print_function, absolute_import
# LIBTBX_SET_DISPATCHER_NAME iota.single_image
# LIBTBX_PRE_DISPATCHER_INCLUDE_SH export PHENIX_GUI_ENVIRONMENT=1
# LIBTBX_PRE_DISPATCHER_INCLUDE_SH export BOOST_ADAPTBX_FPE_DEFAULT=1
'''
Author : Lyubimov, A.Y.
Created : 05/31/2018
Last Change... |
# -*- coding: utf-8 -*-
"""
All native datatypes.
"""
__version__ = '0.12'
__author__ = ['<NAME>']
import os
from redis import Redis
from redis_natives.errors import RedisTypeError
__all__ = (
"Primitive",
"Set",
"ZSet",
"ZOrder",
"Dict",
"List",
"Sequence"
)
class RedisDataType(object... |
from matplotlib import pyplot as plt
from matplotlib.patches import Rectangle
from matplotlib.lines import Line2D
import numpy as np
# 2d box 그리기
def boxplot_2d(x,y, ax, fc, label, whis=1.5):
xlimits = [np.percentile(x, q) for q in (25, 50, 75)]
ylimits = [np.percentile(y, q) for q in (25, 50, 75)]
##the ... |
from functools import partial
from types import SimpleNamespace
import numpy as np
from meerkat.tools.lazy_loader import LazyLoader
scipy_optimize = LazyLoader("scipy.optimize")
scipy_special = LazyLoader("scipy.special")
skmetrics = LazyLoader("sklearn.metrics.pairwise")
def Phi(D, edge_list: list = None):
"""... |
import copy as cp
from sklearn import linear_model
from skmultiflow.core.base import StreamModel
from skmultiflow.evaluation.metrics.metrics import *
class MultiOutputLearner(StreamModel):
""" MultiOutputLearner
A Multi-Output Learner learns to predict multiple outputs for each
instance. The outputs ... |
from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.core.exceptions import ObjectDoesNotExist
from django.contrib.auth.decorators import login_required
from .models import *
from patients.models import Patient
from .forms import ReviewForm
import utils.search_engine as search_... |
# -*- coding: utf8 -*-
import struct
from crypto import keccak256
from ipaddress import ip_address
import binascii
class EndPoint(object):
"""
Endpoint <= 24 == [17,3,3]
{
unsigned address; // BE encoded 32-bit or 128-bit unsigned (layer3 address; size determins ipv4 vs ipv6)
u... |
"""Miscellaneous commands for computing extra metadata (specifically,
days late and status) about trials.
Called during the import process.
"""
from datetime import date
from dateutil.relativedelta import relativedelta
from django.apps import apps
from django.utils.dateparse import parse_date
GRACE_PERIOD = 30
de... |
import builtins
import datetime
from files_sdk.api import Api
from files_sdk.list_obj import ListObj
from files_sdk.exceptions import InvalidParameterError, MissingParameterError, NotImplementedError
class SsoStrategy:
default_attributes = {
'protocol': None, # string - SSO Protocol
'provider':... |
from api import State, util
import random, os
from itertools import chain
import joblib
# Path of the model we will use. If you make a model
# with a different name, point this line to its path.
DEFAULT_MODEL = os.path.dirname(os.path.realpath(__file__)) + '/model.pkl'
class Bot:
__randomize = True
__model... |
#!/usr/bin/env python
##############################################################################
#
# Copyright (c) 2001, 2002, 2013 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accom... |
import csv
import itertools
import numpy as np
from glob import glob
def read_csv(inp, header=True):
"""
Reads a csv file.
:param inp: input file
:param header: inp contains a header
:return:
:titles: titles of the columns
:xs: x-values (1- or 2-dim np.array)
:ys: y-value... |
from board import Board
from random import randint
import cpu
class Game():
def __init__(self, player1, player2, size_horizontal, size_vertical):
self.player1 = player1
self.player2 = player2
self.size_horizontal = size_horizontal
self.size_vertical = size_vertical
... |
# Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
# See https://llvm.org/LICENSE.txt for license information.
# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
"""
Frontend to the compiler, allowing various ways to import code.
"""
import ast
import inspect
import textwrap
from... |
# -*- coding: utf-8 -*-
"""
streamer.operator
---
The module contains some iterator operator - add operation to an iterator and keep its laziness.
Treat this as a semi-internal module - subjected to breaking changes.
"""
from typing import Generic, TypeVar, Iterator, Iterable, Callable, Union, Any, Tuple
from collec... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = 'ipetrash'
import sys
import math
# Auto-generated code below aims at helping you parse
# the standard input according to the problem statement.
city_map = list()
l, c = [int(i) for i in input().split()]
for i in range(l):
row = input()
print(row... |
import praw
import re
import json
from enum import Enum, unique
import unidecode
import string
from random import choice
from collections import OrderedDict
from psaw import PushshiftAPI
import datetime
reddit = praw.Reddit("alphabotical")
pushShift = PushshiftAPI(reddit)
fetch_time = 3 # minutes to fetch from last... |
from __future__ import annotations
import re
import typing as t
from datetime import datetime, timezone
import discord
from discord.ext.commands import (
BadArgument,
Context,
Converter,
IDConverter,
MemberConverter,
UserConverter,
)
from discord.utils import escape_markdown, snowflake_time
f... |
import conformer_rl
import torch
from conformer_rl.agents.PPO.PPO_agent import PPOAgent
def mock_init(self):
pass
def test_step(mocker):
mocker.patch('conformer_rl.agents.PPO.PPO_agent.PPOAgent.__init__', mock_init)
no_grad = mocker.patch('conformer_rl.agents.PPO.PPO_agent.torch.no_grad')
sample = moc... |
## Load other sub-packages
from .. import visual_tools, get_img_info
## Load shared parameters
from . import _distance_zxy, _image_size, _allowed_colors
from . import _num_buffer_frames, _num_empty_frames
## load packages
import numpy as np
import scipy
import os, sys, glob, time
def decide_starting_frames(channel... |
'''
Copyright (C) 2017-2020 <NAME> - <EMAIL>
Please see the LICENSE file for the terms and conditions
associated with this software.
'''
import logging
from decimal import Decimal
import requests
from cryptofeed.backends.backend import (BackendBookCallback, BackendBookDeltaCallback, BackendFundingCallbac... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.