content
stringlengths
5
1.05M
"""Auth middleware tests.""" import asyncio from typing import Any from typing import Dict from typing import Optional from typing import Union from unittest import mock from unittest.mock import MagicMock import pytest from fastapi import FastAPI from orjson import dumps # pylint: disable-msg=E0611 from starlette....
# encoding: utf-8 # Copyright 2008—2012 California Institute of Technology. ALL RIGHTS # RESERVED. U.S. Government Sponsorship acknowledged. ''' EDRN Summarizer Service: utilities. ''' import urllib.parse, re # Why, why, why? DMCC, you so stupid! # @yuliujpl: why is this even here? DEFAULT_VERIFICATION_NUM = '0' * 4...
import torch import torch.nn as nn import src.run_utils as ru from src.run_utils import create_directory, set_seed from src.models import load_model from src.loss import LossFunctions from src.training import training from src.configure import params_from_file, print_congiguration def main(): """ Main method ...
# Generated by Django 2.0.3 on 2018-03-17 06:58 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('documents', '0003_userclient_slug'), ] operations = [ migrations.AddField( model_name='folderclient', name='slug', ...
"""P6E4 VICTORIA PEÑAS Escribe un programa que te pida dos números, de manera que el segundo sea mayor que el primero. El programa termina escribiendo los dos números tal y como se pide:""" num1=int(input("Escribe un número: ")) num2=int(input(f"Escribe un número mayor que {num1}: ")) while num1>=num2: num2=int(inp...
from usuario import Usuario from interacao import Interacao from veiculo import Veiculo from eventos import Eventos from ocorrencias import Ocorrencias from areasEspeciais import AreasEspeciais def main(): print('Bem vindo ao MoraisParking!') #Criação dos objetos usuario = Usuario() interacao = Interaca...
# coding=utf-8 # Copyleft 2019 project LXRT. import sys import traceback import os import json import random import collections import shutil import torch import torch.nn as nn from torch.utils.data.dataloader import DataLoader import pytorch_lightning as pl from pytorch_lightning.loggers import WandbLogger from pyto...
import tensorflow as tf import matplotlib.pyplot as plt from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("MNIST_data/",one_hot=True) type(mnist) image_shape = mnist.train.images[1].shape # plt.imshow(mnist.train.images[1].reshape(28,28)) # plt.imshow(mnist.train.images[1].r...
""" This package/directory contains the tcheasy & sorpa examples. Feel free to take them as a blueprint. """
_base_ = [ '../_base_/models/sagan_128x128.py', '../_base_/datasets/imagenet_128.py', '../_base_/default_runtime.py' ] init_cfg = dict(type='studio') model = dict( generator=dict(num_classes=1000, init_cfg=init_cfg), discriminator=dict(num_classes=1000, init_cfg=init_cfg), ) lr_config = None checkpoin...
''' Переставить min и max ''' def exchangeMinMax(a): minEl = float('inf') minId = -1 maxEl = float('-inf') maxId = -1 for i in range(len(a)): if (a[i] > maxEl): maxEl = a[i] maxId = i if (a[i] < minEl): minEl = a[i] minId = i (a[m...
# 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 # distributed under the ...
#!/usr/bin/env python # -*- coding: utf-8 -*- import inspect import numpy as np import emcee import george from george import kernels import os import sys currentframe = inspect.currentframe() currentdir = os.path.dirname(os.path.abspath(inspect.getfile(currentframe))) parentdir = os.path.dirname(currentdir) sys.pa...
#!/bin/env python # -*coding: UTF-8 -*- # # Argo data fetcher for Argovis. # Code borrows heavily from API gathered at: # https://github.com/earthcube2020/ec20_tucker_etal/blob/master/EC2020_argovis_python_api.ipynb # # This is comprised of functions used to query Argovis api # query functions either return dictionary ...
from .awslambdaevent import * from .awslambda import *
import sys import logging def get_rpc_update(): # Grabs data from applications logging.debug("Checking OS...") if sys.platform in ['Windows', 'win32', 'cygwin']: # Windows data retrieval try: logging.debug("Importing Windows specific modules...") from api.windows imp...
from .base import * DEBUG = False ALLOWED_HOSTS = [ get_secret('ALLOWED_HOSTS'), 'www.' + get_secret('ALLOWED_HOSTS'), ] WSGI_APPLICATION = 'project.wsgi_prod.application' # Database # https://docs.djangoproject.com/en/3.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db....
# -*- coding: utf-8 -*- from __future__ import absolute_import, division import pytest from ndeftool.cli import main @pytest.fixture def runner(): import click.testing return click.testing.CliRunner() @pytest.yield_fixture def isolated_runner(runner): with runner.isolated_filesystem(): yield r...
import typing from typing import Optional from uuid import UUID from marshmallow import Schema, fields, post_dump from commercetools import helpers, schemas, types from commercetools.services import abstract from commercetools.typing import OptionalListInt, OptionalListStr, OptionalListUUID __all__ = ["ProductProjec...
# More info on these dicts in team_picker_setup.py dict = {1: {'exile': ['yasuo'], 'robot': ['blitzcrank']}, 2: {'dragon': ['aurelionsol', 'shyvana'], 'phantom': ['karthus', 'kindred', 'mordekaiser'], 'guardian': ['braum', 'leona']}, 3: {'pirate': ['gangplank', 'graves', 'missfortune', 'pyke', 'twistedfate'], 'void': [...
import requests PO_TOKEN = "ajnub*********74xi8gifnp6r" PO_USER = "u1dj************n81x6vr7vx" def send_push_notify(text): if PO_USER == "yourpushoveruser" or PO_USER is None: print("No notifications since po is not setup") return try: r = requests.post("https://api.pushover.net/1/mess...
class Solution: def divisorGame(self, N: int) -> bool: return not (N & 1)
#!/usr/bin/env python import os import sys import pyami.resultcache import pyami.fileutil import cachefs import threading debug = True def debug(s): if debug: sys.stderr.write(s) sys.stderr.write('\n') class Cache(pyami.resultcache.ResultCache): def __init__(self, disk_cache_path, disk_cache_size, *args, **kw...
# Generated by Django 2.2 on 2020-03-31 19:41 from django.conf import settings from django.db import migrations, models import django.db.models.deletion import sorl.thumbnail.fields class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ...
### DO NOT REMOVE THIS from typing import List ### DO NOT REMOVE THIS class Solution: def divide(self, dividend: int, divisor: int) -> int: if dividend==-2147483648 and divisor==-1: return 2147483647 if dividend/divisor<0: return dividend//divisor if dividend%divisor==0 else ...
#!/usr/bin/env python # -*- coding: utf-8 -*- import numpy as np from vector import vector, plot_peaks from oct2py import octave # Load the Octage-Forge signal package. octave.eval("pkg load signal") print('Detect peaks without any filters.') (_, indexes) = octave.findpeaks(np.array(vector), 'DoubleSided', 'MinPe...
"""Tests.""" import pytest from part1 import TLSTester from part2 import SSLTester class TestPart1UnitTests: """.""" @pytest.mark.parametrize("test_input, expected", [ ("abba", True), ("abcd", False), ("aaaa", False), ("ioxxoj", True) ]) def test_contains_abba(self, t...
# Copyright (C) 2020-2021 by TeamSpeedo@Github, < https://github.com/TeamSpeedo >. # # This file is part of < https://github.com/TeamSpeedo/FridayUserBot > project, # and is released under the "GNU v3.0 License Agreement". # Please see < https://github.com/TeamSpeedo/blob/master/LICENSE > # # All rights reserved. from...
import torch import torch.nn as nn import torch.nn.functional as F from poker_env.datatypes import Globals,SUITS,RANKS,Action,Street,NetworkActions import numpy as np from models.model_utils import strip_padding,unspool,hardcode_handstrength import time from functools import lru_cache class IdentityBlock(nn.Module): ...
from ups import UPSConnection, UPSError, SHIPPING_SERVICES
# Generated by Django 3.2.7 on 2021-09-13 17:05 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('posts', '0004_alter_recipe_slug'), ] operations = [ migrations.RenameField( model_name='recipe', old_name='category', ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = 'ipetrash' import time from typing import Dict, List from urllib.parse import urljoin from bs4 import BeautifulSoup import requests def get_season_by_series() -> Dict[str, List[str]]: url = 'http://rik-i-morti.ru/' s = requests.session() rs ...
# Copyright (c) 2011 X.commerce, a business unit of eBay Inc. # Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # Copyright 2011 Piston Cloud Computing, Inc. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (...
import discord import env import textwrap import random import datetime import os import psycopg2 from psycopg2.extras import DictCursor def get_connection(): dsn = env.DATABASE_URL return psycopg2.connect(dsn, sslmode='require') def key_parser(message, keyword_list): has_keyword = False for key in ...
from .pycgminer import CgminerAPI
# ArgumentParser objects allow the help formatting to be customized by specifying an alternate formatting class. Currently, # there are four such classes: import argparse import textwrap """ RawTextHelpFormatter maintains whitespace for all sorts of help text, including argument descriptions. However, multiple new l...
# Nacar # Copyright 2022 Alberto Morón Hernández # [github.com/albertomh/Nacar] # # Test the Schema module # ▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔ # Test adding subschemas to the registry, setting missing optional attributes, # schema property getters, and raising custom InvalidSchemaErrors. import pytest from cerberus import schema...
import re import argparse from typing import Optional, List from dataclasses import dataclass from lark import Lark, Transformer, v_args USAGE = "A command line calculator" @dataclass class Token: name: str value: str calc_grammar = """ ?start: sum | NAME "=" sum -> assign_var ?sum: ...
import abc from abc import ABC class Parent(ABC): # __metaclass__ = abc.ABCMeta // this appears only to be necessary Python <= 3.4 def __init__(self): print("__init__: Parent") def do_template(self): print("template method leads to {}".format(self.template_method())) @abc.abstractm...
import json import re from django.views.decorators.csrf import csrf_exempt from django.http import HttpResponse from django.contrib.auth import authenticate, login from django.core.exceptions import ObjectDoesNotExist from django.contrib.auth.models import User from django.db import IntegrityError from sample.forms imp...
"""Builds elevation graph between one or more points. Module searches route between two coordinate points, draws a elevation graph and constructs a summary. Route and elevation are fetched using Google Maps APIs. Graph is created from fetched elevation points and drawn with Matplotlib. Usage: Find elevation from He...
import time import sys import re,os import urllib.request,urllib.parse,threading from datetime import datetime try: from googlesearch import search except ImportError: print("[!] \"google\" Module is unavailable. ") print(" Please Install it by using:") print("\n python3 -m pip install google") exit() SAVE...
import re haystack = "Hello world" needle = 'ello' mo = re.search(needle, haystack) print(mo) # Does not work on python 3.6: # assert isinstance(mo, re.Match) assert mo.start() == 1 assert mo.end() == 5 assert re.escape('python.exe') == 'python\\.exe' p = re.compile('ab') s = p.sub('x', 'abcabca') print(s) assert...
from rest_framework import routers, urlpatterns from rest_framework.routers import DefaultRouter from tasks.viewsets import UsersViewSet, TasksViewSet router=DefaultRouter() router.register(r'users', UsersViewSet, basename='users') router.register(r'tasks', TasksViewSet, basename='tasks') urlpatterns=router.urls
# a116_buggy_image.py import turtle as trtl # instead of a descriptive name of the turtle such as painter, # a less useful variable name spider is used spider= trtl.Turtle() spider.pensize(40) spider.circle(20) ## Create a spider body leg_number = 6 leg_length = 70 leg_pos = 380 / leg_number spider.pensiz...
# ------------------------------------------------------------------------------ # name : api_server.js # author : Noe Flatreaud (Retr0) # description: # simple API server for the IHC-controller project # it provide an API url as well as a basic dashboard so you can # use it every were by using the web browser. #...
import time from datetime import timedelta import numpy as np from pytimeparse.timeparse import timeparse from tensorflow import keras from tensorflow import logging from .save_and_load import save_model, save_last_epoch_number, save_best_info class ModelSaver(keras.callbacks.Callback): def __init__(self, mode...
class Solution: def maximumGap(self, nums: List[int]) -> int: nums.sort() a=0 b=nums[0] for x in range(1,len(nums)): if nums[x]-b>a: a=nums[x]-b b=nums[x] return a
# -*- encoding: utf-8 -*- """ @File : settings.py @Time : 2020/12/20 23:34 @Author : chise @Email : [email protected] @Software: PyCharm @info : """ import os from . import global_settings FASTAPI_VARIABLE = "FASTAPI_SETTINGS_MODULE" import importlib class Settings: def __init__(self): setti...
from msf.lib.exploit import Exploit, Revshell import socket import time class Unrealircd(Exploit): # constructor def __init__(self): super().__init__('UnrealIRCD', 'UnrealIRCD 3.2.8.1 exploit') # check args def check(self, target, port=6667): super().check(target, port) print(...
import pytest from math import isclose from quantities import length def test_non_SI_unit(): l = length.Length(32) l1 = l.to_unit(length.foot) l2 = l.to_unit(length.LengthType.inch) l3 = l.to_unit(length.LengthType.yard) l4 = l.to_unit(length.LengthType.mile) l5 = l.to_unit(length.LengthType.as...
from django.contrib import admin from django_jalali.admin.filters import JDateFieldListFilter import django_jalali.admin as jadmin from . import models # Register your models here. #you need import this for adding jalali calander widget class DefenseTimeAdmin(admin.ModelAdmin): list_filter = ( ('occurrenc...
from rdflib import Graph, plugin from rdflib.serializer import Serializer op = "" while(True): try: testrdf = input() except: break g = Graph().parse(data=testrdf, format='n3') op+= str(g.serialize(format='json-ld', indent=1)) +'\n' print(op)
# Generates VariableType.h/cpp # # VariableType is a subclass of at::Type that provides the binding code # necessary to provide a differentiable version of ATen operators. There are a # number of different things we could mean: # # - Given a non-differentiable forward implementation, we might # directly associate...
import os from transmogrify import Transmogrify square_img = os.path.abspath(os.path.join(os.path.dirname(__file__), 'testdata', 'square_img.jpg')) vert_img = os.path.abspath(os.path.join(os.path.dirname(__file__), 'testdata', 'vert_img.jpg')) horiz_img = os.path.abspath(os.path.join(os.path.dirname(__file__), 'testda...
# Copyright 2015-2018 Capital One Services, LLC # Copyright The Cloud Custodian Authors. # SPDX-License-Identifier: Apache-2.0 from ..azure_common import BaseTest, arm_template class LoadBalancerTest(BaseTest): def setUp(self): super(LoadBalancerTest, self).setUp() def test_load_balancer_schema_valid...
import argparse from concurrent.futures import ProcessPoolExecutor, as_completed from pathlib import Path from tqdm import tqdm from traffic.core import Sector # for typing from traffic.data import airac as sectors from traffic.data.so6 import SO6 def clip(so6: SO6, sector: Sector) -> SO6: return so6.inside_bbo...
''' Pytorch implementation for Inception ResNet v2. Original paper: https://arxiv.org/pdf/1602.07261.pdf ''' # import torch # import torch.nn as nn # from torch.autograd import Variable
from django.core.management.base import BaseCommand from django_wireguard.models import WireguardInterface class Command(BaseCommand): help = 'Setup WireGuard interface' def add_arguments(self, parser): parser.add_argument('name', type=str) parser.add_argument('--listen-port', nargs='?', typ...
import pytest @pytest.fixture def cache_dir(tmpdir): cache_path = tmpdir.mkdir('cache') return cache_path @pytest.fixture def config_content(): return """ [source] backup_dirs=/ /root/ /etc "/dir with space/" '/dir foo' backup_mysql=yes [destination] backup_destination={destination} keep_local_path=/va...
#%% import torch import numpy as np def VecLoss(vec_tar,vec): vec_norm = torch.linalg.norm(vec,dim=1) vec = vec/ (vec_norm.unsqueeze(1)) vec_tar_norm = torch.linalg.norm(vec_tar,dim=1) vec_tar = vec_tar/ (vec_tar_norm.unsqueeze(1)) # check dot product loss = vec * vec_tar loss = torch.sum(...
# Open3D: www.open3d.org # The MIT License (MIT) # See license file or visit www.open3d.org for details import copy from py3d import * from os import listdir, makedirs from os.path import exists, isfile, join, splitext ####################### # some global parameters for the global registration ######################...
from sfa_dash.conftest import BASE_URL def test_get_no_arg_routes(client, no_arg_route): resp = client.get(no_arg_route, base_url=BASE_URL) assert resp.status_code == 200 contains_404 = ( "<b>404: </b>" in resp.data.decode('utf-8') or '<li class="alert alert-danger">(404)' in resp.data.dec...
from http import HTTPStatus from exception.error_code import ErrorCode from exception.base_exception import BaseException class UnauthorizedException(BaseException): """ 401 Unauthorized """ def __init__(self, error_code: ErrorCode): super().__init__(HTTPStatus.UNAUTHORIZED, error_code)
import torch import torchvision.models as tvmodels from .cifar_resnet import ResNet from .mlp import MLP def construct_model(args): if args.model_name == 'resnet50': model = tvmodels.resnet.resnet50(False) elif args.model_name == 'resnet56': model = ResNet() elif args.model_name == 'MLP': ...
# coding: utf-8 # Copyright 2018 LINE Corporation # # LINE Corporation licenses this file to you 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 # # Unl...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from mm.utils.mesh import generateFace from mm.utils.transform import rotMat2angle from mm.utils.io import importObj, speechProc from mm.models import MeshModel from mm.utils.visualize import animate import glob, os, json import numpy as np from sklearn.neighbors import N...
import warnings import pandas as pd import numpy as np import time from autox.autox_server.util import log from tqdm import tqdm warnings.filterwarnings('ignore') from sklearn.feature_extraction.text import CountVectorizer from pypinyin import pinyin, lazy_pinyin, Style def str2map(s): if str(s) == 'None': ...
# MIT License # Copyright (c) 2017 Philipp Holzer, Karin Aicher # 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, ...
def plot_ellipse(position,covariance,ax=None,**kwargs): if ax is None: fig, ax = plt.subplots(1,1) if covariance.shape == (2,2): U, s, Vt = np.linalg.svd(covariance) angle = np.degrees(np.arctan2(U[1,0],U[0,0])) width, height = 2 * np.sqrt(s) else: angle = 0 ...
from numpy.linalg import cholesky as chol import numpy as np from numpy import linalg from pycuda.gpuarray import GPUArray, to_gpu from pycuda.gpuarray import empty as gpu_empty import gpustats.kernels as kernels from gpustats import codegen from gpustats.util import transpose as gpu_transpose reload(codegen) reload(k...
import sys from PyQt5.QtWidgets import * class MyWindow(QMainWindow): def __init__(self): super().__init__() self.setGeometry(300, 300, 400, 300) label1 = QLabel(text="고객 ID", parent=self) label1.resize(150, 30) label1.move(10, 10) label2 = QLabel(text="ID 비밀번호", ...
# Requires vertica-python driver: https://pypi.python.org/pypi/vertica-python/ # which also requires the psycopg2 driver: https://github.com/psycopg/psycopg2 # stdlib imports import os try: # Pitfalls: # 1 - Returns are in lists, not tuples # 2 - Parameters are to be tuples, not lists import vertica_py...
import datetime import functools def log(func): # 装饰器函数,参数是一个函数 @functools.wraps(func) # 将装饰器修饰过的函数wapper名字改成参数的名字 def wapper(*args, **kw): # wapper是装饰器函数,包含装饰的代码和调用被装饰函数的语句。 print("I am in position.") # 装饰的代码,比如日志打印 func(*args, **kw) # 原始的函数 return wapper # 返回装饰后的函数 @log # 指...
import os import re from pygame.mixer import Sound from pygame.sprite import Group from game.data.enums import InputMode, Screen from game.data.static import StaticData class DynamicData(): """ Class which holds all the game variables """ def __init__(self): self.__static= StaticData() ...
class TextureNodeCoordinates: pass
import datetime as dt from src.fetchers.genUnitOutagesFetcher import fetchMajorGenUnitOutages from src.fetchers.transElOutagesFetcher import fetchTransElOutages from src.fetchers.longTimeUnrevivedForcedOutagesFetcher import fetchlongTimeUnrevivedForcedOutages def getWeeklyReportContextObj(appDbConStr: str, startDt: d...
import re import jupyter_kernel_test as jkt class IMatlabTests(jkt.KernelTests): kernel_name = "imatlab" language_name = "matlab" file_extension = ".m" code_hello_world = "fprintf('hello, world') % some comment" code_stderr = "fprintf(2, 'oops')" completion_samples = [ {"text": "matl...
from typing import Any, Dict import sharepy from ..config import local_config from ..exceptions import CredentialError from .base import Source class Sharepoint(Source): """ A Sharepoint class to connect and download specific Excel file from Sharepoint. Args: credentials (dict): In credentials ...
x = int(input()) z = int(input()) sum = int(0) cake = x * z while True: piece = input() if piece != "STOP": piece = float(piece) piece = int(piece) sum += piece if sum > cake: print (f"No more cake left! You need {sum - cake} pieces more.") break if p...
from flask import Blueprint, render_template, session, redirect, url_for, abort, request import bcrypt import os from feed.forms import FeedPostForm from settings import Config from werkzeug.utils import secure_filename import uuid from user.decorators import login_required from user.forms import RegisterForm, LoginF...
"""********************************************************************* * * * Description: Implementing a python client for proxy list * * Date: 12/05/2021 * * Author: Marc...
import itertools import time from printer import GridPrinter class SudokuSolver: def __init__(self, grid): self.grid = grid self.grid_size = self.grid.size self.counter = 0 self.time = 0 self.solutions = [] def __set(self, x, y, value): self.counter += 1 ...
from __future__ import print_function from collections import OrderedDict from json import loads from re import sub from flask import Flask, jsonify, request, Response from flask.json import JSONEncoder class Keyword(object): def __init__(self, keyword, argument): self.keyword = keyword self.ar...
import bcrypt from datetime import datetime from sqlalchemy.exc import IntegrityError from sqlalchemy import and_ from models import User, Category, Expense def category_insert(session, category_title): """ Function to create category :param session: :param category_title: :return: returns crea...
import os import base64 from Crypto.PublicKey import RSA from Crypto.Cipher import PKCS1_OAEP import base64 import qrcode from PIL import Image,ImageDraw,ImageFont from shutil import copyfile from src.stegano import * from pyzbar import pyzbar import time from asn1crypto import tsp path_parent = os.path.dirname(os.ge...
import pandas as pd import sys import os import argparse import shutil import datetime import tldextract import csv import json import pyfiglet import random from fnmatch import fnmatch ## custom functions from utilities.helpers import (makedirs, clean_string, compress_text) export_dir = "export" url_data = "url_data...
#/usr/bin/python import os, shutil, sys, getopt, json from pprint import pprint from jinja2 import Environment, FileSystemLoader class Speaker: name = '' email = '' def __init__(self, name, email): self.name = name self.email = email def __repr__(self): return "Speaker[name={...
import json from shared import get_session_for_account, fetch_all_accounts, send_notification from policyuniverse.policy import Policy from policyuniverse.statement import Statement def audit(resource, remediate=False): is_compliant = True if resource["type"] != "ecs_service": raise Exception( ...
# 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...
t=int(input()) #To accept number of testcases while(t!=0): n,k=input().split() #accept the input n=int(n) k=int(k) arr=list(map(int,input().split())) # to get the array of elements dict={} for i in arr: if i in dict: dict[i]+=1 #if element present in dict increment...
from __future__ import absolute_import, unicode_literals from typing import Any, Dict from django.utils.translation import ugettext as _ from wiki.core.plugins import registry from wiki.core.plugins.base import BasePlugin from . import settings from .mdx.otis import OTISExtension class HaxxPlugin(BasePlugin): slu...
""" CNN model architecture for captcha """ import torch import torch.nn as nn from torch.autograd import Variable import torch.nn.functional as F from config import args class Net(nn.Module): def __init__(self, output): super(Net, self).__init__() self.conv1 = nn.Conv2d(1, 32, 3, stride=1, pad...
# encoding=UTF-8 # Copyright © 2010-2017 Jakub Wilk <[email protected]> # # 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,...
#// Don't forget to hit SUBSCRIBE, COMMENT, LIKE, SHARE! and LEARN... Its good to learn! :) # But srsly, hit that sub button so you don't miss out on more content! '''Port scanner FOR ports ending in 000 eg, 1000,2000,3000 etc - untill find hidden service port''' '''imports''' import socket s = socket.socket(soc...
from django.core.mail import send_mail from django.template.loader import render_to_string from django.conf import settings class TrsReport(object): """A report to send to a transmittal communication list.""" def __init__(self, trs_import): self.trs_import = trs_import self.email_list = trs_i...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # --------------------------------------- # Project: PKUYouth Webserver v2 # File: exceptions.py # Created Date: 2020-07-27 # Author: Xinghong Zhong # --------------------------------------- # Copyright (c) 2020 PKUYouth class PKUYouthException(Exception): status_co...
from django.contrib import admin from expiring_links.models import ExpiringLink admin.site.register(ExpiringLink)
from __future__ import absolute_import, unicode_literals import logging from django.apps import apps from django.db import models, transaction from django.utils.timezone import now from mayan.apps.documents.models import Document from .events import ( event_document_auto_check_in, event_document_check_in, e...
from django.db import models # Create your models here. class Student(models.Model): id = models.IntegerField(primary_key=True) name = models.CharField(max_length=100) class Professor(models.Model): id = models.IntegerField(primary_key=True) name = models.CharField(max_length=100) class Score(mod...