content
stringlengths
5
1.05M
import json import boto3 mqttclient = boto3.client('iot-data') dynamodb = boto3.resource('dynamodb') def lambda_handler(event, context): # TODO implement topub = event['Records'][0]['s3']['object']['key'] #print(topub) table = dynamodb.Table('viewerCount_byAds') table.put_item( Item = { ...
import socketio import numpy as np import base64 from PIL import Image import io img = Image.fromarray(np.zeros((50,50,3), dtype=np.uint8)) io_obj = io.BytesIO() img.save(io_obj, format="PNG") img_bytes = io_obj.getvalue() sio = socketio.Client() @sio.event def connect(): print('connection established') @sio.ev...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('app_reservas', '0027_fields_verbose_names'), ] operations = [ migrations.CreateModel( name='Novedad', ...
from __future__ import division, print_function import unittest from keras.layers import Input from keras import backend as K from rvseg.models import convunet from rvseg.models import unet class TestModel(unittest.TestCase): def test_downsampling(self): inputs = Input(shape=(28, 28, 1)) filters...
import os import datetime as dt import pandas as pd DATASETS = os.path.abspath(os.path.dirname(__file__)) class Data(object): def get_data(self): print('GET DATA FIRED!') df = pd.read_csv('https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_ti...
# Copyright 2017 David R. Bild # # 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 agree...
# Copyright (c) 2011-2015 Rackspace US, Inc. # 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...
""" This doesn't work yet for things like TA, because the core is designed to treat the pump as a single pulse, whereas averaging needs to split the pump into two pulses, and the probe into two separate pulses """ #Standard python libraries import os #Dependencies import numpy as np import yaml import matplotlib.pyp...
""" xarray DataArray and Dataset accessor for xcmocean. """ import re import cmocean.cm as cmo import xarray as xr from .options import DIV, REGEX, SEQ @xr.register_dataarray_accessor("cmo") class xromsDataArrayAccessor: """DataArray accessor for package. Attributes ---------- da: DataArray ...
from __future__ import print_function import subprocess from simpleflow.download import with_binaries @with_binaries( { "how-is-simpleflow": "s3://botify-labs-simpleflow/binaries/latest/how_is_simpleflow", } ) def a_task(): print("command: which how-is-simpleflow") print(subprocess.check_out...
# Generated by Django 2.2.4 on 2019-11-18 04:33 from django.conf import settings import django.core.validators from django.db import migrations, models import django.db.models.deletion import jsonfield.fields import uuid class Migration(migrations.Migration): dependencies = [ ('accounts', '0001_initial'...
#!/usr/bin/env python #@# vim: set filetype=python: from argparse import ArgumentParser from concurrent import futures import gc import grpc import json import os import signal import sys import time import vptree sys.path.append(os.path.join(os.path.dirname(__file__), "./lib")) import similar_image_search_pb2 impor...
from flask import Flask, render_template, flash, redirect, request, session, abort app=Flask(__name__) @app.route('/') def home(): return render_template('home.html') @app.route("/about_/") def about(): return render_template('about_.html') if __name__=="__main__": app.run(debug=True)
from ..models import Recipe from ..models import RecipeIngredient from ..models import RecipeIngredientItem from django.contrib.auth.models import User class UpdateRecipeIngredient(): def __init__(self, ingredient): self.ingredient = ingredient self.recipes_ingredient_object = None # Database objec...
import io import asyncio import json import logging import disnake from datetime import datetime, timedelta from typing import Any, Awaitable, Callable, Coroutine, Dict, List, Optional, Set, Tuple, Type, TypeVar, cast from disnake.ext import commands from ._base import BaseCog, loop_error_handled, PermissionDecorator...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # @Date : 2020-06-08 17:07:44 # @Author : AnarL. (anar930906@gmail.com) # @Link : https://anar0615.wordpress.com # @Version : V0.5 import os import struct import sys import binascii import pdb from pywubi import wubi """ 这个脚本代码部分参考:https://blog.csdn.net/zhangzhen...
''' Copyright 2022 Airbus SAS 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 dis...
pathes_mnist = [ './checkpoint/fashion_mnist/0', ] # model_mnist_top_0 = PixelSNAIL( # [32, 32], # 512, # args.channel, # 5, # 4, # args.n_res_block, # args.n_res_channel, # dropout=args.dropout,...
"""Tests for the MonitorBasedSaveBest class.""" __author__ = "David Warde-Farley" __copyright__ = "Copyright 2014, Universite de Montreal" __credits__ = ["David Warde-Farley"] __license__ = "3-clause BSD" __email__ = "wardefar@iro" __maintainer__ = "David Warde-Farley" import os import tempfile from pylearn2.models.m...
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright (c) 2018, S. <essepuntato@gmail.com> # # Permission to use, copy, modify, and/or distribute this software for any # purpose with or without fee is hereby granted, provided that the above # copyright notice and this permission notice appear in all copies. # # THE SOF...
from manga import * import requests as req import json import os #Gets a list of manga #Name, if left blank, will just get the newest manga #Limit has a cap of 100 manga def get_manga(title="", limit=10, offset=0): #Request the manga list from Mangadex and put it into a dictionary r = req.get("http...
# -*- coding: utf-8 -*- ## This file parses all localized keywords from a bunch of relevant files and import os, re, keyring, urllib, urllib.request, certifi, ssl, json sslcontext = ssl.create_default_context(cafile=certifi.where()) MOTHERSHIP = 'https://typeworld2.appspot.com' #MOTHERSHIP = 'http://127.0.0.1:8080' ...
from ares.analysis.ModelSet import ModelSet from ares.analysis.MultiPlot import MultiPanel from ares.analysis.RaySegment import RaySegment from ares.analysis.Global21cm import Global21cm from ares.analysis.PowerSpectrum import PowerSpectrum from ares.analysis.GalaxyPopulation import GalaxyPopulation from ares.analysis....
import pygame, sys from pygame.locals import * pygame.init() DISPLAYSURF = pygame.display.set_mode((400, 300)) pygame.display.set_caption("Hello, World!") BLACK = pygame.Color(0, 0, 0) WHITE = pygame.Color(255, 255, 255) GREEN = pygame.Color(0, 255, 0) BLUE = pygame.Color(0, 0, 128) fontObj = pygame.font.Font("frees...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Dec 7 10:53:43 2020 @author: jacob """ import pandas as pd import matplotlib.pyplot as plt import numpy as np dataFile = "results/model_eval_results_relu.csv" results = pd.read_csv(dataFile) # clean AE labels results["simpName"]=results['label'].str....
def Main(a: str) -> bool: b = None return a == b
class Solution: def isPowerOfFour(self, n: int) -> bool: return n > 0 and n == (n & -n) and (n & 0xAAAAAAAA == 0)
import logging from ..java import JavaSimProcedure from angr.engines.soot.values.strref import SimSootValue_StringRef l = logging.getLogger(name=__name__) class GetSimpleName(JavaSimProcedure): __provides__ = ( ("java.lang.Class", "getSimpleName()"), ) def run(self, this): # pylint: disable=ar...
# Lint as: python2, python3 # Copyright 2019 Google LLC. 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 req...
# PyVision License # # Copyright (c) 2011 David S. Bolme # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source code must retain the above copyright # notice, this lis...
import math import random n = random.randint(1, 1000) ab = [] for i in range(n): ab.append(random.randint(1, n)) # my original implementation tried to use a helper method for stitching together the sorted results of the recursion but I hit Python's recursion lock... not good. Adapted the solution discussed here as i...
import sys input=sys.stdin.readline for _ in range(int(input())): a,b,c=map(int,input().split()) sol1 = a**2 + (b+c)**2 sol2 = b**2 + (a+c)**2 sol3 = c**2 + (a+b)**2 print(min(sol1,sol2,sol3))
from flask import Flask, render_template, url_for, flash, redirect, request, session from forms import RegistrationForm, LoginForm, Post from email_validator import validate_email, EmailNotValidError from cassandra.cluster import Cluster from cassandra.auth import PlainTextAuthProvider import os client_id = os.environ...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Barometer module ---------------- Created by hbldh <henrik.blidh@nedomkull.com> on 2016-08-16 Modified by lkasso <hello@mbientlab.com> """ from __future__ import division from __future__ import print_function from __future__ import absolute_import import re import l...
from django.db import models # Create your models here. from nectr.users.models import User class Dashboard(models.Model): user = models.ForeignKey(User)
#!/usr/bin/env python # --------------------------------------------------------------------------- # Robust Kalman Filter (RKF) # Author: Tianchen Ji # Email: tj12@illinois.edu # Create Date: 2019-12-19 # --------------------------------------------------------------------------- import numpy as np from math import ...
import math import numpy as np import torch from torch import nn from torch.nn import CrossEntropyLoss from dataclasses import dataclass from typing import Optional, Tuple from transformers import DistilBertModel, DistilBertPreTrainedModel from transformers.file_utils import ModelOutput @dataclass class SequenceCla...
import unittest from word_distance import WordDistance class TestWordDistance(unittest.TestCase): def test_find_shortest_distance(self): text = 'We do value and reward motivation in our development team. Development is a key skill for a DevOp.' distance = WordDistance(text).find_shortest_distance...
# coding: utf-8 '''Classify IRS spectra. Create a widget that allows selection of some buttons to classify IRS spectra. A fair amount of by-hand fiddling below depending on what is being done. ''' import glob import os import shutil import pickle import json import numpy as np from scipy import optimize from sklear...
import os import torch import numpy as np import traceback import torch.nn as nn from collections import defaultdict from torch.autograd import Variable from commons.embeddings.word_embedding import WordEmbedding from commons.embeddings.bert_container import BertContainer from models.sqlnet.modules.sel_predict import S...
__release_date__ = "11-mar-2020"
#!/usr/bin/python3 ##!/data/data/com.termux/files/usr/bin/python3.6 #^ termux only version='0.1' import math, sys, argparse from collections import OrderedDict if sys.version_info[0] < 3: raise "Must be using Python 3" exit(1) parser=argparse.ArgumentParser() parser.prog = "lscgen.py" parser.description = "C...
from __future__ import annotations import random from typing import List, Optional, Tuple, TYPE_CHECKING import numpy as np # type: ignore import tcod from UI import color from actions import Action, BumpAction, MeleeAction, MovementAction, WaitAction, FreezeSpellAction, MawSpellAction, \ DrainSpellAction if T...
lista = [] while True: lista.append(int(input('Insira um número: '))) continuar = str(input('Deseja continuar? [S/N] ')) if continuar in 'Nn': break print(f'Foram inseridos {len(lista)} números na lista!') print(f'Valores em ordem decrescente: {list(reversed(lista))}') print(f'O valor 5 se encont...
from functools import partial import tkinter as tk from tkinter.colorchooser import askcolor class App(tk.Tk): def __init__(self): super().__init__() self.title("Colors demo") text = "The quick brown fox jumps over the lazy dog" self.label = tk.Label(self, text=text) self.f...
import logging from inflection import singularize from .views import generate_rest_view from .acl import generate_acl from .utils import ( is_dynamic_uri, resource_view_attrs, generate_model_name, dynamic_part_name, attr_subresource, singular_subresource, get_static_parent, get_route_n...
#python convert 3.1 Skrypt import shlex def map(): print(' _____________________________ ') print('| | | |') print('| | | |') print('| Room B = Room D = Room E |') print('| Jeff | Sword | Alien |') print('| | ...
from lf3py.api.errors import ApiError from lf3py.api.response import ErrorBody, Response from lf3py.lang.error import stacktrace from lf3py.task.result import Result from lf3py.view.render import IRender class ApiRender(IRender): def __init__(self, response: Response) -> None: self._response = response ...
import os from contextlib import contextmanager from typing import Type, Tuple from yaml import SafeLoader, BaseLoader from entrypoints import get_group_all as get_entrypoints from ..config.yaml import ( load_configuration as load_yaml_configuration, yaml_constructor, ) from ..config.python import load_config...
# Copyright (C) 2020-2021 by DevsExpo@Github, < https://github.com/DevsExpo >. # # This file is part of < https://github.com/DevsExpo/FridayUserBot > project, # and is released under the "GNU v3.0 License Agreement". # Please see < https://github.com/DevsExpo/blob/master/LICENSE > # # All rights reserved. from pyrogr...
# Copyright © 2017-2019 Zuercher Hochschule fuer Angewandte Wissenschaften. # 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/l...
import numpy as np import pdb def hat(x): """Returns the hat map of a given 3x1 vector. Args: x: (3x1 numpy array) vector Returns: x_hat: (3x3 numpy array) hat of the input vector """ x = x.reshape((3, 1)) # You may have to uncomment this line depending on # your Nu...
import os import sys import tempfile from os.path import exists, join import pytest from django.conf import settings from django.test import TestCase, override_settings from oscar.core import customisation VALID_FOLDER_PATH = 'tests/_site/apps' class TestUtilities(TestCase): def test_subfolder_extraction(self...
from binance_trading_bot import utilities, visual import pandas as pd import requests, json, re from six.moves import urllib from bs4 import BeautifulSoup import matplotlib.pyplot as plt plt.style.use('classic') from matplotlib.ticker import FormatStrFormatter import matplotlib.patches as mpatches import time from date...
import numpy as np import tensorflow as tf from flask import Flask, request from flask_restx import Resource, Api app = Flask(__name__) api = Api(app) tf_model = tf.keras.models.load_model('tf_cnn_model/1') @api.route('/predict') class SimplePredict(Resource): def post(self): data = request.json.get('da...
# -*- coding: utf-8 -*- """ Noting is perfect, errors and timeouts may happen, and when such failures happen, the consumer has to decide what to do with that. By default, the consumer would reject the envelope (RabbitMQ message) when a failure happens. However, errors and timeouts issues, unless there is a software bug...
# coding: utf-8 # Copyright (c) Vidar Tonaas Fauske. # Distributed under the terms of the Modified BSD License. """Hotpot - Jupyter kernel manager helpers This module contains """ import asyncio from queue import SimpleQueue from jupyter_client.multikernelmanager import MultiKernelManager, AsyncMultiKernelManager f...
# -*- coding: utf-8 -*- """ Problem 23: Non-abundant sums A perfect number is a number for which the sum of its proper divisors is exactly equal to the number. For example, the sum of the proper divisors of 28 would be 1 + 2 + 4 + 7 + 14 = 28, which means that 28 is a perfect number. A number n is called deficient ...
from logging import disable import requests from kivy.app import App from kivy.clock import Clock from kivy.config import Config from kivy.core.text import Label from kivy.graphics import Color, Rectangle from kivy.uix.button import Button from kivy.uix.floatlayout import FloatLayout from kivy.uix.boxlayout import BoxL...
from bearlibterminal import terminal from loguru import logger from utilities import configUtilities, armourManagement, common, externalfileutilities, input_handlers, itemsHelp, \ jewelleryManagement, spellHelp from static.data import constants def display_spell_info_popup(menu_selection, gameworld, player_entity...
#!/usr/bin/env python3 from pathlib import Path import cv2 import depthai as dai import numpy as np import time import glob import os from lxml import etree as ET from tqdm import tqdm def to_planar(arr: np.ndarray, shape: tuple) -> list: return [val for channel in cv2.resize(arr, shape).transpose(2, 0, 1) for y_...
import torch a = torch.rand((9,4)) print(a) out = torch.chunk(a,2,dim=0) print(out[0], out[0].shape) print(out[1], out[1].shape) a = torch.rand((10,4)) print(a) out = torch.split(a,3,dim = 0) print(len(out)) for t in out: print(t,t.shape) out = torch.split(a,[1,3,6], dim=0) for t in out: print(t, t.shape)
#!/usr/bin/env python3 import fileutils def part1(lst): graph = build_graph(lst) count = count_paths(graph["vertices"]["start"], graph["vertices"]["end"], graph["vertices"], 1) return count def part2(lst): graph = build_graph(lst) count = count_paths(graph["vertices"]["start"], graph["vertices"]...
import openpyxl import pandas as pd import datetime from openpyxl import load_workbook from openpyxl.styles import Font from openpyxl.styles.borders import Border, Side from openpyxl.utils.dataframe import dataframe_to_rows import os from django.conf import settings import time class OutProcess: workbook = None ...
import threading import logging import multiprocessing import yaml from gensim.models import KeyedVectors from generate_set import read_word_set try: print("Loading config.yml...") config_yaml = open("../../config.yml") print("config.yml loaded") except: exit("config.yml file is missing, run setup.py"...
from ...core.context import Context from .. import ParadeCommand from ...utils.log import parade_logger as logger class MakeFlowCommand(ParadeCommand): requires_workspace = True @property def aliases(self): return ['new'] def run_internal(self, context, **kwargs): assert isinstance(...
# Copyright 2013 IBM Corporation. # 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...
class DFA: current_state = None current_letter = None valid = True def __init__( self, name, alphabet, states, delta_function, start_state, final_states ): self.name = name self.alphabet = alphabet self.states = states self.delta_function = delta_function ...
import os import numpy as np import matplotlib.font_manager as font_manager import matplotlib.pyplot as plt import seaborn as sns font_paths = font_manager.findSystemFonts() font_objects = font_manager.createFontList(font_paths) font_names = [f.name for f in font_objects] print(font_names) from bayes_cv_prune.StanMo...
from bottle import run from services import IdeaServices import cherrypy __author__ = 'Aishwarya Sharma' run(server="cherrypy", host="localhost", port=8080, debug=True)
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Generated Wed Jul 11 10:26:09 2018 by generateDS.py version 2.29.14. # Python 2.7.13 |Continuum Analytics, Inc.| (default, Dec 20 2016, 23:05:08) [GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.57)] # # Command line options: # ('-o', 'sfftkplus/schema/roi.py') # #...
import numpy as np def get_triangles(npimage, depth=10): """ Makes upper left and lower right triangles. Takes in numpy array, returns array of triangles. Automatically excludes invalid triangles (triangles with one vertex off the edge) """ npimage = npimage + depth h, w = npimage.shape y, x = np.indices((h, w)...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models from django.utils.encoding import python_2_unicode_compatible #, force_text from django.utils.translation import ugettext_lazy as _ from .unique_slugify import unique_slugify from cms.models import CMSPlugin class Abstra...
from pyspark import SparkConf from _Setting import StockSetting import tushare as ts import numpy as np import pandas as pd from pyspark.sql import SparkSession from pyspark.sql.types import StructType, StructField, StringType, DoubleType import json #spark-submit --master yarn --py-files ./_Setting.py --deploy-mode...
# coding=utf-8 # Copyright 2021 The Google Research 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 applicab...
#!/usr/bin/env python3 import sys from ctypes import cdll from ctypes import c_int from ctypes import c_bool from ctypes import c_float from ctypes import c_double from ctypes import byref from ctypes import POINTER from numpy import zeros from numpy import array from numpy import amax from numpy import amin from numpy...
import enum import typing import jsonapi_requests import mbta.api from .common import MbtaModel from .mixin import DirectionMixin from .orm import EnumField class Route(jsonapi_requests.orm.ApiModel, MbtaModel, DirectionMixin): class Meta: type = 'route' path = 'routes' api = mbta.api.co...
from tokenizer_tools.hooks import TensorObserveHook def test_tensorObserveHook(): pass
#!/usr/bin/env python # -*- coding: utf-8 -*- import rospy from std_msgs.msg import String if __name__ == "__main__": rospy.init_node("fake_support_vendor_name") pub = rospy.Publisher("support_vendor_name", String, queue_size=1) support_vendor_name = rospy.get_param("~support_vendor_name", "LexxPluss...
from aiohttp import web from essential_auth.essentialauth import EssentialAuth, VerificationFailedException import aiohttp_jinja2 import jinja2 async def auth_middleware(app, handler): async def middleware_handler(request): try: token = None profile = None if 'token' in ...
import cv2 import imagezmq image_hub = imagezmq.ImageHub() while True: msg, image = image_hub.recv_image() cv2.imshow(msg, image) cv2.waitKey(1) image_hub.send_reply(b'OK')
import torch import torch.nn as nn import torch.nn.functional as F import torch.utils.checkpoint as checkpoint import numpy as np from timm.models.layers import DropPath, to_2tuple, trunc_normal_ from mmcv_custom import load_checkpoint from mmdet.utils import get_root_logger from ..builder import BACKBONES class Mlp...
import logging import random import warnings from multiprocessing import cpu_count from numbers import Number from typing import TYPE_CHECKING, Optional, Sequence, Tuple, Union import numpy as np try: import trimesh except ImportError: trimesh = None from .ncollpyde import TriMeshWrapper, _precision if TYPE...
# Copyright 2004-2005 Joe Wreschnig, Michael Urman # 2012 Christoph Reiter # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation import os import sys from quodlibet.util.importh...
import time import cv2 import object_detector.scanner as scanner from skimage import data if __name__ == "__main__": # Todo: Can unit test framework be applied? image = data.camera() # Get Sample Image image = cv2.resize(image, (100, 100)) image_scanner = scanner.ImageScanner(...
import unittest from collections import deque from ...config import Config from ...sbb import SBB TEST_CONFIG = { 'task': 'reinforcement', 'reinforcement_parameters': { 'environment': 'tictactoe', 'validation_population': 20, 'champion_population': 30, 'hall_of_fame...
from django import dispatch # This will be fired at end of crawling operations, when all Result # objects are ready post_crawl = dispatch.Signal(providing_args=["task_id"]) # Signal will be fired at the end of each scraping action in single page. # This will be corresponded with single Result object. post_scrape = ...
""" Urls de Circles. """ #Django from django.urls import path, include # Django REST Framework from rest_framework.routers import DefaultRouter # Views from .views import circles as circles_views router = DefaultRouter() router.register(r'circles', circles_views.CircleViewSet, basename='circles') urlpatterns = [ ...
#!/usr/bin/python import subprocess; import sys; SEARCH_X="200"; SEARCH_Y="200"; REF_X="100"; REF_Y="100"; STEP="30"; reference=sys.argv[1]; search=sys.argv[2]; nproc=sys.argv[3]; ref_hdr=reference[:reference.rfind(".")]+".hdr"; search_hdr=search[:search.rfind(".")]+".hdr"; ref_samples=""; ref_lines=""; infile=op...
""" DEPRECATD 2017-09-01: ADW: This code is deprecated (probably long before the quoted date). Functions to create and use a look-up table for the signal color probability distribution function. """ import time import numpy import scipy.signal import astropy.io.fits as pyfits import ugali.utils.config import ugali.u...
from flask import Flask, request, make_response from firebase_admin import credentials, messaging import firebase_admin import os import logging cred = credentials.Certificate('secure/private-api-key.json') firebase_admin.initialize_app(credential=cred) # We want to clear out the logs log_name = "logs/log.txt" if os....
import json from random import randint, choice, choices class CantFight(ValueError): pass class NotAMonster(ValueError): pass class Monster(object): def __init__(self, stats): # Save all the stats, in case we want to do something with them at # some later point. Make the more useful on...
from unittest import skipIf from django.conf import settings from nautobot.utilities.choices import ButtonActionColorChoices, ButtonActionIconChoices from nautobot.utilities.testing.integration import SeleniumTestCase @skipIf( "example_plugin" not in settings.PLUGINS, "example_plugin not in settings.PLUGINS...
import math import string import os from ascii_arts import caesar ### FUNCTIONS WITH INPUTS (PARAMETERS AND ARGUMENTS) ''' current_height = 0 def hover(height): print(f"Flying at {height}m") def go_to_goal(x: int = 0, y: int = 0, z: int = current_height): hover(z) print(f"moving to the positon ({x},{y}...
s=input() k=int(input())-1 i=0 while s[i]=="1" and k:k,i=k-1,i+1 print(s[i])
import logging from gym.envs.registration import register logger = logging.getLogger(__name__) register( id='MagicSquare3x3-v0', entry_point='gym_magic.envs:MagicSquare3x3', timestep_limit=100, )
# finding python sentence = 'Learning Python is so easy! Python is now my favourite programming language.' print('Does the word "Python" appear in the sentence?', 'Python' in sentence) print('The first occurrence of "Python" is at index', sentence.find('Python')) print('The last occurrence of "Python" is at index', se...
# -*- coding: utf-8 -*- #from __future__ import print_function import sys import argparse from copy import deepcopy from interval import interval from .csp_parser import CspParser from .csp_semantics import CspSemantics from .contractor_hull import HC4 from .contractor_box import BC3 from .solver import Solver def p...
import re import maya.cmds import mtoa.utils import assetexchange_shared def environment_hdri(asset, selectedVariants): # explode variants variantLabels, variantConfigs = assetexchange_shared.asset.explode_variants( 'Primary', selectedVariants) # iterate variant config for variantConfig in va...
from lisapi import db from lisapi.models.tables import User def init_app(app): @app.cli.command() def seed(): """Add admin user""" admin = User.query.filter_by(username='admin').first() if not admin: print('Creating user admin...') admin = User('admin', 'admin@e...