content
stringlengths
5
1.05M
import json def readJsonFile(fileName): json_data = open(fileName).read() data = json.loads(json_data) return data def writeJsonFile(fileName,data): with open(fileName,'w+') as file: json.dump(data,file,indent=4)
#!/usr/bin/env python import sys, getopt import glob import math import numpy as np import pandas as pd from matplotlib import pyplot as plt from matplotlib import gridspec from matplotlib.patches import Ellipse import mpl_toolkits.axisartist as AA from mpl_toolkits.axes_grid1 import host_subplot from scipy.interpolat...
import numpy as np def _label_axes(ax, x_label, y_label, fontsize=20, rotate_x_ticks=True): ax.set_xlabel(x_label, fontsize=fontsize) ax.set_ylabel(y_label, fontsize=fontsize) if rotate_x_ticks: from matplotlib.artist import setp setp(ax.get_xticklabels(), rotation=90) def plot_contour(x, y...
# encoding:utf-8 -*- import hashlib import MySQLdb import sys import datetime reload(sys) sys.setdefaultencoding("utf-8") host = "127.0.0.1" user = "root" password = "root" database = "Blog" charset = "utf8" def open(): conn = MySQLdb.connect(host, user, password, database, charset=charset) cursor = conn.cu...
import asyncio import functools import async_timeout from thriftpy2.thrift import TMessageType from .protocol import TBinaryProtocol from .util import args2kwargs from .errors import ConnectionClosedError, ThriftAppError from .log import logger async def create_connection( service, address=("127.0.0.1", 600...
from builtins import map from builtins import range from copy import deepcopy from itertools import product from sqlalchemy.sql import select from fonduer.models import TemporaryImage, TemporaryDetailedImage from fonduer.snorkel.candidates import CandidateSpace, Ngrams from fonduer.snorkel.models import Candidate from...
""" Problem 2_7: Heron's formula for computing the area of a triangle with sides a, b, and c is as follows. Let s = .5(a + b + c) --- that is, 1/2 of the perimeter of the triangle. Then the area is the square root of s(s-a)(s-b)(s-c). You can compute the square root of x by x**.5 (raise x to the 1/2 power). Use an inpu...
class FromFile: def __init__(self, filepath, new_lines = False): self.filepath = filepath with open(self.filepath, "r") as readfile: self.lines = readfile.readlines() if new_lines: for i in range(len(self.lines)): self.lines[i] = self.lines...
from tests.utils import build_sphinx, assert_doc_equal, parse_doc def test_headings(common_src_dir, expected_common_dir): out_dir = build_sphinx(common_src_dir, ['headings']) assert_doc_equal( parse_doc(out_dir, 'headings'), parse_doc(expected_common_dir, 'headings'), )
from collections import Counter import io import json import os from typing import Dict _TABLE_HEADER = "\n|Ranking|Solver|Score|\n|---:|:---|---:|\n" class BayesmarkReportBuilder: def __init__(self) -> None: self._solvers: Counter = Counter() self._datasets: Counter = Counter() self._m...
import pytest import os import json import time from os.path import exists from mamba.core.context import Context from mamba.core.msg import Empty from mamba.component.gui.msg import RunAction from mamba.component.gui.tk.save_view_tk import SaveViewComponent from mamba.component.gui.tk import MainWindowTk from mamba.c...
from django.views.generic import ListView, DetailView, TemplateView import markdown from apps.users.models import CustomUser from apps.tools.models import Tool from apps.shop.models import Product from .models import Tag, Article class HomepageListView(ListView): model = Article context_object_name = "artic...
import PySimpleGUI as sg class UI: pad = (30, 2) layout = [ [sg.Button('PWN', size=(10, 2), pad=pad), sg.Button('Inject', size=(10, 2), pad=pad), sg.Button( 'Reset', size=(10, 2), pad=pad), sg.Button('Quit', size=(10, 2), pad=pad)], [sg.Text(size=(100, 15), key='-OUTPUT-', back...
#!/usr/bin/env python3 import re import pandas import subprocess import sys def run_and_get_breakdown(cmd): ret = subprocess.check_output(cmd.split()).decode(sys.stdout.encoding) pattern = 'compute Time = .*? \((?P<percent>[01]\.[0-9][0-9][0-9])' compute = re.search(pattern, ret) compute = compute.group('perc...
from selenium.common.exceptions import TimeoutException from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.ui import WebDriverWait # type: ignore from .....constant import timeout from .....exception.timeout import WaitForPageTitleToChangeTimeoutException def wait_until...
#!/usr/bin/env python import sys from argparse import ArgumentParser from argparse import ArgumentDefaultsHelpFormatter try: from pypacket_dissector import encoder as en except: import encoder as en def main(): ap = ArgumentParser(description="a packet encoder.", formatter_class=A...
from simulation.motor.base_motor import BaseMotor from simulation.motor.basic_motor import BasicMotor
# Specify which file (without .py extension) in the arts folder should be used artFile = "art" #artFile = "test" # Speed of art speed = 0.0043 #0.004 # Print code in the beginning codePrint = False codingSpeed = 0.001 codeColor='red' # Audio playAudio = True audio = 'HappyBirthday.mp3' # Random colo...
# -*- coding: utf-8 -*- #Coded By Ashkan Rafiee https://github.com/AshkanRafiee/PingWidget/ ################Libraries################ import PySimpleGUI as sg import webbrowser import time import threading from pythonping import ping ################Libraries################ status = None mypings1 = [] mypings2 = [] ...
__author__ = "Andre Barbe" __project__ = "Auto-GTAP" __created__ = "2018-3-15" from typing import List class ImportCsvSl4(object): """Imports the CSV Files created by SLTOHT""" __slots__ = ["file_path_list"] def __init__(self, file_path_list: List[str]) -> None: self.file_path_list = file_path_...
import cv2 import numpy as np import math from util import Util as u class Prep(object): def __init__(self, path): self.__img = cv2.imread(path, cv2.IMREAD_COLOR) self.__imgray = cv2.cvtColor(self.__img, cv2.COLOR_BGR2GRAY) self.__invimgray = self.__negate() self.__ottlvl = self.__...
import argparse def options(): p = argparse.ArgumentParser(description = 'Arguments for image2image-translation training.') p.add_argument('--rec-type', help = 'reconstruction loss type (pixel / feature)', default = 'pixel') p.add_argument('--gan-loss-type', help = 'gan loss type', default = 'HINGEGAN') p.add_arg...
#!/usr/bin/python # coding: utf-8 -*- # Copyright (c) 2016, Mario Santos <mario.rf.santos@gmail.com> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'status': ['prev...
#!/usr/bin/env python from distutils.core import setup setup( name='wrench-documentation', version='2.0.0', requires=[ "sphinxcontrib.phpdomain" ] )
# Copyright 2018 Timothée Chauvin # Copyright 2017-2019 Joseph Lorimer <joseph@lorimer.me> # # Permission to use, copy, modify, and distribute this software for any purpose # with or without fee is hereby granted, provided that the above copyright # notice and this permission notice appear in all copies. # # THE SOFTWA...
from django.urls import include, re_path from rest_framework.routers import DefaultRouter from .views import OfferViewSet router = DefaultRouter() router.register('offers', OfferViewSet) urlpatterns = [ re_path('^', include(router.urls)), ]
import asyncio import unittest from unittest import IsolatedAsyncioTestCase from valheim_server.log_dog import ValheimLogDog from utils import default from mongoengine import * config = default.config() unittest.TestLoader.sortTestMethodsUsing = None class TestDeathDocument(Document): key = UUIDField(primary_key=...
import os import shutil import pandas as pd path_data = '/Users/karin.hrovatin/Documents/H3HerbstHackathon/challenge/git/thermal_barrierlife_prediction/data/' def mkdir_missing(path, clean_exist=True): if clean_exist and os.path.isdir(path): shutil.rmtree(path) if not os.path.isdir(path): os.m...
from PyQt5.QtWidgets import QWidget, QSizePolicy, QGroupBox, QVBoxLayout, QHBoxLayout, QSlider from PyQt5.QtCore import pyqtSignal, pyqtSlot, Qt from widgets.joystick import JoyStick class CameraControls(QWidget): """ Custom Qt Widget to group camera controls together. """ camControls = pyqtSignal(tuple) def __...
from . import halconfig_types as types from . import halconfig_dependency as dep name = "FEM" displayname = "External FEM" compatibility = dep.Dependency(platform=(dep.Platform.SERIES1, dep.Platform.SERIES2), mcu_type=dep.McuType.RADIO) # EFR32 category = " Radio" studio_module = { "basename" : "SDK.HAL.FEM", ...
#!/usr/bin/env python3 # -*- coding=utf-8 -*- import cv2 as cv import numpy as np """ OpenCV DNN单张与多张图像的推断 OpenCV DNN中支持单张图像推断,同时还支持分批次方式的图像推断,对应的两个相关API分别为blobFromImage与blobFromImages,它们的返回对象都 是一个四维的Mat对象-按照顺序分别为NCHW 其组织方式如下: N表示多张图像 C表示接受输入图像的通道数目 H表示接受输入图像的高度 W表示接受输入图像的宽度 """ bin_model = "../../../raspberry-...
#!/usr/bin/env python3 """Python replacement fot cat.csh. Defined as: my $fh = &HgAutomate::mustOpen(">$runDir/cat.csh"); print $fh <<_EOF_ #!/bin/csh -ef find $outRoot/\$1/ -name "*.psl" | xargs cat | grep "^#" -v | gzip -c > \$2 _EOF_ ; close($fh); """ import sys import os import gzip def gzip_str(string_...
# -*- coding: utf-8 -*- from collections import OrderedDict from django.db.models import QuerySet from django.utils.functional import SimpleLazyObject from graphene import Field, InputField, ObjectType, Int, Argument, ID, Boolean, List from graphene.types.base import BaseOptions from graphene.types.inputobjecttype imp...
# Program to scrape twitter photos, text, and usernames # May 2016 # authors: Clara Wang with significant amount of code taken from source code # source code: https://gist.github.com/freimanas/39f3ad9a5f0249c0dc64 # NOTE: if there are NO tweets associated with a Twitter handle, no CSV will be produced import tweepy #...
from notebooks.feature_extractors import BaseSegmentExtractor from typing import List class WordCounter(BaseSegmentExtractor): def _segment_extract(self, segment: str) -> List[float]: return [float(len(segment.split()))]
from typing import Dict from presidio_anonymizer.operators import Operator, OperatorType class ReplaceInHebrew(Operator): """ An instance of the Operator abstract class (@Presidio). For each recognized entity ,this custom replace it by custom string depending on its entity type. """ def operate(s...
""" Dissimilarity measures for clustering """ import numpy as np def matching_dissim(a, b, **_): """Simple matching dissimilarity function""" return np.sum(a != b, axis=1) def jaccard_dissim_binary(a, b, **__): """Jaccard dissimilarity function for binary encoded variables""" if ((a == 0) | (a == 1...
#!/usr/bin/env python3 import FTree as ft if __name__ == "__main__": z = ft.Gates() G4 = z.or_gate([["4"]], [["5"]]) G5 = z.or_gate([["6"]], [["7"]]) G6 = z.or_gate([["6"]], [["8"]]) G2 = z.and_gate(G4, G5) G3 = z.or_gate([["3"]], G6) G1 = z.or_gate(G2, G3) G0 = z.or_gate([["1"]], z.or...
#!/usr/bin/env python3 # 用于处理用户信息及操作 import os import sys import json as JSON from database_handle import database_handle as dh from encrypt_and_decrypt import encrypt_and_decrypt_for_users as eadfu class handle_users(): def __init__(self): self.dh = dh() self.eadfu = eadfu() def add_user(self, info={"basic"...
from .evaluation import Evaluation from .eval_from_dict import EvaluationFromDict from .eval_array_xr import EvaluationFromArrayXr
from django.apps import AppConfig from django.db import connection from django.db.models.signals import post_migrate def index_adjustments(sender, using=None, **kwargs): """ Remove -like indexes (varchar_pattern_ops) on UUID fields and create version-unique indexes for models that have a VERSION_UNIQUE at...
import _config import _utils CONFIG_PATH = "config.toml" def main(): config = _config.read(CONFIG_PATH) for path_name in [x.in_ for x in config.directorios]: _utils.list_jpg_files_in_dir(path_name) if __name__ == "__main__": main()
# Generated by Django 2.2.11 on 2020-04-06 11:19 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('resources', '0088_auto_20200319_1053'), ('resources', '0114_auto_20200317_0836'), ] operations = [ ]
# http://www.pythonchallenge.com/pc/return/cat.html # http://www.pythonchallenge.com/pc/return/uzi.html import calendar import datetime def main(): valid = [] # Iterate "1__6" years to match Calendar image for year in range(1006, 2000, 10): # Calendar shows Feb 29, must be a leap year i...
# coding: utf-8 import pprint import re import six class WebImageWordsBlockList: """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the v...
# -*- coding: utf-8 -*- from south.utils import datetime_utils as datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Removing unique constraint on 'Accession', fields ['uqm_accession'] db....
import math import pyxel class Pycocam: __PI = 3.141 __PI2 = 6.283 def __init__(self, width, height): self._theta = None self.z = 0 self.focallength = 5 self.fov = 45 self.theta = 0 self.width = width self.height = height @property def thet...
# -*- coding: utf-8 -*- # MIT License # # Copyright (c) 2020 PANGAEA (https://www.pangaea.de/) # # 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 limitat...
import sys import typing import numba as nb import numpy as np @nb.njit(cache=True) def solve() -> typing.NoReturn: ... def main() -> typing.NoReturn: s = input() if s[-2:] == 'er': print('er') else: print('ist') main()
def select2_processor(idps): """ A simple processor for Select2, to adjust the data ready to use for Select2. See https://select2.org/data-sources/formats """ def change_idp(idp): idp['id'] = idp.pop('entity_id') idp['text'] = idp.pop('name') return idp return [change_id...
#!/usr/bin/env python """ from http://wdc.kugi.kyoto-u.ac.jp/igrf/gggm/ """ import pytest from geo2mag import geo2mag @pytest.mark.parametrize( "glat,glon,mlat,mlon", [ (79.3, 288.59, 88.880248, 11.379883), ( [79.3, 79.3, 0, 90, -90, 45], [288.59, 288.583, 0, 90, -90, 1...
import os import glob import pandas as pd from datetime import date from tempfile import mkdtemp from shutil import rmtree from unittest import main, TestCase from serenata_toolbox.chamber_of_deputies.dataset import Dataset class TestChamberOfDeputiesDataset(TestCase): def setUp(self): self.path = mkdtem...
import warnings from .exceptions import HumioMaxResultsExceededWarning, HumioBackendWarning def warning_on_one_line(message, category, filename, lineno, file=None, line=None): return "%s:%s: %s: %s\n" % (filename, lineno, category.__name__, message) def patched_poll_until_done(self, **kwargs): raise NotImpl...
from flask import Blueprint, render_template from solarvibes.models import Farm, Field, Pump, Agripump from flask_login import current_user from flask_security import login_required from datetime import datetime, timezone settings = Blueprint( 'settings', __name__, template_folder="templates" ) #########...
#!/usr/bin/env python from shutil import copytree, copy2 from pathlib import Path fg_src_dir = Path("~/Goodhertz/fontgoggles/Lib/fontgoggles").expanduser() fg_dst_dir = Path(__file__).parent / "drafting/fontgoggles" fg_dst_dir.mkdir(exist_ok=True) copy2(fg_src_dir.parent.parent / "LICENSE.txt", fg_dst_dir / "LICENS...
from unittest.mock import MagicMock, patch from tornado.testing import AsyncTestCase, gen_test from fixtures.exploits import Exploit from structs import Scan, TransportProtocol, Port, ScanContext from utils.task import Task class TaskTest(AsyncTestCase): """ Testing task behaviour """ @patch('utils...
n = int(input("Enter the number whose factorial you want : ")) def fac(n): if n >= 0: y = 1 else: y = -1 x = 1 for i in range(y, n+y, y): x = x*i return x x = fac(n) print("Factorial of {} is : ".format(n), x)
from time import time import pytest from vk import API from vk.exceptions import VkAPIError def test_missed_v_param(access_token, v): """ Missed version on API instance """ api = API(access_token) with pytest.raises(VkAPIError, match=r'8\. Invalid request: v is required'): api.getServer...
#!/usr/bin/env python import numpy as np import sys def main(): # the array integers refer to the length of cubes in initial state stack1 = range(1, int(sys.argv[1]) + 1) stack2 = [] stack3 = [] global Game Game = np.array([stack1, stack2, stack3]) print("Initial Game State: \n") ...
''' Max of 3 numbers ''' number_1 = int(input()) number_2 = int(input()) number_3 = int(input()) if (number_1 < number_2): number_1 = number_2 if (number_1 < number_3): print(number_3) else: print(number_1)
# coding=utf-8 # Copyright 2017 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import os import shu...
#!/usr/bin/env python # -*- encoding: utf-8 -*- __author__ = 'andyguo' from dayu_file_format.curve.data_structure import Point2D import pytest class TestPoint2D(object): def test___init__(self): p = Point2D(0, 1) assert p.x == 0 assert p.y == 1 assert type(p.x) is float a...
import matplotlib.pyplot as plt time = [600, 800, 1000, 1200, 1400, 1600, 1800, 2000, 2200, 2400] newreno = [0.077068, 0.021771, 0.046267, 0.043259, 0.024609, 0.021640, 0.020837, 0.018810, 0.015794, 0.018096] vegas = [0.305460, 0.183872, 0.162933, 0.135204, 0.103017, 0.126727, 0.089226, 0.087788, 0.079121, 0.079745] ...
class CordParser: """ the file should end in .cord, and should contains the direction and the angles to turn. f -> forward b -> backward r -> right l -> left u -> stop drawing p -> start drawing The file should be written as: f=100 r=20 b=50 ..etc """ def __...
# -*- coding: utf-8 -*- """ gogo.vos.config ~~~~~~~~~~~~~~~ Used to load grpc server config. """ import logging import sys import yaml from gogo.consts import REGISTRY_ENABLED, APP_CONFIG_PATH from gogo.exc import AppConfigLoadFailException from gogo.utils import EnvvarReader, cached_property from gogo.vos.consts i...
#!/usr/bin/env python # Copyright 2021 Calico LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ...
def enable_live_preview(): return """ <script> <script> """
# Generated by Django 3.1.7 on 2021-04-14 19:07 from django.conf import settings from django.db import migrations, models import django.db.models.deletion import markdownx.models import uuid class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(setti...
import json import pytest from mayday.controllers.redis import RedisController USER_ID = 123456789 ACTION = 'test' @pytest.mark.usefixtures() class Test: @pytest.fixture(autouse=True, scope='function') def before_all(self): pass def test_redis_key(self): redis = RedisController() ...
from dataclasses import dataclass from typing import Optional from typing import Tuple from joblib import delayed from joblib import Parallel import numpy as np import pytest from sklearn.base import ClassifierMixin from sklearn.base import clone from sklearn.base import is_classifier from sklearn.ensemble import Grad...
from .handler import connect_websocket, spawn, _javascript_call from bottle.ext import websocket as bottle_websocket import bottle def start(port = 4949, block = True, quiet = True): def run_server(): return bottle.run( port = port, quiet = quiet, host = "0.0.0.0", ...
from socrata.operations.utils import get_filename, SocrataException from socrata.operations.operation import Operation class ConfiguredJob(Operation): def run(self, data, put_bytes, filename = None): filename = get_filename(data, filename) (ok, rev) = self.properties['view'].revisions.create_using...
# -*- Mode: python; tab-width: 4; indent-tabs-mode:nil; coding:utf-8 -*- # vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 # # MDAnalysis --- https://www.mdanalysis.org # Copyright (c) 2006-2017 The MDAnalysis Development Team and contributors # (see the file AUTHORS for the full list of names) # # Released under t...
""" Test blockpy directive """ __author__ = 'Jovan' import unittest import time from unittest import TestCase from runestone.unittest_base import module_fixture_maker, RunestoneTestCase from selenium.webdriver import ActionChains from selenium import webdriver from selenium.webdriver.common.keys import Keys from sele...
# -*- coding: utf-8 -*- import wtforms from flask import render_template, request, Markup, abort, flash, redirect, escape, url_for, make_response from .. import b__ as __ from .form import Form from .fields import SubmitField class ConfirmDeleteForm(Form): """ Confirm a delete operation """ # The lab...
#!/usr/bin/env python import argparse import json import radix import re import subprocess from logger import get_logger from json_schema import json_schema from json import JSONDecoder, JSONDecodeError from netaddr import IPAddress, IPNetwork, IPSet from filelock import FileLock log = get_logger(path="/etc/artemis/...
"""The ``metric_stats`` module provides an abstract class for storing statistics produced over the course of an experiment and summarizing them. Authors: * Peter Plantinga 2020 * Mirco Ravanelli 2020 """ import torch from joblib import Parallel, delayed from speechbrain.utils.data_utils import undo_padding from spee...
import flash from flash import download_data from flash.text import SummarizationData, SummarizationTask if __name__ == "__main__": # 1. Download the data download_data("https://pl-flash-data.s3.amazonaws.com/xsum.zip", 'data/') # 2. Load the data datamodule = SummarizationData.from_files( tra...
import logging import os import time from brownie import chain from yearn.treasury.treasury import Treasury from yearn.outputs import victoria logger = logging.getLogger('yearn.treasury_exporter') sleep_interval = int(os.environ.get('SLEEP_SECONDS', '0')) def main(): treasury = Treasury(watch_events_forever=Tru...
import time import vlc player = vlc.MediaPlayer("background-sounds/countdown.mp4") player.play() time.sleep(10) player.stop()
"""Helper module for handling OS related commands.""" import os import platform import subprocess from phytoolkit.exception.installationexception import InstallationException class OsHelper: """Runs shell commands.""" def __init__(self, config): self.config = config self.console = config.con...
#!/usr/bin/env python3 ''' Copyright 2018, VDMS Licensed under the terms of the BSD 2-clause license. See LICENSE file for terms. API for Host Information Should return data about the host & return the collections for this particular host. ```swagger-yaml /hostcollections/{host_id}/ : x-cached-length: "Every Midnig...
import sys import io import time import pprint input_txt = """ 6 30 35 35 15 15 5 5 10 10 20 20 25 """ sys.stdin = io.StringIO(input_txt) tmp = input() start = time.time() # copy the below part and paste to the submission form. # ---------function------------ def least_multiplication(mtx): ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @File : fib_coroutine.py # @Author: yubo # @Date : 2019/1/15 # @Desc : from bisect import insort from collections import deque from functools import partial from time import time import selectors import sys import types from functools import wraps def log_execution_...
class Solution(object): def intersect(self, nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :rtype: List[int] """ sect = {} res = [] for num in nums1: if num in sect: sect[num][0] += 1 else: ...
# @file Longest Palindrome # @brief given string, find length of longest possible palindrome # https://leetcode.com/problems/longest-palindrome ''' Given a string which consists of lowercase or uppercase letters, find the length of the longest palindromes that can be built with those letters. This is case sensitive...
#!/usr/bin/env python import os import sys from distutils.text_file import TextFile from skbuild import setup # Add current folder to path # This is required to import versioneer in an isolated pip build sys.path.append(os.path.dirname(os.path.abspath(__file__))) import versioneer # noqa: E402 with open('README....
from argparse import Namespace import chainer import numpy import pytest import torch import espnet.lm.chainer_backend.lm as lm_chainer from espnet.nets.beam_search import beam_search from espnet.nets.lm_interface import dynamic_import_lm import espnet.nets.pytorch_backend.lm.default as lm_pytorch from espnet.nets.sc...
# Given a number sequence, find the minimum number of elements that should be # deleted to make the remaining sequence sorted. # Longest increasing subsequence pattern import math def MD(A): # Ini first, to create the matrix # Here we are looking for minimum, so we initialize T to infinity T = ...
from django.contrib.auth.models import Group from rest_framework import serializers from apps.teachers.models import Teacher from apps.users.models import User, House from apps.users.serializers import BasicUserSerializer class TeacherSerializer(serializers.Serializer): id = serializers.IntegerField(source='user...
# Generated by Django 3.0.2 on 2020-01-17 14:55 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('cookbook', '0007_auto_20...
# Licensed under an MIT open source license - see LICENSE ''' Test functions for PSpec ''' from unittest import TestCase import numpy as np import numpy.testing as npt from ..statistics import PowerSpectrum, PSpec_Distance from ._testing_data import \ dataset1, dataset2, computed_data, computed_distances cla...
# TensorFlow & Keras import tensorflow as tf from tensorflow import keras # Numpy & Matplot import numpy as np import matplotlib.pyplot as plt # Version >= 1.12.0 print(tf.__version__) # Download fashion dataset fashion_mnist = keras.datasets.fashion_mnist (train_images, train_labels), (test_images, test_labels) = f...
"""Curvature computation for a circular droplet. (5 seconds) For particles distributed in a box, an initial circular interface is distinguished by coloring the particles within a circle. The resulting equations can then be used to check for the numerical curvature and discretized dirac-delta function based on this art...
#!/usr/bin/env python # Source: https://www.geeksforgeeks.org/python-image-classification-using-keras/ # Author: Nitish_Gangwar - https://auth.geeksforgeeks.org/user/Nitish_Gangwar/articles # Importing all necessary libraries from keras.preprocessing.image import ImageDataGenerator from keras.models import Sequenti...
"""OPM dataset.""" from .opm import data_path, get_version
"""Calculate maximum lyapunov exponent of different coupled physical system. The region below zero is s.""" import numpy as np import matplotlib.pyplot as plt from scipy.integrate import odeint def lyap(cl): def diff_chua(u): k = 1 alpha = -0.1 beta = -1 gamma = 0.1 a = 1 ...
from datetime import datetime, timedelta from typing import List, Optional import dateutil.relativedelta from container import ServerContainer from dependency_injector.wiring import Provide, inject from fastapi import APIRouter, Depends from starlette import status from carbonserver.api.dependencies import get_token_...
from .common import * # noqa DEBUG = True ALLOWED_HOSTS = ['*'] # Database DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'db.sqlite3', } } # Security SESSION_COOKIE_SECURE = False CSRF_COOKIE_SECURE = False
import torch import torch.nn as nn from torch2trt.torch2trt import * from torch2trt.module_test import add_module_test import numpy as np import ctypes try: ctypes.CDLL('libtorch2trt_plugins.so') def create_reflection_pad_2d_plugin(paddingLeft, paddingRight, paddingTop, paddingBottom): registry = tr...