filename
stringlengths
13
19
text
stringlengths
134
1.04M
the-stack_106_18177
import tensorflow as tf import numpy as np import tensorflow as tf import numpy as np import os from model.tf_l0_models import * class New_Start_L0_Mnist( object ): def __init__(self, opts): self.sess = tf.Session() self.opts = opts self.init() self.saver = tf.train.Save...
the-stack_106_18178
from PyQt5 import uic from PyQt5.QtCore import pyqtSlot from PyQt5.QtWidgets import QApplication, QWidget, QMessageBox import sys import modeller class MainWindow(QWidget): def __init__(self, parent=None): super(MainWindow, self).__init__(parent) self._ui = uic.loadUi("window.ui", self) @prop...
the-stack_106_18180
# Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 """Tests the format of human readable logs. It checks the response of the API configuration calls and the logs that show up in the configured logging FIFO. """ import json import os import re from time impor...
the-stack_106_18183
import os from io import StringIO from unittest.mock import Mock import pytest from doit.exceptions import InvalidCommand from doit import reporter, runner from doit.cmd_run import Run from tests.conftest import tasks_sample, CmdFactory class TestCmdRun(object): def testProcessRun(self, dependency1, depfile_nam...
the-stack_106_18184
a = [] abc = int(input("Enter the number of terms")) for i in range(abc): b = int(input()) a.append(b) n = len(a) for i in range(n): for j in range(0,n-i-1): if(a[j]>a[j+1]): a[j],a[j+1] = a[j+1],a[j] print(a)
the-stack_106_18186
"""Storage handers.""" # pylint: disable=import-outside-toplevel from homeassistant.helpers.json import JSONEncoder from custom_components.hacs.const import VERSION_STORAGE from .logger import getLogger _LOGGER = getLogger() def get_store_for_key(hass, key): """Create a Store object for the key.""" key = ke...
the-stack_106_18187
import os import intake import pandas as pd import pytest import xarray as xr from intake_esm import config from intake_esm.core import ESMMetadataStoreCatalog here = os.path.abspath(os.path.dirname(__file__)) def test_build_collection(): with config.set({'database-directory': './tests/test_collections'}): ...
the-stack_106_18189
"""Tests for the Config Entry Flow helper.""" from unittest.mock import patch, Mock import pytest from homeassistant import config_entries, data_entry_flow, setup from homeassistant.helpers import config_entry_flow from tests.common import ( MockConfigEntry, MockModule, mock_coro, mock_integration) @pytest.fixt...
the-stack_106_18191
import numpy as np import scipy import time import torch import torch.nn.functional as F from texttable import Texttable def get_n_params(model): pp=0 for p in list(model.parameters()): nn=1 for s in list(p.size()): nn = nn*s pp += nn return pp def args_print(args): ...
the-stack_106_18193
# Copyright (c) 2013 - 2015 EMC Corporation. # 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...
the-stack_106_18194
import importlib.abc import importlib.machinery import importlib.util import os import platform import shutil import sys import tempfile import time import weakref from pathlib import Path import pytest from jinja2 import Environment from jinja2 import loaders from jinja2 import PackageLoader from jinja2.exceptions i...
the-stack_106_18195
import matplotlib.pyplot as plt import matplotlib as mpl import matplotlib.ticker as mticker import matplotlib.ticker as mtick import numpy as np import os from copy import copy import pdb import pandas as pd plt.rcParams['font.size'] = 14 plt.rcParams['axes.linewidth'] = 2 # Usage: summarize.print_num_v...
the-stack_106_18196
# Copyright 2014 The Oppia Authors. 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 ...
the-stack_106_18197
"""Tests for the mfa setup flow.""" from openpeerpower import data_entry_flow from openpeerpower.auth import auth_manager_from_config from openpeerpower.components.auth import mfa_setup_flow from openpeerpower.setup import async_setup_component from tests.common import CLIENT_ID, MockUser, ensure_auth_manager_loaded ...
the-stack_106_18199
"""Setup for the tqdl package.""" # !/usr/bin/env python # -*- coding: utf-8 -*- import setuptools import versioneer INSTALL_REQUIRES = ['requests', 'tqdm'] TEST_REQUIRES = [ # testing and coverage 'pytest', 'coverage', 'pytest-cov', # unmandatory dependencies of the package itself # NONE # to b...
the-stack_106_18200
import torch import torch.nn as nn from collections import defaultdict THRESHOLD = 0.5 INIT_RANGE = 0.5 EPSILON = 1e-10 class Binarize(torch.autograd.Function): """Deterministic binarization.""" @staticmethod def forward(ctx, X): y = torch.where(X > 0, torch.ones_like(X), torch.zeros_like(X)) ...
the-stack_106_18201
#Take two lists, say for example these two: # a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] # b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] #and write a program that returns a list that contains only the elements that are common between the lists #(without duplicates). Make sure your program works on two lists of dif...
the-stack_106_18203
import logging import os from dataclasses import dataclass from typing import Any, Dict, List from urllib.parse import urljoin import requests from eth_utils import to_checksum_address logger = logging.getLogger(__name__) @dataclass class CoinMarketCapToken: id: int # CoinMarketCap id name: str symbol:...
the-stack_106_18204
""" HDF5 Pricing File Format ------------------------ At the top level, the file is keyed by country (to support regional files containing multiple countries). Within each country, there are 4 subgroups: ``/data`` ^^^^^^^^^ Each field (OHLCV) is stored in a dataset as a 2D array, with a row per sid and a column per s...
the-stack_106_18205
import os file = os.path.dirname(__file__) def Cadastrar(i1, i2, c3): arquivo = open(f"{os.path.join(file, './Contas.txt')}", "a") nome = i1.input.get().strip() senha = i2.input.get().strip() if senha == "" and nome == "": c3.caixa["text"] = "Os campos Usuário e Senha devem ser preenchidos" elif senha == "" an...
the-stack_106_18206
from otree.api import ( models, widgets, BaseConstants, BaseSubsession, BaseGroup, BasePlayer, Currency as c, currency_range ) import random author = 'Charlotte' doc = """ Two simultaneous Prisoner's dilemma/donation game between two players with two different payoffs. For the pairings to mat...
the-stack_106_18207
import io import os from collections import OrderedDict from pathlib import Path from typing import Optional import yaml from serverless.aws.features.stepfunctions import StepFunctions from serverless.service.configuration import Configuration from serverless.service.functions import FunctionManager from serverless.s...
the-stack_106_18212
#!/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 # # Unless required...
the-stack_106_18213
import datetime from Poem.api.models import MyAPIKey from Poem.api.views import NotFound from Poem.poem import models as poem_models from django.db.models import Q from django_tenants.utils import get_public_schema_name from rest_framework import status from rest_framework.authentication import SessionAuthentication f...
the-stack_106_18214
# Copyright (c) IPython Development Team. # Distributed under the terms of the Modified BSD License. import json import os import warnings from unittest import mock import nose.tools as nt from IPython.core import display from IPython.core.getipython import get_ipython from IPython.utils.io import capture_output fr...
the-stack_106_18215
"""Subgraph structure that belongs to the Optimum-Path Forest. """ import numpy as np import opfython.stream.loader as loader import opfython.stream.parser as p import opfython.utils.constants as c import opfython.utils.exception as e import opfython.utils.logging as l from opfython.core import Node logger = l.get_l...
the-stack_106_18216
# 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, software # distributed under th...
the-stack_106_18217
"""Support for Netatmo energy devices (relays, thermostats and valves).""" from __future__ import annotations import logging from abc import ABC from collections import defaultdict from typing import Any from .auth import AbstractAsyncAuth, NetatmoOAuth2 from .exceptions import InvalidRoom, NoSchedule from .helpers i...
the-stack_106_18218
# coding: utf-8 """ Properties All HubSpot objects store data in default and custom properties. These endpoints provide access to read and modify object properties in HubSpot. # noqa: E501 The version of the OpenAPI document: v3 Generated by: https://openapi-generator.tech """ import six class O...
the-stack_106_18221
from bomber_monkey.utils.vector import Vector def test_equal(): v = Vector.create(2, 4) assert v == [2, 4] assert not v == [2, 5] assert not v == [3, 4] def test_add(): v1 = Vector.create(4, 6) v2 = Vector.create(3, 3) v3 = v1 + v2 assert v3 == [7, 9] def test_modify(): v = V...
the-stack_106_18222
import unittest import os import torch from tests.util import create_config, get_dataset_folder from kge import Dataset from kge.indexing import KvsAllIndex class TestDataset(unittest.TestCase): def setUp(self) -> None: self.dataset_name = "dataset_test" self.dataset_folder = get_dataset_folder(se...
the-stack_106_18223
# coding=utf-8 # Copyright 2021 The Google Research Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicab...
the-stack_106_18224
from dateutil.parser import parserinfo, parser class BrParserInfo(parserinfo): JUMP = [" ", ".", ",", ";", "-", "/", "'", "as", "a", "e", "de", "do", "da", "em"] WEEKDAYS = [("Seg", "Segunda"), ("Ter", "Terça"), ("Qua", "Quarta"), ("Qui", "Quinta"),...
the-stack_106_18226
#!/usr/bin/env python3 # Copyright (c) 2015-2017 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test basic for Creating tokens .""" from test_framework.test_framework import BitcoinTestFramework fro...
the-stack_106_18228
# Python program to mail merger # Names are in the file names.txt # Body of the mail is in body.txt # open names.txt for reading with open("names.txt", 'r', encoding='utf-8') as names_file: # open body.txt for reading with open("body.txt", 'r', encoding='utf-8') as body_file: # read entire content of...
the-stack_106_18229
from itertools import product from typing import TYPE_CHECKING, Optional, Union, Tuple, Callable from gym import spaces import numpy as np from highway_env import utils from highway_env.vehicle.dynamics import BicycleVehicle from highway_env.vehicle.kinematics import Vehicle from highway_env.vehicle.controller import ...
the-stack_106_18230
#!/usr/bin/env python3 import filecmp # https://stackoverflow.com/questions/254350 import os import platform # https://stackoverflow.com/questions/1854 import shutil # Copy following files: # If there are changes: # target/release/raspberry-web -> /usr/local/bin/ # raspberry-web-db/raspberry-web.sqlite -> /...
the-stack_106_18233
from ..utils.utils import * #============================================================================== """ Implementation of quick sort algorithm. This modules provides two functions for sorting a list using quicksort algorithm. """ def quick_sort(a): """Sorts given list using Quicksort algorithm. Args...
the-stack_106_18234
import _plotly_utils.basevalidators class NameValidator(_plotly_utils.basevalidators.StringValidator): def __init__(self, plotly_name="name", parent_name="splom.dimension", **kwargs): super(NameValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, ...
the-stack_106_18235
import numpy as np import matplotlib.pyplot as plt import sympy as sp def onehat(x, u): if x < u - 1: return 0 if x > u + 1: return 0 if x < u: return x - u + 1 if x > u: return -x + u + 1 def onehat_vec(x, u): z1 = x < u - 1 z2 = x > u + 1 z = ~np.logical_...
the-stack_106_18236
#!/usr/bin/env python3 import numpy as np # linear algebra import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv) import glob import swifter from tqdm.auto import tqdm tqdm.pandas() from bs4 import BeautifulSoup from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer import os os.makedirs(...
the-stack_106_18239
import copy import os import numpy as np import torch import torch.nn as nn from reinforcement_learning.policy import LearningPolicy from reinforcement_learning.replay_buffer import ReplayBuffer # https://lilianweng.github.io/lil-log/2018/04/08/policy-gradient-algorithms.html class EpisodeBuffers: def __init_...
the-stack_106_18240
from dacy.augmenters.keyboard import Keyboard, qwerty_da_array from dacy.augmenters import create_keyboard_augmenter from spacy.lang.da import Danish from spacy.training import Example def test_Keyboard(): kb = Keyboard(keyboard_array = qwerty_da_array) assert kb.coordinate("q") == (1, 0) assert kb.is_sh...
the-stack_106_18241
""" Document Library Copyright: 2011-2021 (c) Sahana Software Foundation 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-stack_106_18242
# -*- coding: utf-8 -*- import os from setuptools import setup, find_packages def prerelease_local_scheme(version): """Return local scheme version unless building on master in CircleCI. This function returns the local scheme version number (e.g. 0.0.0.dev<N>+g<HASH>) unless building on CircleCI for a ...
the-stack_106_18243
# encoding: utf-8 import codecs import os from xlwt import * import xlrd import numpy as np import xgboost as xgb from xgboost import plot_importance import time import pickle import matplotlib.pyplot as plt from matplotlib.backends.backend_pdf import PdfPages from pylab import mpl mpl.rcParams['font.sans-serif'] = ['...
the-stack_106_18244
from threading import Thread from typing import Optional from torch.utils.data.dataset import IterableDataset as TorchIterableDataset import persia.env as env from persia.ctx import cnt_ctx from persia.logger import get_default_logger from persia.prelude import ( PyPersiaBatchDataChannel, PyPersiaBatchDataRe...
the-stack_106_18245
""" Convert Datasets for the Step Placement models into datasets for the Step Generation model. """ import os import numpy as np from sklearn.metrics import f1_score import h5py import warnings from deepSM import SMData from deepSM import SMDUtils from deepSM import StepPlacement from deepSM import utils from deepSM ...
the-stack_106_18247
# Copyright (c) 2015 Infoblox 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 require...
the-stack_106_18248
# -*- coding: utf-8 -*- """Cisco Identity Services Engine PAN HA API wrapper. Copyright (c) 2021 Cisco and/or its affiliates. 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, ...
the-stack_106_18251
import scrapy from ..items import Mobile class AmazonScraper(scrapy.Spider): name = "amazon_scraper" # How many pages you want to scrape no_of_pages = 1 # Headers to fix 503 service unavailable error # Spoof headers to force servers to think that request coming from browser ;) headers = {'Use...
the-stack_106_18254
from pathlib import Path import pandas as pd def structure_id_path_to_string(structure_id_path): """ Given a path (as a list of structure ids) to a specific structure, return as a string of "/" separated structure ids Parameters ---------- structure_id_path : list list of ints defining...
the-stack_106_18255
from .Scraper import Scraper from .ConnectionScraper import ConnectionScraper import json from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By from selenium.common.exceptions import TimeoutException, NoSuchEl...
the-stack_106_18257
#!/usr/bin/env python """cert_util.py: X509 certificate parsing utility. Usage: cert_util.py <command> [flags] [cert_file ...] Known commands: print: print information about the certificates in given files Each file must contain either one or more PEM-encoded certificates, or a single DER certificate. F...
the-stack_106_18258
# -*- coding: utf-8 -*- # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and contributors # For license information, please see license.txt from __future__ import unicode_literals import frappe from frappe import _ from frappe.utils import flt, cstr from frappe.model.mapper import get_mapped_doc from frappe.model.d...
the-stack_106_18259
from swampdragon import route_handler from swampdragon.route_handler import BaseRouter class ChatRouter(BaseRouter): route_name = 'chat-route' valid_verbs = ['chat', 'subscribe'] def get_subscription_channels(self, **kwargs): return ['chatroom'] def chat(self, *args, **kwargs): error...
the-stack_106_18260
#!/usr/bin/python3 ####### # # Runs command line programs and then saves the output to a file # ####### import subprocess import sys ####### # A check to make sure that we aren't going to try to read from/write to something that doesn't exist if (len(sys.argv) != 4): print("Correct format is <program name> <...
the-stack_106_18261
import sys, yaml, os, pytz, pyaml, json, re from os.path import exists, join, isdir from subprocess import Popen, PIPE from copy import deepcopy from elasticsearch.helpers import scan if (sys.version_info > (3, 0)): PY3 = True string = str else: PY3 = False string = basestring Exception = Standard...
the-stack_106_18262
# The Raw ElasticSearch functions, no frills, just wrappers around the HTTP calls import requests, json, urllib from models import QueryBuilder class ESWireException(Exception): def __init__(self, value): self.value = value def __str__(self): return repr(self.value) ##########################...
the-stack_106_18263
#!/usr/bin/env python3 from reportlab.pdfgen.canvas import Canvas from reportlab.pdfbase.ttfonts import TTFont from reportlab.pdfbase import pdfmetrics from random import randint def printHeader(doc,topmargin=770, leftmargin=30): doc.drawString(leftmargin,topmargin,"Naam:________________________________") def pr...
the-stack_106_18264
__author__ = 'Aaron Yang' __email__ = 'byang971@usc.edu' __date__ = '6/29/2020 11:37 AM' def merge_dictionaries(a, b): return {**a, **b} a = { 'x': 1, 'y': 2} b = { 'y': 3, 'z': 4} print(merge_dictionaries(a, b)) # {'y': 3, 'x': 1, 'z': 4} def most_frequent(list): print(list.count(1)) # 3 return sorted(...
the-stack_106_18265
# Reference: https://github.com/RocketFlash/CAP_augmentation import cv2 import numpy as np import random from glob import glob import random # how to use: cap_aug(p=0.5, n_objects_range=[1, 3], glob_split='_', retry_iters=30, min_inter_area=10, glob_suffix='*.png')() # the pasted objects(images) glob path will be PAT...
the-stack_106_18266
import os import random import soundfile as sf import torch import yaml import json import argparse import pandas as pd from tqdm import tqdm from pprint import pprint from asteroid.metrics import get_metrics from asteroid.losses import PITLossWrapper, pairwise_neg_sisdr from asteroid.data.wham_dataset import WhamData...
the-stack_106_18269
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ ============= TAP plus ============= @author: Juan Carlos Segovia @contact: juan.carlos.segovia@sciops.esa.int European Space Astronomy Centre (ESAC) European Space Agency (ESA) Created on 30 jun. 2016 """ from astropy.extern import six try: ...
the-stack_106_18270
#!/usr/bin/env python3 # coding:utf-8 # $Id: tktest06a_array.py 1303 $ # SPDX-License-Identifier: BSD-2-Clause import tkinter as tk from tkinter import ttk root = tk.Tk() height = 5 width = 5 for i in range(height): #Rows for j in range(width): #Columns entrée = str((i, j)) b = tk.Canvas(root) ...
the-stack_106_18272
from urllib.parse import urljoin import graphene from django.conf import settings from ....product.templatetags.product_images import get_thumbnail from ...translations.enums import LanguageCodeEnum from ..enums import ( AccountErrorCode, AppErrorCode, AttributeErrorCode, ChannelErrorCode, Checkou...
the-stack_106_18276
import warnings import matplotlib.pyplot as plt import mmcv import torch from mmcv.parallel import collate, scatter from mmcv.runner import load_checkpoint from mmdet.core import get_classes from mmdet.datasets.pipelines import Compose from mmdet.models import build_detector from mmdet.ops import RoIAlign, RoIPool ...
the-stack_106_18277
import datetime import numpy import pandas from keras.models import Sequential from keras.layers import Dense from keras.wrappers.scikit_learn import KerasRegressor from sklearn.model_selection import cross_val_score from sklearn.model_selection import KFold # load dataset dataframe = pandas.read_csv("data/Car_sales.c...
the-stack_106_18278
# modify from https://github.com/rosinality/stylegan2-pytorch/blob/master/op/fused_act.py # noqa:E501 import torch import torch.nn.functional as F from torch import nn from torch.autograd import Function from ..utils import ext_loader ext_module = ext_loader.load_ext('_ext', ['fused_bias_leakyrelu']) class FusedBi...
the-stack_106_18279
# Copyright 2015 The TensorFlow Authors. 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 applica...
the-stack_106_18285
# Copyright (c) 2016 Red Hat, 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 require...
the-stack_106_18286
# Copyright 2006 James Tauber and contributors # Copyright (C) 2009 Luke Kenneth Casson Leighton <lkcl@lkcl.net> # # 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/...
the-stack_106_18287
""" Adapted from https://github.com/lukemelas/simple-bert """ import numpy as np from torch import nn from torch import Tensor from torch.nn import functional as F import torch def split_last(x, shape): "split the last dimension to giveTransformern shape" shape = list(shape) assert shape.count(-1) <= 1...
the-stack_106_18289
from django.shortcuts import render, get_object_or_404 from django.shortcuts import redirect from django.contrib.auth import authenticate, login, update_session_auth_hash from django.http import HttpResponse from django.shortcuts import render_to_response from django.template import RequestContext from django.contrib.a...
the-stack_106_18290
# Copyright (c) 2019 SAP SE or an SAP affiliate company. All rights reserved. This file is licensed # under the Apache Software License, v. 2 except as noted otherwise in the LICENSE file # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the Licens...
the-stack_106_18293
# utils.py # Copyright (C) 2008, 2009 Michael Trier (mtrier@gmail.com) and contributors # # This module is part of GitPython and is released under # the BSD License: http://www.opensource.org/licenses/bsd-license.php import contextlib from functools import wraps import getpass import logging import os import platform i...
the-stack_106_18294
#!/usr/bin/env python import auturing import argparse import os import sys import logging import numpy as np def main(): LAUNCHER_DIR = os.path.join(os.path.dirname(__file__)) PYCKAGE_RESOURCES_DIR = os.path.join(os.path.abspath(os.path.join(LAUNCHER_DIR,os.pardir)),"resources") parser = argparse.Argum...
the-stack_106_18300
import math import copy import numpy as np import torch import torch.nn as nn import torch.nn.functional as F class ASFormerMultiStageModel(nn.Module): def __init__(self,device, num_stages, num_layers, num_f_maps, dim, num_classes): super(ASFormerMultiStageModel, self).__init__() self.num_classes ...
the-stack_106_18302
# Copyright 2017 The TensorFlow Authors. 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 applica...
the-stack_106_18306
from tests import TestCase from src.masonite.mail import Mailable class Welcome(Mailable): def build(self): return ( self.to("idmann509@gmail.com") .subject("Masonite 4") .from_("joe@masoniteproject.com") .text("text from Masonite!") .html("<h1>H...
the-stack_106_18307
import re from .common import InfoExtractor from ..utils import ( float_or_none, ExtractorError, ) class UplynkIE(InfoExtractor): IE_NAME = 'uplynk' _VALID_URL = r'https?://.*?\.uplynk\.com/(?P<path>ext/[0-9a-f]{32}/(?P<external_id>[^/?&]+)|(?P<id>[0-9a-f]{32}))\.(?:m3u8|json)(?:.*?\bpbs=(?P<session_...
the-stack_106_18309
""" Record Arrays ============= Record arrays expose the fields of structured arrays as properties. Most commonly, ndarrays contain elements of a single type, e.g. floats, integers, bools etc. However, it is possible for elements to be combinations of these using structured types, such as:: >>> a = np.array([(1, 2...
the-stack_106_18310
# A user is presented with the text below. the program allows them to select an option to list all of their tasks, add a task to their list, delete a task, or quit the program. def main(): problem1() def getList(): print("Congratulations! You're running Superman's Task List program") print("What would...
the-stack_106_18313
from __future__ import print_function # Python 2/3 compatibility import boto3 from boto3.session import Session import json import decimal # Helper class to convert a DynamoDB item to JSON. # class DecimalEncoder(json.JSONEncoder): # def default(self, o): # if isinstance(o, decimal.Decimal): # ...
the-stack_106_18315
# -*- coding: utf-8 -*- R""" Created on Sun May 23 01:00:41 2021 @author: Christian """ from planesections import EulerBeam, OpenSeesAnalyzer, RecordOutput, plotMoment,plotShear import numpy as np import openseespy.opensees as op x = np.linspace(0,5,80) fixed = np.array([1,1,0.]) P = np.array([0.,1000.,0.]) q = np....
the-stack_106_18316
# String encodings and numeric representations import binascii import codecs import string from .types import ( is_string, is_text, ) def decode_hex(value): if not is_text(value): raise TypeError('Value must be an instance of str') return codecs.decode(remove_0x_prefix(value), 'hex') def e...
the-stack_106_18317
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import os # os.environ["CUDA_VISIBLE_DEVICES"] = "1" import sys import time from torch.optim.lr_scheduler import StepLR import torchvision.utils as vutils from lib.loss...
the-stack_106_18318
#!/usr/bin/env python3 # Copyright (c) 2018 The Axe Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. from test_framework.mininode import * from test_framework.test_framework import BitcoinTestFramework from test_fra...
the-stack_106_18319
# Load and prepare the dataset import nltk from nltk.corpus import movie_reviews from nltk.util import ngrams import random import sys import re from emoji import UNICODE_EMOJI from bisect import bisect_left import math from sklearn.metrics import classification_report from nltk.classify.scikitlearn import SklearnClass...
the-stack_106_18321
import inspect import logging import os import re import subprocess from typing import Dict, Any from pyhttpd.certs import CertificateSpec from pyhttpd.conf import HttpdConf from pyhttpd.env import HttpdTestEnv, HttpdTestSetup log = logging.getLogger(__name__) class H2TestSetup(HttpdTestSetup): def __init__(se...
the-stack_106_18322
#!/usr/bin/env python # MBUtil: a tool for MBTiles files # Supports importing, exporting, and more # # (c) Development Seed 2012 # Licensed under BSD # for additional reference on schema see: # https://github.com/mapbox/node-mbtiles/blob/master/lib/schema.sql import sqlite3, sys, logging, time, os, json, zlib, gzip,...
the-stack_106_18323
import ipaddress import json import logging import pytest import re import yaml from tests.common.fixtures.ptfhost_utils import ptf_portmap_file # lgtm[py/unused-import] from tests.common.helpers.assertions import pytest_assert, pytest_require from tests.common.mellanox_data import is_mellanox_device as isMellanoxD...
the-stack_106_18324
""" Deals with multipart POST requests. The code is adapted from the recipe found at : http://code.activestate.com/recipes/146306/ No author name was given. Author : Alexis Mignon (c) email : alexis.mignon@gmail.Com Date : 06/08/2011 """ import httplib import mimetypes import urlparse...
the-stack_106_18326
# Taks 04. Odd and Even Sum def odd_even_sum(digit_as_str): odd_nums = [int(x) for x in digit_as_str if not int(x) % 2 == 0] even_nums = [int(x) for x in digit_as_str if int(x) % 2 == 0] return sum(odd_nums), sum(even_nums) number_string = input() odd_sum, even_sum = odd_even_sum(number_string) print(f'O...
the-stack_106_18327
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
the-stack_106_18328
# Copyright 2018 The TensorFlow Authors. 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 applica...
the-stack_106_18329
from django.contrib.auth import get_user_model from django.urls import reverse from django.test import TestCase from rest_framework import status from rest_framework.test import APIClient from core.models import Tag from recipe.serializers import TagSerializer TAGS_URL = reverse('recipe:tag-list') class PublicTag...
the-stack_106_18331
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # MIT License. See license.txt from __future__ import unicode_literals, print_function import frappe import time from frappe import _, msgprint from frappe.utils import flt, cstr, now, get_datetime_str, file_lock from frappe.utils.background_jobs imp...
the-stack_106_18332
#!/usr/bin/env python3 import signal import traceback import sys import argparse from . import Logger, DefaultConfig, RedisConfig, NetworkConfig class Scripter: def __init__(self, log_dir=None, log_level=Logger.INFO, log_sysout_level=Logger.DEBUG, log_source=None): self.logger = Logger(log_dir=...
the-stack_106_18333
description = 'Verify the user can create a new page from the project page' pages = ['login', 'common', 'index', 'project_pages'] def setup(data): common.access_golem(data.env.url, data.env.admin) index.create_access_project('test') common.navigate_menu('Pages') def test(data)...