content stringlengths 5 1.05M |
|---|
"""
baemo.entity
~~~~~~~~~~~~~~~~~~~~~~~~
This module defines the Entity and Entities interfaces. Entities is a cache of
Entity groups that allows for retrieval by name. Entity is a metaclass that
creates Model and Collection classes.
"""
from collections import OrderedDict
from .delimited import DelimitedDict
from ... |
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.parameter import Parameter
from TorchSUL import Model as M
import config
from . import hrnet
class Head(M.Model):
def initialize(self, head_layernum, head_chn):
self.layers = nn.ModuleList()
for i in range(h... |
from typing import List
import os
import pathlib
import csv
import io
import logging
_logger = logging.getLogger(__name__)
class DatasetDeployer(object):
"""Common deploy operations for persisting files to a local folder.
"""
def __init__(self, key="filename.csv", body="a random data", output_dir="."):... |
# -*- coding: utf-8 -*-
import json
import csv
import glob
import os
import sys
# 3rd party
import pymongo
from pprint import pprint
#%%#######################################################################
## establishing mongo connection, only after you get mongod.exe is running
# C:\Program Files\MongoDB\Server\3... |
# Copyright (C) 2014 eNovance SAS <licensing@enovance.com>
#
# Author: Sylvain Afchain <sylvain.afchain@enovance.com>
#
# 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.apach... |
import configparser
import datetime
import os
import json
import simplejson
def getConfig(file):
config = configparser.ConfigParser()
config.read(file)
if len(config.sections()) == 0:
raise Exception('Could not parse configuration file. Aborting.')
return config
c... |
# Create hourly land and full storm catalog for the Contiguous United States (CONUS).
# Full storm catalog includes storm precipitation and area over the sea, while the land storm catalog only includes
# storms over the land of CONUS.
# author: Yuan Liu
# 2021/12/21
import numpy as np
from time import time
import pand... |
import InvenTree.fields
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('company', '0033_auto_20210410_1528'),
]
operations = [
migrations.CreateModel(
name='ManufacturerPart',
fiel... |
import boto3
import os
import subprocess
import configparser
import pymailer
import tarfile
from hdfs.ext.kerberos import KerberosClient
from logger_setting import *
from datetime import datetime, date, timedelta
py_logger=logging.getLogger('py_logger')
try:
#Your certificate location
os.environ["REQUESTS_CA_... |
# Generated by Django 3.0.7 on 2020-07-27 20:37
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('forum', '0008_auto_20200718_1621'),
]
operations = [
migrations.AlterModelOptions(
name='threadlike',
options={'verbose_name... |
# Parts or the whole documentation of this module
# are copied from the respective module:
# libcloud/compute/drivers/dreamhost.py
# see also:
# https://github.com/apache/libcloud/tree/trunk/libcloud/compute/drivers/dreamhost.py
#
# Apache Libcloud is licensed under the Apache 2.0 license.
# For more information, pleas... |
# -*- coding: utf-8 -*-
pytest_plugins = [
u'ckanext.cloudstorage.tests.ckan_setup',
u'ckanext.cloudstorage.tests.fixtures',
]
|
"""
The :mod:`pure_sklearn.tree` module implements a variety of tree models
"""
from ._classes import (
DecisionTreeClassifierPure,
ExtraTreeClassifierPure,
DecisionTreeRegressorPure,
ExtraTreeRegressorPure,
)
__all__ = [
"DecisionTreeClassifierPure",
"ExtraTreeClassifierPure",
"DecisionTr... |
import config
def clean_image(image):
image[config.WATERMARK_THRESHOLD_LOW < image ] = 255
return image |
from unittest import TestCase
from neo.VM.InteropService import StackItem, Array, Map
from neo.VM.ExecutionEngine import ExecutionEngine
from neo.VM.ExecutionEngine import ExecutionContext
from neo.VM.Script import Script
from neo.SmartContract.Iterable import KeysWrapper, ValuesWrapper
from neo.SmartContract.Iterable.... |
# ----------------------------------------------------------------------
# |
# | __main__.py
# |
# | David Brownell <db@DavidBrownell.com>
# | 2020-07-16 17:02:19
# |
# ----------------------------------------------------------------------
# |
# | Copyright David Brownell 2020-21
# | Distributed unde... |
import requests
from bs4 import BeautifulSoup
from tqdm import tqdm
import pickle
import pkg_resources
knowledge_base_path = pkg_resources.resource_filename(__name__, 'KB.p')
class Helppy:
def __init__(self, kb=None):
self.default_repo = 'https://github.com/vvaezian/Data-Science-Fundamentals'
... |
import unittest
from sprial import spiral
class TestSpiralMethods(unittest.TestCase):
def test_spiral(self):
funcs = [spiral]
for func in funcs:
self.assertEqual(func(3), [[1,2,3], [8,9,4], [7,6,5]])
if __name__ == '__main__':
unittest.main() |
import cv2
import numpy as np
import time
# Creating a VideoCapture object
cap = cv2.VideoCapture(0)
# Give some time for the camera to warm-up!
time.sleep(3)
background=0
for i in range(30):
avl,background = cap.read()
if avl==True:
# Laterally invert the image / flip the image.
background = np.flip(background... |
cash = float(input("Quanto de dinheiro você te na carteira?"))
dol = cash * 5.46
eur = cash * 6.33
print(" Com o valor total da sua carteira {:.2f} é possivél comprar USA {:.2f} e EUR {:.2f}".format(cash, dol, eur))
|
from robodkdriver import RoboDK, RobotSerial
import struct
import numpy as np
import numpy as np
motor_reductions = np.array([[1/48., 0, 0, 0, 0, 0],
[0, 1/48., 1/48., 0, 0, 0],
[0, 0, 1/48., 0, 0, ... |
from __future__ import print_function
from distutils.spawn import find_executable
def cmd_exists(name):
"""Check whether `name` is an executable on PATH."""
return find_executable(name) is not None
def attr(obj, *path, **kwargs):
"""Safely get a nested attribute from an dictionary"""
default = kwarg... |
import reapy
from reapy import reascript_api as RPR
from reapy.core import ReapyObject
from reapy.tools import Program
class Marker(ReapyObject):
_class_name = "Marker"
def __init__(
self, parent_project=None, index=None, parent_project_id=None
):
if parent_project_id is None:
... |
# Centralized location for extracting data information from a THREAD_ID
# These functions can be shared between the different visualization apps
# MINT API ingestion
from __future__ import print_function
import time
import solutioncatalog
from solutioncatalog.rest import ApiException
from pprint import pprint
from sol... |
import sys
import sc2
from sc2 import Difficulty, Race
from sc2.player import Bot, Computer
from __init__ import run_ladder_game
# Load bot
from SunshineBot import SunshineBot
bot = Bot(Race.Terran, SunshineBot())
# Start game
if __name__ == "__main__":
if "--LadderServer" in sys.argv:
# Ladder game st... |
"""Base classes for actions. Actions do something with the payload produced from either
message processors or formatters."""
from typing import Any
from homebot.models import Context
from homebot.utils import AutoStrMixin, LogMixin
from homebot.validator import TypeGuardMeta
class Action(AutoStrMixin, LogMixin, meta... |
"""
This module defines data types in Taichi:
- primitive: int, float, etc.
- compound: matrix, vector, struct.
- template: for reference types.
- ndarray: for arbitrary arrays.
- quantized: for quantized types, see "https://yuanming.taichi.graphics/publication/2021-quantaichi/quantaichi.pdf"
"""
from taichi.types imp... |
import torch
from torch import nn
import torch.nn.functional as F
import models
from torch.utils.data import DataLoader
import os.path as osp
from tqdm import tqdm
from torch.autograd import Variable
import numpy as np
from utils.logger import AverageMeter as meter
from data_loader import Visda_Dataset, Office_Dataset... |
# Generated by Django 3.2.5 on 2021-07-22 08:12
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('alumni', '0002_auto_20210721_2315'),
]
operations = [
migrations.AlterModelOptions(
name='studentsheet',
options={'v... |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
"""Handle cancel and help intents."""
from botbuilder.core import BotTelemetryClient, NullTelemetryClient
from botbuilder.dialogs import (
ComponentDialog,
DialogContext,
DialogTurnResult,
DialogTurnS... |
import unittest
from lexer.token import Token, TokenType, TokenError
class TestToken(unittest.TestCase):
def test_identifier_token_creation(self):
token_inputs = (TokenType.IDENTIFIER, 'ID', '[a-zA-Z_][a-zA-Z0-9_]*')
token = Token(*token_inputs)
self._test_token_creation(token, token_inp... |
"""
pyProm: Copyright 2018.
This software is distributed under a license that is described in
the LICENSE file that accompanies it.
"""
from pyprom.lib.containers.multipoint import MultiPoint
from pyprom.lib.locations.saddle import Saddle
def generate_MultiPoint(x, y, xSpan, ySpan,
datamap, ... |
from __future__ import unicode_literals
from ..elements.elementbase import LogicElement, Attribute
from ..filter import MoyaFilter, MoyaFilterExpression
class Filter(LogicElement):
"""
Define a [i]filter[/i], which may be used in expressions.
Here's an example of a filter:
[code xml]
<filter nam... |
#
# C O N S T A N T S
#
# Various constants
# This is just the text that will be placed on the visible treatment plan
SPRAYER_NAME = ""
# Names for the attributes
# Some of these are a bit redundant and are there for backwards compatibility
NAME_AREA = "area"
NAME_TYPE = "type"
NA... |
#import numpy as np
import neworder as no
print(no.__version__)
no.verbose()
class Test(no.Model):
def __init__(_self, timeline):
super().__init__(timeline, no.MonteCarlo.deterministic_identical_stream)
m = no.Model(no.NoTimeline(), no.MonteCarlo.deterministic_identical_stream)
t = no.NoTimeline()
print(t)
p... |
from rest_framework.serializers import ModelSerializer
from watch.models import Score
class ScoreSerializer(ModelSerializer):
class Meta:
model = Score
fields = "__all__"
|
import logging
import os,site,importlib, inspect
from flare.config import conf
from flare.views.view import View
sitepackagespath = site.getsitepackages()[0]
def generateView( view:View, moduleName, actionName, name = None, data = () ):
instView = view()
instView.params = {
"moduleName":moduleName,
"actionName"... |
import pytest
@pytest.mark.asyncio
async def test_video_info(client):
video = await client.video("fLAcgHX160k")
assert video.title == "The Advent of Omegaα"
|
from napari.plugins.io import read_data_with_plugins
def read_image(imagefile):
data, _ = read_data_with_plugins(imagefile)
return data
data = read_image("/Users/cjw/Desktop/RGB11/MeOH-QS-002.tif")
data2 = read_image("Data/test.nd2")
print(data[0][0].shape, data[0][0].mean(axis=(1,2)))
print(data2[0]... |
"""
Note: Implemented with old implementation of remove_outliers.
"""
# packages
import sys
import os
import numpy as np
sys.path.insert(0, os.path.abspath("../src/ssh-kd"))
from plugin.seg import remove_outliers, helper_object_points
from utils.data_prep import read_file, get_outliers
# hidding the warnings
import ... |
# -*- coding: utf-8 -*-
# ==========================================================================
# Copyright (C) since 2020 All rights reserved.
#
# filename : hello_world.py
# author : chendian / okcd00@qq.com
# date : 2020-05-16
# desc :
# ======================================================... |
import elbus_async
import asyncio
async def main():
name = 'test.client.python.async_sender'
bus = elbus_async.client.Client('/tmp/elbus.sock', name)
await bus.connect()
# send a regular message
result = await bus.send('test.client.python.async',
elbus_async.client.Fram... |
# weight/forms.py
# Jake Malley
# 03/02/15
"""
Defines the forms used in the weight blueprint.
"""
# Imports
from flask_wtf import Form
from wtforms import DecimalField
from wtforms.validators import DataRequired, NumberRange
class AddWeightForm(Form):
"""
Form for users to add weight.
"""
# Decima... |
print(min(a, b, c))
|
import mock
from datetime import timedelta
from tornado import gen
from tornado.testing import gen_test
from microproxy.test.utils import ProxyAsyncTestCase
from microproxy.protocol.http2 import Connection
from microproxy.context import HttpRequest, HttpResponse, HttpHeaders
class TestConnection(ProxyAsyncTestCase):... |
import pandas as __pd
import datetime as __dt
from seffaflik.__ortak.__araclar import make_requests as __make_requests
from seffaflik.__ortak import __dogrulama as __dogrulama
__first_part_url = "market/"
def smf(baslangic_tarihi=__dt.datetime.today().strftime("%Y-%m-%d"),
bitis_tarihi=__dt.datetime.today()... |
# coding: utf8
import requests
import json
if __name__ == "__main__":
# 指定用于匹配的文本并生成字典{"text_1": [text_a1, text_a2, ... ]
# "text_2": [text_b1, text_b2, ... ]}
text = {
"text_1": ["这道题太难了", "这道题太难了", "这道题太难了"],
"text_2": ["这道题是上一年的考题", "这道题不简单", "这道题很有意思"]
}... |
import pandas as pd
import numpy as np
import math
import random
from keras.models import Sequential
from keras.layers.core import Dense, Activation
from keras.layers.recurrent import LSTM
#% matplotlib inline
import matplotlib.pyplot as plt
random.seed(0)
# 乱数の係数
random_factor = 0.05
# サイクルあたりのステップ数
... |
from numpy import inf, nan
from sklearn.decomposition import TruncatedSVD as Op
from lale.docstrings import set_docstrings
from lale.operators import make_operator
class _TruncatedSVDImpl:
def __init__(self, **hyperparams):
self._hyperparams = hyperparams
self._wrapped_model = Op(**self._hyperpar... |
config = dict(
SUPPORTED_LANGUAGES = [ "de", "en", "fr", "it", "es", "ar", "tr", "el", "ru", "uk", "pl"],
RECORDING_DURATION = 8.0, # not used
SPEAKING_ANSWER_TIMEOUT = 2,
#PRINTED_LANGUAGES = ["en", "de", "el", "tr", "ar"],
SERIAL_PORT = "/dev/ttyACM0",
API_ADRESS = "http://localhost:3030"
)
|
import html
with open('./app/app.py', 'r') as f:
source = f.read()
with open('./app/files/source.html', 'w') as f:
f.write('<html><body><code><pre>' + html.escape(source) + '</pre></code></body></html>')
|
from django.contrib.auth.mixins import (UserPassesTestMixin,
LoginRequiredMixin, PermissionRequiredMixin)
from django.http import HttpResponse
from django.shortcuts import redirect
import re
from design import models as design_model
class PageableMixin(object):
def get_context_data(self, **kwargs):
c... |
#!/usr/bin/env python
"""
Created by howie.hu at 2021/1/6.
"""
import ruia
BANNER = f"""
✨ Write less, run faster({ruia.__version__}).
__________ .__ .__ .__ .__
\______ \__ __|__|____ _____| |__ ____ | | | |
| _/ | \ \__ \ / ___/ | \_/ __ ... |
def estimate_home_value(size_in_sqft, number_of_bedrooms):
#Assume all homes are worth at least $50,000
value = 50000
#adjust value estimate based on the size of the house
value += (size_in_sqft*92)
#Adjust the value estimate based on the number of bedrooms
value += number_of_bedrooms*10000
... |
D=int(input())
print("Christmas"+" Eve"*(25-D)) |
# Kількість паліндромів
#
# Назвемо число паліндромом, якщо воно не змінюється при перестановці його цифр у зворотному порядку. Напишіть програму, яка за заданою кількістю K виводить кількість натуральних палиндромiв, що не перевищують K.
#
# ## Формат введення
#
# Визнач однина K (1≤K≤100000).
#
# ## Формат виведення
... |
import numpy as np
from collections import defaultdict
def pairwise_view(target_station, next_station, mismatch='error'):
if target_station is None or next_station is None:
return ValueError("The data is empty.")
if target_station.shape != next_station.shape:
return None # ValueError("Paired ... |
from Jumpscale import j
try:
from mongoengine import connect
except:
j.builders.runtimes.python3.pip_package_install("mongoengine")
from mongoengine import connect
JSConfigClient = j.baseclasses.object_config
class MongoEngineClient(JSConfigClient):
_SCHEMATEXT = """
@url = jumpscale.MongoE... |
# Copyright 2016 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from typing import List
from pants_test.backend.jvm.tasks.jvm_compile.base_compile_integration_test import BaseCompileIT
from pants_test.backend.jvm.tasks.jvm_compile.zinc.zinc_compile_in... |
"""Cirlces URLs"""
# django
from django.db import router
from django.urls import path
from django.urls.conf import include
# Django REST framework
from rest_framework.routers import DefaultRouter
# views
from .views import circles as circle_views
from .views import memberships as membership_views
router = DefaultR... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@Time : 2020/11/14 10:51 PM
@Author : Caroline
@File : 单机estimator实现
@Description :
"""
import tensorflow as tf
from tensorflow import feature_column
# from tensorflow.keras import layers # 1.15版本
# from tensorflow.python.feature_column import featur... |
from rest_framework import serializers
from rest_framework.serializers import ModelSerializer, Serializer
from django.contrib.auth import get_user_model
User = get_user_model()
class RegisterUserSerializer(ModelSerializer):
class Meta:
model = User
fields = ["email", "username", "first_name", "la... |
import os
from app import create_app
config_name = os.getenv('APP_SETTINGS')
app = create_app(config_name="development")
if __name__ == '__main__':
app.run()
|
#!/usr/bin/env python
import argparse
import base64
import hashlib
import json
import os
import shutil
import sys
import time
try:
from urllib.request import urlopen, Request, HTTPError
except ImportError: # python 2
from urllib2 import urlopen, Request, HTTPError
_USER_CREDS = os.environ.get("READWRITE_USE... |
__version__ = "1.2"
__author__ = "Chris Rae"
__all__ = ["upload"]
from upload import upload
|
import os
import extenteten as ex
import qnd
import tensorflow as tf
def def_ar_lm():
qnd.add_flag('cell_size', type=int, default=128)
qnd.add_flag('num_unroll', type=int, default=16)
qnd.add_flag('batch_size', type=int, default=64)
qnd.add_flag('num_batch_threads', type=int, default=os.cpu_count())
... |
# -*- coding: utf-8 -*-
#
# Copyright (c) 2012 Red Hat, 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 a... |
import win32api
import win32gui
import win32con
import time
import random
from control.base_control import BaseControl
import common.screen as screen
RIGHT = 0
DOWN = 1
LEFT = 2
class ReplyMapCommon(BaseControl):
_scranDirection = 0 # 0 → 1 ↓ 2←
_nextScranDirection = 0
_isScranMap = False
_need2F... |
import unreal
import re
selected_assets = unreal.EditorUtilityLibrary.get_selected_assets()
for sa in selected_assets:
if sa.get_class().get_name() == "Material":
textures = unreal.MaterialEditingLibrary.get_used_textures(sa)
x = []
y = []
for texture in textures:
size... |
# coding: utf-8
import logging
from requests import exceptions, get
from config import BASE_URL, HEADERS, TIMEOUT
from config import GENERALES_SERVICE, COMUNA_SERVICE
from config import PRODUCTION, Paso2015
# For testing with simulated data
import json
import io
from config import SIMULATE, JSON_EXAMPLE_PATH
log = log... |
# -*- coding: utf-8 -*-
print """<!DOCTYPE html>
<html>
<head>
<title>TEST</title>
</head>
<body>
<table width="100%" cellspacing="0" cellpadding="5" border="0">
<form method="GET" action="enviar" name="TheForm" >
<tbody><tr>
<td width="100%" bgcolor="#BDCBE4" align="center">
<table width="100%" cellsp... |
import torch
from torch.utils.data import Dataset
from keras.datasets import imdb
from keras.preprocessing.sequence import pad_sequences
class imdbTrainDataset(Dataset):
def __init__(self, vocab_size=20000, maxlen=250):
train, _ = imdb.load_data(num_words=vocab_size, maxlen=maxlen)
self.data = tr... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""makeTextFile.py -- create text file
"""
import os
ls = os.linesep
fname = ''
# get filename
while True:
fname = raw_input('Input filename: ')
if os.path.exists(fname):
print "ERROR: '%s' already exists" % fname
else:
break
# get file cont... |
from little_notes.ext.auth import login_manager
from little_notes.ext.db.models import User
@login_manager.user_loader
def load_user(user_id: int):
return User.query.get(int(user_id))
|
# ----------------------------------------------------------------------------
# pyglet
# Copyright (c) 2006-2008 Alex Holkner
# Copyright (c) 2008-2021 pyglet contributors
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the follo... |
import os
import re
import torch
import matplotlib.pyplot as plt
from src.loader import load_dataset
"""
模型效果测试类
"""
# 支持中文
plt.rcParams['font.sans-serif'] = ['SimHei'] # 用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False # 用来正常显示负号
class EvalData:
def __init__(self, model, config, logger):
self.c... |
from typing import List, Any
from talipp.indicators.Indicator import Indicator
from talipp.indicators.EMA import EMA
class TEMA(Indicator):
"""
Triple Exponential Moving Average
Output: a list of floats
"""
def __init__(self, period: int, input_values: List[float] = None, input_indicator: Indic... |
#!/usr/bin/env python
import os, subprocess, signal
train_dir = os.path.dirname(os.path.realpath(__file__))
enclosed_dir = os.path.normpath(os.path.join(train_dir, '../'))
caffe_dir = os.path.abspath(os.path.join(train_dir, '../../../deps/simnets'))
subprocess.check_call('%s/generate_blob.py' % enclosed_dir, shell=Tru... |
def default_newrepr(self):
return f'Instance of {self.__class__.__name__}, vars = {vars(self)}'
def betterrepr(newstr=None, newrepr=default_newrepr):
def wrapped(cls):
if newstr is not None:
cls.__str__ = newstr
cls.__repr__ = newrepr
return cls
return wrapped
|
#!/usr/bin/env python
# -*- coding: utf8 -*-
import os
from time import sleep
from random import randint
# lock categories
RWLOCK = 'rwlock' # exclusive lock
#TODO shared lock: READLOCK = 'readlock'
def lock(filename, lockcat, max_attempts=10, max_wait_ms=200):
for i in range(0, max_attempts):
succ... |
import classad
import htcondor
import os
import time
from PersonalCondor import PersonalCondor
from Utils import Utils
JOB_SUCCESS = 0
JOB_FAILURE = 1
class CondorJob(object):
def __init__(self, job_args):
self._job_args = job_args
def Submit(self, wait=True):
# Submit the job defined by... |
import numpy as np
from sklearn.model_selection import GridSearchCV
from sklearn.model_selection import cross_val_score
from ml import model_evaluation
def best_estimator(estimator,
X_train,
y_train,
cv,
param_grid,
sco... |
import datetime
from django.utils import timezone
from test_plus.test import TestCase
from .factories import AnnouncementFactory
class TestAnnouncementFeed(TestCase):
def test_ok(self):
announcement = AnnouncementFactory()
response = self.get("announcements:feed")
self.assertResponseCo... |
from display.display import ClockDisplay |
# coding: utf-8
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import sys
import cv2
import random
import numpy as np
import traceback
import tensorflow as tf
from . import dataset_util
from ...file.file_operate import FilesOp
from ...file.parse_... |
from __future__ import absolute_import, print_function
from sage.all import matrix
__all__ = ["dim_affine_hull"]
def dim_affine_hull(points):
"""Return dimension of affine hull of given collection of points."""
return matrix([p - points[0] for p in points[1:]]).rank()
|
import os
import json
from datetime import datetime, date
import dataclasses
from typing import List, Optional, Callable, Sequence, Any
import click
@click.group()
@click.option(
"--verbose/--quiet",
default=None,
is_flag=True,
show_default=True,
help="Change default log level",
)
def main(verbos... |
# See license.txt for license details.
# Copyright (c) 2020-2021, Chris Withers
import os
from setuptools import setup, find_packages
base_dir = os.path.dirname(__file__)
setup(
name='giterator',
version='0.2.0',
author='Chris Withers',
author_email='chris@withers.org',
license='MIT',
descri... |
import tensorflow as tf
from MetReg.base.base_model import BaseModel
from tensorflow.keras import models, Model
from tensorflow.keras import layers
class DNNRegressor(Model):
def __init__(self,
activation='relu',):
super().__init__()
self.regressor = None
self.dense1 = la... |
import matplotlib.pyplot as plt
import networkx as nx
import numpy as np
import dgl
def vis_graph(g, title="", save_name=None):
if isinstance(g, nx.Graph):
pass
elif isinstance(g, np.ndarray):
g = nx.DiGraph(g)
elif isinstance(g, dgl.DGLGraph):
g = g.to_networkx()
else:
... |
r"""
###############################################################################
:mod:`OpenPNM.Algorithms` -- Algorithms on Networks
###############################################################################
Contents
--------
This submodule contains algorithms for performing simulations on pore networks
Clas... |
import os
from pathlib import Path
from qtpy import QtWidgets, QtCore, QtGui
from pyqtgraph.parametertree.Parameter import ParameterItem
from pyqtgraph.parametertree.parameterTypes.basetypes import WidgetParameterItem
from pyqtgraph.parametertree import Parameter
class FileDirWidget(QtWidgets.QWidget):
"""
... |
from server import Server
import os
def install_apt_packages(server):
print("installing apt packages")
server.update_apt_packages()
server.install_apt_package("python3-pip")
packages = server.get_installed_apt_packages()
assert "python3-pip" in packages
def install_pip3_packages(server):
versi... |
#from tensorflow import keras
from tensorflow.keras.layers import Conv2D, MaxPooling2D, ZeroPadding2D
from tensorflow.keras.layers import Dense, Activation, Dropout, Flatten
from tensorflow.keras import optimizers
from tensorflow.keras.models import Sequential
img_width = 150
img_height = 150
def load_model(MODEL_2... |
import random
import time
import itertools
from time import sleep
import numpy as np
from operator import itemgetter
import operator
from ..util import get_direction, get_random_direction, AStarGraph, AStarSearch, get_closest, get_closest_astar
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
# cool... |
from rest_framework.decorators import api_view, permission_classes
from rest_framework.response import Response
from rest_framework.permissions import AllowAny
from django.http import HttpResponse
from rest_framework import status
@api_view()
@permission_classes([AllowAny,])
def HealthCheckView(request):
return Re... |
import logging
import sys
from common.io.net import NetReader
from core.exceptions.config_exceptions import ConfigNoFileNameGivenException
from core.io.config import ConfigReader
from core.io.lines import LineReader
from core.io.periodic_ean import PeriodicEANReader, PeriodicEANWriter
from core.io.ptn import PTNReader... |
import asyncio
from collections import defaultdict
import contextlib
import hashlib
import io
import os
from pathlib import Path
import subprocess
import textwrap
import unittest
import peru.async as async
import peru.plugin as plugin
import shared
from shared import SvnRepo, GitRepo, HgRepo, assert_contents
class T... |
from django import (
forms,
)
from django.conf import (
settings,
)
from django.contrib import (
admin,
)
from django.db import (
models,
)
from adminsortable2.admin import (
SortableAdminMixin,
SortableInlineAdminMixin,
)
from django_simple_file_handler.file_types import (
CHECK_DOC,
... |
try:
import openbayestool
except ImportError:
openbayestool = None
else:
from openbayestool import log_param, log_metric, clear_metric
if openbayestool:
def log_train_acc(acc):
log_metric('train acc max', max(acc))
log_metric('train acc new', acc[-1])
def log_test_acc(acc):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.