filename
stringlengths
13
19
text
stringlengths
134
1.04M
the-stack_0_1033
import numpy as np """ This file creates a grid of stars for the HRD plot """ metallicities = [0.0001, 0.001, 0.01, 0.01416] # make a small grid for all metallicities with open("grid.txt", "w") as f: masses = np.round(np.logspace(np.log10(0.1), np.log10(150.0), 500), 3) grid_lines = ["--initial-mass {} --me...
the-stack_0_1034
import statsapi import pandas as pd # logging import logging logger = logging.getLogger('statsapi') logger.setLevel(logging.DEBUG) rootLogger = logging.getLogger() rootLogger.setLevel(logging.DEBUG) ch = logging.StreamHandler() formatter = logging.Formatter("%(asctime)s - %(levelname)8s - %(name)s(%(thread)s) - %(mess...
the-stack_0_1036
#! /usr/bin/python # coding: utf-8 # Copyright 2018 IBM 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 re...
the-stack_0_1037
# Copyright The Cloud Custodian Authors. # SPDX-License-Identifier: Apache-2.0 # # PYTHON_ARGCOMPLETE_OK (Must be in first 1024 bytes, so if tab completion # is failing, move this above the license) import argcomplete import argparse import importlib import logging import os import pdb import sys import traceback fro...
the-stack_0_1038
#!/usr/bin/env python ''' cchecker_web.reverse_proxy Ruthlessly stolen from: http://flask.pocoo.org/snippets/35/ ''' class ReverseProxied(object): '''Wrap the application in this middleware and configure the front-end server to add these headers, to let you quietly bind this to a URL other than / a...
the-stack_0_1039
__usage__ = """ To run tests locally: python tests/test_arpack.py [-l<int>] [-v<int>] """ import threading import itertools import sys import platform import numpy as np from numpy.testing import (assert_allclose, assert_array_almost_equal_nulp, assert_equal, assert_array_equal, suppres...
the-stack_0_1042
# # Copyright (c) 2008-2015 Citrix 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 applicable l...
the-stack_0_1044
# -*- coding: utf-8 -*- ''' Outputter for displaying results of state runs ============================================== The return data from the Highstate command is a standard data structure which is parsed by the highstate outputter to deliver a clean and readable set of information about the HighState run on mini...
the-stack_0_1046
import logging import os from unittest.mock import create_autospec, patch import boto3 import botocore import botocore.client import botocore.config import pytest import awswrangler as wr from awswrangler._config import apply_configs from awswrangler.s3._fs import open_s3_object logging.getLogger("awswrangler").setL...
the-stack_0_1047
import unittest from cloudrail.dev_tools.rule_test_utils import create_empty_entity from cloudrail.knowledge.context.aws.cloudfront.cloud_front_distribution_list import CloudFrontDistribution, ViewerCertificate from cloudrail.knowledge.context.aws.aws_environment_context import AwsEnvironmentContext from cloudrail.kno...
the-stack_0_1049
# coding: utf-8 """ Contain solution for the python/numpy training """ __authors__ = ["Pierre Knobel", "Jerome Kieffer", "Henri Payno", "Armando Sole", "Valentin Valls", "Thomas Vincent"] __date__ = "18/09/2018" __license__ = "MIT" import inspect import numpy def show(exercice_name): function ...
the-stack_0_1053
import torch from torch.utils.data import DataLoader import isao def main(): train_dataset = isao.Isao('./data/preprocessed', use_label=True, resize=(64,64)) train_dataloader = DataLoader(train_dataset, batch_size=1000, shuffle=True) for batch in train_dataloader: print(batch['img'].shape...
the-stack_0_1055
#!/usr/bin/env python """This module provides utility classes and functions for threading/multiprocessing""" from __future__ import print_function from .logutil import GetLogger from . import sfdefaults as _sfdefaults from . import SolidFireError, SFTimeoutError import atexit import fcntl as _fcntl import functools a...
the-stack_0_1057
from typing import Sequence import editdistance import pytorch_lightning as pl import torch class CharacterErrorRate(pl.metrics.Metric): """Character error rate metric, computed using Levenshtein distance.""" def __init__(self, ignore_tokens: Sequence[int], *args): super().__init__(*args) se...
the-stack_0_1059
import sys import time if sys.version_info < (3, 6, 5): sys.exit('RoboMaster Sdk requires Python 3.6.5 or later') import logging logger_name = "multi_robot" logger = logging.getLogger(logger_name) logger.setLevel(logging.ERROR) fmt = "%(asctime)-15s %(levelname)s %(filename)s:%(lineno)d %(message)s" formatter = ...
the-stack_0_1060
import logging from time import time from threading import Timer from contextlib import contextmanager import progressbar import numpy as np from pybar.analysis.analyze_raw_data import AnalyzeRawData from pybar.fei4.register_utils import invert_pixel_mask, make_box_pixel_mask_from_col_row from pybar.fei4_run_base imp...
the-stack_0_1061
# -------------------------------------------------------- # Deformable Convolutional Networks # Copyright (c) 2017 Microsoft # Licensed under The MIT License [see LICENSE for details] # Modified by Zheng Zhang # -------------------------------------------------------- # Based on: # MX-RCNN # Copyright (c) 2016 by Cont...
the-stack_0_1062
#!/usr/bin/env python3 # Copyright (c) 2018-2019 The Bitcoin Core developers # Copyright (c) 2017 The Raven Core developers # Copyright (c) 2018 The Rito Core developers # Copyright (c) 2020 The KringleProjectCoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http:...
the-stack_0_1063
import sys import colorsys import pygame.gfxdraw try: import pygame except ImportError: print("To simulate a unicorn HAT on your computer, please pip install pygame") class UnicornHatSim(object): def __init__(self, width, height, rotation_offset = 0): # Compat with old library self.AUTO = ...
the-stack_0_1065
#!/usr/bin/env python """These are standard aff4 objects.""" import hashlib import re import StringIO from grr.lib import aff4 from grr.lib import data_store from grr.lib import flow from grr.lib import rdfvalue from grr.lib import utils class VFSDirectory(aff4.AFF4Volume): """This represents a directory from th...
the-stack_0_1066
import warnings import mmcv import numpy as np import pycocotools.mask as maskUtils import torch from mmcv.runner import load_checkpoint from mmdet.core import get_classes from mmdet.datasets import to_tensor from mmdet.datasets.transforms import ImageTransform from mmdet.models import build_detector from imantics im...
the-stack_0_1067
from os import path from pandas.api.types import CategoricalDtype from numpy import mean, concatenate, ones, sqrt, zeros, arange from scipy.stats import norm from sklearn.impute import SimpleImputer from sklearn.linear_model import LinearRegression from sklearn.ensemble import RandomForestClassifier from attack_models...
the-stack_0_1068
from django.db import IntegrityError from django.shortcuts import render,redirect, get_object_or_404 from django.contrib.auth.models import User from django.contrib.auth.decorators import login_required from django.contrib.auth import login, logout, authenticate from django.contrib.auth.forms import UserCreationForm, A...
the-stack_0_1069
import sc2, sys from __init__ import run_ladder_game from sc2 import Race, Difficulty from sc2.player import Bot, Computer # Load bot from example_bot import ExampleBot bot = Bot(Race.Terran, ExampleBot()) # Start game if __name__ == '__main__': if "--LadderServer" in sys.argv: # Ladder game started by La...
the-stack_0_1070
# # Copyright (c) 2021, NVIDIA 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 ...
the-stack_0_1071
# # Collective Knowledge: CK-powered Caffe crowdbenchmarking (very early prototyping) # # See CK LICENSE.txt for licensing details # See CK COPYRIGHT.txt for copyright details # # Developer: Grigori Fursin, Grigori.Fursin@cTuning.org, http://fursin.net # cfg={} # Will be updated by CK (meta description of this module...
the-stack_0_1072
from collections import namedtuple from enum import Enum from string import ascii_lowercase import numpy as np # ABC for the Decision class class Decision(object): ENUM = None FIELDS = ('decision_id') # suggestion for subclassing # FIELDS = super().FIELDS + ('target_idxs',) # etc. # An Elli...
the-stack_0_1073
# coding=utf-8 # Copyright 2020 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_0_1074
from pprint import pformat stack=[] def print_stack_before_operation(f): def method(*args, **kwargs): print("Current stack:", pformat(stack)) f(*args, **kwargs) print("After operation:", pformat(stack)) return method def print_operation_name_and_parameter(f): def method(*args, **k...
the-stack_0_1075
#!/usr/bin/env python import os import time import json import argparse import pprint as pp import numpy as np import pandas as pd import pickle from tqdm import tqdm from datetime import timedelta import torch from torch.utils.data import DataLoader import torch.optim as optim from nets.attention_model import Atten...
the-stack_0_1076
# Copyright 2019. ThingsBoard # # 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 ...
the-stack_0_1077
"""The error checking chain is a list of status word (sw1, sw2) error check strategies. __author__ = "http://www.gemalto.com" Copyright 2001-2012 gemalto Author: Jean-Daniel Aussel, mailto:jean-daniel.aussel@gemalto.com This file is part of pyscard. pyscard is free software; you can redistribute it and/or modify it...
the-stack_0_1078
# -*- coding: utf-8 -*- """The `Common Sense Knowledge Graph <https://github.com/usc-isi-i2/cskg>`_ dataset. - GitHub Repository: https://github.com/usc-isi-i2/cskg - Paper: https://arxiv.org/pdf/2012.11490.pdf - Data download: https://zenodo.org/record/4331372/files/cskg.tsv.gz """ import logging from .base import...
the-stack_0_1080
"""tasks_2_2 URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.2/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-bas...
the-stack_0_1081
# Copyright 2014 eBay Inc. # # Author: Ron Rickard <rrickard@ebaysf.com> # # 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_0_1083
# 1: +train 2: -train 3: +test 4:-test # http://pongor.itk.ppke.hu/benchmark/#/Benchmark_data_formats import numpy as np import os os.system('mkdir Index') mat = np.empty([1357,55], int) infile = open('./CAST.txt') lines = infile.read().splitlines() for i in range(len(lines)): line = lines[i] a = line[7:].spl...
the-stack_0_1084
from datetime import datetime from datetime import timedelta import json import requests from requests_toolbelt import MultipartEncoder import traceback import types import modules.botconfig as config import modules.botlog as botlog agentSession = requests.Session() agentSession.cert = config.BotCertificate agentV2S...
the-stack_0_1086
# -*- coding: UTF-8 -*- import unittest from ytcc.download import Download from unittest.mock import patch, mock_open, Mock from test.fixtures.webvtt import FIXTURE_WEBVTT from colorama import Fore, Style from ytcc.download import NoCaptionsException def red(input): return Fore.RED + input + Style.RESET_ALL cl...
the-stack_0_1088
#!/usr/bin/env python # -*- coding: utf-8 -*- import logging from .base import BaseHandler from ..dao.notice_dao import NoticeDao logger = logging.getLogger('nebula.api.batch_notice') class BatchBWListHandler(BaseHandler): def get(self): """ 批量查询当前未过期黑白灰名单的值集合接口. @API summary...
the-stack_0_1089
"""This component provides Switches for Unifi Protect.""" import logging from homeassistant.components.switch import SwitchEntity from homeassistant.config_entries import ConfigEntry from homeassistant.const import ATTR_ATTRIBUTION from homeassistant.core import HomeAssistant from .const import ( ATTR_DEVICE_MOD...
the-stack_0_1090
import urllib from calcrepo import info from calcrepo import repo name = "ticalc" url = "http://www.ticalc.org/" enabled = True class TicalcRepository(repo.CalcRepository): def formatDownloadUrl(self, url): return "http://www.ticalc.org" + url def updateRepoIndexes(self, verbose=False): self.printd("Rea...
the-stack_0_1092
import sys input = sys.stdin.readline sys.setrecursionlimit(10 ** 7) n = int(input()) a = [0] + list(map(int, input().split())) + [0] diff = [0] * (n + 1) for i in range(n + 1): diff[i] = abs(a[i+1] - a[i]) ans = sum(diff) for i in range(1, n + 1): print(ans - (diff[i-1] + diff[i]) + (abs(a[i+1] - a[i-1])))
the-stack_0_1094
import _plotly_utils.basevalidators class DtickrangeValidator(_plotly_utils.basevalidators.InfoArrayValidator): def __init__( self, plotly_name="dtickrange", parent_name="scatter3d.marker.colorbar.tickformatstop", **kwargs ): super(DtickrangeValidator, self).__init__( ...
the-stack_0_1096
# -*- coding: utf-8 -*- ######################################################################### # Copyright (C) 2011 Cameron Franc and Marc Masdeu # # Distributed under the terms of the GNU General Public License (GPL) # # http://www.gnu.org/licenses/ ##########################################...
the-stack_0_1097
# coding: utf-8 # # Copyright 2019 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 in the "lice...
the-stack_0_1099
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modif...
the-stack_0_1100
import logging from typing import Any, MutableMapping, Optional from cloudformation_cli_python_lib import ( Action, HandlerErrorCode, OperationStatus, ProgressEvent, Resource, SessionProxy, ) from datadog_api_client.v1 import ApiException from datadog_api_client.v1.api.monitors_api import Monit...
the-stack_0_1102
from floodsystem.flood import stations_highest_rel_level from floodsystem.stationdata import build_station_list , update_water_levels from floodsystem.datafetcher import fetch_latest_water_level_data, fetch_station_data stations = build_station_list() N=10 update_water_levels(stations) stations_high_threat ...
the-stack_0_1103
# placeholder definition for an access pattern object, can be passed as input class PatternConfig: def __init__(self, exp_name="default", #name or ID benchmark_name="test", #if this is a specific benchmark, include here read_freq=-1, #number of reads/s total_reads=-1, #total numb...
the-stack_0_1105
import datetime import re from io import BytesIO from unittest.mock import create_autospec, call, Mock import pytest from sap.aibus.dar.client.base_client import BaseClient from sap.aibus.dar.client.data_manager_client import DataManagerClient from sap.aibus.dar.client.exceptions import ModelAlreadyExists, DARHTTPExc...
the-stack_0_1107
from os import getenv from dotenv import load_dotenv load_dotenv() UNSPLASH_ACCESS_KEY = getenv('UNSPLASH_ACCESS_KEY') FLICKR_KEY = getenv('FLICKR_KEY') FLICKR_SECRET = getenv('FLICKR_SECRET') ALBUM_FONTS = [ 'Comforter Brush', 'Praise', 'Dancing Script', 'Estonia', ] ARTIST_FONTS = [ 'Bebas Neue...
the-stack_0_1109
import asyncio import sys import time from datetime import datetime from decimal import Decimal from typing import Callable, List, Optional, Tuple, Dict import aiohttp from peas.cmds.units import units from peas.rpc.wallet_rpc_client import WalletRpcClient from peas.server.start_wallet import SERVICE_NAME from peas.u...
the-stack_0_1110
__author__ = 'marble_xu' import os import json from abc import abstractmethod import pygame as pg from . import constants as c class State(): def __init__(self): self.start_time = 0.0 self.current_time = 0.0 self.done = False self.next = None self.persist = {} @abs...
the-stack_0_1111
from datetime import date from silverstrike.models import Account, Split, Transaction def create_transaction(title, src, dst, amount, type, date=date.today(), category=None): t = Transaction.objects.create(title=title, date=date, transaction_type=type, src=src, dst=dst, amount=...
the-stack_0_1113
# # 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...
the-stack_0_1115
# -*- coding: utf-8 -*- ''' Provide external pillar data from RethinkDB .. versionadded:: 2018.3.0 :depends: rethinkdb (on the salt-master) salt master rethinkdb configuration =================================== These variables must be configured in your master configuration file. * ``rethinkdb.host`` - The Ret...
the-stack_0_1116
# Copyright 2013 OpenStack Foundation # # 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...
the-stack_0_1117
import numpy as np import pickle import os import time import torch import torch.nn as nn import torchvision import torchvision.transforms as transforms from PIL import Image class ImageWriter(object): def __init__(self, data_dir, dataset, unnormalizer): self.data_dir = data_dir self.dataset = dat...
the-stack_0_1118
from bolinette import types, data from bolinette.data import ext, mapping from bolinette.data.defaults.entities import Role @ext.model("role") class RoleModel(data.Model[Role]): id = types.defs.Column(types.db.Integer, primary_key=True) name = types.defs.Column( types.db.String, unique=True, nullable=...
the-stack_0_1119
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class FetchOptions(Package): """Mock package with fetch_options.""" homepage = "http://www....
the-stack_0_1121
# # Copyright (c) 2018 nexB Inc. and others. All rights reserved. # http://nexb.com and https://github.com/nexB/scancode-toolkit/ # The ScanCode software is licensed under the Apache License version 2.0. # Data generated with ScanCode require an acknowledgment. # ScanCode is a trademark of nexB Inc. # # You may not use...
the-stack_0_1122
import os import sys # Try to mute and then load TensorFlow and Keras # Muting seems to not work lately on Linux in any way os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' stdin = sys.stdin sys.stdin = open(os.devnull, 'w') stderr = sys.stderr sys.stderr = open(os.devnull, 'w') import tensorflow as tf tf.logging.set_verbosit...
the-stack_0_1124
def longestPalindrome(s: str) -> str: max_length = 0 start = 0 for i in range(len(s)): for j in range(i + max_length, len(s)): length = j - i + 1 if i + length > len(s): break if length > max_length and isPalin(s, i, j + 1): start = i ...
the-stack_0_1125
# Copyright The OpenTelemetry 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 law or agreed to in ...
the-stack_0_1128
from setuptools import setup, find_packages from os import path here = path.abspath(path.dirname(__file__)) setup( name='monitor', version='0.1.0', description='Monitor component of BIGSEA Asperathos framework', url='', author='Igor Natanael, Roberto Nascimento Jr.', author_email='', ...
the-stack_0_1130
import unittest import os, sys sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '../..'))) import autosar ### BEGIN TEST DATA def apply_test_data(ws): package=ws.createPackage("DataType", role="DataType") package.createSubPackage("DataTypeSemantics", role="CompuMethod") pa...
the-stack_0_1131
# API v1 import logging from django.conf import settings from django.contrib import auth, messages from django.contrib.auth.decorators import login_required from django.shortcuts import get_object_or_404 from django.urls import reverse, reverse_lazy from django.utils.decorators import method_decorator from django.view...
the-stack_0_1133
# from https://github.com/ajbrock/BigGAN-PyTorch (MIT license) # some modifications in class Generator and G_D # new class "Unet_Discriminator" based on original class "Discriminator" import numpy as np import math import functools import torch import torch.nn as nn from torch.nn import init import torch.optim as opti...
the-stack_0_1135
import agate import decimal import unittest from unittest import mock import dbt.flags as flags from dbt.task.debug import DebugTask from dbt.adapters.base.query_headers import MacroQueryStringSetter from dbt.adapters.postgres import PostgresAdapter from dbt.adapters.postgres import Plugin as PostgresPlugin from dbt....
the-stack_0_1138
from __future__ import print_function, division import matplotlib import logging from sys import stdout matplotlib.use('Agg') # Must be before importing matplotlib.pyplot or pylab! from neuralnilm import (Net, RealApplianceSource, BLSTMLayer, DimshuffleLayer, Bidirectio...
the-stack_0_1142
# Copyright 2015 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 in the "license" file accompa...
the-stack_0_1143
# coding: utf-8 """ CRM cards Allows an app to extend the CRM UI by surfacing custom cards in the sidebar of record pages. These cards are defined up-front as part of app configuration, then populated by external data fetch requests when the record page is accessed by a user. # noqa: E501 The version of...
the-stack_0_1144
"""Utilities for including Python state in TensorFlow checkpoints.""" # 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 # # ...
the-stack_0_1145
from typing import List, Optional import aiosqlite from chiadoge.types.blockchain_format.coin import Coin from chiadoge.types.blockchain_format.sized_bytes import bytes32 from chiadoge.types.coin_record import CoinRecord from chiadoge.types.full_block import FullBlock from chiadoge.util.db_wrapper import DBWrapper fr...
the-stack_0_1148
from __future__ import absolute_import import os, itertools, json, numpy, pickle from ann_benchmarks.plotting.metrics import all_metrics as metrics import matplotlib.pyplot as plt def create_pointset(data, xn, yn): xm, ym = (metrics[xn], metrics[yn]) rev = ym["worst"] < 0 data.sort(key=lambda t: t[-1], re...
the-stack_0_1151
from starflyer import Handler, redirect, asjson, AttributeMapper from camper import BaseForm, db, BaseHandler, is_admin, logged_in, ensure_barcamp from wtforms import * from sfext.babel import T from .base import BarcampBaseHandler, LocationNotFound import uuid class ParticipantDataEditForm(BaseForm): """form for...
the-stack_0_1152
# -*- coding: utf-8 -*- """Compound ZIP file plugin related functions and classes for testing.""" import zipfile from plaso.containers import sessions from plaso.storage.fake import writer as fake_writer from tests.parsers import test_lib class CompoundZIPPluginTestCase(test_lib.ParserTestCase): """Compound ZIP ...
the-stack_0_1153
#predicting-house-prices.py #Day 6: Multiple Linear Regression: Predicting House Prices #Intro to Statistics #By derekhh #Apr 2, 2016 from sklearn import linear_model f, n = input().split() f = int(f) n = int(n) clf = linear_model.LinearRegression() x_train = [] y_train = [] for i in range(n): tmp = [float(n) f...
the-stack_0_1157
address_resolver_abi = [ { "inputs": [ { "internalType": "address", "name": "_owner", "type": "address" } ], "payable": False, "stateMutability": "nonpayable", "type": "constructor", "signature": "constructor" }, { "anonymous": False, "inputs": [ { "indexed": False, "inte...
the-stack_0_1159
"""Time series estimator that predicts using the naive forecasting approach.""" import numpy as np from rayml.model_family import ModelFamily from rayml.pipelines.components.estimators import Estimator from rayml.pipelines.components.transformers import TimeSeriesFeaturizer from rayml.problem_types import ProblemTypes...
the-stack_0_1160
# Copyright (c) 2016 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 # # Unless requir...
the-stack_0_1161
import random import string import cherrypy @cherrypy.expose class StringGeneratorWebService(object): @cherrypy.tools.accept(media='text/plain') def GET(self): return cherrypy.session['mystring'] def POST(self, length=8): some_string = ''.join(random.sample(string.hexdigits, int(length)...
the-stack_0_1163
from unittest import TestCase from tests import get_data from pytezos.michelson.converter import build_schema, decode_micheline, encode_micheline, micheline_to_michelson class StorageTestKT1MqrUiQg3GyZ3wTEGJ3LqFn5Xz4jy4bLZU(TestCase): @classmethod def setUpClass(cls): cls.maxDiff = None cls....
the-stack_0_1164
# Time: O(n) # Space: O(1) # inplace solution class Solution(object): def addSpaces(self, s, spaces): """ :type s: str :type spaces: List[int] :rtype: str """ prev = len(s) s = list(s) s.extend([None]*len(spaces)) for i in reversed(xrange(len...
the-stack_0_1165
#!/usr/bin/env python3 # Copyright (c) 2013-2020 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # # Generate seeds.txt from Pieter's DNS seeder # import re import sys import dns.resolver import collect...
the-stack_0_1166
# -*- coding: utf-8 -*- # File: parallel.py import atexit import pickle import errno import traceback import itertools import multiprocessing as mp import os import sys import uuid import weakref from contextlib import contextmanager import zmq from six.moves import queue, range from ..utils import logger from ..util...
the-stack_0_1167
from core.himesis import Himesis import uuid class HSon2Man(Himesis): def __init__(self): """ Creates the himesis graph representing the DSLTrans rule Son2Man. """ # Flag this instance as compiled now self.is_compiled = True super(HSon2Man, self)....
the-stack_0_1168
""" This module lets you practice one form of the ACCUMULATOR pattern, namely, the "IN GRAPHICS" form which features: -- DRAWING OBJECTS via ACCUMULATING positions and/or sizes, as in: x = x + pixels Additionally, it emphasizes that you must ** DO A CONCRETE EXAMPLE BY HAND ** before you can implement a sol...
the-stack_0_1169
# -*- coding: utf-8 -*- import datetime import os from pyvirtualdisplay import Display from selenium import webdriver import constants # Choose and configure the browser of your choice def get_browser(): # # These work on Mac # return webdriver.Chrome() # return webdriver.Firefox() # On Linux you n...
the-stack_0_1171
from enum import Enum from typing import TYPE_CHECKING, Callable, Dict, Optional from prompt_toolkit.clipboard import ClipboardData if TYPE_CHECKING: from .key_processor import KeyPressEvent from .key_bindings.vi import TextObject __all__ = [ 'InputMode', 'CharacterFind', 'ViState', ] class Inp...
the-stack_0_1176
#!/usr/bin/env python3 #-*- coding: utf-8 -*- #pylint: disable-msg=W0122,R0914,R0912 """ File : pkg.py Author : Valentin Kuznetsov <vkuznet@gmail.com> Description: AbstractGenerator class provides basic functionality to generate CMSSW class from given template """ from __future__ import print_function # sys...
the-stack_0_1177
# vim: set fenc=utf8 ts=4 sw=4 et : import os import io import json import unittest from shlex import split from .testcase import TestCase from pdml2flow.conf import Conf import pdml2flow TEST_DIR_PDML2FLOW="test/pdml2flow_tests/" TEST_DIR_PDML2FRAME="test/pdml2frame_tests/" class TestSystem(TestCase): def rea...
the-stack_0_1178
from models.image_classification import alexnet, vgg16, resnet class ModelSelector: @staticmethod def get_model(model_name): model_mux = { "alexnet": alexnet.AlexNet, "vgg16": vgg16.VGG16, "resnet": resnet.ResNet, } return model_mux.get(model_name, "...
the-stack_0_1179
#!/usr/bin/env python # _*_ coding:utf-8 _*_ # auth: clsn # by: covid-19 # date 20200328 #********************** import requests import json import pymysql import datetime import sys # 解决 python2 中文报错 reload(sys) sys.setdefaultencoding('utf8') now_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') # 数据库配置 ...
the-stack_0_1181
def encrypt(text,key): output = "" for i in range(len(text)): char = text[i] if (char.isupper()): output += chr((ord(char) + key - 65) % 26 + 65) elif (char.islower()): output += chr((ord(char) + key - 97) % 26 + 97) else: output += char...
the-stack_0_1182
import json from base64 import b64decode, b64encode import numpy as np from numpy.lib.format import dtype_to_descr, descr_to_dtype def default(obj): if isinstance(obj, (np.ndarray, np.generic)): return { '__numpy__': b64encode(obj.data if obj.flags.c_contiguous else obj.tobytes()).decode('asc...
the-stack_0_1183
from django.core.management import BaseCommand from wagtail.images import get_image_model from cms.tagging import TAG_ENRICHMENT, I18N_TAGS from core.utils import overwrite_media_domain class Command(BaseCommand): def handle(self, *args, **options): get_image_model().objects.filter(tags__name='delete', ...
the-stack_0_1184
import json from datacite import schema40 from osf.metadata import utils from website.settings import DOMAIN serializer_registry = {} def register(schema_id): """Register classes into serializer_registry""" def decorator(cls): serializer_registry[schema_id] = cls return cls return decorat...
the-stack_0_1185
# -*- coding: utf-8 -*- """ Data conversion utility for numpy ===================================== Convert cytoscape.js style graphs from numpy object. http://www.numpy.org """ import numpy as np def from_ndarray(data, name=None, labels=None, directed=False, weighted=False): """ This method is converter to...
the-stack_0_1186
""" CLI command for "deploy" command """ import logging import os import click from samcli.cli.cli_config_file import TomlProvider, configuration_option from samcli.cli.main import aws_creds_options, common_options, pass_context, print_cmdline_args from samcli.commands._utils.cdk_support_decorators import unsupported...