content
stringlengths
5
1.05M
"""Argparse argument types and extensions.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import os, six, glob, itertools, argparse _IMG_EXTS = ('.png', '.jpg', '.bmp', '.jpeg') class ArgumentParser(argparse.A...
# ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. # # Copyright 2020 The Microsoft DeepSpeed Team # Copyright (c) 2020, NVIDIA CORPORATION. # Some functions in this file are adapted from following sou...
from pyspark.sql import SparkSession from pyspark.ml.classification import RandomForestClassifier from pyspark.sql.types import * from pyspark.sql import functions as sql_functions from pyspark.ml.linalg import SparseVector,Vectors, VectorUDT import numpy as np import sys def calmean(a1,a2,a3,a4,a5,a6,a7,a8,a9,a10): ...
# Importar librerias import unittest from context import scripts # Carga de datos de funciones y obtencion del diccionario clases_orf dir_name_functions = '../Data/tb_functions.pl' clases_orf = scripts.ProcessFiles(dir_name_functions).process_functions() class TestEjercicio1(unittest.TestCase): """ Clase que...
"""Calculate value of dipole and associated uncertainty.""" execfile('version.py') import dipole_error from dipole_error import *
""" Copyright (c) Facebook, Inc. and its affiliates. This source code is licensed under the MIT license found in the LICENSE file in the root directory of this source tree. """ import sigpy.mri import numpy as np import torch from math import floor, ceil class MaskFunc: """ Abstract MaskFunc class for creati...
import click from opta.constants import VERSION @click.command(hidden=True) def version() -> None: """Current opta version""" print(VERSION)
import pyparsing as pp from pydbml.classes import Note from pydbml.classes import Project from .common import _ from .common import _c from .common import n from .common import note from .generic import name from .generic import string_literal pp.ParserElement.setDefaultWhitespaceChars(' \t\r') project_field = pp.G...
""" Module for the html output creation class. """ import os import datetime import json import codecs class HTMLCreator(): """ Html output creator. Constructs the HTML string for displaying the CCOBRA evaluation results. """ def __init__(self, evaluations): """ Initializes the html creator...
# This sample tests the handling of the @final method decorator. from typing import final class ClassA: def func1(self): pass @classmethod def func2(cls): pass @final def func3(self): pass @final @classmethod def func4(cls): pass class ClassB...
import itertools import scipy.integrate from pytest import approx import gmw def test_analytic_normalization(): betas = [0.1, 0.4, 5, 10, 23] gammas = [1, 2, 3, 1.1, 3.5] scales = [0.1, 0.5, 1, 2, 10, 100] for beta, gamma, scale in itertools.product(betas, gammas, scales): wavelet = gmw.Mors...
#!/usr/bin/env import os import logging from .generator import Generator import click # ######## LOGGING ######### logger = logging.getLogger('pyrelease') logger.setLevel(logging.DEBUG) # File handler handler = logging.FileHandler(os.path.join(os.getcwd(), 'build.log'), 'w') handler.setLevel(logging.DEBUG) formatter...
# -*- coding: utf-8 -*- """Distance based time series regressors.""" __all__ = ["KNeighborsTimeSeriesRegressor"] from sktime.regression.distance_based._time_series_neighbors import ( KNeighborsTimeSeriesRegressor, )
# Copyright (c) 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 os import parse_deps import re srcdir = os.path.abspath(os.path.join(os.path.dirname(__file__), "../src")) def GritCheck(): filenames = [os.pa...
# Copyright 2016 The Johns Hopkins University Applied Physics Laboratory # # 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...
from datetime import datetime from ui.widgets.background import LcarsBackgroundImage, LcarsImage from ui.widgets.gifimage import LcarsGifImage from ui.widgets.lcars_widgets import * from ui.widgets.screen import LcarsScreen from datasources.network import get_ip_address_string from pathlib import Path class ScreenM...
from config.defs import * import peewee db = peewee.SqliteDatabase(DATABASE_NAME) class BaseModel(peewee.Model): class Meta: database = db class Partida(BaseModel): id_time_casa = peewee.CharField() id_time_visitante = peewee.CharField() time_casa = peewee.CharField() time_visitante = peewee.CharField(...
import os from datetime import datetime from time import time import math import logparser import schedulable import json import shutil from tqdm import tqdm jsondir = '/home/rtss/json' final_logfile = "/home/rtss/final.log" def create_logdir(jsonfile): with open(jsonfile, "r") as f: j = json.loads(f.re...
import copy import sys import gevent import asyncio import ipaddress import socket import random from devp2p import peermanager from devp2p.app import BaseApp from devp2p.discovery import NodeDiscovery from devp2p.protocol import BaseProtocol from devp2p.service import BaseService, WiredService from devp2p.crypto impo...
# GitHub Actions Utility Functions # https://docs.github.com/en/actions/reference/workflow-commands-for-github-actions import os import sys errors_were_printed = False def fail_if_errors(): if errors_were_printed: print("Exiting due to previous errors.", file=sys.stderr) sys.exit(1) def print_err...
import torch def bt_loss(h1: torch.Tensor, h2: torch.Tensor, lambda_, batch_norm=True, eps=1e-15, *args, **kwargs): batch_size = h1.size(0) feature_dim = h1.size(1) if batch_norm: z1_norm = (h1 - h1.mean(dim=0)) / (h1.std(dim=0) + eps) z2_norm = (h2 - h2.mean(dim=0)) / (h2.std(dim=0) + ep...
import bpy import numpy from mathutils import Matrix from mathutils.geometry import intersect_line_plane import sprytile_utils import sprytile_uv from sprytile_uv import UvDataLayers class ToolFill: modal = None left_down = False def __init__(self, modal, rx_source): self.modal = modal rx...
import os import sys import cv2 import numpy as np from PIL import Image image_root = r'./image-50000' resize_min = 256 def trans(): images = os.listdir(image_root) for image_name in images: if image_name.endswith("txt"): continue # image_name = "20180522135150.jpg" print("...
from django.shortcuts import render from django.http import HttpResponse from django.contrib.auth.decorators import login_required from django.template import loader # Create your views here. @login_required def index(request): template = loader.get_template('tutorials/index.html') return HttpResponse(template...
class Solution: def isScramble(self, s1: str, s2: str) -> bool: n = len(s1) m = len(s2) if n != m: return False tmp = [[False for i in range(n + 1)] for j in range(n)] dp = [copy.deepcopy(tmp) for i in range(n)] for i in range(n): fo...
# cat a list of Unicode codepoints (one on each line, in U+XXXX # format) to get a regex character class representing those characters # with contiguous ranges collapsed. Unicode literals will be in # Python-style notation (\uXXXX, \UXXXXXXXX). import sys is_javascript = 'js' in sys.argv def is_surrogate(codepoint)...
# # PySNMP MIB module LUCENT-GENERIC-DLOAD-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/LUCENT-GENERIC-DLOAD-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 19:58:33 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7....
# !/usr/bin/env python # -*- coding = utf-8 -*- # @Author:wanghui # @Time: # @File:getStartActivityConfig.py import configparser import os BASE_DIR = os.path.dirname(os.path.abspath(__file__)) class GetStartActivityConfig(object): def __init__(self): self.config = configparser.ConfigParser() s...
import pytest import os import re from siliconcompiler.core import Chip from siliconcompiler.floorplan import Floorplan def _fp(datadir): c = Chip(loglevel='INFO') c.set('design', 'test', clobber=True) c.target('asicflow_freepdk45') lib = 'ram' c.add('asic', 'macrolib', lib) c.set('library', l...
# Functions to create loss objectives for the discriminator and generator import tensorflow as tf #Alpha does nothing in this function, just there to make things easier def generator_loss_original(fake_output, alpha): cross_entropy = tf.keras.losses.BinaryCrossentropy(from_logits=True) return cross_entropy(...
# Note - local play only works with open hands! from game import Game def get_player_ids(): ids = list() next = 'fnjsfjkalefbesg ' while True: next = input(f"Enter name for player {len(ids)+1}: ") if next: ids.append(next) else: break return ids def main(): player_ids = get_playe...
# Task: # Now, let's use our knowledge of sets and help Mickey. # Ms. Gabriel Williams is a botany professor at District College. # One day, she asked her student Mickey to compute the average of # all the plants with distinct heights in her greenhouse. # # Formula used: # Average = sum of distinct heights / tot...
def ngram(words, N=2): d = {} for idx in range(len(words)): if idx + N - 1 >= len(words): continue key = tuple(words[idx:idx + N]) if key in d: d[key] += 1 else: d[key] = 1 return d s1 = "paraparaparadise" s2 = "paragraph" X = ngram(s1) ...
#!/usr/bin/env python3 # References: # https://docs.python.org/3/library/argparse.html # http://bip.weizmann.ac.il/course/python/PyMOTW/PyMOTW/docs/argparse/index.html # http://stackoverflow.com/questions/3853722/python-argparse-how-to-insert-newline-the-help-text import argparse from argparse import RawTextHelpForma...
from __future__ import absolute_import, division, print_function import json import pytest import stripe class TestSearchResultObject(object): @pytest.fixture def search_result_object(self): return stripe.SearchResultObject.construct_from( {"object": "search_result", "url": "/my/path", ...
import argparse import shlex import sys import ircmessage from alttprbot.alttprgen import mystery, preset, spoilers from alttprbot.database import (config, spoiler_races, srl_races, tournament_results) from alttprbot.exceptions import SahasrahBotException from alttprbot.tournament impo...
import os import numpy as np import pandas as pd import matplotlib.pyplot as plt import calendar import imageio import joblib from shutil import copy2, rmtree from datetime import datetime, timedelta def clean_nan(array): if type(array) == list: array = np.asarray(array) not_nan_array = ~ np.isnan(ar...
from decouple import config from config.db_url import PgUrl # import dj_database_url # from dj_database_url import parse as db_url from .base import * # noqa SECRET_KEY = config('DJANGO_SECRET_KEY') DEBUG = False ALLOWED_HOSTS = ['localhost', '127.0.0.1'] # TODO: Below commented code not work for me # # Improperly c...
# # @lc app=leetcode id=354 lang=python3 # # [354] Russian Doll Envelopes # # @lc code=start import bisect class Solution: def maxEnvelopes(self, envelopes: list[list[int]]) -> int: """transform to find longest increasing subsequence""" heights = [j for _, j in sorted(envelopes, key=lambda e: (e[0...
from CPconfig import configuration from importlib import import_module # A proper implementation of the event selection will at least # define the following: # - categoryNames (list of names of categories) # - eventCategory (category data producer) # - isInCategory (category definition, from category data) # the lis...
from setuptools import find_packages, setup setup( name='src', packages=find_packages(), version='0.1.0', description='Everyone who speaks a language, speaks it with an accent. A particular accent essentially reflects a person\'s linguistic backThe model define accent based audio record.', author='...
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved """Collection of types used in the code.""" from typing import TYPE_CHECKING, Dict, Tuple import gym import numpy as np import torch from omegaconf import DictConfig, ListConfig from mtrl.env.vec_env import VecEnv # type: ignore[attr-defined] L...
from sklearn import svm X = [[0, 0], [1, 1]] y = [0, 1] clf = svm.SVC() clf.fit(X, y)
""" MIT License Copyright (c) 2022 Pedro Correia 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,...
"""General data loading classes.""" import hashlib import logging import pathlib import urllib.request from enum import Enum from typing import Optional import numpy import tqdm from ..settings import K_MAX from ..utils import all_knn logger = logging.getLogger(name=__name__) class Dataset: """Base class for d...
from random import choice print('Choose one side to shoot: ') print('left, center, right') you = input() print('You kicked ' + you) direction = ['left', 'center', 'right'] com = choice(direction) print('Computer saved ' + com) if you != com: print('Goal!') else: print('Oops...')
# Generated by Django 3.2.10 on 2021-12-16 18:57 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('pipelines', '0002_auto_20211216_1942'), ] operations = [ migrations.AlterField( model_name='datasetpipelines', name...
from checkov.common.graph.checks_infra.enums import Operators from checkov.terraform.checks_infra.solvers.connections_solvers.connection_exists_solver import ConnectionExistsSolver class ConnectionNotExistsSolver(ConnectionExistsSolver): operator = Operators.NOT_EXISTS def __init__(self, resource_types, conn...
from .const import * class node: parent=None left=None operator=None right=None result=None left_type=None right_type=None isvar=None def __init__(self,a): self.parent=a def par(exp): ops=['%','/','*','+','-','<','>','!','=','&','|'] #in th...
import pyglet import pool import utils import random import math from spatial import Vector2D from pyglet.window import mouse TIME_STEP = 0.01 VIEW_SCALE = 200 STROKE_THICKNESS = 2 BLACK_COLOUR = [0, 0, 0] WHITE_COLOUR = [255, 255, 255] RED_COLOUR = [255, 0, 0] YELLOW_COLOUR = [255, 255, 0] FELT_COLOUR = [27, 137, 3...
import requests import json import os import queue import logging from prometheus_api_client import PrometheusConnect log = logging.getLogger('prometheus_helper') class PrometheusInfraConnect: def __init__(self, region, verify_ssl=False): self.api = None self.region = region self.prometh...
import random import colorsys import os from colored import fg, bg, attr global HANGMAN_PHOTOS HANGMAN_PHOTOS = { 0: """ x-------x""", 1: """ x-------x | | | | |""", 2: """ x-------x | | | 0 | | ...
import atexit import json import os import pickle import platform as pyplatform import sys class Cache(object): def __init__(self, platform, marshaler='json'): self.marshaler = marshaler or 'json' # We use platform.uname here, because os.uname is not available on # all supported platforms....
""" In the first line, print True if has any alphanumeric characters. Otherwise, print False. In the second line, print True if has any alphabetical characters. Otherwise, print False. In the third line, print True if has any digits. Otherwise, print False. In the fourth line, print True if has any lowercase charac...
from tensorflow import random import numpy as np import argparse import AlexNet import flying_dogs import LeNet_5 import Learner def seed_loop(func, epochs, n_seeds=30): trains, tests = [], [] for seed in range(n_seeds): print(f"Seed: {seed}") random.set_seed(seed) np.random.seed(see...
import useful_functions as func scores = [88, 92, 79, 93, 85] mean = func.mean(scores) curved = func.add_five(scores) mean_c = func.mean(curved) print("Scores:", scores) print("Original Mean:", mean, " New Mean:", mean_c)
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright © 2014, 2015, 2017 Kevin Thibedeau # (kevin 'period' thibedeau 'at' gmail 'punto' com) # # 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...
####################################################### # LOVE_DEATH_ROBOTS # ####################################################### import RPi.GPIO as GPIO import time import threading import roslibpy # Haversine gives the GPS coords of the base station from Haversine import setTargetHeadin...
# -*- coding: utf-8 -*- """ :copyright: Copyright 2020-2022 Sphinx Confluence Builder Contributors (AUTHORS) :license: BSD-2-Clause (LICENSE) """ from tests.lib.testcase import ConfluenceTestCase from tests.lib.testcase import setup_builder from tests.lib import parse import os class TestConfluenceRstImage(Confluenc...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Jul 17 17:38:22 2018 @author: Dan Wendling Last modified: 2018-08-18 Purpose: Ingest selected XML nodes from pubmed.gov data sets, File > XML exports, into Python dataframes. Search strategy used in development: https://www.nlm.nih.gov/services/querie...
import re import sys import warnings from typing import Any, Callable, Generic, TypeVar, Union import wrapt from ..utils import misc from ..utils.translations import trans _T = TypeVar("_T") class ReadOnlyWrapper(wrapt.ObjectProxy): """ Disable item and attribute setting with the exception of ``__wrapped_...
# Simulate seismic wave propagation in 2D # use different acoustic wave velocities.Consider a source-receiver framework # select a given region and discretize over it, we only consider seismic body waves # in isotropic, homogeneous elastic media. # Fdtd is implemented in two ways: # 1. scalar codes to compu...
# -*- coding: utf-8 -*- # Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1) # # (1) Kamaelia Contributors are listed in the AUTHORS file and at # http://www.kamaelia.org/AUTHORS - please extend this file, # not this notice. # # Licensed under the Apache License, Version 2.0 (the "Lice...
from mathutils import Vector def create_ray( start, end, z, r, f ): return [ end, end + Vector((0, 0, -1)) * f ]
from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate from config import Config db = SQLAlchemy() migrate = Migrate() def create_app(debug=True): app = Flask(__name__) app.debug = debug app.config.from_object(Config) from app.api import event_bp,activity_bp...
# Copyright (C) 2018 Bloomberg LP # # 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 writi...
import os import numpy as np from envs.discrete_env.smac.smac_env import SMACEnv #from envs.discrete_env.continuous_mpe.mpe_env import MPEEnv #from envs.continuous_env.continuous_mpe.mpe_env import MPEEnv #from envs.discrete_env.discrete_magym.ma_gym_env import MAGYMEnv from utils.read_yaml import get_yaml_args def...
""" 개발환경 : PyQt5 x64, Python 3.4.3 x64, Windows 8.1 x64 파일 : CryptoVigenereKasiskiHackExtra.py 내용 : Kasiski 검사를 위한 모듈, 참조 내용에서 GUI환경을 위해 약간의 수정을 가함. 참조 : http://inventwithpython.com/hacking (BSD Licensed) """ # Vigenere Cipher Hacker # http://inventwithpython.com/hacking (BSD Licensed) import re import CryptoVigenere...
from django.contrib import admin from .models import Link @admin.register(Link) class LinkAdmin(admin.ModelAdmin): list_display = ('url', 'code')
# Copyright Amazon.com, Inc. or its affiliates. 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. # A copy of the License is located at # # http://www.apache.org/licenses/LICENSE-2.0 # # or in the "license" fil...
""" AWS Lambda and API Gateway """ from os import environ import awscli.clidriver import boto3 import yaml from hip_edit import resource_title def main(cli_options, build_context): """ Packages and deploys the AWS Lambda infrastructure """ prefix = cli_options.name template_path = cli_options.sa...
import argparse import logging from datetime import datetime from pathlib import Path from urllib.parse import urljoin import requests from math import ceil logging.basicConfig(format='%(levelname)s:%(message)s', level=logging.INFO) logger = logging.getLogger(__name__) DEFAULT_PAGE = 0 DEFAULT_SIZE = 10 MAX_PAGE_SIZ...
# Copyright 2016 The Chromium OS 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 logging from cros.factory.test.fixture.robot import robot from cros.factory.external import serial class SixDoFCalibrationRobot(robot.Robot): ...
from threading import current_thread class PublisherMiddleware(object): _draft_status = {} @staticmethod def is_draft(request): authenticated = request.user.is_authenticated() and request.user.is_staff is_draft = 'edit' in request.GET and authenticated return is_draft def pro...
from random import * dogeenergy = 30 dogehp = 0 btcdmg = 200 btcenergy = 20 btchp = 0 ethdmg = 150 ethenergy = 10 ethhp = 0 ltcdmg = 100 ltcenergy = 5 ltchp = 0 fooddmg = 0 foodenergy = 10 foodhp = 0 meddmg = 0 medenergy = 0 medhp = 10 p1hp = 1000 p2hp = 1000 p1energy = 100 p2energy = 100 player...
from __future__ import print_function, division import numpy as np import torch from ..advisor.modules import create_mask from ..advisor.utils import to_var from core.config import * class Evaluator(object): """ Class to evaluate models with given datasets. Args: loss (torch.NN.CrossEntropyLoss, op...
"""Extract all the identifiers (doi, pubmed, isbn, arxiv). Also, keep a stats file that counts where the identifiers have been found.""" import collections import datetime import functools import more_itertools import mwxml from typing import Iterable, Mapping, Callable from .. import dumper, extractors, utils, lang...
"""Spectral Embedding""" # Author: Marina Meila <mmp@stat.washington.edu> # James McQueen <jmcq@u.washington.edu> # LICENSE: Simplified BSD https://github.com/mmp2/megaman/blob/master/LICENSE # # after the scikit-learn version by # Gael Varoquaux <gael.varoquaux@normalesup.org> # Wei LI...
# -*- coding: utf-8 -*- """ Created on Sat May 8 2018. @author: Liu Aiting @e-mail: liuaiting@bupt.edu.cn """ import codecs import time import collections from multiprocessing import Pool import csv import jieba import numpy as np from sklearn.metrics.pairwise import cosine_similarity import config def read_stop_wo...
def paginate(method, **kwargs): client = method.__self__ paginator = client.get_paginator(method.__name__) return ( result for page in paginator.paginate(**kwargs).result_key_iters() for result in page )
from models import * # Testing the models, e.g., for an 4x8 grid states = StateModel( 4, 8) loc = Localizer( states) tMat = loc.get_transition_model() sVecs = loc.get_observation_model() tMat.plot_T() sVecs.plot_o_diags() print(sVecs.get_o_reading(0)) print(sVecs.get_o_reading(None)) print(loc.update())
# -*- encoding: utf-8 -*- """ Created by eniocc at 11/10/2020 """ import ctypes from py_dss_interface.models.Base import Base class MetersF(Base): """ This interface can be used to read/write certain properties of the active DSS object. The structure of the interface is as follows: double Meter...
#!/usr/bin/python3 # -*-coding:utf-8-*- __author__ = "Bannings" from typing import List class Solution: def runningSum(self, nums: List[int]) -> List[int]: ans = [nums[0]] for i in range(1, len(nums)): ans.append(nums[i] + ans[-1]) return ans if __name__ == '__main__': as...
import pygame as pg from settings import * from managers.resourcemanager import ResourceManager as GR from sprites.bullet import Bullet from managers.soundcontroller import SoundController as SC ########## # Guns # ########## ''' Clase abstracta que implementa todo el funcionamiento básico de un arma. ''' class Abs...
import pygame import numpy as np import random as rand from Source import UI_functions as UI from Source import battleships_functions_play as play def Play_Game(screen, bg, Bmap1, Bmap2, cfg): #Init font_s = pygame.font.Font("Assets/Font/impact.ttf", 26) font = pygame.font.Font("Assets/Font/impact.ttf...
"""ops.py""" import torch import torch.nn.functional as F def recon_loss(x, x_recon): n = x.size(0) loss = F.binary_cross_entropy_with_logits(x_recon, x, reduction='sum').div(n) return loss def kl_divergence(mu, logvar): kld = -0.5*(1+logvar-mu**2-logvar.exp()).sum(1).mean() return kld def pe...
# coding: utf-8 # In[ ]: # Let's import the nltk module import nltk # To start, we need some text to play with. NLTK has many corpora and resources for you to explore natural language. # A one-off run of nltk.download() will get you all the resources in one go. Once you've done that you should have # a repository...
# Created by Sinclert Pérez and Silvia Barbero import csv from DataMiner import getBookInfo from DataMiner import getBookReviews from DataMiner import getReviewLabels from DBManager import DataBase # MeaningCloud different labels sentimentLabels = ('P+', 'P', 'NEU', 'N', 'N+', 'NONE') agreementLabels = ('AGREEMENT'...
import uiautomator2 as u2 import time import random from config import * class Crawler(object): def __init__(self, device, app, swipe_duration,friend_total): """ :param device: usb(设备名称)/ADB WiFi(ip:port)/wifi (ip) :param app: packageName :param swipe_duration: 滑屏间隔 """ ...
""" Units tests """ import json import uuid import pint from django.core.cache import cache from django.test import TestCase from rest_framework import status from rest_framework.test import APIClient from geocurrency.units.models import UnitSystem from .models import ExpressionCalculator, Operand from .serializers ...
from typing import List import typer from click.testing import Result from typer.testing import CliRunner from typer_tutorial.cli import (DEFAULT_NAME, FORMAL_GREETING, FORMAL_GREETING_STYLE, GREETING, GREETING_STYLE, SILLY_MESSAGE, SILLY_NAMES, STDERR_STYLE, _main) # Test data FIRST_NAM...
import argparse from simulator.client.check import Check from simulator.client.match import Match from simulator.client.search import Search from simulator.client.upload import Upload from simulator.client.download import Download from simulator.client.authenticate import Authenticate class Client: def __init__...
import json from snipssonos.entities.artist import Artist from snipssonos.entities.track import Track from snipssonos.entities.playlist import Playlist from snipssonos.helpers.spotify_client import SpotifyClient, SpotifyAPISearchQueryBuilder class SpotifyCustomizationService: TIME_RANGES = ["long_term", "medium_...
f = open("/tmp/code/new-evil-script.py", "a") f.write("Conquer the universe!") f.close()
from import_hedgehogs import * def convert_excel_to_csv(excel_file): wb = load_workbook(excel_file) counter = 0 for sheet in wb.sheetnames: sh = wb[sheet] csv_file = open(str(counter)+'.csv', 'w') wr = csv.writer(csv_file, quoting=csv.QUOTE_ALL) for rows in range(sh.nrows): ...
# -*- coding: utf-8 -*- """ Created on Wed Feb 17 21:45:43 2021 @author: Henrique """ import json import numpy as np import pandas as pd import pkg_resources import dash import dash_core_components as dcc from dash.dependencies import Input, Output, State, MATCH, ALL from dash.exceptions import PreventUpdate import p...
class MaxSubArrayBottomUp: def __init__(self, prices): self.prices = prices self.sub_solutions = [None] * len(prices) for i in range(len(self.prices)): if i == 0: self.sub_solutions[i] = self.prices[0] else: self.sub_solutions[i] = max(...
from enum import Enum from crossword import NumberedCell class Word: """ Abstract base class for Across and Down words """ # Enumerated values of word direction. # Safer to use these, like Word.ACROSS and Word.DOWN, instead of string values ACROSS = "A" DOWN = "D" def __init__(self, puzzle...
import numpy as np from numpy.core.umath_tests import inner1d from scipy.ndimage.filters import gaussian_filter from scipy.ndimage.interpolation import map_coordinates def image_histogram_equalization(image, number_bins=256): '''histogram equalization the image ''' # from http://www.janeriksolem.net/2009/...
from .metric import * from .losses import *