content
stringlengths
5
1.05M
import unittest from pyaligner import * class TestMatrixMatchSeq ( unittest.TestCase ): def test_matrix_match_seq_global ( self ): scorer = Scorer( 5, -1, -3, 7 ) seqh = Sequence( "ACTG" ) seqv = Sequence( "ACAAA" ) matrix = DPMatrix( seqh, seqv, scorer ) match_seq = matr...
#!/usr/bin/env python # vim: set fileencoding=utf-8 : # Andre Anjos <andre.anjos@idiap.ch> # Mon 16 Apr 08:18:08 2012 CEST bob_packages = ['bob.core', 'bob.io.base', 'bob.sp', 'bob.math', 'bob.learn.activation', 'bob.learn.linear'] from setuptools import setup, find_packages, dist dist.Distribution(dict(setup_require...
import requests url = 'http://localhost:5000/predict_api' r = requests.post(url,json={'experience':2, 'test_score':9, 'interview_score':6}) print(r.json())
import time from ..modules import VideoCapture from .observable import observable class CaptureVideoPipe: def __init__(self, conf, **kwargs): super().__init__() self.video_capture = VideoCapture(conf, **kwargs).open() self.stop = False observable.register("stop", self, self.on_st...
# -*- coding: utf-8 -*- """ Created on Mon Nov 19 10:52:15 2018 @author: Vladislav Sláma """ import numpy as np def get_distance_matrixes(coor_i, coor_j): Nat_i = len(coor_i) Nat_j = len(coor_j) R = np.tile(coor_j,(Nat_i,1,1)) - np.swapaxes(np.tile(coor_i,(Nat_j,1,1)),0,1) # R[ii,jj] = c...
from .conftest import GoProCameraTest from goprocam import GoProCamera class SetZoomTest(GoProCameraTest): def test_set_zoom_min(self): with self.monkeypatch.context() as m: def verify_cmd(self, cmd): assert cmd == 'digital_zoom?range_pcnt=0' m.setattr(GoProCamera....
import re from typing import List, Optional from structures import FoundSegment class UnitFilter: def filter(self, line_number: int, line: Optional[str]) -> List[FoundSegment]: return [FoundSegment(line_number,0,line)] def CodeBlockFilterFactory(give_in_block: bool): class CodeBlockFilter: d...
# # Copyright (c) 2017, Massachusetts Institute of Technology 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 copyright notice, this # list o...
import argparse from args import init_parser, post_processing import numpy as np from envs import make_env # find the carla module import os import math import random import time import torch import shutil parser = argparse.ArgumentParser(description='SPC') init_parser(parser) # See `args.py` for default arguments...
# Copyright (c) 2021. # The copyright lies with Timo Hirsch-Hoffmann, the further use is only permitted with reference to source from enum import Enum class Tier(Enum): CHALLENGER = "CHALLENGER" GRANDMASTER = "GRANDMASTER" MASTER = "MASTER" DIAMOND = "DIAMOND" PLATINUM = "PLATINUM" GOLD = "...
from django.urls import path, include, re_path from django.conf import settings from django.contrib import admin from django.views.decorators.csrf import csrf_exempt from django.views.generic import TemplateView from graphapi.views import KeyedGraphQLView from graphapi.middleware import QueryProtectionMiddleware from b...
from .admin import admin from .frontend import frontend from .doc import doc, auto
""" Custom integration to integrate Vaillant vSMART with Home Assistant. For more details about this integration, please refer to https://github.com/MislavMandaric/home-assistant-vaillant-vsmart """ from __future__ import annotations from homeassistant.config_entries import ConfigEntry from homeassistant.const import...
import json from dataclasses import dataclass from typing import Any from typing import Optional import requests from requests import JSONDecodeError from requests import Response from requests.adapters import HTTPAdapter from telliot_core.datasource import DataSource from telliot_core.dtypes.datapoint import DataPoin...
def generate_nav_urls(host, query, results): """Generate links to previous and next pages for navigation.""" cur_page = results.current_page() if cur_page > 1: url_prev_page = 'http://' + host + '/search?q=' + query \ + '&page=' + str(cur_page - 1) else: url_prev_...
c.NotebookApp.password = u'sha1:2be34ae0f862:56b76d8a81c2db8f2e7038e1a3f6838a4f47131e'
import FWCore.ParameterSet.Config as cms JetNoBptxPSet = cms.PSet( hltPathsToCheck = cms.vstring( "HLT_UncorrectedJetE30_NoBPTX_v", # 2017 proposal "HLT_UncorrectedJetE30_NoBPTX3BX_v", "HLT_UncorrectedJetE60_NoBPTX3BX_v", "HLT_UncorrectedJetE70_NoBPTX3BX_v", ), recCaloJe...
#!/usr/bin/env python3 # Copyright 2021 Canonical # See LICENSE file for licensing details. # # Learn more at: https://juju.is/docs/sdk """Charm for the Ceph Dashboard.""" import json import logging import tempfile from ops.framework import StoredState from ops.main import main from ops.model import ActiveStatus, Bl...
#!/usr/bin/env python import sys sys.path.append("/opt/DIRT") import os import scipy import argparse from dirtIO import IO from Preprocessing import Preprocessing from fixImageOrientation import fix_orientation def options(): parser = argparse.ArgumentParser(description='Test a range of thresholds on an image us...
from django.http import JsonResponse from .models import Restaurant, Chat from django.shortcuts import render from django.http import HttpResponse from django.utils.safestring import mark_safe from about.models import User def Post(request): if request.method == 'POST': msg = request.POST.get('message', No...
#!/usr/bin/env python3 import numpy as np class KMeans(object): """ Performs the K-Means Clustering algorithm i.e. Lloyd's algorithm a.k.a. Voronoi iteration or relaxation Parameters -------------------------------------------------- k : int the number of clusters to form i.e. the num...
#!/usr/bin/env python3 import os import re from datetime import date from src import BoxBack, BoxLog destination_folder = "0B7nAS5KVLBl4VmlhRDRQRzlrMmM" string = "https://drive.google.com/drive/u/2/folders/0B7nAS5KVLBl4VmlhRDRQRzlrMmM" # string = "0B7nAS5KVLBl4VmlhRDRQRzlrMmM" # string = "fofasdf/0B7nAS5KVLBl4VmlhRD...
"""Defines utility methods for testing files and workspaces""" from __future__ import unicode_literals import datetime import os import django.contrib.gis.geos as geos import django.utils.timezone as timezone from storage.models import CountryData, ScaleFile, Workspace COUNTRY_NAME_COUNTER = 1 WORKSPACE_NAME_COUNTE...
#!/usr/bin/python import urllib2 import re import os import sys import commands import subprocess import shlex import string import getopt DELTTE_TEST_CASE = True # True: allCount all count except test cases Flase: allCount including test cases def search_opt(android_dir, set_file, out_dir): if len(android_dir)...
import numpy as np import unittest from chainercv.utils import assert_is_image from chainercv.utils import testing @testing.parameterize( { 'img': np.random.randint(0, 256, size=(3, 48, 64)), 'color': True, 'check_range': True, 'valid': True}, { 'img': np.random.randint(0, 256, size=(...
# Copyright (c) 2016-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. An additional grant # of patent rights can be found in the PATENTS file in the same directory. """Methods for introduci...
def select_products(products): products = input("Введите товар: ") result = [] for tovar in products: if tovar.get('name', ''): result.append(tovar) return result
# Generated by Django 3.1.6 on 2021-02-05 10:27 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("authentik_sources_ldap", "0009_auto_20210204_1834"), ] operations = [ migrations.AlterField( model_name="ldapsource", ...
#!/usr/bin/env python """ Run the 'cascade' docker container in interactive mode, starting the default app (cascade webserver) in the container. """ import sys import os import subprocess import argparse if __name__ == "__main__": # Process command line arguments parser = argparse.ArgumentParser() parser....
from authy.api import AuthyApiClient from flask import Flask, render_template, request, redirect import os import pdb import time app = Flask(__name__) regdata = {} transfer = {} authy_api_key = os.environ['AUTHY_API_KEY'] authy_api = AuthyApiClient(authy_api_key) @app.route('/') def register(): return render_tem...
#!/usr/bin/env python #coding:utf-8 #This script is aimed to grep logs by application(User should input a packageName and then we look up for the process ids then separate logs by process ids). import os import sys packageName=str(sys.argv[1]) def getDeviceId(): devices = [] command = "adb devices -l | sed '...
''' =============================================================================== -- Author: Hamid Doostmohammadi, Azadeh Nazemi -- Create date: 04/11/2020 -- Description: This codes is for SLIC segmentation and extractions of segments. -- Status: In progress ==============================...
from datetime import datetime, timedelta import pytest from bbapilib import BBClient, BBSession, BBAuth @pytest.fixture def client(): auth = BBAuth("", "", "") auth.token = "TOKEN", "VALIDO" client = BBClient(BBSession(auth)) return client @pytest.fixture def client_authenticated(): auth = BBAut...
#!/usr/bin/env python3 import os import importlib import shutil import sys from common import clone_repo_src, run_command, check_root_dir, create_dirs def setup_stp(): curr_dir = os.getcwd() deps = importlib.import_module("solver-deps") deps.setup_minisat() deps.setup_cms() the_repo = clone_rep...
# -*- coding: utf-8 -*- """ Created on Mon Apr 6 14:01:05 2015 @author: lshi Multiprocess version to calculate reflected signals from FWR2D/3D useful when have multiple frequencies and time steps to analyse """ # using IPython multiprocessing modules, need ipcluster to be started. import time from IPython.paralle...
#!/usr/bin/python import json import re import requests from fuzzywuzzy import fuzz from price_changes import get_stock_price_data GOOGLE_FINANCE_URL = "http://finance.google.com/finance/info?client=ig&q=NSE:" class MutualFundNavAnalysis: matched_stocks_data = {} def __init__(self): MutualFundNa...
# -*- coding: utf-8 -*- """Anima Pipeline Library Anima uses ``Stalker Configuration Framework``. To be able to make it work set the STALKER_CONFIG environment variable to a valid configuration folder (which has a config.py file inside, if there is no config.py file create one). Place the following variables in to t...
# pylint: disable=no-value-for-parameter from dagster_shell import create_shell_command_op from dagster import graph @graph def my_graph(): a = create_shell_command_op('echo "hello, world!"', name="a") a()
import streamlit as st import json import os import re import pandas as pd import numpy as np import argparse import requests import logging import yaml import glob import datetime import time from models import clustering import pyLDAvis import webbrowser import base64 import pytest cluster_amount = 8 additional_sto...
import confply.cpp_compiler as cpp_compiler fallbacks = ["cl", "clang++", "g++", "gcc", "clang"] tool_name = None for tool in fallbacks: if cpp_compiler.is_found(tool): tool_name = tool break def generate(): cpp_compiler.tool = tool_name return cpp_compiler.generate() def get_environ(...
import tkinter as tk from PIL import Image, ImageTk import pygame import time as delay from openpyxl import * from modules import janelaconfig import os from tkinter.messagebox import showwarning # Classe destinada a visualização da database. class MostraData(tk.Toplevel): # Constroi o objeto MostraData. d...
# Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
import json from django.shortcuts import render from django.utils.safestring import mark_safe def index(request): return render(request, 'basic_system/index.html', {}) def room(request, room_name): return render(request, 'basic_system/room.html', { 'room_name_json': mark_safe(json.dumps(room_name)) ...
""" See https://mathworld.wolfram.com/TalismanSquare.html An n x n array of the integers from 1 to n^2 such that the difference between any integer and its neighbor (horizontally, vertically, or diagonally, without wrapping around) is greater than or equal to some value k is called a (n,k)-talisman square. Examples ...
import time def fib_lin(x): a, b = 0, 1 for i in range(x+1): a, b = b, a + b return a x= int(input("Give the number of fibonnacci terms: ")) for x in range(1,x+1): start=time.time() print(x,":",fib_lin(x)) stop=time.time() print("total time taken to this program is {} sec".forma...
"""Jobs for the Lifecycle Management plugin.""" from datetime import datetime from nautobot.dcim.models import Device, InventoryItem from nautobot.extras.jobs import Job from nautobot_device_lifecycle_mgmt import choices from nautobot_device_lifecycle_mgmt.models import ( DeviceSoftwareValidationResult, Inven...
""" Report template model definitions """ # -*- coding: utf-8 -*- from __future__ import unicode_literals import os import sys import logging import datetime from django.urls import reverse from django.db import models from django.conf import settings from django.core.exceptions import ValidationError, FieldError ...
""" AMG solvers """ postpone_import = 1
from arcgis import GIS from arcgis.features import GeoAccessor, GeoSeriesAccessor import arcpy from arcpy import env from arcpy.sa import * import numpy as np import os import pandas as pd ##### arcpy.env.overwriteOutput = True arcpy.CheckOutExtension("Spatial") def select_feature_by_attributes_arcgis(input,Attri_NM...
from django.db import models class Notification(models.Model): title = models.CharField(max_length=255, null=True) description = models.CharField(max_length=100000, null=True) notification_type = models.CharField(max_length=255, null=True) date_time = models.DateTimeField(auto_now_add=True) is_de...
from django.views.decorators.csrf import csrf_exempt from graphene_django.views import GraphQLView # See https://github.com/PaulGilmartin/graph_wrap/issues/5 for csrf_exempt # rationale. @csrf_exempt def graphql_view(request): from graph_wrap.django_rest_framework import schema schema = schema() view = Gr...
# -*- coding: utf-8 -*- from django.test import TestCase, RequestFactory, Client from django_webtest import WebTest from app.tests.mixins import AuthRouteTestingWithKwargs from app.tests.mixins import Pep8ViewsTests from app.models import User, Schedule import app.views as views pto = views.pto_views class Password...
#!/usr/bin/env python """Web server for the Trendy Lights application. The overall architecture looks like: server.py script.js ______ ____________ _________ | | | | | | | EE | <-> | App Engine | <-> | Browser | |______| |____________| |___...
import simulation import matplotlib.pyplot as plt # ticks are in seconds tick = 1 sim_duration = 60 * 60 * 6 speed_kmh = 60 # Initialize all simulation classes incident_sunlight = 1000 initial_battery_charge = 0.9 lvs_power_loss = 0 basic_array = simulation.BasicArray(incident_sunlight) basic_array.set_produced_ener...
import myth.frontend import socket frontend = myth.frontend.Frontend(('10.1.1.6', 6543)) #sock = socket.socket() #sock.connect(('10.1.1.6', 6543)) #version = myth.protocol.ProtocolVersion(sock, 31) #version.send() #version.recv() #ann = myth.protocol.Announce(sock, 'chipotle') #ann.send() #ann.recv() #filetrans = ...
#!/usr/bin/env python import os import argparse import imp import cPickle as pkl import numpy as np import shutil import cv2 import datetime import glob import sys import json # TODO simplify this class class RobotEnvironment: def __init__(self, exp_path, robot_name, conf, resume=False, ngpu=1, gpu_id=0, is_bench...
"""Dicionário Escreva uma função que simula a função dict() do Python. """ def myDict(**keywords: dict) -> dict: return keywords print(myDict(a=10, b=20, c=30, d=40, e=50))
import numpy as np import cv2 import gc class Image(object): """The base-class for image input""" def __init__(self, image=None): if image is not None: self.image = image def imread(self, path): self.image = cv2.imread(path) def extract_convWin(self, x, y, offset, xOff=N...
# -*- coding: utf-8 -*- """The hashing analyzer implementation.""" from __future__ import unicode_literals from plaso.analyzers import interface from plaso.analyzers import logger from plaso.analyzers import manager from plaso.analyzers.hashers import manager as hashers_manager from plaso.containers import analyzer_r...
import oofcppc from ooflib.SWIG.common.IO import stopper from threading import * import sys import time from types import * import string class TextProgressBar: def __init__(self, type = "continuous", name_top = " "): if type == "continuous": self.progressbar = stopper.cProgressBar(1, nam...
import numpy as np def get_hits(adj_matrix, EPSILON = 0.001): """[summary] hubs & authorities calculation Arguments: adj_matrix {float[][]} -- [input Adjacent matrix lists like [[1, 0], [0, 1]] Keyword Arguments EPSILON {float} -- [factor of change comparision] (default: {0.001}) ...
from setuptools import setup, find_packages setup( name='luxai2021', version='0.1.0', author='Geoff McDonald', author_email='glmcdona@gmail.com', packages=find_packages(exclude=['tests*']), url='http://pypi.python.org/pypi/luxai2021/', license='MIT', description='Matching python environ...
"""Implementation of the Bingham Mixture Loss""" import torch from .maad import angular_loss_single_sample from .bingham_fixed_dispersion import BinghamFixedDispersionLoss from .bingham_loss import BinghamLoss from .gram_schmidt import gram_schmidt_batched from utils import vec_to_bingham_z_many class BinghamMixture...
from datetime import timedelta from mimetypes import guess_type from secrets import token_urlsafe from django.contrib.auth.hashers import ( check_password, make_password, ) from django.contrib.auth.models import AbstractUser from django.db import models from django.http import HttpResponse from django.shortcut...
# -*- coding: utf-8 -*- """Tests dict input objects for `tackle.providers.yubikey.hooks.yubikey` module.""" # import pytest # import os # from tackle.main import tackle # # # def test_provider_yubikey_hook_read(change_dir): # """Verify the hook call works successfully.""" # o = tackle('.', context_file='read.ya...
from __future__ import absolute_import try: import unittest2 as unittest except: import unittest import numpy as np from math3.objects.matrix3 import Matrix3 from math3.objects.matrix4 import Matrix4 from math3.objects.quaternion import Quaternion from math3.objects.vector3 import Vector3 from math3.objects.vec...
import json from io import StringIO from django.core.management.base import BaseCommand, CommandError from django.db import transaction import xmltodict import pandas as pd from datetime import datetime import xml.etree.ElementTree as ET from foundation.models import AppleHealthKitDataDB,AppleHealthKitUpload class C...
import json import time from datetime import datetime, timedelta from urllib import parse # prevent Error: Failed to import _strptime because the import lockis held by another thread. # see https://www.raspberrypi.org/forums/viewtopic.php?t=166912 import _strptime import xbmc _ON_SETTING_CHANGE_EVENTS = "onSettingCha...
import numpy as np import math from keras.initializers import RandomUniform from keras.models import model_from_json from keras.models import Sequential, Model from keras.layers import Dense, Flatten, Input, merge, Lambda, Activation from keras.optimizers import Adam import tensorflow as tf import keras.backend as K im...
import cv2 import numpy import time class CaptureManager: def __init__(self,capture, previewWindowManager = None, shouldMirrorPreview = False) -> None: self.previewWindowManager = previewWindowManager self.shouldMirrorPreview = shouldMirrorPreview self._capture = capture self._chan...
from typing import List class Solution: def reverseString(self, s: List[str]) -> None: """ Do not return anything, modify s in-place instead. """ l, r = 0, len(s) - 1 while l < r: s[l], s[r] = s[r], s[l] l += 1 r -= 1
# 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...
#!/usr/bin/python # Authors: # 2016: Jayamine Alupotha https://github.com/jaymine # 2020: Wolfgang Fahl https://github.com/WolfgangFahl import socket import json import os import struct import threading import time import uuid from enum import IntEnum from queue import Queue, Empty from subprocess import * from thread...
from django.conf.urls import url from slack_utils import views urlpatterns = [ url('events/$', views.EventsView.as_view(), name='slack-events-api'), url('commands/$', views.CommandView.as_view(), name='slack-commands'), ]
from gallery.db.dao import BaseDAO from gallery.db.parcel.builders import IndexGalleryParcelBuilder, PageGalleryParcelBuilder from gallery.models import BellImage, BellGallery from django.core.exceptions import ObjectDoesNotExist from gallery.exceptions import NonexistentGalleryError class RestfulIndexDAO(BaseDAO): ...
import re, sys def usage(): print("Usage:\n%s [input file] [output file]" % (sys.argv[0])) def getcard(card_snippet): cards = [] matcher = re.compile("\\\carta\{(.*?)\}", re.S | re.I) m = re.findall(matcher, card_snippet) for match in m: text = match.replace('\n', ' ').replace('\puntini', ...
import requests import json import sys sys.path.append("..") from utils.config import TOKEN from utils.config import API_URL class Api: def __init__(self, obj): self.endpoint = obj.get("endpoint") self.symbol = obj.get("symbol") self.sector = obj.get("sector") self.period = obj.get...
from __future__ import annotations import asyncio from typing import Any import asynctest.mock # type: ignore import pytest # type: ignore import pytest_mock._util # type: ignore pytest_mock._util._mock_module = asynctest.mock class EventLoopClockAdvancer: """ A helper object that when called will advan...
import myhdl from myhdl import Signal, intbv def blinky(clock, led, button): """A simple LED blink example. This is intended to be used with the Xula2+StickIt motherboard and an LED+button PMOD board. Arguments (ports): clock: 12MHz external clock led: the LED port/pin butto...
# Package provides a simple widget-based framework for interactive visualization of algorithms. # PyPi: https://pypi.org/project/interactive-visualization/ # Github: https://github.com/Malkovsky/interactive-visualization # pip install interactive-visualization
def title1(content): return "<h1 class='display-1'>{}</h1>".format(content) def title2(content): return "<h2 class='display-2'>{}</h2>".format(content) def title3(content): return "<h3 class='display-3'>{}</h3>".format(content) def title4(content): return "<h4 class='display-4'>{}...
import numpy as np import matplotlib.pyplot as plt from scipy.optimize import curve_fit class RandomWalk2D: def __init__(self): self.positions = [] self.steps = [] self.time = 0 def render(self, time, step_length=1): self.time = time self.positions = np.zeros(time + 1,...
import dynet as dy import dynet_modules as dm import numpy as np import random from utils import * from time import time from collections import defaultdict from modules.seq_encoder import SeqEncoder from modules.bag_encoder import BagEncoder from modules.tree_encoder import TreeEncoder class LinDecoder(Decoder): ...
# -*- coding: utf-8 -*- # Generated by Django 1.11.9 on 2018-01-09 17:11 from __future__ import unicode_literals from django.db import migrations subscription_choices = ['A', 'B', 'A+B', 'AdL', 'Student', 'Professor', 'Other'] def subtype_choice_to_foreignkey(apps, schema_editor): Subscribe = apps.get_model(...
#!/usr/bin/python3 import requests import sys from collections import defaultdict from datetime import datetime from tqdm import tqdm def main(): url = f'https://codeforces.com/api/user.ratedList?activeOnly=true' r = requests.get(url) users = r.json()['result'] print('handle,rating,country,city,solve...
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'settings_ui.ui' # # Created by: PyQt5 UI code generator 5.15.1 # # WARNING: Any manual changes made to this file will be lost when pyuic5 is # run again. Do not edit this file unless you know what you are doing. from PyQt5 import QtCore, ...
#!/usr/bin/env python # # glossaries.py # # Copyright © 2020 Dominic Davis-Foster <dominic@davis-foster.co.uk> # # 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, incl...
#!/usr/bin/env python import urllib2 import urllib import sys import main request = dict( token='xxxxx', team_id='T0001', channel_id='C2147483705', channel_name='test', timestamp='1355517523.000005', user_id='U2147483697', user_name='tester', text=' '.join(sys.argv[1:]), ) event = di...
from collections.abc import Callable import torch import hydra.utils as hyu import omegaconf.omegaconf import logging import typing log = logging.getLogger(__name__) __all__ = ["Collection"] class Collection(Callable): #TODO: inherit from UserList as well, need to update items to iteration def __init__(self, ...
# For a given list of integers and integer K, find the number of non-empty subsets S such that min(S) + max(S) <= K. # Example 1: # nums = [2, 4, 5, 7] # k = 8 # Output: 5 # Explanation: [2], [4], [2, 4], [2, 4, 5], [2, 5] # Example 2: # nums = [1, 4, 3, 2] # k = 8 # Output: 15 # Explanation: 16 (2^4) - 1 (empty set...
from upy2 import u, U, undarray from upy2.typesetting.scientific import ScientificTypesetter st = ScientificTypesetter(2, 2) st.default() uprov = U(2) uprov.default() print undarray(10, 2) print [10] +- u([2]) print 10 +- u(2)
# Copyright 2019-2020 the ProGraML authors. # # Contact Chris Cummins <chrisc.101@gmail.com>. # # 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...
import os import sys from bs4 import BeautifulSoup import pytest from mock import Mock from app import create_app # Don't import app.settings to avoid importing google.appengine.ext sys.modules['app.settings'] = Mock() sys.modules['app.gaesession'] = Mock() AUTH_USERNAME = 'user' AUTH_PASSWORD = 'pass' @pytest.y...
# -*- coding: utf-8 -*- """ transistor.tests.conftest ~~~~~~~~~~~~ This module defines pytest fixtures and other constants available to all tests. :copyright: Copyright (C) 2018 by BOM Quote Limited :license: The MIT License, see LICENSE for more details. ~~~~~~~~~~~~ """ import pytest from kombu import Connection fr...
import tkinter as tk from tkinter import Scrollbar, Listbox, Frame from datetime import datetime class Console: master = None mainContainer = None console = None def __init__(self, master): self.master = master self.mainContainer = Frame(self.master) self.mainContainer.pack(si...
from google.cloud import storage from google.cloud import speech from google.cloud.speech import enums from google.cloud.speech import types import os import time import inspect import praw from tqdm import tqdm import ConfigParser # Maybe add async upload? https://cloud.google.com/appengine/docs/standard/python/datas...
import KratosMultiphysics as Kratos import KratosMultiphysics.KratosUnittest as KratosUnittest import KratosMultiphysics.DEMApplication as DEM # This test consists in applying OMP_DEMSearch to assign, to each node in # a 'Base' model part, the corresponding neighbors from a 'Target' model part. # The results calculat...
#!/usr/bin/python3 import flask import requests as HTTP_REQUESTS import socket from pdb import set_trace import flask_fat Journal = self = flask_fat.Journal(__file__) """ ----------------------- ROUTES --------------------- """ @Journal.BP.route('/help', methods=['GET']) def register_external_api(): global Jour...
import cv2 import numpy as np import matplotlib.pyplot as plt import os, torch def readLabel(data, imsz): ## 좌표 값 및 크기 계산 후 return labels = [] dh, dw, _ = imsz for d in data: _, x, y, w, h = list(map(float, d.split(" "))) l = int((x - w / 2) * dw) r = int((x + w / 2) * dw) ...
#!/usr/bin/python3 import datetime import uuid import models class BaseModel: """The base class for all storage objects in this project""" def __init__(self, *args, **kwargs): """initialize class object""" if len(args) > 0: for k in args[0]: setattr(self, k, args[0]...