content
stringlengths
5
1.05M
import inspect import textwrap import shlex from docopt import docopt class Cmd3Command (object): pass def command(func): ''' A decorator to create a function with docopt arguments. It also generates a help function @command def do_myfunc(self, args): """ docopts text """ pass ...
from collections import defaultdict import inspect import os import os.path import unittest from typing import Dict from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys from selenium.webdriver.support.expected_conditions import presence_of_element_l...
import logging import sys from configargparse import ArgParser from mowgli_etl.cli.commands.augment_cskg_release_command import AugmentCskgReleaseCommand from mowgli_etl.cli.commands.drive_upload_command import DriveUploadCommand from mowgli_etl.cli.commands.etl_command import EtlCommand try: from mowgli_etl.cli....
#!/usr/bin/env python3 import io import os import hashlib WORK_DIR = os.path.dirname(os.path.realpath(__file__)) WIN_INC_DIR = os.path.join(WORK_DIR, 'include') API_HASH_FILE = os.path.join(WORK_DIR, 'src', 'ag_dns_h_hash.inc') API_FILES = [ os.path.join(WIN_INC_DIR, 'ag_dns.h'), ] file_hash = hashlib.sha256()...
n1 = int(input('Digite um número: ')) n2 = int( input('Digite outro número: ')) if n1>n2: print('O primeiro número é maior') elif n2>n1: print('O segundo número é maior ')
import re import functools class command(object): def __init__(self, matcher=None): self._matcher = matcher def __call__(self, func): # Default the command's name to an exact match of the function's name. # ^func_name$ matcher = self._matcher if matcher is None: ...
# -*- coding: utf-8 -*- """ mslib.msui.mpl_map ~~~~~~~~~~~~~~~~~~ Map canvas for the top view. As Matplotlib's Basemap is primarily designed to produce static plots, we derived a class MapCanvas to allow for a certain degree of interactivity. MapCanvas extends Basemap by functionality to, for ...
def encode(valeur,base): """ int*int -->String hyp valeur >=0 hypothèse : base maxi = 16 """ chaine="" if valeur>255 or valeur<0 : return "" for n in range (1,9) : calcul = valeur % base if (calcul)>9: if calcul==10: bit='A' if...
__author__ = 'Alex Hlukhov' # -*- coding: utf-8 -*- class Group(object): def __init__(self, name, header, footer): self.name = name self.header = header self.footer = footer
#!/usr/bin/python3 from jjcli import * c=clfilter(opt="a") i=j=w=r=0 ocr = {} #for line in c.input(): for par in c.paragraph(): #all = findall(r"[a-zA-Z]+", par) for w in findall(r"\w+", par): ocr[w] =1 if w not in ocr else ocr[w] + 1 #print(all) def dict_word(d): for k,v in sorted(d.items(), k...
# type: ignore import unittest from evilunit import test_target @test_target("prestring:LazyArguments") class LazyArgumentsTests(unittest.TestCase): def test_it(self): target = self._makeOne([1, 2, 3]) self.assertEqual(str(target), "1, 2, 3") def test_modified_after_rendeing__no_changed(self)...
import os import json import numpy as np import pandas as pd import random import unittest from sklearn.ensemble import RandomForestClassifier from sklearn.model_selection import train_test_split from sklearn.compose import ColumnTransformer from sklearn.preprocessing import OneHotEncoder, StandardScaler from sklearn.i...
## MapGenerator ## ## Shortcut to regenerate the map and start/stop HOF's MapFinder utility. ## ## Shortcuts: ## ## ALT + G doRegenerate() ## ALT + CTRL + G doStart() ## ALT + CTRL + SHIFT + G doStop() ## ## Adapted from HOF Mod 3.13.001. ## ## Notes ## - May be init...
import scrapy class MySpider(scrapy.Spider): name = 'myspider' def start_requests(self): return [scrapy.FormRequest('http://www.example.com/login', formdata={'user': 'json', 'pass': 'secret'}, callback=self.login)] def login(self, response): pass
#!/usr/bin/env python3 ############################################################################## # This script takes a gap file produced by prune_infreq.py or SPLATT and a map # file of keys, and merges them into a new map file with gapped keys removed. ############################################################...
for i in range(int(input())): # IntegerInput word = input() word=word.upper() vowels = ['A', 'E', 'I', 'O', 'U'] count = 0 # Removed = for j in range(0, len(word)): # Colon & len if word[j] in vowels: # Removed bracket if j == 0: # Added = count += 1 ...
""" @file @brief Check various settings. """ import sys import os import site from io import BytesIO import urllib.request as urllib_request def getsitepackages(): """ Overwrites function :epkg:`getsitepackages` which does not work for a virtual environment. @return site-package somewhere ...
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% # '''Class for boxes in complex frequency space''' # The routines of this class assist in the solving and classification of # QNM solutions # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% # class cwbox: # ***********...
import asyncio import logging import sys import click from solarium.player import Player from . import led from .utils import update_color LOG_FORMAT = "%(asctime)s %(levelname)-8s %(message)s" logger = logging.getLogger(__package__) @click.command() @click.argument("latitude", type=float) @click.argument("longi...
import requests # Basic Variables MIN_RANGE = 22000 MAX_RANGE = 40000 BASE_URL = 'http://B%d.cdn.telefonica.com/%d/ch%t/%s.m3u8' CHANNELS_IDS = ['NICK_SUB', 'DSNJR_SUB', '40TV_SUB', 'DSNYXD_SUB', 'COCINA_SUB', '24HORAS_SUB', 'INVITADO_SUB', 'FOX_SUB', 'AXN_SUB', 'CLL13_SUB', 'TNT_SUB', 'FOXCRIME_SUB', 'CSM...
#!/usr/bin/env python # -*- coding: utf-8 -*- """Tests for `json2xml` package.""" import unittest from collections import OrderedDict import pytest import xmltodict from json2xml import json2xml from json2xml.utils import readfromjson, readfromstring, readfromurl, JSONReadError, StringReadError, URLReadError clas...
secondNamePath=r'C:\Users\Billy\PycharmProjects\TestHackZurich2018\Second_Names' maleNamePath=r'C:\Users\Billy\PycharmProjects\TestHackZurich2018\MaleNames' femaleNamePath=r'C:\Users\Billy\PycharmProjects\TestHackZurich2018\FemaleNames' jsonPath=r'C:\Users\Billy\PycharmProjects\TestHackZurich2018\users_json' countOfUse...
# -*- coding: utf-8 -*- # # Copyright 2011 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 o...
# encoding: utf-8 from bs4 import BeautifulSoup from nose.tools import ( assert_equal, assert_not_equal, assert_raises, assert_true, assert_in ) from mock import patch, MagicMock from routes import url_for import ckan.model as model import ckan.plugins as p from ckan.lib import search import cka...
# %% __init__(), no argument import parent_import from tune_easy import LGBMRegressorTuning import pandas as pd # Load dataset df_reg = pd.read_csv(f'../sample_data/osaka_metropolis_english.csv') TARGET_VARIABLE = 'approval_rate' # Target variable USE_EXPLANATORY = ['2_between_30to60', '3_male_ratio', '5_household_mem...
#!/usr/bin/env python # -*- coding: utf-8 -*- # from __future__ import unicode_literals AUTHOR = 'Ron Scott-Adams' SITENAME = 'MD Options Test' SITEURL = '' PATH = 'content' TIMEZONE = 'America/Chicago' DEFAULT_LANG = 'en' # Feed generation is usually not desired when developing FEED_ALL_ATOM = None CATEGORY_FEED_...
# Rewritten by RayzoR import sys from com.l2jfrozen.gameserver.model.quest import State from com.l2jfrozen.gameserver.model.quest import QuestState from com.l2jfrozen.gameserver.model.quest.jython import QuestJython as JQuest qn = "269_InventionAmbition" class Quest (JQuest) : def __init__(self,id,name,descr): ...
from ipykernel.kernelapp import IPKernelApp from . import BakeryKernel IPKernelApp.launch_instance(kernel_class=BakeryKernel)
""" Entry point """ from repl import Repl def run(): Repl().loop()
import click from ..alias import AliasedGroup from .. import wrapboto, display @click.group(cls=AliasedGroup, short_help='Delete resources.') def delete(): pass @delete.command(name='service') @click.argument('service', required=True) @click.option('--force', is_flag=True, default=False, help='Scale down count...
from collections.abc import Sequence from pathlib import Path import os import copy import pytest from regolith.schemas import SCHEMAS, validate, EXEMPLARS from pprint import pprint @pytest.mark.parametrize("key", SCHEMAS.keys()) def test_validation(key): if isinstance(EXEMPLARS[key], Sequence): for e i...
from .entity import EntityType, Entity from .validator import PropertyValidator from calm.dsl.store import Cache from calm.dsl.constants import CACHE # Ref class RefType(EntityType): __schema_name__ = "Ref" __openapi_type__ = "app_ref" @classmethod def pre_decompile(mcls, cdict, context, prefix="")...
import unittest from kdap import analysis import os import shutil import json class TestAnalysis(unittest.TestCase): def setUp(self): self.test_dir = os.path.join(os.path.dirname(__file__), 'testOutput/') self.ropar_filename = 'Indian_Institute_of_Technology_Ropar.knolml' self.zinc_filenam...
#!/usr/bin/env python ''' It can save the contents of the file to the mysql database. ''' import os import random import MySQLdb #import string f = open(os.getcwd()+'\\2','w') for x in range(200): words = [chr(a) for a in range(65,91)]+[chr(a) for a in range(97,122)]+[str(a) for a in range(0,11)] # It is equal to...
# -*- coding: utf-8 -*- #列表页相关 # @Author : joker # @Date : 2019-01-11 from flask import render_template, jsonify, request, current_app from flask_login import current_user from app.common.response_code import RET from ...common import constants from app.models import House from ..v1 import api @api.route('/searc...
import xml.etree.ElementTree as etree from html import unescape from textwrap import dedent from markdown.extensions import Extension from markdown.treeprocessors import Treeprocessor from pygments.formatters import HtmlFormatter from pygments.lexers import get_lexer_by_name from pygments.styles import get_style_by_na...
from typing import List """ # Definition for a Node. class Node: def __init__(self, val, left=None, right=None): self.val = val self.left = left self.right = right """ class Solution: def treeToDoublyList(self, root: 'Node') -> 'Node': if root == None: return root ...
# Generated by Django 2.0.7 on 2018-11-15 05:03 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('eclass', '0008_auto_20181109_2243'), ] operations = [ migrations.AddField( model_name='list', name='Subject_list', ...
import torch import torch.linalg class HalfSquared: def solve_dual(self, P, c): m = P.shape[1] # number of columns = batch size # construct lhs matrix P* P + m I lhs_mat = torch.mm(P.t(), P) lhs_mat.diagonal().add_(m) # solve positive-definite linear system using Cholesk...
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! """Client and server classes corresponding to protobuf-defined services.""" import grpc from google.protobuf import empty_pb2 as google_dot_protobuf_dot_empty__pb2 import neurotransmitter_pb2 as neurotransmitter__pb2 class NeuronAPIStub(object): ...
import matplotlib.pyplot as plt _COLORS = """ #a6cee3 #1f78b4 #b2df8a #33a02c #fb9a99 #e31a1c #fdbf6f #ff7f00 #cab2d6 #6a3d9a #ffff99 #b15928""".split() def plot_concellation(data_dict): corners = data_dict.corners pattern_id = data_dict.pattern_id.squeeze() ...
# generated from genmsg/cmake/pkg-genmsg.context.in messages_str = "/home/robproj/code/convoy/airforce_ws/src/crazyflie_ros/crazyflie_driver/msg/LogBlock.msg;/home/robproj/code/convoy/airforce_ws/src/crazyflie_ros/crazyflie_driver/msg/GenericLogData.msg;/home/robproj/code/convoy/airforce_ws/src/crazyflie_ros/crazyflie...
#!/usr/bin/env python3 import sys, yaml from jinja2 import Environment, FileSystemLoader if __name__ == "__main__": root_dir = sys.argv[1] template_filename = sys.argv[2] yaml_filename = sys.argv[3] with open('{}/{}'.format(root_dir, yaml_filename)) as y: config_data = yaml.safe_load(y) # print(config_data) ...
import unittest from test_env import TestEnv class TestSet(TestEnv): def test_cpy_constructor(self): code=""" def are_equal(s1): s2 = set(s1) return s2 == s1 """ self.run_test(code, {'jack', 'sjoerd'}, are_equal=[{str}]) def test_in(self): self.run_test("def _in(a,b):\n return ...
import os, csv, requests, json, time, sys import scraper, config from multiprocessing.dummy import Pool as ThreadPool def get_recent_run(pv_path): #find the most timestamp of shops added to the archive scraper.pprint('--get recent run') files = os.listdir(pv_path) dates = [] for f in files: ...
# Third step import cv2 import glob fps = 30 image_folder = '/home/duy/Documents/mmdetection/result_images/result_4' video_name = './' + str(fps) + '_fps_video.avi' img_array = [] frameSize = () for filename in sorted(glob.glob(image_folder + '/*.png')): img = cv2.imread(filename) height, width, layers = img.s...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Oct 11 14:52:44 2018 @author: Alexander Hadjiivanov @license: MIT ((https://opensource.org/licence/MIT) """ import cortex.cortex as ctx import cortex.network as cn import cortex.layer as cl import time import math import torch import torch.nn as tn i...
#!/usr/bin/env python3 # Import standard modules ... import glob import os # Import special modules ... try: import PIL import PIL.Image except: raise Exception("\"PIL\" is not installed; run \"pip install --user Pillow\"") from None # Import my modules ... try: import pyguymer3 import pyguymer3....
""" FactSet ESG API FactSet ESG (powered by FactSet Truvalue Labs) applies machine learning to uncover risks and opportunities from companies' Environmental, Social and Governance (ESG) behavior, which are aggregated and categorized into continuously updated, material ESG scores. The service focuses on company...
#!/usr/bin/env python import os import sys import unittest from collections import namedtuple sys.path = [ os.path.abspath(os.path.join(os.path.dirname(__file__), '../..')) ] + sys.path from pluckit import pluck class CornerCasesTest(unittest.TestCase): def test_null_handle(self): data = [1, 2, 3] ...
import json import requests import xml.etree.ElementTree as ET import webbrowser from const import * import urllib.request class Wrapper(): payload="""<scan:ScanSettings xmlns:scan="http://schemas.hp.com/imaging/escl/2011/05/03" xmlns:dd="http://www.hp.com/schemas/imaging/con/dictionaries/1.0/" xmlns:dd3="http://ww...
"""Exception classes used throughout the FindTrajectory project. AUTHOR: Max Birkett <m.birkett@liverpool.ac.uk>, Department of Chemistry, University of Liverpool, UK. RELEASE: 2022-02-04, version 0.1. DEPENDENCIES: Python 3.6. LICENCE: Please see LICENCE.txt for more details. """ class AppError(Exception): """Gener...
from selenium_ui.confluence import modules from extension.confluence import extension_ui # noqa F401 # this action should be the first one def test_0_selenium_a_login(confluence_webdriver, confluence_datasets, confluence_screen_shots): modules.login(confluence_webdriver, confluence_datasets) def test_1_seleniu...
from django.urls import path,include from .views import ( HomeView, ItemDetailView, ) app_name = 'mysalon' from django.urls import path from django.conf.urls import url from . import views urlpatterns = [ path('home/',HomeView.as_view(),name='home'), path('product/<slug>/',ItemDetailView.as_view(),...
# -*- coding: utf-8 -*- """ Time Series Reader for the SMAP Time Series """ from pygeogrids.netcdf import load_grid from pynetcf.time_series import GriddedNcOrthoMultiTs import os from netCDF4 import num2date import pandas as pd from io_utils.read.geo_ts_readers.mixins import OrthoMultiTsCellReaderMixin class SMAPTs...
#!/usr/bin/python3 import os import sys import re def execute(command): cmd = command.split() #print('PID: ', os.getpid(), 'about to execute: ', cmd) # Check if command[0] is itself a path if os.path.exists(cmd[0]): os.execve(cmd[0], cmd, os.environ.copy()) else: for directory in ...
#!/usr/bin/env python # MIT License # # Copyright (c) 2017 Dan Persons <dpersonsdev@gmail.com> # # 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 limi...
import os os.environ["CUDA_VISIBLE_DEVICES"] = "1" import argparse import torch import torch.utils.data from torch import nn, optim from torch.nn import functional as F from torchvision import datasets, transforms from torchvision.utils import save_image from dataset import * from model import * from tqdm import tqdm...
"""setup file for pycsdl2""" import os import re import shlex import subprocess from os.path import join from glob import glob import distutils.util try: from setuptools import setup, Extension except ImportError: from distutils.core import setup from distutils.extension import Extension def pkg_config(pa...
import os.path def main(request, response): type = request.GET.first("type", None) if type != None and "svg" in type: filename = "green-96x96.svg" else: filename = "blue96x96.png" path = os.path.join(os.path.dirname(__file__), "../../../images", filename) body = open(path, "rb").r...
from django.contrib.admin import AdminSite from django.test import TestCase from django.test.client import RequestFactory from ltilaunch.admin import LTIToolConsumerAdmin, LTIToolProviderAdmin from ltilaunch.models import LTIToolConsumer, LTIToolProvider class LTIToolConsumerAdminTestCase(TestCase): def setUp(se...
from os import path this_dir = path.dirname(path.realpath(__file__)) input_file = path.join(this_dir, "input.txt") diff_count = {1: 0, 2: 0, 3: 0} distinct_arrangements = 0 def get_num_combintations_ending_with(num, input_dict): return input_dict.get(num - 1, 0) \ + input_dict.get(num - 2, 0) \ +...
import requests import json import time def getETHValue(): # GraphQL Query query = f'''{{ token(id: "0x6b175474e89094c44da98b954eedeac495271d0f"){{ name symbol decimals derivedETH tradeVolumeUSD totalLiquidity }} }}'...
""" Wallet Exceptions """ class PassParameterException(Exception): """ Parameter based Exception """
dj-database-url==0.5.0 Django==2.2.7 django-bootstrap3==11.1.0 django-heroku==0.3.1 gunicorn==20.0.0 Pillow==6.2.1 psycopg2==2.8.4 pytz==2019.3 sqlparse==0.3.0 whitenoise==4.1.4
# -*- coding:utf-8 -*- # Author: hankcs # Date: 2020-01-09 00:06 import hanlp recognizer = hanlp.load(hanlp.pretrained.ner.MSRA_NER_BERT_BASE_ZH) print(recognizer([list('孽债 (上海话)')])) print(recognizer(['超', '长'] * 256))
#!/usr/bin/python """ 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...
import datetime as dt def datas(): data = dt.datetime.now() data_br = data.strftime('%d/%m/%Y') return data_br def horas(): hora = dt.datetime.now() hora_br = hora.strftime('%H:%M:%S') return hora_br
""" * Copyright 2019 EPAM Systems * * 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,...
''' Write a program that takes a list of numbers (for example, a = [5, 10, 15, 20, 25]) and makes a new list of only the first and last elements of the given list. For practice, write this code inside a function. ''' def giveFirstAndLast(listX): return [listX[0],listX[-1]] a = [5, 10, 15, 20, 25] myList = giveFi...
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from parlai.utils.testing import AutoTeacherTest # noqa: F401 class TestBotAdversarialDialogueTurn4Teacher(A...
import argparse import glob import hashlib import json import os import random import re import shutil import sys import zipfile import networkx as nx from BlackDuckUtils import BlackDuckOutput as bo from BlackDuckUtils import Utils as bu from BlackDuckUtils import bdio as bdio from BlackDuckUtils import globals as bd...
"""Helper functions to detect settings after app initialization. AKA 'dynamic settings'""" from distutils.util import strtobool from functools import lru_cache # # X_auth_enabled checks to see if a backend has been specified, thus assuming it is enabled. # Leverages `lru_cache` since these are called per user sessio...
""" Tests for the DJORNL Parser At the present time, this just ensures that the files are parsed correctly; it does not check data loading into the db. These tests run within the re_api docker image. """ import json import unittest import os from importers.djornl.parser import DJORNL_Parser from spec.test.helpers im...
from django.shortcuts import redirect, render from django.views import View from .forms import TestForm from .models import Post class PostUpdate(View): def get(self, request, pk): post = Post.objects.get(id=pk) bound_form = TestForm(instance=post) return render(request, 'blog/post_update...
"""Provides a Star class for using stars from the Trident API. """ from pykep import epoch, AU from pykep.planet import keplerian import requests from tridentweb.constant import Constant class Star: """Represents a star. Arguments: system_id - ID number denoting the solar system. star_id - ID number...
from django.test import TestCase from django.urls import reverse from rest_framework.test import APIClient from rest_framework import status from ..models import Product, Category import requests class CategoryAPITestCase(TestCase): def setUp(self): self.client = APIClient() self.category_api = {...
""" Read .nyzoblock file from ../data directory and convert to a list of native blocks objects. No sanity check / validation yet, but checked to match nyzo website for first files. """ import sys sys.path.append('../') from pynyzo.block import Block blocks = Block.from_nyzoblock('../data/000000.nyzoblock', verbose=Fa...
############################################################################## # Copyright (c) 2017 Huawei Technologies Co.,Ltd and others. # # All rights reserved. This program and the accompanying materials # are made available under the terms of the Apache License, Version 2.0 # which accompanies this distribution, ...
#!/usr/bin/env python3 """Some shared testing infrastructure.""" from contextlib import contextmanager import io try: from io import StringIO except ImportError: from StringIO import StringIO import os import shutil import sys import tempfile class NormalizedStringIO(StringIO): """StringIO, with write o...
#!/usr/bin/python # this source is part of my Hackster.io project: https://www.hackster.io/mariocannistra/radio-astronomy-with-rtl-sdr-raspberrypi-and-amazon-aws-iot-45b617 # this program will output the Jupiter-IO radio storm predictions in text format. # It's a port to python of an older QBasic program whose orig...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- help_info = """ This script uses takes a TRUST image and extracts the estimated blood T2 from the superior sagittal sinus. It then applies a number of models to quantify venous oxygenation. The script will create: 1) a folder in the TRUST images directory called 'tru...
from json import JsonObject from draftHost import models import fantasy, college class JsonNflPosition(JsonObject): pass # No extra fields needed class JsonNflPlayer(JsonObject): fields = ['first_name', 'last_name'] functions = ['team', 'college', 'nfl_position', 'fantasy_position', ...
# -*- coding: utf-8 -*- """ Created on Fri Dec 10 20:14:07 2021 @author: jorge """ from PIL import Image import matplotlib.pyplot as plt im1 = Image.open('D:/jorge/Documents/ISPRS/Potsdam/1_DSM/dsm_potsdam_02_10.tif') width = 2560 height = 2560 im2 = im1.resize((width, height), Image.NEAREST) im3 = im1.resize(...
from util.module import make_class_instance from .road import Road from .curve_builder import CurveBuilder from .curve_resolver import CurveResolver class RoadBuilder: def __init__(self): self.links = set() self.lanes = set() self.curve_builders = {} self.auto_id_counter = 0 d...
# definitions de fonctions def aire_carre(cote): aire = cote * cote return aire def aire_rectangle(hauteur, largeur): aire = hauteur * largeur return aire def aire_carre2(cote): aire = aire_rectangle(cote, cote) return aire def aire_rectangle2(hauteur, largeur=None): if largeur is None ...
# ==BEGIN LICENSE== # # MIT License # # Copyright (c) 2018 SRI Lab, ETH Zurich # # 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 right...
from crypt import methods from lib2to3.pgen2.token import EQUAL from flask import render_template, Blueprint, request from conexao import start_connection_db, close_connection_db cadastro = Blueprint('cadastro',__name__,static_folder='static',template_folder='templates') @cadastro.route('', methods=['GET','POST']) de...
#!/usr/bin/env python3 # Copyright (C) 2020-2021 The btclib developers # # This file is part of btclib. It is subject to the license terms in the # LICENSE file found in the top-level directory of this distribution. # # No part of btclib including this file, may be copied, modified, propagated, # or distributed except...
from flask import Flask, jsonify, request # import objects from the Flask model from email_service import authenticate, send_message, create_message app = Flask(__name__) # define app using Flask @app.route('/', methods=['POST']) def read_html(): html_message = request.data.decode("UTF-8") recipient = requ...
import pytorch_lightning as pl import torch import torchmetrics # LightningModule that receives a PyTorch model as input class LightningClassifier(pl.LightningModule): def __init__(self, model, learning_rate, log_accuracy): super().__init__() self.log_accuracy = log_accuracy # Note that ...
# utils/profdata_merge/server.py # # This source file is part of the Swift.org open source project # # Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors # Licensed under Apache License v2.0 with Runtime Library Exception # # See http://swift.org/LICENSE.txt for license information # See http://swift.or...
# Задача 9, Вариант 12 # Создайте игру, в которой компьютер выбирает какое-либо слово, а игрок должен его отгадать. # Компьютер сообщает игроку, сколько букв в слове, и дает пять попыток узнать, есть ли какая-либо # буква в слове, причем программа может отвечать только "Да" и "Нет". Вслед за тем игрок должен попроб...
# This file holds the base algorithms which manipulate the graph and do flow simulation # It avoids dealing with UI and other concerns from functools import partial from collections import defaultdict import tqdm def check_nodes_equal_height(node_a, node_b, state, settings): return ( settings.height_map[...
from django.shortcuts import render, redirect, reverse, get_object_or_404 from django.contrib.auth.decorators import login_required from django.contrib.auth import get_user_model from django.http import HttpResponse from django.views.generic import CreateView, ListView, DetailView, TemplateView from django.views import...
# Given a 2D list, let's call a element "smooth" if index of the # element in its 1D list plus the element is even. For example, # given the 2D list [[0,4][2,6]], the 1st element of each of the # 1D list is considered "smooth" because 0 + 0 is 0 and 0 + 2 is 2 # (both are even numbers). Find the maximum "smooth" el...
import os import re from cort.core.spans import Span from cort.core.corpora import Corpus from _collections import defaultdict from nltk import cluster import codecs import subprocess import shutil import fileinput # annotator = 'minh' annotator = 'cltl' metrics = 'ceafm' scorer_path = 'reference-coreference-scorers/v...
"""Tests for the ``signed_request`` module.""" from datetime import datetime, timedelta from nose.tools import * from aiofacepy import SignedRequest TEST_ACCESS_TOKEN = '181259711925270|1570a553ad6605705d1b7a5f.1-499729129|8XqMRhCWDKtpG-i_zRkHBDSsqqk' TEST_SIGNED_REQUEST = u'' \ 'mnrG8Wc9CH_rh-GCqq97GFAPOh6AY...
import inspect import bokeh import matplotlib import matplotlib.pyplot as plt import numpy as np import sys import os import glob import pyspawn import h5py from bokeh.io import curdoc from bokeh.layouts import row, widgetbox from bokeh.models import ColumnDataSource from bokeh.models.widgets import Slider, TextInput f...
import os import sys def inject_index_html(filename): with open(filename, "r") as f: content = f.readlines() PATTERNS = [ "/assets", "/_dash", ] for line_idx in range(len(content)): for p in PATTERNS: content[line_idx] = content[line_idx].replace( ...