content
stringlengths
5
1.05M
from math import sqrt from numpy import matrix from intpm import intpm A = matrix([[1, 0, 1, 0], [0, 1, 0, 1]]) b = matrix([1, 1]).T c = matrix([-1, -2, 0, 0]).T mu = 100 x1 = 0.5 * (-2 * mu + 1 + sqrt(1 + 4*mu*mu)) x2 = 0.5 * (-mu + 1 + sqrt(1 + mu * mu)) x0 = matrix([x1, x2, 1 - x1, 1 - x2]).T intpm(A, b, c, x0, ...
# -*- coding: utf-8 -*- """ Created on Wed Oct 21 10:57:29 2020 @author: cheritie """ # modules for the KL basis computation: import numpy as np from astropy.io import fits as pfits from AO_modules.tools.tools import createFolder import AO_modules...
from collections import deque from re import sub from sys import stderr p1 = deque([], maxlen = 52) p2 = deque([], maxlen = 52) n = int(input()) # the number of cards for player 1 for i in range(n): p1.append(input()) # the n cards of player 1 m = int(input()) # the number of cards for player 2 for i in range(...
import operator from pandas import notnull, isnull from zeex.core.utility.collection import Eval STRING_TO_OP = { '+' : operator.add, '-' : operator.sub, '*' : operator.mul, '/' : operator.truediv, '%' : operator.mod, '^' : ...
# tensorflow core import tensorflow as tf # a=3,b=5,(a+b)+(a*b)=? node1 = tf.constant(3.0) node2 = tf.constant(4.0) print("node1:", node1, "\nnode2:", node2) sess = tf.Session() print("sess.run([node1,node2]):", sess.run([node1, node2])) node3 = tf.add(node1, node2) print("node3:", node3) print("sess.run(node3):", sess...
#!/usr/bin/env python # encoding: utf-8 """ display.py is the portion of Death God that manages the screen. by William Makley """ import pygame from pygame.locals import Rect from . import colors from . import settings from . import fonts from .map_view import MapView from . import message from .status_view import St...
#!/usr/bin/env python # coding: utf-8 import re import logging from collections import defaultdict from abc import ABC, abstractmethod from . import strutil REPLACER = "**" REPLACER_HEAD = "*" REPLACER_TAIL = "*" REPLACER_REGEX = re.compile(r"\*[A-Z]*?\*") # shortest match ANONYMIZED_DESC = "##" _logger = logging....
import pandas as pd import numpy as np from sklearn.externals import joblib from sklearn.preprocessing import LabelEncoder from functools import partial import re num_months = 4 chunk_size = 1000000 indicators = ['ind_ahor_fin_ult1', 'ind_aval_fin_ult1', 'ind_cco_fin_ult1', 'ind_cder_fin_ult1', 'ind_cno_fin_ult1', ...
""" navigate env with velocity target """ #!/usr/bin/env python from __future__ import absolute_import, division, print_function from typing import Any, Callable, Dict, List, Optional, Tuple, Union import numpy as np import rospy from blimp_env.envs.common.abstract import ROSAbstractEnv from blimp_env.envs.common.ac...
import os.path import unittest import unittest.mock as mock import psutil import pytest import fpgaedu.vivado def find_vivado_pids(): ''' return a set containing the pids for the vivado processes currently activated. ''' vivado_procs = filter(lambda p: 'vivado' in p.name(), psutil.process_iter())...
# Copyright 2021 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...
#imports from random import randint stDevMonthly = 0.07 stDevWeekly = 0.0095 def getDosageStats(popSize): exposureStats = [] for i in range(0, popSize): temp = [] temp.append(randint(3,7)) temp.append(stDevMonthly) temp.append(stDevWeekly) exposureStats.append(temp) ...
from flask import Flask from flask import render_template app = Flask(__name__) @app.route('/') def index(): name = 'Jhasmany' return render_template('index.html', name=name) @app.route('/client') def client(): list_name = ['Test1', 'Test2', 'Test3'] return render_template('client.html', list=list_na...
#------------------------------------------------------------------------------ # Get the trending colors. # GET /v1/color_trends/{report_name}/trending_colors #------------------------------------------------------------------------------ import os import json import requests from urlparse import urljoin from pprint ...
#coding=utf-8 from __future__ import print_function import os import sys # Do not use end=None, it will put '\n' in the line end auto. print('test\r\ntest',end=u'') # 74 65 73 74 0D 0D 0A 74 65 73 74 # Debug in python Windows source code, it run into # builtin_print() -> PyFile_WriteObject()->file_Pyobject_Print()-> ...
from . import serializers from rest_framework import generics,authentication,permissions from rest_framework.authtoken.views import ObtainAuthToken from rest_framework.settings import api_settings class CreateUserView(generics.CreateAPIView): serializer_class=serializers.UserApiSerializer class CreateTokenView(O...
#!/usr/bin/env python # Load required modules import matplotlib matplotlib.use('agg') import sys, os, argparse, json, matplotlib.pyplot as plt, seaborn as sns, pandas as pd, numpy as np import matplotlib.patches as mpatches from models import EN, RF, IMPORTANCE_NAMES, FEATURE_CLASS_NAMES sns.set_style('whitegrid') # ...
def other_side_of_seven(num): dist = 7 - num num = 7 + (2 * dist) return num print(other_side_of_seven(4)) print(other_side_of_seven(12))
import argparse def parse(): parser = argparse.ArgumentParser() parser.add_argument("URL", nargs='?') parser.add_argument("-s", action="store_true") parser.add_argument("-l", type=str) parser.add_argument("-t", type=str) args = parser.parse_args() return args
import torch from torchtext import data import numpy as np import pandas as pd import torch.nn as nn import torch.nn.functional as F import spacy nlp = spacy.load('en') SEED = 1 torch.manual_seed(SEED) torch.cuda.manual_seed(SEED) TEXT = data.Field(tokenize='spacy') LABEL = data.LabelField(tensor_type=torch.FloatTen...
from django.contrib.auth.models import User from rest_framework import serializers from .models import Rating, Site, Picture, Like, Category class CategorySerialier(serializers.ModelSerializer): class Meta: model = Category fields = ('id', 'description', 'icon') class RatingSerializer(serializer...
#!/usr/bin/env python import os import time import re import sys import hashlib import shutil import pathlib import traceback import subprocess import pandas import argparse from ...shared import shared_tools as st import lxml.etree as et from pathlib import Path from datetime import datetime from job...
# Generated by Django 1.10.5 on 2017-02-15 08:48 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('admin', '0008_domain_enable_dns_checks'), ] operations = [ migrations.RenameField( model_name='domain', old_name='quota', ...
#assigning the int 100 to "cars" cars = 100 #assiging the int 4.0 to "space_in_a_car space_in_a_car = 4.0 #assigning drivers to the int 30 drivers = 30 #assigning passangers to the int 90 passengers = 90 #assigning cars_not_driver to (cars-drivers) cars_not_driven = cars - drivers #assigning cars_driven to drivers cars...
""" Copyright 2020 The OneFlow 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 applicable law or agr...
import codecs import logging import time from concurrent.futures.thread import ThreadPoolExecutor from pathlib import Path import frontmatter from bs4 import BeautifulSoup from jinja2 import Environment, FileSystemLoader from aqui_brain_dump import base_url, content_path, get_creation_date, get_last_modification_date...
#! /usr/bin/env python """ This script produces the stacks for emission line luminosity limited samples. """ import sys import os from os.path import join import glob import numpy as n import astropy.io.fits as fits import SpectraStackingEBOSS as sse from scipy.interpolate import interp1d import matplotlib matplotlib...
import socket import sys name = sys.argv[1] print 'Resolving Server Service Name for ' + name ipAddress = socket.gethostbyname(name) print('IP address of host name ' + name + ' is: ' + ipAddress)
import cStringIO as StringIO import numpy as np from sensor_msgs.msg import PointCloud2 #from rospy.numpy_msg import numpy_msg #PointCloud2Np = numpy_msg(PointCloud2) import pypcd import pyrosmsg pc = pypcd.PointCloud.from_path('./tmp.pcd') msg = pc.to_msg() #msg2 = PointCloud2() #msg2.deserialize(smsg) def wit...
#!/usr/bin/env python3 # train MNIST with latent equilibrium model # and track experiment using sacred import torch from sacred import Experiment from sacred.observers import FileStorageObserver ex = Experiment('layeredMNIST') ex.observers.append(FileStorageObserver('runs')) # configuration @ex.config def config():...
from django.contrib import admin from demo_api import models admin.site.register(models.CustomUser) # Register your models here.
# Generated by Django 2.0.7 on 2018-08-06 16:58 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('main', '0004_auto_20180804_2152'), ] operations = [ migrations.AlterModelOptions( name='dac', options={'ordering': [...
import os from flask import Flask, redirect from flask import request from flask import jsonify import hashlib app = Flask(__name__) c = 0 clients = [] chat = [] #[from, to, status[0sent, 1accepted, 2rejected]] requests = {} requests_sent = {} version = 5 additive = 0 def getUID(ip): return hashlib.sha256(str(...
from django.apps import AppConfig from django.db.models.signals import post_migrate from django.utils.translation import gettext_lazy as _ class SitesConfig(AppConfig): default_auto_field = "django.db.models.BigAutoField" name = "webquills.sites" label = "sites" verbose_name = _("Webquills sites") ...
import socket import select import threading import json import sys import traceback import os import random from clientInterface import ClientInterface from constants import LOGIN, LOGOUT, CREATE_ACCOUNT, DELETE_ACCOUNT, EXIT, ACTIVE_USERS, ACTIVE_STATUS, INACTIVE_STATUS, OPEN_CHAT, CLOSE_CHAT, DELETE_MESSAGES, SEND_M...
#!/usr/bin/env python # The MIT License (MIT) # Copyright (c) 2017 Lancaster 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 #...
import matplotlib.pyplot as plt import cartopy.crs as ccrs import cartopy.io.img_tiles as cimgt from sklearn import neighbors import numpy as np from ela.textproc import * from ela.classification import KNN_WEIGHTING # These functions were an attempt to have interactive maps with ipywidgets but proved to be a pain...
import os import six from six.moves import cPickle import time import numpy as np import modelarts.aibox.ops as ops from modelarts.aibox.pipeline import Pipeline import modelarts.aibox.types as types _R_MEAN = 125.31 _G_MEAN = 122.95 _B_MEAN = 113.87 _CHANNEL_MEANS = [_R_MEAN, _G_MEAN, _B_MEAN] _R_STD = 62.99 _G_ST...
#!/usr/bin/env python import flask from flask import Flask, render_template, request, json, redirect, session, flash from flaskext.mysql import MySQL from processor import Processor from werkzeug import generate_password_hash, check_password_hash def init_db(): print "Init DB" print "mysql = ", mysql pr...
from . import BaseAgent from pommerman.constants import Action from pommerman.agents import filter_action import random class RulesRandomAgentNoBomb(BaseAgent): """ random with filtered actions but no bomb""" def __init__(self, *args, **kwargs): super(RulesRandomAgentNoBomb, self).__init__(*args, **k...
class Database(object): placeholder = '?' def connect(self, dbtype, *args, **kwargs): if dbtype == 'sqlite3': import sqlite3 self.connection = sqlite3.connect(*args) elif dbtype == 'mysql': import MySQLdb self.connection = MySQLdb.con...
import re import requests import csv lines = [] with open('01.csv', 'r') as csvFile: texts = csv.reader(csvFile) for text in texts: lines.append(text[0]) datas = [] datass = [] count = 0 # 提取阅读数,评论数,转发数,收藏数 for num in range(0,220): datas = [] x = lines[num] w = x[-21:-13] ...
from connaisseur.image import Image class ValidatorInterface: def __init__(self, name: str, **kwargs): # pylint: disable=unused-argument """ Initializes a validator based on the data from the configuration file. """ self.name = name def validate(self, image: Image, **kwargs) ...
""" defines: - CalculixConverter """ from collections import defaultdict from numpy import array, zeros, cross from numpy.linalg import norm # type: ignore from pyNastran.bdf.bdf import BDF, LOAD # PBAR, PBARL, PBEAM, PBEAML, from pyNastran.bdf.cards.loads.static_loads import Force, Moment class CalculixConvert...
import serial import serial.tools.list_ports import time import threading as thread class Laser: def __init__(self): self.__ser = serial.Serial() self.pulseMode = None self.repRate = None self.burstCount = None self.diodeCurrent = None self.energyMode = None ...
# Generated by Django 3.1.5 on 2021-04-15 14:49 from django.db import migrations, models import django.db.models.deletion import mptt.fields class Migration(migrations.Migration): dependencies = [ ('comments', '0001_initial'), ] operations = [ migrations.AlterField( model_na...
from datetime import datetime from flask import (Flask, abort, flash, jsonify, redirect, render_template, url_for, request) from flask_bootstrap import Bootstrap from flask_login import (LoginManager, current_user, UserMixin, login_required, login_user, logout_user) from fl...
from hstest import StageTest, TestedProgram, CheckResult, dynamic_test class Test(StageTest): answers = [ '#### Hello World!\n', 'plain text**bold text**', '*italic text*`code.work()`', '[google](https://www.google.com)\n', '1. first\n2. second\n3. third\n4. fourth\n', ...
import pytest from pasee.__main__ import load_conf from pasee import MissingSettings import mocks def test_load_conf(): """Test the configuration logging""" with pytest.raises(MissingSettings): load_conf("nonexistant.toml") config = load_conf("tests/test-settings.toml") assert config["host"] ...
from UR10 import * u = UR10Controller('10.1.1.6') x = URPoseManager() x.load('t1.urpose') print(x.getPosJoint('home')) resp = input('hit y if you want to continue') if resp == 'y': x.moveUR(u,'home',30)
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Wireshark - Network traffic analyzer # By Gerald Combs <gerald@wireshark.org> # Copyright 1998 Gerald Combs # # SPDX-License-Identifier: GPL-2.0-or-later '''Update the "manuf" file. Make-manuf creates a file containing ethernet OUIs and their company IDs. It merges the...
from unittest import mock import json import time from aiohttp import web from aiohttp.web_middlewares import _Handler from aiohttp.test_utils import TestClient from typing import Any, Dict from aiohttp_session import get_session, SimpleCookieStorage from aiohttp_session import setup as setup_middleware from typede...
import json import os import dotenv class ConfigError(Exception): def __init__(self, field): super().__init__(f'Missing environment variable {field}') def get_env_var(name: str, default: str = None, prefix='', allow_empty=False): if prefix: env = prefix + '_' + name else: env = ...
"""Library for Byte-pair-encoding (BPE) tokenization. Authors * Abdelwahab Heba 2020 * Loren Lugosch 2020 """ import os.path import torch import logging import csv import json import sentencepiece as spm from speechbrain.dataio.dataio import merge_char from speechbrain.utils import edit_distance import speechbrain ...
from ExceptionHandler import ExceptionHandler class InputController: def __init__(self, inputReader, exceptionHandler): self.InputReader = inputReader self.ExceptionHandler = exceptionHandler def pollUserInput(self): return self.ExceptionHandler.executeFunc()
import math def factors(n): results = set() for i in range(1, int(math.sqrt(n)) + 1): if n % i == 0: results.add(i) results.add(int(n/i)) return results x = 0 i = 0 while True: x += i if len(factors(x)) > 500: print(x) i += 1
""" MesoNet Authors: Brandon Forys and Dongsheng Xiao, Murphy Lab https://github.com/bf777/MesoNet Licensed under the Creative Commons Attribution 4.0 International License (see LICENSE for details) The method "vxm_data_generator" is adapted from VoxelMorph: Balakrishnan, G., Zhao, A., Sabuncu, M. R., Guttag, J., & Dal...
from py.test import raises from pypy.conftest import gettestobjspace class AppTestUnicodeData: def setup_class(cls): space = gettestobjspace(usemodules=('unicodedata',)) cls.space = space def test_hangul_syllables(self): import unicodedata # Test all leading, vowel and trailing...
# Copyright 2021 Huawei Technologies Co., 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 ap...
class A: def foo<caret><error descr="Method must have a first parameter, usually called 'self'">()</error>: # Add 'self' pass
import copy import math import random import typing as t import hypemaths as hm from ..exceptions import ( InvalidMatrixError, MatrixDimensionError, MatrixNotSquare, ) from ..mixins import CopyMixin class Matrix(CopyMixin): def __init__( self, matrix: t.Union[int, float, list]...
# # Qutebrowser Config # from cconfig import CConfig # Custom state full config options cc = CConfig(config) cc.redirect = True # ==================== General Settings ================================== c.hints.chars = 'dfghjklcvbnm' c.hints.uppercase = True c.confirm_quit = ['n...
"""Misc funcs for backtester""" import pandas as pd from io import StringIO from . import fb_amzn def load_example(): """Load example input data""" df = pd.read_csv(StringIO(fb_amzn.data)) df['date'] = pd.to_datetime(df['date']).dt.tz_localize('US/Central') return df
import pprint import sys import numpy as np def pbatch(source, dic): ss = np.transpose(source) for line in ss[:10]: for word in line: a = dic[word] b = a if a == "SOS": b = "{" elif a == "EOS": b = "}" elif a =...
from cryptofield.fieldmatrix import * import unittest class TestFMatrix(unittest.TestCase): def testMatrixGetRow1(self): F = FField(4) m = FMatrix(F, 3, 3) m.ident() r = m.getRow(1) ans = [FElement(F, 0), FElement(F, 1), FElement(F, 0)] self.assertEqual(r, ans) def testMatrix...
# Generated by Django 2.2.5 on 2019-10-28 17:29 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('service', '0001_initial'), ] operations = [ migrations.AlterField( model_name='rating', ...
def binary_search(input_array, value): first = 0 last = len(input_array) - 1 found = False while first <= last and not found: middle_point = (first + last)//2 if input_array[middle_point] == value: found = True else: if value < input_array[middle_point]: ...
from rest_framework import permissions class IsBuyerOrSellerUser(permissions.BasePermission): def has_permission(self, request, view): if request.user.is_authenticated and request.user.is_buyer_or_seller: return True return False
from copy import deepcopy from dbt.contracts.graph.manifest import WritableManifest from dbt.contracts.results import CatalogArtifact def edit_catalog( catalog: CatalogArtifact, manifest: WritableManifest ) -> CatalogArtifact: output = deepcopy(catalog) node_names = tuple(node for node in output.nodes) ...
# -*- coding: utf-8 -*- """ encryption test_services module. """ import pytest import pyrin.security.encryption.services as encryption_services import pyrin.configuration.services as config_services from pyrin.security.encryption.handlers.aes128 import AES128Encrypter from pyrin.security.encryption.handlers.rsa256 i...
""" HoNCore. Python library providing connectivity and functionality with HoN's chat server. Packet ID definitions. Updated 23-7-11. Client version 2.40.2 """ """ Server -> Client """ HON_SC_AUTH_ACCEPTED = 0x1C00 HON_SC_PING = 0x2A00 HON_SC_CHANNEL_MSG = 0x03 HON_SC_JOINE...
"""A quantum tic tac toe running in command line""" from qiskit import Aer from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit import CompositeGate from qiskit import execute import numpy as np from composite_gates import cry,cnx,any_x,bus_or,x_bus class Move(): def __init__(self,ind...
import os import foundations from foundations_contrib.global_state import current_foundations_context, message_router from foundations_events.producers.jobs import RunJob foundations.set_project_name('default') job_id = os.environ['ACCEPTANCE_TEST_JOB_ID'] pipeline_context = current_foundations_context().pipeline_c...
class MySql(object): pass
#!/usr/bin/env python3 # # Author: Jeremy Compostella <jeremy.compostella@gmail.com> # # 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 copyright # notic...
import cv2 import numpy as np from PIL import Image, ImageDraw from scipy.spatial import ConvexHull from skimage import filters import tensorflow as tf from monopsr.core import evaluation from monopsr.datasets.kitti import instance_utils, calib_utils from monopsr.visualization import vis_utils def np_proj_error(poin...
# # Copyright 2021 Red Hat Inc. # SPDX-License-Identifier: Apache-2.0 # """Test the ExpiredDataRemover object.""" import logging import re from datetime import datetime from unittest.mock import patch from uuid import uuid4 import pytz from dateutil import relativedelta from api.provider.models import Provider from m...
import threading import time import numpy as np from matplotlib import pyplot as plt from matplotlib.figure import Figure from matplotlib.widgets import Slider, Button import logging logging.basicConfig(level=logging.DEBUG, format='(%(threadName)-9s) %(message)s',) class MyFigure(Figure): def ...
# MIT License # # Copyright (C) 2021. Huawei Technologies Co., Ltd. All rights reserved. # # 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 th...
#!/usr/local/bin/python3.3 def echo(message): print(message) return echo('Direct Call') x = echo x('Indirect Call') def indirect(func, arg): func(arg) indirect(echo, "Argument Call") schedule = [(echo, 'Spam'), (echo, 'Ham')] for (func, arg) in schedule: func(arg) def make(label): def echo(me...
# Copyright (c) 2015 # # All rights reserved. # # This file is distributed under the Clear BSD license. # The full text can be found in LICENSE in the root directory. from boardfarm.devices import prompt from boardfarm.tests import rootfs_boot class NetperfRFC2544(rootfs_boot.RootFSBootTest): """Single test to s...
import SimpleITK as sitk import numpy as np def reshape_by_padding_upper_coords(image, new_shape, pad_value=None): shape = tuple(list(image.shape)) new_shape = tuple(np.max(np.concatenate((shape, new_shape)).reshape((2,len(shape))), axis=0)) if pad_value is None: if len(shape)==2: pad_...
# # PySNMP MIB module SUN-SNMP-NETRA-CT-RSC-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/SUN-SNMP-NETRA-CT-RSC-MIB # Produced by pysmi-0.3.4 at Wed May 1 15:12:10 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3....
from django.core.management.base import BaseCommand from django.conf import settings from ..utilities.modelwriter import * class Command(BaseCommand): help = 'Add a new model to an app.' def add_arguments(self, parser): parser.add_argument( 'app_name', action='store', ...
from test.vim_test_case import VimTestCase as _VimTest from test.constant import * # Recursive (Nested) Snippets {{{# class RecTabStops_SimpleCase_ExpectCorrectResult(_VimTest): snippets = ('m', '[ ${1:first} ${2:sec} ]') keys = 'm' + EX + 'm' + EX + 'hello' + \ JF + 'world' + JF + 'ups' + JF + 'en...
from disnake import CommandInteraction, Embed, Thread from disnake.ext.commands import Cog, Param, slash_command from src import Bot from src.impl.database import Channel, ChannelMap, Message from src.impl.utils import is_administrator class Core(Cog): def __init__(self, bot: Bot) -> None: self.bot = bot...
from .models import Folder, MEDIA_MODELS def handle_uploaded_file(file, folder=None, is_public=True): '''handle uploaded file to folder match first media type and create media object and returns it file: File object folder: str or Folder isinstance is_public: boolean ''' _folder = None ...
# Copyright 2021 The SeqIO 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 wr...
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # 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...
import time import RPi.GPIO as GPIO import SerialWombatPigpioI2c import SerialWombatServo import SerialWombatAnalogInput import SerialWombatQuadEnc GPIO.setwarnings(False) sw = SerialWombatPigpioI2c.SerialWombatChipPigpioI2c(17,27,0x6D) sw.begin(False) print(sw.version) print(sw.model) print(sw.fwVersion) servo =...
#!/usr/bin/python # -*- coding: utf-8 -*- # newclass.py from pfp_sdk.PFPUtil import * class Example(wx.Frame): def __init__(self, parent, title): super(Example, self).__init__(parent, title=title, pos=(100,100), size=(800, 230)) self.InitUI() self.Centre() self.Show() ...
"""A practical configuration system. """ from .extension_point import ExtensionPoint # noqa: F401 from .loading import load_from_module, load_from_pkg_resources # noqa: F401 from .option import build_default_config, Option # noqa: F401 from .profile import Profile # noqa: F401 from .utilities import merge # noqa:...
"""Transform metrics stored in SQuaSH into InfluxDB format. See sqr-009.lsst.io for a description on how metrics are stored in SQuaSH and the resulting InfluxDB data model. """ __all__ = ["Transformer"] import logging import math import pathlib import urllib.parse import requests import yaml from requests.exception...
from globibot.lib.web.handlers import SessionHandler from globibot.lib.web.decorators import authenticated, respond_json from http import HTTPStatus server_data = lambda server: dict( id = server.id, name = server.name, icon_url = server.icon_url, ) class GuildHandler(SessionHandler): @aut...
import json import random import glob import torch import numpy as np import clip.clip as clip import pickle from collections import Counter, defaultdict from tqdm import tqdm from torch.utils.data import DataLoader import sys from vqa.vqa_dataset import VQADataset SOFT_PROMPT = True ITER_TO_BREAK = 999 def eval_ini...
""" Created on Jan 27, 2016 @author: tmahrt Tests that praat files can be read in and then written out, and that the two resulting files are the same. This does not test that the file reader is correct. If the file reader is bad (e.g. truncates floating points to 1 decimal place), the resulting data structures will...
from pyfluminus.authorization import vafs_jwt from pyfluminus.api import name, modules, get_announcements from pyfluminus.structs import Module from flask import Flask, request, jsonify, redirect, url_for, render_template import sys from app import app, db, util from app.models import User, User_Mods, Announcements, M...
""" Copyright (c) 2018-2021 Intel Corporation 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 wri...
# -*- coding: utf-8 -*- """ runserver.py ~~~~~~~~~~~~~ This code launches the backend webserver of moves using flask with eventlet (for concurrency) and socket.io. """ from moves import app,socketio,r app.run(debug=True) socketio.run(app,host='0.0.0.0',port=PORT, debug=DEBUG)
import torch from models.MaskRCNN import get_model_instance_segmentation from dataset import PennFudanDataset, get_transform from references.engine import train_one_epoch, evaluate from references import utils # train on the GPU or the CPU, if a GPU is not available device = torch.device('cuda') if torch.cuda.is_avai...