filename stringlengths 13 19 | text stringlengths 134 1.04M |
|---|---|
the-stack_106_31720 | # ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# Copyright (c) 2021. by Daniel Barrejon, UC3M. +
# All rights reserved. This file is part of the Shi-VAE, and is released under the +
# "MIT License Agreement". Please see the LICE... |
the-stack_106_31722 | # -*- coding:utf-8 -*-
# Copyright 2015 NEC Corporation. #
# #
# Licensed under the Apache License, Version 2.0 (the "License"); #
# you may not use this file except in compliance with the License... |
the-stack_106_31723 | #!/usr/bin/env python3
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
import torch
from flsim.common.pytest_helper import assertEqual, assertAlmostEqual
from flsim.utils.timing.trai... |
the-stack_106_31725 | """OPP WS2812 wing."""
import logging
from mpf.core.platform_batch_light_system import PlatformBatchLight
from mpf.platforms.opp.opp_rs232_intf import OppRs232Intf
class OPPNeopixelCard:
"""OPP Neopixel/WS2812 card."""
__slots__ = ["log", "chain_serial", "platform", "addr", "card_num", "num_pixels", "num_... |
the-stack_106_31726 | from dataclasses import replace
from typing import Any, Iterator, List
from unittest.mock import patch
import pytest
import black
from tests.util import (
DEFAULT_MODE,
PY36_VERSIONS,
THIS_DIR,
assert_format,
dump_to_stderr,
read_data,
)
SIMPLE_CASES: List[str] = [
"attribute_access_on_nu... |
the-stack_106_31728 | from discord.ext import commands
import asyncio
from cogs.utils import twitconn
from cogs.utils import checks
from discord.errors import Forbidden, InvalidArgument
import json, os, twitutils, linkutils, discordutils
class Streams:
bot = None
def __init__(self, bot):
self.bot = bot
... |
the-stack_106_31730 | #!/usr/bin/env python3
# -*-coding:utf-8-*-
# @Time : 2017/11/1 ~ 2019/9/1
# @Author : Allen Woo
import sys
from signal import signal, SIGCHLD, SIG_IGN
from pymongo.errors import OperationFailure
from apps.configs.config import CONFIG
from apps.configs.db_config import DB_CONFIG
from apps.core.db.config_mdb import Data... |
the-stack_106_31731 | """A wrapper for engaging with the THOR environment."""
import copy
import json
import os
import random
from .offline_controller_with_small_rotation import OfflineControllerWithSmallRotation
class Environment:
""" Abstraction of the ai2thor enviroment. """
def __init__(
self,
u... |
the-stack_106_31733 | from tensorflow.contrib.training import HParams
# Default hyperparameters
hparams = HParams(
# Comma-separated list of cleaners to run on text prior to training and eval. For non-English
# text, you may want to use "basic_cleaners" or "transliteration_cleaners".
cleaners="english_cleaners",
# If you o... |
the-stack_106_31735 | import os
import sys
try:
from setuptools import setup
except ImportError:
sys.exit('ERROR: setuptools is required.\n')
try: # for pip >= 10
from pip._internal.req import parse_requirements
except ImportError: # for pip <= 9.0.3
from pip.req import parse_requirements
# try:
# from pip.req import ... |
the-stack_106_31736 | from django.shortcuts import render
from django.http import HttpResponse, JsonResponse
from django.core import serializers
from .models import Event
from .serializers import EventSerializer
from django.db.models import Q
import datetime
def get_events(request):
startDate = request.GET.get('start')
endDate = r... |
the-stack_106_31737 | import wx
import wx.grid
import wx.lib.gizmos as gizmos
import CustomGridRenderer as cgr
import wx.propgrid as wxpg
import wx.lib.scrolledpanel as scrolled
import sqlite3
import time
import os
import typing
from typing import List
from typing import Union
from typing import Tuple
from typing import Dict
from typing imp... |
the-stack_106_31740 | import os
import pickle
import sqlite3
import subprocess
import tempfile
import warnings
from collections import defaultdict
from contextlib import closing
from typing import Any, Dict, List
import prefect
__all__ = ["AirflowTask", "AirflowTriggerDAG"]
def custom_query(db: str, query: str, *params: str) -> List:
... |
the-stack_106_31741 | from config import denoise_image_config as config
from pyimagesearch.denoising.helper import blur_and_threshold
from imutils import paths
import progressbar
import cv2
import random
train_paths = sorted(list(paths.list_images(config.TRAIN_PATH)))
cleaned_paths = sorted(list(paths.list_images(config.CLEANED_PATH)))
w... |
the-stack_106_31742 |
from importlib.abc import ExecutionLoader
from thingsboard_gateway.storage.sqlite.database import Database
from time import time, sleep
from queue import Queue
from thingsboard_gateway.storage.sqlite.database_request import DatabaseRequest
from thingsboard_gateway.storage.sqlite.database_action_type import DatabaseAc... |
the-stack_106_31744 | import random
import numpy as np
from fedot.core.log import default_log
from fedot.core.repository.tasks import Task, TaskTypesEnum, TsForecastingParams
from fedot.api.api_utils.presets import OperationsPreset
class ApiParams:
def __init__(self):
self.default_forecast_length = 30
self.api_params... |
the-stack_106_31745 | # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You
# may not use this file except in compliance with the License. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompan... |
the-stack_106_31746 | import datetime
from sqlalchemy import orm, types, Column, Table, ForeignKey, desc, or_
import ckan.model
import meta
import types as _types
import domain_object
__all__ = ['Activity', 'activity_table',
'ActivityDetail', 'activity_detail_table',
]
activity_table = Table(
'activity', meta.m... |
the-stack_106_31749 | #!/usr/bin/env python3
from collections import Counter
from copy import deepcopy
from itertools import chain, repeat
import sys
def get_layout(filename):
# adding floors lets us not worry about literal edge cases
with open(filename, "r") as ifile:
# add floor around each edge
layout = [["."] +... |
the-stack_106_31750 | """:mod:`asuka.service` --- Service interface
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
"""
import re
from .build import BaseBuild
from .instance import Instance
from .logger import LoggerProviderMixin
__all__ = 'DomainService', 'Service'
class Service(LoggerProviderMixin):
"""The inteface of services.
... |
the-stack_106_31752 | # SPDX-FileCopyrightText: 2021 Dan Halbert, written for Adafruit Industries
# SPDX-FileCopyrightText: Copyright (c) 2021 Adafruit Industries for Adafruit Industries LLC
#
# SPDX-License-Identifier: MIT
"""
`adafruit_ble_lywsd03mmc`
================================================================================
BLE Su... |
the-stack_106_31755 | # -*- encoding: utf-8 -*-
"""
Created by eniocc at 11/10/2020
"""
import os
import platform
class System:
@staticmethod
def detect_platform():
"""
Method to detect platform. Based on that result the methods can change
:return: plat: A string contains the platform name like 'Windows', ... |
the-stack_106_31756 | #!/usr/bin/env python3
from sys import argv
from re import search
from math import log2
import urllib3
import ssl
"""
Programmed with urllib3.
Global RIR IPv4 CIDR prefix extractor, by country.
It now searches for a particular CC in all RIRs:
RIPE NCC, APNIC, ARIN, LACNIC and AFRINIC
Usage: ./pro... |
the-stack_106_31757 | from flask import make_response, abort, jsonify, send_from_directory, send_file
import sys
from io import StringIO
import os
import re
import urllib
import matplotlib.style
import matplotlib
matplotlib.use("Agg")
matplotlib.style.use('ggplot')
import seaborn as sns
import pandas as pd
import matplotlib.pyplot as plt
... |
the-stack_106_31758 |
from __future__ import print_function
import os
import sys
import pickle
import subprocess
import nltk
import re
import time
import requests, json
from nltk.corpus import stopwords
from nltk.tag import StanfordNERTagger
from nltk.tokenize import word_tokenize
from nltk.tokenize import PunktSentenceTokenizer
import req... |
the-stack_106_31759 | """ Utilities for parsing datastore entities. """
import datastore_server
from dbconstants import JOURNAL_SCHEMA
from dbconstants import JOURNAL_TABLE
from dbconstants import KEY_DELIMITER
from dbconstants import KIND_SEPARATOR
from google.appengine.datastore import entity_pb
def get_root_key_from_entity_key(key):
... |
the-stack_106_31761 | """
stale_sensors.py - Detects devices that haven't checked into
CrowdStrike for a specified period of time.
- jshcodes@CrowdStrike, 09.01.21
"""
from datetime import datetime, timedelta, timezone
from argparse import RawTextHelpFormatter
import argparse
from tabulate import tabulate
try:
from f... |
the-stack_106_31762 | """
Details about crypto currencies from CoinMarketCap.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.coinmarketcap/
"""
import logging
from datetime import timedelta
import json
from urllib.error import HTTPError
import voluptuous as vol
impor... |
the-stack_106_31765 | import json
import re
import scrapy
from locations.items import GeojsonPointItem
class WilcoFarmSpider(scrapy.Spider):
name = "wilcofarm"
allowed_domains = ["www.farmstore.com"]
start_urls = (
'https://www.farmstore.com/locations/',
)
def parse(self, response):
pattern = r"(var ma... |
the-stack_106_31768 | from hls4ml.converters.keras_to_hls import parse_default_keras_layer
from hls4ml.converters.keras_to_hls import keras_handler
from hls4ml.converters.keras.core import TernaryQuantizer
@keras_handler('GarNet', 'GarNetStack')
def parse_garnet_layer(keras_layer, input_names, input_shapes, data_reader, config):
assert... |
the-stack_106_31769 |
from flask import Flask
from redis import Redis
app = Flask(__name__)
redis = Redis(host="redis")
counter_key = "haha_counter"
@app.route("/")
def index():
## increae the counter by 1, get outcome.
count = redis.incr(counter_key)
return "The total number of visit to this page: {0}".format(count)
... |
the-stack_106_31770 | from __future__ import print_function
import pandas as pd
import numpy as np
from sklearn.neighbors import KNeighborsClassifier
val = pd.read_csv('val.csv')
#val = pd.read_csv('train.csv')
true_labels = val["Id"].values
embeddings = pd.read_pickle('trained/embeddings.pkl')
labels = embeddings['Id'].values.astype('in... |
the-stack_106_31771 | import copy
import logging
from typing import List, Union, Optional
from pathlib import Path
import shutil
import tempfile
import tarfile
import zipfile
import warnings
import functools
from datetime import datetime
from datetime import time as datetime_time
from geopandas import GeoDataFrame
import shapely
from shape... |
the-stack_106_31775 | # 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_31777 | import codecs
import os
import re
from setuptools import find_packages, setup
def get_absolute_path(*args):
"""Transform relative pathnames into absolute pathnames."""
return os.path.join(os.path.dirname(os.path.abspath(__file__)), *args)
def get_contents(*args):
"""Get the contents of a file relative ... |
the-stack_106_31778 | # Copyright 2019, The TensorFlow Federated 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 o... |
the-stack_106_31779 | import re
class TokexTokenizer(object):
"""
Base class for Tokex tokenizers. Uses re.findall & a collection of regular expressions to break up an
input string into a sequence of tokens.
Can be extended by subclassing this class & implementing a `tokenize` function or creating a custom
list of tok... |
the-stack_106_31780 | # -*- coding: utf-8 -*-
"""
hooks.pre_gen_project
~~~~~~~~~~~~~~~~~~~~~
Hooks to run before project generation.
:copyright: (c) 2016 by John P. Neumann.
:license: BSD, see LICENSE for more details.
"""
import re
import sys
MODULE_REGEX = r'^[_a-zA-Z][_a-zA-Z0-9]+$'
module_name = '{{ cookiecutt... |
the-stack_106_31781 | from setuptools import setup
requirements = []
with open("requirements.txt", "r") as fh:
for line in fh:
requirements.append(line.strip())
with open("README.md", encoding="utf-8") as f:
long_description = f.read()
setup(
name = "welearn-bot-iiserkol",
description = "A command line client for ... |
the-stack_106_31784 | import os
from virgil_trust_provisioner.core_utils import CRCCCITT
from virgil_trust_provisioner.data_types import TrustList
class FileKeyStorage:
def __init__(self, storage_path):
super(FileKeyStorage, self).__init__()
self.storage_path = storage_path
def __save_key_pair(self, file_name, ... |
the-stack_106_31786 | # Perform the necessary imports
import matplotlib.pyplot as plt
from sklearn.manifold import TSNE
# from rlkit.envs.read_hdf5 import get_dataset, qlearning_dataset
import matplotlib.pyplot as plt
import numpy as np
import h5py
import torch
from uncertainty_modeling.rl_uncertainty.model import *
import gym
import d4rl
... |
the-stack_106_31790 | from json import dumps
from pathlib import Path
from os import getenv
path = Path(".")
directory = []
origin = getenv("origin", "https://noo.farfrom.world/")
for noo_file in path.glob("*/*.noofile.yml"):
directory.append(str(noo_file))
# Export as json
with open("index.json", "w+") as f:
f.write(dumps(directo... |
the-stack_106_31793 | #!/usr/bin/env python
#
# Electrum - lightweight Bitcoin client
# Copyright (C) 2012 thomasv@gitorious
#
# 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 witho... |
the-stack_106_31794 | import pytest
import gym
from gym.spaces import MultiDiscrete
from regym.environments import Task, EnvType
from regym.environments import gym_parser
@pytest.fixture
def RPS_env():
import gym_rock_paper_scissors
return gym.make('RockPaperScissors-v0')
@pytest.fixture
def Pendulum_env():
return gym.make(... |
the-stack_106_31795 | """IPython terminal interface using prompt_toolkit in place of readline"""
from __future__ import print_function
import base64
import errno
from getpass import getpass
from io import BytesIO
import os
import signal
import subprocess
import sys
import time
from warnings import warn
try:
from queue import Empty # ... |
the-stack_106_31796 | #!/usr/bin/env python
#
# Electrum - lightweight Bitcoin client
# Copyright (C) 2015 Thomas Voegtlin
#
# 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... |
the-stack_106_31798 | # Copyright 2021 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import absolute_import
from argparse import Action, ArgumentTypeError, Namespace, _ActionsContainer
from pex import pex_warnings
from pex.argparse import HandleBoolAction... |
the-stack_106_31800 | def to_dict(obj, class_key=None):
if isinstance(obj, dict):
data = {}
for (k, v) in obj.items():
data[k] = to_dict(v, class_key)
return data
elif hasattr(obj, "_ast"):
return to_dict(obj._ast())
elif hasattr(obj, "__iter__") and not isinstance(obj, str):
r... |
the-stack_106_31802 | import numpy as np
from scipy.linalg import expm
from matplotlib.pylab import *
sigma_x = 0.5*np.r_[[[0, 1],[1, 0]]]
sigma_y = 0.5*np.r_[[[0,-1j],[1j, 0]]]
sigma_z = 0.5*np.r_[[[1, 0],[0, -1]]]
print(sigma_x)
print(sigma_y)
print(sigma_z)
print('commutator test')
print(np.dot(sigma_x,sigma_y) - np.dot(sigma_y,sigma... |
the-stack_106_31804 |
def permutate(elements):
if len(elements) == 1: return elements
permutations = []
for index, element in enumerate(elements):
for suffix in permutate(elements[:index] + elements[index+1:]):
permutations.append(element + suffix)
return permutations
counter = {}
for permutation in pe... |
the-stack_106_31807 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... |
the-stack_106_31808 | from typing import Optional
from ruptures.base import BaseCost
from ruptures.detection import Binseg
from sklearn.linear_model import LinearRegression
from etna.transforms.change_points_trend import ChangePointsTrendTransform
from etna.transforms.change_points_trend import TDetrendModel
class BinsegTrendTransform(C... |
the-stack_106_31809 | #
# 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 us... |
the-stack_106_31810 | # Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
# no unicode literals
from __future__ import absolute_import, division, print_function
import ctypes
import os
import os.path
import platfo... |
the-stack_106_31811 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""This module contains the table found on asrank.caida.org.
This table inherits from Generic Table. For more information:
https://github.com/jfuruness/lib_bgp_data/wiki/Generic-Table
"""
__author__ = "Abhinna Adhikari, Justin Furuness"
__credits__ = ["Abhinna Adhikari"... |
the-stack_106_31812 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from refinery.units import arg, Unit
class group(Unit):
"""
Group incoming chunks into frames of the given size.
"""
def __init__(self, size: arg.number(help='Size of each group; must be at least 2.', bound=(2, None))):
super().__init__(size=size)... |
the-stack_106_31814 | # -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# (C) British Crown Copyright 2017-2021 Met Office.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions a... |
the-stack_106_31815 | """
Code here relates to displaying and string-manipulating header dictionaries created by the ABFheader class.
"""
import os
def show(header):
"""Display the contents of the header in an easy to read format."""
for key in header.keys():
if key.startswith("###"):
print("\n%s"%key)
... |
the-stack_106_31816 | #!/usr/bin/env python
# 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
# "L... |
the-stack_106_31818 | """Min temp after, max temp after, count of days"""
import datetime
from scipy.stats import linregress
from pandas.io.sql import read_sql
from pyiem.util import get_autoplot_context, get_dbconn
from pyiem.plot.use_agg import plt
from pyiem.network import Table as NetworkTable
BOOLS = {
'yes': 'Yes, fit linear reg... |
the-stack_106_31819 | #!/usr/bin/env python3
# Copyright (c) 2019 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 diazd aborts if can't disconnect a block.
- Start a single node and generate 3 blocks.
- Delete the un... |
the-stack_106_31820 | """
@author: Thang Nguyen <nhthang1009@gmail.com>
"""
import os
import argparse
import shutil
import cv2
import numpy as np
from src.utils import *
import pickle
from src.yolo_net import Yolo
CLASSES = ["person", "bicycle", "car", "motorcycle", "airplane", "bus", "train", "truck", "boat",
"traffic light", "... |
the-stack_106_31821 | # Copyright 2014-present PlatformIO <contact@platformio.org>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicabl... |
the-stack_106_31822 | from locusts.support import *
from locusts.environment import *
def create_exec_file(id_list, command_template, indir, outdir, output_filename_templates,
exec_filename, shared_inputs=[], inputs_for_clean_environment=[]):
with open(exec_filename, "w") as exec_file:
for ip, idx in enumerate(id_list):... |
the-stack_106_31823 | # -*- coding: utf-8 -*-
#
# Configuration file for the Sphinx documentation builder.
#
# This file does only contain a selection of the most common options. For a
# full list see the documentation:
# http://www.sphinx-doc.org/en/stable/config
# -- Path setup ------------------------------------------------------------... |
the-stack_106_31828 | # Copyright (c) 2021 SUSE LLC
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of version 3 of the GNU General Public License as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; witho... |
the-stack_106_31829 | import numpy as np
import scipy.stats
import pytest
from .. import bq_c
from . import util
import logging
logger = logging.getLogger("bayesian_quadrature")
logger.setLevel("DEBUG")
DTYPE = util.DTYPE
options = util.options
def test_remove_jitter():
n = 2
arr = np.ones((n, n))
jitter = np.zeros(n)
... |
the-stack_106_31830 | """Calculate distances and shortest paths and find nearest node/edge(s) to point(s)."""
import itertools
import multiprocessing as mp
import warnings
import networkx as nx
import numpy as np
import pandas as pd
import pyproj
from rtree.index import Index as RTreeIndex
from shapely.geometry import Point
from . import... |
the-stack_106_31833 | # Copyright 2019 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_31834 | # Copyright (c) 2020 by Fraunhofer Institute for Energy Economics
# and Energy System Technology (IEE), Kassel. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
from pandapipes import pandapipesNet
from pandapipes.multinet.control.run_control_mult... |
the-stack_106_31836 | import torch
import torch.nn as nn
import ops.create5Dimages as create5D
import ops.create4Dimages as create4D
# 新加模块
class Self_Attn(nn.Module):
"""Self attention Layer"""
# (2048,4,16,7,7,4096) (2048,4,16,7,7,256)
# 调用:self.Attention = attention.Self_Attn(2048,4,16,7,7,256)
def __init__(self, in_... |
the-stack_106_31839 | import os
import tensorflow as tf
from model import get_model
from dataset import dataset
def main():
"""
Get the dataset, model
Set the callback
Train and save the best weights based on validation accuracy
"""
train_images, train_labels, test_images, test_labels = dataset()
model = ge... |
the-stack_106_31840 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
This is a socket implementation of http server
'''
# Import socket module
from socket import socket
from socket import AF_INET
from socket import SOCK_STREAM
from socket import SOL_SOCKET, SO_REUSEADDR
from wsgiref.handlers import format_date_time
from datetime import ... |
the-stack_106_31841 | # Copyright 2018 Google LLC.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
#... |
the-stack_106_31842 | import os
import struct
import threading
from collections import namedtuple
from io import BytesIO
from tarfile import TarFile, TarInfo
from c3nav.mapdata.utils.cache import AccessRestrictionAffected, GeometryIndexed, MapHistory
CachePackageLevel = namedtuple('CachePackageLevel', ('history', 'restrictions'))
class ... |
the-stack_106_31843 | from abc import ABC
import tensorflow as tf
print(tf.__version__)
class Controller(tf.keras.layers.Layer):
def __init__(self, init):
super(Controller, self).__init__(name='Controller')
self.w = tf.Variable(initial_value=init, dtype='float32', trainable=True)
def call(self, Mod... |
the-stack_106_31844 | from collections import Iterable
def as_iterable(object):
if isinstance(object, Iterable):
return object
else:
return [object]
class Logger:
def __init__(self, source, processors, sink, timer):
self.source = source
self.processors = as_iterable(processors)
self.si... |
the-stack_106_31846 | # -*- coding: UTF-8 -*-
################################################################################
#
# Copyright (c) 2020 Baidu, 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... |
the-stack_106_31848 | #!usr/bin/python3
"""ThreadMessage object representation.
Documentation example:
.. code-block:: javascript
{
"id": 67,
"type": "message",
"attributes": {
"message": "I choose you!",
"message_html": "I choose you!",
"posted_at": "2019-04-03T09:33:05+03:00",
"atta... |
the-stack_106_31851 | # -*- coding: utf-8 -*-
"""
This module defines images used by image reader, image properties
are set by user or read from image header.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
from abc import ABCMeta, abstractmethod
import nibabel as ... |
the-stack_106_31852 | import argparse
import collections
import torch
import numpy as np
import data_loader.data_loaders as module_data
import model.loss as module_loss
import model.metric as module_metric
import model.model as module_arch
from parse_config import ConfigParser
from trainer import Trainer
from utils import prepare_device
# ... |
the-stack_106_31853 | """Downloading data from the M4 competition
"""
import os
import requests
def download(datapath, url, name, split=None):
os.makedirs(datapath, exist_ok=True)
if split is not None:
namesplit = split + "/" + name
else:
namesplit = name
url = url.format(namesplit)
file_path = os... |
the-stack_106_31856 | # -*- coding: utf-8 -*-
# Copyright (C) 2020-2021 by SCICO Developers
# All rights reserved. BSD 3-clause License.
# This file is part of the SPORCO package. Details of the copyright
# and user license can be found in the 'LICENSE.txt' file distributed
# with the package.
r"""Extensions of numpy ndarray class.
.. te... |
the-stack_106_31857 | # -*- coding: utf-8 -*-
from django.db import models, migrations
def add_cache(apps, schema_editor):
Article = apps.get_model("news", "Article")
for article in Article.objects.all():
version_count = article.version_set.count()
if version_count == 0:
article.delete()
... |
the-stack_106_31858 | #name: KNN
#description: Imputes (numerical) missing values using the kNN algorithm
#reference: https://en.wikipedia.org/wiki/K-nearest_neighbors_algorithm
#language: python
#tags: demo, hide-suggestions
#sample: demog.csv
#input: dataframe data [Input data table with NA elements]
#input: column_list imputeColumns {typ... |
the-stack_106_31859 | # 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_31860 | # -*- coding:utf-8 -*-
# /usr/bin/env python
"""
Date: 2021/1/26 10:58
Desc: 金融期权数据
http://www.sse.com.cn/assortment/options/price/
"""
import pandas as pd
import requests
from akshare.option.cons import (
SH_OPTION_URL_50,
SH_OPTION_PAYLOAD,
SH_OPTION_PAYLOAD_OTHER,
SH_OPTION_URL_KING_50,
SH_OPTIO... |
the-stack_106_31861 | """
CircuitPython Touch Input Example - Blinking an LED using a capacitive touch pad.
This example is meant for boards that have capacitive touch pads, and no simple way to wire up
a button. If there is a simple way to wire up a button, or a button built into the board, use
the standard Digital Input template and exam... |
the-stack_106_31863 | """Implementation of the Perdomo et. al model of strategic classification.
The data is from the Kaggle Give Me Some Credit dataset:
https://www.kaggle.com/c/GiveMeSomeCredit/data,
and the dynamics are taken from:
Perdomo, Juan C., Tijana Zrnic, Celestine Mendler-Dünner, and Moritz Hardt.
"Performative P... |
the-stack_106_31864 | from typing import Dict, List, Optional, Any, Union
from pydantic import BaseModel, validator
from tracardi.service.plugin.domain.register import Plugin, Spec, MetaData, Documentation, PortDoc
from tracardi.service.plugin.domain.result import Result
from tracardi.service.plugin.runner import ActionRunner
from tracar... |
the-stack_106_31865 | import cv2
import os.path as op
import numpy as np
import pandas as pd
from PIL import Image
import torch
import torch.nn as nn
from torchvision import transforms, datasets
from torch.utils.data import Dataset
from torch.utils.data.sampler import BatchSampler
from torchvision.datasets import ImageFolder
import random
... |
the-stack_106_31867 | from pathlib import Path
from typing import Dict
def get_system_extra_hosts(extra_host_domain: str) -> Dict:
extra_hosts = {}
hosts_path = Path("/etc/hosts")
if hosts_path.exists() and extra_host_domain != "undefined":
with hosts_path.open() as hosts:
for line in hosts:
... |
the-stack_106_31868 | # -*- coding: utf-8 -*-
"""This module is deprecated."""
from cloudant.client import Cloudant
from cloudant.error import CloudantException
from cloudant.result import Result, ResultByKey
from cloudant.query import Query
from cloudant.document import Document
import array_comparison as ac
import time
def get_databas... |
the-stack_106_31869 | """
Copyright 2019-present Han Seokhyeon.
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,... |
the-stack_106_31870 | # Copyright 2022, Lefebvre Dalloz Services
#
# 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 ag... |
the-stack_106_31871 | #!/usr/bin/env python3
import re
import sys
def imm_to_bin(num: str, bits: int, signed: bool=False) -> str:
"""Convert a number to a binary string
Args:
num: The number to be converted to binary.
Can be either Hexadecimal, decimal or binary.
bits: The number of bits of t... |
the-stack_106_31872 | from django.db import models, transaction
from django.forms.models import model_to_dict
from .element import Element
from .team import Team
from typing import List, Dict, Any
import hashlib
import json
class ElementGroupManager(models.Manager):
def _hash_elements(self, elements: List) -> str:
elements_lis... |
the-stack_106_31873 | #
# Command Generator
#
# Send SNMP GET request using the following options:
#
# * with SNMPv3 with user 'usr-md5-des', MD5 auth and DES privacy protocols
# * use remote SNMP Engine ID 0x80004fb805636c6f75644dab22cc (USM
# autodiscovery will run)
# * over IPv4/UDP
# * to an Agent at demo.snmplabs.com:161
# * setting ... |
the-stack_106_31875 | # Copyright © 2019 Province of British Columbia
#
# 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 agr... |
the-stack_106_31877 | from galaxy.workflow import render
from .workflow_support import yaml_to_model
TEST_WORKFLOW_YAML = """
steps:
- type: "data_input"
order_index: 0
tool_inputs: {"name": "input1"}
position: {"top": 3, "left": 3}
- type: "data_input"
order_index: 1
tool_inputs: {"name": "input2"}
position: {"... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.