text
stringlengths
8
6.05M
import logging from datetime import datetime from typing import Optional, Dict, Sequence, List from waitlist.utility.swagger.eve import ESIResponse logger = logging.getLogger(__name__) class SearchResponse(ESIResponse): def __init__(self, expires: datetime, status_code: int, error: Optional[str], ...
# -*- coding: utf-8 -*- import sys from project_ui import Ui_MainWindow import cv2 as cv import numpy as np import glob import os from PyQt5.QtWidgets import QMainWindow, QApplication class MainWindow(QMainWindow, Ui_MainWindow): def __init__(self, parent=None): super(MainWindow, self).__init__(parent) ...
# -*- coding: utf-8 -*- from collections import Counter class Solution: def intersect(self, nums1, nums2): return list((Counter(nums1) & Counter(nums2)).elements()) if __name__ == "__main__": solution = Solution() assert [2, 2] == solution.intersect([1, 2, 2, 1], [2, 2])
from django.contrib import admin # Register your models here. from .models import Dessert admin.site.register(Dessert)
from game import Game from model.components.ai.monster import BasicMonster, StunnedMonster, FrozenMonster, ConfusedMonster from model.config import config from model.entities.party.player import Player from model.maps.area_map import AreaMap import pytest from unittest.mock import Mock def setup_module(module): Ga...
from schoolDemo import app app.secret_key= "gerileboLTD" app.run(debug=True)
import numpy as np def interpolateNewton(x,y,order=5,x0 = None, appError = 1e-8,numDigits = 4): """ 6 inputs: 2 lists necessary and 4 has default: list (or numpy array) :x :the input x values for all points list (or numpy array) :y :the input y values for all points (length of y should equal length of ...
# Programa: Imprimir de 1 até um número digitado pelo usuário x = 1 print('o numero é: %d' %x) ler = 1 while ler != 0: ler = int(input('Digite um novo número: ')) print('o número é: %d' %ler)
#!/usr/bin/env python3 # ---------------------------------------------------------------------- # The MIT License (MIT) # # Copyright (c) 2016, Heiko Möllerke # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to dea...
# test file def get_integer(m): my_integer = int(input(m) ) return my_integer def get_string(m): my_string = input(m) return my_string def double_loop_print(): for i in range(0, len(L)): output = "{}:{}".format(i, L[i]) print(output) for j in range (0, len(L[i])): ...
from django.http import ( HttpResponse, HttpResponseRedirect ) from django.shortcuts import ( render, redirect ) from .forms import ( QueryForm, TrackingForm, FeedbackForm ) from django.views import View from django.contrib import messages from django.db import models from django.contrib.auth im...
n, k = map(int, input().split()) a = list(map(int, input().split())) no_distinct_element = len(set(a)) # print(no_distinct_element, set(a)) if no_distinct_element < k: print('NO') else: print('YES') print(*[a.index(i)+1 for i in list(set(a))[:k]])
import link_checker if __name__ == "__main__": link_checker.web_access.start()
from __future__ import absolute_import from celery import Celery import os import random import time from datetime import datetime from flask import Flask, request, session, flash, redirect, url_for, jsonify app = Flask(__name__) celery = Celery(app.name) celery.config_from_object('celeryconfig') @celery.task def sp...
# ============LICENSE_START======================================================= # Copyright (c) 2018-2021 AT&T Intellectual Property. All rights reserved. # ================================================================================ # Licensed under the Apache License, Version 2.0 (the "License"); # you may not...
import db_handler import move_cs_folders import service_handler import configparser import logging import logging.config import datetime import os import sys logging.config.fileConfig("logging.conf") logging.info("Getting data from configuration file") conf = configparser.ConfigParser() conf.read('main.conf') TODAY ...
#main.py from flask import Flask, jsonify, request from db import get_songs, add_songs app = Flask(__name__) @app.route('/', methods=['POST', 'GET']) def padre(): if request.method == 'POST': if not request.is_json: return jsonify({"msg": "Falta JSON en la solicitud"}), 400 add_padr...
i = 0 no = 0 y = 0 z = 0 f = 0 y = 0 redteam = [] blueteam = [] def program(): global i, no, y, redteam, blueteam, none, z, f fr = open("tagout.txt","w") file = open("tagin.txt", "r") r = file.readlines() for line in r: word = r[no].split(' ') y += 1 check1 ...
# Copyright (c) 2021 Mahdi Biparva, mahdi.biparva@gmail.com # miTorch: Medical Imaging with PyTorch # Deep Learning Package for 3D medical imaging in PyTorch # Implemented by Mahdi Biparva, April 2021 # Brain Imaging Lab, Sunnybrook Research Institute (SRI) import torch import numbers import random from . import...
""" TextWriterクラスのテスト """ import os import sys from unittest import TestCase import pickle # srcの下をパスに追加 sys.path.append(os.path.join(os.getcwd(), 'src')) from fig_package.text_writer import TextWriter class TestTextWriter(TestCase): """ TextWriterクラスのテスト """ def setUp(self): """ テスト前処...
""" A simple Python based hangman solver. One flaw with this program is that it uses letter based frequency analysis, as opposed to a word based analysis. Hence, it implicitly weights all words as equally likely to appear in a hangman game -- additional data weighting the actual frequency of words that appear in the c...
import unittest from katas.kyu_7.highest_profit import min_max class HighestProfitTestCase(unittest.TestCase): def test_equals(self): self.assertEqual(min_max([1, 2, 3, 4, 5]), [1, 5]) def test_equals_2(self): self.assertEqual(min_max([2334454, 5]), [5, 2334454]) def test_equals_3(self)...
#!/usr/bin/python size = 21 def recurse(x, y): global grid if x == size - 1: if grid[x][y + 1] != 0: grid[x][y] = grid[x][y + 1] return grid[x][y] grid[x][y] = recurse(x, y + 1) return grid[x][y] elif y == size - 1: if grid[x + 1][y] != 0: ...
import random class Node: def __init__(self, val): self.l_child = None self.r_child = None self.data = val def binary_insert(root, node): if root is None: root = node else: if root.data > node.data: if root.l_child is None: ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Apr 13 21:33:52 2018 @author: brandinho """ import numpy as np from pokerCombinatorics import calcProbs, findHandStatus def fetchProbabilityArray(hand, table, currentHandRank): """ the array has the following probabilities: [straight f...
# -*- coding: utf-8 -*- # Copyright 2020 Ali Akhtari <https://github.com/AliAkhtari78> # # 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 #...
# -*- coding: utf-8 -*- """Tests for Safari Cookies (Cookies.binarycookies) files.""" import io import os import unittest from dtformats import errors from dtformats import safari_cookies from tests import test_lib class BinaryCookiesFileTest(test_lib.BaseTestCase): """Safari Cookies (Cookies.binarycookies) file...
from XML_parser import XMLParser from keras.callbacks import ModelCheckpoint, CSVLogger from image_generator import ImageGenerator from models import simpler_CNN from utils import split_data from utils import get_labels dataset_name = 'german_open_2017' batch_size = 30 num_epochs = 250 input_shape = (48, 48, 3) traine...
import numpy as np import tensorflow as tf import random as rn import os import pandas as pd from keras.callbacks import ModelCheckpoint from keras import backend as K import keras from keras.layers.normalization import BatchNormalization #from keras_layer_normalization import LayerNormalization from ...
from interface import *
#!/usr/bin/env python # # First create a config file in either /etc or ~/ # Contents should be as follows # # ------------------------------------------------- # [global] # default = https://gitlab.com # ssl_verify = true # timeout = 5 # # [gitlab] # url = https://gitlab.com # private_token = <your private gitlab toke...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Nov 23 17:47:11 2020 @author: shihyu """ import pandas as pd from venn import venn import matplotlib.pyplot as plt gene_file=pd.read_excel(r'Input/Genelist.xlsx') SetA=set(gene_file.iloc[:,0].dropna()) SetB=set(gene_file.iloc[:,1].dropna()) SetC=set(g...
import numpy as np from keras.layers import Input,Dense, Activation from keras.models import Model from keras.utils.generic_utils import get_custom_objects def XOR_train_fully_keras(): #Since Q1 (XOR) only asks for drawing, in the code, I used Keras/TF codes. x = np.array([[0,0], [0,1], ...
from django.urls import path from . import views urlpatterns = [ path('',views.home,name='home'), path('chatbot', views.chatbot,name='chatbot'), path('addmsg',views.addmsg,name='addmsg'), ]
from flask import Flask, request, session, redirect, send_from_directory import json from demandresponse import UserManager, PermissionManager app = Flask(__name__, static_url_path="/static") config = json.loads(open("data/cfg.json", "r").read()) app.config["SECRET_KEY"] = config["SECRET_KEY"] USERMANAGER ...
#!/usr/bin/env python3 import sys import math import json import time from pymongo import MongoClient import requests from pprint import pformat from pprint import pprint SINGLE_ENDPOINT = "https://services.nvd.nist.gov/rest/json/cve/1.0" COLLECTION_ENDPOINT = "https://services.nvd.nist.gov/rest/json/cves/1.0" ...
import json import numpy as np import ktrain __model = None def get_predicted_sentiment(review): data = [review] return __model.predict(data) def load_saved_artifacts(): print("loading saved artifacts...start") global __model if __model is None: __model = ktrain.load_predictor('./artifa...
from django.db import models from edtech.models.questions import Question from djutil.models import TimeStampedModel from edtech.models.mixins import DefaultPermissions from edtech.models.test_series import TestSeries class QuestionTestSeries(TimeStampedModel, DefaultPermissions): question = models.ForeignKey(Q...
LOGGEDOUT_SCSS_MSG = "User Logged out successfully" LOGIN_SCSS_MSG = "User Logged in successfully" INVALID_PASS = "Passowrd not valid" INVALID_USER = "User dose not exsists" INVALID_SESSION = "Session Invalid" INVALID_REQUEST = "Not a valid request" BAD_REQUEST = "Bad request" PASSWORD_EXPIERD = "Password Expier...
def concat(n,m): u=str(n) v=str(m) return int(u+v) def large_pair(n,m): u=str(n) v=str(m) n_1 = concat(n,m) n_2 = concat(m,n) if( i=0 j=0 while
def readNumber(line, index): number = 0 while index < len(line) and line[index].isdigit(): number = number * 10 + int(line[index]) index += 1 if index < len(line) and line[index] == '.': index += 1 keta = 0.1 while index < len(line) and line[index].isdigit(): number += int(line[index]) *...
# -*- coding: utf-8 -*- # Generated by Django 1.9.2 on 2016-05-26 16:47 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('backend', '0012_unisizegroup'), ] operations = [ ...
__author__ = 'Elisabetta Ronchieri' import sys import datetime import time import os import simplejson #import check_testplan as ctp import utils def set_inpt_fn(n_df, n_dfn, path='', subdir=True): '''Set Input filename (ifn), Back filename (bfn) and Destinatin filename (dfn)''' #t=datetime.datetime.now() ...
import torch import torch.nn as nn import torch.nn.init as torch_init from torch.autograd import Variable class bLSTM(nn.Module): def __init__(self, config): super(bLSTM, self).__init__() # gets the configurations self.is_bidirectional = config['bidirectional'] # i...
#!/usr/bin/python from timeit import Timer t = Timer('cur.execute("SELECT SQL_NO_CACHE * FROM `ticket` WHERE theater_id = 3;");cur.fetchall()', 'import MySQLdb;db = MySQLdb.connect(host="localhost", user="root", passwd="", db="sakila");cur = db.cursor()') print "theater_id %0.3f sec " % t.timeit(100) t = Timer('cur.e...
# -*- coding: cp936 -*- row = 2000 #数据的维度 col = 62 #数据的样本数量 train = [] #训练数据集 label = [] #标签 distance = [] #距离 inputdata = [] #被预测的集合 equal_k3_cnt= 0 #当K=3时预测准确的次数 equal_k5_cnt = 0 #当K=5时预测准确的次数 cnt = 0 #样本计数 #将gecolon_data.txt中的数据读入到train中 with open('gecolon_data.txt', 'r') as f: f...
# unit tests for initial_buffering.py from initial_buffering import * def test_segment_should_store_size_and_duration(): segment = Segment(123000, 5) assert segment.duration == 5 assert segment.size == 123000 def test_playlist_should_store_segments(): segment_1 = Segment(123000, 5) segment_2 = Se...
import json from datetime import datetime from django.template.loader import render_to_string from django.urls import reverse class Omitable(object): """ This value is empty and the key should be omitted. If you're thinking: "What is that crazy german guy doing?", well the answer is simple: I didn't ...
def hashing(myS): multiplier = 1 hashVar = 0 for char in myS: hashVar += multiplier * ord(char) multiplier += 1 return hashVar
from Dynamics import Dynamics from Main.Robot import Robot # This class class HapticController(object): def __init__(self): pass # Here is some sample code to get the mass matrix # Dyanamics r = Robot() M = Dynamics.make_mass_matrix(r) print M
#coding=utf-8 import discord import re from secure import DISCORD_TOKEN from settings import * from bot.modules.redisClient import startRedisConnection redisConn=startRedisConnection() from bot.modules import backgroundTasks from bot.modules import errors import logging from bot.modules.discordUtils import sa...
from __future__ import division from sys import argv import numpy as np import pandas as pd import matplotlib.pyplot as plt from math import exp,log from scipy.misc import factorial from time import sleep import argparse import matplotlib as mpl import string ''' This module is imported by the "leiva_2step" script and...
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Fri Mar 17 08:44:00 2017 @author: ian """ import pandas as pd import numpy as np import matplotlib.pyplot as plt import DataIO as io path = ('/home/ian/OzFlux/Sites/GatumPasture/Data/Processed/2016/' 'GatumPasture_2016_L4.nc') df = io.OzFluxQCnc_...
#Write a program that computes the sum of the squares of the numbers in the list numbers. For example a call #with, numbers = [2, 3, 4] should print 4+9+16 which is 29. numbers=[2,1,2] count=0 for i in numbers: count+=i**2 print(numbers, "which is", count)
# -*- coding: utf-8 -*- """ Created on Tue Nov 3 23:34:54 2020 @author: sumant """ # Student Progress Report print("Welcome") sub = ["telugu","hindi","english","maths","science","social"] marks=[] for i in range(6): marks.append(int(input(f"Enter {sub[i]} marks: "))) total = sum(marks) av...
#!/usr/bin/env python """ Author: Patrick Monnahan Purpose: This script generates commands for svtools genotype and svtools copynumber. These commands are meant to be run subsequent to generating a merged vcf via svtools lsort followed by lmerge. copynumber must be run subsequently to genotype and will run only if th...
from excel_handler import create_workbook, worksheet_timeline, worksheet_users, worksheet_places from fullArchive import get_all username = 'user' start_time = "2006-03-21T00:00:00.000Z" end_time = "2021-05-31T00:00:00.000Z" max_results = 500 workbook = create_workbook(username + '.xlsx') tweets, users, places = get...
# -*- coding: utf-8 -*- """ Created on Thu Dec 24 13:19:18 2015 @author: HSH """ class Solution(object): def generateMatrix(self, n): """ :type n: int :rtype: List[List[int]] """ result = [[0 for x in range(n)] for x in range(n)] nlevel = int(n/2) val = 1 ...
# Rotate ply file to normalized position # based at points on symmetry axis # MB import math from math import * import sys import numpy # Main function def main(): # input user .ply file name_file_ply = sys.argv[1] # input user symmetry points file sym_points_file = sys.argv[2] # to function 'ex...
# -*- coding: utf-8 -*- def compute(a,b): c=a.count(b) print("{:} occurs {:} time(s)".format(b,c)) return c a=input() b=input() compute(a,b)
import ast class Attachment(object): def __inti__(self): self._AttachmentName = "" self._AttachmentLabel = "" self._IsTypeFile = False self._IsTypeImage = False self._IsOptional = False @property def Attachme...
import datetime import io import re from unittest import mock import arrow import freezegun import pytest from botocore.exceptions import ClientError import keg_storage.backends as backends from keg_storage.backends.base import ( FileMode, FileNotFoundInStorageError, ListEntry, ShareLinkOperation, ) ...
from rest_framework import serializers from .models import Level, LevelPackage, PackageUserRelation class LevelDetailedRetrieveSerializer(serializers.ModelSerializer): class Meta: model = Level fields = [ 'id', 'name', 'time', 'date', 'singer', 'song_name', 'ms...
from sympy.ntheory import sieve from collections import Counter from itertools import combinations solution = 0 min = float("inf") is_perm = lambda x, y: Counter(str(x)) == Counter(str(y)) primes = sieve.primerange(10**3, 10**4) for x, y in combinations(primes, 2): n = x * y if n < 10**7: ...
import threading from peewee import Database, ExceptionWrapper, basestring from peewee import sort_models_topologically, merge_dict from peewee import OperationalError from peewee import (RESULTS_NAIVE, RESULTS_TUPLES, RESULTS_DICTS, RESULTS_AGGREGATE_MODELS, RESULTS_MODELS) from peewee import SQL, ...
import sqlalchemy from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from models import Base, User engine = create_engine('sqlite:///user.db', echo=False) #Base.metadata.drop_all(engine) Base.metadata.create_all(engine) Session = sessionmaker(bind=engine) session = Session() user1 = User(n...
# -*- coding: utf-8 -*- import scrapy from headerchange.user_agents import agents import random import json class HeadervalidationSpider(scrapy.Spider): name = 'headervalidation' def start_requests(self): url='http://httpbin.org/ip' for i in range(5): yield scrapy.Request(url=url,d...
import random import networkx as nx import numpy as np import matplotlib.pyplot as plt from class_2_3.trust_system.agent import DummyAgent from class_2_3.trust_system.environment import Environment Agent = DummyAgent NUM_AGENTS = 10 # Number of agents random.seed(0) # set the random seed agents = [] for i in rang...
import pandas as pd import math """ Point A to B continuous path finder ----------------------------------- step 1 : Import csv file step 2 : get first and last point (latitude,longitude) step 3 : find the slope ratio by using equation (first latitude-last latitud2)/(first latitude - last latitude) step 4 : slope rat...
#!/usr/bin/env python # coding: utf-8 # In[2]: import csv import json import sys # In[11]: input_file_txt = sys.argv[1] input_file_csv = sys.argv[2] output_file = sys.argv[3] all_chat_info = open(input_file_txt, 'r') people_chat_lst = [] for i in all_chat_info: useful_info = i.replace("\n","").split() c...
s,x=map(int,input().split()) l=list(map(int,input().split())) flag=0 for i in l: if(x==i): flag=1 if(flag==1): print("yes") else: print("no")
#!/usr/bin/env python3 import turtle import os #lets u do some basic graphics for beginners best (inbuilt) wn = turtle.Screen() #creating window wn.title("Ping Pong You Vs The Computer Game ") #giving title wn.bgcolor("black") wn.setup(width=800,height =600) #wn.tracer(0) #stops window from updsating so ...
def solution(A): # write your code in Python 3.6 hash = dict() for num in A: if num not in hash.keys(): hash[num] = 1 else: hash[num] *= -1 for key, value in hash.items(): if value == 1: return key
from urllib.parse import urljoin import sys import requests from ex02_bearer import bearer_token_for_namespace import stacksmith def get_app_details(namespace, token, app): endpoint = urljoin( stacksmith.url, 'ns/{ns}/apps/{app}'.format( ns=namespace, app=app ) ...
#!/usr/bin/env python # # Copyright (c) 2012, Jake Marsh (http://jakemmarsh.com) # # license: GNU LGPL # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the...
#Ejercicio 12 """ Una empresa distribuidora de energía le cobra a sus abonados el consumo de kW por hora, pero además debe sumarle el 0,21 % de impuesto, pero actualmente todos los cliente están dentro de un plan de promoción que les descuenta el 3,7 % del monto total apagar. """ kw = float (input ("Ingrese la canti...
import re from Jumpscale import j from Jumpscale.tools.threegit.ThreeGit import load_wiki WIKIS = {"info_grid": "wiki.grid.tf", "info_foundation": "wiki.threefold.tf", "info_tokens": "wiki.tokens.tf"} BRANCH = "development" TF_WIKIS_LINKS = { "info_grid": f"https://github.com/threefoldfoundation/info_grid/tree/{B...
#通过用户输入数字,计算阶乘。(30分) print("请输入一个数字") num=int(input()) sum=0 f=1 for i in range(1,num+1): f=f*i sum+=f print("阶乘为",sum)
class Solution(object): def myAtoi(self, s): """ https://leetcode.com/problems/string-to-integer-atoi/ """ s = s.lstrip() sign = 1 start = 0 pos_max = 2**31-1 neg_max = -2**31 if len(s) == 0: return 0 if s[0] == '-': ...
import unittest from katas.beta.counting_array_elements import count class CountTestCase(unittest.TestCase): def test_equals(self): self.assertEqual(count(['a', 'a', 'b', 'b', 'b']), {'a': 2, 'b': 3})
import requests import argparse import pathlib import hashlib import sys import os from zeroconf import ServiceBrowser, Zeroconf from concurrent.futures import Future from requests.auth import HTTPDigestAuth class ESPFinder: def __init__(self, espid): self.espid = espid self.expected_suffix = f'-...
# Copyright 2021 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from pants.backend.shell import dependency_inference, shunit2_test_runner from pants.backend.shell.goals import tailor, test from pants.backend.shell.subsystems import shunit2 from pants.b...
"""Module containing database cli and models.""" from flask import Flask from sqlalchemy import event from sqlalchemy.engine import Engine from .db import DB, MIGRATE from .cli import register_cli_blueprint def register_db(app: Flask): """Register the sqlalchemy db and alembic migrations with the flask app.""" ...
import tkinter as tk import numpy as np import random import time import datetime import threading import Adafruit_DHT from time import sleep # Library will let us put in delays import RPi.GPIO as GPIO pin = 4 sensor = Adafruit_DHT.DHT22 button1_pin=12 # Button 1 is connected to physical pin 12 GPIO.setmode(GPIO.BO...
import random import math def split_data_set(data, fraction): train_set = data.sample(frac=fraction, random_state=random.randrange(10)) test_set = data.drop(train_set.index) return train_set, test_set def calculate_net(node, weights): nets = [0 for i in range(len(node))] for i in range(len(node...
import sys, traceback, os import wmi import subprocess def decryptorTaskName(): return 'DeArchiver' def isDecryptorTaskRunningWithPID(pid): c = wmi.WMI() for process in c.Win32_Process(): if decryptorTaskName().lower() in process.Name.lower() and pid == process.ProcessID: return True return False def killDe...
#!/usr/local/bin/ryu-manager from os import environ environ['EVENTLET_ZMQ'] = '1' # Hack to load parent module from sys import path path.append('..') # Import the Template Controller from base_controller.base_controller import base_controller from eventlet.green import zmq # Import the System and Name methods from...
import random import json from os import walk import operator import re #import lyricsgenius filenames = [] for (dirpath, dirnames, filenames_list) in walk("./songs"): filenames.extend(filenames_list) break lyrics = [] for filename in filenames: try: file = open("./songs/"+filename) lines = file.readline...
#!/usr/bin/env python """ :: run ~/opticks/ana/debug_buffer.py """ import os, numpy as np np.set_printoptions(suppress=True) os.environ.setdefault("OPTICKS_EVENT_BASE",os.path.expandvars("/tmp/$USER/opticks")) path = os.path.expandvars("$OPTICKS_EVENT_BASE/G4OKTest/evt/g4live/natural/1/dg.npy") dg = np.load(pa...
# 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 use ...
# -*- coding: utf-8 -*- import regex import logging import sqlite3 from datetime import datetime import config import stuff import get from telegram.ext import Updater, MessageHandler, CommandHandler, Filters, PrefixHandler, CallbackContext from telegram import TelegramError, ReplyKeyboardMarkup, ReplyKeyboardRemove,...
# Generated by Django 3.1.1 on 2020-09-30 18:31 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('scrapingApp', '0018_theodoteam'), ] operations = [ migrations.DeleteModel( name='TheodoTeam', ), migrations.AddF...
#!/usr/bin/env python # coding: utf-8 import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText class Mail: def __init__(self): self.sender = 'autosendmail@qq.com' self.smtpserver = 'smtp.qq.com' self.username = 'autosendmail@qq.com' self.pa...
import numpy as np from typing import Union, Optional from .callback import Callback class Bandit: def __init__(self, k: int, rewards: np.ndarray): self.k = k self.actions = np.arange(k) self.rewards = rewards self.unbiased_constant = 0 def constant(self, step_size: float, **...
import numpy as np import torch import torch.nn.functional as F from torch import optim from torch.nn import CrossEntropyLoss import cfg import utils def _train_epoch(model, epoch, dataloader, optimizer): model.train() # set model to training mode for batch_idx, (images, masks, _) in enumerate(dataloader, ...
import pyrebase config = { "apiKey": "AIzaSyB3UTG878t8nyfUiw8zIhfyqb5Pqwp7S2I", "authDomain": "thebigtag-135f2.firebaseapp.com", "databaseURL": "https://thebigtag-135f2.firebaseio.com/", "storageBucket": "thebigtag-135f2.appspot.com", "serviceAccount": "thebigtag-135f2-firebase-adminsdk-f3yzd-32e7052d24.json" } fireb...
from django.db import models class Quote(models.Model): quote_author = models.CharField(max_length=50) quote_body = models.TextField() context = models.CharField(max_length=240, blank=True) source = models.CharField(max_length=120, blank=True) created_at = models.DateTimeField(auto_now_add=True) ...
Input: S = hello Output: h Solution: from collections import Counter class Solution: #Function to find the first non-repeating character in a string. def nonrepeatingCharacter(self,s): #code here freq = Counter(s) for i in s: if (freq[i] == 1): ...
from ncclient import manager import sys import xml.dom.minidom HOST='10.1.100.33' PORT = 830 USER='cisco' PASS='cisco' FILE='get_interface_gigabit3.xml' def get_configured_interfaces(xml_filter): with manager.connect(host=HOST, port=PORT, username=USER, password=PASS, hostkey_verify=FALSE, device_params={'name':...
from autodisc.explorers.randomexplorer import RandomExplorer from autodisc.explorers.goalspaceexplorer import GoalSpaceExplorer from autodisc.explorers.goalspacedensityexplorer import GoalSpaceDensityExplorer from autodisc.explorers.onlinelearninggoalexplorer import OnlineLearningGoalExplorer