content
stringlengths
5
1.05M
import discord, random, asyncio, chalk from discord.ext import commands as client from Cogs.config import conf class Start(client.Cog):#does the on_ready stuff def __init__(self, bot): self.b = bot @client.Cog.listener() async def on_ready(self): print("\n") print(chalk.green(f"[S...
# # Copyright (c) 2019 Wind River Systems, Inc. # # SPDX-License-Identifier: Apache-2.0 # from oslo_log import log as logging from sysinv.common import exception from sysinv.common import utils from sysinv.helm import common from sysinv.helm import elastic LOG = logging.getLogger(__name__) class ElasticsearchHelm(e...
from trex_stl_lib.api import * # send G ARP from many clients # clients are "00:00:dd:dd:00:01+x", psrc="55.55.1.1+x" DG= self.dg class STLS1(object): def __init__ (self): self.num_clients =3000; # max is 16bit def create_stream (self): # Create base packet and pad it to size bas...
#!/usr/bin/env python # encoding: utf-8 """ @author: zhanghe @software: PyCharm @file: run_job_counter_clear.py @time: 2018-05-02 10:24 """ import time import schedule from apps.client_rk import counter_clear as job_counter_clear from tools import catch_keyboard_interrupt # 计数清零 schedule.every().day.at('00:00').do...
# coding: utf-8 """ SendinBlue API SendinBlue provide a RESTFul API that can be used with any languages. With this API, you will be able to : - Manage your campaigns and get the statistics - Manage your contacts - Send transactional Emails and SMS - and much more... You can download our wrappers at h...
import os import json import argparse import onepanel.core.api from onepanel.core.api.models.metric import Metric from onepanel.core.api.rest import ApiException from onepanel.core.api.models import Parameter def main(args): # Load Task A metrics with open(args.from_file) as f: metrics = json.load(f) ...
# -*- encoding:utf-8 -*- """ * Copyright (C) 2017 OwnThink. * * Name : findword.py - 新词发现 * Author : Yener <yener@ownthink.com> * Version : 0.01 * Description : 新词发现算法实现 special thanks to http://www.matrix67.com/blog/archives/5044 https://github.com/zoulala/New_words_find """ import re from ma...
import os from approvaltests.core.writer import Writer class StringWriter(Writer): contents = '' def __init__(self, contents, extension='.txt'): self.contents = contents or '' self.extension_with_dot = extension def write_received_file(self, received_file): self.create_directory...
# coding=utf-8 # Copyright 2020 The Google Research 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 applicab...
from dexy.doc import Doc from tests.utils import TEST_DATA_DIR from tests.utils import assert_output from tests.utils import runfilter from tests.utils import wrap from nose.exc import SkipTest import os import shutil def test_phantomjs_render_filter(): with runfilter("phrender", "<p>hello</p>") as doc: as...
""" 针对FairMOT模型中多个解耦头的实现 一个相对独立的部分 没有做过其它更改 """ import torch.nn as nn from ..utils.weights_init import fill_fc_weights class CommonHead(nn.Module): """ 公共头部分的实现 """ def __init__(self, heads, head_conv = 256): super(CommonHead, self).__init__() self.heads = heads s...
# Obtener el n-número de fibonacci # Usando ciclos def fib(n): x1 = 0 x2 = 1 contador = 3 xn = 0 i = 0 while contador <= n: print("iteracion: ", i) i = i + 1 xn = x1 + x2 x1 = x2 x2 = xn contador = contador + 1 if n == 1: xn...
# Generated by Django 2.0.5 on 2018-05-25 03:07 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('child', '0005_auto_20180524_2143'), ] operations = [ migrations.AlterField( model_name='medical...
from .hugo2lunr import main
from django.urls import include, path from drf_spectacular.views import (SpectacularAPIView, SpectacularRedocView, SpectacularSwaggerView) from talana.apps.api.users import urls as users_urls app_name = 'api' urlpatterns = [ path('users/', include(users_urls, namespace='users')...
""" Kelly Kapowski algorithm with computing cortical thickness """ __all__ = ['kelly_kapowski'] from ..core import ants_image as iio from .. import utils def kelly_kapowski(s, g, w, its=45, r=0.025, m=1.5, **kwargs): """ Compute cortical thickness using the DiReCT algorithm. Diffeomorphic registration-...
from setuptools import setup, find_packages setup( name='blockex-tradeapi', version='1.0.0rc1', description='Python client library for BlockEx Trade API', url='', author='D. Petrov, BlockEx', author_email='developers@blockex.com', classifiers=[ 'Development Status :: 4 - Beta', ...
from django import template from django.utils.safestring import mark_safe from blog.models import Category, Comment, Article, Tags # 这里的register不能随便修改 register = template.Library() @register.simple_tag def get_category_list(): # 可以定义任意名称函 return Category.objects.all() @register.simple_tag def get...
import csv with open("Datasets/favorite_colors.csv", "r") as f: data = csv.DictReader(f) table = {} for student in data: grade = student["grade"] color = student["favorite_color"] if grade not in table: table[grade] = {} if color not in table[grade]: t...
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union from ... import _utilities, _tables from...
#!/usr/bin/env python # -*- coding: utf8 -*- import asyncore import logging logging.basicConfig(level=logging.DEBUG, format='[*] %(name)s - %(funcName)16s - %(message)s') class EchoHandler(asyncore.dispatcher_with_send): def __init__(self, _sock=None, _map=None): self.logger = loggi...
import math def euclidean_distance(A, B): """ >>> A = (1, 0) >>> B = (0, 1) >>> euclidean_distance(A, B) 1.4142135623730951 >>> euclidean_distance((0,0), (1,0)) 1.0 >>> euclidean_distance((0,0), (1,1)) 1.4142135623730951 >>> euclidean_distance((0,1), (1,1)) 1.0 >>> ...
""" Functions used for Unit Testing our web application """ from django.test import SimpleTestCase, TestCase, Client from django.template.loader import render_to_string from app.models import CafeTable, CoffeeUser, Message, Report, Task client = Client() class LogInTests(TestCase): """ Unit tests for login page...
name = "yalesmartalarmclient"
### NLP TOOLBOX LIBRARY ### # Created by Dmitri Paley # ~First public version~ # This library was created to make certain deep-learning NLP uses easily accessible and usable by anyone # The library is made to be easily imported into your Python code and for complex operations to be simply called via a few simple comman...
''' Crie uma tupla preenchida com os 20 primeiros colocados da Tabela do Campeonato Brasileiro de Futebol, na ordem de colocação. Depois mostre: A) Apenas os 5 primeiros colocados. B) Os últimos 4 colocados da tabela. C) Uma lista com os times em ordem alfabética. D) Em que posição na tabela está o time da Chapecoense....
# ============================================================================= # Import OHLCV data and perform basic visualizations # Author : Mayank Rasu # Please report bug/issues in the Q&A section # ============================================================================= # Import necesary libraries import p...
from django.contrib.sitemaps import Sitemap from .models import NursingHome def update_sitemap(sitemap_dict): sitemap_dict.update({ 'nursinghomes-nursinghome': NursingHomeSitemap, }) return sitemap_dict class NursingHomeSitemap(Sitemap): priority = 0.25 changefreq = 'yearly' def it...
#!/usr/bin/env python3 """ Copyright © 2020 Borys Olifirov Generating PSF estimation by two models, Richards-Wolf's (PSF library) and Gibson-Lanni (flowdec library, module gila.py) """ import sys import logging import numpy as np import psf import gila def psfRiWo(setting, ems=False): """ Calculate Richards-Wol...
#!/usr/bin/env python __author__ = 'Kurt Schwehr' __version__ = '$Revision: 4799 $'.split()[1] __revision__ = __version__ # For pylint __date__ = '$Date: 2006-09-25 11:09:02 -0400 (Mon, 25 Sep 2006) $'.split()[1] __copyright__ = '2008' __license__ = 'Apache 2.0' __doc__ =''' Output python code for BBM encode a...
#8.1 def count_words(input_str): return len(input_str.split()) print(count_words('This is a string')) #8.2 demo_str = 'Hello world' print(count_words(demo_str)) #8.3 def find_min(num_list): min_item = num_list[0] for num in num_list: if min_item >= num: min_item = num return(min_it...
import ast import inspect import random import sys import traceback import imp ### from robotexception import * from settings import settings import rg def init_settings(map_file): global settings map_data = ast.literal_eval(open(map_file).read()) settings.spawn_coords = map_data['spawn'] settings.obst...
from itertools import cycle, islice from functools import partial from sklearn.preprocessing import StandardScaler from sklearn import datasets import torch import matplotlib.pyplot as plt from matplotlib.patches import Ellipse import numpy as np from hmmlearn.hmm import GaussianHMM from torchmm.hmm import HiddenMar...
from decimal import Decimal as D, ROUND_UP from django.core import exceptions from django.db import models from django.utils.translation import gettext_lazy as _ from oscar.apps.offer import utils from oscar.apps.offer.conditions import ( CountCondition, CoverageCondition, ValueCondition, ) from oscar.core....
import matplotlib.pyplot as plt import numpy as np import pandas as pd # rpy2 import rpy2.robjects as ro import seaborn as sns import textwrap import traceback from pathlib import Path from roses.effect_size import vargha_delaney # roses from roses.statistical_test.kruskal_wallis import kruskal_wallis from ...
# -*- coding: utf-8 -*- execfile("initcctbx.py") # Don't use the installed version import os, sys sys.path.insert(1, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from spectrocrunch.materials.compoundfromformula import compoundfromformula from spectrocrunch.materials.mixture import mixture from spe...
import os import sys from newspaper import Article # import common package in parent directory sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'common')) sys.path.append(os.path.join(os.path.dirname(__file__), 'scrapers')) import cnn_news_scraper from cloudAMQP_client import CloudAMQPClient DEDUPE_NEW...
import FWCore.ParameterSet.Config as cms process = cms.PSet() process.fwliteInput = cms.PSet( fileNames = cms.vstring('file:patTuple.root'), ## mandatory maxEvents = cms.int32(100), ## optional outputEvery = cms.uint32(10), ## optional ) proce...
import numpy as np import pandas as pd import matplotlib.pyplot as plt import FinanceDataReader as fdr from pykrx import stock import datetime import requests # from datetime import timedelta # 마이크로초 전, 마이크로초 후 를 구하고 싶다면 timedelta from dateutil.relativedelta import relativedelta # 몇달 전, 몇달 후, 몇년 전, 몇년 후 를 구하고 싶다면 relat...
""" See extensive documentation at https://www.tensorflow.org/get_started/mnist/beginners """ # Directives needed by tensorFlow from __future__ import absolute_import from __future__ import division from __future__ import print_function # Some misc. libraries that are useful import keras.backend as K from keras.mode...
# 로또의 최고 순위와 최저 순위 def solution(lottos, win_nums): answer = [] # 0개 1개 ... 6개 동일할 때 등수 rank = [6,6,5,4,3,2,1] # 당첨번호 카운터 count_lottos = {} count_win = {} count = 0 # 0이 없는 경우 대비 count_lottos[0] = 0 # 당첨번호 카운트 for num in win_nums: count_lottos[num] = 0 ...
from aocd import data from aoc.utils import rows import re from functools import partial rules = {} for row in rows(data): if ":" in row: id_, rule = re.match(r"(\d*): (.*)", row).groups() rules[int(id_)] = rule messages = [row for row in rows(data) if ":" not in row and row != ""] max_recursion_...
# Config import json import pathlib # Read config.json try: path_cfg = pathlib.Path( pathlib.Path.cwd()).parents[1].joinpath("config.json") with open(path_cfg, "r") as _file: settings = json.load(_file) except: path_cfg = pathlib.Path( pathlib.Path.cwd()).parents[2].joinpath("config...
import smtplib import logging from functools import wraps from email.header import Header from email.mime.text import MIMEText class SendEmailRetryTimeout(Exception): pass def error_retry(func): @wraps(func) def warps_func(*args, **kwargs): for i in range(3): try: rlt...
import inspect import json import os from ctypes.util import find_library from ctypes import * from functools import wraps from queue import Queue from threading import Thread from bot.custom import errors from . import td_api threads: list = list() def run_async(func): @wraps(func) def async_func(*ar, **k...
# Databricks notebook source # MAGIC # MAGIC %md # MAGIC # Class-Utility-Methods-Test # MAGIC The purpose of this notebook is to faciliate testing of courseware-specific utility methos. # COMMAND ---------- spark.conf.set("com.databricks.training.module-name", "common-notebooks") # COMMAND ---------- # MAGIC %md #...
from selenium import webdriver import time # driver = webdriver.Chrome(executable_path="./chromedriver.exe")#传入路径有两种方式 driver = webdriver.Chrome()#打开浏览器,把chrome放入与python同级目录,括号内不需要添加执行路径。 def openBaiDu(url, selector, keyword,pic): driver.get(url) if selector == 'kw': driver.find_element_by_id(selector)...
# File: tala_connector.py # # Copyright (c) 2018-2021 Splunk 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 app...
import angr BEFORE_STRINGS_NOT_EQUAL_ADDR = 0x8048B2C FIND_ADDR = 0x8048B43 AVOID_ADDR = 0x8048B3 # Load the binary proj = angr.Project('bomb', load_options={'auto_load_libs':False}) # Start right before the data comes in: state = proj.factory.blank_state(addr=BEFORE_STRINGS_NOT_EQUAL_ADDR) # Approach 1 -...
import pygame,sys import random import math from pygame.locals import * from pygame.sprite import Group import gF import Bullet import Slave import global_var import Effect import Item def polyByLength(bullets,type,length,sideNum,standardSpeed,standardAngle,pos,color='white',doCode=False,*args): halfAngle=360/side...
from FSMSIM.expr.expr import Expr class ConcatExpr(Expr): def __init__(self, l: Expr, r: Expr) -> None: self.l = l self.r = r def evaluate(self) -> str: return self.l.evaluate() + self.r.evaluate() def __len__(self) -> int: return len(self.l) + len(self.r)
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import pulumi import pulumi.runtime class GetManagedZoneResult(object): """ A collection of values returned by getManagedZone....
def ping() -> str: return "pong"
import os import sys import logging from pathlib import Path import importlib import boto3 from botocore.exceptions import ClientError import timone from timone.errors import StorageException class StorageDriver(object): def __init__(self): super() def object_exists(self, org, repo, oid): r...
# Random Forest Classifier import sys import numpy as np import pickle from sklearn import model_selection from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import accuracy_score, confusion_matrix from MNIST_Dataset_Loader.mnist_loader import MNIST import matplotlib.pyplot as plt from ...
# https://docs.aws.amazon.com/rekognition/latest/dg/API_IndexFaces.html import boto3 #BUCKET = "amazon-rekognition" BUCKET = "smart-door-image-store" KEY = "ted_pic.jpg" # Either key in S3 or however img frame gets passed from KVS IMAGE_ID = KEY COLLECTION = "faces" REGION = "us-east-1" # Collection is already cr...
#!/usr/bin/env python # coding: utf-8 import os import pathlib from io import StringIO from unittest import TestCase from sampan.toto import get_samples class TestToto(TestCase): TEST_CSV_FILE = os.path.join(str(pathlib.Path(__file__).parent), 'resources', 'test.csv') def test_get_samples(self): get...
import _lib import re import time def StartNodeInteractive(datadir, address, port,comment = ""): _lib.StartTest("Start node (debug) "+comment) res = _lib.ExecuteHangNode(['startintnode','-datadir',datadir,'-port',port,'-minter',address],datadir) _lib.FatalAssertSubstr(res,"Process started","No process star...
from chatbot.models import Survey def test_database(test_session): """Tests that the mock database was set up correctly""" # execute surveys = test_session.query(Survey).all() # validation assert len(surveys) == 2 for survey in surveys: assert survey.name in ["survey1", "survey2"] ...
v = [9, 8, 7, 12, 0, 13, 21] p = [] i = [] for x in v: if x % 2 == 0: p.append(x) else: i.append(x) print(f'Números pares: {p}') print(f'Números ímpares: {i}')
import numpy as np import tensorflow as tf from gtrain import FCNet, gtrain from gtrain.data import AllData np.random.seed(555) tf.set_random_seed(555) def generate_test_data(num_of_train_samples=1000, num_of_validation_samples=100): data_tr = np.random.rand(num_of_train_samples, 2) data_val = np.random.ran...
# create a class and __init__ class Book(): pass book = Book() print(book) # we get <__main__.Book object at 0x7fe3b9636a60> # When we say Book() we are instantiating a new object # This object iws assigned to the book variable # Printing it gives us the type and memory location # second method: print(type(boo...
from bs4 import BeautifulSoup import sys from prep.helpers import HttpHelpers class iJobs: def __init__(self, url): self.url = url self.helpers = HttpHelpers() def get(self): page = self.helpers.download_page(self.url) if page is None: sys.exit('Error downloading ...
from rest_framework import status from rest_framework.response import Response from rest_framework.generics import GenericAPIView from ..permissions import IsAuthenticated from ..utils import readbuffer, decrypt_with_db_secret from ..app_settings import ( ReadHistorySerializer ) from ..authentication import Toke...
#单一路径图片文件夹生成训练文件 # import numpy as np import os import random from sklearn.model_selection import train_test_split from matplotlib import pyplot as plt import pickle import cv2 train_X = [] train_y = [] # set folder path ''' 这样做的好处是不需要手动将文件夹分为train、val,符合实际工程 ''' folder_path1 = '/home/yao/data/hymenoptera_data/ants...
import pandas as pd from faker.factory import Factory from stop_watch import stop_watch # 実行時間測定 # import json # To create a json file from random import randint # For id Faker = Factory.create fake = Faker() fake.seed(20000) # 設定することで結果が固定される。 fake = Faker("ja_JP") @stop_watch def make_data(use_columns, row_co...
from .light_frontend import LightFrontend from .full_frontend import FullFrontend from .hybrid_frontend import HybridFrontend from .composite_frontend import CompositeFrontend from .replacement_frontend import ReplacementFrontend
from __future__ import print_function import os import argparse import torch import torch.nn as nn import torch.nn.functional as F import torchvision import torch.optim as optim from torchvision import datasets, transforms from models.wideresnet import * from models.resnet import * from adv import adv_loss_new parser...
# day 5 Numpy import numpy as np def introduction(): print('Numpy Version', np.__version__) def array_operation(): np.random.seed(0) # seed for reproducibility x1 = np.random.randint(10, size=6) # One-dimensional array x2 = np.random.randint(10, size=(3, 4)) # Two-dimensional array x3 = ...
# -*- coding: utf-8 -*- """ @date: 2021/2/23 下午8:22 @file: fashionmnist.py @author: zj @description: """ from torch.utils.data import Dataset import torchvision.datasets as datasets from zcls.data.datasets.util import default_converter # from zcls.data.datasets.evaluator.general_evaluator import GeneralEvaluator f...
from bsm.loader import load_common class Base(object): def __init__(self, config, env): self._config = config self._env = env class OperationError(Exception): pass class Operation(object): def __init__(self, config, env): self.__config = config self.__env = env def...
import sys import torch import torch.nn.functional as F # import utils class Net(torch.nn.Module): def __init__(self,inputsize,taskcla, unitN = 400, split = False, notMNIST = False): super(Net,self).__init__() ncha,size,_=inputsize self.notMNIST = notMNIST if notMNIST: ...
import numpy as np import pandas as pd filename = {"data1": "GSE71858.npy", # "data2": "GSE60361.npy", # "data3": "GSE71585.npy", "data4": "GSE62270.npy", # "data5": "GSE48968.npy", # "data6": "GSE52529.npy", # "data7": "GSE77564.npy", ...
import matplotlib.pyplot as plt import tensorflow as tf import numpy as np import functools def new_weights(shape): return tf.Variable(tf.truncated_normal(shape, stddev=0.05)) def new_biases(length): return tf.Variable(tf.constant(0.05, shape=[length])) def new_conv_layer(input, num_input_channels, filter...
from time import ctime from torbjorn.version import VERSION def run(): cur_time = ctime() text = f""" # Torbjorn Version {VERSION} ({cur_time} +0800) """ print(text)
def dijkstra(vertices, arestas, inicial, final): visitados = set() parente = dict() nao_visitados = set({inicial}) distancias = {inicial:0} while len(nao_visitados) > 0: atual = min([(distancias[no],no) for no in nao_visitados])[1] if atual == final: # já achou o menor caminho até...
# Copyright (c) Xavier Figueroa # 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, sof...
# -*- coding: utf-8 -*- import sys import os import datetime import time import codecs import ctypes import array WM_CHAR = 0x0102 def enum_child_windows_proc(handle, list): list.append(handle) return 1 qLogNow=datetime.datetime.now() qLogFlie = 'temp/_log/' + qLogNow.strftime('%Y%m%d-%H%M%S') + '_' + ...
code = '''UDRLRRRUULUUDULRULUDRDRURLLDUUDURLUUUDRRRLUUDRUUDDDRRRLRURLLLDDDRDDRUDDULUULDDUDRUUUDLRLLRLDUDUUUUDLDULLLDRLRLRULDDDDDLULURUDURDDLLRDLUDRRULDURDDLUDLLRRUDRUDDDLLURULRDDDRDRRLLUUDDLLLLRLRUULRDRURRRLLLLDULDDLRRRRUDRDULLLDDRRRDLRLRRRLDRULDUDDLDLUULRDDULRDRURRURLDULRUUDUUURDRLDDDURLDURLDUDURRLLLLRDDLDRUURURRRRDRR...
import ovl target_filters = [ovl.percent_area_filter(min_area=0.005), ovl.circle_filter(min_area_ratio=0.7), ovl.area_sort()] threshold = YELLOW_HSV = ovl.Color([20, 100, 100], [55, 255, 255]) yellow_circle = ovl.Vision(threshold=threshold, target_filter...
# C1C Matt Grimm # Nov 15 # USAFA import threading from threading import Thread import RPi.GPIO as GPIO import spidev import time # This is my attempt at trying to analyze multiple signals at once on the same # Raspberry Pi Board. It's a low resource "logic analyzer", or I'd like to think so. def xmit(): for x in...
#!/usr/bin/env python # coding: utf-8 # Sets up the source description (both single force and moment) from results of conduit flow model # In[2]: import numpy as np import gc # In[ ]: def time_height(time, dt, height, cushion=4000): ''' takes the time and height arrays from conduit flow simulation and ...
import unittest from multiplicable_numbers import displays_detected_numbers class TestDisplaysDetectedNumbers(unittest.TestCase): def setUp(self): self.one_to_a_hundred_with_three_and_five_multiplicables = [ '1', '2', 'Three', '4', 'Five', 'Three', '7', '8', 'Three', 'Five', '11', 'Three', '1...
"""Reflexec config validator module. """ import logging import shlex from distutils.util import strtobool log = logging.getLogger("reflexec") def validate_config_value(key, cfg): """Validate config value.""" if key not in cfg: return validator_fn = globals()[f"validate_{key}"] value = cfg[ke...
# Generated by Django 2.2.2 on 2019-06-13 18:22 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('library', '0002_auto_20190613_1747'), ] operations = [ migrations.RemoveField( model_name='author', name='slug', ...
# encoding: utf-8 """Utilities for working with data structures like lists, dicts and tuples. """ #----------------------------------------------------------------------------- # Copyright (C) 2008-2011 The yap_ipython Development Team # # Distributed under the terms of the BSD License. The full license is in # t...
import re from composite import composite_function from typing import * from error import error A = NewType('A', int) class Token: def __init__(self, type_: str, text_: str): self.type = type_ self.text = text_ def __repr__(self): return "[" + self.type + ", " + self.text + "]" # genT...
import sys from sessions import get_session account_number = sys.argv[1] stage = sys.argv[2] function_name = sys.argv[3] version = sys.argv[4] function_arn = f'arn:aws:lambda:eu-west-2:{account_number}:function:{function_name}' boto_session = get_session(account_number, "TDRJenkinsLambdaRole" + stage.capitalize()) c...
class DriverArgument: def __init__(self) -> None: self.action: str = None self.pl_project: dict = None self.pl_projects: list = None self.pl_field: str = None self.o_lim: bool = None self.o_quit: bool = None def get_action(self) -> str: """ Returns the action this DriverArgument h...
#! /usr/bin/env python from b3p import geometry_section from b3p import geometry_blade_shape from b3p import geometry_web import pickle def build_mesh( pckfile, radii, web_inputs, web_intersections, prefix, n_web_points=10, n_ch_points=120, outfile="out.vtp", added_datums={}, ...
#! /usr/bin/python2.7 # -*- coding: utf-8 -*- import pytest @pytest.fixture def hannanum_instance(): from konlpy import init_jvm from konlpy.tag import Hannanum init_jvm() h = Hannanum() return h @pytest.fixture def string(): return u"꽃가마 타고 강남 가자!" def test_hannanum_analyze(hannanum_insta...
''' callcontract.py - デプロイしたコントラクトを呼び出す ''' import os from web3 import Web3 from web3.contract import Contract KOVAN_URL = os.getenv('KOVAN_URL') address_file = 'HelloWorld.address' abi_file = 'HelloWorld.abi' w3 = Web3(Web3.HTTPProvider(KOVAN_URL)) print('w3.isConnected:', w3.isConnected()) ''' コントラクトアドレスの読み出し ''...
import os import copy import numpy as np import pandas as pd import torch from sklearn.metrics import f1_score from utils import load_model_dict from models import init_model_dict from train_test import prepare_trte_data, gen_trte_adj_mat, test_epoch cuda = True if torch.cuda.is_available() else False def cal_feat_i...
import os from collections import OrderedDict from jogger.utils.files import walk from .base import Task, TaskError try: import flake8 # noqa HAS_FLAKE8 = True except ImportError: HAS_FLAKE8 = False try: import isort # noqa HAS_ISORT = True except ImportError: HAS_ISORT = False try: i...
import os, re, shutil, requests, threading from httpsreqfast.encoder import Encoder from httpsreqfast.browser import Browser from httpsreqfast.receiver import Receiver from httpsreqfast.config import * from httpsreqfast.utils.request import request_post class Getter: def fast_get( self, ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 01/24/22 10:38 PM # @Author : Fabrice Harel-Canada # @File : minist.py import os from typing import Optional import numpy as np import pandas as pd import matplotlib.pyplot as plt import torch from torch.nn import functional as F from torch import nn fro...
from selfdrive.car import dbc_dict # Steer torque limits class SteerLimitParams: #controls running @ 100hz STEER_MAX = 9 STEER_DELTA_UP = 10 / 100 # 10Nm/s STEER_DELTA_DOWN = 1000 / 100 # 10Nm/sample - no limit STEER_ERROR_MAX = 999 # max delta between torque cmd and torque motor class SteerActu...
#!/usr/bin/env python import sys import imp import os import subprocess from datetime import datetime import csv import tempfile def main(): if len(sys.argv) != 2: print 'Usage: ./broeval.py <configfile>' return (cfgpath, cfgname) = os.path.split(sys.argv[1]) (cfgname, cfgext) = os.path.sp...
def str_format(s, *args, **kwargs): """Return a formatted version of S, using substitutions from args and kwargs. (Roughly matches the functionality of str.format but ensures compatibility with Python 2.5) """ args = list(args) x = 0 while x < len(s): # Skip non-start token characters...
# coding: utf-8 import ast from datetime import timedelta from django.core.exceptions import EmptyResultSet, FieldDoesNotExist from django.db import ProgrammingError from django.db.models import functions from django.db.models.query import F, Prefetch, QuerySet from django.utils.timezone import now from rest_framework...