content
stringlengths
0
894k
type
stringclasses
2 values
from clases.dia_mañana import * from clases.yinyang import * from clases.alternativa import * if __name__ == "__main__": print("¿Qué ejercicio quieres ver?:", "\n","1)Dia del mañana", "\n","2)Inmortal", "\n","3)Alternativa herencia multiple") n =int(input("Número del ejercicio: ")) if n == 1: des...
python
# -*- coding: utf-8 -*- ################################################################################ ## Form generated from reading UI file 'expstatus.ui' ## ## Created by: Qt User Interface Compiler version 5.15.0 ## ## WARNING! All changes made in this file will be lost when recompiling UI file! ################...
python
first = list(input()) sec = list(input()) te = first + sec te.sort() third = list(input()) third.sort() if te==third: print("YES") else: print("NO") s,i=sorted,input;print('YNEOS'[s(i()+i())!=s(i())::2])
python
# -*- coding: utf-8 -*- from ..components import * from ..container import * from ..elements import * __all__ = ['regression_report'] def regression_report(truth, predict, label=None, per_target=True, target_names=None, title=None): """Regression report. This method will compose a sta...
python
# encoding: utf-8 # Copyright 2011 California Institute of Technology. ALL RIGHTS # RESERVED. U.S. Government Sponsorship acknowledged. def nullUpgradeStep(setupTool): '''A null step for when a profile upgrade requires no custom activity.'''
python
#range_test function definition goes here def range_test(num): if num < 1 or num > 500: return False else: return True num = int(input("Enter a number: ")) if range_test(num): print( "{:d} is in range.".format(num)) else: print("The number you entered is outside the range!")
python
# Python - 3.6.0 def is_sator_square(tablet): n = len(tablet) for r in range(n): for c in range(n): if not (tablet[r][c] == tablet[-(r + 1)][-(c + 1)] == tablet[c][r] == tablet[-(c + 1)][-(r + 1)]): return False return True
python
from platform import system, release from sys import version_info from configparser import ConfigParser from pyrfc import Connection, get_nwrfclib_version config = ConfigParser() config.read('pyrfc.cfg') params = config._sections['test'] conn = Connection(**params) print(('Platform:', system(), release())) print(('P...
python
import platform, sys if platform.system() == 'Windows': # pragma: no cover WIN = True else: WIN = False # True if we are running on Python 2. PY2 = sys.version_info[0] == 2 if not PY2: # pragma: no cover from urllib.parse import quote, unquote string_type = str unicode_text = str byte_st...
python
"""Tests for flake8.plugins.manager.PluginManager.""" import mock from flake8.plugins import manager def create_entry_point_mock(name): """Create a mocked EntryPoint.""" ep = mock.Mock(spec=['name']) ep.name = name return ep @mock.patch('entrypoints.get_group_all') def test_calls_entrypoints_on_ins...
python
PyV8 = "PyV8" Node = "Node" JavaScriptCore = "JavaScriptCore" SpiderMonkey = "SpiderMonkey" JScript = "JScript" PhantomJS = "PhantomJS" SlimerJS = "SlimerJS" Nashorn = "Nashorn" Deno = "Deno"
python
from flask.sessions import SessionInterface, SessionMixin from flask.json.tag import TaggedJSONSerializer from werkzeug.datastructures import CallbackDict from itsdangerous import BadSignature, want_bytes from CTFd.cache import cache from CTFd.utils import text_type from CTFd.utils.security.signing import sign, unsign ...
python
import math n = int(input("Enter the number till where the series ius to be printed = ")) for i in range(1,n+1): k = math.pow(i,3) j = k + 2*i print(j)
python
#Write a function that prompts user to input his/her full name. #After user enter's his/her full name, split it and store it in variables first_name and last_name. count=0 k=0 name=str(input("Enter your full name: ")) s=name.split(" ") print("The first name is:",s[0]) if len(s)==3: print("The middle name is:",s[...
python
from typing import Tuple, Optional from abc import ABC, abstractmethod from mercury.msg.smart_grid import ElectricityOffer from xdevs.models import Atomic, Port, PHASE_PASSIVE, INFINITY from mercury.utils.history_buffer import EventHistoryBuffer class EnergyProvider(Atomic, ABC): def __init__(self, **kwargs): ...
python
from abc import abstractmethod from dataclasses import dataclass from typing import List, Any, Callable, Dict, Tuple, NamedTuple, Union from data_splitting import split_splits, LearnCurveJob, EvalJob from seq_tag_util import calc_seqtag_f1_scores, Sequences from util.worker_pool import GenericTask @dataclass class ...
python
from SeeThru_Feeds.Model.Attribution import Attribution from SeeThru_Feeds.Model.Properties.Properties import * from SeeThru_Feeds.Model.Properties.PropertyManager import PropertyManager class ComponentBase(PropertyManager, Attribution): def component_execute(self): """ This function should be ove...
python
''' Copyright 2021 Kyle Kowalczyk 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 ...
python
# Copyright (c) 2019, MD2K Center of Excellence # - Nasir Ali <nasir.ali08@gmail.com> # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above cop...
python
import pytesseract import jiwer from PIL import Image from os import listdir from os.path import join, isfile TEST_PATH = '/train/tesstrain/data/storysquad-ground-truth' extractions = [] ground_truths = [] count = 0 for file_name in listdir(TEST_PATH): file_path = join(TEST_PATH, file_name) if...
python
from typing import ( IO, Any, Iterable, Sequence, Tuple, ) from eth_utils import ( ValidationError, to_tuple, ) from eth_utils.toolz import ( sliding_window, ) from ssz.exceptions import ( DeserializationError, SerializationError, ) from ssz.sedes.base import ( CompositeSed...
python
import pytest from lendingblock.const import Side, OrderType, Ccy @pytest.fixture async def wallets_org_id(lb, org_id): for ccy in Ccy.BTC.name, Ccy.ETH.name, Ccy.LND.name: await lb.execute( f'organizations/{org_id}/wallets', 'POST', json={ 'address': f...
python
# -*- coding: utf-8 -*- from __future__ import print_function from __future__ import absolute_import import numpy as np import tensorflow as tf import scipy import cPickle import os import glob import random import imageio import scipy.misc as misc log_device_placement = True allow_soft_placement = True gpu_option...
python
from flask_wtf import FlaskForm from wtforms.validators import DataRequired, Length, Email, EqualTo, ValidationError from wtforms import TextField, TextAreaField, SubmitField, validators, ValidationError,StringField, PasswordField, SubmitField, BooleanField class LoginForm(FlaskForm): email = StringField('Email', ...
python
# # Copyright (c) 2020 Carsten Igel. # # This file is part of puckdb # (see https://github.com/carstencodes/puckdb). # # License: 3-clause BSD, see https://opensource.org/licenses/BSD-3-Clause # import unittest import tempfile import os import time import puckdb class BasicTest(unittest.TestCase): def test_no_c...
python
#!/usr/bin/env python """ Inherits the stuff from tests.csvk – i.e. csvkit.tests.utils """ from tests.csvk import * from tests.csvk import CSVKitTestCase as BaseCsvkitTestCase import unittest from unittest.mock import patch from unittest import skip as skiptest from unittest import TestCase import warnings from io ...
python
from src.gui.alert import alert def show_statistics(app): """Creates an alert that displays all statistics of the user Args: app (rumps.App): The App object of the main app """ message_string = "\n".join(f"{k} {str(i)}" for k, i in app.statistics.values()) alert( title="Statistics...
python
#!/usr/bin/env ipython import numpy as np import ipdb import matplotlib.pyplot as plt import seaborn as sns import derived_results import results_utils from results_utils import ExperimentIdentifier plt.style.use('ggplot') def run_checks(cfg_name, model, diffinit, data_privacy='all', convergence_point=None): f...
python
from room import Room from player import Player from item import Item import sys import os # Declare all the rooms room = { 'outside': Room("Outside Cave Entrance", "North of you, the cave mount beckons"), 'foyer': Room("Foyer", """Dim light filters in from the south. Dusty passages run north and east."""...
python
from .employee import *
python
#!/usr/bin/python3 # -*- coding: utf-8 -*- from scipy.stats import geom import matplotlib.pyplot as plt import numpy as np def testGeom():# {{{ """ Geometric Distribution (discrete) Notes ----- 伯努利事件进行k次, 第一次成功的概率 为什么是几何分布呢, 为什么不叫几毛分布? 与几何数列有关 (乘积倍数) p: 成功的概率 q: 失败的概率(1-p) ...
python
import base64 import json import os import twitter import boto3 from time import sleep from src.sam_quest import handle_game_state # Constants AWS_REGION = 'AWS_REGION' total_processed = 0 # Environment Variables aws_region = os.environ.get(AWS_REGION, 'us-west-2') dynamodb_table_name = os.environ.get('TABLE_NAME'...
python
import math import re from termcolor import colored from sympy import Interval import locale locale.setlocale(locale.LC_ALL, '') def round_sig(number, precision=4): """ Round number with given number of significant numbers - precision Args: number (number): number to round precision (int): nu...
python
import copy import json import unittest from typing import Any, Dict import avro.schema # type: ignore from wicker import schema from wicker.core.errors import WickerSchemaException from wicker.schema import dataloading, dataparsing, serialization from wicker.schema.schema import PRIMARY_KEYS_TAG from wicker.testing...
python
from oslo_config import cfg from oslo_log import log as logging from nca47.common.i18n import _ from nca47.common.i18n import _LI from nca47.common.exception_zdns import ZdnsErrMessage from nca47.common.exception import NonExistDevices from nca47.api.controllers.v1 import tools import requests import json CONF = cfg.C...
python
from flask import Flask, render_template, make_response, abort, jsonify, request, url_for import os import matplotlib.pyplot as plt from io import BytesIO from utils import * import json app = Flask(__name__, template_folder="tp4/templates", static_folder="tp4/static") app_dir = os.getcwd() db_ensembl = "tp4/data/ens...
python
# -*- coding: utf-8 -*- # @Author: JanKinCai # @Date: 2019-12-26 23:15:03 # @Last Modified by: JanKinCai # @Last Modified time: 2019-12-28 00:02:51 from interact import interacts config = { "ipv4": { "type": "string", "regex": r"^\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}$", "default": "192.168.1...
python
# -*- coding: utf-8 -*- # Copyright (C) 2018 Intel Corporation # # SPDX-License-Identifier: Apache-2.0 """ CLI logger """ import logging import sys import os import io VERBOSE = any(arg.startswith("-v") for arg in sys.argv) XML_REPORTING = any(arg.startswith("-x") for arg in sys.argv) class StreamHandler(logging.St...
python
# # WSGI entry point for RD # from rdr_service.main import app as application if __name__ == "__main__": application.run()
python
import logging from spaceone.core.base import CoreObject from spaceone.core.transaction import Transaction _LOGGER = logging.getLogger(__name__) class BaseConnector(CoreObject): def __init__(self, transaction: Transaction = None, config: dict = None, **kwargs): super().__init__(transaction=transaction) ...
python
import string from api.create_sync_video_job import UAICensorCreateSyncVideoJobApi from api.create_async_video_job import UAICensorCreateAsyncVideoJobApi from operation.utils import parse_unrequired_args from operation.base_datastream_operation import UAICensorBaseDatastreamOperation class UAICensorCreateVideoJobOp...
python
# -*- coding: utf-8 -*- from dart_fss import api, auth, corp, errors, filings, fs, utils, xbrl from dart_fss.auth import set_api_key, get_api_key from dart_fss.corp import get_corp_list from dart_fss.filings import search from dart_fss.fs import extract from dart_fss.xbrl import get_xbrl_from_file __all__ = [ 'api...
python
from random import randint as rand Map = {0:42, 1:43, 2:45} n = rand(0, rand(0, int(input()))) with open("in", "w+") as f: f.write(chr(rand(48, 57))) i, operators = 0, 0 while i < n: if i == operators: f.write(chr(rand(48, 57))) i += 1 continue op = rand(0, 1) if op: f.write(chr(Map[rand(0, 2)])) ...
python
#!/usr/bin/env python # Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo # Copyright (C) 2008-2020 German Aerospace Center (DLR) and others. # This program and the accompanying materials are made available under the # terms of the Eclipse Public License 2.0 which is available at # https://www.ec...
python
# Imports from utils import labeled_loader, suncet_fine_tune, config import tensorflow as tf import time # Constants STEPS_PER_EPOCH = int(config.SUPPORT_SAMPLES // config.SUPPORT_BS) TOTAL_STEPS = config.FINETUNING_EPOCHS * STEPS_PER_EPOCH # Prepare Dataset object for the support samples # Note - no augmentation sup...
python
""" The MIT License (MIT) Copyright (c) 2016 Jake Lussier (Stanford University) 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...
python
''' Faça um programa que leia um número inteiro e mostre na tela o suscessor e seu antecessor. ''' print('===== Exercício 05 =====') n1 = int(input('Digite um número: ')) print(f'O antecessor de {n1} é {n1-1} e o sucessor é {n1+1}')
python
""" 1265, print immutable linked list reverse Difficulty: medium You are given an immutable linked list, print out all values of each node in reverse with the help of the following interface: ImmutableListNode: An interface of immutable linked list, you are given the head of the list. You need to use the following f...
python
""" Module providing AES256 symmetric encryption services If run as a Python command-line script, module will interactively prompt for a password, then print out the corresponding encoded db_config.ini password parameters suitable for cut/pasting into API .ini config files. Copyright (C) 2016 ERT Inc. """ import getp...
python
#!/usr/bin/env python # # Copyright 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 o...
python
import psycopg2 # printStackTrace prints as follows for postgres connection error # -------------------------------------------------------------------------------- # Error connecting postgres database: # -------------------------------------------------------------------------------- # Traceback (most recent call las...
python
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'Participant' db.create_table(u'precon_participant', ( (u'id', self.gf('django.db...
python
import pathlib from . import UMRLogging from .UMRType import ChatType, ForwardTypeEnum, DefaultForwardTypeEnum, LogLevel from pydantic import BaseModel, validator from typing import Dict, List, Union, Type, Optional, Generic, AnyStr, DefaultDict from typing_extensions import Literal import importlib import yaml import ...
python
import torch.nn as nn import torch.nn.functional as F from CGS.gnn.IGNN.IGNNLayer import ImplicitGraph from CGS.gnn.IGNN.utils import get_spectral_rad from CGS.nn.MLP import MLP from CGS.nn.MPNN import AttnMPNN class IGNN(nn.Module): def __init__(self, node_dim: int, edge_dim: ...
python
def interative_test_xdev_embed(): """ CommandLine: xdoctest -m dev/interactive_embed_tests.py interative_test_xdev_embed Example: >>> interative_test_xdev_embed() """ import xdev with xdev.embed_on_exception_context: raise Exception def interative_test_ipdb_embed(): ...
python
import unittest from maturin_sample import hello class SampleTestCase(unittest.TestCase): def test_hello(self): self.assertEqual(hello([]), 0) self.assertEqual(hello([5]), 1) self.assertEqual(hello([9, 1, 5, 2, 3]), 5) if __name__ == "__main__": unittest.main()
python
import pytest from optional import Optional from optional.something import Something class TestSomething(object): def test_can_not_instantiate_with_a_none_value(self): with pytest.raises(ValueError, match='\\AInvalid value for Something: None\\Z'): Something(value=None, optional=Optional) ...
python
from board import Board,MoveRecommendation from math import inf as infinity import random def __player_turn(board: Board): set_field = input('Enter the number of the field you want to play?[1:' + str(board.size**2) + ']') print('field id', set_field) if(set_field!=''): board.player_set(int(set_fiel...
python
#!/usr/bin/env python3 import os, re, json import sqlite3 from markov import Markov SQLITE_DATABASE = os.path.join(os.path.dirname(os.path.realpath(__file__)), "chains.db") CHAT_HISTORY_DIRECTORY = os.path.join(os.path.dirname(os.path.realpath(__file__)), "..", "..", "..", "@history") def get_metadata(): with o...
python
#!/usr/bin/python fichier = open('day6_input.txt') groupes_txt = fichier.read().split('\n\n') compteur = 0 for g in groupes_txt: reponses = set() for q in g.split('\n'): for r in q: reponses.add(r) print(reponses) compteur = compteur + len(reponses) print('fin',compteu...
python
from cereal import car from common.realtime import DT_CTRL from common.numpy_fast import interp, clip from selfdrive.config import Conversions as CV from selfdrive.car import apply_std_steer_torque_limits, create_gas_command from selfdrive.car.gm import gmcan from selfdrive.car.gm.values import DBC, CanBus, CarControll...
python
import json import pytest from common.assertions import equal_json_strings from common.methods import anonymize, anonymizers, decrypt @pytest.mark.api def test_given_anonymize_called_with_valid_request_then_expected_valid_response_returned(): request_body = """ { "text": "hello world, my name is Jan...
python
import sys import maya.OpenMaya as OpenMaya import maya.OpenMayaMPx as OpenMayaMPx import maya.cmds as cmds __author__ = 'Haarm-Pieter Duiker' __copyright__ = 'Copyright (C) 2016 - Duiker Research Corp' __license__ = '' __maintainer__ = 'Haarm-Pieter Duiker' __email__ = 'support@duikerresearch.org' __status__ = 'Produ...
python
import os import subprocess from multiprocessing import Pool, cpu_count import numpy as np from energy_demand.read_write import read_weather_data def my_function(simulation_number): print('simulation_number ' + str(simulation_number)) # Run smif run_commands = [ "smif run energy_demand_constrain...
python
'''Netconf implementation for IOSXE devices''' from ncclient import manager from ncclient.transport.errors import TransportError from ncclient.operations.rpc import RPCError import xmltodict def compare_proposed_to_running(proposed_config, running_config): '''Return diff between *proposed_config* and *running_co...
python
# AUTOGENERATED! DO NOT EDIT! File to edit: nbs/03_model_splits.ipynb (unless otherwise specified). __all__ = ['bert_SeqClassification_split', 'roberta_SeqClassification_split', 'gpt2_lmhead_split', 'distilbert_SeqClassification_split', 'albert_SeqClassification_split'] # Cell #export from fastcore.all imp...
python
from .main import Wav2Vec2STTTorch
python
import subprocess import logging from subprocess import PIPE import tempfile import json, os, re from github import Github, GithubException from datetime import datetime """ search-demo-mkdocs-material Submodule Update PR for Uncle Archie Notes: - search-demo is private-www - fake-docs is submodule - install webh...
python
# # DMG 136 # import os import csv import random import numpy as np from .dice import dice from .utils import csv2dict from .utils import filterDictList data_dir = os.path.join( os.path.dirname( os.path.realpath(__file__) ), "data" ) files = { "ART_AND_GEMSTONES": os.path.join(data_dir, 'ART...
python
# -*- cpy-indent-level: 4; indent-tabs-mode: nil -*- # ex: set expandtab softtabstop=4 shiftwidth=4: # # Copyright (C) 2019 Contributor # # 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 # # ...
python
import sys import os.path import subprocess import sublime try: from .sublime_connection import SublimeConnection from .common import msg, shared as G, utils, flooui from .common.exc_fmt import str_e assert G and G and utils and msg except ImportError: from sublime_connection import SublimeConnect...
python
# Generated by Django 3.2.9 on 2022-02-15 08:57 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('clients', '0026_servicerequest_facility'), ('common', '0015_faq'), ('staff', '0002_alter_staff_default_facility'), ] operations = [ ...
python
from airflow import DAG from airflow.operators.dummy_operator import DummyOperator from datetime import datetime with DAG('example_dag', start_date=datetime.now()) as dag: op = DummyOperator(task_id='op')
python
import os from PIL import Image, ImageQt import tkinter as tk import sys from PyQt5 import QtWidgets from PyQt5.QtWidgets import QApplication, QWidget, QMainWindow, QVBoxLayout, QLabel, QSlider, QStackedLayout, QPushButton, QFileDialog from PyQt5.QtGui import QFont, QImage, QPixmap from PyQt5.QtCore import Qt from copy...
python
from common.remote_execution.SSHConf import sshConfig import socket from Constants import * import json from dataModels.KubeCluster import KubeCluster cluster_management_objects={} def get_cluster_management_object(kube_cluster_name): if kube_cluster_name not in cluster_management_objects: return None ...
python
#!/usr/bin/env python # -*- coding: utf-8 -*- """ build dict interface """ import argparse import os from collections import defaultdict import six def build_dict(input_path, output_path, col_nums, feq_threshold=5, sep=' ', extra_words=None, ...
python
# Databricks notebook source # MAGIC %md # Python REST Client using Wrapper Module # COMMAND ---------- # MAGIC %md ####Load REST Class # COMMAND ---------- # MAGIC %run ./008-REST_API_Py_Requests_Lib # COMMAND ---------- # MAGIC %md ####Initialize REST Object # COMMAND ---------- import datetime import json #...
python
#!/usr/bin/python3 import sys import time sys.path.append("./shared") #from sbmloader import SBMObject # location of sbm file format loader from ktxloader import KTXObject # location of ktx file format loader #from sbmath import m3dDegToRad, m3dRadToDeg, m3dTranslateMatrix44, m3dRotationMatrix44, m3...
python
# -*- coding: utf-8 -*- import numpy as np import pytest from pandas import DataFrame, Index, Series, Timestamp from pandas.util.testing import assert_almost_equal def _assert_almost_equal_both(a, b, **kwargs): """ Check that two objects are approximately equal. This check is performed commutatively. ...
python
"""Register thermal expansion data.""" import pandas as pd import sqlalchemy.sql.functions as func from setting import session from create_db import * def main(): df = pd.DataFrame({"id":[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], "name":[ "ポンタ", "たぬまる", ...
python
import requests from datetime import datetime from .get_client_id import get_client_id from ._client_keys import _sign_message_as_client, _ephemeral_mode from ._kachery_cloud_api_url import _kachery_cloud_api_url def _kacherycloud_request(request_payload: dict): client_id = get_client_id() url = f'{_kachery_cl...
python
from conans import ConanFile, tools, AutoToolsBuildEnvironment, MSBuild import os class YASMConan(ConanFile): name = "yasm" url = "https://github.com/conan-io/conan-center-index" homepage = "https://github.com/yasm/yasm" description = "Yasm is a complete rewrite of the NASM assembler under the 'new' B...
python
""" Convert a PCF file into a VPR io.place file. """ from __future__ import print_function import argparse import csv import json import sys import os import vpr_io_place from lib.parse_pcf import parse_simple_pcf def main(): parser = argparse.ArgumentParser( description='Convert a PCF file into a VPR io....
python
''' SOLO TEs are these transcripts that contain intact, or semi intact unspliced transcripts. As we don't trust the short read data to assemble these, we only consider them from the pacbio data: ''' import sys from glbase3 import glload, genelist, config config.draw_mode = 'pdf' sys.path.append('../../') import s...
python
from KeyHardwareInput import * from time import * from Enderecos import * class keyController(object): def __init__(self): pass def pressionar(self,tecla,tempo): if (tecla==0): self.pressKey(S) sleep(tempo) self.releaseKey(S) if (tecla==1): ...
python
def insertionsort(lista): tam = len(lista) for i in range(1, tam): proximo = lista[i] atual = i - 1 while proximo < lista[atual] and atual >= 0: lista[atual + 1] = lista[atual] atual -= 1 lista[atual + 1] = proximo # debug if __name__ == "__main__": ...
python
import time import argparse from helpers.connection import conn import tabulate as tb tb.WIDE_CHARS_MODE = True def parsing_store(parser:argparse.ArgumentParser): sub_parsers = parser.add_subparsers(dest='function') # info parser_info = sub_parsers.add_parser('info') parser_info.add_argument('id', ty...
python
# Copyright The PyTorch Lightning 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 to i...
python
# -*- coding: utf-8 -*- """ 定时监控futnn api进程,如果进程crash, 自动重启, 1. 该脚本仅支持windows (目前api也只有windows版本) 2. 构造 FTApiDaemon 需指定ftnn.exe所在的目录 ,一般是'C:\Program Files (x86)\FTNN\\' 3. 对象实现的本地监控, 只能运行在ftnn api 进程所在的机器上 """ import psutil import time import socket import sys import configparser from threading import Thread ...
python
import os from jinja2 import Environment, FileSystemLoader PATH = os.path.dirname(os.path.abspath(__file__)) TEMPLATE_PATH = os.path.join("/".join(PATH.split("/")[0:-1]),'resources') TEMPLATE_ENVIRONMENT = Environment( autoescape=False, loader=FileSystemLoader(TEMPLATE_PATH), trim_blocks=False) def render...
python
# Defines projections through a parallel slab. import math import numpy from camera_model import central_projection def polar_normal(elevation, azimuth): # Defines the polar coordinate representation of a normal oriented towards the z-axis per default # # elevation Elevation of the normal vector # a...
python
from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from .models import UserDetails, HospitalDetails, BankDetails, Address, DoantionLogDetails class UserRegisterForm(UserCreationForm): email = forms.EmailField() first_name = forms.CharFie...
python
import re from typing import List, TYPE_CHECKING, Union from MFramework import ( Interaction, Application_Command_Option_Type, Interaction_Type, Snowflake, Message, Interaction_Type, ChannelID, RoleID, UserID, User, Guild_Member, GuildID, Groups, ) from .command imp...
python
from scipy.optimize import linprog import numpy as np import pandas as pd class OptimizationFailedError(Exception): pass def findTaxaAGSVec(proportions, sampleAGS, taxaBounds=True): nsamples, ntaxa = proportions.shape b = np.concatenate([sampleAGS, -1 * sampleAGS]) if taxaBounds: taxaMax = 1...
python
# coding: utf-8 # In[ ]: from Bio.Blast.Applications import NcbiblastpCommandline from Bio.Blast import NCBIXML import pandas as pd import os # In[ ]: meso_file = "best_hit_org/hit_meso.csv" thermal_file = "best_hit_org/query_thermal.csv" meso_fold = "meso_protein/" thermal_fold = "thermal_protein/" meso_fst_fo...
python
# coding: utf-8 from .base import Base from .config_auth import ConfigAuth from .config import Config from .user import User from .song import Song from .feedback import Feedback
python
# Standard import sys # Dependencies import xdg.BaseDirectory as xdg class Config_File_Parse: def __init__(self, project_name, file_name): """ This function creates a diction of configuration keys and values by reading a specified text file passed as an argument. It excludes lines...
python
import pytoml as toml class TomlConfig(object): def __init__(self, param={}): pass def load_file(self, fn): with open(fn, 'r') as f: return toml.load(f) def load_str(self, s): return toml.loads(s) def dump_file(self, data, fn): with open(fn, 'w') as f: ...
python
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import sonnet as snt import tensorflow as tf from ..direction import Direction from ..naive_effect import ShortEffectLayer from ..short_board.black_piece import select_black_gi __author__ = 'Yasuhiro' __date__ = '2018/2/19' class BlackGiEffectLayer(snt.AbstractModule)...
python
length = int(input()) width = int(input()) height = int(input()) lengths_edges = 4 * (length + width + height) area = 2 * ((length * width) + (width * height) + (length * height)) volume = (length * width) * height print(lengths_edges) print(area) print(volume)
python