text
stringlengths
2
999k
class Dog: def __init__ (self, length, width): self.length = length self.width = width def get_length(self): return self.length def get_width(self): return self.width while True: print("Hello there, this is your first program in an executable") meta = Dog(10, 20) print("This is the width of meta" , m...
import warnings import numpy as np from sklearn.gaussian_process import GaussianProcessRegressor from sklearn.gaussian_process.kernels import RBF, ConstantKernel as CK def GP_Interpolator(X, Y, eY, X_q, NaN_fill=0.1): # * nan-correction Avmask = ~np.isnan(Y) X, Y, eY = X[Avmask], Y[Avmask], eY[Avmask] ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # %% import argparse import sys import os import multiprocessing import numpy as np import matplotlib.pyplot as plt from copy import deepcopy import pandas as pd import torch from torch import nn, optim import higher import wandb torch.set_num_threads(multiprocessing....
import ast from ctypes import c_int8, c_int16, c_int32, c_int64 from ctypes import c_uint8, c_uint16, c_uint32, c_uint64 from typing import Dict from py2many.analysis import get_id from py2many.clike import class_for_typename from py2many.exceptions import AstUnrecognisedBinOp from py2many.inference import get_inferre...
# -*- coding: utf-8 -*- # Generated by Django 1.10 on 2016-11-19 17:54 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('core', '0026_auto_20161119_1647'), ] operations = [ migrations.AddField( ...
import os # comment out below line to enable tensorflow logging outputs os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' import time import tensorflow as tf physical_devices = tf.config.experimental.list_physical_devices('GPU') if len(physical_devices) > 0: tf.config.experimental.set_memory_growth(physical_devices[0], True...
# -*- coding: utf-8 -*- ''' SoftLayer HW Cloud Module ========================= The SoftLayer HW cloud module is used to control access to the SoftLayer hardware cloud system Use of this module only requires the ``apikey`` parameter. Set up the cloud configuration at: ``/etc/salt/cloud.providers`` or ``/etc/salt/clo...
from plastering.inferencers.quiver import DummyPritoni import rdflib ebu3b_ttl = 'groundtruth/ebu3b_brick.ttl' ebu3b_g = rdflib.Graph() ebu3b_g.parse(ebu3b_ttl, format='turtle') pritoni = DummyPritoni(ebu3b_ttl, 'ebu3b', []) pritoni.update_prior(ebu3b_g) pred = pritoni.predict()
import pyaf.Bench.TS_datasets as tsds import tests.artificial.process_artificial_dataset as art art.process_dataset(N = 32 , FREQ = 'D', seed = 0, trendtype = "ConstantTrend", cycle_length = 5, transform = "None", sigma = 0.0, exog_count = 0, ar_order = 0);
# FROM 6.3py # 6.3.1 prepare the climate data import keras print(keras.__version__) # 2.1.6 import os # prepare the climate data base_dir = 'D:/AI/deep-learning-with-python-notebooks-master' climate_dir = os.path.join(base_dir, 'jena_climate') fname = os.path.join(climate_dir, 'jena_climate_2009_2016.csv') f = ope...
import os import os.path as osp from collections import defaultdict import pickle as pkl from itertools import product import multiprocessing as mp from openbabel import pybel from classicalgsg.molreps_models.gsg import GSG from classicalgsg.classicalgsg import OBFFGSG from classicalgsg.molreps_models.utils import sc...
import requests server='http://127.0.0.1:5000/' response=requests.get(server+'flag?ioc=ninjas').text print(response)
# Copyright 2013 Rackspace, 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 agreed to in writing...
"""Jira issues collector.""" import itertools import re from base_collectors import SourceCollector from collector_utilities.type import URL, Value from model import Entities, Entity, SourceMeasurement, SourceResponses class JiraIssues(SourceCollector): """Jira collector for issues.""" SPRINT_NAME_RE = re....
""" ============================================================================= Comparing Nearest Neighbors with and without Neighborhood Components Analysis ============================================================================= An example comparing nearest neighbors classification with and without Neighborho...
import os from typing import Any, Mapping, Optional from pdm.builders.base import EnvBuilder class EnvSdistBuilder(EnvBuilder): """Build sdist in isolated env with managed Python.""" def build( self, out_dir: str, config_settings: Optional[Mapping[str, Any]] = None ) -> str: self.install...
import os from logging import DEBUG, getLogger from time import time from comet_ml import Experiment # isort: split import gym import hydra import numpy as np # from gym.utils.play import play import random import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from accel.agen...
#!/usr/bin/python import os import util import logging import subprocess import glob import signal import sys import shutil from datetime import timedelta logger = logging.getLogger('backup') class Backup: def __init__(self, settings, backup_dir, now): self.settings = settings self.date_format =...
import os import random import time import numpy as np from PIL import Image, ImageOps import numbers from torchvision.transforms import Pad,RandomHorizontalFlip from torchvision.transforms import ToTensor, ToPILImage def _is_pil_image(img): return isinstance(img, Image.Image) def crop(img, i, j, h, w): ...
from training import * from training.label_processor import process_labels from utilities.utilities import * if __name__ == "__main__": base_path = os.path.abspath(__file__ + "/..") # Must include operation being done. # e.g. generate_data_set if len(sys.argv) < 2: raise Exception("You must i...
# -*- coding: utf-8 -*- # Generated by Django 1.10.2 on 2017-04-24 06:22 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('organizer', '0006_auto_20170407_1946'), ] operations = [ migrations.CreateM...
from synapse.lib.module import CoreModule class ChemMod(CoreModule): @staticmethod def getBaseModels(): modl = {} name = 'chem' return ((name, modl),)
# Generated by Django 2.2.2 on 2019-06-26 22:16 import django.core.validators from django.db import migrations, models import django.utils.timezone class Migration(migrations.Migration): initial = True dependencies = [ ('auth', '0011_update_proxy_permissions'), ] operations = [ mig...
a=input("a= ") b=input("b= ") aa=a a=b b=aa print("a=",a) print("b=",b)
# AUTOGENERATED! DO NOT EDIT! File to edit: 01_lottery.ipynb (unless otherwise specified). __all__ = ['has_self_assignments', 'get_assignemnts'] # Cell import pandas as pd from pathlib2 import Path import random # Cell def has_self_assignments(assignments): 'Returns `True` in case the list of touples `assignment...
#!/usr/bin/env python3 # Copyright (c) 2018 The PaydayCoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test the blocksdir option. """ import os import shutil from test_framework.test_framework import Payday...
# Databricks notebook source # MAGIC %md-sandbox # MAGIC # MAGIC <div style="text-align: center; line-height: 0; padding-top: 9px;"> # MAGIC <img src="https://databricks.com/wp-content/uploads/2018/03/db-academy-rgb-1200px.png" alt="Databricks Learning" style="width: 600px"> # MAGIC </div> # COMMAND ---------- # M...
import numpy as np from phonopy.structure.cells import get_reduced_bases from phonopy.harmonic.dynamical_matrix import DynamicalMatrix class UnfolderDynamicalMatrix(DynamicalMatrix): """Dynamical matrix class When prmitive and supercell lattices are L_p and L_s, respectively, frame F is defined by L_...
from ckan.tests import TestCase import paste.fixture import pylons.test import ckan.model as model import ckan.tests as tests from ckanext.ytp_tasks.model import YtpTaskTables class TestYtpTasksPlugin(TestCase): """ Test YtpTasksPlugin class """ @classmethod def setup_class(cls): cls.app = paste....
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
# coding: utf-8 """ Copyright 2016 SmartBear Software 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...
from django.shortcuts import render, redirect from publish.models import Category def explore(request): return render(request, 'explore/explore.html') def exploreCategory(request, category): catExists = Category.objects.filter(url=category) if len(catExists) == 0: return redirect('explore:explore'...
base_variables = ['x1', 'x2', 'f1', 'f2', 'a1'] non_base_variables = ['f1', 'f2', 'a1'] M = 9999 matrix = [ [1.0, 0.0, 1.0, 0.0, 0.0], [0.0, 2.0, 0.0, 1.0, 0.0], [3.0, 2.0, 0.0, 0.0, 1.0] ] objective = [-3, -5, 0, 0, M] total = 0 independent_terms = [4, 12, 18] quotients = []
# tullinge/booking # https://github.com/tullinge/booking # imports from flask import Blueprint, render_template, redirect, request, session, jsonify # components import from components.decorators import ( login_required, user_setup_completed, user_not_setup, booking_blocked, ) from components.core imp...
#!/usr/bin/env python # -*- coding: utf-8 -*- from conans import ConanFile, CMake, tools import os def sort_libs(correct_order, libs, lib_suffix='', reverse_result=False): # Add suffix for correct string matching correct_order[:] = [s.__add__(lib_suffix) for s in correct_order] result = [] for expec...
# coding: utf-8 """ Automox Console API API for use with the Automox Console # noqa: E501 OpenAPI spec version: 2021-11-16 Contact: support@automox.com Generated by: https://github.com/swagger-api/swagger-codegen.git """ import pprint import re # noqa: F401 import six class OrgEndpointLimitD...
################################################################################# # The Institute for the Design of Advanced Energy Systems Integrated Platform # Framework (IDAES IP) was produced under the DOE Institute for the # Design of Advanced Energy Systems (IDAES), and is copyright (c) 2018-2021 # by the softwar...
def sort_bits_by_commonness(lines, index): bitlist = [line[index] for line in lines] num_0 = bitlist.count('0') num_1 = len(bitlist) - num_0 return ('0', '1') if num_0 > num_1 else ('1', '0') def get_rate(lines, rate_type): rate = '' for i in range(len(lines[0])): mcb, lcb = sort_bits_...
#!/usr/bin/env python from distutils.core import setup setup(name='brole', version='0.1', description='sphinx role for including notebooks', author='Matthew Brett, Min Ragan-Kelley', author_email='matthew.brett@gmail.com', url='http://github.com/matthew-brett/brole', packages=['bro...
from check50 import * import os class Isbnreflect(Checks): @check() def submitted(self): """You submitted 'ISBN Reflection'""" files = os.listdir() if not any(filename.startswith("isbnreflect") for filename in files): raise Error("File not found")
""" Implements the basic blame report experiment. The experiment analyses a project with VaRA's blame analysis and generates a BlameReport. """ import typing as tp from pathlib import Path from benchbuild import Project from benchbuild.utils import actions from benchbuild.utils.cmd import mkdir, opt from benchbuild....
# -*- coding: utf-8 -*- """ flask.ext.security.decorators ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Flask-Security decorators module :copyright: (c) 2012 by Matt Wright. :license: MIT, see LICENSE for more details. """ from collections import namedtuple from functools import wraps from flask import current_...
#!/usr/bin/env python import sys,string import matplotlib.pyplot as plt from matplotlib.ticker import AutoMinorLocator import matplotlib.gridspec as gridspec import numpy as np fig, ax = plt.subplots() # Values of alpha: alpha = np.array([6,8,10,15,20,30]) # Corresponding model energies: En = np.array([1.457,1.589,...
from watchFaceParser.elements.weatherElements.temperature import Temperature from watchFaceParser.elements.weatherElements.icon import Icon from watchFaceParser.elements.basicElements.number import Number class Weather: definitions = { 1: { 'Name': 'Icon', 'Type': Icon}, 2: { 'Name': 'Temperature',...
import os import fcntl import signal import json import numpy as np from selfdrive.hardware import TICI CONF_PATH = '/data/ntune/' CONF_LQR_FILE = '/data/ntune/lat_lqr.json' ntunes = {} def file_watch_handler(signum, frame): global ntunes for ntune in ntunes.values(): ntune.handle() class nTune(): def __...
# Stack Abstract Data Type (ADT) # Stack() creates a new stack that is empty. # It needs no parameters and returns an empty stack. # push(item) adds a new item to the top of the stack. # It needs the item and returns nothing # pop() removes the top item from the stack. # It needs no parameters and returns the...
# import the basic python packages we need import os import sys import tempfile import pprint import traceback # disable python from generating a .pyc file sys.dont_write_bytecode = True # change me to the path of pytan if this script is not running from EXAMPLES/PYTAN_API pytan_loc = "~/gh/pytan" pytan_static_path =...
import argparse from PIL import Image import os, sys import os.path as osp import pandas as pd from tqdm import tqdm import numpy as np import matplotlib.pyplot as plt from sklearn.metrics import roc_curve, auc, confusion_matrix, accuracy_score from sklearn.metrics import matthews_corrcoef from utils.evaluation import ...
def count(alist): length = len(alist) i = length-1 letter = 0 num = 0 upperLetter = 0 lowerLetter = 0 special1 = 0 special2 = 0 special3 = 0 while(i>=0): s = alist[i] if ord('A') <= ord(s) and ord('Z') >= ord(s): upperLetter += 2 elif ord('a') <= ord(s) and ord('z') >= ord(s): lowerLetter += 2 ...
import asyncio import synapse.lib.cell as s_cell import synapse.lib.coro as s_coro import synapse.lib.stormsvc as s_stormsvc import synapse.exc as s_exc import synapse.common as s_common import synapse.daemon as s_daemon import synapse.telepath as s_telepath import synapse.tests.utils as s_t_utils class Foo: de...
""" This examples show how to train a Bi-Encoder for the MS Marco dataset (https://github.com/microsoft/MSMARCO-Passage-Ranking). The queries and passages are passed independently to the transformer network to produce fixed sized embeddings. These embeddings can then be compared using cosine-similarity to find matchin...
import warnings from openapi_core.security.exceptions import SecurityError class BaseProvider(object): def __init__(self, scheme): self.scheme = scheme class UnsupportedProvider(BaseProvider): def __call__(self, request): warnings.warn("Unsupported scheme type") class ApiKeyProvider(Bas...
import logging import pytest from multiprocessing.dummy import Pool from helpers.cluster import ClickHouseCluster from helpers.postgres_utility import get_postgres_conn cluster = ClickHouseCluster(__file__) node1 = cluster.add_instance('node1', main_configs=['configs/named_collections.xml'], with_postgres=True) node2...
# Copyright 2021 Alibaba Group Holding Limited. All Rights Reserved. from abc import ABCMeta, abstractmethod from torch.utils.data import Dataset from essmc2.utils.file_systems import FS from ..transforms import build_pipeline, TRANSFORMS class BaseDataset(Dataset, metaclass=ABCMeta): def __init__(self, ...
person = input('Enter your name: ') print("Hello " + person + "!")
import json import os import uuid from abc import ABC, abstractmethod from dataclasses import dataclass from datetime import datetime from decimal import Decimal from typing import ( Any, Dict, Generic, Iterator, List, Mapping, Optional, Type, cast, ) from uuid import UUID from even...
# -*- coding: utf-8 -*- # Copyright 2020 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...
# -------------- # Code starts here class_1 = ['Geoffrey Hinton','Andrew Ng','Sebastian Raschka','Yoshua Bengio'] class_2 = ['Hilary Mason','Carla Gentry','Corinna Cortes'] new_class = class_1 + class_2 print(new_class) new_class.append('Peter Warden') print(new_class) new_class.remove('Carla Gentry') print(new_c...
from typing import Any from fastapi import Request from fastapi.responses import JSONResponse from src.Auth.Domain.Exceptions.TokenNotFoundException import TokenNotFoundException class TokenNotFoundHttpException: def __init__(self, app: Any): @app.exception_handler(TokenNotFoundException) async...
# -*- coding: utf-8 -*- from collections import Iterable, OrderedDict from uno import (helpers, constants) from uno.constants import (PAYLOAD, CSS, STATIC_TAGS, NORMAL_TAGS, ABNORMAL_TAGS, SELF_CLOSING_TAGS, RESERVED_WORDS_UPPER) PAYLOAD_TAGS = helpers.minus(NO...
import os from setuptools import setup here = os.path.abspath(os.path.dirname(__file__)) README = open(os.path.join(here, 'README.rst')).read() CHANGES = open(os.path.join(here, 'CHANGES.txt')).read() setup( name='django-basicauth', version='0.5.3', author='Hiroki KIYOHARA', author_email='hirokiky@gma...
""" Project Bluebox 2015, University of Stuttgart, IPVS/AS """ from itertools import count """ Project Bluebox Copyright (C) <2015> <University of Stuttgart> This software may be modified and distributed under the terms of the MIT license. See the LICENSE file for details. """ import base64 ...
# Copyright © 2017-2019 Zuercher Hochschule fuer Angewandte Wissenschaften. # 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/l...
import logging logger = logging.getLogger(__name__) __all__ = ["Int", "Datetime", "String", "Table", "CatRef", "DocRef"] Int = "int" Datetime = "datetime" String = "varchar" class Table(dict): pass # TODO: references class Ref(object): def __init__(self, prefix, target_name): self.target = "%s.%s" %...
import graphene from dagster import check from dagster.core.events import AssetLineageInfo, DagsterEventType from dagster.core.execution.plan.objects import ErrorSource from dagster.core.execution.stats import RunStepKeyStatsSnapshot from ...implementation.fetch_runs import get_step_stats from ..asset_key import Graph...
from typing import Union, Optional, Tuple, List from hwt.code import If, Switch, Concat from hwt.hdl.frameTmplUtils import ChoicesOfFrameParts from hwt.hdl.transPart import TransPart from hwt.hdl.types.defs import BIT from hwt.hdl.types.stream import HStream from hwt.hdl.types.struct import HStructField from hwt.inter...
# https://www.hackerrank.com/challenges/decibinary-numbers/problem # 7/8 Test Cases Passed #!/bin/python3 import math import os import random import re import sys import bisect from collections import defaultdict, Counter # # Complete the 'decibinaryNumbers' function below. # # The function is expected to return a L...
"""Type visitor classes. This module defines the type visitors that are intended to be subclassed by other code. They have been separated out into their own module to ease converting mypy to run under mypyc, since currently mypyc-extension classes can extend interpreted classes but not the other way around. Separatin...
#Write a Python program to calculate midpoints of a line def mid(x1,y1,x2,y2): xm = (x1+x2)/2 ym = (y1+y2)/2 return xm,ym print(mid(2,4,5,9)) print(mid(0,0,8,1))
# -*- coding: utf-8 -*- from os.path import join as pjoin from pathlib import Path from tempfile import TemporaryDirectory from tests.base import TestCase, assets, main, copy_of_directory from ocrd.resolver import Resolver from ocrd_utils import pushd_popd, initLogging METS_HEROLD = assets.url_of('SBB0000F293000100...
# Copyright 2020 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
import unittest import tempfile import shutil from lbry.wallet.server.db.revertable import RevertableOpStack, RevertableDelete, RevertablePut, OpStackIntegrity from lbry.wallet.server.db.prefixes import ClaimToTXOPrefixRow, HubDB class TestRevertableOpStack(unittest.TestCase): def setUp(self): self.fake_d...
import logging import time from urllib.parse import urlparse import dns.resolver from ..configuration import Configuration from ..credentials import OAuth2Credentials from ..errors import AutoDiscoverFailed, AutoDiscoverCircularRedirect, TransportError, RedirectError, UnauthorizedError from ..protocol import Protocol...
import pycountry import requests import sys import time from entity.video import YouTubeVideo from util.args import Args from util.file_processing import get_data_from_file from .data_preprocessing import prepare_feature, get_tags class YouTubeTrendingVideosScraper: def __init__(self): self.__api_key =...
import logging import random from fastapi import APIRouter import pandas as pd from pydantic import BaseModel, Field, validator log = logging.getLogger(__name__) router = APIRouter() class Item(BaseModel): """Use this data model to parse the request body JSON.""" Description: str City: ...
# -*- coding: utf-8 -*- from django.conf import settings from django.db import migrations, models import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('contenttypes', '0002_remove_content_type_name'), migrations.swappable_dependency(settings.AUTH_USER_MODEL), ...
# encoding: utf-8 """ Latent style-related objects. """ from __future__ import ( absolute_import, division, print_function, unicode_literals ) from . import BabelFish from docxx.shared import ElementProxy class LatentStyles(ElementProxy): """ Provides access to the default behaviors for latent styles i...
# Copyright 2019 DeepMind Technologies Ltd. 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 appl...
# -*- coding: utf-8 -*- """ Created on Wed Mar 14 19:58:29 2018 @author: sarth, demi, sid """ import os from setuptools import setup, find_packages PACKAGES = find_packages() # Get version and release info, which is all stored in shablona/version.py ver_file = os.path.join('shablona', 'version.py') with open(ver_file)...
""" Tests scikit-learn's KNeighbours Classifier and Regressor converters. """ import unittest from distutils.version import StrictVersion import numpy from sklearn import datasets from sklearn.model_selection import train_test_split from sklearn.neighbors import KNeighborsRegressor, KNeighborsClassifier from sklearn.pi...
# # Copyright (C) 2016 Transaction Processing Performance Council (TPC) and/or # its contributors. # # This file is part of a software package distributed by the TPC. # # The contents of this file have been developed by the TPC, and/or have been # licensed to the TPC under one or more contributor license agreements. # ...
# encoding=utf-8 # Author: Yu-Lun Chiang # Description: Test NewsCrawler import logging import pytest from collections import namedtuple from Sanga.media import ftvnews from Sanga.struct import NewsStruct logger = logging.getLogger(__name__) TEST_DATA = namedtuple( typename="TEST_DATA", field_names=[ ...
#!C:\Users\ruthw\PycharmProjects\flask-tutorial\venv\Scripts\python.exe # EASY-INSTALL-ENTRY-SCRIPT: 'pip==9.0.1','console_scripts','pip3' __requires__ = 'pip==9.0.1' import re import sys from pkg_resources import load_entry_point if __name__ == '__main__': sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys....
import jwt from fastapi import Depends from fastapi import HTTPException from fastapi.security import OAuth2PasswordBearer from starlette.requests import Request from schemas.user import User as UserSchema from passlib.hash import argon2 from config import get_config app_config = get_config() oauth2_scheme = OAuth2Pa...
from typing import List, Optional, Tuple, NamedTuple, Union, Callable import torch from torch import Tensor from torch_sparse import SparseTensor class EdgeIndex(NamedTuple): edge_index: Tensor e_id: Optional[Tensor] size: Tuple[int, int] def to(self, *args, **kwargs): edge_index = self.edge...
# -*- coding: utf-8 -*- import calendar import collections import re import six from datetime import datetime, timedelta from warnings import warn from dateutil.relativedelta import relativedelta from dateparser.date_parser import date_parser from dateparser.freshness_date_parser import freshness_date_parser from dat...
from gibson.envs.minitaur_env import MinitaurNavigateEnv from gibson.utils.play import play import argparse import math import os config_file = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', 'configs', 'minitaur_navigate_nonviz.yaml') class SineStandController: """An example of minitaur standing an...
#!/usr/bin/python """ This script demonstrates the usage of mraa library for interfacing a temperature sensor setup: The temperature sensor is connected to port A1 Demo: start the application in the command line by using following command: python temp_mraa.py You should see the temperature being printed out in the ...
"""Class to encapsulate a message.""" from datetime import datetime from copy import copy import asyncio from random import randrange from opsdroid.helper import get_opsdroid class Message: # pylint: disable=too-few-public-methods """A message object.""" def __init__(self, text, user, room, connector, ...
# -*- coding: utf-8 -*- """ babel.localedata ~~~~~~~~~~~~~~~~ Low-level locale data access. :note: The `Locale` class, which uses this module under the hood, provides a more convenient interface for accessing the locale data. :copyright: (c) 2013 by the Babel Team. :license: BSD, s...
import pytest import falcon from falcon import testing def test_custom_router_add_route_should_be_used(): check = [] class CustomRouter: def add_route(self, uri_template, *args, **kwargs): check.append(uri_template) def find(self, uri): pass app = falcon.API(rou...
""" Dynamic pseudo-scoping for Python. Call functions with context.call({key: value}, func); func and functions that it calls will be able to use 'context.get(key)' to retrieve 'value'. This is thread-safe. """ from __future__ import division, absolute_import from threading import local defaultContextDict = {} se...
#!/usr/bin/env python # encoding: utf-8 # Copyright (c) 2019 Elephant Robotics, Inc. All rights reserved. # File name: visiongenerator.py # Author: Leonid, Joey # Version: 1.01 # Date: 20, Jan, 2020 # Description: vision feature generator # Using this MarsAI source code is subject to the terms a...
#%% import data import helper as hp import cnn import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim transform = 'default' learnRate = 0.001 momentum = 0.9 epoch = 10 criterion = nn.CrossEntropyLoss() num_device = 2 device = torch.device("cuda:{}".format(num_device) if torch...
# -*- coding: utf-8 -*- # Copyright (c) 2015 Ericsson AB # # 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 ...
import sqlite3 conn = sqlite3.connect('example.db') DB_NAME = 'example.db' conn.cursor().execute('CREATE TABLE IF NOT EXISTS posts(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, author TEXT, content TEXT)') conn.commit() class DB: def __enter__(self): self.conn = sqlite3.connect(DB_NAME) retu...
""" Smart loading of a spyre app """ import time import sys from importlib import import_module import traceback from spyre.widgets.spyre_widget import SpyreApp, SpyreWidget from spyre.widgets.spyrelet_widget import SpyreletWidget from spyre.instrument import Instrument #from main_config import spyrelets, devices ...
from typing import List, Optional, Tuple, cast from hpcrocket.core.progressive_file_operations import ( CopyInstruction, progressive_copy, progressive_clean, ) from hpcrocket.core.errors import get_error_message from hpcrocket.core.filesystem import FilesystemFactory from hpcrocket.core.slurmbatchjob impor...
import os import datetime import csv import time import random from time import sleep from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By from selenium.common.exceptions import NoSuchElementExceptio...
import abc from contextlib import contextmanager from dataclasses import dataclass, replace from typing import Callable, Dict, Iterator, List, Optional, Union from .error import DecompFailure from .options import Target from .asm_instruction import ( ArchAsmParsing, Argument, AsmGlobalSymbol, AsmLitera...