content
stringlengths
5
1.05M
from datetime import datetime from app import db from app.models.base.base import BaseModel class WithdrawOauthAccountModel(db.Model, BaseModel): __bind_key__ = "a_coffer" __tablename__ = "withdraw_oauth_account" id = db.Column(db.Integer, primary_key=True) user_id = db.Column(db.Integer, default=0)...
# SPDX-License-Identifier: MIT # Copyright (c) 2020 The Pybricks Authors """ Hardware Module: 1 Description: Verifies the distance values of the Ultrasonic Sensor. It rotates the motor to place an obstacle in front of the sensor to test distance values. Then it rotates quickly to verify faster readings. """ from pyb...
#!/usr/bin/env python # -*- coding: utf-8 -*- # setup_teardown_test.py # Note! run: pytest -v -s # Class Example # # Note: The setup class and teardown class methods # have the @classmethod decorator applied, as they # are passed in the uninstantiated class object # rather than a unique instance of the class. impo...
# --coding--:utf-8 -- import cv2 import mediapipe as mp import time class PoseDetector: def __init__(self, mode = False, upBody = False, smooth=True, detectionCon = 0.5, trackCon = 0.5): self.mode = mode self.upBody = upBody self.smooth = smooth self.detectionCon = detectionCon...
#coding=utf-8 import random import jieba import nltk def run(): pass def gender_features(weibo): a = jieba.cut(weibo[1:]) fl = (" ".join(a)).split() fd = {} count = 1 for i in fl: fd[str(count)] = i count += 1 # print fd return fd def readin(path): ...
# Copyright 2021 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, ...
from django.forms import ModelForm from .models import Order, Profile class OrderForm(ModelForm): class Meta: model = Order fields = ['user','service','payment_method'] class ProfileForm(ModelForm): class Meta: model = Profile fields = ['name', 'photo', 'age', 'email']
"""generate_user_tables Revision ID: 47e4599484a1 Revises: 89edb69f4be3 Create Date: 2018-05-10 21:33:01.943092 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '47e4599484a1' down_revision = '89edb69f4be3' branch_labels = None depends_on = None def upgrade():...
import pandas as pd import numpy as np import numpy.linalg as LA from numpy import sin,cos from tqdm import tqdm from functools import partial from multiprocessing import Pool, cpu_count from cvxopt import matrix, solvers, sparse,spdiag,spmatrix import time # TODO # 1. get rid of uniform timestamps assumption -> resam...
"""Tests for the logging transactions module focusing on threads""" from threading import Thread from ska.log_transactions import transaction from tests.conftest import get_all_record_logs, clear_logger_logs class ThreadingLogsGenerator: """Generate logs by spawning a number of threads and logging in them So...
from secml.ml.features.tests import CPreProcessTestCases from collections import OrderedDict try: import torch import torchvision except ImportError: CPreProcessTestCases.importskip("torch") CPreProcessTestCases.importskip("torchvision") else: import torch from torch import nn, optim from ...
######################################################################################################################## __doc__ = \ """ Transpiler module for Michelanglo --- IO parts plus basic cleaning of PDB block """ __author__ = "Matteo Ferla. [Github](https://github.com/matteoferla)" __email__ = "ma...
import numpy as np from core.transform import Transform class Mesh: def __init__(self, name, vertices, vertex_indices, normals, normal_indices, transform=None): self.name = name # we have triangle mesh assert len(vertex_indices) % 3 == 0 assert len(normal_indices) == len(vertex_in...
import tensorflow as tf import numpy as np import cv2 def extract_person(image, bbox, person_image_shape): bbox = np.array(bbox) new_width = float(person_image_shape[1]) / person_image_shape[0] * bbox[3] bbox[0] -= (new_width - bbox[2]) / 2 bbox[2] = new_width bbox[2:] += bbox[:2] bbox = bbox....
##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ ## Created by: Yaoyao Liu ## NUS School of Computing ## Email: yaoyao.liu@u.nus.edu ## Copyright (c) 2019 ## ## This source code is licensed under the MIT-style license found in the ## LICENSE file in the root directory of this source tree ##++...
import copy import torch import torch.nn as nn class Transformer(nn.Module): def __init__(self, d_model=512, nhead=8, num_encoders=6, num_decoders=6, dim_feedforward=2048, dropout=0.1): super(Transformer, self).__init__() encoder_layer = TransformerEncoderLayer(d_model, nhead, dim_feedforward, d...
from flask import Flask, request, jsonify from io import BytesIO import os from processor import processImage app = Flask(__name__) CORS_ORIGIN = 'http://localhost:8080' OUTPUT_PATH = 'assets' class InvalidFiletype(Exception): status_code = 400 def __init__(self, message, status_code=None, payload=None): Ex...
from gcloud import storage from gcloud.storage.blob import Blob class xamoom_acl(object): #actors ALL = 0 ALL_AUTH = 1 DOMAIN = 2 GROUP = 3 USER = 4 #rights GRANT_READ = 0 GRANT_WRITE = 1 GRANT_OWNER = 2 REVOKE_READ = 3 REVOKE_WRITE = 4 REVOKE_OWNER = 5 #membe...
import os, logging from flask import Flask from flask.ext.basicauth import BasicAuth app = Flask(__name__) app.config.from_object(os.environ.get('SETTINGS')) if app.config.get('BASIC_AUTH_USERNAME'): app.config['BASIC_AUTH_FORCE'] = True basic_auth = BasicAuth(app) print "============" print app.config prin...
import bluetooth import lightblue # we should know target_name = "Galaxy S8" # we don't know yet obex_port = None target_address = None print("searching for nearby devices...") nearby_devices = bluetooth.discover_devices() for bdaddr in nearby_devices: print(bluetooth.looku...
import matplotlib.pyplot as plt import pandas as pd import seaborn as sns import shapefile as shp from structlog import get_logger from collections import namedtuple from mappa import config logger = get_logger() NomConfig = namedtuple("NomConfig", ["intensity", "palette"]) NOMENCLATURE = [ ("Sin poblacion hab...
from django.db import models class EFilingSubmission(models.Model): id = models.AutoField( auto_created=True, primary_key=True, serialize=False, verbose_name="ID" ) created_date = models.DateTimeField(auto_now_add=True) last_updated = models.DateTimeField(blank=True, null=True) submission_...
import sys sys.path.insert(0, '..') import numpy as np import torch import os import psutil import random import pickle from tqdm import tqdm from collections import OrderedDict from deepctr_torch.inputs import (DenseFeat, SparseFeat, VarLenSparseFeat, get_feature_names) from deepctr...
""" Created on Wed Feb 8 19:42:38 2017 @author: Gautham """ import matplotlib.pyplot as plt import matplotlib.animation as animation from matplotlib import style style.use("ggplot") out = "twitter-feed-textblob.txt" data = open(out, "r").read() lines = data.split('\n') query = lines[0] fig = plt.figure() fig.can...
# Generated by Django 2.1.4 on 2019-01-12 13:51 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('home', '0013_auto_20190112_1153'), ] operations = [ migrations.AddField( model_name='blogpage', name='cover_invert_t...
from ..validators import must_not_be_none from marshmallow import ValidationError from unittest import mock, TestCase class TestAgentMessage(TestCase): def test_data_is_blank(self): try: must_not_be_none({}) except: self.fail("must_not_be_none() raised Exception unexpecte...
import os import requests import shutil import gzip import pprint import json pp = pprint.PrettyPrinter(indent=4) __base_url__ = 'https://www.encodeproject.org/' __root_dir__ = '/media/dna/ENCODE_idr_20Jan_2017/' ALLOWED_FILETYPES = ['bed narrowPeak', 'bed broadPeak'] def safe_makedir(dname): """Make a directory ...
# -*- coding: utf-8 -*- """ Created on Fri Jul 9 14:29:16 2021 @author: Giray Balcı """ # %% # from fpdf import FPDF import subprocess import time import os # from datetime import datetime #for pdf autotime stamp fileName = "exampleCircuit.asc" dir_XVIIx64 = "C:\Program Files\LTC\LTspiceXVII\\" exeName = "XVIIx64...
import setuptools # Supports editable installs. setuptools.setup()
from isbnlib import * import easygui as eg import sys import csv import os # clean-up old files os.remove("YBP_HOLDINGS.txt") # select file csv_file_path = eg.fileopenbox(msg='Select .CSV file', title='Select File', filetypes='*.csv') ...
# ******************************************************************************* # Copyright 2017 Dell 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/L...
import time import traceback import numpy as np from math import log, ceil from mfeshb.optimizer.base.mq_base_facade import mqBaseFacade from mfeshb.optimizer.base.utils import sample_configurations from openbox.utils.config_space import ConfigurationSpace class Hyperband(mqBaseFacade): """ The implementation of...
from django.http import HttpResponse, Http404 from django.shortcuts import render_to_response, render, get_object_or_404 from models import ContentModel, ModelVersion from datetime import datetime, date import json #-------------------------------------------------------------------------------------- # Query by label...
import os, sys, qtmodern.styles, qtmodern.windows, warnings, logging from PyQt5.QtWidgets import QApplication from PyQt5.QtGui import QIcon from PyQt5.QtCore import Qt from argparse import ArgumentParser # from howdy import resourceDir from howdy.core import returnQAppWithFonts from howdy.email import email_demo_gui # ...
"""Test the UniFi Protect lock platform.""" # pylint: disable=protected-access from __future__ import annotations from unittest.mock import AsyncMock, Mock from pyunifiprotect.data import Doorlock, LockStatusType from homeassistant.components.unifiprotect.const import DEFAULT_ATTRIBUTION from homeassistant.const imp...
from typing import Callable from fastapi import FastAPI from motor.motor_asyncio import AsyncIOMotorClient from vacations.config import ( MONGODB_URI, HISTORY_COLLECTION, USERS_COLLECTION, ) def start_app_handler(app: FastAPI) -> Callable: async def startup() -> None: app.state.motor = Async...
from paropt_sdk.utils.auth import do_login_flow, make_authorizer, logout from paropt_sdk.config import (check_logged_in, PAROPT_SERVICE_ADDRESS, CLIENT_ID) from globus_sdk.base import BaseClient, slash_join from mdf_toolbox import login, logout from tempfile import mkstemp import pickle as pkl import pandas as pd imp...
import frappe from frappe import _ def execute(): frappe.reload_doctype("System Settings") settings = frappe.get_doc("System Settings") settings.db_set("app_name", "OryxERP", commit=True)
# ReadRecord.py # -------------------------------------------------------------------------- # # Written: minjie # Date: May 2016 # A procedure which parses a ground motion record from the PEER # strong motion database by finding dt in the record header, then # echoing data values to the output file. # # For...
import bs4 import os import argparse script = """ (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,documen...
# # ovirt-engine-setup -- ovirt engine setup # # Copyright oVirt Authors # SPDX-License-Identifier: Apache-2.0 # # import atexit import gettext import os import random import string import tempfile from otopi import constants as otopicons from otopi import filetransaction from otopi import util from otopi import pl...
"""Create your test for the user views here.""" import pytest from django.conf import settings from django.contrib import messages from django.contrib.auth.models import AnonymousUser from django.contrib.messages.middleware import MessageMiddleware from django.contrib.sessions.middleware import SessionMiddleware from d...
# Copyright (C) 2020 NumS Development Team. # # 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 ...
#! /usr/bin/env python # -*- coding: utf-8 -*- """Train the student model with multiple GPUs (Librispeech corpus).""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from os.path import join, isfile, abspath import sys import time import tensorflow as tf f...
import os from typing import List from ds_simple_db.core.entry import Entry from ds_simple_db.core.filter import Filter from ds_simple_db.serializers import SerializerFactory class Storage: """ A base class for all storage types that provide underlying structures to store data. Storage can be persistent ...
from unittest.mock import patch from unittest import mock, TestCase from requests import Session from dhf_wrapper.client import PaymentClient from dhf_wrapper.entities.payment import PaymentDTO class TestPaymentClient(TestCase): @patch.object(Session, 'get') def test_positive_getting_payments(self, mock_ge...
# -*- coding: utf-8 -*- """Test Workflow for playing with deployment options.""" import time from dask.distributed import Client, progress def set_value(value): """.""" return value def square(value): """Square the specified value.""" time.sleep(2.0) return value**2 def neg(value): """Ret...
############################################################################## # Copyright (c) 2017 Rajesh Kudaka <4k.rajesh@gmail.com> # Copyright (c) 2018 Intel Corporation. # # All rights reserved. This program and the accompanying materials # are made available under the terms of the Apache License, Version 2.0 # w...
from django.contrib.gis.db.models.fields import BaseSpatialField from django.contrib.gis.measure import Distance from django.db import NotSupportedError from django.db.models.expressions import Expression from django.db.models.lookups import Lookup, Transform from django.db.models.sql.query import Query from django.uti...
import pytest import capybara class TestHasAllOfSelectors: @pytest.fixture(autouse=True) def setup_session(self, session): session.visit("/with_html") def test_is_true_if_the_given_selectors_are_on_the_page(self, session): assert session.has_all_of_selectors("css", "p a#foo", "h2#h2one",...
class Reference: def __init__(self, data, last_ref, next_ref): self.data, last_ref, next_ref = data, last_ref, next_ref def __str__(self): retstr = str([self.last_ref.data if self.last_ref else None, self.data, self.next_ref.data if self.next_ref else None]) return retstr[1:-1] class ...
# Generated by Django 3.2.2 on 2021-05-31 16:49 import django.db.models.deletion from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("zerver", "0331_scheduledmessagenotificationemail"), ] operations = [ migrations.CreateModel( na...
from django.core.exceptions import ImproperlyConfigured from mock import patch from pytest import raises from task_api.utils import resolve_class, get_backend_cls class Test(object): pass def test_resolve_class(): assert resolve_class('tests.test_utils.Test') == Test def test_resolve_invalid_class(): ...
# Standard Library import datetime import os # Third Party Code from dateutil.tz import tzutc import responses # Supercell Code from supercell.breezometer.air_quality import ( air_quality_forecast_hourly, current_air_quality, historical_air_quality_hourly, ) from supercell.breezometer.air_quality.models.a...
import datetime from typing import List, Optional, Set import sqlalchemy from telegram_logger.chat_log import ChatLog from telegram_logger.log_entry import LogEntry class Database: def __init__(self, db_str: str) -> None: self.engine = sqlalchemy.create_engine(db_str) self.conn = self.engine.con...
__version__ = '0.24.dev0'
""" Created by @Jisan7509 plugin for Cat_Userbot ☝☝☝ You remove this, you gay. """ import os from telethon.errors.rpcerrorlist import YouBlockedUserError from ..core.managers import edit_delete, edit_or_reply from ..helpers.functions import clippy from . import _codtools, codex, convert_toimage, mention, reply_id pl...
import os import random import cv2 COLORS = [[random.randint(0, 255) for _ in range(3)] for _ in range(10)] def draw_gt(): imgs = os.listdir('../dataset/NWPU VHR-10 dataset/positive image set') for img_name in imgs: print(img_name) img = cv2.imread('../dataset/NWPU VHR-10 dataset/positive im...
# ----------------------------------------------------------------------------- # Copyright (c) 2014--, The Qiita Development Team. # # Distributed under the terms of the BSD 3-clause License. # # The full license is in the file LICENSE, distributed with this software. # ------------------------------------------------...
from re import * from ply.lex import lex ''' DSVR -> SRs SRs -> SRs SR | SR SR -> RMDEF ID SUBS '.' t[0] = f''' def {p[2]}(t): texto = "_" + texto while(True): texto,num1 = subn('_the','o_',texto) texto,num2 = subn('_cat','gato_',texto) texto,num3 = subn('_is sleeping','esta a...
#Constants position_dict = { 1 : 'Center' , 2 : 'Left Wing' , 3 : 'Right Wing' , 4 : 'Defense' , 5 : 'Goalie' } team_dict = { 1: 'Boston Bruins' , 2: 'Buffalo Sabres' , 3: 'Calgary Flames' , 4: 'Chicago Blackhawks' , 5: 'Detroit Red Wings' , 6: 'E...
# emacs: -*- mode: python; py-indent-offset: 4; tab-width: 4; indent-tabs-mode: nil -*- # ex: set sts=4 ts=4 sw=4 et: # ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ## # # See COPYING file distributed along with the datalad package for the # copyright and license terms. # # ## ### ### ...
#!/usr/bin/env python3 #-*- coding: utf-8 -*- ''' ================================== = mixingcycles_Isoclines.py ================================== Computes isoclines of the dynamics of average inoculum sizes over multiple cycles Lukas Geyrhofer, l.geyrhofer@technion.ac.il, 2018 ''' import numpy as np i...
from django.contrib import admin from .models import Paste # Register your models here. admin.site.register(Paste)
# -*- coding: utf-8 -*- """ Profile: http://hl7.org/fhir/StructureDefinition/NutritionOrder Release: STU3 Version: 3.0.2 Revision: 11917 Last updated: 2019-10-24T11:53:00+11:00 """ from typing import Any, Dict from typing import List as ListType from pydantic import Field, root_validator from . import backboneelement...
class GameError(Exception): def __init__(self, message): self.message = message def __format__(self): return self.message def __repr__(self): return f"{self.__class__.__name__}: {self.message}" class IllegalMove(GameError): pass
from D5_coffee_data import MENU, resources #python programming for implementing a simple coffee machine profit = 0 #initial value in machine set to 0 is_on = True # TODO 1: Prompt user by asking “What would you like? (espresso/latte/cappuccino): # TODO 2:Turn off the Coffee Machine by entering “off” to the promp...
from django import forms from multiselectfield import MultiSelectFormField from tfg_webapp.models import DataFile, ReportSettings class DataFileForm(forms.ModelForm): class Meta: model = DataFile fields = ('data_file',) labels = { 'data_file': '' } class ColumnsForm(...
Server_ip = "182.294.242.181" Token = '121899714:AAEXTAOSsuyFIb6Nydku3GhBM9sJtvstn8M' The_group_id_you_wanna_forward = 0 # change it if The_group_id_you_wanna_forward == 0: print(f""" You have to set the The_group_id_you_wanna_forward varable to use this program. """) exit() from king_chat import Client ...
from setuptools import setup, find_packages def load_requirements(path): with open(path) as fin: return [ line for line in map(lambda l: l.strip(), fin.readlines()) if line and not line.startswith('#') ] requirements = load_requirements('requirements.txt') se...
import cv2 as cv import numpy as np img = cv.imread("D:/Programming/Python_Projects/Computer_Vision/ROV/FishSize/Source/" + "samplefromvideo_1.png") cv.imshow('Park', img) blank = np.zeros(img.shape[:2], dtype='uint8') b,g,r = cv.split(img) blue = cv.merge([b,blank,blank]) green = cv.merge([blank,g,bla...
import torch from scipy.optimize import nnls def Fixed_Weight_Greedy_Parallel(A, b, val_set_size, nnz=None, device="cpu"): '''approximately solves min_x ||Ax - b||_2 s.t. x_i \in \{0,1\} Args: A: design matrix of size (d, n) b: measurement vector of length d nnz = maximum number of nonzero co...
""" Default settings for the Richie courses app. If you use Django Configuration for your settings, you can use our mixin to import these default settings: ``` from configurations import Configuration from richie.apps.courses.settings.mixins import RichieCoursesConfigurationMixin class MyConfiguration...
from glob import glob import os path = "/home/gongjinlan/projects/revolve/output/cpg_bo/main_1559644358-BO-gecko7/" print(path) paths = glob(path + "*/*.png") print(len(paths)) for path in paths: os.remove(path)
import tensorflow as tf from keras.models import load_model from flask import Flask, render_template, request import numpy as np import base64 import json import logging from scipy.misc import imresize import imageio import warnings tf.get_logger().setLevel(logging.ERROR) warnings.filterwarnings("ignore") app = Flas...
""" Given an unsorted array, find the maximum difference between the successive elements in its sorted form. Return 0 if the array contains less than 2 elements. Example 1: Input: [3,6,9,1] Output: 3 Explanation: The sorted form of the array is [1,3,6,9], either (3,6) or (6,9) has the maximum difference...
"""DESIGM Clustering Algorithm""" # Authors: Jeffrey Wang # License: BSD 3 clause import numpy as np from ._utils import format_array, create_random_state class DSIGM: """ A Clustering Model using the DSIGM Clustering Algorithm. DSIGM - Density-sensitive Self-stabilization of Independent Gaussian Mixtures. Fi...
""" This file is part of GSMWS. """ import gsm import collections import threading import logging import time import datetime import Queue import sqlite3 import zmq from sets import Set class MeasurementReportList(object): def __init__(self, maxlen=10000): self.lock = threading.Lock() self.maxlen ...
import struct import codecs from protogen.stalk_proto import models_pb2 as models from typing import List, Union, Optional ColorType = List[float] def color(*channels: Union[int, float], alpha: Optional[float] = None) -> ColorType: """ Convert a set 0-255 RGB int values to 0.0-1.0 floats. Alpha is expected ...
import os import numpy as np import tensorflow as tf import tensorflow.contrib.slim as slim import itertools class Model: def __init__(self, logger, optimizer, learning_rate, checkpoint_dir): self.logger = logger self.init_global_step() self.build_model() self.x = tf.placeholder(s...
# -*- coding: utf-8 -*- # Copyright (c) 2011-2020 Raphaël Barrois # This code is distributed under the two-clause BSD license. from django.conf import settings from django.db import models as django_models from django.utils.translation import gettext_lazy as _ from .. import models class TransitionLog(models.Generi...
from os import EX_CANTCREAT from glogpy.job import gaussian_job from glogpy.linkparser import linkparsers import numpy as np # Jobs of the form # 1/xxxx/1,18; # 2/xxxx/2; <- GEOM INIT # 3/xxxx/1,2,3; # 4/xxxx/1,5; # 5/xxxx/10; <- State composition # 8/xxxx/1; # 11/xxx/1; # 10/xxx/3(-3); # 6/...
# Resource object code (Python 3) # Created by: object code # Created by: The Resource Compiler for Qt version 6.0.0 # WARNING! All changes made in this file will be lost! from PySide6 import QtCore qt_resource_data = b"\ \x00\x00\x06{\ T\ EMPLATE = app\x0aLA\ NGUAGE = C++\x0aTAR\ GET = as\ sistant\x0a\x0aCON...
''' ==================================================================== Copyright (c) 2016 Barry A Scott. All rights reserved. This software is licensed as described in the file LICENSE.txt, which you should have received as part of this distribution. ===========================================================...
"""Module to create database from downloaded comments in JSON format. """ import json import sqlite3 from datetime import datetime from chatbot.config import * START_ROW = 0 CLEANUP_ROW = 1000000 PRINT_STATUS_ROW = 100000 def create_table(cursor): sql = "DROP TABLE IF EXISTS parent_reply;" cursor.execute(...
import os import glob from catsndogs.data import training_dir, is_cat, is_dog dogs = os.path.join(training_dir, "dog") cats = os.path.join(training_dir, "cat") def plot_samples(axes=None, n=4): import matplotlib.pyplot as plt import numpy as np from skimage import io m = 2 cats =...
#!/usr/bin/env python3 import argparse import os import re import sqlite3 import sys DEFAULT_DB_FILE = os.path.join(sys.path[0], 'database.db') def print_classification_count(conn): c = conn.cursor() c.execute(""" SELECT CLASSIFICATION, COUNT(*) FROM `GithubProjectUnfiltered` WHERE STAT...
from .urban3d_training import * from .urban3d_validation import * from .urban3d_training_cgan import *
from typing import List, Literal, Tuple from colorama import Fore, Style # type: ignore from .util import create_id, format_amount def format_name(acc: "Account", in_relation_to: "Account | None" = None) -> str: if in_relation_to is None: return f"{acc.name} ({acc.id})" if ( hasattr(acc, "...
""" SPDX-FileCopyrightText: © 2016 Ben Dudson, University of York. Email: benjamin.dudson@york.ac.uk SPDX-License-Identifier: MIT """ from freeqdsk import _fileutils from io import StringIO def test_f2s(): assert _fileutils.f2s(0.0) == " 0.000000000E+00" assert _fileutils.f2s(1234) == " 1.234000000E+03" ...
import re import os import csv from time import localtime,strftime FTI_FILE_HEADER= \ """;FTI Report ;Interfaces Internal/External ;Author Author ;Version Version ;Date %s \n\n""" % (strftime("%d %b %Y %H:%M:%S", localtime())) def Process(File_Name,Symbols): file = open(File_Na...
import pytest from argo.workflows.client import V1alpha1Arguments, V1alpha1Inputs, V1Toleration from pydantic import ValidationError from hera.input import InputFrom from hera.operator import Operator from hera.resources import Resources from hera.retry import Retry from hera.task import Task from hera.toleration impo...
class TessellatedShapeBuilderResult(object,IDisposable): """ Describes what TessellatedShapeBuilder has construct. """ def Dispose(self): """ Dispose(self: TessellatedShapeBuilderResult) """ pass def GetGeometricalObjects(self): """ GetGeometricalObjects(self: TessellatedShapeBuilderResult)...
from __future__ import annotations import typing import dataclasses @dataclasses.dataclass class Node(): ... @dataclasses.dataclass class Edge(): from_: int to: int weight: typing.Optional[int] = None, capacity: typing.Optional[int] = None @dataclasses.dataclass class Graph(): nodes: typing.List[No...
from time import time from datetime import datetime from random import getrandbits def xFactorOfY(x, y): return y % x == 0 def countUpperAndLower(string): return (len([char for char in string if 65 <= ord(char) <= 90]), len([char for char in string if 97 <= ord(char) <= 122])) def reverse(string): return strin...
#This code contain transformet BERT code from https://github.com/google-research/bert, please see LICENSE-BERT import tensorflow as tf import tensorflow_probability as tfp tfd = tfp.distributions import math import six import numpy as np def dropout(input_tensor, dropout_prob): """Perform dropout. Args: ...
# ----------------------------------------------------------------------------- # Copyright * 2014, United States Government, as represented by the # Administrator of the National Aeronautics and Space Administration. All # rights reserved. # # The Crisis Mapping Toolkit (CMT) v1 platform is licensed under the Apache #...
import random valid_inputs = ["rock", "paper", "scissor"] def ask_the_user(): val = input("Choose: rock, paper, scissor \n") if val in valid_inputs: return val else: print("Sorry, I can't understand") return ask_the_user() def ask_the_PC(): return random.choice(valid_inputs) ...
''' High-level editor interface that communicates with underlying editor (like Espresso, Coda, etc.) or browser. Basically, you should call set_context(obj) method to set up undelying editor context before using any other method. This interface is used by zen_actions.py for performing different actions like Expand ab...
''' Hello world from tensorflow ''' import tensorflow as tf hello_world = tf.constant('Hello World Tensorflow!') with tf.Session() as sess: print(sess.run(hello_world))