text stringlengths 957 885k |
|---|
<reponame>DocOtak/gsw-xarray
_names = {
"CT_first_derivatives": ("CT_SA", "CT_pt"),
"CT_first_derivatives_wrt_t_exact": ("CT_SA_wrt_t", "CT_T_wrt_t", "CT_P_wrt_t"),
"CT_freezing": "CT_freezing",
"CT_freezing_first_derivatives": ("CT_freezing_SA", "CT_freezing_P"),
"CT_freezing_first_derivatives_poly... |
import os
from deepneuro.outputs.inference import ModelPatchesInference
from deepneuro.preprocessing.preprocessor import DICOMConverter
from deepneuro.preprocessing.signal import N4BiasCorrection, ZeroMeanNormalization
from deepneuro.preprocessing.transform import Coregister
from deepneuro.preprocessing.skullstrip imp... |
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
import logging
import warnings
import random
import os
import torch
import numpy as np
from tqdm import tqdm
from torch.utils.data import DataLoader
from torchvision import datasets, transforms
from torch.utils.tensorboard import SummaryWriter
from config import get_conf... |
import numpy as np
import cv2
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml')
cap = cv2.VideoCapture(0)
trnImages = []
trnLabels = []
trnImages.append(cv2.cvtColor(cv2.imread("detectedFace0.jpg"), cv2.COLOR_BGR2GRAY))
... |
<gh_stars>100-1000
import asyncio
import base64
from collections import namedtuple
from collections.abc import AsyncIterator
import time
from urllib.parse import quote
from async_timeout import timeout
import grpc
from sonora import protocol
_HandlerCallDetails = namedtuple(
"_HandlerCallDetails", ("method", "in... |
# xmlutils.py
#
# Copyright 2013 Mandiant Corporation.
# Licensed under the Apache 2.0 license. Developed for Mandiant by William
# Gibb and Seth.
#
# Mandiant licenses this file to you under the Apache License, Version
# 2.0 (the "License"); you may not use this file except in compliance with the
# License. You m... |
<gh_stars>10-100
import config
import numpy as np
import data_utils
BATCH_SIZE = config.BATCH_SIZE
SEQ_IN = config.SEQ_IN
SEQ_OUT = config.SEQ_OUT
IN_DIM = config.IN_DIM
def convert_velocity(data):
velocity = data[1:] - data[:-1]
return velocity
def get_batch(data, one_hot, actions):
"""Get a random batch of da... |
import numpy as np
from collections import defaultdict
from sklearn.base import TransformerMixin, BaseEstimator
from sklearn.decomposition import PCA
from sklearn.ensemble import BaseEnsemble
class LocalDecisionStump:
"""
An object that implements a callable local decision stump function and that also includ... |
from django.db import models
# Create your models here.
class ShareholderInfo(models.Model):
# BE_PRESENT_CHOICE = (
# (0,'否'),
# (1,'是')
# )
# year = models.CharField(max_length=4, verbose_name="会议年份")
# xh = models.SmallIntegerField()
# cx = models.SmallIntegerField(choices=BE... |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2015-2016 Hewlett Packard Enterprise Development LP
#
# 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
... |
<reponame>PavanKishore21/probability<filename>tensorflow_probability/python/bijectors/scale_matvec_lu.py<gh_stars>1-10
# Copyright 2018 The TensorFlow Probability 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 obt... |
<reponame>exebixel/oneparams
#!/usr/bin/python
import click
import sys
import pandas as pd
from oneparams.reset import pw_reset
from oneparams.api.login import login
from oneparams.excel.card import cards
from oneparams.excel.colaborador import colaborador
from oneparams.excel.comissao import Comissao
from oneparams.... |
<reponame>kzinmr/pyknp-extend
#-*- encoding: utf-8 -*-
import re
import sys
import unittest
from pyknp import MList
from pyknp import Morpheme
from pyknp import Features
class Tag(object):
"""
格解析の単位となるタグ(基本句)の各種情報を保持するオブジェクト.
"""
def __init__(self, spec, tag_id=0, newstyle=False):
self._mrp... |
<gh_stars>1-10
#!/usr/bin/env python
import atexit
import logging
import os
import random
import signal
import subprocess
import tempfile
import time
import urllib
from streamcorpus_pipeline.stages import BatchTransform
logger = logging.getLogger(__name__)
# TODO: recast as an IncrementalTransform with persist... |
<reponame>easyopsapis/easyops-api-python
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: remove.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import mess... |
<gh_stars>0
# MIT License
#
# Copyright (c) 2021 <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, modif... |
import numpy as np
import matplotlib.pyplot as plt
# Physical Constants
m = 0.1 #kg
Ixx = 0.00062 #kg-m^2
Iyy = 0.00113 #kg-m^2
Izz = 0.9*(Ixx + Iyy) #kg-m^2 (Assume nearly flat object, z=0)
dx = 0.114 #m
dy = 0.0825 #m
g = 9.81 #m/s/s
DTR = 1/57.3; RTD = 57.3
# Simulation time and model parame... |
<gh_stars>1-10
# Copyright: <NAME>, 2021
import torch
import torch.nn as nn
from torch.nn.utils.rnn import pack_padded_sequence
from torch.nn.functional import softmax
class RNN(torch.nn.Module):
def __init__(self, rnn_config):
super(RNN, self).__init__()
self.embedding_layer = nn.Embedding(
... |
# import Asclepius dependencies
from pandas.core.frame import DataFrame
from asclepius.instelling import GGZ, ZKH
from asclepius.medewerker import Medewerker
from asclepius.portaaldriver import PortaalDriver
from asclepius.testen import TestFuncties, Verklaren
# import other dependencies
from typing import Union
from ... |
<reponame>SuLab/myvariant.info
from .clinvar_xml_parser import load_data as load_common
import biothings.dataload.uploader as uploader
from dataload.uploader import SnpeffPostUpdateUploader
SRC_META = {
"url" : "https://www.ncbi.nlm.nih.gov/clinvar/",
"license_url" : "https://www.ncbi.nlm.nih.gov/clin... |
<gh_stars>1-10
import numpy as np
import math
import os
import sys
sys.path.append("../..")
from PARAMETERS import *
from subvision.utils import CameraFacing
class Watchout:
'''
Calculate the distance to an object from bounding box coordinates, camera information, and expected object sizes in meters.
Imp... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# controller.py
#
# Home to the MyController class, used for:
# - Interacting directly with hardware: LEDs, PIR sensor
# - Interacting directly with the SpaceAuth API and the datalogger script
# - Checking IDs
# - Granting/denying access
import time
import sys
import os
... |
<gh_stars>0
"""Mock service for testing Service integration
A JupyterHub service running a basic HTTP server.
Used by the `mockservice` fixtures found in `conftest.py` file.
Handlers and their purpose include:
- EchoHandler: echoing proxied URLs back
- EnvHandler: retrieving service's environment variables
- APIHan... |
<filename>experiments/mainFT.py<gh_stars>0
import sys, argparse,os,glob
sys.path.insert(0, '../')
# import geomloss
from pytorch_lightning import Trainer
from pytorch_lightning.loggers import WandbLogger
from pytorch_lightning.callbacks import EarlyStopping, ModelCheckpoint
from dataProcessing.dataModule import Sing... |
# -*- coding: UTF8 -*-
"""
TODO:
- Fix arguments of find_contact()
- Implement PING protocol
"""
import socket
import random
import logging
from unittest import mock
from typing import Tuple, Optional
from json.decoder import JSONDecodeError
from .node import Node
from .config import Config
fr... |
<gh_stars>0
from django.shortcuts import render, redirect
from django.http import HttpResponse, Http404, HttpResponseRedirect
from django.contrib.auth.decorators import login_required
from django.core.exceptions import ObjectDoesNotExist
from .models import neighbourhood, healthservices, Business, Health, Authorities, ... |
# coding: utf-8
from __future__ import absolute_import
from datetime import date, datetime # noqa: F401
from typing import List, Dict # noqa: F401
from swagger_server.models.base_model_ import Model
from swagger_server import util
class NewsElement(Model):
"""NOTE: This class is auto generated by the swagger... |
import numpy as np
import matplotlib.pyplot as plt
import random
class GaussianBandit:
def __init__(self):
self._arm_means = np.random.uniform(0., 1., 10) # Sample some means
self.n_arms = len(self._arm_means)
self.rewards = []
self.total_played = 0
def reset(self):
s... |
import os, sys
sys.path.append("..")
from lookup import Lookup
def test_lookup (lookup, text = "A test."):
print(lookup)
print("Testing with: [{}]".format(text))
id_of_bos = lookup.convert_tokens_to_ids(lookup.bos_token)
id_of_eos = lookup.convert_tokens_to_ids(lookup.eos_token)
id_of_pad... |
<gh_stars>0
import numpy as np
class GrowingMat(object):
def __init__(self, shape, capacity, grow_factor=4):
self.data = np.zeros(capacity)
self.shape = shape
self.capacity = capacity
self.grow_factor = grow_factor
def expand(self, cols=None, rows=None, block=None):
i... |
<filename>awsscripts/sketches/emr.py
from typing import Dict, Any, Optional, List
from awsscripts.ec2.ec2 import ec2_instances
from awsscripts.emr.emr import EMR
from awsscripts.sketches.sketchitem import SketchItem
class EmrSketchItem(SketchItem):
def has_configuration(self, name: str) -> bool:
"""
... |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
import logging
import numpy.testing as npt
from reagent.core.parameters import ProblemDomain
from reagent.gym.envs import Gym
from reagent.gym.envs.wrappers.simple_minigrid import SimpleObsWrapper
from reagent.gym.utils impo... |
<filename>src/cli.py<gh_stars>0
#!/usr/bin/env python3
# coding: utf8
import sys
import argparse
import requests
import response_parser from ResponseParser
import hatena_photo_life_rss from HatenaPhotoLife
import wsse from WSSE
class CLI:
def __init__(self):
self.VERSION = '0.0.1'
def parse():
p... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
from psychopy.visual import Window, TextStim
from psychopy.core import wait, Clock, quit
from psychopy.event import clearEvents, waitKeys, Mouse
from psychopy.gui import Dlg
from time import... |
import requests
import time
from bs4 import BeautifulSoup
headers = {
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36',
}
def proceed(url, retry_time = 0):
"""
use link in proceed tag if whole article is not available
... |
<gh_stars>0
# type: ignore
import random
from django.test import TestCase
from memrise.core.domains.entities import (
CourseEntity,
LevelEntity,
WordEntity,
)
from memrise.core.use_cases.dashboard import DashboardCourseContainer
class TestWordEntity(TestCase):
def test_entity(self):
word_id... |
<reponame>dcdanko/capalyzer
import math
import pandas as pd
from scipy.stats import gmean, entropy
from numpy.linalg import norm
from random import random, sample
import numpy as np
MIL = 1000 * 1000
# ALPHA Diversity`
def shannon_entropy(row, rarefy=0):
"""Return the shannon entropy of an iterable.
Sha... |
#!/usr/bin/env python
from color import Color, ColorHSV
from LPD8806 import LPD8806
from WS2801 import WS2801
#Not all LPD8806 strands are created equal.
#Some, like Adafruit's use GRB order and the other common order is GRB
#Library defaults to GRB but you can call strand.setChannelOrder(ChannelOrder)
#to set the ord... |
from django.shortcuts import render, redirect
from . import models, forms
from utils.utils import hash_code, make_confirm_email
from django.conf import settings
from send_email import send_email
import datetime
def index(request):
if not request.session.get("is_login", None):
return redirect("/login/")
... |
<filename>notebookjs/_display.py
from IPython.core.display import display, HTML, Javascript
from string import Template, ascii_uppercase
import pkg_resources
import random
import re
import json
from ._comm import setup_comm_api
def id_generator(size=15):
"""Helper function to generate random div ids."""
chars ... |
import warnings
import inspect
import matplotlib.pyplot as plt
import IPython.display
import numpy as np
from cued_sf2_lab.familiarisation import load_mat_img, plot_image
from cued_sf2_lab.laplacian_pyramid import quantise
from cued_sf2_lab import laplacian_pyramid
import warnings
import inspect
import matplotlib.pyplo... |
<gh_stars>0
"""
Inference
---------
Module description
"""
import warnings
from abc import ABC, abstractmethod
from collections.abc import Iterable
import chainer
import chainer.functions as F
import numpy as np
from tqdm import tqdm
from brancher.optimizers import ProbabilisticOptimizer
from brancher.variables impor... |
import mysql as mysql
import mysql.connector
import tkinter as tk
from tkinter import *
from tkinter import ttk, messagebox
import pandas as pd
import matplotlib.pyplot as plt
class sql:
def __init__(self):
pass
def insert(self,name,phone,email,question,answer,password):
mydb = mysql.... |
<gh_stars>0
import os ,datetime
os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
import numpy as np
import pandas as pd
import tensorflow as tf
from tensorflow.keras.models import *
from tensorflow.keras.layers import *
import matplotlib.pyplot as plt
batch_size = 32
seq_len = 49
d_k = 256
d_v = 256
n_heads = 12
ff_dim = ... |
<filename>test/management_interface_integration_tests.py
# Copyright PA Knowledge Ltd 2021
# For licence terms see LICENCE.md file
import os
import unittest
import subprocess
import requests
import json
import threading
from test_helpers import TestHelpers
from Emulator import launch_management_interface
from nose.pl... |
<reponame>jspeerless/citrine-python
"""A collection of FileLink objects."""
import mimetypes
import os
from enum import Enum
from logging import getLogger
from typing import Iterable, Optional, Tuple, Union, List, Dict
from uuid import UUID
import requests
from boto3 import client as boto3_client
from boto3.session im... |
<filename>venv/lib/python3.8/site-packages/azureml/core/compute/compute.py<gh_stars>0
# ---------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# ---------------------------------------------------------
"""Contains the abstract parent and configuration c... |
import plotly.graph_objects as go
from plotly.subplots import make_subplots
import numpy as np
import pandas as pd
import math
from static_data import ARR_ranges, on_plot_shown_label,fig_size,color_schemes,themes
from preprocess_util import *
from plot_func.plot_util_multi_method import *
from plot_func.multi_method_p... |
<reponame>aleksas/remap<gh_stars>1-10
from sys import path
path.append('..')
from unittest import TestCase, main
from re_map import Processor
class MatchingGroupTestCase(TestCase):
'''
Tests perfect matching match group replacements.
'''
def test_matching_1(self):
text = ' BBB AAA AAA BBB '
... |
<filename>bin/commonSubroutines/drawFigure/drawFigure_parallel1tiled.py
##########################################################################
# Copyright 2017, <NAME> (<EMAIL>) #
# #
# This file is part of CCseqBasic5 . ... |
## FC Newtork
class FCNet:
def __init__(self):
from keras.models import Sequential
from keras.layers import Cropping2D, Lambda, Flatten, Dense
from keras import optimizers
from keras.callbacks import ModelCheckpoint
self.model = Sequential()
# Input layer
... |
'''
These tests are inspired by and use code from the tests made by cs540-testers
for the Fall 2020 semester
Their version can be found here: https://github.com/cs540-testers/hw5-tester/
'''
__maintainer__ = 'CS540-testers-SP21'
__author__ = ['<NAME>']
__credits__ = ['<NAME>', '<NAME>', '<NAME>', '<NAME>']
__version_... |
<gh_stars>0
import unittest
import numpy as np
import simulator
import models
import estimators
class TestFloorPlan(unittest.TestCase):
def test_basic_u(self):
np.random.seed(401)
z_ref = -1
width = 10
length = 10
# planes
x_planes = []
x_offsets = np.... |
# Copyright (c) 2021 PaddlePaddle 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 applic... |
# Copyright (C) 2006-2011, University of Maryland
#
# 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,... |
import itertools
import re
from typing import Dict
class CalcParseError(Exception):
pass
class EvaluateError(Exception):
pass
class UnknownOperatorError(Exception):
pass
def add(a, b):
return a + b
def sub(a, b):
return a - b
def mul(a, b):
return a * b
... |
import warnings as test_warnings
from datetime import datetime, timedelta
from http import HTTPStatus
from json.decoder import JSONDecodeError
from unittest.mock import MagicMock, call, patch
import pytest
import requests
from rotkehlchen.accounting.structures.balance import Balance
from rotkehlchen.assets.converters... |
# AUTOGENERATED! DO NOT EDIT! File to edit: 03_dataset.ipynb (unless otherwise specified).
__all__ = ['MovieDataset', 'Tokenize', 'RandomResizeCrop', 'ToTensor', 'NormalizeStandardize', 'Compose']
# Internal Cell
from torch.utils.data import Dataset
from torchvision import transforms
from transformers import DistilBe... |
<filename>pr0ntools/layer/parser.py
from pr0ntools.layer.layer import *
from pr0ntools.layer.polygon import *
class LayerSVGParser:
@staticmethod
def parse(layer, file_name):
parser = LayerSVGParser()
parser.layer = layer
parser.file_name = file_name
parser.do_parse()
def process_transform(self, transform)... |
# Copyright (c) 2020, Huawei Technologies.All rights reserved.
#
# Licensed under the BSD 3-Clause License (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://opensource.org/licenses/BSD-3-Clause
#
# Unless required by applicable law... |
"""Contains the Spectrum class."""
import numpy as np
from darkhistory import utilities as utils
from darkhistory.spec.spectools import get_bin_bound
from darkhistory.spec.spectools import get_log_bin_width
from darkhistory.spec.spectools import rebin_N_arr
import matplotlib.pyplot as plt
import warnings
from scipy i... |
<gh_stars>0
# For handling debug output
import logging as log
from scipy.optimize import shgo
import numpy as np
class EffortAllocation:
def __init__(self, model, covariate_data, allocation_type, *args):
"""
*args will either be budget (if allocation 1) or failures (if allocation 2)
... |
from app.model.bukuModel import Buku
from app.model.anggotaModel import Anggota
from app.model.transaksiModel import Transaksi
from app.utility import *
from datetime import datetime, timedelta
import pyfiglet
def transaksiMenu(idUser, namaUser):
print(pyfiglet.figlet_format("E-LIB") + "===========================")
... |
# 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, overload
from ... import _utilities
fro... |
<reponame>jordyantunes/Imagine
import threading
from collections import deque
import numpy as np
import time
from mpi4py import MPI
class ReplayBuffer:
def __init__(self, buffer_shapes, size_in_transitions, T, sample_transitions, goal_sampler, reward_function):
"""Creates a replay buffer.
Args:
... |
from pynwb.misc import AnnotationSeries
from pynwb.misc import TimeSeries
import pandas as pd
import numpy as np
import scipy
import os
# <NAME> 2021
def load_templates_optophysiology(stimuli_mat_file):
# This function loads a mat file containing a structure with ALL the possible stimuli templates
... |
<gh_stars>1-10
import numpy as np
from pandas import (
Categorical,
CategoricalIndex,
Index,
Interval,
)
import pandas._testing as tm
class TestReindex:
def test_reindex_list_non_unique(self):
# GH#11586
ci = CategoricalIndex(["a", "b", "c", "a"])
with tm.assert_produces_w... |
from __future__ import unicode_literals
import nose
from reviewboard.hostingsvcs.tests.testcases import ServiceTests
from reviewboard.scmtools.models import Repository, Tool
class AssemblaTests(ServiceTests):
"""Unit tests for the Assembla hosting service."""
service_name = 'assembla'
fixtures = ['test... |
<filename>test/test_trainer.py
from unittest import TestCase, main as unittest_main, mock
import numpy as np
import torch
import torch.nn as nn
from experiments.experiment_histories import calc_hist_length_per_net
from training.trainer import TrainerAdam
def generate_single_layer_net():
""" Setup a neural netwo... |
# (C) Copyright 2005-2021 Enthought, Inc., Austin, TX
# All rights reserved.
#
# This software is provided without warranty under the terms of the BSD
# license included in LICENSE.txt and may be redistributed only under
# the conditions described in the aforementioned license. The license
# is also available online at... |
#!/usr/bin/python
import urllib2
import json, csv
import subprocess
import sys
import platform
import getopt
import re
all_flag = False
download_flag = False
filename=None
events=[]
try:
opts, args = getopt.getopt(sys.argv[1:],'a,f:,d',['all','file=','download'])
for o, a in opts:
if o in ('-a','--all... |
import sys
bin16 = lambda x : ''.join(reversed( [str((x >> i) & 1) for i in range(16)] ) )
def print_comp_error(ins,data,line):
print(f"Compilation Error! Intruction {ins} has wrong data: {data} Line: {line}")
return
def decode_instr(instruction, data, instruction_line):
output = 0b0
if instr == 'JMP':
outpu... |
<filename>tests/test_scm_manager.py<gh_stars>10-100
#!/usr/bin/env python
# -*- coding: utf-8 -*-
###############################################################################
# The MIT License
#
# Copyright (c) 2016 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this so... |
# # Imports
from timeit import default_timer as timer
import numpy as np
import pyopencl as cl
import handybeam.tx_array
# # Class
class RectPropMixin():
"""This is a mixin class for the compiled OpenCL kernel _hbk_rect_propagator. It assigns
the compiled OpenCL kernel to this Python class which can then be... |
import asyncore
import matplotlib.pyplot as plt
import zlib,socket
import numpy as np
import MFSKDemodulator, DePacketizer, MFSKSymbolDecoder, time, logging, sys
from scipy.io import wavfile
import MFSKModulator,Packetizer
import sounddevice as sd
import soundfile as sf
from scipy.io import wavfile
from thread import... |
<filename>precipitation_nowcasting/Fugaku/resnet_channels_hvd.py
# coding: utf-8
import os,glob,re
import numpy as np
import tensorflow as tf
from numpy.random import randint,choice
from metrics import *
from multiprocessing import Pool
import itertools
os.environ['HDF5_USE_FILE_LOCKING'] = 'FALSE'
folder="data3d... |
import logging
from typing import TYPE_CHECKING, Optional
import numpy as np
from .base import BaseCallback
if TYPE_CHECKING:
from ..base import BaseTuner
class EarlyStopping(BaseCallback):
"""
Callback to stop training when a monitored metric has stopped improving.
A `model.fit()` training loop wi... |
<filename>IVOS_main_DAVIS.py
from davisinteractive.session import DavisInteractiveSession
from davisinteractive import utils as interactive_utils
from davisinteractive.dataset import Davis
from davisinteractive.metrics import batched_jaccard, batched_f_measure
from libs import custom_transforms as tr
from datasets_tor... |
import os
import time
from datetime import datetime
import numpy as np
import numpy.random as npr
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import tensorflow as tf
print(tf.__version__)
from tensorflow.python.client import device_lib
device_lib.list_local_devices()
from tensorflow.contr... |
"""
Nonconforming Group Graphical Lasso experiment
===================================================
Example script for Group Graphical Lasso with non-conforming dimension, i.e. some variables exist in some instances but not in all.
We generate one underlying precision matrix and then drop one block of variables in ... |
<reponame>anuragpeshne/DRL_collab
import numpy as np
import random
import copy
from collections import namedtuple, deque
from model import Actor, Critic
import torch
import torch.nn.functional as F
import torch.optim as optim
BUFFER_SIZE = int(1e6) # replay buffer size
BATCH_SIZE = 128 # minibatch size
GAMMA... |
<gh_stars>1000+
# Copyright 2018 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 appl... |
import unittest
from mock import Mock, call
import photo
import json
from StringIO import StringIO
import requests
from download import FlickrApiDownloader
class ThrowsTwice:
def __init__(self, successful_response):
self.successful_response = successful_response
self.count = 0
def get(self, ur... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# pylint: disable-msg=E1103
import collections
import functools
import os
import os.path
import cPickle as pickle
import fcntl
import hashlib
from itertools import ifilterfalse
from heapq import nsmallest
from operator import itemgetter
persistent_cache_directory = '~... |
import errno
import os
from functools import reduce
import numpy as np
import torch
from torch.utils.data import DataLoader
from torchvision.datasets import MNIST
from pyro.contrib.examples.util import get_data_directory
# This file contains utilities for caching, transforming and splitting MNIST data
# efficiently.... |
# This code is part of Qiskit.
#
# (C) Copyright IBM 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative wo... |
import hashlib
try:
import cPickle as pickle
except:
import pickle
import logging as _logging
import zlib
import time
import gc
import cloudstorage as gcs
from google.appengine.ext import ndb
from google.appengine.api import app_identity
__author__ = 'fernando'
CACHE_TIMEOUT = 86400*7
TEXTCHARS = ''.join(ma... |
<filename>pyeffects/Try.py
# -*- coding: utf-8 -*-
"""
pyeffects.Try
~~~~~~~~~~~~----
This module implements the Try, Success, and Faiure classes.
"""
from typing import Callable, List, Type, TypeVar, Union
from .Monad import Monad
A = TypeVar('A', covariant=True)
B = TypeVar('B')
class Try(Monad[A]):
@staticm... |
<reponame>KhanJr/Generative-Adversarial-Networks-COMPUTER-VISION
class helpyou:
"""
PreRequisite : Knowlege of Python (Basic[class, modules, function]), Pytorch, Neural Network, Activation Function.
Installation : pytorch(CUDA 10.2), torchvision, pillow, mpi4py, numpy.
To Train and Get Generated Images Run desi... |
<filename>pliers/tests/test_stims.py
from .utils import get_test_data_path
from pliers.stimuli import (VideoStim, VideoFrameStim, ComplexTextStim,
AudioStim, ImageStim, CompoundStim,
TranscribedAudioCompoundStim,
TextStim)
from pliers.s... |
<reponame>Hybrid-Cloud/birdie-dashboard
# Copyright (c) 2017 Huawei, 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
#
# ... |
import numpy as np
from .dist_func import get_distance_L2_pbc
from numba import njit
from .projection_func import *
# Programmer: <NAME>
# Date: 4.29.2021
def get_comp_perimeter(width=200.,height=200.):
'''returns project_point_2D
Obeys periodic boundary conditions on a width-x-height square domain.
retur... |
import unittest
from configparser import RawConfigParser
from io import StringIO
from typing import Dict, List, Union
from imperfect import ConfigFile
from parameterized import parameterized
from dowsing.setuptools.types import (
BoolWriter,
DictWriter,
ListCommaWriter,
ListCommaWriterCompat,
List... |
<gh_stars>10-100
import copy
import itertools
import operator
import sqlite3
# All functions in this file written by <NAME> for TALON, and
# adapted to interface with TALON dbs
# Converts input to string that can be used for IN database query
def format_for_in(l):
if type(l) is tuple:
l = list(l)
if type(l) is st... |
import osmnx as ox
import networkx as nx
import pandas as pd
import geopandas as gpd
from tqdm import tqdm
from shapely.geometry import shape, Polygon, Point
import warnings
warnings.filterwarnings(action='ignore', message='Mean of empty slice')
import numpy as np
def bikeability(place, scale = 'city',data = Fals... |
import math
import torch
from torch.optim.optimizer import Optimizer
from torch.optim.sgd import SGD
import numpy as np
class Neumann(Optimizer):
"""
Documentation about the algorithm
"""
def __init__(self, params , lr=1e-3, eps = 1e-8, alpha = 1e-7, beta = 1e-5, gamma = 0.9, momentum = 1, sgd_steps ... |
<gh_stars>0
import nipype.pipeline.engine as pe
from nipype.interfaces import ants
from nipype.interfaces import fsl
import nipype.interfaces.io as nio
import numpy as np
import os
project_folder = '/home/gdholla1/projects/bias'
workflow = pe.Workflow(name='register_epi_to_struct_ants')
workflow.base_dir = os.path.jo... |
<filename>pressurecooker/images.py<gh_stars>1-10
import math
import tempfile
import numpy as np
import os
import wave
import subprocess
import sys
import matplotlib
import zipfile
import ebooklib
import ebooklib.epub
from io import BytesIO
# Set the backend to avoid platform-specific differences in MPLBACKEND
matplotl... |
""" Standalone webinterface for Openstack Swift. """
# -*- coding: utf-8 -*-
#pylint:disable=E1101
from swiftclient import client
from django.shortcuts import render_to_response, redirect
from django.template import RequestContext
from django.contrib import messages
from django.conf import settings
from django.http im... |
<gh_stars>0
# Takes RAW arrays and returns calculated OD for given shot
# along with the best fit (between gaussian and TF) for ROI.
from __future__ import division
from time import time
from scipy.ndimage import *
from mpl_toolkits.axes_grid1 import make_axes_locatable
import os
import pandas as pd
import numpy as np... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.