content
stringlengths
5
1.05M
from app import app from app.models import User, Dataset @app.shell_context_processor def make_shell_context(): return {'db': db, 'User': User, 'Dataset': Dataset} if __name__ == "__main__": app.run(host="0.0.0.0")
import torch import torch.nn as nn import torch.nn.functional as F from torch_scatter import scatter_add from typing import Optional from graph import Graph class MLP(nn.Module): def __init__(self, d_in: int, d_out: int): """Two layer perception with sigmoid non linearity Args: d_in ...
from __future__ import print_function import torch import numpy as np import os def mkdir(path): if not os.path.exists(path): os.makedirs(path) MESH_EXTENSIONS = [ '.vtk', ] def is_mesh_file(filename): return any(filename.endswith(extension) for extension in MESH_EXTENSIONS) def pad(input_arr, ...
"""End to end testing on simple linear models""" # pylint: disable=C0103 # pylint: disable=C0325 # pylint: disable=E1101 import numpy as np from scipy.stats import zscore from sklearn.linear_model import LogisticRegression as sk_LogisticRegression from sklearn.linear_model import LinearRegression as sk_LinearRegres...
# -*- coding: utf-8 -*- # Автор: Гусев Илья # Описание: Разметка по грамматическим значениям import os from typing import List, TextIO from sentence_splitter import SentenceSplitter from rnnmorph.predictor import RNNMorphPredictor from rupo.main.tokenizer import Tokenizer, Token class Morph: @staticmethod ...
""" @ authors: Andrei Militaru, Jeanne Chaverot @ date: 5th of April 2020 """ import numpy as np class CompartmentManager(object): """ Class that lets multiple cells interact with one another and evolve. In principle, no specific model has been assumed, although for the moment only the SIR has been i...
import argparse import logging import json import time from typing import List, NamedTuple, Any import gevent from geventwebsocket import WebSocketServer, WebSocketApplication, Resource from collections import OrderedDict log = logging.getLogger(__name__) class SequenceEmitterApp(WebSocketApplication): def o...
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! import grpc from . import thermo_pb2 as thermo__pb2 class TemperatureServerStub(object): """Missing associated documentation comment in .proto file""" def __init__(self, channel): """Constructor. Args: channel...
#!/usr/bin/env python # Copyright (c) 2013-2016 CORE Security Technologies # # This software is provided under under a slightly modified version # of the Apache Software License. See the accompanying LICENSE file # for more information. # # SMB Relay Server # # Author: # Alberto Solino (@agsolino) # # Description: # ...
import sublime, sublime_plugin from .logic import indent_arguments, find_arguments_region, format_arguments class _AbstractBaseCommand(sublime_plugin.TextCommand): def run(self, edit): for region in self.view.sel(): start, end = find_arguments_region(edit, self.view, region.b) region = sublime.Regio...
# Copyright (c) 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. class TimelineEvent(object): """Represents a timeline event.""" def __init__(self, category, name, start, duration, args=None): self.category = c...
# # PySNMP MIB module A3COM-HUAWEI-VOIF-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/A3COM-HUAWEI-VOIF-MIB # Produced by pysmi-0.3.4 at Wed May 1 11:07:48 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (def...
#!/usr/bin/env python3 from argparse import ArgumentParser from glob import glob from os import environ from os.path import basename from sys import argv from vang.maven.pom import get_pom_info from vang.nexus3.upload import upload from vang.nexus3.utils import get_artifact_base_uri, get_pom_path def get_pom_publis...
from django.shortcuts import render, redirect from django.conf import settings #from django.contrib.auth.models import User from django.contrib import auth from .forms import CustomUserCreationForm, LoginForm, CustomUserChangeForm, ChangeForm from .models import CustomUser # from django.forms.models import model_to_dic...
import pymongo conn = pymongo.MongoClient('mongodb://db:27017') db = conn.get_database('example') collection = db.get_collection('example') print('Find all documents') results = collection.find() [print(result) for result in results] print('Find all documents which key is "cbchoi"') results = collection.fin...
import pygame import pygame.gfxdraw import math def main(): pygame.init() display = pygame.display.set_mode((800, 800), pygame.RESIZABLE) clock = pygame.time.Clock() process_interrupted = False pygame.display.set_caption("Segment Snake") pygame.display.set_icon(pyga...
try: from io import BytesIO, TextIOWrapper, StringIO except ImportError: try: from cStringIO import StringIO as BytesIO except ImportError: from StringIO import StringIO as BytesIO from tempfile import NamedTemporaryFile import os import pickle import json import sys import unittest from ...
from ..factory import Type class userTypeDeleted(Type): pass
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import os import argparse from natsort import natsorted import funannotate.library as lib from Bio import SeqIO from collections import OrderedDict def scaffold2Dict(input): # get scaffold names/lengths scaffLen = {} with open(input, 'r') as seqin:...
from DFS import DFS class DFSOrders(DFS): def __init__(self, graph): assert graph.directed, "must be digraph" super(DFSOrders, self).__init__(graph) self.preOrder = [] self.postOrder = [] def dfs(self, u): self.marked[u] = True self.preOrder.append(u) for v in self.g.adj[u]: if not self.marked[v...
from paramak import ExtrudeStraightShape from paramak.utils import cut_solid class BlanketCutterParallels(ExtrudeStraightShape): """Creates an extruded shape with a parallel rectangular section repeated around the reactor. The shape is used to cut other components (eg. blankets and firstwalls) in order t...
from django.urls import path from . import views urlpatterns= [ #Books paths path('',views.index,name="index"), #home page path('newBook1/',views.newBook1,name="newBook1"), path('newBook2/',views.newBook2,name="newBook2"), path('allBookNames/',views.allBookNames,name="allBooksNames"), path('da...
# Generated by Django 3.1.8 on 2021-04-22 16:04 import bookwyrm.models.fields from django.conf import settings from django.db import migrations import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ("bookwyrm", "0068_ordering_for_list_items"), ] operations = [...
# p46.py str1 = input().split() str1 = list(map(int, str1)) n = str1[0] m = str1[1] q = str1[2] light = [[0] * m for i in range(n)] str2 = [] sum1 = 0 for i in range(0, q): str2 = input().split() str2 = list(map(int, str2)) if str2[0] == 1: if light[str2[1] - 1][str2[2] - 1] == 0:...
import cv2 import numpy as np from cv2 import aruco from obj_loader import * import sys import math markerLength = 0.25 # Here, our measurement unit is centimetre. obj_path = sys.argv[1] obj = OBJ(obj_path, swapyz=True) ref_image = np.array([[0, 0], [1000, 0], [0, 1000], ...
from . import errors from .resources import SubscriptionV1, CreditcheckV2, CheckoutSessionV1, \ Resource from .connector import Connector from .client import Client from .utils import decode_date, decode_attachment, encode_attachment __all__ = [ "Client", "Connector", "Resource", "errors", "decode_date", "...
from io import BytesIO import logging from . import codec, fs log = logging.getLogger(__name__) class File: """File object. :param file_name: Any file name. """ def __init__(self, file_name): self.file_name = file_name self.fs = fs.get_fs(file_name)(file_name) self.codec = ...
# Generated by Django 3.0.6 on 2020-05-22 18:40 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('cor', '0010_component_recicletype'), ] operations = [ migrations.AlterField( model_name='component', name='recicleTy...
from __future__ import print_function, division, absolute_import, unicode_literals __author__ = 'Alexandre Drouin' import h5py as h import json from numpy import float from ..spectrum import Spectrum from ..utils import _is_mz_equal, _is_mz_precision_equal, _is_metadata_type_dict def hdf5_save(file_name, spectra, ...
import pytest from ..attributes_query import ( QueryTreeToSQLBitwiseTransformer, inheritance_query, PARSER, inheritance_converter, BitwiseTreeTransformer, ) @pytest.mark.parametrize( "query,expected", [ ("mendelian", "(BITAND(col, 2) != 0)"), ("not mendelian", "(NOT ((BITAN...
import numpy as np import pytest from foolbox.v1.attacks import PrecomputedAdversarialsAttack as Attack def test_attack(bn_adversarial): adv = bn_adversarial image = adv.unperturbed input_images = image[np.newaxis] output_images = np.zeros_like(input_images) attack = Attack(input_images, output...
##################################################### ########## Welcome to TensorFlow World ############## ##################################################### # The tutorials in this section is just a start for going into TensorFlow world. # The TensorFlow flags are used for having a more user friendly environment....
import json import requests from transcriptic.cli import cli from ..helpers.fixtures import * from ..helpers.mockAPI import MockResponse # Structure of the response object from SCLE def queue_test_success_res(sessionId="testSessionId"): return {"success": True, "sessionId": sessionId} fake_valid_URL = "somet...
import bpy import bmesh import mathutils import math from enum import Enum from mathutils import Vector from . import (bindings, lights, materials, util) from ctypes import * from .bindings import * from .util import * from .lights import add_lights from .materials import add_materials NEE_INTEGRATORS = ['PT', 'LT'] M...
# Generated by Django 2.0 on 2018-02-10 12:39 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('main', '0002_auto_20180209_1654'), ] operations = [ migrations.AddField( model_name='staff', name='profilepic', ...
import pyautogui from helper.win32 import waitForT, pause from PIL import Image from functools import reduce from io import BytesIO import win32clipboard # Contains all helper screenshot code # Takes a screenshot on T press def takeShot(TL, OFF): waitForT() # Take a screenshot image = pyautogui.screensh...
import csv disc = [] with open("/home/sean/Repos/mint/data/raw/credit_history.csv") as f: cf = csv.reader(f) for line in cf: disc.append(line) disc = [d[1:] for d in disc] disc = disc[1:] account_name = "Credit Card" def fix_date(dstr): items = reversed(list(map(str, dstr.split("/")))) return...
from sprezz.views.webfinger import webfinger @webfinger.rel('http://openid.net/specs/connect/1.0/issuer') async def openid_issuer(request, account, resource, rels=None): return [{ 'rel': 'http://openid.net/specs/connect/1.0/issuer', 'href': 'https://{netloc}'.format( netloc=request.app...
# remove duplicates in two lists def removeDups0(L1, L2): # this block of code doesn't work as expected for a in L1: if a in L2: L1.remove(a) def removeDups1(L1, L2): l = len(L1) while l > 0: if L1[0] in L2: L1.remove(L1[0]) l -= 1 def re...
import csv import io from django.utils.translation import ugettext_lazy as _ from pretalx.common.exporter import BaseExporter from pretalx.submission.models import SubmissionStates class CSVSpeakerExporter(BaseExporter): public = False icon = 'fa-users' identifier = 'speakers.csv' verbose_name = _(...
habitacion = {'Habitacion1': 'HABI1', 'Habitacion2': 'HABI2', 'Habitacion3': 'HABI3', 'Cocina': 'COCIN', 'Comedor': 'COMED', 'Living': 'LIVI1', 'Living': 'LIVI2', 'Patio': 'PATIO', 'Jardin': 'JARDI', 'Quincho1': 'QUIN1', 'Quincho2': 'QUIN2', 'Pileta': 'PILET'} def translate(n): for nLargo, nCorto in habitacion...
import pytest from erp.provider import search def test_search_sort_and_filter(): results = search.sort_and_filter_results( "34830", [ {"siret": "1", "code_insee": "42000", "coordonnees": [1, 1]}, {"siret": "2", "code_insee": "34830", "coordonnees": [1, 1]}, {"s...
from build_tools.config import LAB_FOLDER_NAME from lectures.model import LectureNotes, Lecture, LectureResource from resources.models import RESOURCES def get_project_overview_lecture() -> Lecture: project_title = 'Project Grading Overview' project_num = 0 title = f'Project {project_num} - {project_title...
import sys import argparse def init_argparse(): parser = argparse.ArgumentParser( description="Change retraction speed or retraction distance gradually by a specific layer height in gcode files" ) parser.add_argument('-m', '--mode', required=True, choices=['speed', 'distance'], ...
# 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 ...
import os subfolders= [f.path for f in os.scandir(".") if f.is_dir()] for i in subfolders: os.chdir(f"{i}") if os.path.exists("current.ckpt"): os.remove("current.ckpt") if os.path.exists("visual_bert_final.pth"): os.remove("visual_bert_final.pth") if os.path.exists("models"): o...
# Generated by Django 3.1 on 2020-09-03 05:08 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('application', '0007_discussion'), ] operations = [ migrations.DeleteModel( name='Discussion', ), ]
#!/usr/bin/env python """ # # # File Name: dataset.py # Description: """ import time import os import numpy as np import pandas as pd import scipy from scipy.io import mmread import scanpy as sc import anndata as ad class SingleCellDatasetDRA(): """ "10x_68k", "10x_73k", "Macosko", "Zeisel", "data1", "yan" ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Distributed under the terms of the MIT License. """ Script used on 10/10/18 to re-search PUBCHEM for all molecules with multiple entries for IUPAC, logP and complexity. Author: Andrew Tarzia Date Created: 10 Oct 2018 """ from PUBCHEM_IO import get_logP_from_name, get...
from fastapi import FastAPI from fastapi_utils.tasks import repeat_every import os from app.api.routes import kubernetes, projects, namespaces, user_actions, user_management, namespace2projecttransfer from app.db import database, engine, metadata from app.api.crud import project2external from app.api.auth0 import acce...
import numpy as np from automon.cb.cb_common_node import CbCommonNode # Implementation according to https://dl.acm.org/doi/pdf/10.1145/3226113 class CbInnerProductNode(CbCommonNode): def __init__(self, idx, func_to_monitor=None, d=2, domain=None): # func_to_monitor must be func_inner_product; howeve...
#!/usr/bin/env python2 # copyright (c) 2014 the dzcoin core developers # distributed under the mit software license, see the accompanying # file copying or http://www.opensource.org/licenses/mit-license.php. # # test -reindex with checkblockindex # from test_framework.test_framework import dzcointestframework from te...
# Copyright 2020 The TensorFlow Ranking Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ag...
# Copyright (c) 2014 Hewlett-Packard Development Company, L.P. # 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/LICEN...
class DfsStructure(object): def __init__(self, monitored_area): self.monitored_area = monitored_area self.is_root = False self.open_neighbors_id = None # neighbors Id : see "open" in the algorithm self.children_id = [] self.parent_id = 0 self.pseudo_children_id = []...
class LogMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): print("Before middleware") response = self.get_response(request) print("After middleware") return response
# coding: utf-8 def array_fill_keys(keys, value): return dict.fromkeys(keys, value) if __name__ == '__main__': keys = ['foo', 5, 10, 'bar'] print(array_fill_keys(keys, 'banana'))
# Third party libraries import tracers.function # Local libraries import server.utils.aio @tracers.function.trace() async def encode(string: str) -> str: result = await server.utils.aio.unblock(string.encode, 'utf-8') return await encode_bytes(result) @tracers.function.trace() async def encode_bytes(bytes...
# -*- coding: utf-8 -*- # MIT License # Copyright (c) 2020 Sandro Klippel # 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 ...
import torch from torch import nn from . import PITLossWrapper class SinkPITLossWrapper(nn.Module): r"""Permutation invariant loss wrapper. Args: loss_func: function with signature (targets, est_targets, **kwargs). n_iter (int): number of the Sinkhorn iteration (default = 200). S...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.utils.decorators import method_decorator from django.views.decorators.csrf import csrf_exempt from opentok import OpenTok, Roles, MediaModes, OutputModes from django.views.generic import View from django.http import ( JsonResponse, Http...
import numpy as np import tensorflow as tf import tensorflow.contrib.layers as layers import tensorflow.contrib.distributions as dbns # parent class for all VAE variants class AbstVAE: def __init__(self, seed, model_scope): self.seed = seed self.model_scope = model_scope np.random.seed(sel...
# Generated by Django 3.0.7 on 2020-06-17 08:01 import ckeditor.fields from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('core', '0005_faq'), ] operations = [ migrations.CreateModel( name='Example', fields=[ ...
import sys import calendar from datetime import datetime as dt import datetime import copy import lzma from datetime import datetime as dt from datetime import date, time import os, os.path from pytz import timezone import pytz import urllib.request from struct import * import numpy as np import pandas as pd from qsf...
#!/usr/bin/python3 import sys import os sys.path.append(f"{os.path.dirname(__file__)}/..") import util import math fn = f"{os.path.dirname(__file__)}/in.txt" # An iteration over all possible combinations was sufficient. # I added logic so that different orderings of the same combinations # of numbers are not used. l...
# Generated by Django 4.0.1 on 2022-01-20 17:45 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('app_uniplan', '0005_remove_student_profile_completed_units_and_more'), ] operations = [ migrations.RemoveField( model_name='student_prof...
from sklearn.ensemble import RandomForestClassifier from GCL.eval import BaseSKLearnEvaluator class RFEvaluator(BaseSKLearnEvaluator): def __init__(self, params=None): if params is None: params = {'n_estimators': [100, 200, 500, 1000]} super(RFEvaluator, self).__init__(RandomForestClas...
import warnings warnings.filterwarnings('ignore') import os from astroquery.simbad import Simbad from astropy.coordinates import SkyCoord as acoord import numpy as np import astropy.units as un __all__ = ['Target', 'Fournax'] class Target: ''' The TOI class represents an astronomical target of interest (T...
# -*- coding: utf-8 -*- # Generated by Django 1.10.6 on 2017-03-06 09:31 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('school', '0002_auto_20170306_0930'), ] operations = [ migrations.AlterField...
import argparse from paramiko import SSHClient parser = argparse.ArgumentParser() parser.add_argument("username") parser.add_argument("hostname") parser.add_argument("server_dir") parser.add_argument("release_candidate_dir") parser.add_argument("project_prefix") args = parser.parse_args() host = args.hostname user =...
from django.contrib import messages from django.http.response import JsonResponse from django.utils.translation import gettext_lazy as _ from django.shortcuts import redirect from django.views.generic import View from posts.models import Post from .models import Comment class CommentView(View): # http_method_na...
from lib.actions import BaseAction class ArticleSearch(BaseAction): def run(self, query): params = { 'q': query, } response = self._api_get('/articles', params=params) articles = response['articles'] return articles
import json from os import getenv import discum from dotenv import load_dotenv load_dotenv() def load_settings(settings_filename: str) -> dict: with open(settings_filename, encoding='utf-8') as f: return json.load(f) def main(): settings = load_settings('settings.json') user_ids_to_watch = set...
from spyd.game.command.command_base import CommandBase from spyd.permissions.functionality import Functionality from spyd.registry_manager import register @register("command") class ResumeCommand(CommandBase): name = "resume" functionality = Functionality("spyd.game.commands.resume.execute", "You do not have ...
from flask import Flask import pprint, pdb, logging logger = logging.getLogger(__name__) app = Flask(__name__) app.config.from_pyfile('default_config.py') app.config.from_envvar('MFWR_SETTINGS', silent=True) logging.basicConfig( filename='log.log', level=logging.DEBUG, for...
# Generated by Django 3.1.13 on 2021-07-11 14:59 import django.db.models.deletion from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("core", "0021_merge_20210711_1742"), ] operations = [ migrations.AlterField( model_name="ticket...
import logging import multiprocessing import os import random import sys import traceback from io import StringIO from pathlib import Path from typing import Any, Callable, Dict, List, Optional, Tuple, Union from spacy.lang.en import English import gobbli.model from gobbli.experiment.classification import ( Class...
import sys import os.path import pdb from .. import config sys.path.append(os.path.join(os.path.dirname(__file__), 'features_extraction')) # BUT WHYYYYYYYYYYYYYYY #obj_fe.extract_features(EnumModels.Models.bvlc_alexnet.name , "fc8") #obj_fe.extract_features(EnumModels.Models.ResNet18_ImageNet_CNTK_model.name , ...
import os import sys import json import re from glob import glob ICONS = {"pdf": "fa-file-text-o", "code": "fa-file-text-o", "video": "fa-video-camera", "powerpoint": "fa-file-powerpoint-o"} DEFAULT_ICON = "fa-file-text-o" DEFAULT_DOCUMENT = "<a <!--$$LINK$$-->><i class='fa fa <!--$$ICON$$--> text-primary'></...
import unittest import os import shutil from pathlib import Path class PipelineTest(unittest.TestCase): @classmethod def setUpClass(cls): cls.input_file = Path('input_examples', 'input.txt') cls.output_dir = Path('test_data', 'tokenizer_output') cls.output_file = Path('test_data', 'o...
import logging from pyvisdk.exceptions import InvalidArgumentError ######################################## # Automatically generated, do not edit. ######################################## log = logging.getLogger(__name__) def Capability(vim, *args, **kwargs): '''A particular product may or may not support cert...
import gunicorn gunicorn.SERVER_SOFTWARE = 'gunicorn'
from logging import getLogger from logging import NullHandler import python_liftbridge.api_pb2 from python_liftbridge.base import BaseClient from python_liftbridge.errors import handle_rpc_errors from python_liftbridge.errors import handle_rpc_errors_in_generator from python_liftbridge.message import Message # noqa: ...
"""imitation: implementations of imitation and reward learning algorithms.""" __version__ = "0.2.0"
import torch import numpy as np import random import os def set_seed(num): torch.manual_seed(num) torch.cuda.manual_seed_all(num) torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False np.random.seed(num) random.seed(num) os.environ['PYTHONHASHSEED'] = str(num)
import argparse import pandas as pd import matplotlib.pyplot as plt def initParser(): parser = argparse.ArgumentParser(description='File info') parser.add_argument('file_name', type=str, help='File name') parser.add_argument('--plot_name', dest='new_file', type=str, help='Name of the file to store plot') ...
#!/usr/bin/python """Plot an order parameter from multiple simulations.""" import argparse import matplotlib.pyplot as plt from matplotlib import cm from matplotlib import gridspec import numpy as np from scipy import interpolate from matplotlibstyles import styles from matplotlibstyles import plotutils import orig...
# coding: utf-8 r"""Tabby rear suspension assembly""" from car_assemblies import make_rear_suspension_assembly from osvcad.view import view_assembly, view_assembly_graph assembly = make_rear_suspension_assembly() if __name__ == "__main__": view_assembly(assembly) view_assembly_graph(assembly)
#!/usr/bin/python import sys import math def factors(x): lo, hi = [], [] n = int(math.sqrt(x)) for i in range(1,n+1): if x % i != 0: continue j = x / i lo += [i] hi += [j] hi.reverse() return lo + hi def test_A(x): for a in A: if x % a != 0:...
'Configuration of global variables and settings for every file' 'PLC.py' x = 0 y = 0 'arm.py' isCutting, isReleasing,isGrabbing,isClosingIn = False,False,False,False isReady = True 'vision.py' process = None PORT = 'COM3'
import numba import numpy as np @numba.njit(fastmath=True) def levenshtein_distance(a: str, b: str): """ Calculates Levenshtein distance between two strings using dynamic programming. Complexity: O(len(a) * len(b)) """ m = len(a) n = len(b) d = np.zeros((m + 1, n + 1), dtype=np.uintc) ...
#!/usr/bin/python import glob, os for src in glob.glob("*.png"): dst = src.replace(".png", ".bmp") update = False if os.path.exists(dst): srcStat = os.stat(src) dstStat = os.stat(dst) if srcStat.st_mtime > dstStat.st_mtime: update = True else: update = True ...
# Generated by Django 2.1.3 on 2018-11-19 14:44 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('openbook_common', '0002_auto_20181119_1520'), ] operations = [ migrations.AddField( model_name='emoji', name='order'...
from rest_framework.response import Response from rest_framework import status from rest_framework.views import APIView from drf_yasg.utils import swagger_auto_schema from sendgrid import SendGridAPIClient from .serializers import MailSerializer, TemplateMailSerializer, UserSerializer from send_email_microservice.setti...
""" This module is an example of a barebones writer plugin for napari It implements the ``napari_get_writer`` and ``napari_write_image`` hook specifications. see: https://napari.org/docs/dev/plugins/hook_specifications.html Replace code below according to your needs """ from napari_plugin_engine import napari_hook_i...
import typing if typing.TYPE_CHECKING: from ..client import Client from ..core import Gateway, GatewayDispatch from ..models import deserialize_channel async def channel_create(client: "Client", gateway: "Gateway", event: "GatewayDispatch") -> typing.List[typing.Awaitable]: """ |coro| ...
import paddle import paddle.nn as nn import paddle.nn.functional as F class PyramidPoolingModule(nn.Layer): """PyramidPoolingModule VisionTransformerUpHead is the decoder of PSPNet, Ref https://arxiv.org/abs/1612.01105.pdf Reference: ...
# Generated by Django 2.2.11 on 2021-07-19 15:35 import care.utils.models.validators import django.contrib.postgres.fields.jsonb from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('facility', '0266_auto_20210717_2041'), ] operations = [ migrations....
"""Faça um programa que pergunte o preço de três produtos e Informe qual produto você deve comprar, sabendo que a decisão é sempre pelo mais barato """ preco1 = int(input('Informe o primeiro preco: ')) preco2 = int(input('Informe o segundo preco: ')) preco3 = int(input('Informe o terceiro preco: ')) if preco1 == pre...
"""Simple Pulumi program standing up an EC2 VM serving a static file. """ import pulumi # Import the infrastructure module, which will create all of the # cloud resources. import infra # "export" values from the Pulumi Stack, making them easier to # access from other tools. pulumi.export("instanceID", infra.instance...