content stringlengths 5 1.05M |
|---|
from __future__ import print_function
import sys
#sys.path.insert(0, '../')#use this to have a reference to ripser_plusplus_python module (module is in parent directory)
# Importing from a previous directory if not installed
import ripserplusplus as rpp_py
import numpy as np
import os
'''
LOWER-DISTANCE MATRIX - READ... |
#!/usr/bin/env python
import sys
import numpy as np
import matplotlib.pyplot as plt
def is_red(x):
return np.all(x == np.array([1,0,0,1]))
class PointInteractor(object):
"""
Select/deselect points on a scatter plot
"""
def __init__(self, x, y, inds = []):
"""
Parameters
--... |
#!/usr/bin/env python
#
import rospy
import sys
import math
from geometry_msgs.msg import Pose
from std_msgs.msg import Float32
from std_msgs.msg import Float32MultiArray
from std_msgs.msg import Bool
def getOdometry(data):
global odometry
odometry = data
# print("get checkFlag Data:", checkFlag)
def getCh... |
from keras.models import Sequential
from keras.layers import BatchNormalization, Conv2D
import numpy as np
model = Sequential()
model.add(BatchNormalization(input_shape=(2, 1, 3)))
model.add(Conv2D(2, (1, 1)))
model.compile(optimizer='sgd', loss='mse')
params = [0] * 4
params[0] = np.array([3,3,3]) # gamma
params[1... |
import logging
import sys
from pathlib import Path
from loguru import logger
sys.path.insert(0, str(Path().absolute().parent))
from config import PROJECT_NAME, RULE_EXE_QUEUE_NAME, RCSExchangeName, PRE_FETCH_COUNT, LOG_FILE_PATH, LOG_FILENAME, \
LOG_FILE_RETENTION, LOG_FILE_ROTATION
from utils.fastapi_app import ap... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
from dbs.initdb import DBSession
from dbs.models.Host import Host
from sqlalchemy import desc
from sqlalchemy.exc import InvalidRequestError
from sqlalchemy.dialects.mysql import insert
class HostOp:
def __init__(self):
self.session = DBSession
def inser... |
"""LinkFixer class.
Does two things. Takes as input entry lists as expected by the Sidebar and
Banner classes, and returns a massaged list where any current links are
boldified and turned into non-links. Also supports global string
interpolation over the links using a dictionary.
"""
import sys
import urlparse
imp... |
from .connect_four.connect_four import env, raw_env
|
"""
author: Hosung Lee
date: December 7 2020
Abstract Cipher class is a base class of all ciphers used within photocrypt package.
"""
from abc import ABC, abstractmethod
from typing import Optional, List
class Cipher(ABC):
"""
Abstract cipher class
"""
@abstractmethod
... |
# -*- coding: utf-8 -*-
from pyndf.constants import CONST
from pyndf.process.data.records.abstract import Record
class ExcelRecord(Record):
def __init__(self, record, *args, **kwargs):
super().__init__(*args, **kwargs)
self.log.debug("Create Excel record")
# Personal info
for key ... |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import numpy as np
import tensorflow as tf
from .base_model import BaseModel
__all__ = ["XDeepFMModel"]
class XDeepFMModel(BaseModel):
def _build_graph(self):
"""The main function to create xdeepfm's logic.
... |
# Generated by Django 3.1.4 on 2021-02-28 02:03
import django.core.validators
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('users', '0008_auto_20210227_0534'),
]
operations = [
migrations.AlterField(
model_name='user',
... |
# -*- coding: utf-8 -*-
from crc_ccitt import CRC
import struct
from utils import hexdump
class Device():
def __init__(self, name, signature, pagesize, flashsize, eepromsize, bootsection):
self.name=name
self.signature=signature
self.pagesize=pagesize
self.flashsize=flashsize
... |
# Generated by Django 3.0.5 on 2020-05-03 12:31
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('medicine', '0001_initial'),
]
operations = [
migrations.AddConstraint(
model_name='medicine',
constraint=models.Uniq... |
import codecs
import discord
import os
import subprocess
client = discord.Client()
@client.event
async def on_message(message):
if message.author.bot:
return
if message.content == '!sin':
await message.channel.send("16進数の文字を入力してください")
def check(command):
return command.auth... |
# During World War 2, you are a mathematician who has joined the cryptography team to decipher the enemy's enigma code.
# Your job is to create a program to crack the codes.
# On the first line of the input, you will receive the encrypted message.
# After that, until the "Decode" command is given, you will be receiv... |
#!/usr/bin/env python
"""
Generic LPU demo
Notes
-----
Generate input file and LPU configuration by running
cd data
python gen_generic_lpu.py
"""
import argparse
import itertools
import networkx as nx
from neurokernel.tools.logging import setup_logger
import neurokernel.core_gpu as core
from neurokernel.LPU.LPU ... |
import torch
import numpy as np
import os
from tqdm import tqdm
from submodules.GAN_stability.gan_training.train import toggle_grad, Trainer as TrainerBase
from submodules.GAN_stability.gan_training.eval import Evaluator as EvaluatorBase
from submodules.GAN_stability.gan_training.metrics import FIDEvaluator, KIDEvalua... |
import hashlib
from {{ cookiecutter.project_name|lower|replace('-', '_')|replace(' ', '_') }}.example import ExampleEngine
class TestExampleEngine:
"""Very dumb test class to execute some example tests."""
def setup_method(self):
comparer = hashlib.sha256()
self.secret = "this is a ultra s... |
# PlacesCNN for scene classification
#
# by Bolei Zhou
# last modified by Bolei Zhou, Dec.27, 2017 with latest pytorch and torchvision (upgrade your torchvision please if there is trn.Resize error)
import torch
from torch.autograd import Variable as V
import torchvision.models as models
from torchvision import transfor... |
import os
import cv2
class VideoRec:
def __init__(self, camID: int, fname: str, fps: int, res: str):
self.camId = camID
self.cam = cv2.VideoCapture(self.camId, cv2.CAP_DSHOW)
self.fname = fname
self.fps = fps
self.res = res
self.VIDEO_TYPE = {
'avi': ... |
#!/usr/bin/env python3
# nesting dictionary in a list
carrer_log = [
{
"Fundations": "low level programming",
"Languages": ["C", "Assembly"],
"Projects": 2
},
{
"Fundations": "Higer level programming",
"Languages": ["Python", "Ruby"],
"Projects": 4
},
]
... |
#!/usr/bin/env python
import rospy
from std_msgs.msg import UInt16
def recv_buzzer(data):
rospy.loginfo(type(data))
rospy.loginfo(data.data)
if __name__ == '__main__':
rospy.init_node('buzzer')
rospy.Subscriber("buzzer",UInt16,recv_buzzer)
rospy.spin()
# Copyright 2016 Ryuichi Ueda
# Released under the BSD Lic... |
import sys
import time
import logging
import deviceRegistration.newDeviceRegistration
import utils.settings
import API.authentication as auth
import API.identity
logger = logging.getLogger('Device Registration')
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
l... |
import numpy as np
size = 32
np.random.seed(42)
# normalized random noise map
map = np.random.rand(size,size)
# scales an array up along vertical and horizontal axis
def scale_up(array, factor):
vertical_axis = np.repeat(array, factor, axis=1)
both_axes = np.repeat(vertical_axis, factor, axis=0)
return b... |
#Helper file for Parameters.py
import numpy
###################### Solves for npts #########################
def PTShelper(start, stop, step):
'''
:param start: (float) the beginning of the energy region
:param stop: (float) the end of the energy region
:param step: (float) the step of the energy regi... |
#!/usr/bin/python3
# encoding:utf-8
from authmysql.connect import *
import time
import hashlib
def md5(arg):
md5_pwd = hashlib.md5(bytes('abd',encoding='utf-8'))
md5_pwd.update(bytes(arg,encoding='utf-8'))
return md5_pwd.hexdigest()
def register():
try:
while True:
name=input("[... |
import click
@click.group()
def cli() -> None:
"""Demos for various prompts"""
@cli.command()
def confirm_as_variable() -> None:
"""Asks the user for confirmation and stores the response in a variable"""
confirmed = click.confirm("Are you sure you want to drop the users table?")
status = click.style(... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
def WALLPAPER():
os.system("nitrogen --restore")
def LAPTOP():
os.system("xrandr --output eDP1 --primary --mode 1366x768 --pos 0x156 --rotate normal --output HDMI1 --off --output VIRTUAL1 --off")
def HDMI():
os.system("xrandr --output e... |
import logging
import os
log = logging.getLogger('no_subprocess_init')
def handle_event(event):
log.info('%s %d %s' % (__file__, os.getpid(), event))
def __sgevents_init__(dispatcher):
dispatcher.register_callback(callback=handle_event, callback_in_subprocess=False)
|
# https://leetcode.com/problems/container-with-most-water/
#
# Given n non-negative integers a1, a2, ..., an, where each represents a point at coordinate (i, ai).
# n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0).
# Find two lines, which together with x-axis forms a container, ... |
#!/usr/bin/env python
# encoding: utf-8
from base import BaseHandler
class Better404Handler(BaseHandler):
def _write_404(self):
self.send_response(
None,
error_code=-1,
error_msg='The api does not exist.'
)
def get(self):
self._write_404()
def... |
import functools
import itertools
from typing import Tuple, Union
import warnings
from builtins import range
from collections import defaultdict
# import numba
import numpy as np
import pandas as pd
"""Entropy functions"""
# Borrowed from https://github.com/raphaelvallat/antropy/blob/master/antropy/entropy.py
import ... |
"""
"""
import numpy as np
from astropy.utils.misc import NumpyRNGContext
from .. import array_utils
__all__ = ('test_find_idx_nearest_val', )
fixed_seed = 43
def test_find_idx_nearest_val():
# Create an array of randomly sorted integers
x = np.arange(-10, 10)
with NumpyRNGContext(fixed_seed):
... |
import torch
from mmdet.core.bbox.coder import YOLOBBoxCoder
def test_yolo_bbox_coder():
coder = YOLOBBoxCoder()
bboxes = torch.Tensor([[-42., -29., 74., 61.], [-10., -29., 106., 61.],
[22., -29., 138., 61.], [54., -29., 170., 61.]])
pred_bboxes = torch.Tensor([[0.4709, 0.6152,... |
# adb/commands.py - Run executables on an Android device -*- python -*-
#
# This source file is part of the Swift.org open source project
#
# Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
# Licensed under Apache License v2.0 with Runtime Library Exception
#
# See https://swift.org/LICENSE.txt for l... |
import ud_solicitacao
import wizards
import ud_solicitacao_responsavel |
# coding: utf-8
# In[23]:
from requests import get
from requests.exceptions import RequestException
from contextlib import closing
from bs4 import BeautifulSoup
from datetime import timedelta
import pandas as pd
import urllib3
import datetime
import time
import os
import db_manager
# -*- coding: utf -*-
# In[24]... |
import logging
import random
import astropy.units as u
from astropy.io.misc import yaml
import simtools.config as cfg
import simtools.io_handler as io
import simtools.util.general as gen
from simtools.util import names
from simtools.layout.layout_array import LayoutArray
from simtools.util.general import collectDataF... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
:author: Muneeb Ali | http://muneebali.com
:license: MIT, see LICENSE for more details.
"""
from flask import Flask, make_response, render_template, jsonify, request
import serial, socket
app = Flask(__name__)
# import the database and the tables from the database... |
from .config import conf
from .snippet import *
from .tracker import *
from .daemon import *
from .http_service import *
from .hash import *
from .crypto import *
from .pg import *
from .request_args import *
|
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist_data = input_data.read_data_sets('MNIST_data', one_hot=True)
input_size = 784
no_classes = 10
batch_size = 100
total_batches = 200
x_input = tf.placeholder(tf.float32, shape=[None, input_size])
y_input = tf.placeholder(tf.float3... |
from pylab import *
from loader import gload, load, save, gsave, fload
gray()
def LOG(x):
return log(x+1e-300)
def show_mat(x,vmin=None,vmax=None):
hold(False)
imshow(x,interpolation='nearest',vmin=vmin,vmax=vmax)
def show(V,vmin=None,vmax=None):
if V.ndim==1:
res = int(sqrt(shape(V)[0]))... |
from pyspark import RDD
from sparkquantum import constants
__all__ = ['is_scalar', 'is_shape']
def is_scalar(obj):
"""Check if an object is a scalar (number), i.e., an int, a float or a complex.
Parameters
----------
obj
Any python object.
Returns
-------
bool
True if a... |
class Solution:
def myAtoi(self, str):
"""
:type str: str
:rtype: int
"""
result = 0
INT_MIN, INT_MAX = - 2 ** 31, 2 ** 31 - 1
index = 0
sign = 1
while index < len(str):
if str[index].isspace():
index += 1
... |
from sktime.datasets import load_basic_motions
from sktime.datasets import load_italy_power_demand
from sktime_dl.deeplearning import CNNClassifier
from sktime_dl.utils.model_lists import SMALL_NB_EPOCHS
from sktime_dl.utils.model_lists import construct_all_classifiers
def test_basic_univariate(network=CNNClassifier... |
# -*- encoding: utf-8 -*-
"""
@File : enums.py
@Time : 2020/6/27 18:05
@Author : chise
@Email : chise123@live.com
@Software: PyCharm
@info :
"""
from enum import Enum
class TaskEnum(Enum):
Silver='Silver'
EverydayTask= 'EverydayTask'
LotteryResult='LotteryResult'
connect='connect'
PKLott... |
# -*- coding: utf-8 -*-
class BinaryTree(object):
def __init__(self, value):
self.key = value
self.leftNode = None
self.rightNode = None
def insertLeft(self, value):
if self.leftNode == None:
self.leftNode = BinaryTree(value)
else:
t = BinaryTree(value)
t.leftChild = self.lef... |
import demo_registrydao.models as models
from demo_registrydao.types.registry.parameter.propose import ProposeParameter
from demo_registrydao.types.registry.storage import RegistryStorage
from dipdup.context import HandlerContext
from dipdup.models import Transaction
async def on_propose(
ctx: HandlerContext,
... |
import os.path as osp
import h5py
import numpy as np
import tqdm
from sklearn.metrics.pairwise import cosine_similarity
class Gallery():
def __init__(self):
self.features = None
self.ids = []
def id(self, index):
return self.ids[index]
def cosines(self, query_feature):
i... |
import datetime
import pytz
from sqlalchemy import Column, Integer, String, DateTime, BigInteger, ForeignKey
from sqlalchemy.orm import relationship
from vardb.datamodel.migration.migration_base import Base
class Attachment(Base):
__tablename__ = "attachment"
id = Column(Integer, primary_key=True)
sha256... |
import numpy as np
from h5py import File, Group
from .type import is_seq_of
import torch
def get_one_shape(x):
if isinstance(x, (dict, Group, File)):
return get_one_shape(x[list(x.keys())[0]])
elif is_seq_of(x):
return get_one_shape(x[0])
else:
assert hasattr(x, 'shape'), type(x)
... |
import logging
import pandas
from rdkit import Chem
from rdkit.Chem import QED, Descriptors, Lipinski
from cuchem.wf.generative import MolBART
from tests.utils import _create_context
from cuchem.decorator import LipinskiRuleOfFiveDecorator
import dask.dataframe as dd
import multiprocessing
logger = logging.getLogger(... |
#!/usr/bin/env python
# encoding: utf-8
import json
from flask import Flask, request
from base64 import decodebytes
from model import Translator
app = Flask(__name__)
t = Translator()
def base_to_jpg(key):
form_data = request.form
image_base64 = form_data[key]
str_to_bytes = str.encode(image_base64)
... |
# Generated by Django 3.2 on 2021-06-03 18:07
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('erp', '0003_auto_20210603_1303'),
]
operations = [
migrations.CreateModel(
name='Category',
fields=[
(... |
# Copyright 2019 - Nokia
# All Rights Reserved.
import os
from nuage_tempest_plugin.lib.test import nuage_test
from nuage_tempest_plugin.lib.topology import Topology
CONF = Topology.get_conf()
LOG = Topology.get_logger(__name__)
class BaseTestCase(object):
"""Wrapper around the base to avoid it being executed ... |
"""
Defines the blueprint for the movie
"""
from flask import Blueprint
from flask_restful import Api
from resources import MovieResource
from resources import MovieAuthorResource
MOVIE_BLUEPRINT = Blueprint("movie", __name__)
Api(MOVIE_BLUEPRINT).add_resource(
MovieResource, "/movie/<string:title>"
)
Api(MOVIE_B... |
'''
Example:
>> python wcdbcli/convert_mat_to_hdf5.py \
-o "Mycoplasma genitalium" \
-n "Wild-type set #1" \
-d /home/projects/WholeCell/simulation/output/runSimulation/2011_10_19_02_53_45/1 \
-i 1
'''
import argparse
import h5py
import numpy
import os
import re
import scipy.io
impo... |
import argparse
import os
import tensorflow as tf
import tflearn
from tflearn.layers.core import input_data, dropout, fully_connected
from tflearn.layers.estimator import regression
from tflearn.layers.normalization import l2_normalize
from tflearn.metrics import Top_k, R2
import cv2
import sys
from model import *
fro... |
from django.shortcuts import redirect, get_object_or_404
from django.core.exceptions import PermissionDenied
from django.contrib.auth import logout as django_logout
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from .models import Tweet
@login_required()
def logout(re... |
#!/usr/bin/env python3
from apex import amp
from hashembed.embedding import HashEmbedding
import io
import itertools
import math
import numpy as np
import sys
import torch
import torch.multiprocessing
import torch.nn as nn
import torch.nn.functional as F
import torch.nn.utils
import torch.optim as optim
import torch.u... |
#!/usr/bin/env python
"""igcollect - Highwinds CDN
Copyright (c) 2018 InnoGames GmbH
"""
import sys
import json
import grequests
from time import gmtime, strftime, time
from argparse import ArgumentParser
try:
from urllib.request import Request, urlopen
from urllib.parse import urlencode
except ImportError:... |
# encoding: utf-8
"""Unit tests for ckan/logic/action/patch.py."""
import pytest
from ckan.tests import helpers, factories
@pytest.mark.usefixtures("clean_db", "with_request_context")
class TestPatch(object):
def test_package_patch_updating_single_field(self):
user = factories.User()
dataset = fa... |
from src.services.cloudflare import create_dns_record, delete_dns_record
from src.services.database import database
class DnsController:
def create_record(self, user, name, ip_address):
created_domain_name = create_dns_record(name, ip_address)
created_domain_name['userId'] = user.id
datab... |
import boto3
import certifi
import json
import os
from aws_requests_auth.aws_auth import AWSRequestsAuth
from elasticsearch import Elasticsearch, RequestsHttpConnection
import logging
# Log level
logging.basicConfig()
logger = logging.getLogger()
# Parameters
REGION = os.getenv('AWS_REGION')
esendpoint = os.environ['... |
import json
import sys
import numpy as np
from scipy.spatial import ConvexHull
def find_point(coords, point_list):
"""
Coordinates represent either the source or destination [x,y] coordinates of a line.
Given a list of unique points, map one to the given coordinates.
"""
for p in point_list:
... |
from distutils.core import setup
setup(
name = "pickler",
version = "1.0.0.0",
py_modules = ['pickler'],
author = "Sanjeev",
author_email = 'iamsanjeev@gmail.com',
url = "none",
description = "A simple module for pickling",
)
|
'''
Module Python Datastructures
@author Shivakumar Viraktamath
@email shivmath9@gmail.com
'''
#Linked list
class LList:
def __init__(self,data=None):
self.data=data
self.next=None
def addToLast(self,data):
if self.data==None and self.next==None:
self.da... |
# -*- coding: utf-8 -*-
#
# This file is part of Karesansui Core.
#
# Copyright (C) 2009-2012 HDE, Inc.
#
# 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 withou... |
import ee
import folium
import streamlit as st
import geemap.foliumap as geemap
import geemap.colormaps as cm
@st.cache
def uploaded_file_to_gdf(data):
import tempfile
import os
import uuid
_, file_extension = os.path.splitext(data.name)
file_id = str(uuid.uuid4())
file_path = os.path.join(te... |
import shlex
from os import path
from ansible.module_utils.basic import AnsibleModule
STATE_ENABLED = 'enabled'
STATE_DISABLED = 'disabled'
def main():
module = AnsibleModule(
supports_check_mode = False,
# https://docs.ansible.com/ansible/latest/dev_guide/developing_program_flow_modules... |
import json
from pprint import pprint
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
with open('sessions/2016-09-05T09:56:27.739Z-session.json') as data_file:
data = json.load(data_file)
# def lowpassFilter(vector, alpha):
# output = []
# output.append(vector... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# pylint: disable=logging-format-interpolation
"""Context management API of minpy."""
from __future__ import absolute_import
import mxnet
from .utils import log
# pylint: disable= invalid-name
_logger = log.get_logger(__name__)
# pylint: enable= invalid-name
class Con... |
# -*- coding: utf-8 -*-
import pandas as pd
from deprecation import deprecated
from .common import _getJson, _strOrDate, _reindex, _toDatetime
def exchanges(token='', version='', filter=''):
'''Returns an array of U.S. exchanges.
https://iexcloud.io/docs/api/#u-s-exchanges
8am, 9am, 12pm, 1pm UTC daily
... |
'''
Created on Nov 2, 2013
@author: peterb
'''
import logging # @UnresolvedImport
from tornado.websocket import WebSocketHandler
from blueshed.fling.request import Request
from blueshed.fling import utils
class FlingHandler(WebSocketHandler):
def initialize(self, worker=True):
WebSocketHandler.... |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... |
from difflib import get_close_matches
from thefuck.shells import get_history, thefuck_alias
from thefuck.utils import get_closest, memoize, get_all_executables
def _not_corrected(history, tf_alias):
"""Returns all lines from history except that comes before `fuck`."""
previous = None
for line in history:
... |
def solution2(n,m):
if n>m:
loB = []
A = n%m
B = m
while A != 0:
loB.append(B)
A = B%A
B = loB[-1]
GCD = loB[-1]
if m>n:
loB = []
A = m%n
B = n
while A != 0:
loB.append(B)
A = B%A
... |
from .main_buycoins_sdk import BuycoinsSDK
from . import types
__all__ = [
'BuycoinsSDK',
'types'
]
|
#
# Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# This file is licensed under the Apache License, Version 2.0 (the "License").
# You may not use this file except in compliance with the License. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# Thi... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations
from django.conf import settings
import audit_log.models.fields
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('contributions', '0... |
import unittest
import random
import numpy as np
from hbaselines.fcnet.replay_buffer import ReplayBuffer
from hbaselines.goal_conditioned.replay_buffer import HierReplayBuffer
from hbaselines.multiagent.replay_buffer import MultiReplayBuffer
from hbaselines.multiagent.replay_buffer import SharedReplayBuffer
class Te... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.core.urlresolvers import reverse
from django.db import models
from django.utils import timezone
from django.utils.encoding import python_2_unicode_compatible
from blanc_basic_assets.fields import AssetForeignKey
@python_2_unicode_compatibl... |
"""
Parameter selection for Benjamini Hochberg Analysis and T analysis.
"""
from __future__ import absolute_import, division, print_function
import numpy as np
import matplotlib.pyplot as plt
import sys
import itertools
import nibabel as nib
import os
name="sub001"
#set up paths
project_path = "../../"
pa... |
import os
from typing import Optional
import pytest
from fastapi.testclient import TestClient
from pytest import fail
from sqlalchemy.orm import Session
from v3io.dataplane import RaiseForStatus
from v3io_frames import CreateError
from v3io_frames import frames_pb2 as fpb2
from mlrun.api.api.endpoints.grafana_proxy i... |
"""
Python API for the user service.
"""
# Standard library modules
# Installed packages
import requests
class User():
"""Python API for the user service(s1).
Handles the details of formatting HTTP requests and decoding
the results.
Parameters
----------
url: string
The URL for ac... |
t = lambda: int(input())
n = t()
for i in range(n):
m = t()
o = t()
for j in range(o):
a, b = tuple(input().split())
m += int(a)*int(b)
print(m)
|
import os
import glob
from pathlib import Path
def get_paths(path_glob):
paths = glob.glob(path_glob, recursive=True)
ret = []
for p in paths:
p = Path(p)
if not p.is_absolute():
p = p.resolve()
ret.append(p)
return ret
|
import pytest
from hamcrest import assert_that, is_, has_length
from pet_store_client import PetStoreClient
example_pet = {
"name": "Harry",
"category": "Cat",
"bio": "I am fuzzy",
"status": "Available",
"tags": [],
"photoUrls": []
}
def test_get_pet(pet_context, customer_context, pet_store_c... |
from .fixtures import app_client
from urllib.parse import urlencode
def test_homepage(app_client):
response = app_client.get('/.json')
assert response.status == 200
assert response.json.keys() == {'dummy_tables': 0}.keys()
d = response.json['dummy_tables']
assert d['name'] == 'dummy_tables'
ass... |
from typing import Optional, TypedDict
class User(TypedDict):
name: str
username: str
avatar: str
class PostMedia(TypedDict):
link: str
title: str
image: str
excerpt: str
class PostComment(TypedDict):
username: str
date: str
text: str
replies: int
echos: int
upv... |
import pytest
from main.app import app
from tests.utils import MockMemcache
@pytest.fixture(scope="function", autouse=True)
def session():
# Create app context
app.app_context().push()
yield app
@pytest.fixture
def client(session):
testing_client = session.test_client()
yield testing_client
... |
GAS_DENSITY = 2.858
ONE_MPH = 0.44704
from yaw_controller import YawController
from pid import PID
from lowpass import LowPassFilter
import rospy
class Controller(object):
def __init__(self, vehicle_mass, fuel_capacity, brake_deadband, decel_limit, accel_limit, wheel_radius, wheel_base, steer_ratio,
... |
from typing import List
from gridfs import GridFS, GridOut
from badger_utils.sacred.natural_sort import NaturalSort
class GridFSReader:
def __init__(self, fs: GridFS):
self.fs = fs
@staticmethod
def _artifact_prefix(run_id: int) -> str:
return f'artifact://runs/{run_id}/'
def list... |
import os
import sys
import math
import json
from scipy.special import comb
import torch
import torch.nn as nn
import torch.nn.functional as F
from .evaluation import *
from .utility import update_bn_curve
def poly_chain(t, pt_num):
weight_list = [0,] * pt_num
seg_index = int(t * (pt_num - 1)) % (pt_num - 1... |
import pytest
from asdf.exceptions import AsdfDeprecationWarning
from asdf.resolver import Resolver, ResolverChain
def test_resolver_no_mappings():
r = Resolver([], "test")
assert r("united_states:maryland:baltimore") == "united_states:maryland:baltimore"
def test_resolver_tuple_mapping():
r = Resolver... |
from . import api_miners |
from django.conf import settings
from django.core.urlresolvers import reverse_lazy
from django.db.models import Count
from django.http import Http404
from django.shortcuts import render, redirect, get_object_or_404
from django.views.generic import View, TemplateView, ListView
from application.models import Application... |
# Copyright 2016 Google, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
def get_features(image, model):
layers = {'0': 'conv1_1',
'5': 'conv2_1',
'10': 'conv3_1',
'19': 'conv4_1',
'21': 'conv4_2',
'28': 'conv5_1'} # Content Extraction
features = {}
for name, layer in model._modules.items():
image =... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.