content
stringlengths
5
1.05M
#!/bin/python # -*- coding: utf-8 -*- import subprocess,json from Model.CFGForest import CFGForest from Model.CFG import CFG from Model.Block import Block from Model.Node import * from Common.Commons import * import os """ Purpose: Engine would be used to generate AST/CFG/DFG accordingly for the language. """ class PH...
from ontosearch.ext_search.ext_search import do_ext_multi_search
"""Autoreply serializers.""" from django.utils import timezone from django.utils.translation import ugettext as _ from rest_framework import serializers from . import models class ARMessageSerializer(serializers.ModelSerializer): """A serializer for ARmessage.""" class Meta: model = models.ARmessa...
import logging import queue import sys import os import time # will change these to specific imports once code is more final from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * import ruamel.yaml as yaml from mpfmonitor.core.bcp_client import BCPClient class DeviceNode(object): d...
import matplotlib import matplotlib.pyplot as plt def draw_ece(): ''' draw ece bar ''' erm = [0.0204, 0.0336, 0.1097] dropout = [0.0186, 0.0324, 0.1208] lsr = [0.1894, 0.1762, 0.1851] flood = [0.0109, 0.0085, 0.0709] mixup = [0.0447, 0.0549, 0.0883] adv = [0.0178, 0.0341, ...
def breakingRecords(scores): maxi = scores[0] maxi_num = 0 mini = scores[0] mini_num = 0 for s in scores[1:]: if s > maxi: maxi = s maxi_num += 1 elif s < mini: mini = s mini_num += 1 return [maxi_num, mini_num] print(breakingReco...
# -*- coding: utf-8 -*- from typing import Optional, Union from .dialect import Dialect from ..exceptions import ConfigError class Server: def __init__( self, identifier: str, hostname: str, dialect: Union[Dialect, str], port: Optional[int]=None, ): if not ho...
from serverless.aws.functions.generic import Function from serverless.service import YamlOrderedDict class S3Event(YamlOrderedDict): yaml_tag = "s3" def __init__(self, bucket, event, rules=None): super().__init__() self.bucket = bucket self.event = event if rules: ...
#!/usr/bin/env python import roslib import rospy import math import tf import geometry_msgs.msg from object_recognition_msgs.msg import RecognizedObjectArray import turtlesim.srv from geometry_msgs.msg import PoseStamped coke_can_pose = PoseStamped() coke_can_pose.header.seq = 1 coke_can_pose.header.frame_id = "kine...
# coding:utf-8 import sys import tornado.locale import tornado.ioloop from config import SITE_CFG from application import app PORT = SITE_CFG['PORT'] if __name__ == "__main__": tornado.locale.set_default_locale('zh_CN') # tornado.locale.load_gettext_translations('locale', 'yunsuan') if len(sys.argv) > 1:...
# Copyright 2017-2020 EPAM Systems, Inc. (https://www.epam.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 # # Unless required by appli...
# Copyright 2014 Open Source Robotics Foundation, 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...
import logging class Logging: LEVEL = logging.INFO logger: logging.Logger = None @staticmethod def set_log_level(level): Logging.LEVEL = level Logging.logger = logging.getLogger("python-qa") Logging.logger.setLevel(level) Logging.set_log_level(Logging.LEVEL)
# Copyright 2015 Scalyr 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, so...
#!/usr/bin/env python # # Copyright 2017 Nomos # # 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...
# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: spacex/api/device/wifi.proto """Generated protocol buffer code.""" from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection from...
# -*- coding: utf-8 -*- """ Django settings for ui project. Generated by 'django-admin startproject' using Django 1.9.6. For more information on this file, see https://docs.djangoproject.com/en/1.9/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.9/ref/setting...
""" This script defines a class which inherits from the TransformersWrapper class, and is specific to the Rostlab models (eg ProtBert and ProtBert-BFD) developed by hugging face - ProtBert: https://huggingface.co/Rostlab/prot_bert - ProtBert BFD: https://huggingface.co/Rostlab/prot_bert_bfd """ from typing import Dict,...
__author__ = 'adrianrosebrock' # import the necessary packages from batcountry import BatCountry
import sys sys.argv.extend(['-a', ' ']) import DigitalMicrograph as DM import numpy as np import tifffile import tkinter.filedialog as tkf def threed_roll_axis(img): stack = np.rollaxis(img, 2, 0) return stack def fourd_roll_axis(stack): stack = np.rollaxis(np.rollaxis(stack, 2, 0), 3, 1) return s...
from SGA.SGAUI import SGAUI import sys import numpy as np from PyQt5.QtWidgets import * from PyQt5 import QtWidgets from PyQt5.QtCore import * from SGA.Figure_Canvas import Figure_Canvas from SGA.SGA import * class LogicalUI(QMainWindow, SGAUI): def __init__(self, parent=None): super(LogicalUI, self).__ini...
from typing import Union import requests from model.open_interest import OpenInterestRequestParams, OpenInterestResponse from type import Failure API_BASE_URL = "https://testnet.binancefuture.com" class BinanceApiClient: def __init__(self, api_base_url: str = API_BASE_URL): self.api_base_url = api_base_...
# Copyright (c) 2016-present, Facebook, 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...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Test case for 2D grid canvas. """ import unittest import matplotlib.pyplot as plt from catplot.grid_components.grid_canvas import Grid2DCanvas, Grid3DCanvas from catplot.grid_components.nodes import Node2D class Grid2DCanvasTest(unittest.TestCase): def setUp(...
import argparse from collections import OrderedDict import re if __name__ == "__main__": """Script to clean Kindle book text file""" parser = argparse.ArgumentParser(description="Script to clean Kindle book text file") parser.add_argument("-i", "--input", help="Input path", type=str, required=True) pa...
import numpy as np import cv2 img = cv2.imread('F:/pythonSeries/ai_series/cascade_exe/dist/images.jpg') font = cv2.FONT_HERSHEY_SIMPLEX gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) cascade = cv2.CascadeClassifier('F:/pythonSeries/ai_series/cascade_classifier/haarcascade_smile.xml') objectt = cascade.detectMultiSca...
from __future__ import absolute_import from . import Absorption_Continuum from . import Absorption_Continuum_MTCKD from . import Absorption_Crosssections_HITRAN2016 from . import Absorption_Crosssections_UV from . import hitran_cia_fast from . import ClimateUtilities from . import Get_Fluxes from . import Get_Fluxes_p...
from gpiozero import MotionSensor PIR_PIN = 26 pir = MotionSensor(PIR_PIN) while True: if pir.motion_detected: print "motion detected" while pir.motion_detected: print "motion still detected" else: print "no motion!"
# ------------------------------------------------------------------------------------------------------------------------------------------------------------- from __future__ import print_function from lib import meeus import sys import math # ---------------------------------------------------------------------------...
import logging def setup_log(): logging.basicConfig(level = logging.DEBUG, format = '[%(asctime)s] <%(levelname)s> %(message)s', datefmt = '%0H:%0M:%0S') def log(msg, level = logging.DEBUG): logging.getLogger('__main__').log(level, msg)
# Copyright 2014 Google Inc. 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 ag...
class Solution: def largestSumAfterKNegations(self, A: List[int], k: int) -> int: A.sort() for i, v in enumerate(A): if v<0: A[i] *= -1 k-=1 else: break if k == 0: break k%=2 ...
import grpc import model_pb2 import model_pb2_grpc import sys def run(ip, port): channel = grpc.insecure_channel('%s:%s'%(ip, port)) stub = model_pb2_grpc.PredictServiceStub(channel) response = stub.Ping(model_pb2.hi(msg = 'Ping test')) print('Response {res}'.format(res=response.status)) if __name__...
import unittest from aoc2019.helpers.day01 import calculateFuel, calculateFuelWithAddedMass class Day1Test(unittest.TestCase): def test_calculateFuel_exampleCase1(self): self.assertEqual(calculateFuel(12), 2) def test_calculateFuel_exampleCase2(self): self.assertEqual(calculateFuel(14), 2) ...
__version__ = "0.3.4" __author__ = "Kaj Siebert <kaj@k-si.com>" from .api import GraphApi
try: from setuptools import setup from setuptools import Extension except: from distutils.core import setup from distutils.extension import Extension import numpy as np, os from findblas.distutils import build_ext_with_blas from sys import platform ## https://stackoverflow.com/questions/724664/python-distutils-how...
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright (C) 2013 PolyBeacon, 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...
""" Utilities for the py_search library. """ from __future__ import print_function from __future__ import unicode_literals from __future__ import absolute_import from __future__ import division from tabulate import tabulate from random import uniform from functools import wraps from functools import partial import tim...
from django.conf.urls import url, include from django.contrib import admin from rest_framework import routers, serializers, viewsets from django.views.generic import TemplateView # Wire up our API using automatic URL routing. # Additionally, we include login URLs for the browsable API. urlpatterns = [ url(r'^$', Tem...
"""Configuration for mTLS tests""" import pytest @pytest.fixture(scope="module", params=[ pytest.param(("valid_authority", 200), id="Matching authorities"), pytest.param(("invalid_authority", 502), id="Mismatched authorities") ]) def authority_and_code(request): """ Returns authority for httpb...
#!/usr/bin/env python3 import collections import operator import sys import os try: from urllib.request import urlopen except ImportError: from urllib2 import urlopen import xml.etree.ElementTree as et _topology_host = "topology.opensciencegrid.org" _topology_itb_host = "topology-itb.opensciencegrid.org...
# Copyright 2013 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. import json import logging import os import platform import shutil import socket import sys import tempfile import time import urllib2 import zipfile from te...
import pytest from django.db import IntegrityError from db.models.clusters import Cluster from db.models.config_options import ConfigOption from db.models.owner import Owner from factories.factory_users import UserFactory from tests.base.case import BaseTest @pytest.mark.configs_mark class TestConfigOptionModels(Ba...
class MemoryMixin(object): def short(self, addr): lo = self[addr] or 0 hi = self[addr + 1] or 0 return lo | hi << 8 def bignum(self, addr, size): result = 0 for i in range(0, size): octet = self[addr + i] or 0 result |= octet << (8 * i) return result class MemoryRegion(MemoryMi...
#!/usr/bin/env python """Small demo for visualization of algorithms Both approximations (by max error/ by number of sampling points) are applied to an exemplary trajectory implemented as random walk. """ import polyprox import numpy as np import rdp import time import matplotlib.pyplot as plt __author__ = "Kai Geiss...
import threading as th import socket import pygame as pg ''' Locals ''' from scripts.package import _unpack,_pack,BUFFER_SIZE from scripts.player import Player class Client: def __init__(self,addr): self._socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM) self._socket.connect(addr) #Desbloque...
file = open('file.txt', 'r') f = file.readlines() readingList = [] for line in f: readingList.append(line.strip()) print(readingList) file.close()
#!/usr/bin/python3 import gbi import argparse parser = argparse.ArgumentParser(description="") parser.add_argument("--repo", required=True) parser.add_argument("--main-branch", required=False, default="master") parser.add_argument("--info", required=False, default=False, action="store_true") parser.add...
from app import app # =========================================================================== # * `python run.py` # ? Module to launch app in development mode. # Deployment module executes app from app.py # =========================================================================== app.run(debug=Tru...
''' Solves numerically and analyses the stability of the solution for the double pendulum using scaled, dimensionless variables. ''' import numpy as np import matplotlib.pylab as plt class DoubleBob(object): ''' Represents the moving bobs in a double pendulum. Object B hangs from object A. ...
# Copyright (c) OpenMMLab. All rights reserved. import pytest import torch from mmocr.models.textrecog.encoders import (ABIVisionModel, BaseEncoder, NRTREncoder, SAREncoder, SatrnEncoder, TransformerEncoder) def test_sar_encode...
import os import uuid from urllib.parse import urljoin from django.conf import settings from django.core.files.storage import default_storage from django.http.response import JsonResponse from django.views.decorators.http import require_POST def image_uploader(image): ext = os.path.splitext(image.name)[1] if...
import os import pickle import numpy as np import matplotlib from matplotlib import pyplot as plt from utils_log import MetricSaver from gan_training.chainer_evaluate import evaluation import pickle import torchvision import torch from gan_training import utils from gan_training.checkpoints import CheckpointIO from g...
import regex as re from Crypto.Hash import keccak non_checksummed_patterns = (re.compile( "^(0x)?[0-9a-f]{40}$"), re.compile("^(0x)?[0-9A-F]{40}$")) sol_pattern = re.compile('[0-9a-zA-Z]{44}$') def validate_eth(addr: str) -> bool: """Determines whether a given address is a valid public Ethereum address ...
# Copyright 2022 Sony Semiconductors Israel, Inc. 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 b...
#!/usr/bin/env python3 import json def create_model(active_fragments: str, model_configuration: dict) -> dict: active_smiles = select_molecules(active_fragments) model = { "configuration": model_configuration, "data": { "active": active_smiles } } retu...
# Generated by Django 3.1.4 on 2021-01-04 19:00 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('inventory', '0001_initial'), ] operations = [ migrations.RemoveField( model_name='movement', name='currency', ), ...
# -*- coding: utf-8 -*- """ Post-passes on untyped IR emitted by the front-end bytecode translation. """ from __future__ import print_function, division, absolute_import import inspect from .translation import Translate from flypy.compiler.signature import compute_missing from flypy.rules import typematch from flypy...
'''Setup: loss functions used for training and evaluation.''' ## External modules. import numpy as np ## Internal modules. from mml.losses import Loss from mml.losses.absolute import Absolute from mml.losses.classification import Zero_One from mml.losses.logistic import Logistic from mml.losses.quadratic import Quadr...
''' This script contains a transpiler from markdown to json. ''' import re import json from markdown_tree_parser.parser import parse_string from libs.kafka.logging import LogMessage rules = [ ("#", ""), ("*", ""), ("\n\n", " "), (" Summary: ", ""), ("\nSummary: ", ""), ] rules_after = [ ("\...
from typing import Optional import pytest from fastapi import FastAPI, Header from fastapi.testclient import TestClient from meiga import BoolResult, Failure, isFailure, isSuccess from petisco import NotFound, assert_http from petisco.extra.fastapi import FastAPIController app = FastAPI(title="test-app") result_fro...
load("//tools/bzl:maven_jar.bzl", "maven_jar") def external_plugin_deps(): maven_jar( name = "commons_io", artifact = "commons-io:commons-io:1.4", sha1 = "a8762d07e76cfde2395257a5da47ba7c1dbd3dce", )
import os import sys sys.path.append(os.path.join(os.path.dirname(__file__), '..')) from lib.camera.camera import CameraInfoPacket, catesian2homogenous import ipdb import copy import json import numpy as np from camera_augmentation import h36m_cameras_intrinsic_params from camera_augmentation import init_camera_h36m...
"""Allows using assets that were bundled using pyinstaller.""" import os import sys def asset_path(relative_path: str) -> str: """Returns the path of an asset file.""" if hasattr(sys, "_MEIPASS"): # pylint: disable=E1101,W0212 return os.path.join(sys._MEIPASS, relative_path) # type: ignore ...
import requests, json, time, discord from discord_webhook import DiscordWebhook, DiscordEmbed false = False true = True availablility = True def initialize(): r = requests.get("https://amnotify.com/api/stock/available") data = json. loads(r.text) stockold = data["available"] retu...
# SAS MVA interface for sasoptpy import sasoptpy from sasoptpy.libs import np from sasoptpy.interface import Mediator from saspy import SASsession from sasoptpy.interface.util import wrap_long_lines, replace_long_names import warnings class SASMediator(Mediator): """ Handles the connection between sasoptpy a...
#import CV libraries import numpy import cv2 img=cv2.imread("/home/udayan/Downloads/Lena.png", 0) #read image, 0=read as grayscale, -1=read as color print "Shape of Image: " + str(img.shape) #shape of image print "No. of pixels in the Image: " + str(img.size) #size of image print "Datatype of I...
""" Copyright 2011-2012 Lars Kruse <devel@sumpfralle.de> This file is part of PyCAM. PyCAM is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. ...
#!/usr/bin/env python3 """Artistools - spectra related functions.""" from artistools.estimators.estimators import ( apply_filters, dictlabelreplacements, get_averaged_estimators, get_averageexcitation, get_averageionisation, get_ionrecombrates_fromfile, get_partiallycompletetimesteps, g...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # pylint: disable=C0103 ''' _ _ __ _ _|_ (_ (_| | (_| |_ computer-aided rhythm analysis toolbox Compute microtiming pattern of onsets within a beat ''' import sys import argparse import matplotlib.pyplot as plt from carat import annotations, microtiming, display d...
""" To create a new `Calendar` you need to subclass it, then instanciate it with an `Era`. A `Calendar` subclass has to have a name, a list of `Month` and an intercalation method to be valid. >>> class NewCal(Calendar): ... _name = "My New Calendar" ... _months = [Month(31, 32, "FirstMonth"), ... ...
# =============================================================================== # Copyright 2015 Jake Ross # # 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...
# -*- coding: utf-8 -*- # # Copyright: (c) 2017, F5 Networks Inc. # GNU General Public License v3.0 (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import (absolute_import, division, print_function) __metaclass__ = type import os import json import pytest import sys from nose.plugins.skip i...
import pandas as pd import stewicombo from electricitylci.model_config import inventories_of_interest #Send one on more process dictionary from a model def count_processes(process_dict): return len(process_dict) def count_facility_matches(): inventory_no_overlap = stewicombo.combineInventoriesforFacilitiesi...
from __future__ import print_function import h5py import numpy as np def rewrite_mask(sample): print("Processing sample", sample) # f = h5py.File('/groups/saalfeld/saalfeldlab/larissa/data/cremi-2017/sample_{' # '0:}_padded_20170424.aligned.hdf'.format(sample), 'r') # g = h5py.File('/grou...
import pickle profile_file=open("profile.pickle","wb") profile={"이름":"이지혁","나이":30, "취미":["게임, 영화 코딩"]} print(profile) pickle.dump(profile,profile_file) #profile에 있는 정보를 file에 저장 profile_file.close() profile_file=open("profile.pickle","rb") profile=pickle.load(profile_file) #file에 있는 정보를 profile에 불러오기 print(profile) p...
import wot.ot CELL_SET_HELP = 'gmt, gmx, or grp file of cell sets.' CELL_DAYS_HELP = 'File with headers "id" and "day" corresponding to cell id and days' TMAP_HELP = 'Directory of transport maps as produced by optimal transport' MATRIX_HELP = 'A matrix with cells on rows and features, such as genes or pathways on colu...
import pytest from seldump.dbobjects import Table, Sequence from seldump.exceptions import ConfigError from .sample_dbs import create_sample_db def test_void(dumper): """On empty input, result is empty.""" dumper.perform_dump() assert not dumper.writer.dumped def test_one_table(dumper): """You can...
# library importss from rest_framework import viewsets from django.http import HttpResponse, JsonResponse # property imports from .properties import ID # persistence layer imports from .models import TruckEntity from .serializer import BullySerializer, ConvoySerializer, AdminSerializer # error messages ERR_MSG_ACCES...
# Copyright 2020 Huawei Technologies Co., Ltd # # 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...
import abc import six import argparse from .. import core from .. import parallel_tasks @six.add_metaclass(abc.ABCMeta) class GenericTangosTool(object): parallel = True tool_name = None tool_description = None def parse_command_line(self, argv=None): parser = self._get_parser_obj() opt...
from rest_framework.test import APITestCase from legalaid.tests.views.test_base import CLAOperatorAuthBaseApiTestMixin from legalaid.tests.views.mixins.case_notes_history_api import CaseNotesHistoryAPIMixin class CaseNotesHistoryViewSetTestCase(CLAOperatorAuthBaseApiTestMixin, CaseNotesHistoryAPIMixin, APITestCase):...
from pydub import AudioSegment import os for sample in os.listdir("."): if sample.endswith(".wav") and not sample.startswith("ss"): silence = AudioSegment.silent(duration=32000) # or be explicit song = AudioSegment.from_wav(sample) + silence song.export("ss"+sample)
def assert_strings(strings, parser, tokanizer): for s, target in strings: try: parsed = parser.parse(tokanizer(s), s) assert parsed == target print("Success: ", parsed, "==", target) except AssertionError: print("Failed: ", parsed, "!=", target)
import os from typing import Optional from kg_phenio.transform_utils.transform import Transform from kgx.cli.cli_utils import transform # type: ignore ONTO_FILES = { 'MonarchTransform': 'monarch-merged.owl', } class MonarchTransform(Transform): """ MonarchTransform parses the merged monarch.owl into nodes...
import neural_network_lyapunov.train_barrier as mut import neural_network_lyapunov.barrier as barrier import neural_network_lyapunov.control_affine_system as control_affine_system import neural_network_lyapunov.control_barrier as control_barrier import neural_network_lyapunov.gurobi_torch_mip as gurobi_torch_mip import...
# Generated by Django 3.0.2 on 2020-01-28 20:58 from django.db import migrations, models import django.db.models.deletion import django.utils.timezone import uuid class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( nam...
import os, logging from db_api.common.constants import INSTANCE_FOLDER_PATH def get_logging_level(LEVEL): SWITCH = { 'CRITICAL': logging.CRITICAL, 'ERROR' : logging.ERROR, 'WARNING' : logging.WARNING, 'INFO' : logging.INFO, 'DEBUG' : logging.DEBUG, 'NOTSET' :...
from pyspark.sql import SparkSession import pyspark.sql.functions as F from pyspark.ml.feature import Bucketizer, QuantileDiscretizer from pyspark.sql import Window from pyspark.sql.types import * from pyspark.sql.functions import lower, col, lit import subprocess import argparse import os import unicodedata import sys...
import sqlalchemy as sql from app import db from lib.sqlalchemy import CRUDMixin from const.db import utf8mb4_name_length, mediumtext_length, now class KeyValueStore(CRUDMixin, db.Base): __tablename__ = "key_value_store" __table_args__ = {"mysql_engine": "InnoDB", "mysql_charset": "utf8mb4"} id = sql.Col...
import pyteal as pt def test_constructor(): block1 = pt.TealConditionalBlock([]) assert block1.ops == [] assert block1.trueBlock is None assert block1.falseBlock is None block2 = pt.TealConditionalBlock([pt.TealOp(None, pt.Op.int, 1)]) assert block2.ops == [pt.TealOp(None, pt.Op.int, 1)] ...
""" Dask Distributed Tools """ from typing import Any, Iterable, Optional, Union, Tuple from random import randint import toolz import queue from dask.distributed import Client import dask import threading import logging from botocore.credentials import ReadOnlyCredentials from botocore.exceptions import BotoCoreError...
from .camera import Camera, Frame from .mode import Mode from .obstacle import Obstacle from .path_segment import PathSegment from .point import Point from .point3d import Point3d from .pose import Pose, PoseStep from .robot import Robot, RobotParameters, RobotShape from .rotation import Rotation from .spline import Sp...
import json import pytest from django.urls import reverse from tests import testdata @pytest.mark.django_db def test_choose_list_choose_unauthorized(client): choose_url = reverse("list_chooser:choose") response = client.get(choose_url) assert response.status_code == 302 assert "login" in response["l...
class NumArray: def __init__(self, nums): """ :type nums: List[int] """ self.nums = nums self.sum_array = [] if len(nums) == 0: return self.sum_array.append(nums[0]) for i in range(1, len(nums)): self.sum_array.append(...
from rest_framework import permissions from rest_framework.permissions import SAFE_METHODS from portfolio.models import Portfolio class IsOwnerOrReadOnly(permissions.BasePermission): """ Custom permission to only allow owners of an object to edit it. """ def has_object_permission(self, request, view...
from flask import session, request from flask_socketio import emit, send, disconnect from app import socketio, games from app.play.bridgit import Bridgit @socketio.on('connect', namespace='/play') def on_connect(): user_id = request.sid level = session['level'] f_move = int(session['f_move']) color = i...
import os import sys from subprocess import check_call REPO_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) os.chdir(REPO_ROOT) os.putenv( "PATH", "{}:{}".format(os.path.join(REPO_ROOT, "bin"), os.getenv("PATH")) ) os.putenv("DVC_HOME", REPO_ROOT) os.putenv("DVC_TEST", "true") if len(sys.argv...
# -*- coding: utf-8 -*- # --------------------------------------------------------------------- # Linux.Alt.get_fqdn # --------------------------------------------------------------------- # Copyright (C) 2007-2018 The NOC Project # See LICENSE for details # -------------------------------------------------------------...
#!/usr/bin/python3 # author Diego Rodríguez Riera # from https://github.com/riera90/scripts # licenced under BSD 3-Clause License # date 18/02/19 # Intended to use on websites, what else would you use this for... import requests import re import json import threading import time import os ########################...