text stringlengths 3.07k 12.6k |
|---|
# Copyright (c) 2013 Rackspace, 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 wr... |
import random
from math import ceil
from functools import wraps
#=======================#
# Crossover decorators: #
#=======================#
def _check_weight(individual_method):
"""Checks if the weight is between 0 and 1 before running.
Exception may occur when using ga.adapt, which will catch
the erro... |
"""
Module Title: Regression Module
Source Path: modules/regression.py
Description:
The Regression Module contains the classes representing the Linear and Exponential regression
models used within this project. An instance of a LinearRegressionModel will contain the gradient
and the y-intercept of the best-fitting li... |
try:
from unittest2 import TestCase
except ImportError:
from unittest import TestCase # flake8: noqa
import mock
from pyramid.security import Authenticated
from daybed.backends import exceptions
from daybed.permissions import (
All, Any, DaybedAuthorizationPolicy,
invert_permissions_matrix, dict_set2... |
import os, sys
current_dir = os.path.dirname(os.path.realpath(__file__))
parent_dir = os.path.dirname(current_dir)
sys.path.append(parent_dir)
from math_utils import *
from debug_utils import *
# def EW_MGc(ar, ES, ES2, c):
# CV = math.sqrt(ES2 - ES**2)/ES
# return (1 + CV**2)/2 * EW_MMc(ar, ES, c)
def EW_MMc_wGam... |
import os
import sys
import argparse
import numpy as np
import pandas as pd
import torch as th
import torch.optim as optim
import torch.nn as nn
from tqdm import tqdm
from torch.utils.tensorboard import SummaryWriter
import utils
import defaults.EPIC_JPOSE as EPIC_JPOSE
from models.jpose import JPOSE
from datasets.... |
import pytest
from VulnerableBySeveritySplunk import (
VulnerableBySeveritySplunk,
Vulnerability,
VulnerabilityAlert,
Project,
)
import json
@pytest.fixture
def vuln():
"""Test data"""
with open("tests/fixtures/data/vulnerable_by_severity.json") as f:
return json.load(f)
def test_pro... |
#! /usr/bin/env python3
import argparse
import re
import subprocess
from xml.etree import ElementTree
from yaml import dump, safe_load
_PYTHON_VERSION_FILE = "lib/python/frugal/version.py"
_POM = "pom"
_POM_XML = "{0}/pom.xml"
_NS = {_POM: "http://maven.apache.org/POM/4.0.0"}
class LanguageBase(object):
"""La... |
import inspect
import torch
import itertools
import types
from typing import Union, Tuple, Optional
import geoopt.utils
from geoopt.manifolds.base import Manifold, ScalingInfo
import functools
__all__ = ["Scaled"]
def rescale_value(value, scaling, power):
return value * scaling ** power if power != 0 else value
... |
from socket import socket, AF_INET, SOCK_DGRAM
import time
SERVER_ADDR = '0.0.0.0'
SERVER_PORT = 5300
# Upsteam Address, use 114 DNS
UPSTREAM_ADDR = '172.16.31.10'
UPSTREAM_PORT = 53
# Duration to cleanup caches
CACHE_TTL = 1800
caches = []
# Query without EDNS
class SimplifiedQuery(object):
def __init__(self... |
import pandas as pd
import pymongo
import requests
from bs4 import BeautifulSoup
from splinter import Browser
from IPython.display import display_html
def init_browser():
executable_path = {'executable_path': '../../ChromeDriver/chromedriver.exe'}
return Browser('chrome', **executable_path, headless=F... |
import pygame
import math
from random import randint
import sys
class Branch():
def __init__(self, a, b, c, w):
self.start = a
self.end = b
self.weight = w
if c == "true":
self.angle = randint(2,20)
self.rand = True
elif c !="0":
self.angle = int(c)
self.rand = False
else:
self.angle = 4
... |
# (c) 2012-2014, <NAME> <<EMAIL>>
# (c) 2017 Ansible Project
# 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
import crypt
import multiprocessing
import random
import string
import sys
f... |
#!/usr/bin/env python
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Input, Dense, Embedding, Dot, Flatten, Concatenate, Dropout, Lambda, Subtract
from tensorflow.keras.initializers import Initializer, RandomNormal, Zeros, Ones
from tensorflow.keras.regularizers import l2, l1, l1_l2
fro... |
#!/usr/bin/env python3
import math
import sys
import click
import fiona
import joblib
import matplotlib.pyplot as plt
from multiprocessing import Pool as ThreadPool
from netCDF4 import Dataset
import numpy as np
import numpy.ma as ma
import pandas as pd
import rasterio
import projections.utils as utils
import pdb
... |
#!/usr/bin/env python
import argparse
import os
import readline
import sys
import subprocess
import shutil
from tempfile import NamedTemporaryFile
from termcolor import colored
from pygments import highlight
from pygments.lexers import DiffLexer
from pygments.formatters import TerminalFormatter
from collections im... |
import os
from matplotlib import pyplot as plt
import numpy as np
import photutils as pu
from astropy.wcs import WCS
from astropy.stats import sigma_clipped_stats
from astropy import table
from astropy.io import fits
import visualization as vis
def find_obj_center(filename, x=None, y=None, plot=True, fig_dir='./'):... |
from hyperopt import Trials, STATUS_OK, tpe
from keras.initializers import TruncatedNormal
from keras.utils import np_utils, to_categorical
from keras.layers import Dense, Activation, Dropout, Reshape
from keras.layers.normalization import BatchNormalization
from keras.models import Sequential, load_model
from keras.op... |
import torch
from torch import nn
from torch.nn import functional as F
EPS = 1e-10
def regular_control(n_control):
control = torch.linspace(-1, 1, n_control)
c1 = control.view(1, n_control).expand(n_control, -1).reshape(-1)
c2 = control.view(n_control, 1).expand(-1, n_control).reshape(-1)
... |
from typing import TYPE_CHECKING, Dict, List, Set, Union
if TYPE_CHECKING:
from pyppeteer.connection.cdpsession import CDPSession
from pyppeteer.jshandle import ElementHandle
class Accessibility:
def __init__(self, client: 'CDPSession'):
self._client = client
async def snapshot(self, interes... |
import torch
import torch.nn as nn
import torch.nn.functional as F
class GradientHarmonization(nn.Module):
def __init__(self, loss_N_grad_fn, disabled=False, momentum=.9, number_of_bins=30):
super().__init__()
self.exponential_moving_average = None
self.loss_N_grad_fn = loss_N_grad_fn
... |
#########
# Copyright (c) 2014 GigaSpaces Technologies Ltd. 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... |
"""Definition of Processor class."""
import logging
import traceback
import itertools
from typing import Iterable, Type, Dict, List
from pydantic import BaseModel, Extra
from pydantic.error_wrappers import ValidationError
from circuit_maintenance_parser.output import Maintenance
from circuit_maintenance_parser.data ... |
# -*- coding: utf-8 -*-
"""Top-level package for Copulas."""
__author__ = 'MIT Data To AI Lab'
__email__ = '<EMAIL>',
__version__ = '0.7.1.dev0'
import contextlib
import importlib
from copy import deepcopy
import numpy as np
import pandas as pd
EPSILON = np.finfo(np.float32).eps
class NotFittedError(Exception):
... |
# coding=utf-8
import os
import sys
# === import project path ===
curPath = os.path.abspath(os.path.dirname(__file__))
rootPath = os.path.split(curPath)[0]
sys.path.append(rootPath)
# ===========================
import base.default_excutable_argument as dea
import pandas as pd
from PIL import Image
import os... |
import numpy as np
from gcg.misc import schedules
from gcg.replay_pools.per_pool import PERPool
from gcg.data.logger import logger
class ProportionalPERPool(PERPool):
def __init__(self, env_spec, obs_history_len, N, size,
labeller=None, save_rollouts=False, save_rollouts_observations=True, save_... |
import argparse
import os
import torch
import torchvision
import torch.utils.data
from . import utils
from .logger import get_logger
from torchvision.datasets.folder import has_file_allowed_extension, default_loader, IMG_EXTENSIONS
dataset_list = ['mnist', 'fashion-mnist', 'cifar10', 'ImageNet', 'folder']
def add_ar... |
import numpy as np
import torch
from scipy.spatial.transform import Rotation as Rot
def get_camera_mat(fov=49.13, invert=True):
# fov = 2 * arctan( sensor / (2 * focal))
# focal = (sensor / 2) * 1 / (tan(0.5 * fov))
# in our case, sensor = 2 as pixels are in [-1, 1]
focal = 1. / np.tan(0.5 * fov * np... |
import abc
import json
from typing import Callable, Type, TypeVar, Generic, Any, Union
from amino import List, Either, __, Left, Eval, ADT, Right, Try, Path, Map, Lists
from amino.do import do, Do
from amino.boolean import false, true
from amino.json.decoder import decode_json_type
from ribosome.nvim.io.compute impor... |
import argparse
from python_codes.util.config import args
import warnings
warnings.filterwarnings("ignore")
from python_codes.util.util import *
from matplotlib import rcParams
rcParams['font.family'] = 'sans-serif'
rcParams['font.sans-serif'] = ['Arial','Roboto']
rcParams['savefig.dpi'] = 300
import matplotlib.pyplot ... |
import glob
import os
import numpy as np
import pandas as pd
from xml.etree import ElementTree
from ..generic.mapping_io import read_geo_image
def list_central_wavelength_re():
""" create dataframe with metadata about RapidEye
Returns
-------
df : datafram
metadata and general multispectral... |
# --------------------------------------------------------
# Compute metrics for detectors using ground-truth data
# Written by <NAME> (<EMAIL>), Version 20200321
# Based on pycocotools (https://github.com/cocodataset/cocoapi/)
# --------------------------------------------------------
import numpy as np
import... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union
from ... import _utilities, _tables
__a... |
import unittest
import os
import whisper
import time
import random
import mock
from carbonate.fill import fill_archives
def _average(ints_or_nones):
total = 0
count = 0
for i in ints_or_nones:
if i is not None:
total += i
count += 1
return total // count
class FillTe... |
"""
Support for Google Actions Smart Home Control.
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/google_assistant/
"""
import asyncio
import logging
from typing import Any, Dict # NOQA
from aiohttp.hdrs import AUTHORIZATION
from aiohttp.web import R... |
import numpy as np
from gym import spaces
from gym import Env
#from . import register_env
class PointEnv_SMM(Env):
def __init__(self,goal_prior=None,sample_goal = None,shaped_rewards=None,distance_threshold=None,init_object_pos_prior=None,terminate_upon_success=None,terminate_upon_failure=None,goal_radius=1,goal... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue May 12 20:10:00 2020
@author: thorius
"""
import os
import numpy as np
import logging
import pyaudio
import time
from VoiceActivate.tf_stream import StreamActivate
from VoiceControl.tf_stream import StreamControl
from play_video import PlayVideo
from ... |
"""Submit jobs to a cluster and poll for the result.
<NAME>
2019
"""
import inspect
from pathlib import Path
import re
import subprocess
import sys
import tempfile
import time
import uuid
SLURM_TEMPLATE = """#!/bin/sh
# SLURM directives
#
#SBATCH --job-name=alcyone-{uid}
#SBATCH --time=10:00:00
#SBATCH --tasks-per-... |
from datetime import datetime
from bs4 import BeautifulSoup
from slack_sdk import WebClient
from slack_sdk.errors import SlackApiError
from time import sleep
import urllib.request
import argparse
import config as config
PARSER = argparse.ArgumentParser()
PARSER.add_argument("--slack", help="print the avial... |
import numpy as np
import matplotlib.pyplot as plt
import random
import os
from sklearn.metrics import balanced_accuracy_score, f1_score
def train(env, agent, N, custom_reward=None, print_progress=True, seed=None):
"""
record every episode's reward, action accuracy and f1 over iteration.
:param env:
:... |
__copyright__ = """
Copyright 2019 <NAME>
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 o... |
# TensorFlow - Deep MNIST for Experts
# https://www.tensorflow.org/get_started/mnist/pros
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
# MNIST データセットを用意
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
# Nx784 の入力
x = tf.placeholder(tf.float32, shape=[None, 784])
#... |
"""
File: boggle.py
Name: <NAME>
----------------------------------------
This program plays the 4x4 boggle game.
This program recursively finds all the word that
more than four alphabets and terminates when input
string is not alphabet or input string is more than
one character.
If you correctly implement this progra... |
#!/usr/bin/python
# Copyright (c) 2018 Cohesity Inc
# Apache License Version 2.0
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from ansible.module_utils.basic import AnsibleModule
import json
import traceback
from ansible.module_utils.urls import open_url, urllib_error
try:
... |
"""
Dataset preparation and cleaning script
This script converts the dataset from the given format
(a lot of text files in 5 folders belonging to 5 classes)
into a CSV format such that every row has a cleaned text
and the class. The dataset is also divided into a train
and a test set.
The following things are done:... |
from unittest import TestCase
from seleniumwire.request import Request, Response
class RequestTest(TestCase):
def test_create_request(self):
request = self._create_request()
self.assertEqual('GET', request.method),
self.assertEqual('http://www.example.com/some/path/?foo=bar&hello=world&... |
"""
.. module:: MNISTCNN
:synopsis: A CNN model for MNIST
.. moduleauthor:: <NAME> <<EMAIL>>
"""
from collections import OrderedDict
import torch
from torch import nn, optim
from secml.ml.classifiers import CClassifierPyTorch
class Flatten(nn.Module):
def __init__(self):
super(Flatten, self).__init... |
# 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, software
# d... |
#!/usr/bin/python
#
# Copyright 2020 Google LLC
#
# 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... |
#!/usr/bin/env python3
import argparse
import os
import gtfparse
from sqlalchemy import Index
from sqlalchemy.engine import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.exc import NoResultFound
from setup_db import Gene, Transcript, Exon
def get_genome_annotations(gtf_handle, protein_coding... |
import sys
import random
import math
import numpy as np
from qlazy import QState
#
# custom gates
#
class MyQState(QState):
def swap(self,q0,q1):
self.cx(q0,q1).cx(q1,q0).cx(q0,q1)
return self
def hadamard(self,id=None):
for i in range(len(id)):
self.h(id[i])
... |
########################################################################
#
# Copyright (c) 2021, STEREOLABS.
#
# All rights reserved.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHA... |
import time
import numpy as np
import pxng
from pxng.keys import *
from fractal import Range2D
from fractal import py_create_fractal
from fractal.shader_fractal import ShaderFractal
from fractal.term_fractal import term_fractal
from fractal._fractal import create_fractal as rust_create_fractal
def handle_input(wind... |
import numpy as np
from queue import PriorityQueue
###############################
# General A* implementation #
###############################
class PathFindingError(Exception): pass
def a_star_search_forward_pass(start: int, goal: int, heuristic, adjacency, early_stopping : bool, maxits : int):
frontier = P... |
import discord
from discord.ext import commands
import youtube_dl
import os
import json
import time
SONG_LIST = []
SOLO_LIST = []
SOLO_KING = "insert king here"
LAST_WON = SOLO_KING
GAME_COUNT = 1
TOKEN = "insert here"
client = commands.Bot(command_prefix='~')
def get_info(url):
ydl_opts = {
... |
import multiprocessing
import queue
import threading
import json
from datetime import datetime
import enum
import logging
from sqlalchemy import MetaData, Table
from ..db.datamodel import db, app, project, portscanner, target, vulnLookupTable
from ..utils import Ports, PortStatus
class WorkerCommand(enum.Enum):
STO... |
"""
DROBaseWidget
-------------
"""
from qtpy.QtCore import Slot, Property
from qtpyvcp.plugins import getPlugin
from qtpyvcp.utilities.settings import getSetting
from qtpyvcp.widgets import VCPWidget
from qtpyvcp.utilities import logger
from qtpyvcp.utilities.info import Info
LOG = logger.getLogger(__name__)
INF... |
from __future__ import annotations
from typing import Tuple
from polynom.ecc import Scalar, zero, one
from polynom.utils import pad_scalars, trim_zeros
def evaluate(point: Scalar, *inputs: Polynomial) -> list[Scalar]:
return [input(point) for input in inputs]
def lagrange_interpolation(xy: list[Tuple(Scalar, Sc... |
from typing import List, Optional
import cv2
import numpy as np
from skimage.transform import resize
from wholeslidedata.annotation.structures import Point, Polygon
from wholeslidedata.samplers.utils import shift_coordinates
from wholeslidedata.image.wholeslideimage import WholeSlideImage
from wholeslidedata.samplers.... |
# -*- Mode: Python -*-
# GObject-Introspection - a framework for introspecting GObject libraries
# Copyright (C) 2010 Red Hat, Inc.
# Copyright (C) 2010 <NAME>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Softw... |
# <NAME> - 22 March 2018
# Student ID: G00364778
# GMIT 52167 Final Project
"""
The purpose of this python code is to perform three major functions on the iris dataset
* Read is the csv data from a text file and return it in a format for further processing
* Run some basic statistical calculations on the data... |
import uuid
from django.db.models import Case
from django.db.models import When
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import viewsets
from rest_framework.exceptions import ParseError
from rest_framework.response import Response
from rest_framework.serializers import Validati... |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import math
import types
import torch
import torch.optim
from . import FairseqOptimizer, register_optimizer
@register_optimizer('laprop')
... |
import pytest
def test_auto_register():
import torch
from nics_fix_pt import nn_fix as nnf
from nics_fix_pt import NAR as nnf_auto
torch.nn.Linear_another2 = torch.nn.Linear
class Linear_another(torch.nn.Linear): # a stub test case
pass
torch.nn.Linear_another = Linear_another
... |
import torch
from torch import optim
from torch import nn
import os
from collections import OrderedDict
from torchvision import datasets,transforms, models
def load_datasets(base_data_dir):
print ("Define training transforms and loading data...")
training_dir = os.path.join(base_data_dir, 'train')
va... |
# Copyright 2017 ProjectQ-Framework (www.projectq.ch)
#
# 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 app... |
import matplotlib.pyplot as plt
import matplotlib.colors as colors
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
def get_row(array, row):
return array[row, :]
def get_col(array, col):
return array[:, col]
if __name__ == "__main__":
with open("red_rf.field", 'rb') as f:
... |
# coding: utf-8
# Copyright 2018 <NAME>
# Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
import argparse
import numpy
import pytest
import torch
import espnet.lm.pytorch_backend.extlm as extlm_pytorch
from espnet.nets.pytorch_backend import e2e_asr
import espnet.nets.pytorch_backend.lm.default as lm_pyto... |
#!/usr/bin/python3
# <NAME>
import os
import logging
import argparse
import re
import time
import urllib
from selenium import webdriver
from reportlab.pdfgen import canvas
# logger
LOGGER='dumpbook118'
DEFAULT_WAIT_INTERVAL=2.5
def init_logging(verbose):
log = logging.getLogger(LOGGER)
ch = loggin... |
#!/usr/bin/env python
# -*- coding: utf-8
#
# CLI script to crop an image.
#
# Copyright (c) 2019 Polytechnique Montreal <www.neuro.polymtl.ca>
# Authors: <NAME>
#
# About the license: see the file LICENSE.TXT
import sys
import os
import argparse
from spinalcordtoolbox.cropping import ImageCropper, BoundingBox
from ... |
##
# Part of `MasterNodeMonitorBot`
#
# Copyright 2018 dustinface
#
# 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... |
#! /usr/bin/env python
"""
Do gather matches on contigs => taxonomy, and save to JSON
"""
import sys
import argparse
import os.path
import json
from collections import defaultdict
import screed
import sourmash
from sourmash.lca.command_index import load_taxonomy_assignments
from sourmash.lca import LCA_Database
from... |
import itertools
import numpy as np
from net.utils.func_utils import weighted_focal_loss_for_cross_entropy, weighted_smooth_l1
# ------------------------------ bbox regression -------------------------------------
# "UnitBox: An Advanced Object Detection Network" - <NAME>, <NAME>, <NAME>, <NAME>, <NAME>
# https://ar... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Read/write wave audio files to/from lists of native Python types.
The library is currently limited to PCM (integer) formats but supports arbitrary
precision, including 16-, 24-, 32-, and 64-bit samples.
Usage: reading wave files
f = wavfile.open(file, 'r')
where... |
# -*- coding: utf-8 -*-
from base64 import b64encode
from django import VERSION
from django.utils import six
from django.test import TestCase
from pyquery.pyquery import PyQuery
from server.forms.client_validation import SubscribeForm as ClientValidatedForm
from server.forms.combined_validation import SubscribeForm as ... |
""" Find the connected regions of a volumetric mesh.
This script contains methods that find the connected regions of a volumetric mesh
This is done by assembling an adjacency matrix of the nodal-connectivity,
constructing a graph from this matrix, and then finding the 'connected components'
of the graph.
Parameters
... |
from collections import OrderedDict
import json
import logging
import os
try:
import urllib.parse as urlparse
except ImportError:
import urlparse
from humanfriendly import format_size, parse_size
import requests
MAX_FILE_DEFAULT = parse_size('128m')
OH_BASE_URL = os.getenv('OHAPI_OH_BASE_URL', 'https://www.o... |
import abc
import logging
import threading
from queue import Empty, Full
from typing import Any, Callable, Generic, List, NamedTuple, Optional, Tuple, TypeVar, Union
logger = logging.getLogger(__name__)
Empty = Empty
Full = Full
QItem = TypeVar("QItem")
class Queue(abc.ABC, Generic[QItem]):
@property
def n... |
# ******************************************************************************
# Copyright 2017-2020 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apa... |
import socket
import time
import io
import sys
import seaborn as sns
import numpy as np
import pandas as pd
import sklearn
import matplotlib.pyplot as plt
sns.set_style('whitegrid')
print(np.__version__)
print(pd.__version__)
print(sys.version)
print(sklearn.__version__)
from sklearn.svm import SVC
from sklearn.model_... |
"""
detect circle
"""
import os,sys
import time
import traceback
import socket
import gevent
import json
import toml
import numpy as np
import cv2
from multi_logging import get_logger
import cvlib
from config import get_config
#conf_fn = os.sep.join(
# [os.path.split(os.path.realpath(__file__))[0], "conf... |
# Lint as: python3
# Copyright 2013 The CARFAC Authors. All Rights Reserved.
#
# This file is part of an implementation of Lyon's cochlear model:
# "Cascade of Asymmetric Resonators with Fast-Acting Compression"
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in co... |
import json
import logging
import asyncio
import aiohttp
from aiohttp import client_exceptions
from asgiref.sync import sync_to_async
from channels.layers import get_channel_layer
from django.conf import settings
from django.apps import apps
from django.core.serializers.json import DjangoJSONEncoder
from awx.main.a... |
import time
import csv
import json
import os
from flask import Flask, request, abort, jsonify
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
APP_ROOT = os.path.realp... |
import argparse, librosa
import numpy as np
import torch
import torch.nn as nn
import torchaudio
from model import Tacotron as Tacotron
from collate_fn import collate_fn
from dataset import *
from util import *
from griffin_lim import GLA
from audio_processing import *
parser = argparse.ArgumentParser(description='t... |
import re
import win32process
import win32gui
import win32com
from win32com.client import GetObject
import win32api, win32con
def move_mouse_to(x,y,with_click=True):
win32api.SetCursorPos((x,y))
if with_click:
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,x,y,0,0)
win32api.mouse_event(win32con.... |
#!/usr/bin/env python2.7
# Copyright 2016, VIXL authors
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this l... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: <NAME> (<EMAIL>)
import torch
import torch.nn as nn
import torch.nn.functional as F
from .layers import Conv1x1, Conv3x3, CRPBlock, upsample
from .layers import GraphConvolution, GCN
import math
import scipy.sparse as sp
import numpy as np
import networkx as nx
... |
"""
Functions for applying wavelet analyses to NeuroPace data.
Created by: <NAME>
Updated: 2019/03/19
"""
import os
os.environ['OMP_NUM_THREADS'] = '1'
os.environ['MKL_NUM_THREADS'] = '1'
os.environ['OPENBLAS_NUM_THREADS'] = '1'
import warnings
warnings.filterwarnings('ignore')
exec(open('__init__.py').read())
rs_p... |
from envs.One_bus_env import PowerSys_1bus
from nets.policy_net import PolicyNetwork
from nets.vertex_policy_net import VertexPolicyNetwork
from nets.RCI_policy_net import RCIPolicyNetwork
from nets.value_net import ValueNetwork
from utils.replay_buffer import ReplayBuffer
from algos.ddpy import DDPG
import numpy as n... |
import tensorflow as tf
import numpy as np
import seaborn as sns; sns.set_style('whitegrid')
import os
from tqdm import tqdm
from plot_utils import *
from tensorflow.examples.tutorials.mnist import input_data
from tensorflow.contrib.layers import stack, fully_connected as fc, flatten
from tensorflow.python.ops.distribu... |
#!/usr/bin/env python
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "L... |
import argparse
import socket
import sys
import signal
from toolset.benchmark.benchmarker import Benchmarker
from toolset.utils.scaffolding import Scaffolding
from toolset.utils import cleaner
from toolset.utils.results_helper import Results
from toolset.utils.benchmark_config import BenchmarkConfig
from toolset.utils ... |
#!/usr/bin/env python3
import setupLibPaths
import sys
import argparse
import rogue
import rogue.hardware.axi
import rogue.interfaces.stream
import rogue.interfaces.memory
import pyrogue as pr
import pyrogue.gui
import pyrogue.utilities.prbs
import pyrogue.interfaces.simulation
import axipcie as pcie
import surf.ax... |
import unittest
from urllib.parse import urlparse
import time
from .domain import *
from .scheduler import *
class DomainTest(unittest.TestCase):
def test_domain(self):
domain = Domain("xpto.com", 10)
self.assertTrue(domain.is_accessible(),
"Ao iniciar um servidor, ele dev... |
#!/usr/bin/env python
# coding: utf-8
# In[1]:
"""
CONTENT-BASED RECOMMENDER
Recommendation Systems 2020.2
PPGCC / UFMG
Author: <NAME> (2020656790)
E-mail: <EMAIL>
"""
import pandas as pd
import numpy as np
import argparse, ast
DICT, TEXT = 0, 1
parser = argparse.ArgumentParser(description='Trabalho SR | Clariss... |
# -*- coding: utf-8 -*-
# Copyright (c) 2019, Frappe Technologies and contributors
# License: MIT. See LICENSE
import ast
from types import FunctionType, MethodType, ModuleType
from typing import Dict, List
import frappe
from frappe.model.document import Document
from frappe.utils.safe_exec import get_safe_globals, s... |
# Copyright 2013: Mirantis 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 b... |
import torch.nn as nn
import numpy as np
import torch
# from nnunet.training.loss_functions.TopK_loss import TopKLoss
# from nnunet.utilities.nd_softmax import softmax_helper
# from nnunet.training.loss_functions.ND_Crossentropy import CrossentropyND
# from nnunet.utilities.tensor_utilities import sum_tensor
from torc... |
import os
import math
import onnx
import numpy as np
import torch
import psutil
import pytest
import torch.nn as nn
import onnxruntime as ort
from sklearn.ensemble import RandomForestClassifier
import bentoml
import bentoml.models
from bentoml.exceptions import BentoMLException
from tests.utils.helpers import assert_... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.