content
stringlengths
5
1.05M
# """ # This is the interface that allows for creating nested lists. # You should not implement it, or speculate about its implementation # """ #class NestedInteger(object): # def isInteger(self): # """ # @return True if this NestedInteger holds a single integer, rather than a nested list. # :rt...
# SPDX-License-Identifier: MIT """Implementation of :class:`~calingen.interfaces.plugin_api.LayoutProvider` that provides TeX-sources for a simple list of events.""" # local imports from .simple_event_list import SimpleEventList # noqa: F401 default_app_config = "calingen.contrib.layouts.simple_event_list.apps.Cali...
# # 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 # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing...
# -*- coding: utf-8 -*- # Copyright 2013 tsuru authors. All rights reserved. # Use of this source code is governed by a BSD-style # license that can be found in the LICENSE file. import os from fabric.api import abort, cd, env, local, put, run, sudo current_dir = os.path.abspath(os.path.dirname(__file__)) env.tsuru_...
# jsb/plugs/core/chan.py # # """ channel related commands. """ ## jsb imports from jsb.lib.persist import Persist, findnames from jsb.utils.name import stripname from jsb.lib.commands import cmnds from jsb.lib.examples import examples from jsb.lib.callbacks import callbacks from jsb.lib.channelbase import ChannelBas...
import numpy as np import scipy.special from pymanopt.manifolds.manifold import RiemannianSubmanifold from pymanopt.tools.multi import ( multiexpm, multilogm, multiqr, multiskew, multisym, multitransp, ) class SpecialOrthogonalGroup(RiemannianSubmanifold): r"""The (product) manifold of ro...
import requests class Portainer: def __init__(self, base_url, username, password, endpoint=1): self._base_url = base_url self._username = username self._password = password self._current_endpoint = str(endpoint) self._headers = { "Content-Type": 'applicatio...
num = 1 123
from .base import Resource class Projects(Resource): def list(self): return self._get('/projects') def get(self, id_): return self._get('/projects/{0}'.format(id_)) def tasks(self, id_): return self._get('/projects/{0}/tasks'.format(id_))
from pycocoevalcap.bleu.bleu import Bleu from pycocoevalcap.cider.cider import Cider from pycocoevalcap.meteor.meteor import Meteor from pycocoevalcap.rouge.rouge import Rouge from pycocoevalcap.spice.spice import Spice from bert_score import BERTScorer from eval import * from bleurt import score as bleurt_sc import s...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Jan 27 15:32:52 2017 @author: Nadiar """ def gcdRecur(a, b): ''' a, b: positive integers returns: a positive integer, the greatest common divisor of a & b. ''' if (b == 0): return a else: return gcdRecur(b, ...
# Copyright 2020 InterDigital Communications, 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 ...
arr=list(map(int,input().split())) for i in range(0,len(arr)): if(arr[i]>0): arr[len(arr)-i-1]=arr[i] print(arr)
import math import string from functools import reduce import numpy as np # encoder for protein sequence class ProEncoder: elements = 'AIYHRDC' structs = 'hec' element_number = 7 # number of structure kind struct_kind = 3 # clusters: {A,G,V}, {I,L,F,P}, {Y,M,T,S}, {H,N,Q,W}, {R,K}, {D,E}, {...
import sys import time import RPi.GPIO as GPIO lForward=22 lBackward=27 rForward=23 rBackward=24 sleeptime=1 GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) GPIO.setup(lForward, GPIO.OUT) GPIO.setup(lBackward, GPIO.OUT) GPIO.setup(rForward, GPIO.OUT) GPIO.setup(rBackward, GPIO.OUT) i=0 def rforward(x): GPIO.output(r...
# Project Quex (http://quex.sourceforge.net); License: MIT; # (C) 2005-2020 Frank-Rene Schaefer; #_______________________________________________________________________________ from quex.constants import E_R from quex.engine.analyzer.door_id_address_label import DoorID from quex.engine.operations.operation_li...
import numpy as np import pytest from pyabc.random_choice import fast_random_choice def test_fast_random_choice_basic(): """Test the fast random choice function for various inputs.""" # run with many values (method 1) weights = np.random.uniform(0, 1, size=10000) weights /= weights.sum() fast_ran...
# Generated by Django 3.1.3 on 2020-12-20 11:48 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ("api", "0007_artist_userid"), ] operations = [ migrations.RemoveField( model_name="concert", name="state", ), ]
from cmp.ast import * from utils.macros import * from cmp.pycompiler import Grammar from cmp.utils_parser import LR1Parser CoolGrammar = Grammar() # non-terminals program = CoolGrammar.NonTerminal('<program>', startSymbol=True) class_list, def_class = CoolGrammar.NonTerminals('<class-list> <def-class>') feature_list,...
import tkinter as tk class LabeledEntry(tk.Entry): def __init__(self, master=None, label="Search", **kwargs): tk.Entry.__init__(self, master, **kwargs) self.label = label self.on_exit() self.bind('<FocusIn>', self.on_entry) self.bind('<FocusOut>', self.on_exit) def on_e...
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import unicode_literals from __future__ import absolute_import from core_backend import context from core_backend.service import handler from core_backend.libs import token as tk from core_backend.libs.exception import Error from server.domain.models impor...
import requests, json import config api = 'https://api.dictionaryapi.dev/api/v2/entries/en/' # add a word to the end of the link headers = {'Host': 'api.dictionaryapi.dev', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:96.0) Gecko/20100101 Firefox/96.0', 'Connection': 'keep-alive',} def search_a_word(...
__author__ = 'Administrator' class MySqlConfig(object): name = "root" password = "" db = "bichon" hostName = "127.0.0.1" charset = "utf8"
def get_git_ver(): try: import git repo = git.Repo(search_parent_directories=True) return repo.head.object.hexsha except: return "UNKNOWN"
"""Script for starting the data collection service that collects the entire Netatmo history once and then stops. It contains an extra layer of rate limiters to prevent being kicked out of the Netatmo API.""" import os import sys import socket import logging from logging.handlers import TimedRotatingFileHandler import...
""" Image Data Analysis Using Numpy & OpenCV author: Mohammed Innat email: innat1994@gmail.com website: https://iphton.github.io/iphton.github.io/ Please feel free to use and modify this, but keep the above information. Thanks! """ import imageio import numpy as np import matplotlib.pyplot as plt from skim...
import numpy as np bfp = "bf_bnp4_mi159_box%d.txt" params = np.zeros((40,4)) for i in range(40): params[i] = np.loadtxt(bfp%i) import matplotlib.pyplot as plt i = np.arange(40) plt.plot(i, params) plt.show()
#!/usr/bin/python3 class Command: def __init__(self, target_block, action, additional_information): self._target_block = target_block self._action = action self._additional_information = additional_information @property def target_block(self): return self._target_block ...
import json from model import Place, PlaceAlias, get_one_or_create from util import GeometryUtility class GeometryLoader(object): """Load Place objects from a NDJSON document like that generated by geojson-places-us. """ def __init__(self, _db): self._db = _db self.places_by_external...
""" Adds decorator to log execution times """ import os import logging from inspect import isawaitable from time import time def is_debug(): try: level_is_debug = os.environ.get("LOG_LEVEL", "INFO").upper() == "DEBUG" return level_is_debug except Exception as e: logging.error("Error c...
""" ConvNetCifar10 model class. -- willie@cs.cmu.edu """ # Copyright 2017 The TensorFlow Authors. All Rights Reserved. # And modified by Willie, 2018. # # 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 th...
class Config: # flag for working environment currunt_env = "" #Monitor File path MONITERFILE = "monitor.yml" #DB PSQL PS_DATABASE_NAME ="defaultdb" PS_USERNAME = "avnadmin" PS_PASSWORD ="pwg47mw42l6m1fp5" PS_HOST ="pg-task-project-50ec.aivencloud.com" PS_PORT= "26508" ...
class Solution: def containsDuplicate(self, nums: List[int]) -> bool: prelen = len(nums) postlen = len(set(nums)) if prelen == postlen: return False else: return True
# python >= 3.6 import os import sys import faulthandler import collections import multiprocessing as mp import threading import signal import time import queue import json import traceback # _ProcessStatusInfo contains process status information _ProcessStatusInfo = collections.namedtuple('_ProcessStatusInfo', ...
import cv2 import argparse import base64 import json import requests parser = argparse.ArgumentParser() parser.add_argument("--path",type=str) args = parser.parse_args() def img2b64(img): retval, buffer = cv2.imencode('.jpg', img) jpg_as_text = base64.b64encode(buffer) return(jpg_as_text) while True: ...
""" This file implements the class for Euler's equation. This includes a source term to model a toy star, and an atmosphere. """ import numpy class EulerToyStar(object): def __init__(self, gamma=2, rho_atmosphere=1e-6, e_atmosphere=1e-6): assert gamma == 2 self.gamma = gamma self.rh...
from app import flask_app from app import acrawler from flask import request @flask_app.route('/v2/linc/') def index(): return acrawler.get_qs(request.args.get('p'))
import datetime from unittest import mock from jwt.exceptions import InvalidAudienceError from django.contrib.sessions.middleware import SessionMiddleware from django.contrib.auth import get_user_model, logout from django.contrib.auth.models import AnonymousUser from django.core.exceptions import ValidationError from...
# Import local modules from photoshop.api._core import Photoshop class RGBColor(Photoshop): """The definition of an RGB color mode.""" object_name = "RGBColor" def __init__(self, parent): super().__init__(parent=parent) self.blue = self.app.blue self.green = self.app.green ...
#!/usr/bin/python # # Copyright 2009 Google 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 a...
from contentstack_utils.embedded.styletype import StyleType def convert_style(style) -> StyleType: if style == 'block': return StyleType.BLOCK if style == 'inline': return StyleType.INLINE if style == 'link': return StyleType.LINK if style == 'display': return StyleType...
#!/usr/bin/python # # Copyright (C) 2007 Google 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 ...
# local imports from nautilus.conventions.services import connection_service_name, model_service_name from nautilus.models import BaseModel, fields def create_connection_model(service): """ Create an SQL Alchemy table that connects the provides services """ # the services connected services = service._serv...
import unittest from mltoolkit.mldp.steps.readers import JsonReader from mltoolkit.mldp.steps.transformers.general import ChunkSorter from mltoolkit.mldp.tests.common import read_data_from_csv_file, \ concat_data_chunks class TestJsonReader(unittest.TestCase): def test_reading_from_tree_json(self): c...
import json from decimal import Decimal class GeoJSONEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, Decimal): return str(obj) # Let the base class default method raise the TypeError return json.JSONEncoder.default(self, obj) class GeoJSONIterator(): ...
distancia = int(input("Insira a distância a ser percorrida: ")) if distancia <= 200: passagem = distancia * 0.50 else: passagem = distancia * 0.45 print("O preço da passagem ficou em: R$" + str(passagem))
""" The :mod:`websockets.protocol` module handles WebSocket control and data frames as specified in `sections 4 to 8 of RFC 6455`_. .. _sections 4 to 8 of RFC 6455: http://tools.ietf.org/html/rfc6455#section-4 """ __all__ = ['WebSocketCommonProtocol'] import codecs import collections import logging import random imp...
from django.apps import AppConfig class SegmentsConfig(AppConfig): name = 'segments'
__author__ = 'JordSti' import ctypes import os import sprite class direction_sprite_header(ctypes.Structure): _fields_ = [('sprite_name', ctypes.c_char * 64), ('nb_frames', ctypes.c_int32 * 5), ('width', ctypes.c_int32), ('height', ctypes.c_int32) ] ...
from six import text_type, iteritems from contextlib import contextmanager from functools import wraps import os import uuid from lxml import etree import py import allure from allure.constants import AttachmentType, Status from allure.structure import Attach, TestStep, TestCase, TestSuite, Failure, EnvParameter from...
def pytest_configure(config): from glue_plotly import setup setup()
# VRA ABX ACTION TO CREATE DHCP NETWORK ################################################################################ ### Copyright (C) 2019-2020 VMware, Inc. All rights reserved. ### SPDX-License-Identifier: BSD-2-Clause ################################################################################ import requ...
import pytest from operator import attrgetter from vakt.storage.memory import MemoryStorage from vakt.policy import Policy from ..helper import MemoryStorageYieldingExample @pytest.mark.parametrize('st', [ MemoryStorage(), MemoryStorageYieldingExample(), ]) def test_retrieve_all_for_returning_storage(st): ...
import tensorflow as tf import matplotlib.pyplot as plt import os files = ['../img/' + str for str in sorted(os.listdir('../img/'))] img_raw = tf.stack([tf.read_file(file) for file in files]) def decode_func(i): decoded = tf.cast(tf.image.decode_jpeg(i), tf.float32) / (2 ** 8) return decoded img_decoded = ...
from pathlib import Path import os def setHadoopHomeEnvVar(): venvPath = os.getcwd() + '/.venv' hadoopHomePath = Path(Path(venvPath).joinpath('hadoop')) os.environ['HADOOP_HOME'] = str(hadoopHomePath)
# Generated by Django 2.2.7 on 2020-01-05 08:43 from django.db import migrations, models import chat.models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Room', fields=[ ('id', ...
# Generated by Django 2.1.7 on 2019-03-11 11:59 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('odk', '0007_xform_modified_at'), ] operations = [ migrations.AlterModelOptions( name='mediafile', options={'default_related_...
# Copyright 2017 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...
#!/usr/bin/python3 """ AUTHOR: Matthew May - mcmay.web@gmail.com """ # Imports import json import maxminddb import redis import re import random import io from const import META, PORTMAP from argparse import ArgumentParser, RawDescriptionHelpFormatter from sys import exit from time import localtime, sleep, strftime ...
a.index = a / 1 ''' @test(a=missing;$$;a.index) @prefix(a;とても) aとa2[を|が]好き aとa2 ''' df.index = pd.to_datetime(df) ''' @test(pd=df=ds=missing;$$;df.index) [Pandasで、|]__Y__を日付データに変換し、[dfの|]インデックスにする ''' # ピボットテーブル df.pivot_table(index='Pclass', columns='Sex') @ @let @type(df)の{@type('Pclass', カラム)をインデックス}、{@type...
# -*- coding: utf-8 -*- ''' :codeauthor: :email:`Daniel Wallace <dwallace@saltstack.com` ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import os import shutil import tempfile # Import Salt Testing libs from tests.support.runtests import RUNTIME_VARS from tests.s...
# This file is part of Moksha. # Copyright (C) 2008-2010 Red Hat, 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 b...
from rich.text import Text from rich.panel import Panel from rich.padding import Padding from rich.console import Console, Group title1 = ''' ██╗ ██╗ ████████╗ ██████╗ ████████╗ ██║ ██╔╝ ╚══██╔══╝ ██╔═══██╗ ╚══██╔══╝ █████╔╝ ██║ ██║ ██║ ██║ ██╔═██╗ ██║ ██║ ...
import os import testinfra.utils.ansible_runner testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner( os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all') def test_python_version(host): c = host.run('/opt/Python/installations/3.8.1/bin/python3.8 --version') assert '3.8.1' in c.stdout
from contextlib import contextmanager import enum from itertools import islice import typing import pymongo from energuide import dwelling from energuide import logger LOGGER = logger.get_logger(__name__) class EnvVariables(enum.Enum): username = 'ENERGUIDE_USERNAME' password = 'ENERGUIDE_PASSWORD' ho...
from terregex.mlr import Node, NodeList, Literal, NotLiteral, \ In, Negate, Range, Category, MinRepeat, MaxRepeat, \ SubPattern, Branch, Any, parse from terregex.transform import Transformer
# Encoding: UTF-8 # Copyright (c) Marnik Bercx, University of Antwerp # Distributed under the terms of the MIT License import numpy as np import os import shutil import pdb from pybat.core import Cathode, LiRichCathode from pybat.sets import BulkSCFSet, BulkRelaxSet, PybatNEBSet from monty.serialization import loadfn...
from unittest.mock import patch, Mock from django.urls import reverse from rest_framework.views import status from rest_framework.test import APITestCase, APIClient class TestSocialAuthentication(APITestCase): """ This class is to test the social authentication feature for facebook, twitter and google. ...
__source__ = 'https://leetcode.com/problems/maximum-distance-in-arrays/' # Time: O(n) # Space: O(1) # # Description: 624. Maximum Distance in Arrays # # Given m arrays, and each array is sorted in ascending order. # Now you can pick up two integers from two different arrays (each array picks one) and calculate the dis...
"""Support for discovering Wordpress listings.""" from os.path import realpath from re import I, search from lib.readfile import * from lib.request import * class wplisting(Request): def __init__(self,url,data,kwargs): self.url = url self.data = data self.kwargs = kwargs Request.__init__(self,kwargs) def...
# Dark Violet Editor - A Delta Skin mapping editor tool. # Copyright Dark Violet - All Rights Reserved from pathlib import Path from tkinter import * from tkinter import ttk import json import easygui from pdf2image import convert_from_path import tempfile def chooseSize(): size = input("Choose the screen size yo...
import pickle import faiss import torch import numpy as np import Levenshtein from nlgeval import compute_metrics from tqdm import tqdm from transformers import RobertaTokenizer, RobertaModel import pandas as pd from bert_whitening import sents_to_vecs, transform_and_normalize dim = 256 df = pd.read_csv("data/train...
# This scripts use an example of DCGAN described in a TensorFlow tutorial to simulate ultrasound images: https://pytorch.org/tutorials/beginner/dcgan_faces_tutorial.html. import os import torch import torch.nn as nn import utils os.environ["CUDA_VISIBLE_DEVICES"]="0" use_cuda = torch.cuda.is_available() filename = ...
#! /usr/bin/env python # encoding: utf-8 r""" Simplistic utility to extract docstrings from a module or class and throw them into a simple [GitHub Flavoured Markdown](md) document. Its purpose is to quickly generate `README.md` files for small projects. [md]: https://help.github.com/articles/github-flavored-markdown ...
''' Code to make the analysis and figures used in the paper: "The Kepler Catalog of Stellar Flares", J. R. A. Davenport (2016) ''' import numpy as np import matplotlib.pyplot as plt import matplotlib.cm as cm from matplotlib.colors import LogNorm import matplotlib import os import sys import appaloosa import pandas as ...
# Generated by Django 3.1.8 on 2021-04-13 16:19 from decimal import Decimal import django.core.validators from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("store", "0006_auto_20210413_1549"), ] operations = [ migrations.RenameField( ...
# Copyright (c) 2021 elParaguayo # # 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, modify, merge, publish, distrib...
from typing import Any, cast import aws_cdk as cdk from aws_cdk import aws_dynamodb as dynamodb from aws_cdk import aws_iam as iam from constructs import Construct from api.infrastructure import Api from database.infrastructure import Database from monitoring.infrastructure import Monitoring class UserManagementBac...
#!/usr/bin/python from mininet.topo import Topo, SingleSwitchTopo from mininet.net import Mininet from mininet.log import lg, info from mininet.cli import CLI def main(): lg.setLogLevel('info') net = Mininet(SingleSwitchTopo(k=3)) net.start() h1 = net.get('h1') #server h2 = net.get('h2') #control...
#!/usr/bin/python # Copyright (c) 2017-present Alibaba Group Holding Limited. He Guimin <heguimin36@163.com.com> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under t...
#-*- coding: utf-8 -*- # Copyright 2019 ibelie, Chen Jie, Joungtao. All rights reserved. # Use of this source code is governed by The MIT License # that can be found in the LICENSE file. from app import route, response, redirect, config from logic.account import github import utils SESSION = utils.Session(config.SESS...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('xenserver', '0004_auto_20160622_0825'), ] operations = [ migrations.AlterField( model_name='template', ...
import pandas as pd import numpy as np import random from sklearn.decomposition import FastICA seed = snakemake.params['random_seed'] random.seed(seed) np.random.seed(seed) X = pd.read_csv(snakemake.input[0]) X.set_index('index',inplace=True) X = X.T ica = FastICA(n_components=int(snakemake.params['comps']), random_s...
import sys from tests.mocks import ui, console, speech # mock pythonista ui package sys.modules['ui'] = ui sys.modules['console'] = console sys.modules['speech'] = speech from AreYouEnabledView import AreYouEnabledView def test_Name(): toto = AreYouEnabledView() # toto.button_pressed(namedtuple('Sender', ['n...
#! /usr/bin/env python3 # coding: utf-8 from __future__ import annotations import typing as t import pendulum from psycopg2.extensions import connection from withings_api import AuthScope, WithingsApi, WithingsAuth from withings_api.common import ( Credentials, GetActivityField, MeasureGetActivityResponse...
import datetime from app.models import db, bcrypt class OrgUserModel(db.Model): __tablename__ = "orgUser" orgId = db.Column(db.Integer, db.ForeignKey('org.id'), primary_key=True) userId = db.Column(db.Integer, db.ForeignKey('user.id'), primary_key=True) role = db.Column(db.String(256), nullable=False) crea...
#py3.7 def functionCalc(operation, arg1, arg2): d = {'add': lambda x, y: x + y , 'sub': lambda x, y: x - y, } d['mul'] = lambda x, y: x * y d['div'] = lambda x, y: arg1 / arg2 #using external arg1 and arg2 in lambda #print(d) #for logging return d.get(operation, lambda x, y: None)(arg1, ar...
# This code is part of Qiskit. # # (C) Copyright IBM 2021. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative wo...
from test.assert_json import assert_json from topcoder.stitch import solution def test_stitch (): assert_json('stitch', solution)
import unittest from array_product_except_self.solution import Solution class SolutionTest(unittest.TestCase): def test_solution(self): s = Solution() tests = [ ([1, 2, 3, 4], [24, 12, 8, 6]), ] for test in tests: input = test[0] expected =...
def digit_sum(x): return sum([ord(s) - ord('0') for s in str(x)]) if __name__ == "__main__": cnt = 0 ans = [] for i in range(2, 50): for j in range(2, 400): v = j ** i if digit_sum(v) == j: cnt += 1 ans.append(v) if cnt >= ...
# -*- coding: utf-8 -*- import datetime import json from decimal import Decimal from collections import OrderedDict, namedtuple from collections.abc import Iterable from itertools import chain as iter_chain from ..domobj import dset, DSetBase, dobject, reshape from .dtable import json_object, dtable, dsequence from...
import csv from django.core.exceptions import PermissionDenied from django.http import HttpResponse def export_as_csv(modeladmin, request, queryset): """ Generic csv export admin action. """ if not request.user.is_staff: raise PermissionDenied opts = modeladmin.model._meta response = Ht...
"""Create users table Revision ID: 63a018fe1c9c Revises: Create Date: 2021-06-13 19:56:00.090344 """ from sqlalchemy import BigInteger, Column, Integer, String from alembic import op # revision identifiers, used by Alembic. revision = "63a018fe1c9c" down_revision = None branch_labels = None depends_on = None def...
import os import testinfra.utils.ansible_runner testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner( os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all') def test_htpdate_service(host): htpdate = host.service("htpdate") assert htpdate.is_running assert htpdate.is_enabled def test_htp...
import pandas as pd import numpy as np def find_and_replace(dataframe, column_name, find, replace): dataframe[column_name] = dataframe[column_name].str.replace(find, replace, regex=True) def process_data(path_to_df): df1 = ( pd.read_csv(path_to_df, header=None) .rename(columns = {0: 'Age'...
# # Copyright IBM Corp. All Rights Reserved. # # SPDX-License-Identifier: Apache-2.0 # import unittest import subprocess import os fca_sample_directory = '../../fabric-samples/fabric-ca' class ACL(unittest.TestCase): def test_FAB6490_Using_FCA_With_ACL_Permissioning(self): ''' In this ACL test,...
class Solution: def solve(self, s): count = 0 res = 0 for i in s: if i == '1': count += 1 else: count = 0 res += count return res % (10 ** 9 + 7)
km = float(input('Qual a quantidade de KM rodados? ')) dias = int(input('Qual a quantidades de dias alugados? ')) KM = 0.15 * km DIAS = 60 * dias total = KM + DIAS print('O valor total foi de RS{:.2f}'.format(total))
# Copyright (c) 2020 Horizon Robotics. 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 applicab...