content
stringlengths
5
1.05M
from loan_payments.common import field_names, lookup def validate_input_add_new_bank(inputs): flag = True msg = 'all good' name = inputs[field_names.name] if name == '' or len(name) > 10: msg = 'name is blank or length is more than 10 characters' flag = False else: obj = lo...
from settings_gis import * # noqa # Run `spatialite tastypie-spatialite.db "SELECT InitSpatialMetaData();"` before # trying spatialite on disk. # "InitSpatiaMetaData ()error:"table spatial_ref_sys already exists" can be ignored. DATABASES['default']['ENGINE'] = 'django.contrib.gis.db.backends.spatialite' DATABASES['d...
from ..base import SystemVariant, NamedType, BaseUnit, UnitSystem, ScalingMeasurement, Scale __all__ = ['Time'] @UnitSystem @NamedType class Time(ScalingMeasurement): Millisecond: type Second: type Minute: type Hour: type Day: type Week: type Year: type Decade: type Century: type Millennia: type class _S...
# imports import logging import getpass from conflux import Conflux import pprint import os import sys import datetime # info __author__ = "Jorge Somavilla" # initialize logger logger = logging.getLogger('graphyte') pp = pprint.PrettyPrinter(indent=4) def build_confluence_page(d, c, p, s): """Create content st...
from django.urls import reverse from django.db import models from django.contrib.postgres.fields import ArrayField from prplatform.core.models import TimeStampedModel from prplatform.users.models import User class BaseCourseManager(models.Manager): def get_by_natural_key(self, code): return self.get(code...
#!/usr/bin/env python3 def door_handler(sender, message, bot_id, app_id): ''' Get in the door wherever you at ''' usage_message = "Let me in the door!\nusage: !door <optional: location | in>" message = message.strip().split() if len(message) == 1: return "Let me in!" elif len(m...
from base.base_train import BaseTrain import sys import numpy as np import tensorflow as tf import time class ExampleTrainer(BaseTrain): def __init__(self, sess, model, config): super(ExampleTrainer, self).__init__(sess, model, config) self.best_score = float('inf') def train(self): t...
# Copyright 2018 D-Wave Systems 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...
#Quest reworked like L2OFF by OnePaTuBHuK special for L2JFrozen. All rights reserved. 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 = "622_SpecialtyLiquorDeli...
# # Copyright (c) nexB Inc. and others. # Extracted from http://nexb.com and https://github.com/nexB/debian_inspector/ # Copyright (c) Peter Odding # Author: Peter Odding <peter@peterodding.com> # URL: https://github.com/xolox/python-deb-pkg-tools # SPDX-License-Identifier: MIT # # Visit https://aboutcode.org and https...
from .seq import Seq from .word import Word from .dsl import pattern __all__ = ['constants', 'word', 'seq', 'patterns', 'dsl']
size = int(input()) def spaces_count(size): spaces = size - 1 return spaces def single_line(spaces, stars): line = '' line += ' ' * (spaces - stars) line += '* ' * (stars + 1) return line def triangle1(spaces): for stars in range(spaces): print(single_line(spaces, stars)) ...
from flask import request, render_template, jsonify, url_for, redirect, g, session from .models import AppUser, Module, School, Staff, OAuth2Token from index import app, db, mongo_db from bson.json_util import dumps from sqlalchemy.exc import IntegrityError from .utils.auth import generate_token, requires_auth, verify_...
# Author: Nic Wolfe <nic@wolfeden.ca> # URL: http://code.google.com/p/sickbeard/ # # This file is part of Sick Beard. # # Sick Beard is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the Lice...
"""Initiate pygame, logging and other things""" import pygame import os import logging import sys sys.path.append("/src/") from options import Options pygame.mixer.pre_init(44100, -16, 1, 512) # Makes all gun sounds play # Without this, only some play because they are so close together pygame.init...
import json from dateutil.parser import parse as ts_parse from covid_scheduling import (validate_people, validate_config, assign_schedules) if __name__ == '__main__': with open('data/tufts.json') as f: config = validate_config(json.load(f)) with open('data/tufts_sample_500...
from manimlib.imports import * class Table(Scene): def construct(self): h_size = .75 nr_size = .7 t_size = .5 title = TexMobject("\\text{Planned Formation Scenarios}").shift((0, 3.5, 0)).scale(.75) header = TexMobject("\\text{Nr. }", "\\text{Dim. }", "\\text{Formation Scen...
import subprocess from pathlib import Path import typer from onlinejudge import utils from pydantic.types import DirectoryPath from judge.schema import JudgeConfig MAX_SAMPLE_NUM = 100 class AddJudgeConfig(JudgeConfig): testdir: DirectoryPath def main( workdir: Path = typer.Argument(".", help="a director...
import heapq import os from math import sqrt from model import MovieLens as ModelBase from model import relative_path from operator import itemgetter def relative_path(path): """ Returns a path relative from this file """ #dirname = os.path.dirname(__file__) dirname = os.path.dirname(os.path.rea...
# ---------------------------------------------------------------------- # Action # ---------------------------------------------------------------------- # Copyright (C) 2007-2020 The NOC Project # See LICENSE for details # ---------------------------------------------------------------------- # Python modules from t...
''' Blog fetch ''' import concurrent.futures as futures import logging import time from datetime import timedelta import opml from util.feed_utils import transform_feed from util.requests import fetch_from_server logging.basicConfig(level=logging.INFO) def _process_feed(details, limit, frequency): _, __, fee...
from ariadne import ObjectType post = ObjectType("Post")
import random sayi = random.randint(1,100) print ("Tahmin Oyununa Hos Geldiniz") sayac=0 while True: tahmin = int(input("Sayi Girin:")) sayac += 1 if tahmin == sayi: print ("\nTebrikler {} denemede bildiniz!" .format(sayac)) break elif tahmin < sayi: print ("Daha Buyuk Bir...
from pathlib import Path """absolute path used as default for the json file database""" default_path: Path = Path.home() / ".isensus"
cadastro1 = {} cadastro2 = {} def e_cad(): for i in range(0, 2): nome = input('Nome: ').strip() idade = int(input('Idade: ')) cpf = input('CPF: ').strip() if idade >= 18: dados = nome, idade, cpf cadastro1[cpf] = dados if idade < 18: dados2...
# palindrome # Returns True if the given string is a palindrome, False otherwise. # # Convert string str.lower() and use re.sub to remove non-alphanumeric characters from it. Then compare the new # string to the reversed. def palindrome(string): """ :type string: str """ from re import sub s = su...
import typing T = typing.TypeVar("T") class TrieNode(typing.Generic[T]): def __init__(self): self.values: typing.List[T] = [] self.children: typing.Dict[str, TrieNode] = {} class Trie(typing.Generic[T]): """A simple in-memory trie""" def __init__(self): self._root: TrieNode[T]...
from .config import ( SMTP_HOST, SMTP_PORT, SMTP_USER, SMTP_PASSWORD, SMTP_MAIL_FROM, SMTP_STARTTLS, SMTP_SSL, ) from .logging import logger from pathlib import Path from email import encoders from email.mime.base import MIMEBase from email.mime.multipart import MIMEMultipart from email.mime...
import glob import os import sys import unittest import shutil import subprocess import logging as logger import argparse class test_requirements(unittest.TestCase): """ Ensuring the correct tools are present """ def test_check_requirements(self): if not shutil.which("art_illumina"): lo...
"""Tests for the parsers-package Tests for individual parsers are in their own files """ # Standard library imports from datetime import datetime import pathlib # Third party imports import numpy as np import pytest # Midgard imports from midgard import parsers def get_parser(parser_name): """Get a parser tha...
from flask import Blueprint, render_template,url_for, redirect,request import xls,app,json ENTRY_LIMIT = 5 entryCount = 0 is_log = 1 # 0:Null 1:student 2:manager def loginAct(sheetName,id,password): global is_log accountInfo = xls.read(id, password) #list of accountInfo is_log = xls.sheetName(sh...
import requests from bs4 import BeautifulSoup import pandas as pd import json import math import json import numpy as np class NpEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, np.integer): return int(obj) if isinstance(obj, np.floating): return float(o...
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import ungettext_lazy from horizon import tables from openstack_dashboard import api import logging from vmexpires.expires.api.expires import delete as api_delete LOG = logging.getLogger(__name__) class MyFilterAction(tables.Fil...
from django.apps import AppConfig class DashboardConfig(AppConfig): name = "codershq.dashboard" def ready(self): pass
import subprocess import os import time class App: def __init__(self): self.dev_local_user_var = 'DEV_LOCAL_USER' def assignPermissions(self, physical_vhost_path) -> bool: if os.name == 'nt': return False current_user = self.__get_dev_user__() if current_user ==...
# ET.indent() will be available from Python 3.9; until then, I use # the implementation from http://effbot.org/zone/element-lib.htm#prettyprint # below. # (see https://bugs.python.org/issue14465) def ET_indent(elem, level=0): i = "\n" + level * " " if len(elem): if not elem.text or not elem.text.strip(...
''' Created on 04-May-2020 @author: srinivasan ''' import gin from pyspark import StorageLevel from pyspark.ml import Pipeline from pyspark.ml.clustering import LDA, LocalLDAModel from pyspark.ml.feature import CountVectorizer from pyspark.sql.dataframe import DataFrame from pyspark.sql.functions import monotonically_...
#Class to represent a graph class Graph: def __init__(self,vertices): self.V= vertices # No. of vertices self.graph = [] # default dictionary def addEdge(self,u,v,w): self.graph.append([u,v,w]) # A utility function to find set of an element i (uses path compression techni...
# -*- encoding: utf-8 -*- """ License: MIT Copyright (c) 2019 - present AppSeed.us """ from flask_wtf import FlaskForm from flask_wtf.file import FileField, FileRequired from wtforms import StringField, TextAreaField, SubmitField, PasswordField from wtforms.validators import InputRequired, Email, DataRequired class ...
import math from PyQt5.QtCore import QAbstractTableModel, QByteArray, QDir, QStorageInfo, Qt from PyQt5.QtWidgets import QAbstractItemView, QApplication, QTreeView def sizeToString(size): if size <= 0: return "0 b" decimals = 2 units = ["b", "kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB...
def getMinMax(arr): min = arr[0] max = arr[0] for i in range(1, len(arr)): if arr[i] < min: min = arr[i] elif arr[i] > max: max = arr[i] print("min: {} and max: {}".format(min, max)) getMinMax([2,4,2,99,8,77,3,1,77])
# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: contract_call_local.proto """Generated protocol buffer code.""" from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection from go...
from hypothesis import strategies from tests.strategies import (iterables, non_negative_indices, positive_indices) iterables = iterables non_negative_slices_fields = strategies.none() | non_negative_indices non_negative_slices = strategies.builds(slice, ...
#!/usr/bin/python import getopt import os import sys from cryptography.fernet import Fernet from dotenv import load_dotenv def main(argv): mode = "" key_env = "" key_gen = False input_file = "" output_file = "" try: opts, args = getopt.getopt(argv, "hm:i:o:k:", ["mode=", "input=", "output=", "key=", "keyge...
from PyQt5 import QtCore import os, tempfile from scipy.misc import toimage import brukerWriter as bw import utils from FilesTreeWidget import * __all__ = ["FilesTreeThread", "SaveThread"] class FilesTreeThread(QtCore.QThread): def __init__(self, parent = None, mode = "create", dirnames = ""): super()...
#encoding=utf-8 # classfinder.py # This file is part of PSR Registration Shuffler # # Copyright (C) 2008 - Dennis Schulmeister <dennis -at- ncc-1701a.homelinux.net> # # This is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Softwa...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Jun 15 00:32:48 2020 @author: lutra """ import glob import os from rotate_genbank_PLPs import blast_db, run from datetime import datetime def mkdir(fold): if fold[-1:] == '/': fold = fold[:-1] loc = '/'.join(fold.split('/')[:-1]) +'/' ...
""" Unittests for asa plugin Uses the mock_device.py script to test the plugin. """ __author__ = "Dave Wapstra <dwapstra@cisco.com>" import os import re import yaml import unittest import unicon from unicon import Connection from unicon.core.errors import SubCommandFailure from unicon.mock.mock_device import moc...
import salabim as sim env = sim.Environment() names = sorted(sim.colornames().keys()) env.animation_parameters(modelname='show colornames', background_color='20%gray') x = 10 y = env.height() - 110 sx = 165 sy = 21 for name in names: sim.Animate(rectangle0=(x, y, x + sx, y + sy), fillcolor0=name) sim.Animate(...
import tensorflow as tf #conda create -n tf_gpu python==3.8 #conda activate tf_gpu print("Num GPUs Available: ", len(tf.config.list_physical_devices('GPU')))
from django.http import Http404, HttpResponseRedirect from django.shortcuts import render_to_response from django.template import RequestContext from django.views.generic.list_detail import object_list, object_detail from codereviewr.code.models import Code from pygments import highlight from pygments.formatters import...
from typing import Union from datetime import datetime import rdflib OG_NAMESPACES = ( rdflib.Namespace("http://opengraphprotocol.org/schema/"), rdflib.Namespace("http://ogp.me/ns#"), ) REQUIRED_ATTRIBUTES = ["title", "type", "image", "url", "description"] OG_TYPES = Union[str, int, float, bool, datetime, ...
""" N queens puzzle. """ class NQueens: def __init__(self, size=8): self._size = size self._solotions = 0 self._result = [-1] * self._size self.calculate(0) def calculate(self, row: int): if row == self._size: self._solotions += 1 print('No....
"""Tests dict input objects for `tackle.providers.system.hooks.command` module.""" import os import pytest from tackle.exceptions import HookCallException from tackle.main import tackle if os.name == 'nt': pytest.skip("Skipping when run from windows.", allow_module_level=True) def test_provider_system_hook_comm...
# Find usernames/ids for people in free chat and not in paid chat # TODO: Compare paid chat to google sheets signup form and send messages for renewal import pandas as pd df_free = pd.read_csv('../data/users/ATTA_FREE.csv') df_paid = pd.read_csv('../data/users/ATTA_PAID.csv') username_free = set(df_free['username'...
import regionmask import numpy as np import dask def create_windmax_dict(u, v, names, borders, longitude, latitude): """Produce a dictionary of masked maximum wind speeds in units of mph.""" if u.units != "m s**-1": raise ValueError("U field does not have units m/s") if v.units != "m s**-1": ...
from pathlib import Path from urllib.request import urlopen from .element import Element import json import shutil import logging logger = logging.getLogger(__name__) def read_gltf(fin): with open(fin, encoding='utf-8') as f: gltf = json.load(f, object_hook=lambda d: Element(**d)) # ...
""" This file shows how to use Python TCP API to do a simple pick and place with the Niryo One """ # Imports from niryo_one_tcp_client import * # -- MUST Change these variables robot_ip_address = "192.168.1.202" # IP address of the Niryo One gripper_used = RobotTool.GRIPPER_2 # Tool used for picking # -- Should Ch...
# # @lc app=leetcode id=1010 lang=python3 # # [1010] Pairs of Songs With Total Durations Divisible by 60 # from typing import List class Solution: # def numPairsDivisibleBy60(self, time: List[int]) -> int: # length = len(time) # # res = 0 # for i in range(length): # for j i...
""" Implements a controller for MATLAB Statistics Toolbox """ import matlab.engine import numpy as np from fitbenchmarking.controllers.base_controller import Controller from fitbenchmarking.controllers.matlab_mixin import MatlabMixin eng = matlab.engine.start_matlab() class MatlabStatsController(MatlabMixin, Contr...
import shlex import subprocess # import sklearn.preprocessing as prep # def standard_scale(X_train, X_test): # preprocessor = prep.StandardScaler().fit(X_train) # X_train = preprocessor.transform(X_train) # X_test = preprocessor.transform(X_test) # return X_train, X_test def run_system_command(comma...
## Neural Network class.
N = int(input()) min = N % 60 hour = N // 60 % 24 print(hour, min)
def test_get_named_cookie(session, url): session.url = url("/common/blank.html") session.execute_script("document.cookie = 'foo=bar'") result = session.transport.send("GET", "session/%s/cookie/foo" % session.session_id) assert result.status == 200 assert isinstance(result.body["value"], dict) ...
import abc import typing from abc import ABC import colorama from fiepipelib.components.data.components import AbstractComponent, AbstractNamedItemListComponent from fiepipelib.components.routines.bound_component import AbstractBoundComponentRoutines from fiepipelib.components.routines.component import AbstractCompone...
import unittest from brownies.BNL.utilities.bins import * class Test_Utilities(unittest.TestCase): def test_equal_lethargy_bins(self): self.maxDiff = None answer = [1.0e-05, 0.00037606030930863936, 0.014142135623730951, 0.53182958969449889, 20.0] calc = equal_lethargy_bins(5, domainMax=20...
import numpy as np import load_test_data import pre_process X_train, Y_train, X_dev, Y_dev = pre_process.preprocessData('train.csv') X_test, Y_test = load_test_data.loadTestData('test.csv') def updateWeights(gradient, learningRate, W): W = W - (learningRate * gradient) return W def logisticRegression(X, Y...
from intersection import * def test_intersection(): test1 = Binary_Tree() test1.root = Node(90) test1.root.right = Node(80) test1.root.left = Node(100) test2 = Binary_Tree() test2.root = Node(20) test2.root.right = Node(10) test2.root.left = Node(100) assert tree_intersection(test...
''' This code is part of QuTIpy. (c) Copyright Sumeet Khatri, 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 wor...
import asyncio import json import logging from datetime import date, datetime, timedelta from redbot.core import Config, checks, commands from redbot.core.bot import Red from redbot.core.i18n import Translator, cog_i18n from redbot.core.utils.chat_formatting import humanize_list, pagify from .constants import TEAMS f...
__version__ = '0.2.1' __copyright__ = 'Copyright (c) 2018, skioo SA' __license__ = 'MIT' __URL__ = 'https://github.com/skioo/django-netaxept-gateway'
import numpy as np from igl import comb_line_field from directional_clustering.fields import VectorField __all__ = ["comb_vector_field"] def comb_vector_field(vector_field, mesh): """ Combs a vector field defined on a reference triangular mesh. Parameters ---------- vector_field : `directiona...
import tensorflow as tf import modules as m import embed as e class MatchLSTM(object): """https://arxiv.org/abs/1608.07905""" def __init__(self, config, batch, word_mat=None, char_mat=None, is_train=True): self.is_train = tf.get_variable( "is_train", shape=[], dtype=tf.bool, trainable=Fa...
from flask_restful import Api from app.apis.client.user import UsersResource from app.apis import api_blueprint client_api = Api(api_blueprint) client_api.add_resource(UsersResource,'/user/')
#!/usr/bin/env pytest # # Reimplements cmd_drain_policies.run. # import sys import time import textwrap from pathlib import Path import logging logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) import htcondor from ornithology import ( config, standup, Condor, action, Cluster...
import shutil from function import * if __name__ == "__main__": shutil.rmtree(PROCESS_FOLDER) os.mkdir(PROCESS_FOLDER) shutil.rmtree(DIGITS_STR_FOLDER) os.mkdir(DIGITS_STR_FOLDER) shutil.rmtree(WRITE_FOLDER) os.mkdir(WRITE_FOLDER) for filename in os.listdir(READ_FOLDER): find_digits...
# -*-coding: utf-8-*- import cv2 import os # import tensorflow as tf import numpy as np import copy import random file_path = r'/YeDisk/home/tyding/Fruit/fruit/Test/' def file_name(file_dir): list0 = [] list_label = [] dict0 = {} i = -1 for files in os.listdir(file_dir): ...
import argparse import logging import os import pathlib from typing import Any, List from monaistream.util.convert import to_onnx, to_trt CMD_ACTIONS = ["convert"] class Entry: def __init__( self, loglevel: Any = logging.ERROR, actions: List[str] = CMD_ACTIONS, logformat: str = (...
# Generated by Django 3.2.11 on 2022-04-21 21:54 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("corpus", "0028_translate_documenttype"), ] operations = [ migrations.AddField( model_name="document", name="shelfma...
# Copyright (c) 2010-2014 openpyxl from zipfile import ZipFile from openpyxl.workbook import Workbook from openpyxl.worksheet import Worksheet from openpyxl.reader import comments from openpyxl.reader.excel import load_workbook from openpyxl.xml.functions import fromstring import pytest def test_get_author_list()...
# # OtterTune - set_default_knobs.py # # Copyright (c) 2017-18, Carnegie Mellon University Database Group # import logging from .models import KnobCatalog, SessionKnob from .types import DBMSType, KnobResourceType, VarType LOG = logging.getLogger(__name__) # Default tunable knobs by DBMS. If a DBMS is not listed her...
# coding: utf-8 # Copyright (C) 2021, [Breezedeus](https://github.com/breezedeus). # 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 f...
import random import urllib.request import urllib.parse import request as request class HtmlDownloader(object): def download(self, new_url): print("准备下载页面 "+new_url) headers = {'User-Agent': "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110...
def build_rainbow(): RAINBOW_COLORS = ( (255, 0, 0), (255, 127, 0), (255, 255, 0), (0, 255, 0), (0, 0, 255), (111, 0, 255), (143, 0, 255), (255, 0, 0) ) def rainbow_color(t, r): "Returns a rainbow color, 0 <= t <= r" if t == r:...
# coding: utf-8 import pprint import re import six class RestScheduleConfDTO: """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the valu...
from threading import * import time '''def job1(): print('Executed by t1') t2=Thread(target=job2) print('t2 is Daemon:',t2.isDaemon()) t2.start() def job2(): print('Executed by t2') t1=Thread(target=job1) t1.setDaemon(True) print('t1 is daemon:',t1.isDaemon())#False t1.start() time.sleep(10)''' def job(): fo...
#!/usr/bin/env python2 # -*- coding: utf-8 -*- # ---------------------------------------------------------------- # tests/test_load_save.py # # Test loading images and saving thumbnails. # ---------------------------------------------------------------- # copyright (c) 2015 - Domen Ipavec # Distributed under The MIT L...
import sys sys.path.insert(1,"../../../") import h2o from tests import pyunit_utils import numpy as np from h2o.estimators.glm import H2OGeneralizedLinearEstimator def wide_dataset_large(): print("Reading in Arcene training data for binomial modeling.") trainDataResponse = np.genfromtxt(pyunit_utils.locate("small...
# -encoding:utf8- import sys import depio import re import operator from itertools import chain from pprint import pprint morph_funcs = [ ['seg', [2,-1]], ['pos-seg', [2, 5, -1]], ['pos-seg-feats', [2, 5, 6, -1]] ] def get_morph_func(name): m = dict(morph_funcs)[name] return operator.itemgetter(*m) de...
# -*- coding: utf-8 -*- # 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...
#!/usr/bin/env python # Licensed to Cloudera, Inc. under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. Cloudera, Inc. licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you ma...
heroes = {hero: [] for hero in input().split(", ")} command = input() while command != "End": hero, item, price = command.split("-") if item not in heroes[hero]: heroes[hero] += [item, price] command = input() for hero, items in heroes.items(): price = [int(item) for item in items if item.isde...
from websocket import create_connection import time import re ws = create_connection("ws://127.0.0.1/websocketclient") print("Sending 'Hello, World'...") ws.send("Hello, World") print("Sent") print("Receiving...") ######################################################## #i) two words 'move e2e4' -> extract only the se...
from flask import Blueprint, current_app, jsonify, request from app import document_store, antivirus_client from app.utils import get_mime_type from app.utils.antivirus import AntivirusError from app.utils.authentication import check_auth from app.utils.urls import get_direct_file_url, get_frontend_download_url uploa...
#!/usr/bin/python3 import time import numpy as np from picamera2.encoders import H264Encoder from picamera2.outputs import CircularOutput from picamera2 import Picamera2 lsize = (320, 240) picam2 = Picamera2() video_config = picam2.video_configuration(main={"size": (1280, 720), "format": "RGB888"}, ...
from HighActivityState import HighActivityState from MediumActivityState import MediumActivityState from LowActivityState import LowActivityState
from distutils.core import setup CLASSIFIER = [ "Development Status :: 4 - Beta", "Intended Audience :: Science/Research", "License :: OSI Approved :: MIT License", "Natural Language :: English", "Programming Language :: Python", "Programming Language :: Python :: 3", "Operating System :: P...
import logging from typing import Iterable from . import Model log = logging.getLogger(__name__) # pylint: disable=C0103 class Index: def __init__(self, keys: Iterable[str]): log.debug('Index.__index__ %s', keys) self.keys = keys def __call__(self, model: Model) -> tuple: log.debug...
import torch def artanh(x): return 0.5*torch.log((1+x)/(1-x)) def p_exp_map(v): normv = torch.clamp(torch.norm(v, 2, dim=-1, keepdim=True), min=1e-10) return torch.tanh(normv)*v/normv def p_log_map(v): normv = torch.clamp(torch.norm(v, 2, dim=-1, keepdim=True), 1e-10, 1-1e-5) return artanh(normv)...
from django.apps import AppConfig class ApiCustConfig(AppConfig): name = 'api_cust'