content
stringlengths
5
1.05M
#!/usr/bin/env python3 # PYTHONPATH is set properly when loading a workspace. # This package needs to be installed first. import pyaudio import numpy import threading from datetime import datetime, timedelta import queue # ROS import rospy from opentera_webrtc_ros_msgs.msg import PeerAudio p = pyaudio.PyAudio() outp...
import os import tkinter from tkinter import * class SimpleDialog: def __init__(self, master, text='', buttons=[], default=None, cancel=None, title=None, class_=None): if class_: self.root = Toplevel(master, class_=class_) else: self.root =...
#!/usr/bin/env python3 import xlrd import csv import requests from bs4 import BeautifulSoup import os import subprocess as subp import face_recognition R = '\033[31m' # red G = '\033[32m' # green C = '\033[36m' # cyan W = '\033[0m' # white session = requests.session() session.proxies = {} session.proxies['http'] = '...
from .naive_bayes import NaiveBayes
# vim: set tabstop=4 expandtab : ############################################################################### # Copyright (c) 2019-2021 ams AG # # 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 o...
"""deserialization tools""" import typing as t from datetime import datetime from functools import partial from toolz import flip from valuable import load from . import types registry = load.PrimitiveRegistry({ datetime: partial(flip(datetime.strptime), '%Y-%m-%dT%H:%M:%SZ'), **{ c: c for c in [ ...
import numpy as np import unittest from pythran.typing import * from pythran.tests import TestEnv try: np.float128 has_float128 = True except AttributeError: has_float128 = False class TestConversion(TestEnv): def test_list_of_uint16(self): self.run_test('def list_of_uint16(l): return l', [n...
from pathlib import Path from setuptools import setup, find_packages package_dir = 'topic_analysis' root = Path(__file__).parent.resolve() # Read in package meta from about.py about_path = root / package_dir / 'about.py' with about_path.open('r', encoding='utf8') as f: about = {} exec(f.read(), about) # G...
import pandas as pd import numpy as np import tensorflow as tf from sklearn.model_selection import train_test_split from sklearn.utils import shuffle import tensorflow.keras.layers as L from tensorflow.keras import Model from sklearn.metrics import f1_score from tensorflow.keras import callbacks import pickle from tqdm...
# -*- coding: utf-8 -*- """ Tencent is pleased to support the open source community by making BK-BASE 蓝鲸基础平台 available. Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved. BK-BASE 蓝鲸基础平台 is licensed under the MIT License. License for BK-BASE 蓝鲸基础平台: ------------------------------------------...
""" Decorator utilities """ import functools from requests.exceptions import ConnectionError as RequestsConnectionError try: from functools import cached_property except ImportError: # pragma: no cover # Python 3.7 from cached_property import cached_property def retry_on_connection_error(func=None, ma...
# Generated by Django 3.0.5 on 2020-08-21 16:37 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('user', '0002_auto_20200815_1933'), ] operations = [ migrations.AlterField( model_name='user', name='QQ', ...
from flask_wtf import FlaskForm from wtforms import SubmitField, RadioField, BooleanField class QuizQuestionViewModel(FlaskForm): question_text: str = '' answers = [] question_number: int = 0 subject_name: str = '' answer_selection = RadioField() is_validation_step = BooleanField() ...
V_MAJOR = 1 V_MINOR = 0 ENGINE_NAME = "cpuemulate" PROJECT_NAME = "cpueditor" TOOLS_DIR = "tools" import sys, platform PLATFORM = sys.platform for platInfo in platform.uname(): if "microsoft" in platInfo.lower(): PLATFORM = "windows" break def IsWindows(): return PLATFORM == "windows" de...
####### # Objective: Create a dashboard that takes in two or more # input values and returns their product as the output. ###### # Perform imports here: # Launch the application: # Create a Dash layout that contains input components # and at least one output. Assign IDs to each component: # Create a ...
"""To be used in conjunction with stateAnalysis.cpp. This file generates plots of the respective action classes given a specific vehicular state.""" import plotly.express as px import pandas as pd import json import tool as tl from typing import Tuple, Dict def load_data() -> Tuple[Dict, pd.DataFrame]: """Loads ...
import argparse import os import random import time import warnings import sys import numpy as np import torch import torch.nn as nn import torch.nn.parallel import torch.backends.cudnn as cudnn import torch.distributed as dist import torch.optim from sklearn.metrics import roc_auc_score from scipy.spec...
# coding:utf-8 import os import numpy as np import tensorflow as tf from cvtron.Base.Trainer import Trainer from cvtron.data_zoo.segment.SBD import TFRecordConverter from cvtron.model_zoo.deeplab.deeplabV3 import deeplab_v3 from cvtron.preprocessor import training from cvtron.preprocessor.read_data import (distort_ra...
import argparse import textwrap import json import matplotlib.pyplot as plt parser = argparse.ArgumentParser(prog='PROG', formatter_class=argparse.RawDescriptionHelpFormatter,\ epilog=textwrap.dedent('''\ Here an example on how to run the script: python3 create_plots.py --input_file results.json ...
# -*- coding: utf-8 -*- # Copyright (c) 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 applicab...
from base64 import b64decode from inspect import getmembers, ismethod from .constants import * from .message import (JMSMessageType, _add_required_message_attribute_names, _encode_jms_message, _encode_jms_messages, _get_string_attribute) class JMSClient(object): def ...
import yaml import os, os.path loc = os.path.dirname(os.path.abspath(__file__)) hosts = yaml.load(open(loc+'/hosts.yml')) projects = yaml.load(open(loc+'/projects.yml')) allocations = yaml.load(open(loc+'/allocations.yml')) users = yaml.load(open(loc+'/users.yml'))
import os from .util import Object from hardhat.terminal import Terminal from threading import Thread try: from urllib.request import ProxyHandler, build_opener, Request from urllib.request import install_opener from urllib.parse import urlparse from http.server import HTTPServer, BaseHTTPRequestHandl...
import pytest from flask import g, session from sqlalchemy import text from flaskr.db import get_db def test_register(client, app): assert client.get("/auth/register").status_code == 200 response = client.post( "/auth/register", data={"email": "a", "password": "a", "first_name": "a", "last_n...
# coding=utf-8 """ Ref: https://github.com/NVIDIA/apex/blob/f5cd5ae937f168c763985f627bbf850648ea5f3f/examples/imagenet/main_amp.py#L256 """ import torch # import torch.nn as nn # import torch.nn.functional as F class data_prefetcher(): def __init__(self, loader): self.loader = iter(loader) sel...
from utils import setup_distrib, disk, square, rank_print, plot_matrix import torch.distributed as dist import torch.multiprocessing as mp import torch OPERATION = dist.ReduceOp.MAX def main_process(rank, world_size=2): device = setup_distrib(rank, world_size) image = torch.zeros((11, 11), device=device) ...
import gym import numpy as np import torch from stable_baselines3.common.vec_env import DummyVecEnv as VecEnv from src.core.reparam_module import ReparamPolicy from tqdm import tqdm from src.core.gail import train_discriminator, roll_buffer, TerminalLogger from dataclasses import dataclass from src.safe_options.policy...
from datetime import datetime from django.core.cache import cache from django.conf import settings class AlreadyLocked(Exception): def __init__(self, lock): self.lock_obj = lock super(AlreadyLocked, self).__init__() class EditLock(object): """ Using Django's cache system this class imple...
from src.models.db import AggregateDatasetModel, AggregateModelData, AggregateBenchmarkData class SummarizeDatasetRepo(object): def __init__(self): self.aggregateDatasetModel = AggregateDatasetModel() self.aggregateModel = AggregateModelData() self.aggregateBenchmark ...
""" This module contains functionality required for disconnected installation. """ import glob import logging import os import tempfile import yaml from ocs_ci.framework import config from ocs_ci.helpers.disconnected import get_oc_mirror_tool, get_opm_tool from ocs_ci.ocs import constants from ocs_ci.ocs.exceptions ...
#Defines a day aggregator object import datetime """Node and Leaf classes helping to build a date tree structure, could be expanded easily""" class MainContainer(object): """ Container class holding all derived instances """ def __init__(self, date=None, _type="", sensor="", _id="DummyID", name="con...
#!/usr/bin/env python # -*- coding: utf-8 -*- # Docstring """Butyi's Python3 Auto-DJ RadioPlayer. It plays programme of my radio station.""" # Authorship information __author__ = "Janos BENCSIK" __copyright__ = "Copyright 2020, butyi.hu" __credits__ = "James Robert (jiaaro) for pydub (https://github.com/jiaaro/pydub)...
import DBLib as db exit = False while exit != True: print ("\nCurrent database actions:\n-Add Entry = Adds a new entry to database\n-Delete Entry = Deletes an entry from the database\n-Show Entries = Shows the whole entries") answer = input("\nDatabase Action: ") if answer == 'Add Entry': uName = ...
# Copyright (c) 2013 Rackspace, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wr...
# coding = utf-8 from appium import webdriver import yaml import logging """ @Author: Allison Liu @Date: 07/06/2019 """ def desired_caps(): with open('../config/xueqiu_caps.yaml', 'r', encoding='utf-8') as f: data = yaml.load(f) des_caps = { 'platformName': data['platformName'], ...
''' Given an array nums of integers, return how many of them contain an even number of digits. Example 1: Input: nums = [12,345,2,6,7896] Output: 2 Explanation: 12 contains 2 digits (even number of digits). 345 contains 3 digits (odd number of digits). 2 contains 1 digit (odd number of digits). 6 contains 1 dig...
""" 爬取悦音台mv排行榜 使用requests --- bs4 技术 """ import requests import bs4 import random def get_html(url): try: r = requests.get(url, timeout=30) r.raise_for_status r.encoding = r.apparent_encoding return r.text except: return "Something wrong!" def get_content(url): i...
import requests HOST = "http://192.168.77.47:3000" # Create a new case params = {"engineer_id": "1", "case_name": "sample_case", "elevator_tag": "ELEVATOR_001", "description": "What's wrong?"} r = requests.post("{}/service/create_case".format(HOST), params) print(r.text) # Create problem for the new case files = {"...
import os def is_aws_credentials_not_set(): return not ( "AWS_ACCESS_KEY_ID" in os.environ and "AWS_SECRET_ACCESS_KEY" in os.environ and "AWS_DEFAULT_REGION" in os.environ and "AWS_ROLE" in os.environ )
from temboo.Library.SendGrid.WebAPI.InvalidEmails.DeleteInvalidAddress import DeleteInvalidAddress, DeleteInvalidAddressInputSet, DeleteInvalidAddressResultSet, DeleteInvalidAddressChoreographyExecution from temboo.Library.SendGrid.WebAPI.InvalidEmails.RetrieveInvalidEmails import RetrieveInvalidEmails, RetrieveInvalid...
from unittest import TestCase from obihai_helper import ObihaiHelper class TestObihaiHelper(TestCase): def test_add_caller_to_history(self): config_folder = "./" self.helper = ObihaiHelper(config_folder) self.helper.add_caller_to_history("port2", "11234567891", "John Smith", 1, "12:23:45 0...
# 序号 # 方法及描述 # 1 # os.access(path, mode) # 检验权限模式 # 2 # os.chdir(path) # # 改变当前工作目录 # 3 # os.chflags(path, flags) # # 设置路径的标记为数字标记。 # 4 # os.chmod(path, mode) # # 更改权限 # 5 # os.chown(path, uid, gid) # # 更改文件所有者 # 6 # os.chroot(path) # # 改变当前进程的根目录 # 7 # os.close(fd) # # 关闭文件描述符 fd # 8 # os.closerange(fd_low, fd_high) #...
from redwind import db from redwind.models import Venue db.create_all() db.engine.execute( 'ALTER TABLE location ADD COLUMN venue_id INTEGER REFERENCES venue(id)') db.engine.execute( 'ALTER TABLE post ADD COLUMN venue_id INTEGER REFERENCES venue(id)')
#!/usr/bin/env python # -*- coding: utf-8 -*- import re import sys import traceback import os import threading import time import socket import select descriptors = list() Desc_Skel = {} _Worker_Thread = None _Lock = threading.Lock() # synchronization lock Debug = False def dprint(f, *...
from conans import ConanFile, CMake import os # This easily allows to copy the package in other user or channel channel = os.getenv("CONAN_CHANNEL", "testing") username = os.getenv("CONAN_USERNAME", "demo") class HelloReuseConan(ConanFile): settings = "os", "compiler", "build_type", "arch" requires = ("hello/...
import numpy as np from scipy.linalg import expm import leg_controllers.hopper as hopper import leg_controllers.model as model A = np.array([ [0., 1., 0.], [-hopper.omega**2, 0., -model.g], [0.,0.,0.] ]) def reference(E,y0,t): # calculate initial velocity from E,y0 v0 = -np.sqrt(2*(E-.5*(hopper.o...
from fastapi import APIRouter from . import auth, challenges, roles, users router = APIRouter(prefix="/v1") router.include_router(auth.router) router.include_router(challenges.router) router.include_router(roles.router) router.include_router(users.router)
#!/usr/bin/python """ Examples for how to use cluster.py """ import argparse import os.path import time import yaml import pylib.mps.cluster.packages as packages def push(p, packages, args): p.push(args.local_root, args.package, args.version) def f_import(p, packages, args): if '' != args.location: src = a...
#!/usr/bin/python from __future__ import (absolute_import, division, print_function) # Copyright 2019-2020 Fortinet, Inc. # # This program 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 th...
# coding: utf-8 class Vertice: def __init__(self, nome_cidade, distancia_objetivo): self.nome_cidade = nome_cidade self.visitado = False self.distancia_objetivo = distancia_objetivo self.cidades = [] def adicionar_cidade(self, cidade): self.cidades.append(cidade) ...
""" Managing Attack Logs. ======================== """ import csv from csv import writer from textattack.metrics.attack_metrics import ( AttackQueries, AttackSuccessRate, WordsPerturbed, ) from textattack.metrics.quality_metrics import Perplexity, USEMetric from . import CSVLogger, FileLogger, VisdomLogge...
#!/usr/bin/env python3 import select, socket response = b'HTTP/1.1 200 OK\r\nConnection: close\r\n\r\nHello World!' serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM) serv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) serv.bind(('0.0.0.0', 9000)) serv.listen(16) serv.setblocking(0) rlist =...
# Write a program, which sums the ASCII codes of N characters and prints the sum on the console. # On the first line, you will receive N – the number of lines. # On the following N lines – you will receive a letter per line. Print the total sum in the following format: "The sum equals: {total_sum}". # Note: n will be...
""" Pointers -------- Ex: a house that you want to sell; a few Python functions that work with images, so you pass high-resolution image data between your functions. Those large image files remain in one single place in memory. What you do is create variables that hold the locations of those images in memory. The...
#!/usr/bin/python3 -B import re import os import sys import json import shutil import base64 import subprocess from time import sleep from rich.progress_bar import ProgressBar from rich.console import Console from rich.panel import Panel from rich.table import Table PIPE = subprocess.PIPE DESCRIPTION = b'Clt5ZWxsb3d...
import copy from cgi import parse_header from functools import reduce, wraps from heapq import nsmallest from io import BytesIO import json from operator import itemgetter import os.path from lxml.html import document_fromstring from PIL import Image from twisted.internet import defer, protocol, reactor from twisted....
# ParentID: 1002002 # Character field ID when accessed: 109090300 # ObjectID: 1000005 # Object Position Y: -724 # Object Position X: -142
from random import randint #################################### # DEVELOPER : VIKRAM SINGH # # TECHNOLOGY STACK : PYTHON # #################################### # Evaluation Definitions X_WINS = 1000 O_WINS = -1000 DRAW = 0 class TicTacToe(): ''' ALGO: MIN-MAX By making any of the move if in ...
# -*- coding: utf-8 -*- import sys from .error import Invalid import warnings import logging, inspect log = logging.getLogger(__name__) _python3 = sys.version_info[0]>=3 class PASS: pass class __MISSING__( str ): def __str__(self): return '' __unicode__ = __str__ MISSING = __MISSING__() de...
#!/usr/bin/python # -*- coding: utf-8 -*- var1 = 'Hello World!' var2 = "Python Runoob" print "var1[0]: ", var1[0] print "var2[1:5]: ", var2[1:5] print "更新字符串 :- ", var1[:6] + 'Runoob!' a = "Hello" b = "Python" print "a + b 输出结果:", a + b print "a * 2 输出结果:", a * 2 print "a[1] 输出结果:", a[1] print "a[1:4] 输出结果:", ...
# -*- coding: utf-8 -*- # # Copyright 2019 Google LLC. 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 requir...
import difflib import discord import pandas as pd from gamestonk_terminal.stocks.screener.finviz_model import get_screener_data import discordbot.config_discordbot as cfg from discordbot.helpers import pagination from discordbot.stocks.screener import screener_options as so async def ownership_command(ctx, preset="t...
from fontTools.ttLib import newTable from fontTools.ttLib.tables import otTables as ot from fontTools.colorLib import builder from fontTools.colorLib.errors import ColorLibError import pytest def test_buildCOLR_v0(): color_layer_lists = { "a": [("a.color0", 0), ("a.color1", 1)], "b": [("b.color1",...
import threading import logging from defensics.coap_proxy import CoapProxy from defensics.tcp_server import TCPServer class DataHandler(threading.Thread): def __init__(self, proxy: CoapProxy, tcp_server: TCPServer): super().__init__() self.proxy = proxy self.tcp_server = tcp_server ...
# This is a comment import os import sys from PySide2.QtWidgets import QApplication, QMainWindow from PySide2.QtCore import QFile from PySide2.Qt3DExtras import Qt3DExtras from PySide2.Qt3DCore import Qt3DCore from PySide2.QtGui import QVector3D, QColor from PySide2.Qt3DRender import Qt3DRender from ui_mainwindow impor...
import zmq context = zmq.Context() socket = context.socket(zmq.REP) socket.bind("tcp://*:5555") example_container_id = "346cddf529f3a92d49d6d2b6a8ceb2154eff14709c10123ef1432029e4f2864a" while True: message = socket.recv_string() socket.send_string(example_container_id)
#!/usr/bin/env python from argparse import ArgumentParser from os.path import isfile, isdir, join from sys import exit import numpy as np #from pleiopred import prior_generating, coord_trimmed, pre_sumstats import pred_main_bi_rho # Create the master argparser and returns the argparser object def get_argparser(): p...
from .sr04 import SR04
from django.apps import AppConfig class FlippyConfig(AppConfig): name = "flippy"
""" This middleware can be used when a known proxy is fronting the application, and is trusted to be properly setting the `X-Forwarded-Proto`, `X-Forwarded-Host` and `x-forwarded-prefix` headers with. Modifies the `host`, 'root_path' and `scheme` information. https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers#...
class Solution: def kthSmallest(self, mat: List[List[int]], k: int) -> int: h = mat[0][:] for row in mat[1:]: h = sorted([i+j for i in row for j in h])[:k] return h[k-1]
# Copyright 2019 TWO SIGMA OPEN SOURCE, 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 agre...
input_number: float = float(input()) if input_number == 0: print('zero') exit(0) input_number_sign: str = 'positive' if input_number > 0 else 'negative' input_number_abs: float = abs(input_number) if input_number_abs < 1: print(f'small {input_number_sign}') elif input_number_abs > 1000000: print(f'l...
from typing import Callable, List def chain_functions(*functions_list: List[Callable]) -> Callable: """Chain the given functions in a single pipeline. A helper function that creates another one that invoke all the given functions (defined in functions_list) in a waterfall way. The given function...
import sys, itertools # sys.stdin = open('input.txt', 'r') n, m = map(int, sys.stdin.readline().strip().split()) # temp = itertools.combinations(range(n), m) for temp in itertools.permutations(range(1, n+1), m): print(*temp)
import asyncio import time import numpy as np from mavfleetcontrol.craft import Craft from mavfleetcontrol.actions.point import FlyToPoint from mavfleetcontrol.actions.percision_land import PercisionLand from mavfleetcontrol.actions.arm import Arm from mavfleetcontrol.actions.disarm import Disarm from mavfleetcontrol...
from max_sequence import max_sequence import unittest class Test(unittest.TestCase): def test_1(self): result = max_sequence([-2, 1, -3, 4, -1, 2, 1, -5, 4]) self.assertEqual(result, [4, -1, 2, 1]) def test_2(self): result = max_sequence([-2, -1, -3, -4, -1, -2, -1, -5, -4]) s...
# NOTE: For stable output, this should be run on a Python version that # guarantees dict order (3.7+). import re import os.path import sys from enum import Flag, auto from collections import defaultdict from pprint import pprint if len(sys.argv) < 3: print("Need input and output file names") sys.exit(1) fn = os.path...
# coding: utf-8 # # Copyright 2022 :Barry-Thomas-Paul: Moss # # 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...
DEPS = [ 'recipe_engine/path', 'recipe_engine/properties', 'recipe_engine/python', 'recipe_engine/step', ] # TODO(phajdan.jr): provide coverage (http://crbug.com/693058). DISABLE_STRICT_COVERAGE = True
clinvar = open('/lgc/datasets/dbsnp/141/clinvar_20140702.vcf') variants = 0 variants_before_129 = 0 pathogenic_before_129 = 0 for line in clinvar: if not line.startswith('#'): variants += 1 row = line.split('\t') info = row[7].split(';') #get dbsnpbuild dbsnpbuild = 0 for item in info: if item.startswi...
# -*- coding: utf-8 -*- """ Created on Fri Jan 22 23:55:22 2021 @author: Reza """ class InternalServerError(Exception): pass class SchemaValidationError(Exception): pass class DataNotExistsError(Exception): pass class KeyError(Exception): pass class ThresholdError(Exception): pass errors = { ...
import time subscriptions = set() def subscribe_for_events(sub): subscriptions.add(sub) def unsubscribe_from_events(sub): subscriptions.remove(sub) def put_event(event): for subscription in subscriptions: subscription.put(event) def app_state_event(app_state): put_event({ 'type'...
import functools import json import logging import re import traceback import urllib.parse from apispec import yaml_utils from flask import Blueprint, current_app, jsonify, make_response, request from flask_babel import lazy_gettext as _ import jsonschema from marshmallow import ValidationError from marshmallow_sqlalc...
from argh import arg from six import iteritems import pnc_cli.common as common import pnc_cli.cli_types as types import pnc_cli.utils as utils from pnc_cli.swagger_client import ProductRest from pnc_cli.pnc_api import pnc_api __author__ = 'thauser' def create_product_object(**kwargs): created_product = Product...
import os import argparse import pickle import tensorflow as tf import numpy as np import pandas as pd from augmentation import processing_data_functions, AUTO, partial from skimage.measure import label from google.protobuf.descriptor import Error from sklearn.metrics import accuracy_score, f1_score import segmentat...
# # Copyright (C) 2019 Databricks, 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 i...
import numpy as np from sklearn.preprocessing import LabelBinarizer def dcg_score(y_true, y_score, k=5): """Discounted cumulative gain (DCG) at rank K. Reference: https://www.kaggle.com/davidgasquez/ndcg-scorer Parameters ---------- y_true : array, shape = [n_samples] Ground truth (tr...
''' Code for generating and applying unified diff patches to files being modified. Goal is to be able to make relatively clean edits to the existing x3 scripts and other source files without having to copy the contents. Initial version is not expected to support multiple patches to the same file through this method. T...
import subprocess def build_message_database(code): if code: return 'Database deploy failed.' return 'Database ok.' def build_message_deploy(code): if code: return 'Composition deploy failed' return 'Composition deployed' def deploy_backend(): print('deploying database') ex...
#!/usr/bin/env python #coding:utf-8 from gevent import monkey monkey.patch_all() import web from web.httpserver import StaticMiddleware from socketio import server urls = ( '/', 'IndexHandler', # 返回首页 '/topic', 'TopicHandler', '/topic/(\d+)', 'TopicHandler', '/message', 'MessageHandler', '/user'...
import sys import jmespath from termcolor import colored from datetime import datetime from botocore.compat import json, six def milis2iso(milis): res = datetime.utcfromtimestamp(milis/1000.0).isoformat() return (res + ".000")[:23] + 'Z' class LogPrinter(object): def __init__(self, log_group_name, max_st...
# -*- coding: utf-8 -*- from datetime import timedelta from influxdb import SeriesHelper from redtrics.api.influxdbapi import InfluxDBApi from redtrics.api.github import GithubApi from redtrics.utils.dateutils import DateUtils from redtrics.metrics.registry import MetricRegistry from .base import BaseMetric class Co...
from Disruptor import Disruptor from Scrambler import Scrambler import Receiver from Descrambler import Descrambler #Klasa przedstawiajaca kanal transmisyjny dla sygnalu scramblowanego/niescramblowanego class Channel: def __init__(self, sygnal, algorythm, channel): disrupter = Disruptor(sygnal) #tworzeni...
from scipy import misc import tensorflow as tf import align.detect_face import matplotlib.pyplot as plt import numpy as np minsize = 20 # minimum size of face threshold = [0.6, 0.7, 0.7] # three steps's threshold factor = 0.709 # scale factor gpu_memory_fraction = 1.0 # function pick = nms(boxes,thresho...
"""A library for describing and applying affine transforms to PIL images.""" import numpy as np import PIL.Image class RGBTransform(object): """A description of an affine transformation to an RGB image. This class is immutable. Methods correspond to matrix left-multiplication/post-application: for e...
from roboclaw import * print "set pid started" current_pid = readM1pidq(128) print "M1 before p,i,d,qpps: ", current_pid SetM1pidq(128,22000,80000,16351,180000) new_pid = readM1pidq(128) print "M1 after p,i,d,qpps: ", new_pid current_pid = readM2pidq(128) print "M2 before p,i,d,qpps: ", current_pid SetM2pidq(128,22...
# (C) StackState 2020 # All rights reserved # Licensed under a 3-clause BSD style license (see LICENSE) from ..base.utils.persistent_state import *
from fastapi import FastAPI import os import sys from pathlib import Path DIR = Path(__file__).absolute().parent sys.path.append(str(DIR)) from data import ReadDatas data = ReadDatas() data.main() root_path = os.getenv("ROOT_PATH", "") app = FastAPI( title="子育て施設一覧(保育園・幼稚園・認定こども園等) API", root_path=root_path )...
import os import sys import yaml import json import subprocess sys.path.insert(0, os.path.abspath('./functions')) from create_canned_tasks import main from jira_api import get_all_tasks_in_epic # load JIRA username and password jira_creds = yaml.load(open('./user_dev.yml')) username = jira_creds['user']['name'] passw...