content
stringlengths
5
1.05M
#!/usr/bin/env python """ Copyright (C) 2014 Ivan Gregor 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 the License, or (at your option) any later version. ...
# We start out with an integer. wealth = 1000000000 # We convert it to a string formatted the way we want. formatted = format(wealth, ',d') # Print it out! print(formatted)
from django.urls import path from . import views urlpatterns = [ path('',views.get_room,name='chat'), path('public/',views.get_public_room,name='public-chat'), path('student/<int:pk>',views.chat_with_Student,name='teacher-chat'), path('<str:room_name>/', views.room, name='room'), ]
# coding=utf-8 # Copyright 2018 The Tensor2Tensor 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 applicable...
from django.shortcuts import render, redirect from django.contrib.auth import update_session_auth_hash from django.contrib.auth.decorators import login_required from django.http import * from django.urls import reverse from apps.accounts.models import * from apps.accounts.forms import * @login_required def login_redi...
"""Contains pytest fixtures.""" import os import pytest from ase_notebook.data import get_example_atoms @pytest.fixture(scope="function") def get_test_filepath(): """Fixture to return a path to a file in the raw files folder.""" dirpath = os.path.abspath(os.path.dirname(__file__)) def _get_test_filepat...
class Order: def __init__(self, order_number, customer_id, lp_number, category, pickup_date, return_date, price, insurance, actual_return_date): self.__order_number = order_number self.__customer_id = customer_id self.__lp_number = lp_number self.__category = category se...
from moderate.queue.serialization import pack, unpack class BaseQueue(object): def put(self, name, *args, **kw): pass def get(self): pass def pack(self, name, args, kw): return pack({'name': name, 'args': args, 'kw': kw}) def unpack(self, msg): return unpack(msg)
# Generated by Django 2.2.3 on 2019-07-17 18:32 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('products', '0001_initial'), ] operations = [ migrations.CreateModel( name='...
from pathlib import Path import sys TEST_MODE = bool(len(sys.argv) > 1 and sys.argv[1] == "test") def phase1(v): return next(v[i]*v[j] for i in range(len(v)) for j in range(i,len(v)) if v[i]+v[j] == 2020) def phase2(v): return next(v[i]*v[j]*v[k] for i in range(len(v)) for j in range(i,len(v)) for k in range...
# -*- coding: utf-8 -*- # # Copyright 2018 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://aws.amazon.com/apache2.0/ # # or i...
from __future__ import unicode_literals from django.apps import AppConfig class WagerConfig(AppConfig): name = 'Wager'
# -*- coding: utf-8 -*- """This code is a part of Hydra Toolkit .. module:: hydratk.extensions.datagen.translation.en :platform: Unix :synopsis: English language translation for Datagen extension .. moduleauthor:: Petr Czaderna <[email protected]> """ language = { 'name': 'English', 'ISO-639-1': 'en' } ...
from django.contrib import admin from .models import City,Question # Register your models here. admin.site.register(City) admin.site.register(Question)
import time import random import string from vectorai import ViClient, ViCollectionClient class TempClient: def __init__(self, client, collection_name: str=None): self.client = client if isinstance(client, ViClient): self.collection_name = collection_name elif isinstance(client,...
# # voice-skill-sdk # # (C) 2020, Deutsche Telekom AG # # This file is distributed under the terms of the MIT license. # For details see the file LICENSE in the top directory. # # # Caching functions to facilitate L1/L2 caching # from .decorators import CallCache # noqa: F401
#!/usr/bin/env python # -*- coding: utf-8 -*- """ test_pympa-core ------------ Tests for `pympa-core` models module. """ import os import shutil import unittest from pympa_core import models class TestPympa_core(unittest.TestCase): def setUp(self): pass def test_something(self): pass ...
#!/usr/bin/env python # -*- coding: utf-8 -*- from gBlockChain.lib.database import db, Model, Column, relationship, reference_col class Host(Model): __tablename__ = 'host' id = Column(db.Integer, primary_key=True, autoincrement=True, unique=True) ip = Column(db.String(64), nullable=False, index=True, uni...
# Select an element # Open yaml file with entity types # If parameters are already present, set values according to yaml input import sys import clr import System import rpw import yaml import pprint from System.Collections.Generic import * clr.AddReference("RevitAPI") from Autodesk.Revit.DB import * from rpw.ui.fo...
from flask import Blueprint, request, render_template, redirect, url_for, g, session authorization = Blueprint("authorization", __name__) @authorization.route("/login", methods=["GET", "POST"]) def login(): # Redirect if already logged in if g.user: return redirect("/") if request.method == "GET...
from django.apps import apps from lru import LRU from .. import settings from . import RecordMetadata, Record, get_offset_backend from botocore.exceptions import ClientError import boto3 import collections import logging import time logger = logging.getLogger(__name__) class KinesisBase(object): _client = None ...
import codecs import datetime import os import pathlib import time from ctd_processing import cnv_column_info from ctd_processing import exceptions from ctd_processing.cnv.cnv_header import CNVheader from ctd_processing.cnv.cnv_parameter import CNVparameter class CNVfileInfo: def __init__(self, file_path): ...
import unittest from pycoin.cmds import ku from pycoin.coins.bitcoin.networks import BitcoinMainnet from .ToolTest import ToolTest # BRAIN DAMAGE Key = BitcoinMainnet.ui._key_class class KuTest(ToolTest): @classmethod def setUpClass(cls): cls.parser = ku.create_parser() cls.tool_name = "k...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import os import sys import unittest # Add the repo root to the beginning of the Python module path. # Even if the user has installed family_tree locally, the version # next to the test file will be used. sys.path = [os.path.join(os.path.dirname(__file__), '..')] + sys.p...
"""Macro support for P65. P65 Macros are cached SequenceNodes with arguments set via .alias commands and prevented from escaping with .scope and .scend commands.""" import sys import Ophis.IR as IR import Ophis.CmdLine as Cmd import Ophis.Errors as Err macros = {} currentname = None currentbody = None def newMa...
#!/usr/bin/env python # # Copyright (c) 2018 [email protected] and others. # # All rights reserved. This program and the accompanying materials # are made available under the terms of the Apache License, Version 2.0 # which accompanies this distribution, and is available at # http://www.apache.org/licenses/LI...
"""Base class for undirected graphs. The Graph class allows any hashable object as a node and can associate key/value attribute pairs with each undirected edge. Self-loops are allowed but multiple edges are not (see MultiGraph). For directed graphs see DiGraph and MultiDiGraph. """ # Copyright (C) 2004-2011 by # ...
from django.urls import path from playgroup import views app_name = 'playgroup' urlpatterns = [ path('', views.dashboard, name='dashboard'), path('create/', views.manage, name="create"), path('<int:group_id>/', views.details, name="details"), path('<int:group_id>/edit/', views.manage, name="edit"), ...
def validate_base_sequence(base_sequence, RNAflag=False): """Return True if the string base_sequence contains only upper- or lowercase T (or U, if RNAflag), C, A, G characters, otherwise False""" seq = base_sequence.upper() result = len(seq) == (seq.count('A') + seq.count('U' if RNAflag else 'T') + ...
import sys var.verboseRead = 0 var.warnReadNoFile = 0 var.nexus_allowAllDigitNames = True # put it somewhere else read(sys.argv[2]) d = Data() d.compoSummary() read(sys.argv[3]) t = var.trees[0] t.data = d c1 = t.newComp(free=1, spec='empirical') c2 = t.newComp(free=1, spec='empirical') # Put the c1 comp on all th...
from hydroDL.data import gageII from hydroDL import kPath from hydroDL.app import waterQuality from hydroDL.post import axplot import pandas as pd import numpy as np import time import os import matplotlib.pyplot as plt import importlib # read slope data dirCQ = os.path.join(kPath.dirWQ, 'C-Q') mapFolder = os.path.joi...
#!/usr/bin/env python # Copyright 2017 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 # # Unle...
#!/usr/bin/python # -*- coding: utf-8 -*- def xpath_soup(element): """ Generate xpath from BeautifulSoup4 element :param element: BeautifulSoup4 element. :type element: bs4.element.Tag or bs4.element.NavigableString :return: xpath as string :rtype: str Usage: >>> import bs4 ...
# NeoPixel Color Picker demo - wire up some NeoPixels and set their color # using Adafruit Bluefruit Connect App on your phone import time import busio import board from digitalio import DigitalInOut from adafruit_bluefruitspi import BluefruitSPI import neopixel ADVERT_NAME = b"BlinkaNeoLamp" # 16 neopixels on a dig...
"""Module that holds success messages template""" audit_messages = { 'created': 'created a new {} ', 'retrieved': 'retrieved {} successfully', 'updated': 'updated {} with id {} ', 'deleted': 'deleted favorite things with id {}' }
from allennlp.modules.token_embedders.pretrained_transformer_mismatched_embedder import PretrainedTransformerMismatchedEmbedder from allennlp.modules.token_embedders.token_embedder import TokenEmbedder from typing import Optional, Dict, Any, List, Union from .adapters import Adapter, AdapterBertLayer import torch.nn as...
import os import xml.etree.ElementTree as ET import sqlite3 import tempfile from . import (AError, ACommandLineTool, AOS) _commandlineTool = ACommandLineTool.CommandLineTool('svn') _commandlineTool.checkExistence() def getCommandLineTool(): return _commandlineTool class SVN_Error(AError.Error): ...
import json from lbrynet.testcase import CommandTestCase class ResolveCommand(CommandTestCase): async def test_resolve(self): tx = await self.channel_create('@abc', '0.01') channel_id = tx['outputs'][0]['claim_id'] # resolving a channel @abc response = await self.resolve('lbry://...
from bot_settings import welcome_channel_id, default_role, server_id from discord.utils import get import logging async def on_ready(client): logging.getLogger('BotEvents').debug(f"Logged in successfully as {client.user}!") async def on_message(client,message): content = message.content if message.content els...
# -*- coding: utf-8 -*- import math import time # 绘图设置 # ELAPSED_DAY_CHAR='H' # 已流逝天数的绘图字符 # ELAPSED_DAY_CHAR="\u2591" # 已流逝天数的绘图字符 ░ # ELAPSED_DAY_CHAR="\u2764" # 已流逝天数的绘图字符 ❤ ELAPSED_DAY_CHAR="\u2665" # 已流逝天数的绘图字符 ♥ # REMAIN_DAY_CHAR='\u002D' ...
""" Python Daemonizing helper Originally based on code Copyright (C) 2005 Chad J. Schroeder but now heavily modified to allow a function to be daemonized and return for bitbake use by Richard Purdie """ import os import sys import io import traceback def createDaemon(function, logfile): """ Detach a process ...
#! /usr/bin/env python import unittest import os, sys sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from src.kronprod import * class TestKronSparse(unittest.TestCase): # add global stuff here def setUp(self): return def testOnes(self): A1 = [ np.array([[1.,...
from rest_pandas import ( PandasView, PandasUnstackedSerializer, PandasScatterSerializer, PandasBoxplotSerializer, ) from .serializers import EventResultSerializer from .filters import ChartFilterBackend import swapper EventResult = swapper.load_model('results', 'EventResult') class ChartView(PandasView): ...
from django.contrib.gis.db import models from django.conf import settings from django.contrib.gis.measure import A, D from lingcod.unit_converter.models import length_in_display_units, area_in_display_units class SpacingPoint(models.Model): name = models.CharField(max_length=200) geometry = models.PointField(s...
import random from sys import maxsize from math import sqrt, inf RANDOM_SEED = 1208 LARGE_NUMBER = inf EQUAL_THRESHOLD = 0.0001 class KMeans: def __init__(self, n_clusters): self.n_clusters = n_clusters def initialCentroidsRandomPick(self, X, k): """ :return centroids: dict - {0:[...
import logging import sanic.request import sanic.response from sanic_json_logging import setup_json_logging app = sanic.Sanic("app1") setup_json_logging(app, context_var="test1") logger = logging.getLogger("root") async def log(): logger.info("some informational message") @app.route("/endpoint1", methods=["...
from django.apps import AppConfig class DBConfig(AppConfig): name = 'db'
import numpy as np import dace as dc import sympy as sp # N, R, K, M1, M2 = (dc.symbol(s) for s in ('N', 'R', 'K', 'M1', 'M2')) R, K, M1, M2 = (dc.symbol(s, dtype=dc.int64, integer=True, positive=True) for s in ('R', 'K', 'M1', 'M2')) N = R**K # TODO: Temporary fix! @dc.program def mgrid1(X: dc.uint...
import os import sys import click @click.command() @click.argument("state_file", type=str) @click.argument("exit_1", type=int) @click.argument("exit_2", type=int) @click.argument("exit_3", type=int) def main( state_file: str, exit_1: int, exit_2: int, exit_3: int, ): if not os.path.exists(state_f...
str1 = 'I love Python Programming' str2 = 'Python' str3 = 'Java' print(f'"{str1}" contains "{str2}" = {str2 in str1}') print(f'"{str1}" contains "{str2.lower()}" = {str2.lower() in str1}') print(f'"{str1}" contains "{str3}" = {str3 in str1}') if str2 in str1: print(f'"{str1}" contains "{str2}"') else: print...
from amaranth.back import verilog from register_bank import RegisterBank top = RegisterBank() with open("register_bank.v", "w") as f: f.write(verilog.convert(top, ports=[top.reset, top.regNum0, top.regNum1, top.wRegNum, top.writeEnable, top.dataOut0, top.dataOut1, top.dataIn]))
import sys sys.path.append("yam") import config def test_config_man(): config.setConfigFolder("./") assert config.getConfigFolder() == "./" config.setProperty("test-property", "test-value") assert config.getProperty("test-property") == "test-value" config.deleteConfigFile()
import numpy as np from sklearn.metrics.scorer import _BaseScorer from solnml.components.utils.constants import CLS_TASKS, IMG_CLS from solnml.datasets.base_dl_dataset import DLDataset from solnml.components.evaluators.base_dl_evaluator import get_estimator_with_parameters from solnml.components.ensemble.dl_ensemble.b...
# -*- coding: utf-8 -*- __version__ = '$Id$' import family # The wikispecies family class Family(family.WikimediaFamily): def __init__(self): super(Family, self).__init__() self.name = 'species' self.langs = { 'species': 'species.wikimedia.org', } self.names...
# 用摄像头捕获视频 # 先创建一个VideoCapture对象. 它的参数可以实设备的索引号 # 或是一个视频文件. # Cap.isOpen检查是否初始化成功 # cap.get(propId)可以获取是平的一些参数信息, propId从0~18代表视频的一个属性 # cap.set(propId, value)可以修改视频属性 import numpy as np import cv2 cap = cv2.VideoCapture(0) # Define the codec and create VideoWriter object # 利用cv2.VideoWriter_fourcc(*’XVID’)定义视频格式,然后创...
#!/usr/bin/python # coding=UTF-8 from math import log import os import re import sys from comparator import calculate_errors from tokenizer import Tokenizer from trainer import Trainer from estimator import Estimator verbose = False class Model(): def __init__(self, tokenizer, estimator): self.tokenizer = toke...
import pygame import time import sys from grid import grid # Colors used black = (0, 0, 0) white = (255, 255, 255) gray = (192, 192, 192) MARGIN = 5 # Margin between cells WIDTH = 20 # Cell width HEIGHT = 20 # Cell height ROW = 40 # Random row count COL = 40 # Random column count speed_delta = 10 max_speed = 125 ...
#!/usr/bin/env python #-*- coding: utf-8 -*- import sys from lxml import etree, html def run(bk): count = 0 print('start') for (file_id, _) in bk.text_iter(): modified = True html_original = bk.readfile(file_id) doc = html.fromstring(html_original.encode("utf-8")) ...
from output.models.ms_data.particles.particles_r020_xsd.particles_r020 import ( B, R, Doc, ) from output.models.ms_data.particles.particles_r020_xsd.particles_r020_imp import ( ImpElem1, ImpElem2, ) __all__ = [ "B", "R", "Doc", "ImpElem1", "ImpElem2", ]
from django.contrib import admin from tastie.models import SimpleRest admin.site.register(SimpleRest)
import mysql.connector import csv mydb = mysql.connector.connect( host="localhost", user="root", password="admin123", db="db_TEST" ) mycursor = mydb.cursor() # mycursor.execute("CREATE TABLE customers (customerid INT AUTO_INCREMENT PRIMARY KEY,firstname TEXT,lastname TEXT,companyname TEXT,billingaddres...
__author__ = 'renderle' def scrambleForecast(fc1, fc2): return (fc1 + fc2) /2;
# Generated by Django 3.1.13 on 2022-01-07 16:23 import django.db.models.deletion from django.db import migrations from django.db import models class Migration(migrations.Migration): dependencies = [("api", "0051_reapply_partition_trigger_func")] operations = [ migrations.AddField( model...
import itertools from computation.split_and_merge.domain_centers.calculate_domain_centers import calculate_domain_centers as calc_dom from computation.split_and_merge.util.pos_bool_type import PosBoolType from computation.split_and_merge.util.numpy_extension.find_index_of_first_element_not_equivalent import find_index...
# -*- coding: utf-8 -*- __all__ = ["Zero", "Constant"] import theano.tensor as tt class Zero: def __call__(self, x): return tt.zeros_like(x) class Constant: def __init__(self, value): self.value = tt.as_tensor_variable(value) def __call__(self, x): return tt.zeros_like(x) + se...
# http://soundjax.com/beep-1.html # structure the class # define what the cla<ss does # add comments # # add to string - complexity # impr: # same ingredient twice # keeping sorted the steps # --------------------------------------------------------------- # Imports # ---------------------------------------------...
import os import math import argparse import torch import torch.nn as nn import torch.backends.cudnn as cudnn from PIL import Image import numpy as np from torch.autograd import Variable from torchvision.utils import save_image from torch.utils.data import DataLoader from data.dataloader import ErasingData, ErasingData...
import glob import numpy as np import pandas as pd import re import matplotlib.pyplot as plt import matplotlib import matplotlib.colors as mcolors import random matplotlib.rc('text', usetex=True) matplotlib.rc('font', size=15) matplotlib.rc('legend', fontsize=14) def read_metrics(filename: str): opinions = [] ...
import torch import torch.nn as nn import numpy as np import sys import disc_span_parser """ class MarginLoss(nn.Module): def __init__(self, complexity, ill_nested, reduction="mean"): super(MarginLoss, self).__init__() self.complexity = complexity self.ill_nested = ill_nested self.m...
import collections # Keep indexes of good candidates in deque d. # The indexes in d are from the current window, they're increasing, # and their corresponding nums are decreasing. # Then the first deque element is the index of the largest window value. # For each index i: # 1. Pop (from the end) indexes of smaller e...
from distutils.core import setup, Extension import numpy module =Extension('FunNorm', sources = ['FunNorm.c'],libraries=['gsl','gslcblas','m'],include_dirs=[numpy.get_include()+'/numpy']) setup(name = 'Funciones creadas por Nestor: Extensiones de C/Python', version = '1.0', ext_modules = [module])
# Copyright 2013-2014, Simon Kennedy, [email protected] # # Part of 'hiss' the asynchronous notification library import hashlib from os import urandom from binascii import hexlify, unhexlify from hiss.exception import ValidationError DEFAULT_HASH_ALGORITHM = 'SHA256' class HashInfo(): """Records the hash...
from .BroadcastInfo import BroadcastInfo from .ConcatInfo import ConcatInfo from .PadInfo import PadInfo from .ReductionInfo import ReductionInfo from .ReshapeInfo import ReshapeInfo from .SliceInfo import SliceInfo from .StackInfo import StackInfo from .TileInfo import TileInfo from .TransposeInfo import TransposeInfo...
from sqlite_random import Sqlite_random
from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.chrome.options import Options def test_home(): options = Options() options.add_argument("--no-sandbox") options.add_argument("--headless") driver = webdriver.Chrome(chrome_options=options) driver.get("http://162...
import sys read = sys.stdin.buffer.read readline = sys.stdin.buffer.readline readlines = sys.stdin.buffer.readlines sys.setrecursionlimit(10 ** 7) n = int(readline()) s = read().rstrip().decode() cnt = 0 for i in range(1000): num = str(i).zfill(3) idx = -1 for m in num: idx = s.find(m, idx + 1) ...
# Do not import ir in this Module import typing if typing.TYPE_CHECKING: from spydrnet.ir.element import Element from spydrnet.ir.first_class_element import FirstClassElement from spydrnet.ir.netlist import Netlist from spydrnet.ir.library import Library from spydrnet.ir.definition import Definitio...
import unittest from parameterized import parameterized_class from pyfx import PyfxApp from pyfx.config import parse from pyfx.model import DataSourceType from tests.fixtures import FIXTURES_DIR from tests.fixtures.keys import split @parameterized_class([ {"config_file": "configs/basic.yml"}, {"config_file"...
"""Definitions (types) for style sheets.""" from enum import Enum from typing import Sequence, Tuple, TypedDict, Union Color = Tuple[float, float, float, float] # RGBA Padding = Tuple[float, float, float, float] # top/right/bottom/left Number = Union[int, float] class TextAlign(Enum): LEFT = "left" CENTER ...
from shapy.framework.commands import * from .stats import *
from unittest import TestCase import numpy as np from model_parameters.KaonParametersFixedRhoOmega import KaonParametersFixedRhoOmega, Parameter class TestModelParametersFixedRhoOmega(TestCase): def setUp(self): self.parameters = KaonParametersFixedRhoOmega( 0.5, 0.6, 0.7, 0.8, 0...
from django.test import TestCase from curious import model_registry from curious.query import Query from curious_tests.models import Blog, Entry, Author from curious_tests import assertQueryResultsEqual import curious_tests.models class TestQueryJoins(TestCase): def setUp(self): names = ('Databases', 'Relationa...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = "Christian Heider Nielsen" __doc__ = r""" Created on 18/03/2020 """ __all__ = ["get_host_ip"] def get_host_ip() -> str: """Get host ip. Returns: str: The obtained ip. UNKNOWN if failed.""" import socket try: ...
''' Schema of behavioral information. ''' import re import os from datetime import datetime import pathlib import numpy as np import scipy.io as sio import datajoint as dj import h5py as h5 from . import reference, subject, utilities, stimulation, acquisition, analysis schema = dj.schema(dj.config['custom'].get('dat...
#!/usr/bin/env python # -*- coding: utf-8 -*- """Base Taxon of SpeciesEvolver.""" from abc import ABC, abstractmethod class Taxon(ABC): """Base Taxon of SpeciesEvolver. A SpeciesEvolver Taxon represents a group of organisms. Examples of the kind of group represented by a subclass include an analog group ...
""" Copyright (c) 2019 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 applicable law or agreed to in writing,...
""" Simple Facebook Echo bot: Respond with exactly what it receives Standalone version """ import sys, json, traceback, requests from flask import Flask, request application = Flask(__name__) app = application PAT = 'replace_your_own_PAT_here' @app.route('/', methods=['GET']) def handle_verification(): print "Ha...
from pwnypack.bytecode import *
from peewee import * from .PWDatabase import PWDatabase from neocore.Cryptography.Crypto import Crypto from neocore.UInt256 import UInt256 from neocore.UInt160 import UInt160 import binascii from neo.Wallets.Coin import CoinReference from neo.Blockchain import GetBlockchain class ModelBase(Model): class Meta: ...
import numpy as np import numpy.linalg as la #This function calculates the SVD and returns S' a resized version of S matrix def SVD(matrix, dimension): A = matrix r = dimension AT = A.T AAT = np.dot(A, AT) evalues1, evectors1 = la.eig(AAT) #calculate out the S matrix nonzero = eva...
import pytest from pyupgrade._data import Settings from pyupgrade._main import _fix_plugins @pytest.mark.parametrize( ('s', 'version'), ( pytest.param( 'foo(*[i for i in bar])\n', (2, 7), id='Not Python3+', ), pytest.param( '2*3', ...
from sklearn.compose import ColumnTransformer from sklearn.pipeline import Pipeline from sklearn.preprocessing import OneHotEncoder def get_column_names_from_ColumnTransformer(column_transformer, orig_cols, verbose=False): col_name = [] # the last transformer is ColumnTransformer's 'remainder' for transfor...
#!/usr/bin/env python # =========================================================================== # Copyright 2017 `Tung Thanh Le` # Email: ttungl at gmail dot com # # Heterogeneous Architecture Configurations Generator for Multi2Sim simulator # (aka, `HeteroArchGen4M2S`) # `HeteroArchGen4M2S` is free software, whic...
from datetime import datetime, timedelta from django.test import TestCase from corehq.apps.domain.shortcuts import create_domain from corehq.apps.enterprise.tests.utils import create_enterprise_permissions from corehq.apps.users.dbaccessors import delete_all_users from corehq.apps.users.models import WebUser from cor...
from nested_diff import Differ, handlers def test_diff_handlers(): class FloatHanler(handlers.TypeHandler): handled_type = float def __init__(self, precision=2, *args, **kwargs): super().__init__(*args, **kwargs) self.precision = precision def diff(self, differ, a...
from datetime import datetime, timezone from typing import Any, Dict, Iterable, List, Optional, Set from dateutil.rrule import DAILY, rrule from sqlalchemy import not_, or_ from sqlalchemy.orm.attributes import InstrumentedAttribute from sqlalchemy.sql import ClauseElement from athenian.api.controllers.logical_repos ...
## Backreference re.sub(r'\[(\d+)\]', r'\1', '[52] apples and [31] mangoes') re.sub(r'(_)?_', r'\1', '_foo_ __123__ _baz_') re.sub(r'(\w+),(\w+)', r'\2,\1', 'good,bad 42,24') re.sub(r'\[(\d+)\]', r'(\15)', '[52] apples and [31] mangoes') re.sub(r'\[(\d+)\]', r'(\g<1>5)', '[52] apples and [31] mangoes') re.sub(r'\...
# pylint: disable = import-error, invalid-name """General model classes""" from org.kie.kogito.explainability import ( TestUtils as _TestUtils, Config as _Config, ) from java.util import ArrayList, List TestUtils = _TestUtils Config = _Config def toJList(pyList): """Convert a Python list to a Java ArrayL...
''' read_bovespa.py - helper functions to interpret records from BOVESPA's historical data. Raw data available in http://http://www.bmfbovespa.com.br ''' import pandas as pd from collections import OrderedDict from datetime import date from datetime import datetime as dt from typing import Any, Callable, Iterator, Uni...
from urllib.request import urlopen from bs4 import BeautifulSoup import ssl ctx = ssl.create_default_context() ctx.check_hostname = False ctx.verify_mode = ssl.CERT_NONE url = input('Enter URL - ') count = int(input('Enter iterations:')) position = int(input('Enter position:')) for _ in range(count+1): html = ur...