text
stringlengths
1
927k
N = int(input()) a_list = [int(input()) for _ in range(N)] b_list = a_list.copy() b_list.sort(reverse=True) max_num = max(b_list) for i in range(N): a = a_list[i] if a != max_num: print(max_num) else: f = True cnt = 0 for b in b_list: if a != b: ...
# coding: utf-8 # ----------------------------------------------------------------------------------- # <copyright company="Aspose" file="delete_comment_request.py"> # Copyright (c) 2021 Aspose.Words for Cloud # </copyright> # <summary> # Permission is hereby granted, free of charge, to any person obtaining a copy ...
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
import logging from pyvisdk.exceptions import InvalidArgumentError ######################################## # Automatically generated, do not edit. ######################################## log = logging.getLogger(__name__) def VmGuestRebootEvent(vim, *args, **kwargs): '''This is a virtual machine guest reboot re...
from django.views import generic # Create your views here. class RealtimeIndex(generic.TemplateView): template_name = "index.html"
import h3.api.basic_str as h3 def test1(): assert h3.geo_to_h3(37.7752702151959, -122.418307270836, 9) == '8928308280fffff' def test5(): expected = { '89283082873ffff', '89283082877ffff', '8928308283bffff', '89283082807ffff', '8928308280bffff', '8928308280ffff...
# 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...
from __future__ import absolute_import import re def get_pages(filename): with open(filename) as f: data = f.read() return data.split('\x0c') header_pattern = re.compile(r'^RFC \d+\s+.*\s+(\w+ \d{4})$', re.M) footer_pattern = re.compile(r'^\w+\s+\w+\s+\[Page \d+\]$', re.M) def remove_header(page): page = he...
#!/usr/bin/env python """ Example of a right prompt. This is an additional prompt that is displayed on the right side of the terminal. It will be hidden automatically when the input is long enough to cover the right side of the terminal. This is similar to RPROMPT is Zsh. """ from prompt_toolkit import prompt from pro...
from dataclasses import dataclass, field import os import glob from typing import Any, Dict, List, Optional from monosi.reporter import Reporter import monosi.utils.yaml as yaml @dataclass class ProjectConfigurationDefaults: version: str = '0.0.1' # TODO: Update to automatic collection_name: Optional[str] = ...
import logging from typing import Callable, Any, Dict import functools import numpy as np logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) class cached_property: """ A property that is only computed once per instance and then replaces itself with an ordinary attribute. Deleting the a...
import sys from itertools import combinations import qiskit import numpy as np import tqix sys.path.insert(1, '../') import qtm.base import qtm.nqubit import qtm.fubini_study def self_tensor(matrix, n): product = matrix for i in range(1, n): product = np.kron(product, matrix) return product ...
# ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # -------------------------------------------------------------------------- from typi...
from Load_And_Visualize_Time_Data import Load_and_Visualize_Time_Data import sys import pandas as pd import numpy as np from sktime.forecasting.model_selection import temporal_train_test_split from sktime.forecasting.exp_smoothing import ExponentialSmoothing from sktime.utils.plotting import plot_series from sktime.per...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = 'CYX' import aiohttp, asyncio HOST = 'localhost' async def url_access(session, url): async with session.get(url) as response: return await response.read() async def main(url): async with aiohttp.ClientSession() as sess: res = await...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # 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, ...
# -*- coding: utf-8 -*- """ .. _tut-cluster-spatiotemporal-sensor: ===================================================== Spatiotemporal permutation F-test on full sensor data ===================================================== Tests for differential evoked responses in at least one condition using a permutation clu...
from django.apps import AppConfig class CreateDerivativesConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'create_derivatives'
import threading import warnings from functools import wraps, update_wrapper from pyramid.response import Response class cache_forever: def __init__(self, wrapped): self.wrapped = wrapped self.saved = None update_wrapper(self, wrapped) def __call__(self, request, *args, **kwargs): ...
import keras import numpy as np from data.vocab import TextEncoder def _get_pos_encoding_matrix(max_len: int, d_emb: int) -> np.array: pos_enc = np.array( [[pos / np.power(10000, 2 * (j // 2) / d_emb) for j in range(d_emb)] if pos != 0 else np.zeros(d_emb) for pos in range(max_len)], dtype=np.flo...
""" This module demonstrates various patterns for ITERATING through SEQUENCES, including: -- Beginning to end -- Other ranges (e.g., backwards and every-3rd-item) -- The COUNT/SUM/etc pattern -- The FIND pattern (via LINEAR SEARCH) -- The MAX/MIN pattern -- Looking two places in the sequence at once -- Lo...
from django.db import models from django.contrib.auth.models import User class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) about = models.CharField(max_length=1000, default="[empty]") to_review = models.BooleanField(default=False) created = models.DateTimeFiel...
from typing import List from flask import request from flask_restx import Namespace, Resource from CTFd.api.v1.helpers.request import validate_args from CTFd.api.v1.helpers.schemas import sqlalchemy_to_pydantic from CTFd.api.v1.schemas import APIDetailedSuccessResponse, APIListSuccessResponse from CTFd.constants impo...
# -*- coding: utf-8 -*- import numpy as np import tensorflow as tf from inferbeddings.models import base as models from inferbeddings.models import similarities from inferbeddings.knowledgebase import Fact, KnowledgeBaseParser from inferbeddings.parse import parse_clause from inferbeddings.models.training import cons...
import read_arduino import math import globvar def temperatur(): read_arduino.read() #Berechnung des Widerstandswert vom NTC tempOhmREF =1100 Measure0=float(globvar.measure0) tempSPAN =Measure0*4.86/1023 #umwandeln von 8 bit in spannungswert #anwenden von u/(r1+r2)= u2/r2 umgewandelt zu r1=((u*r2)/u2)-r2 ...
from wikipedia2vec import Wikipedia2Vec import numpy as np import matplotlib.pyplot as plt import nltk nltk.download('stopwords') from nltk.corpus import stopwords import csv import scipy from scipy import stats from easyesn.optimizers import GradientOptimizer from easyesn import PredictionESN from easyesn.optimizers...
import asyncio import os import signal from queue import Queue from unittest.mock import MagicMock import pytest from sanic_testing.testing import HOST, PORT from sanic.compat import ctrlc_workaround_for_windows from sanic.response import HTTPResponse async def stop(app, loop): await asyncio.sleep(0.1) ap...
from flask import jsonify from anchore_engine.apis.authorization import get_authorizer, INTERNAL_SERVICE_ALLOWED from anchore_engine.clients.services.simplequeue import LeaseAcquisitionFailedError from anchore_engine.common.helpers import make_response_error from anchore_engine.services.policy_engine.api.models import...
from fastapi.responses import HTMLResponse from fastapi.staticfiles import StaticFiles from fastapi.templating import Jinja2Templates def mount_static_directory(api): api.mount( "/static", StaticFiles(directory="FastAPI/static"), name="static") templates = Jinja2Templates( directory=...
# Task1 Get hourly candle data from CryptoCompare ## 1. Explore CryptoCompare Data API ### Required #### 1. **Write a function** to download histohour data, parameters: # fsym: BTC, tsym: USDT, start_time="2017-04-01", end_time="2020-04-01", e='binance' # import libraries import requests import pandas as pd import tim...
"""Integration test cases to validate the properly parse of python imports""" import ast from typing import Callable, List, Tuple from py_imports.base.models import ImportStatement from py_imports.manager import PyImports class TestPyImports: """ Test cases to validate the properly parse of imports in .py fi...
from njunmt.decoders.rnn_decoder import AttentionDecoder from njunmt.decoders.rnn_decoder import CondAttentionDecoder from njunmt.decoders.rnn_decoder import SimpleDecoder from njunmt.decoders.transformer_decoder import TransformerDecoder
# -*- test-case-name: axiom.test.test_upgrading -*- from axiom.item import Item from axiom.attributes import text, integer, reference, inmemory from axiom.upgrade import registerUpgrader class ActivateHelper: activated = 0 def activate(self): self.activated += 1 class Adventurer(ActivateHelper, Ite...
""" Custom :class:`~django_analyses.models.output.output.Output` and :class:`~django_analyses.models.output.definitions.OutputDefinition` subclasses. These models expand upon django_analyses_\' :mod:`~django_analyses.models.output` module to facilitate integration with the various analysis interfaces. .. _django_anal...
#!/usr/local/bin/python # -*- coding: utf-8 -*- import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier, BaggingClassifier def plotSensores(): ### Letra A df_a = pd.read_csv("data/bernardo/bernardo-A-3-emg.csv") df_a_...
""" Base class for losses. Reduction mecanisms are implemented here. """ import torch.nn as tnn from nitorch.core.math import nansum, nanmean, sum, mean class Loss(tnn.Module): """Base class for losses.""" def __init__(self, reduction='mean'): """ Parameters ---------- redu...
# -*- test-case-name: twisted.test.test_paths -*- # Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. """ Object-oriented filesystem path representation. """ import base64 import errno import os import sys from os import listdir, stat, utime from os.path import ( abspath, basename, di...
from flask import Blueprint api = Blueprint("process_manage_api", __name__) from . import data_upload from . import data_set from . import annotation from . import pre_process from . import model_train from . import task_manage from . import batch_process
import os import glob ROOT_DIR = '/Volumes/NEUROBAU/PUBLIC/MM/Salvatore/jaws_loom_video_ethovision/' FILE_EXTENSION = 'mpg' CHARACTER_TO_REMOVE = ' ' for old_file_name in glob.iglob(ROOT_DIR + '*.' + FILE_EXTENSION): # print(old_file_name) # print("_".join(old_file_name.split(CHARACTER_TO_REMOVE))) new_fi...
# ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # -------------------------------------------------------------------------- from ..co...
# Copyright 2014 Cloudbase Solutions Srl # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless r...
# -*- coding: utf-8 -*- """ Created on Sat Jun 5 01:09:24 2021 @author: Pavel Gostev """ import setuptools with open("README.md", "r", encoding="utf-8") as fh: long_description = fh.read() setuptools.setup( name="lightprop2d", version="1.0.1", author="Pavel Gostev", author_email="gostev.pavel@ph...
# -*- coding: utf-8 -*- """ Neighbor Articles Plugin for Pelican ==================================== This plugin adds ``next_article`` (newer) and ``prev_article`` (older) variables to the article's context """ from pelican import signals def iter3(seq): """Generate one triplet per element in 'seq' following PE...
import applemusicpy from applemusicpy.client import ResourceType team_id = 'team_id' key_id = 'key_id' secret_file = 'AuthKey_' + key_id + '.p8' with open(secret_file,'r') as f: secret_key = f.read() auth = applemusicpy.Auth(secret_key=secret_key, key_id=key_id, team_id=team_id) client = applemusicpy.Client(auth...
# Copyright 2017 Bo Shao. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agre...
from os import stat from .utils.context import Context from discord.ext import commands import discord import logging from .utils.config import Config from .utils.db import RoDBClient from .utils.api import RedditAPI from .utils import static log = logging.getLogger("cogs.automod") REDDIT_DOMAINS = [ "reddit.com"...
# binary filter # to complement ranker import random def title_filter(data) -> int: #mockup return random.randint(0,1) def _filter(category: str,data: list) -> list: for i in data: i['filter_name'] = "low_quality" i['filter'] = title_filter(i['title']) return data
""" ========= Hat graph ========= This example shows how to create a `hat graph`_ and how to annotate it with labels. .. _hat graph: https://doi.org/10.1186/s41235-019-0182-3 """ import numpy as np import matplotlib.pyplot as plt def hat_graph(ax, xlabels, values, group_labels): """ Create a hat graph. ...
# -*- coding: utf-8 -*- import re from osgeo import ogr class ShpToGDALFeatures(object): def __init__(self, shpFilePath=None): if shpFilePath is None: raise Exception('No shapefile path provided') if re.search(r'(\.shp)$', shpFilePath) is None: raise TypeError( ...
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License import random from typing import List, Callable from azure.kusto.ingest._resource_manager import _ResourceUri from azure.storage.queue import QueueServiceClient, QueueClient, QueueMessage, TextBase64EncodePolicy, TextBase64DecodePolicy class Qu...
import xml.etree.ElementTree as ET import requests import random from functions.config import config def dl_connect(): configuration = config() link = configuration['Datalogger']['ip'] + configuration['Datalogger']['key'] try: # When the session is expired, this link returns an error # ...
from dataclasses import dataclass from enum import Enum from typing import Optional from open_sea_v1.endpoints.abc import BaseEndpoint from open_sea_v1.endpoints.client import BaseClient, ClientParams from open_sea_v1.endpoints.urls import EndpointURLS from open_sea_v1.responses.asset import AssetResponse class Asse...
from django.shortcuts import render # Create your views here. import folium def home(request): mf = folium.Map([35.3369, 127.7306], zoom_start=10) mf = mf._repr_html_() first ='juna' result ={'mapfolium': mf, 'fo1':first} return render(request, template_name='maps/home.html', context=result) de...
# Generated by Django 2.2.4 on 2019-10-14 10:20 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('bonbon', '0006_auto_20191013_0512'), ] operations = [ migrations.AddField( model_name='res', name='cate', ...
import main as Logger # import PyLogger.main as Logger logger = Logger.MouseLogger("Logs/mouselog.txt") logger.init_logging()
# coding=utf-8 ''' Created: 2021/3/12 @author: Slyviacassell@github.com ''' import torch import torch.nn as nn from memonger import SublinearSequential class Stage(nn.Module): def __init__(self, out_channels, layers): super(Stage, self).__init__() if isinstance(layers, (nn.Sequential, Sublinear...
""" HTTP server that implements the Python WSGI protocol (PEP 333, rev 1.21). Based on wsgiref.simple_server which is part of the standard library since 2.5. This is a simple server for use in testing or debugging Django apps. It hasn't been reviewed for security issues. DON'T USE IT FOR PRODUCTION USE! """ from __f...
from typing import Tuple, Optional from torch import Tensor from torch.distributions import MultivariateNormal import numpy as np from torch.distributions.multivariate_normal import _batch_mv from torch.distributions.utils import _standard_normal def bmat_idx(*args) -> Tuple: """ Create indices for tensor a...
from tweepy import TweepError from ultron.actions import Action from ultron.exception.twitterexceptions import InvalidUserException from ultron.helpers.twitter_helper import load_api class FollowUser(Action): def __init__(self, screen_name): self.api = load_api() self.follow_status = False ...
# Copyright The OpenTelemetry Authors # # 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 ...
""" WSGI config for tbx project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_...
import datetime import json import logging import sys import time from base64 import b64decode import httplib2 import requests from redash import settings from redash.query_runner import * from redash.utils import JSONEncoder logger = logging.getLogger(__name__) try: import apiclient.errors from apiclient.d...
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Utility for dealing with Git repositories.""" import logging import os import shutil import stat import subprocess import sys import tempfile import time...
def BinarySearch(Array, LowerBound, UpperBound, What): while LowerBound != UpperBound: mid = (LowerBound + UpperBound) // 2 if Array[mid] < What: LowerBound = mid elif Array[mid] > What: UpperBound = mid - 1 else: return mid return None
# coding: utf-8 from __future__ import unicode_literals from ..compat import compat_parse_qs, compat_urllib_parse_urlparse from ..utils import clean_html, remove_start from .common import InfoExtractor class Varzesh3IE(InfoExtractor): _VALID_URL = r"https?://(?:www\.)?video\.varzesh3\.com/(?:[^/]+/)+(?P<id>[^/]+...
import private def test_exports() -> None: assert private.__all__ == ["foo"]
if __name__ == '__main__': # Fill in the code to do the following # 1. Set x to be a non-negative integer (no decimals, no negatives) # 2. If x is divisible by 3, print 'Fizz' # 3. If x is divisible by 5, print 'Buzz' # 4. If x is divisible by both 3 and 5, print 'FizzBuzz' # 5. If x is divisib...
#!/usr/bin/env python3 from pathlib import Path import pandas as pd from src import base_dir, logger _external_data_paths = { # "rsid": base_dir / "tensorqtl_runs/genomes_210409/snp_list.biallelic_known_snps.harmonized.VQSR_filtered_99.rsID.GT_only.pkl", "rsid": base_dir / "tensorqtl_runs/genomes_210409/snp_posi...
from __future__ import absolute_import import os.path # Use the built-in version of walk if possible, otherwise # use the scandir module version try: from os import walk except ImportError: from scandir import walk from glob import glob from ceres import CeresTree, CeresNode from django.conf import settings ...
#!/usr/local/bin/python import re import sh import sys import os ##################### # Comment functions # ##################### def find_substring(substring, string): indices = [] index = -1 # Begin at -1 so index + 1 is 0 while True: # Find next index of substring, by starting search from ind...
import json import logging import urllib.error from datetime import date, timedelta from decimal import ROUND_HALF_UP, Decimal import vat_moss.exchange_rates from django.conf import settings from django.core.files.base import ContentFile from django.core.serializers.json import DjangoJSONEncoder from django.db import ...
"""Transfer Out item definition.""" from gaphas.geometry import Rectangle from gaphor.core import gettext from gaphor.core.modeling import DrawContext from gaphor.diagram.presentation import ( Classified, ElementPresentation, from_package_str, ) from gaphor.diagram.shapes import Box, IconBox, Text, stroke...
# Code generated by `typeddictgen`. DO NOT EDIT. """V1CustomResourceDefinitionNamesDict generated type.""" from typing import TypedDict, List V1CustomResourceDefinitionNamesDict = TypedDict( "V1CustomResourceDefinitionNamesDict", { "categories": List[str], "kind": str, "listKind": str, ...
from pathlib import Path from vunit.verilog import VUnit VU = VUnit.from_argv() p = Path(__file__).parent print(p) lib = VU.add_library("lib") lib.add_source_files(p / "example/*.sv", allow_empty=True) lib.add_source_files(p / "ofd/example/*.sv", allow_empty=True) lib.add_source_files(p / "*.sv", allow_empty=True) lib...
import tcod as libtcod from components.ai import ConfusedMonster from game_messages import Message def heal(*args, **kwargs): entity = args[0] amount = kwargs.get('amount') results = [] if entity.fighter.hp == entity.fighter.max_hp: results.append({'consumed': False, 'message': Message('You...
#!/usr/bin/env python import SimpleHTTPServer class MyHTTPRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler): def end_headers(self): self.send_my_headers() SimpleHTTPServer.SimpleHTTPRequestHandler.end_headers(self) def send_my_headers(self): self.send_header("Access-Control-Al...
def kill_door(): Driftwood.script["rumble.py"].end_rumble() Driftwood.tick.register(kill_door_callback1, once=True, delay=1.0) Driftwood.tick.register(kill_door_callback2, once=True, delay=2.0) Driftwood.tick.register(kill_door_callback3, once=True, delay=3.0) def kill_door_callback1(seconds_past): ...
import sys class Process: def __init__(self, program, input, output): self._program = program.copy() self._input = input self._output = output self._heap = {} self._wait_input = False self._halted = False self._instruction_ptr = 0 self._relative_base = 0 def run(self): self._w...
from operator import itemgetter import pytest from dvc.data.meta import Meta from dvc.data.tree import Tree, _merge from dvc.hash_info import HashInfo @pytest.mark.parametrize( "lst, trie_dict", [ ([], {}), ( [ {"md5": "def", "relpath": "zzz"}, {"m...
from fastapi import FastAPI import uvicorn from app.api.api_v1.api import api_router from app.core import elasticsearch as es from app.core.logging import init_logging init_logging() def create_app() -> FastAPI: app = FastAPI() app.add_event_handler("startup", es.connect_to_es) app.add_event_handler("sh...
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2013 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apach...
from dataclasses import dataclass @dataclass class Lyric: id_: str track_id: str common_track_id: str content: list @dataclass class Track: id_: str common_id: str name: str instrumental: int explicit: int artist: str album: str @dataclass class Song: name: str ...
# -*- coding: utf-8 -*- """Resnet_Full_CIFAR10 Automatically generated by Colaboratory. Original file is located at https://colab.research.google.com/drive/1MnKg-EW7K410GxNk-I8ibQExcN1mpmcb """ !nvidia-smi # Mount google drive from google.colab import drive drive.mount('/content/drive') import os import numpy...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from datetime import datetime from django.core import serializers from django.core.serializers import SerializerDoesNotExist from django.core.serializers.base import ProgressBar from django.db import connection, transaction from django.http import HttpRe...
""" exspec extracts individual bundles of spectra with one bundle per output file. This script merges them back together into a single file combining all bundles. This workflow is hacky. Release early, release often, but also refactor often. Stephen Bailey, LBL March 2014 """ from __future__ import absolute_import,...
import insightconnect_plugin_runtime from .schema import GetScansInput, GetScansOutput, Input, Output # Custom imports below from komand_rapid7_insightappsec.util.endpoints import Scans from komand_rapid7_insightappsec.util.resource_helper import ResourceHelper import json class GetScans(insightconnect_plugin_runtim...
# ======================== # Information # ======================== # Direct Link: https://www.hackerrank.com/challenges/word-order/problem # Difficulty: Medium # Max Score: 50 # Language: Python # ======================== # Solution # ======================== from collections import Counter N = int(i...
from pathlib import Path HOME_DIR = str(Path(__file__).resolve().parents[1])
import numpy as np import cv2 as cv import argparse parser = argparse.ArgumentParser(description='This sample demonstrates the meanshift algorithm. \ The example file can be downloaded from: \ https://www.bogotobogo.com/python/...
# # Copyright 2018 Analytics Zoo Authors. # # 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...
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2019. # # 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 modif...
import torch from sklearn.metrics import accuracy_score from torch.nn import Linear from torch.nn.functional import relu, dropout, log_softmax, nll_loss, leaky_relu from torch_geometric.nn import GCNConv, JumpingKnowledge from torch_geometric.utils.num_nodes import maybe_num_nodes from torch_sparse import coalesce fro...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models from django.conf import settings class Migration(migrations.Migration): dependencies = [ ('stardate', '0001_initial'), ] operations = [ migrations.AlterField( model_name=...
import pyos import math ans = 0 def sqrt(n): return math.sqrt(n) def nrt(r, n): return n**(1.0/r) def onStart(s, a): global state, app state = s app = a calc = Calculator() class Calculator(object): def __init__(self): app.ui.clearChildren() self.input = "" s...
import numpy as np from scipy.interpolate import interp1d import cv2 import rospy from .utils.topics import * from .utils.conversions import r2n class OculusFireMsg(object): """Oculus Fire Message uint8_t masterMode; // mode 0 is flexi mode, needs full fire message (not available for third party d...
from .dispatch import Event from .const import EVENT_TYPES as ETYPES import re class MessageEvent(Event): type = ETYPES.MSG @property def text(self): return self._get('text') @property def user(self): return self._get('user') @property def channel(self): return self._get('channel') class CommandEvent(...
""" EDID helper """ from subprocess import CalledProcessError, check_output from typing import ByteString, List __all__ = ["EdidHelper"] class EdidHelper: """Class for working with EDID data""" @staticmethod def hex2bytes(hex_data: str) -> ByteString: """Convert hex EDID string to bytes ...
from __future__ import annotations from datetime import datetime from mltrace.db.base import Base from sqlalchemy import ( Column, String, LargeBinary, Integer, DateTime, Table, ForeignKey, Enum, ) from sqlalchemy.orm import relationship import enum import typing class PointerTypeEnum...
# -*- coding: UTF-8 -*- import logging import os import sys import json import shutil import csv import cherrypy import re import time import datetime import collections import time import ConfigParser import uuid import validatectf from splunk import AuthorizationFailed, ResourceNotFound import splunk.rest import spl...
#!/usr/bin/env python # -- Content-Encoding: UTF-8 -- """ The Node Composer :author: Thomas Calmant :license: Apache Software License 2.0 :version: 3.0.0 .. Copyright 2014 isandlaTech Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the ...