text
stringlengths
1
927k
""" test_sphinx_parsers ~~~~~~~~~~~~~~~~~~~ Tests parsers module. :copyright: Copyright 2007-2020 by the Sphinx team, see AUTHORS. :license: BSD, see LICENSE for details. """ from unittest.mock import Mock, patch import pytest from sphinx.parsers import RSTParser from sphinx.util.docutils impor...
"""simple image bingo card generator in python, originally for bots""" import os import io import math import random import textwrap import PIL.Image import PIL.ImageDraw import PIL.ImageFont CARD_SIZE = (720, 720) NUDGE = 8 MODE = "RGBA" IMAGE_FORMAT = "PNG" PALETTE = ["#37547d", "#1d3a62", "#8499b6", "#ffffff", ...
#runas: import numpy as np ; N = 500 ; X = np.random.randn(N,N,3); laplacien(X) #pythran export laplacien(float64[][][3]) import numpy as np def laplacien(image): out_image = np.abs(4*image[1:-1,1:-1] - image[0:-2,1:-1] - image[2:,1:-1] - image[...
# 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...
COLORS = { 'lightblue': '#1c98fa', 'darkblue': '#040443', 'lightgrey': '#c2c8d0', 'darkgrey': '#525252', 'black': '#040404', 'orange': '#fa6e1c', 'red': '#fa361c', 'gold': '#fadc1c', 'purple': '#bb1cfa', 'lime': '#1cfa7c', 'green': '#5bfa1c', }
import numpy as np import unittest import ray import ray.rllib.agents.dqn as dqn from ray.rllib.utils.framework import try_import_tf from ray.rllib.utils.test_utils import check, framework_iterator, \ check_compute_action tf = try_import_tf() class TestDQN(unittest.TestCase): @classmethod def setUpClass...
""" Diamond cutting implementation AUTHORS: - Jan Poeschko (2012-07-02): initial version """ # **************************************************************************** # Copyright (C) 2012 Jan Poeschko <jan@poeschko.com> # # Distributed under the terms of the GNU General Public License (GPL) # as publishe...
''' File Created: Sunday, 17th March 2019 3:58:52 pm Author: Peng YUN (pyun@ust.hk) Copyright 2018 - 2019 RAM-Lab, RAM-Lab ''' import os import math import numpy as np from numpy.linalg import inv from .utils import read_image, read_pc_from_bin, _lidar2leftcam, _leftcam2lidar, _leftcam2imgplane # KITTI class KittiCalib...
from __future__ import print_function from random import randint from tempfile import TemporaryFile import numpy as np import math def _inPlaceQuickSort(A, start, end): count = 0 if start < end: pivot = randint(start, end) temp = A[end] A[end] = A[pivot] A[pivot] = temp ...
from rest_framework.routers import DefaultRouter from .views import SchoolViewSet router = DefaultRouter() router.register(prefix='api/v1/schools', viewset=SchoolViewSet, basename='school') urlpatterns = router.urls
# -*- coding: utf-8 -*- """ TencentBlueKing is pleased to support the open source community by making 蓝鲸智云-权限中心(BlueKing-IAM) available. Copyright (C) 2017-2021 THL A29 Limited, a Tencent company. All rights reserved. Licensed under the MIT License (the "License"); you may not use this file except in compliance with th...
#!/usr/bin/env python3 import requests import json import sys import hashlib #from __future__ import print_function SERVER="https://cms.integreat-app.de" def eprint(*args, **kwargs): print(*args, file=sys.stderr, **kwargs) def get_sites(): r = requests.get("{}/wp-json/extensions/v3/sites".format(SERVER), hea...
import torch def validate_tensor_shape_2d_4d(t): shape = t.shape if len(shape) not in (2, 4): raise ValueError( "Only 2D and 4D tensor shapes are supported. Found " "Found tensor of shape {} with {} dims".format(shape, len(shape)) ) def pad_inner_dims(t, pad_to): ...
#!/usr/bin/env python # Copyright 2014-2018 The PySCF Developers. 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 # # U...
from flask import Flask as _Flask,jsonify from flask import request from flask import render_template from flask.json import JSONEncoder as _JSONEncoder from jieba.analyse import extract_tags import decimal import utils import string class JSONEncoder(_JSONEncoder): def default(self, o): if isinsta...
""" WSGI config for Melbit project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/2.0/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTIN...
#!/usr/bin/env python3 """ Parses console arguments. """ import sys import argparse import uuid import logging from abc import ABCMeta class BaseSettings(object, metaclass=ABCMeta): """ All modes (abstract base class) """ def __init__(self, from_console_arguments=False): self._from_console_arg...
#!/usr/bin/env python """ -------------------------------------------------------------------------------- Created: Jackson Lee 7/8/14 This script reads in a tab delimited file of clusters, and a list of number ranges for reads in each cluster. The script will parse all reads based on the number ranges, and then o...
#!/usr/bin/env python from distutils.core import setup from catkin_pkg.python_setup import generate_distutils_setup # Fetch values from package.xml. setup_args = generate_distutils_setup( packages=['commander'], package_dir={'': 'src'}, ) setup(**setup_args)
from .movie_library import spearman_corr from .movie_library import sentiment_boxoffice_all from .movie_library import sentiment from .movie_library import tweet_collector
# -*- coding: utf-8 -*- import scrapy # needed to scrape import xlrd # used to easily import xlsx file import json import re import pandas as pd import numpy as np from openpyxl import load_workbook import datetime #from datetime import timedelta class ICObench(scrapy.Spider): name = 'ICOBench' # Name of Sc...
import torch import torch.nn as nn import torch.autograd as autograd import torch.nn.functional as F class DDQNCnn(nn.Module): def __init__(self, input_shape, num_actions): super(DDQNCnn, self).__init__() self.input_shape = input_shape self.num_actions = num_actions self....
import time,math from datetime import datetime pi =3.141592653589793238462643 tpi = 2 * 3.141592653589793238462643 degs = 180.0/3.141592653589793238462643 rads = 3.141592653589793238462643/180.0 def C2K(temp_c): return temp_c + 273.16 def C2F(temp_c): return ((temp_c * 9.0)/5.0) + 32.0 def F2C(temp_f): ...
import enum import functools import gzip import io import lzma import mmap import os import os.path import pathlib import pickle import platform from typing import BinaryIO from typing import ( Sequence, Callable, Union, Any, Tuple, TypeVar, Iterator, Dict, Optional, IO, Size...
# checkboxes.py # import necessary modules import sys from PyQt5.QtWidgets import (QApplication, QWidget, QCheckBox, QLabel) from PyQt5.QtCore import Qt class CheckBoxWindow(QWidget): def __init__(self): super().__init__() self.initializeUI() def initializeUI(self): """ Initia...
# 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 # "License"); you may not u...
""" Module contains tools for processing files into DataFrames or other objects """ from __future__ import print_function from collections import defaultdict import csv import datetime import re import sys from textwrap import fill import warnings import numpy as np import pandas._libs.lib as lib import pandas._libs...
# coding: utf-8 import os import time basic_cmd = "python " # generate the indices indices = range(0, 200, 50) for i in xrange(len(indices)-1): time.sleep(5) from_idx = str(indices[i]) to_idx = str(indices[i + 1]) cmd = basic_cmd + "/home/mjoys/user_profile2/projects/user_label.py " + from_idx + " " + to_idx p...
# recipe.py (lciafmt) # !/usr/bin/env python3 # coding=utf-8 """ This module contains functions needed to compile LCIA methods from the ReCiPe model """ import pandas as pd import openpyxl import lciafmt.cache as cache import lciafmt.df as dfutil import lciafmt.xls as xls from .util import datapath, aggregate_factor...
# Generated by Django 2.1.7 on 2019-04-15 11:03 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('status', '0003_auto_20180822_1244'), ] operations = [ migrations.AlterField( model_name='progress', name='image_file...
class Node: def __init__(self, key): self.left = None self.right = None self.val = key # Traverse preorder def traversePreOrder(self): print(self.val, end=' ') if self.left: self.left.traversePreOrder() if self.right: self.right.traver...
""" Code reference: https://github.com/MishaLaskin/rad/blob/master/encoder.py """ import gym.spaces import torch import torch.nn as nn from .utils import CNN, MLP, flatten_ac class Encoder(nn.Module): def __init__(self, config, ob_space): super().__init__() self._encoder_type = config.encoder...
#!/usr/bin/python3 """ Copyright 2021 Vittorio Lo Mele 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...
# -*- coding: utf-8 -*- from decimal import Decimal import graphene class PricefulType(graphene.ObjectType): base_price = graphene.Float() price = graphene.Float() discount_amount = graphene.Float() discount_rate = graphene.Float() discount_percentage = graphene.Float() taxful_price = graphen...
import csv from django.test import TestCase from .models import Product from .product_scraping import AmazonScrapper, WalmartScrapper, TargetScrapper, CostcoScrapper from .views import scraping_class from .utilities import mail_user from .Google_Scraping import GoogleScraping,GoogleSearch class ProductTestCase(TestCa...
# Copyright (c) MONAI Consortium # 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, so...
import deck import copy S = copy.deepcopy(deck.SPADES) C = copy.deepcopy(deck.CLUBS) H = copy.deepcopy(deck.HEARTS) D = copy.deepcopy(deck.DIAMONDS) ONE_PAIR_SCSSS = [] for i in range(13): for j in range(13): for k in range(13): for l in range(13): if i != j and i != k and i !=...
from copy import deepcopy from contextlib import contextmanager import json import os import shutil import tempfile import unittest from unittest import mock import yaml import dbt.config import dbt.exceptions from dbt.adapters.factory import load_plugin from dbt.adapters.postgres import PostgresCredentials from dbt....
import pandas as pd from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import f1_score, precision_score, recall_score import pickle import numpy as np # load train, val data train = pd.read_csv('../data/big-vul_dataset/train.csv') val =...
import io import pandas class HourlyHydrogenCurves: @property def hourly_hydrogen_curves(self): # get hourly hydrogen curves if self._hourly_hydrogen_curves is None: self.get_hourly_hydrogen_curves() return self._hourly_hydrogen_curves ...
from pymongo import MongoClient, DESCENDING from bcrypt import hashpw, checkpw, gensalt import builtins class Users: """ A class to store and retrieve user info and passwords to MongoDB. """ def __init__(self): self.mongo_client = builtins.tornado_config['mongo_client'] self.mongo_db = se...
# -*- coding: utf-8 -*- import scrapy from locations.items import GeojsonPointItem from locations.hours import OpeningHours import datetime Days = ["Mo", "Tu", "We", "Th", "Fr"] class LidsSpider(scrapy.Spider): name = "lids" item_attributes = {"brand": "Lids"} allowed_domains = ["lids.com"] def star...
# Generated by Django 2.1.15 on 2020-04-21 15:07 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('accounts', '0018_editoritemviewed'), ] operations = [ migrations.AddField( model_name='userprofile', name='email_ab...
import time import torch import torch.nn as nn import torch.nn.init as init from .utils import load_state_dict_from_url from typing import Any __all__ = ['SqueezeNet', 'squeezenet1_0', 'squeezenet1_1'] model_urls = { 'squeezenet1_0': 'https://download.pytorch.org/models/squeezenet1_0-a815701f.pth', 'squeezene...
#!/usr/bin/env python3 from cereal import car from panda import Panda from common.params import Params from selfdrive.config import Conversions as CV from selfdrive.car.hyundai.values import CAR, EV_CAR, HYBRID_CAR, LEGACY_SAFETY_MODE_CAR, Buttons, CarControllerParams from selfdrive.car.hyundai.radar_interface import R...
N, K = [int(n) for n in input().split()] H = [int(h) for h in input().split()] print(len([x for x in H if x>=K]))
# -*- coding: utf-8 -*- import datetime import math import numpy as np import pandas as pd from sklearn.preprocessing import StandardScaler from mabwiser.mab import LearningPolicy from tests.test_base import BaseTest class LinTSTest(BaseTest): def test_alpha0_0001(self): arm, mab = self.predict(arms=[...
# -*- coding: utf-8 -*- from wakatime.main import execute from wakatime.packages import requests import logging import os import time import shutil import sys import uuid from testfixtures import log_capture from wakatime.arguments import parse_arguments from wakatime.compat import u, is_py3 from wakatime.constants ...
import os import matplotlib import matplotlib.pyplot as plt import numpy as np import PySpin import torch import torchvision.transforms.functional as F from .._file_utils import get_highest_numbered_file from .._image_utils import RGB8Image, draw_bboxes from .. import _models from .._s3_utils import s3_bucket_exists,...
from imagezmq import imagezmq import argparse import numpy as np import tensorflow as tf import cv2 import time from utils import label_map_util from utils import visualization_utils_color as vis_util # Path to frozen detection graph. This is the actual model that is used for the object detection. PATH_TO_CKPT = './m...
import logging logging.basicConfig(level=logging.DEBUG) logger = logging.getLogger() def parse_gcn(i): import facts.gcn as g import facts.core as c G = g.gcn_source(i) F = c.workflows_for_input(dict(arg=G, arg_type=g.GCNText), output='dict') logger.info(F) for p, o in F.items(): pri...
# # GridCoordinates.py # # @author Alain Rinder # @date 2017.06.02 # @version 0.1 # from lib.graphics import * from src.interface.IDrawable import * from src.interface.Color import * class Square(IDrawable): def __init__(self, board, coord): self.board = board self.coo...
import pytest from sqlalchemy.orm import Session from itunesdb.web import crud from itunesdb.web import database from itunesdb.web import models from itunesdb.web import schemas @pytest.fixture def album_ambient_1(db: Session, genre_ambient: models.Genre) -> models.Album: return crud.create_album( schema...
#!/usr/bin/python # Copyright 2015 Huawei Devices USA 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 r...
import province import re pop_types = { "aristocrats" : (11, 40, 93), "artisans" : (127, 3, 3), "bureaucrats" : (136, 136, 136), "capitalists" : (18, 129, 10), "clergymen" : (234, 227, 40), "clerks" : (240, 240, 240), "craftsmen" : (12, 157, 162), "farme...
import click from chia.util.keychain import supports_keyring_passphrase @click.command("init", short_help="Create or migrate the configuration") @click.option( "--create-certs", "-c", default=None, help="Create new SSL certificates based on CA in [directory]", type=click.Path(), ) @click.option( ...
from common.match_symbols import Match, get_mathml_matches DEFAULT_TEX_PATH = "tex-path" DEFAULT_EQUATION_INDEX = 0 def test_matches_self(): mathml = "<mi>x</mi>" matches = get_mathml_matches([mathml]) assert len(matches) == 1 assert matches[mathml] == [Match(mathml, mathml, 1)] def test_matches_ch...
import unittest import os from lxml import etree from redi import redi file_dir = os.path.dirname(os.path.realpath(__file__)) goal_dir = os.path.join(file_dir, "../") proj_root = os.path.abspath(goal_dir)+'/' DEFAULT_DATA_DIRECTORY = os.getcwd() class TestCreateEmptyEventsForOneSubject(unittest.TestCase): def s...
from app import app, db from counter.models import * @app.route('/') def init(): counter = Counter.query.first() if not counter: counter = Counter(1) db.session.add(counter) db.session.commit() else: counter.count += 1 db.session.commit() return "<h1>Counter: " +...
# coding: utf-8 from __future__ import unicode_literals CONTROL_FILE_DATA = """ Source: nginx Section: httpd Priority: optional Maintainer: Ubuntu Developers <ubuntu-devel-discuss@lists.ubuntu.com> XSBC-Original-Maintainer: Kartik Mistry <kartik@debian.org> Uploaders: Jose Parrella <bureado@debian.org>, Fab...
from multiprocessing import Pool def MakeWorkers(function,argumentList): pool = Pool(processes=3) result = pool.map(function,argumentList) return result if __name__ == "__main__": print("Settup complete")
from __future__ import absolute_import from datetime import datetime from hashlib import sha512 class Authenticator: """ Functionality used to authenticate all requests made to Payoneer Escrow. """ def __init__(self, api_key, api_secret): """ Initialize an Authenticator. Args...
from util import * import re lines=get_file_contents("../input/day19-sample.txt", False) lines=get_file_contents("../input/day19.txt", False) d = {} rgx = {} def getrules(): global lines global d, rgx for i in range(len(lines)): if lines[i] == '8: 42': lines[i] = '8: 42 | 42 8' ...
import argparse import logging import operator from collections import Counter from collections import defaultdict logging.basicConfig(format='%(asctime)s %(message)s', level=logging.INFO) def calculate_prot_length(start, end): return (abs(int(end) - int(start)) + 1)/3.0 def test_calculate_prot_length(): as...
#!/usr/bin/env python import locale import subprocess import time import os import sys import re import socket import json ARC_PREFIX_MATCHER = 'arcadia(?:.yandex.ru)?/arc/' ARC_DIRECTORIES = '(?:/arcadia|/arcadia_tests_data|/data|/quality-eval|$)' indent = " " def print_c_header(result): result.write("#pra...
# -*- coding: utf-8 -*- from .axestuple import NamedAxesTuple from .quick_construct import MetaConstructor from .utils import set_family, HIST_FAMILY from .storage import Storage import warnings import functools import operator import histoprint import numpy as np import boost_histogram as bh from typing import Call...
import os import glob import psycopg2 import pandas as pd from sql_queries import * def process_song_file(cur, filepath): """ - Load data from a song file to the song and artist data tables """ # open song file df = pd.read_json(filepath, lines=True) # insert song record song_data = list...
""" Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ # Tests component properties that are containers import azlmbr.bus as bus import azlmbr.editor as editor impor...
# coding: utf-8 """ Basic forms. This overrides npyscreen's forms, allowing concurrent widget updates. """ import sys import curses import npyscreen from sugarui.windows.floating import HelpForm class SugarForm(npyscreen.FormBaseNewWithMenus): """ Main form with the menus. """ id = "MAIN" # npysc...
# Django Library from django.db import models from django.urls import reverse from django.utils.translation import ugettext_lazy as _ # Localfolder Library from .company import PyCompany SHARE_PRODUCT_CHOICE = ( ("no", "No Share"), ("yes_some", "Yes Some"), ('yes_all', 'Yes All') ) class BaseConfig(mode...
import unittest from api.binance import Binance, OrderSide, OrderType import utils class TestBinanceAPI(unittest.TestCase): def setUp(self): apiKey = 'vmPUZE6mv9SD5VNHk4HlWFsOr6aKE2zvsw0MuIgwCIPy6utIco14y7Ju91duEh8A' secretKey = 'NhqPtmdSJYdKjVHjA7PZj4Mge3R5YNiP1e3UZjInClVN65XAbvqqM6A7H5fATj0j' ...
import os import sys import django from django.conf import settings from django.test.utils import get_runner def run_tests(): os.environ["DJANGO_SETTINGS_MODULE"] = "open_widget_framework.test_settings" django.setup() TestRunner = get_runner(settings) test_runner = TestRunner() failures = test_ru...
# -*- coding: utf-8 -* from paths import ROOT_PATH # isort:skip from videoanalyst.config.config import cfg from videoanalyst.config.config import specify_task from videoanalyst.model import builder as model_builder from videoanalyst.pipeline import builder as pipeline_builder from videoanalyst.utils import complete_p...
from datetime import date import dateutil.parser import matplotlib.pyplot as plt import pandas as pd df = pd.read_csv('colors_2010_2022_6.txt', delimiter="\t") df = df[df['reportDate'] >= '2018'] print(df.head()) #df = df.set_index('reportDate') dates = sorted(df['reportDate'].unique()) print(dates) df2 = pd.DataFram...
def get_funky(funk_level): print(f'Turning the funk up to {funk_level}')
from flask import Flask, render_template, request, redirect, url_for, flash from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) app.secret_key = "Secret Key" #SqlAlchemy Database Configuration With Mysql app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:5271@localhost/seustudents_info' app.confi...
import abc import rpy2.rinterface from rpy2.rinterface_lib import _rinterface_capi import rpy2.robjects from rpy2.robjects.packages import (importr, WeakPackage) import rpy2_R6.utils import textwrap import typing import warnings with warnings.catch_warnings(): warnings.simplefilt...
from .compat import * from . import wconn as wpa_cli
import logging class Address(): def __init__(self, name: str = None, value: int = None, relative: int = None, indirect: bool = False): self.logger = logging.getLogger("shazzam") if name is None and value is None and indirect is None: raise ValueError("Address cannot be void") ...
x=int(input("enter any number: ")) if x%2==0: print("the no is odd") else: print('the number is even')
import itertools from io import StringIO from queue import Queue import pytest import requests from docker.errors import APIError from compose.cli.log_printer import build_log_generator from compose.cli.log_printer import build_log_presenters from compose.cli.log_printer import consume_queue from compose.cli.log_prin...
#!/usr/bin/env python3 import os from oidctest.site_setup import oidc_op_setup _distroot = os.path.abspath(os.path.join(os.path.dirname(__file__), "../../..")) _root = 'test_site' if os.path.isdir(_root) is False: os.makedirs(_root) os.chdir(_root) oidc_op_setup(_distroot)
''' @author: Rahul Tanwani @summary: Contains base test case for reusable test methods. ''' import json from django.test import TestCase from batch_requests.settings import br_settings as settings class TestBase(TestCase): ''' Base class for all reusable test methods. ''' def assert_reponse_co...
import re import requests LEGACY_VERSION_RE = re.compile(r'/(\d\.\d\.\d)/') def make_metric_tree(metrics): metric_tree = {} for metric in metrics: # We make `tree` reference the root of the tree # at every iteration to create the new branches. tree = metric_tree # Separate ...
import datetime import sys from PyQt5.QtCore import QObject, QUrl, QByteArray from PyQt5.QtQml import QQmlApplicationEngine from PyQt5.QtWidgets import QMainWindow, QApplication from ViewStuff.text_input.text_input_controller import TextInputController from CalendarStuff import Calendar from ViewStuff.default_calendar...
from __future__ import absolute_import from celery.exceptions import SecurityError from celery.security.serialization import SecureSerializer from celery.security.certificate import Certificate, CertStore from celery.security.key import PrivateKey from . import CERT1, CERT2, KEY1, KEY2 from .case import SecurityCase...
# Copyright 2019-2020 the .NET Foundation # Distributed under the terms of the revised (3-clause) BSD license. """Interacting with the WWT Communities APIs.""" import json import os.path import requests import sys from urllib.parse import parse_qs, urlparse from . import APIRequest, Client, enums __all__ = ''' Comm...
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (c) 2021 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.apache.org/licenses/LICENSE-2.0 # # Unl...
# import the necessary packages from keras.models import Sequential from keras.layers.convolutional import Conv2D from keras.layers.core import Activation from keras.layers.core import Flatten from keras.layers.core import Dense from keras import backend as K class ShallowNet: @staticmethod def build(width, h...
import re from contextlib import redirect_stdout from io import StringIO from typing import Union, Optional from rdflib import Graph, RDF, Namespace from rdflib.compare import to_isomorphic, IsomorphicGraph, graph_diff from biolinkml.meta import BIOLINKML, META # TODO: Find out why test_issue_namespace is emitting g...
import torch from toolz import curry @curry def weighted_loss(weight, x, y): # return torch.mean(torch.pow(x - y, 2).mul(weight.float())) return torch.mean(torch.abs(x - y).mul(weight.float())) @curry def dynamic_loss(truth, pred, weights=None): x = truth['prognostic'] y = pred['prognostic'] to...
# coding=utf-8 # Author: Diego González Chávez # email : diegogch@cbpf.br / diego.gonzalez.chavez@gmail.com # # Resistance Controller # # TODO: # Make documentation import time import numpy __all__ = ['ResistanceController'] class ResistanceController(object): # Controllador de SourceMeter para medidas de resi...
#!/usr/bin/env python # encoding: utf-8 """ File name: project.py Function Des: ... ~~~~~~~~~~ author: 1_x7 <lixuanqi1995@gmail.com> <http://lixuanqi.github.io> """ from flask_restful import Resource, marshal_with from app.handler.project import get_all_projects from app.utils.fields.project import...
from django.core.management.base import BaseCommand, CommandError from cddp.models import CptCadastreScdb from shack.utils import copy_cddp_cadastre, prune_addresses class Command(BaseCommand): help = 'Undertakes copy of cadastre data from a database connection' def add_arguments(self, parser): pars...
import dataclasses import datetime import io import pathlib import pickle import pytest import pandas as pd import numpy as np import structlog from datapublic.common_fields import CommonFields from datapublic.common_fields import DemographicBucket from datapublic.common_fields import FieldName from datapublic.common...
""" Test for the SmartThings lock platform. The only mocking required is of the underlying SmartThings API object so real HTTP calls are not initiated during testing. """ from pysmartthings import Attribute, Capability from pysmartthings.device import Status from homeassistant.components.lock import DOMAIN as LOCK_DO...
# -*- coding:utf-8 -*- # /usr/bin/env python """ Date: 2021/5/14 17:52 Desc: """
import re text = input() new_text = re.sub(r"(.)\1+", r"\1",text) print(new_text)
''' MIT License Copyright 2019 Oak Ridge National Laboratory 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, mer...
import asyncio import datetime import sqlite3 from functools import partial from pathlib import Path from typing import Union from .goal import Goal from .reminder import Reminder from .reminder_day import ReminderDay from .reminder_time import ReminderTime from .unlocks import Unlock from .farmertown import ( Fa...