text stringlengths 3.07k 12.6k |
|---|
import os
import torch
from torch import nn
from torch.nn import functional as F
class Mish(nn.Module):
def __init__(self):
super(Mish, self).__init__()
def forward(self, x):
return x * (torch.tanh(F.softplus(x)))
class FirstResidualBlock(nn.Module):
def __init__(self, inchannel, outcha... |
import os
from importlib import import_module
from importlib.util import module_from_spec, spec_from_file_location
from pathlib import Path
from .printer import printer
def abs_path(path, format_kwargs={}, relative_to=None, keep_slash=False):
"""Get abs. path for ``path``.
``path`` may be a relative or abso... |
import unittest
import collections
import pickle
import random
import mock
import six
from torchnlp.text_encoders import subword_text_tokenizer
from torchnlp.text_encoders.subword_text_tokenizer import encode
from torchnlp.text_encoders.subword_text_tokenizer import decode
from torchnlp.text_encoders.subword_text_tok... |
"""
Script that evaluates the `SunMoon` class.
For one location, this script computes solar event times for all of
the nights of one year by three methods:
1. with one call to get_solar_events_in_interval
2. with one call per day to get_solar_events
3. with one call per event to get_solar_event_time
For ... |
"""
Copyright 2020 The OneFlow Authors. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agr... |
import numpy as np
from tifffile import imread as tifread
from matplotlib import pyplot as plt
from skimage.measure import label
def label_cytoplasma_and_overlap(data):
"""
Transform a volume of labels to a stack of two channels. The first channel is the cytoplasma label and the second
channel is the over... |
# Test images with pretrained tensorflow models
# call :
# python models/research/object_detection/test_models.py --frozen_graph {$path_to_frozen_graph}
# --label_map {$path_to_##.pbtxt} --test_dir {$path_to_test_set}
# --num {$number_test_images} --output_dir {$path_to_save_output_imagesWITHboxes}
import argparse
imp... |
import operator
from functools import reduce
from django.contrib.auth import get_user_model
from django.contrib.auth.decorators import login_required
from django.db.models import Q, Sum
from django.shortcuts import HttpResponse, get_object_or_404, redirect, render
from django.views.generic import View
from django.view... |
FILENAME = 'sequences_full.csv'
VOCAB_SIZE = None
UNK = 'UNK'
POS_TAGS = { 'CC' : '<CC>', 'CD' : '<CD>', 'DT' : '<DT>', 'EX' : '<EX>', 'FW' : '<FW>', 'IN' : '<IN>', 'JJ' : '<JJ>', 'JJR' : '<JJR>', 'JJS' : '<JJS>', 'LS' : '<LS>', 'MD' : '<MD>', 'NN' : '<NN>', 'NNS' : '<NNS>', 'NNP' : '<NNP>', 'NNPS' : '<NNPS>', 'PDT' :... |
import pytest
import time
from ethfinex.public_client import PublicClient
@pytest.fixture(scope='module')
def client():
return PublicClient()
@pytest.mark.usefixtures('client')
class TestPublicClient(object):
@staticmethod
def teardown_method():
time.sleep(.5) # Avoid rate limit
def test... |
"""
vtelem - A module implementing a message storage.
"""
# built-in
from contextlib import contextmanager
import os
from tempfile import TemporaryDirectory
from typing import Dict, Callable, List, Optional, Iterator, Tuple
# internal
from vtelem.classes.data_cache import DataCache
from vtelem.frame.fields import to_... |
"""Support for Habitica sensors."""
from collections import namedtuple
from datetime import timedelta
from http import HTTPStatus
import logging
from aiohttp import ClientResponseError
from homeassistant.components.sensor import SensorEntity
from homeassistant.config_entries import ConfigEntry
from homeassistant.cons... |
# ===============================================================================
# Copyright 2018 ross
#
# 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/LICE... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# (c) 2019, <NAME> (<EMAIL>)
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
from ansible.module_utils.urls import CertificateError
from ans... |
import logging
import time
from temboardagent.routing import add_route
from temboardagent.errors import (
HTTPError,
NotificationError,
SharedItem_exists,
SharedItem_no_free_slot_left,
SharedItem_not_found,
)
from temboardagent.sharedmemory import Session
from temboardagent.types import (
T_PAS... |
import torch
import numpy as np
import itertools
import time
from model.module.dependency import Dependency
from model.module.constituency import Constituency, InternalParseNode
from model.module.vocab import Vocabulary
from model.chart_parser import ChartParser
DEP_PATH = "../samples/dep_train.txt"
CON_PATH = "../... |
#! python3
"""
MIT License
Copyright (c) 2020 <NAME>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publ... |
from django.shortcuts import render
from django.http import HttpResponseRedirect
from trainings.models import Training, Exercise, TrainingPlan
from django.utils import timezone
from django.db.models import Sum
from plotly.offline import plot
import plotly.graph_objects as go
def trainings_view(request):
all_train... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 18 00:39:56 2021
@author: nimarahimian
"""
import time
import random
from functools import lru_cache
import numpy as np
import matplotlib.pyplot as plt
def marks(n, scenario):
"""Genererar spelarnas positioner på spelbrädet.
Tilldelar spe... |
from environments.TestNodesEnvironment import TestNodesEnvironment
from trajectory_utils.ModelFactory import ModelFactory
from trajectory_utils.ExperienceBag import ExperienceBag
from trajectory_utils.ModelTrainer import ModelTrainer
import numpy as np
import tensorflow as tf
import gym
cartPoleEnv = gym.make("Frozen... |
#
# Copyright (c) 2014-2018 Wind River Systems, Inc.
#
# SPDX-License-Identifier: Apache-2.0
#
import os
import socket
from sm_api.openstack.common import log
LOG = log.getLogger(__name__)
SM_API_SERVER_ADDR = "/tmp/.sm_server_api"
SM_API_CLIENT_ADDR = "/tmp/.sm_client_api"
SM_API_MSG_VERSION = "1"
SM_API_MSG_REV... |
# built-in
import subprocess
import sys
from argparse import ArgumentParser
from os import environ, name as os_name, pathsep
from pathlib import Path
from shutil import rmtree
from venv import create
POST_MESSAGE = """DepHell is installed now. Great!
DepHell was added in your PATH. Please, restart your shell.
"""
P... |
import DistConvGAN as model
import lbann.contrib.launcher
import lbann.contrib.args
import argparse
import os
from lbann.core.util import get_parallel_strategy_args
import lbann
import lbann.modules as lm
def list2str(l):
return ' '.join([str(i) for i in l])
def construct_lc_launcher_args():
parser = argpars... |
# Copyright 2012 OpenStack Foundation
# Copyright 2013 IBM Corp.
# 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/LIC... |
from datetime import datetime
import olympia.core.logger
from olympia import amo
from olympia.activity import log_create
from olympia.users.utils import get_task_user
log = olympia.core.logger.getLogger('z.amo.blocklist')
def add_version_log_for_blocked_versions(obj, old_obj, al):
from olympia.activity.models ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
**Project Name:** MakeHuman
**Product Home Page:** http://www.makehumancommunity.org/
**Github Code Home Page:** https://github.com/makehumancommunity/
**Authors:** <NAME>
**Copyright(c):** MakeHuman Team 2001-2019
**Licensing:** AG... |
import xml.etree.ElementTree as ET # good hints on using the XML module: https://stackabuse.com/reading-and-writing-xml-files-in-python/
from somo.sm_link_definition import SMLinkDefinition
from somo.sm_joint_definition import SMJointDefinition
############# utility to suppress printing - temporarily suppresses con... |
import numpy as np
import os
import errno
import torch
from torch.utils.data import Dataset, DataLoader
from torchvision import transforms
import pickle
from PIL import Image
from tqdm import tqdm
from image_encoder import load_resnet
def load_image(image_path):
''' Loads a single image from the given path.
P... |
import sys
from descent.asttypes import NamedType, TokenType, NodeType
def _indent(lines):
for line in lines:
if isinstance(line, list):
for indented in _indent(line):
yield " " + indented if indented else ""
else:
yield line
def _concat(lines):
re... |
# Copyright 2017 Red Hat, 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 ... |
# coding=utf-8
# Copyright 2021 HuggingFace 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 ag... |
# static analysis: ignore
from .error_code import ErrorCode
from .implementation import assert_is_value, dump_value
from .value import KnownValue, MultiValuedValue, TypedValue, UNRESOLVED_VALUE
from .test_node_visitor import assert_passes, assert_fails
from .test_name_check_visitor import TestNameCheckVisitorBase
cla... |
# Import packages.
import cvxpy as cp
import numpy as np
import sympy
class GlobalPolynomialOptimization:
def __init__(self):
pass
def coefficient_symbolic_match(self):
x, y, gamma = sympy.symbols('x y gamma')
# f(x, y) = 4 x^2 - 21/10* x^4 + 1/3 x^6 + xy - 4y^2 + 4y^4
f_mono... |
'''
Created on 2020-05-05 16:28:59
Last modified on 2020-09-30 11:42:01
@author: <NAME> (<EMAIL>)
'''
# imports
# standard library
import os
import pickle
import gzip
import shutil
# third-party
import pandas as pd
# local library
from .utils.file_handling import get_unique_file_by_ext
from .utils.file_handling i... |
"""
This module containes pure functions to help with creating flow table entries.
No to switch communication is supposed to reside in here.
"""
from ryu.ofproto import ofproto_v1_4 as ofp
from ryu.ofproto import ofproto_v1_4_parser as parser
from ryu.lib.ofctl_v1_3 import actions_to_str
import netaddr
T_DEFAULT = 0
... |
# MLFlow-augmented version of https://github.com/pytorch/examples/blob/master/mnist/main.py
from __future__ import print_function
import os
import mlflow
import argparse
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import numpy as np
import pandas as pd
from torchvisio... |
from ctypes import *
import math
import random
import os
import cv2
import numpy as np
import time
import darknet
import argparse
# !python darknet_video -v -c -w
# augument parser
ap = argparse.ArgumentParser()
ap.add_argument("-v" ,"--video", type=str, required=True,
help="Path to input video")
ap.... |
""" Helper classes used when processing the XPLT file """
from __future__ import print_function
import collections
import numpy
import stomasimulator.geom.geom_utils as geom
import stomasimulator.stomata.stoma_config as sc
from . import xplt_utils as xut
class Section( object ):
""" Represent a section of an... |
# -*- coding: utf-8 -*-
from decimal import Decimal
from django.conf.urls.defaults import patterns, include, url
from django.contrib.auth.models import User
from django.test import Client
import os
from ...pricing.app import ProductAppPricingMixin
from ...product.app import MagicProductApp
from ...product.tests.pricin... |
# -*-coding:utf-8 -*-
import re
import urllib.parse
from datetime import datetime
from bs4 import BeautifulSoup
from page_get import status
from logger.log import parser
from db.models import WeiboData
from config.conf import get_crawling_mode
from decorators.decorator import parse_decorator
ORIGIN = 'http'
PROTOC... |
from .utils import PyKEArgumentHelpFormatter
from . import kepio, kepmsg, kepkey
import numpy as np
from astropy.io import fits as pyfits
__all__ = ['kepclean']
def kepclean(infile, outfile=None, zero=True, overwrite=False, verbose=False,
logfile='kepclean.log'):
"""
Remove NaN values from a kepl... |
#!/usr/bin/env python3
import sys
import os
import subprocess
import platform
import json
import glob
C = {}
BZ_VERSION = '1.0.0'
BZ_CONFIG_FILE = 'buildzri.config.json'
BZ_OS = platform.system().lower()
BZ_ISLINUX = BZ_OS == 'linux'
BZ_ISDARWIN = BZ_OS == 'darwin'
BZ_ISWIN = BZ_OS == 'windows'
BZ_ISVERBOSE = '--ver... |
import sys
from PyQt5.QtGui import QPixmap
from Wheels import Wheels
from Accelerator import Accelerator
from PyQt5 import uic
from PyQt5.QtCore import QBasicTimer, Qt, QDataStream
from PyQt5.QtWidgets import QMainWindow, QApplication
from PyQt5.QtNetwork import QUdpSocket, QHostAddress, QTcpServer
from config.Confi... |
import os
os.environ['CUDA_VISIBLE_DEVICES'] = '2'
import numpy as np
from glob import glob
import random
import tensorflow as tf
from malaya_speech.train.model import fastspeech, fastvc
from math import ceil
from malaya_speech.train.loss import calculate_2d_loss, calculate_3d_loss
import malaya_speech.train as train... |
import argparse
import code
import importlib
import logging
import os
import sys
import threading
import traceback
from dataclasses import dataclass
from types import ModuleType
import blessed
from ovld import ovld
from watchdog.events import FileSystemEventHandler
from watchdog.observers import Observer
from watchdog... |
# -*- coding: utf-8 -*-
"""
Created on Thu Jul 23 22:30:21 2020
@author: pc
"""
import streamlit as st
import re
from string import punctuation
from nltk import word_tokenize
from nltk.corpus import stopwords
import docx
import time
def findclosestsentence(AllParagraphs,ParagraphNo,wordsFiltered2):
... |
# Copyright 1999-2021 Alibaba Group Holding Ltd.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... |
import sys
import os
import logging
import json
import pickle
import numpy as np
import traceback
sys.path.append("..")
import config
import cphmm.cphmm as hmm
from utils import parallel_utils, close_pair_utils
def init_hmm(species_name, genome_len, block_size):
# initialize the hmm with default params
# clon... |
"""
A collection of utilities used for SSL tests.
"""
import json
import logging
from typing import Any, Dict, Optional
import sdk_cmd
import sdk_security
import sdk_utils
log = logging.getLogger(__name__)
def setup_service_account(
service_name: str,
service_account_secret: Optional[str] = None,
) -> Dict... |
import logging
import multiprocessing
import os
from datetime import date
import numpy as np
import pandas as pd
from gensim.models.doc2vec import Doc2Vec, TaggedDocument
from keras.layers import Dense, Input
from keras.models import Model, load_model
from scipy.spatial.distance import cosine
from skimage.filters impo... |
import matplotlib.pyplot as plt
import numpy as np
import random as rand
from sklearn import preprocessing
from core.dynamics import ConfigurationDynamics
from core.controllers import ConstantController, PDController
from koopman_core.controllers import PerturbedController, OpenLoopController
class KoopPdOutput(Config... |
'''
Created on Jan 10, 2014
@author: sean
'''
from __future__ import print_function, unicode_literals, absolute_import
import sys
import struct
from pprint import pprint
from .errors import RPMError
tags = {'signature': 267
, 'md5': 269
, 'name': 1000
, 'version': 1001
, 'release': 1002
, 'serial'... |
import logging
from brainy.utils import invoke, load_yaml
from brainy.errors import BrainyProcessError
from brainy.process.base import BrainyProcess
from brainy.project.report import BrainyReporter
from brainy.process.decorator import (format_with_params,
require_key_in_description... |
import torch
from torch import nn
from thesis.wrappers import instantiate_environment
from thesis.preprocessor import MyObssPreprocessor
import numpy as np
import utils
from torch_rl.utils import DictList, ParallelEnv
import datetime
from thesis.wrappers import environment_name
import time
def train_environment_model... |
import datetime
import math
import re
string_types = str
class PersonnummerException(Exception):
pass
class Personnummer:
def __init__(self, ssn, options=None):
"""
Initializes the Object and checks if the given Swedish personal identity number is valid.
:param ssn
:type ssn... |
import re
from json import JSONDecodeError
from typing import Text, List, Dict, Match, Optional, NamedTuple, Any
import logging
import rasa.shared.nlu.training_data.util
from rasa.shared.constants import DOCS_URL_TRAINING_DATA_NLU
from rasa.shared.exceptions import InvalidEntityFormatException
from rasa.shared.nlu.con... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import codecs
import os
from lazagne.config.DPAPI.masterkey import MasterKeyPool
from lazagne.config.DPAPI.credfile import CredFile
from lazagne.config.DPAPI.vault import Vault
from lazagne.config.DPAPI.blob import DPAPIBlob
from lazagne.config.write_output import print_debug... |
grid = ['1', '2', '3', '4', '5', '6', '7', '8', '9']
# make a dictionary
grid_map = {1: ' ', 2: ' ', 3: ' ',
4: ' ', 5: ' ', 6: ' ',
7: ' ', 8: ' ', 9: ' '}
def gameOver(player1sMark): # x or 0
winner = 0
winning_grid_identifier = 0
if (grid_map[1] == grid_map[2] == grid_map[3]):
... |
import numpy as np
from tqdm import tqdm
from sklearn.model_selection import GroupShuffleSplit
def aa_encoding(adata, read_col, ohe_col=None, label_col=None, length_col=None, pad=False, aa_to_id=None, start_end_symbol=True):
"""
Encoding of protein or nucleotide sequence inplace, either one-hot-encoded or as index ... |
from bs4 import BeautifulSoup
import pandas as pd
import requests
def get_soup(url):
page = requests.get(url)
soup = BeautifulSoup(page.text, 'html.parser')
return soup
def scrape_mat_names():
soup = get_soup('https://gamepress.gg/grandorder/materials')
tables = soup.find('div', attrs={'class': ... |
import cupy as cp
import numpy as np
import pandas as pd
import itertools
import math
import networkx as nx
from gpucsl.pc.kernel_management import get_module
function_names = [
"calculate_contingency_matrix_level_0<12>",
"calculate_contingency_matrix_level_n<100, 2>",
"calculate_marginals_level_n",
"c... |
# Copyright 2020 Adap GmbH. 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 ag... |
# -*- coding: utf-8 -*-
"""
Created on Tue May 15 11:05:38 2018
@author: CUHKSZ
"""
import time
import xlsxwriter
import random
from collections import deque
import globalvar as gl
from ina219 import INA219
from ina219 import DeviceRangeError
def sensor():
global heading
global PWM... |
# Copyright 2021 The Cirq Developers
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in ... |
from numpy import zeros, ones, pi, array
from pyleecan.Classes.Simu1 import Simu1
from Tests.Validation.Simulation.CEFC_Lam import CEFC_Lam
from pyleecan.Classes.InputCurrent import InputCurrent
from pyleecan.Classes.ImportGenVectLin import ImportGenVectLin
from pyleecan.Classes.ImportMatrixVal import ImportMatrixVal... |
from django.test import Client, SimpleTestCase
class WithoutMixinTestCase(SimpleTestCase):
def test_get(self):
response = Client().get('/')
self.assertContains(response, "Received a GET", status_code=200)
def test_post(self):
response = Client().post('/')
self.a... |
#!/usr/bin/env python3
import argparse
import logging
import sys
from typing import Optional
from typing import Sequence
from typing import Tuple
from typing import Union
import humanfriendly
import torch
from typeguard import check_argument_types
from espnet.utils.cli_utils import get_commandline_args
from espnet2.f... |
# -*- coding: utf-8 -*-
"""Chemical Engineering Design Library (ChEDL). Utilities for process modeling.
Copyright (C) 2016, <NAME> <<EMAIL>>
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... |
import pygame
import time
pygame.init()
WIDTH = 100
HEIGHT = 100
CELL = 10
RIGHT_MARGIN = 200
MENU_ITEM_HEIGHT = 50
START_GAME = False
life = pygame.display.set_mode(
size=(WIDTH*CELL + RIGHT_MARGIN, HEIGHT*CELL)
)
pygame.display.set_caption("Conway's Game of Life")
WHITE = (255, 255, 255)
RED = (85, 17, 17)
B... |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
This plugin provides customization of the header displayed by pytest for
reporting purposes.
PYTEST_DONT_REWRITE
"""
import os
import sys
import datetime
import locale
from collections import OrderedDict
from distutils.version import LooseVersion
if... |
# Copyright 2016 Rackspace
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, sof... |
# -*- coding: utf-8 -*-
# --------------------------------------
# @Time : 2020/11/01
# @Author : <NAME>
# @Email : <EMAIL>
# @File : generator_anchors.py
# Description :generator k anchors
# --------------------------------------
"""
Boxes:
[[ 5 5]
[ 7 15]
[ 16 41]
[ 18 43]
[ 19 47]
[ 28 104]]
Ac... |
import tensorflow as tf
import urllib
def get_vgg16_weights():
"""
Returns: string
"""
urllib.urlretrieve("https://github.com/fchollet/deep-learning-models/releases/download/v0.1/vgg16_weights_tf_dim_ordering_tf_kernels_notop.h5",
filename="vgg16_weights_tf_dim_ordering_tf_ker... |
import logging
import time
from jwt import InvalidTokenError
from django.conf import settings
from django.contrib.auth import get_user_model
from django.contrib.auth.middleware import AuthenticationMiddleware
from django.contrib.auth.models import AnonymousUser
from django.contrib.sessions.backends.base import Update... |
# -----------------------------------------------------------------------------
#
# P A G E B O T E X A M P L E S
#
# Copyright (c) 2017 <NAME> <https://github.com/thomgb>
# www.pagebot.io
# Licensed under MIT conditions
#
# Supporting DrawBot, www.drawbot.com
# Supporting Flat, xxyxyz.org/flat... |
#!@PYTHON_EXECUTABLE@
#
# MIT License
#
# Copyright (c) 2018, The Regents of the University of California,
# through Lawrence Berkeley National Laboratory (subject to receipt of any
# required approvals from the U.S. Dept. of Energy). All rights reserved.
#
# Permission is hereby granted, free of charge, to any person... |
import numpy as np
from scipy.interpolate import interp1d
from .base import Prior
from ..utils import logger
class Interped(Prior):
def __init__(self, xx, yy, minimum=np.nan, maximum=np.nan, name=None,
latex_label=None, unit=None, boundary=None):
"""Creates an interpolated prior functio... |
import numba as nb
import numba_scipy
import numpy as np
from interpolation import interp
from scipy.special import gamma, gammaincc
from cosmogrb.sampler.temporal_functions import norris
from cosmogrb.utils.numba_array import VectorFloat64
@nb.njit(fastmath=True, cache=False)
def cpl(x, alpha, xp, F, a, b):
if... |
# Copyright 2018 The Kubeflow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicabl... |
import pandas as pd
import numpy as np
from itertools import combinations
from sklearn.model_selection import cross_val_score
from sklearn.feature_selection import RFE, SelectKBest, chi2
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier
from skle... |
import pycosat
import copy
import numpy as np
class CNF(object):
def __init__(self,n,m=0):
self.n = n
self.m = m
self.clauses = []
self.sat = None
#end
def SR(n):
cnf = CNF(n)
sat = True
while sat:
# Select a random k ~ Bernouilli(0.3) + Geo(0.4)
k = np.random.binomial(1,0.4) + np.random.ge... |
bl_info = {
"name": "Shipgenerator Hull",
"author": "<NAME> (KiOskars)",
"version": (0, 1),
"blender": (2, 80, 0),
"location": "View3D > Add",
"description": "Creates a ship hull surface",
"warning": "",
"wiki_url": "",
"category": "Add Surface",
}
import logging
import bpy
import r... |
import asyncio
import types
import urllib.parse as urlparse
from typing import Any, Awaitable, Callable, Iterable, List, Optional, TypeVar, Union
import aiowamp
from aiowamp import INVOKE_ROUND_ROBIN, INVOKE_SINGLE, URI, connect
from .handler import Handler, create_procedure_uri, create_registration_handler, create_su... |
# Colab setup ------------------
import os, sys, subprocess
import pkg_resources
if "google.colab" in sys.modules:
cmd = "pip install --upgrade iqplot colorcet watermark"
process = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = process.communicate()
data_p... |
import numpy as np
import pandas as pd
import os
from sklearn.model_selection import train_test_split
from util import data_io
def build_features(data):
features = []
# remove NaNs
data.fillna(0, inplace=True)
data.loc[data.Open.isnull(), "Open"] = 1
# Use some properties directly
features.ext... |
import numpy
import reikna.helpers as helpers
import reikna.cluda.dtypes as dtypes
from reikna.cluda import Module
import reikna.cluda.functions as functions
TEMPLATE = helpers.template_for(__file__)
class Sampler:
"""
Contains a random distribution sampler module and accompanying metadata.
Supports ``_... |
from enum import Enum
class TokenType(Enum):
Root = 0
Plus = 1
Minus = 2
Star = 3
Slash = 4
Int = 5
Float = 6
LeftBracket = 7
RightBracket = 8
class Token:
def __init__(self, tokenType: TokenType, value=None):
self.type = tokenType
self.value = value
def __repr__(self):
return repr(... |
# libraries
import gym
# pytorch library is used for deep learning
import torch
from collections import namedtuple
import matplotlib.pyplot as plt
# Policy Net
class PolicyNet(torch.nn.Module):
def __init__(self, input_size, output_size, hidden_layer_size=64):
super(PolicyNet, self).__init__()
s... |
import torch
import numpy as np
import torch.optim as optim
import random
import torch.nn as nn
import argparse
import time
import h5py
import datetime
import os, sys, pdb
from torch.utils.data import Dataset, DataLoader
import sparseconvnet as scn
batch_size = 32
epochs = 100
device = torch.device("cuda" if torch.cu... |
#!/usr/bin/env python
# -*- coding: utf-8; py-indent-offset:4 -*-
###############################################################################
#
# Copyright (C) 2015, 2016 <NAME>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as publish... |
""" Trains a Feed Forward Neural Network using features generated
by build_transaction_data().
"""
import pandas as pd
import numpy as np
import logging
import gc
import mlflow
import src.features.outlier_correction as oc
from src.features import build_features
from src.models import feed_forward
from pathlib impor... |
import os
import cv2
import pydload
import logging
import numpy as np
import onnxruntime
from progressbar import progressbar
from .detector_utils import preprocess_image
from .video_utils import get_interest_frames_from_video
def dummy(x):
return x
FILE_URLS = {
"default": {
"checkpoint": "https://... |
r"""Fetch ACP data.
Steps:
1. Open a new RFmx session
2. Configure Selected Ports
3. Configure the basic signal properties (Center Frequency, Reference Level and External
Attenuation)
4. Configure ACP Averaging Parameters
5. Configure ACP Integration BW, Number of Offset Channels and Channel Spacing
... |
import os
import subprocess
import pyperclip
import keyboard
import evdev
import sys
import yaml
import signal
from shutil import which
from evdev import InputDevice, categorize, ecodes
# Check if sudo or not
# Import umacro_conf
# Open YAML config file
with open("/etc/umacro/umacro_conf.yml", 'r') as f:
config =... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2019, <NAME> (<EMAIL>)
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals, print_function
from frida_tools.model import Module, Function, ModuleFunction
def main():
import threading
from frida_tools.application import await_enter, ConsoleApplication
class DiscovererApplication(ConsoleApplication, UI):
de... |
"""
Make plots for hashing bound.
"""
import numpy as np
import itertools
import scipy.optimize
from scipy.interpolate import griddata
def get_project_axes():
x_axis, y_axis, z_axis = np.eye(3)
h_axis = y_axis - x_axis
h_axis = h_axis/np.sqrt(h_axis.dot(h_axis))
xy_midpoint = (x_axis + y_axis)/2
... |
from __future__ import annotations
from typing import TYPE_CHECKING, Dict, Optional, Union
from .asset import Asset
# Internal imports
from .enums import EmbedType
from .file import File, get_file_from_url
if TYPE_CHECKING:
from .internals import HTTPHandler
from .types import (
EmbedPayload,
... |
# 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 json
import logging
import os
import sys
from http import HTTPStatus
import requests
from dotenv import load_dotenv
from telegram import Bot, ReplyKeyboardMarkup
from telegram.ext import CommandHandler, Filters, MessageHandler, Updater
import exceptions
load_dotenv()
TELEGRAM_TOKEN = os.getenv('TOKEN')
hand... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.