text
stringlengths
2
999k
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = 'Ren Qiang' # %% 汉明距离 def hanmingDistance(nums: list) -> int: # c1 = bin(nums[0]) # c2 = bin(nums[1]) # c3 = nums[0] ^ nums[1] calc = bin(nums[0] ^ nums[1]) output = calc.count('1') print(output) return output if __name__ == '__...
# coding: utf-8 """ Copyright 2015 SmartBear Software 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 applica...
from django.urls import path from . import views app_name = 'party' urlpatterns = [ path('', views.PartyListView.as_view(), name='list'), path('<str:id>/', views.PartyDetailView.as_view(), name='detail'), ]
import os from shutil import rmtree from tempfile import mkdtemp from galaxy.tools.loader import load_tool, template_macro_params from galaxy.util import parse_xml def test_loader(): class TestToolDirectory(object): def __init__(self): self.temp_directory = mkdtemp() def __enter__(...
from project.drink.drink import Drink class Water(Drink): def __init__(self, name: str, portion: float, brand: str): super().__init__(name, portion, 1.5, brand)
#!/usr/bin/env python3 # IMPORTS from mpd import (MPDClient, CommandError) from socket import error as SocketError from sys import exit import time ## SETTINGS ## HOST = 'localhost' PORT = '6600' PASSWORD = "password" ### # Chill test sounds # uri = 'spotify:user:b584371:playlist:4zlvIZSMVmeb0N6ZgLU7sk' uri = 'spotif...
# -*- coding: utf-8 -*- import datetime import re import rssit.util import bs4 import sys try: import tweepy except ImportError: tweepy = None sys.stderr.write("Warning: no twitter API support (install tweepy to fix)\n") import pprint from calendar import timegm import xml.sax.saxutils import urllib.parse...
# Copyright 2016 The TensorFlow Authors. 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 required by applica...
from core.Model import * from core.Utils import Utils from models.NewsType import NewsType from models.User import User from models.File import File class News(Base, Model): __tablename__ = "news" id = Column(BigInteger, primary_key=True, autoincrement=True) user_id = Column(BigInteger, ForeignKey(User.i...
#!/usr/bin/python # -*- coding: utf-8 -*- import sys # I'm too lazy to explain how it works, # instead check below sites out: # https://en.wikipedia.org/wiki/Binary_search_algorithm # https://www.geeksforgeeks.org/binary-search/ # Make sure you know concept of Recursion # Function explaination: # ar is the array #...
import warnings import ipywidgets as widgets import numpy as np from traitlets import ( Any, Bool, Bytes, Dict, Float, Int, Integer, List, TraitError, Unicode, Union, validate, ) from traittypes import Array from ._version import __version__ as version from .helpers imp...
from standard import * vout("------vy compiler ------") cp=vin("> ") with open(cp+'.vy','r') as f: temp=f.read() write_file('temp.py','w','from standard import *\n'+temp) run('temp.py')
import pyttsx3 import speech_recognition as sr import openai as op import os op.api_key = os.getenv("OPENAI_API_KEY") engine = pyttsx3.init() engine.setProperty('rate', 150) engine.setProperty('volume', 1.0) voices = engine.getProperty('voices') engine.setProperty('voice', voices[1].id) def tell(text): engine.s...
import tkinter import matplotlib.pyplot as plt import matplotlib.ticker as ticker from config import Config from matrix import Matrix class Graphic: TITLE = "Heat distribution in the rod(t = " def __init__(self, a, u): self.root = tkinter.Tk() self.root.title(self.TITLE + str(0) + ")") ...
default_application = 'ForCA' # ordinarily set in base routes.py default_controller = 'default' # ordinarily set in app-specific routes.py default_function = 'index' # ordinarily set in app-specific routes.py
from pyrogram import filters from pyrogram.types.bots_and_keyboards import callback_game from pyrogram.types.bots_and_keyboards.inline_keyboard_button import InlineKeyboardButton from pyrogram.types.bots_and_keyboards.inline_keyboard_markup import InlineKeyboardMarkup from nksama import bot ,help_message from typing i...
import os import json import queue from typing import ClassVar import requests from requests import Request, Session import logging from queue import Queue from dataclasses import dataclass from requests.exceptions import Timeout import threading import math import time import datetime @dataclass class PreparedReque...
import os, sys, re, os.path import platform import subprocess def replace(filename, pattern, replacement): f = open(filename) s = f.read() f.close() s = re.sub(pattern,replacement,s) f = open(filename,'w') f.write(s) f.close() dbms_cfg = ["config-std.h", "config.h"] algs = ['no', 'serial', 'parallel'] def in...
import pygame import sys import random from gamefiles.objects.playerClass import Player from gamefiles.objects.laserClass import Laser from gamefiles.objects.enemyClass import Enemy from gamefiles.objects.enemyLaserClass import EnemyLaser from gamefiles.utilities.label import Label class Engine(object): ...
from django.contrib import admin from budgets.models import Budget, BudgetCategory, BudgetOperation @admin.register(Budget) class BudgetAdmin(admin.ModelAdmin): pass @admin.register(BudgetCategory) class BudgetCategoryAdmin(admin.ModelAdmin): list_display = ("title", "active") @admin.register(BudgetOpera...
from .dataset import Dataset from .jcampdx import JCAMPDX from .exceptions import * from pathlib import Path import copy import operator as op import json from random import random from copy import deepcopy DEFAULT_DATASET_STATE = { "parameter_files" : [], "property_files" : [], ...
from django.shortcuts import render from django.views import generic import json import requests from ContestSpace.models import Contest, Problem, User, Team, pendingrequests, userContest, results from django.http import HttpResponseRedirect from django.urls import reverse import datetime from ContestSpace.form...
#!/usr/bin/env python # Copyright 2016 Hewlett Packard Enterprise Development Company LP # # 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 ...
from pwn import * from LibcSearcher import LibcSearcher import click import sys import os import time import functools ''' 本脚本为做buuctf上的pwn题所编写,利用click模块配置命令行参数, 能方便地进行本地调试和远程解题。 本地命令: python3 exp.py filename --tmux 1 --gdb-breakpoint 0x804802a 即可开始本地调试,并且会断在地址或函数处 建议启动tmux。tmux是一个窗口管理神器! 远程命令: python3 exp....
#! /usr/bin/env python # -*- coding: utf-8 -*- """ Module that contains options to select rig bones/joints """ from __future__ import print_function, division, absolute_import import os import json from Qt.QtCore import Qt, QFileInfo from Qt.QtWidgets import QDialog, QTreeWidget, QTreeWidgetItem from tpDcc import ...
import enforce from web3tools import web3util, web3wallet @enforce.runtime_validation class BToken: def __init__(self, contract_address): name = self.__class__.__name__ abi = web3util.abi(name) web3 = web3util.get_web3() self.contract = web3.eth.contract(contract_address, abi=abi) ...
from __future__ import absolute_import, unicode_literals import os from celery import Celery # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'crm.settings') # os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'crm.dev_settings') # os.environ.setdefault...
# coding: utf-8 """ ELEMENTS API The version of the OpenAPI document: 2 Generated by: https://openapi-generator.tech """ import pprint import re # noqa: F401 import six from elements_sdk.configuration import Configuration class TestExternalTranscoderConnectionRequest(object): """NOTE: This clas...
"""Team related endpoints.""" from flask import jsonify from flask_restplus import Namespace, Resource import api from api import PicoException, require_login from .schemas import team_req ns = Namespace('teams', description='Team management') @ns.route('') class TeamList(Resource): """Create and join a new te...
import post_office def get_email_template(name, default=None): """Get an email template, or fall back to use the default template object (if provided)""" try: return post_office.models.EmailTemplate.objects.get(name=name) except post_office.models.EmailTemplate.DoesNotExist: return default...
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** from ... import _utilities import typing # Export this package's modules as members: from ._enums import * from .event_subscription import * from .get_...
import numpy as np from hyperopt import fmin, tpe, hp from GPyOpt.methods import BayesianOptimization import GPyOpt#.optimization.optimizer as GPyOO from GPyOpt.optimization.optimizer import OptLbfgs, OptDirect, OptCma, Optimizer from GPyOpt.core.errors import InvalidVariableNameError from ._base import BaseSearcher...
import socket from queue import Queue import threading target = "" queue = Queue() open_ports = [] def port_scan(): while not queue.empty(): try: port = queue.get() sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((target, port)) open_p...
from aws_xray_sdk import core as xray_core from tests.fixture import * def pytest_sessionstart(): samples_dir = os.getenv("SAMPLES_DOCS_DIR") if not os.path.exists(samples_dir): raise pytest.UsageError(f"Undefined samples folder: {samples_dir} (value defined in pytest.ini).") example_dir = os.get...
import asyncio import time from telethon.tl import functions from telethon.errors import FloodWaitError from userbot.utils import admin_cmd DEL_TIME_OUT = 60 @borg.on(admin_cmd(pattern="bio")) # pylint:disable=E0602 async def _(event): if event.fwd_from: return while True: DMY = time.strfti...
#!/usr/bin/env python __author__ = "alvaro barbeira" import os import logging import numpy import pandas from genomic_tools_lib import Utilities, Logging def run(args): if os.path.exists(args.output): logging.info("%s exists. Nope.", args.output) return logging.info("Loading regions") re...
"""COMMAND : .balaji""" from telethon import events import asyncio @borg.on(events.NewMessage(pattern=r"\.(.*)", outgoing=True)) async def _(event): if event.fwd_from: return animation_interval = 5 animation_ttl = range(0, 15) input_str = event.pattern_match.group(1) if input_s...
log_level = 'INFO' load_from = None resume_from = None dist_params = dict(backend='nccl') workflow = [('train', 1)] checkpoint_config = dict(interval=10) evaluation = dict(interval=10, metric='mAP', save_best='AP') optimizer = dict( type='Adam', lr=5e-4, ) optimizer_config = dict(grad_clip=None) # learning pol...
class Buffer: def __init__(self, buffer_size): self.buffer = [None]*buffer_size def push(self, element): # Add element at zero position and remove last element (maintain fixed size) if None in self.buffer: self.buffer.insert(0,element) self.buffer = sel...
# coding: utf8 # Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserve. # # 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 requ...
from template import render class Index: def GET(self): return render.index()
import rospy from ds4_driver.msg import Trackpad class TrackpadHandler(object): STATE_INACTIVE = 0 STATE_TAPPED = 1 STATE_ONE_FINGER_DRAG = 2 STATE_TWO_FINGER_DRAG = 3 def __init__(self, tap_timeout=0.3): self._state = TrackpadHandler.STATE_INACTIVE self._prev_coord = None ...
import sys import os from sqlalchemy import Table from yaml import load,dump try: from yaml import CSafeLoader as SafeLoader print("Using CSafeLoader") except ImportError: from yaml import SafeLoader print("Using Python SafeLoader") def importyaml(connection, metadata, source_path, language='en'): ...
# -*- coding: UTF-8 -*- # # copyright: 2020-2022, Frederico Martins # author: Frederico Martins <http://github.com/fscm> # license: SPDX-License-Identifier: MIT """Afghani currency representation(s).""" from decimal import Decimal from typing import Optional, Union from .currency import Currency class Afghani(Curre...
# -*- coding: utf-8 -*- """ In django-SHOP, a commodity is considered a very basic product without any attributes, which can be used on a generic CMS page to describe anything. """ from __future__ import unicode_literals from django.conf import settings from django.core.exceptions import ImproperlyConfigured from djan...
# for this to work download the dataset from the provided link. # then cd in the Images_Processed directory. import os import numpy as np import cv2 from scipy.io import savemat C = np.ones((349,)) N = np.zeros((397,)) labels = np.concatenate((C, N), axis=0) covid = os.listdir('CT_COVID') n_covid = os.listdir('CT_Non...
import logging import os from urllib.parse import urlencode import scrapy from burplist.items import ProductLoader from burplist.utils.parsers import parse_quantity from burplist.utils.proxy import get_proxy_url from scrapy.downloadermiddlewares.retry import get_retry_request from scrapy.utils.project import get_proje...
# Copyright 2016 Pinterest, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writi...
# -*- encoding: utf-8; test-case-name: tests.test_modwalk -*- # ======================================================================== """ Copyright and other protections apply. Please see the accompanying :doc:`LICENSE <LICENSE>` and :doc:`CREDITS <CREDITS>` file(s) for rights and restrictions governing use of this...
import os import re from setuptools import setup, find_packages with open(os.path.join(os.path.dirname(__file__), "sqlalchemy_cockroachdb", "__init__.py")) as v: VERSION = re.compile(r'.*__version__ = "(.*?)"', re.S).match(v.read()).group(1) with open(os.path.join(os.path.dirname(__file__), "README.md")) as f: ...
# Copyright 2019 IBM 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 # # Unless required by applicable law or agreed to in writing, ...
import os import sys import mock import pytest from program_synthesis.karel import arguments from program_synthesis.karel.dataset import dataset from program_synthesis.karel.dataset import edit_data_loader from program_synthesis.karel.models import karel_edit_model @pytest.fixture def args(): with mock.patch('s...
# -*- coding: utf-8 -*- """ Minimum Dominating Set ======================= """ # Copyright (C) 2017 by # Alex Gates <ajgates42@gmail.com> # Rion Brattig Correia <rionbr@gmail.com> # All rights reserved. # MIT license. import networkx as nx import itertools import copy # # Minimum Dominating Set # def mds(d...
# -*-coding:Utf-8 -* # Copyright (c) 2010-2017 LE GOFF Vincent # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # ...
# Copyright (c) 2021 PaddlePaddle Authors. 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 required by applic...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # 将一个元素加入集合后,判断它存在于集合的结果为真 # 没加入的元素,或已经删除的元素,判断它存在于集合的结果为假 # 简单线性表实现集合 """ 集合插入与删除: 1、插入元素时,检查它是否在集合中,保证集合中元素的唯一性 删除元素时,找到第一个相同的元素并将其删除 2、插入时,简单将其加入线性表 删除时,检查整个表,删除指定元素的所有拷贝 """ # 简单线性表实现技术简单,元素判断和几个集合运算的操作效率低 # O(m*n) # 采用排序表操作 # O(m+n) # 采用hash表实现 # O...
# Read to ints and return a multiplication var1 = int(input("Digite um número inteiro: ")) var2 = int(input("Digite um outro número inteiro: ")) def multi(x,y): return x * y print(f'O produto de {var1} com {var2} é igual a {multi(var1, var2)}')
# Software License Agreement (BSD License) # # Copyright (c) 2009, Willow Garage, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above...
#!/usr/bin/env python2 # Copyright (c) 2014 The Bitcoin Core developers # Distributed under the MIT/X11 software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # # Exercise the wallet. Ported from wallet.sh. # Does the following: # a) creates 3 nodes, with an e...
# Configuration file for the Sphinx documentation builder. # # This file only contains a selection of the most common options. For a full # list see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html # -- Path setup -------------------------------------------------------------- # If ex...
''' Evaluates the performance of a CoNLL format annotated file. Also shows the errors that were found in the file. The file should have three columns (token, true tag, predicted tag). Usage: conll_evaluate_results.py <conll_file_path> <output_results_path> [options] Arguments: <conll_file_path> ...
# coding: utf-8 """ Kubernetes No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) OpenAPI spec version: v1.12.1 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import os import sys i...
from enum import Enum, IntEnum, auto, unique @unique class Classification(IntEnum): PUBLIC = -1 RESTRICTED = 0 CONFIDENTIAL = 1 @unique class Role(Enum): AGENT = 'agent' SERVICE = 'service' STORAGE = 'storage' @unique class Profile(Enum): BLACK = 'black' GREY = 'grey' WHITE = '...
from django.contrib import messages from django.contrib.auth.decorators import login_required from django.core.exceptions import PermissionDenied from django.core.urlresolvers import reverse, reverse_lazy from django.db.models import Count from django.http import Http404, HttpResponseRedirect from django.utils.decorato...
from __future__ import division import numpy as np from ngraph.frontends.neon.aeon_shim import AeonDataLoader from ngraph.util.persist import get_data_cache_or_nothing def make_aeon_dataloader(manifest_filename, audio_length, transcript_length, sample_freq_hz=16000, frame_length=.025, frame_s...
import numpy as np import argparse from sklearn.model_selection import cross_val_score from sklearn import metrics from sklearn.metrics import (precision_recall_curve, average_precision_score, roc_curve, roc_auc_score) from sklearn.ensemble import RandomForestC...
import boto3 boto3.__version__ import os, time import os, time from dateutil import tz if os.name == 'nt': def _naive_is_dst(self, dt): timestamp = tz.tz._datetime_to_timestamp(dt) # workaround the bug of negative offset UTC prob if timestamp+time.timezone < 0: current_time = t...
import numpy as np from numpy.random import rand # Import the new module. from cython_ftridiag import cytridiag as ct # Construct arguments to pass to the function. n=10 a, b, c, x = rand(n-1), rand(n), rand(n-1), rand(n) # Construct a matrix A to test that the result is correct. A = np.zeros((n,n)) A.ravel()[A.shape[...
import os import os.path import cv2 import numpy as np from torch.utils.data import Dataset from network.datasets import edge_utils as edge_utils import torch IMG_EXTENSIONS = ['.jpg', '.jpeg', '.png', '.ppm', '.bmp', '.pgm'] def is_image_file(filename): filename_lower = filename.lower() return any(filenam...
# coding:utf8 # 首先导入系统库,再导入框架库,最后导入用户库 import platform import django from django.views.generic.base import TemplateView from django.shortcuts import render, HttpResponseRedirect from django.views.decorators.http import require_http_methods from django.contrib.auth import authenticate, login from django.urls import reve...
from __future__ import absolute_import import re # noqa: F401 import six from ionoscloud.api_client import ApiClient from ionoscloud.exceptions import ( # noqa: F401 ApiTypeError, ApiValueError ) class IPBlocksApi(object): def __init__(self, api_client=None): if api_client is None: ...
from collections import Counter import ast import json import psycopg2 def string_to_list(x): return ast.literal_eval(x) def ingredient_getter(word): if len(word) == 0: return json.dumps({'error': 'nothing entered'}) else: results_list = [] split_words = word.split() if n...
#!/usr/bin/env python3 # Copyright (c) 2014-2017 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test mempool persistence. By default, bitcoind will dump mempool on shutdown and then reload it on sta...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import trio import pyfuse3 from mcafee_fde import McafeeFde from crypto_handler import CryptoHandler from utils import parse_args, init_logging, log, check_signature, check_if_files_exist def main(): options = parse_args() init_logging(options.debug) if op...
# -*- coding: utf-8 -*- """ Created on Thu Oct 22 16:01:46 2020 @author: Isaac """ import numpy as np import astropy.units as u from plotly.offline import init_notebook_mode from einsteinpy.plotting import GeodesicPlotter from einsteinpy.coordinates import SphericalDifferential from einsteinpy.bodies ...
# Generated by Django 3.2.3 on 2021-05-25 16:16 import django.contrib.auth.models from django.db import migrations, models import django.utils.timezone class Migration(migrations.Migration): initial = True dependencies = [ ('auth', '0012_alter_user_first_name_max_length'), ] operations = [...
""" Ory Kratos API Documentation for all public and administrative Ory Kratos APIs. Public and administrative APIs are exposed on different ports. Public APIs can face the public internet without any protection while administrative APIs should never be exposed without prior authorization. To protect the admini...
# Copyright 2021 The Cirq Developers # # 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 agreed to in ...
from toolz.itertoolz import last from web3 import Web3 import argparse import time import datetime import sys import json import numpy as np import random from decimal import Decimal with open('config.json') as f: config = json.load(f) # Connect our wallet web3 = Web3(Web3.HTTPProvider("https://bsc-dataseed.binanc...
#!/usr/bin/env python ############################################################################### # $Id$ # # Project: GDAL/OGR Test Suite # Purpose: Test read/write functionality for ADRG driver. # Author: Frank Warmerdam <warmerdam@pobox.com> # ##################################################################...
from pyhocon import ConfigTree # noqa: F401 from typing import Dict, Optional # noqa: F401 from databuilder.transformer.base_transformer import Transformer from databuilder.models.table_column_usage import ColumnReader, TableColumnUsage from databuilder.extractor.bigquery_usage_extractor import TableColumnUsageTuple...
import pyaf.Bench.TS_datasets as tsds import tests.artificial.process_artificial_dataset as art art.process_dataset(N = 32 , FREQ = 'D', seed = 0, trendtype = "MovingMedian", cycle_length = 30, transform = "RelativeDifference", sigma = 0.0, exog_count = 0, ar_order = 12);
__all__ = ['SmartsMolFilter', 'SDSupply', 'SmartsRemover', 'SmilesDupeFilter', 'SmilesOutput']
""" **DEPRECATED** NOTE This module is deprecated and will be removed in future versions. Use instead `utils.networkviz` """ try: from pyvis.network import Network as PyvisNetwork except ImportError: print("ERROR: this module requires pyvis `pip install pyvis`") raise import IPython import os from .. im...
import json from decimal import Decimal from django.core.serializers.json import DjangoJSONEncoder from django.db import models from django.http import HttpResponse from django.utils.encoding import force_text from django.utils.functional import Promise class JsonResponse(HttpResponse): def __init__(self, data):...
"""For entities that have a parameter template.""" from gemd.entity.link_by_uid import LinkByUID from gemd.entity.setters import validate_list from gemd.entity.template.base_template import BaseTemplate from gemd.entity.template.parameter_template import ParameterTemplate class HasParameterTemplates(object): """ ...
import unittest import os from functools import lru_cache from itertools import product from canine.adapters.base import ManualAdapter @lru_cache() def factorial(x): if x <= 1: return 1 return x * factorial(x-1) class TestUnit(unittest.TestCase): """ Runs tests on various utilities """ ...
# DP solution class Solution: def longestPalindrome(self, s: str) -> str: maxPalindrome = '' maxLen = 0 n = len(s) # palindrome[i][j] = True if s[i:j+1] is a palindrome palindrome = [[False for _ in range(n)] for _ in range(n)] # all substrings of length 1 are palind...
from .git_index_file import GitIndexFile from .git_index_file_entry import GitIndexFileEntry from .git_index_file_extension import GitIndexFileExtension from .parser import GitIndexParser, GitIndexParserException
# # # from __future__ import absolute_import, division, print_function, \ unicode_literals from logging import getLogger from nsone import NSONE from nsone.rest.errors import RateLimitException, ResourceException from time import sleep from ..record import Record from .base import BaseProvider class Ns1Provide...
# Copyright 2018 Google 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 agreed to in writing, ...
import unittest import numpy as np from dpipe.im.preprocessing import * class TestPrep(unittest.TestCase): def setUp(self): self.x = np.random.rand(3, 10, 10) * 2 + 3 def test_normalize_image(self): x = normalize(self.x) np.testing.assert_almost_equal(0, x.mean()) np.testing....
from django_filters import rest_framework as filters from apis.models import Api class ApiFilter(filters.FilterSet): def __init__(self, *args, author=None, **kwargs): super().__init__(*args, **kwargs) name = filters.CharFilter(field_name='name', lookup_expr='contains') username = filters.CharFilt...
#!/usr/bin/env python3 # Copyright (c) 2016-2020 The Wflscoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test segwit transactions and blocks on P2P network.""" from decimal import Decimal import math import ...
#!/usr/bin/env python3 from __future__ import print_function import os import re import math import filecmp import os.path import subprocess from collections import namedtuple from PIL import Image, ImageChops from openscad_runner import RenderMode, OpenScadRunner class ImageRequest(object): _size_re = re.comp...
import numpy as np class NeuralNetwork(object): def __init__(self, input_nodes, hidden_nodes, output_nodes, learning_rate): # Set number of nodes in input, hidden and output layers. self.input_nodes = input_nodes self.hidden_nodes = hidden_nodes self.output_nodes = output_nodes ...
# -*- coding: utf-8 -*- from __future__ import print_function, division, absolute_import from numba import PY3 from .external import ExternalFunction from numba.typesystem import * c_string_type = char.pointer() class ofunc(ExternalFunction): arg_types = [object_] return_type = object_ class Py_IncRef(ofun...
class Player(): def __init__(self, colour): self.cnt = 0; self.movingPhase = True; return; def action(self, turns): self.cnt = self.cnt + 1; if (self.cnt > 12): self.movingPhase = False; paction = None; if self.movingPhase: pos = input("Placing Phase White Player:"); # tmplist = (); pos =...
from abc import abstractmethod from typing import List from app.db.models import PostDB, OID class DatabaseManager(object): @property def client(self): raise NotImplementedError @property def db(self): raise NotImplementedError @abstractmethod async def connect_to_database(s...
# Copyright 2018 The TensorFlow Authors. 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 required by applica...