filename
stringlengths
13
19
text
stringlengths
134
1.04M
the-stack_106_17534
# rasterio from collections import namedtuple import logging import os import warnings from rasterio._base import eval_window, window_shape, window_index from rasterio._drivers import driver_count, GDALEnv import rasterio.dtypes from rasterio.dtypes import ( bool_, ubyte, uint8, uint16, int16, uint32, int32, floa...
the-stack_106_17535
""" URL: https://codeforces.com/problemset/problem/1417/A Author: Safiul Kabir [safiulanik at gmail.com] Tags: greedy, math, *800 """ t = int(input()) for _ in range(t): n, k = map(int, input().split()) a = list(map(int, input().split())) a.sort() count = 0 for i in range(1, n): if a[i] <=...
the-stack_106_17536
# # Copyright (c) 2020 Idiap Research Institute, http://www.idiap.ch/ # Written by Angelos Katharopoulos <angelos.katharopoulos@idiap.ch>, # Apoorv Vyas <avyas@idiap.ch> # """Similar to the corresponding module in fast_transformers.attention, this module performs all the query, key, value projections and output projec...
the-stack_106_17537
# Copyright (c) 2015-2016, 2018, 2020 Claudiu Popa <pcmanticore@gmail.com> # Copyright (c) 2016 Ceridwen <ceridwenv@gmail.com> # Copyright (c) 2017 Roy Wright <roy@wright.org> # Copyright (c) 2018 Ashley Whetter <ashley@awhetter.co.uk> # Copyright (c) 2019 Antoine Boellinger <aboellinger@hotmail.com> # Copyright (c) 20...
the-stack_106_17538
from unittest import mock import pytest from h.search import ( DeletedFilter, Limiter, Search, TopLevelAnnotationsFilter, UserFilter, ) from h.services.annotation_stats import AnnotationStatsService, annotation_stats_factory class TestAnnotationStatsService: def test_total_user_annotation_co...
the-stack_106_17540
""" Copyright 2020 The Magma Authors. This source code is licensed under the BSD-style license found in the LICENSE file in the root directory of this source tree. Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES O...
the-stack_106_17541
# # The Python Imaging Library. # $Id$ # # BMP file handler # # Windows (and OS/2) native bitmap storage format. # # history: # 1995-09-01 fl Created # 1996-04-30 fl Added save # 1997-08-27 fl Fixed save of 1-bit images # 1998-03-06 fl Load P images as L where possible # 1998-07-03 fl Load P images as 1 where...
the-stack_106_17542
import torch from PyTorch_VAE.models import BaseVAE from torch import nn from torch.nn import functional as F from .types_ import * class VanillaVAE(BaseVAE): def __init__(self, in_channels: int, latent_dim: int, hidden_dims: List = None, **kwa...
the-stack_106_17543
import os import io from google.oauth2 import service_account from google.cloud import speech_v1 def recognize(filepath, language_code='en_US', model='default', cred_file=None): # if cred_file is not None: # cred = service_account.Credentials.from_service_account_file( # cred_file, # ...
the-stack_106_17545
# killableprocess - subprocesses which can be reliably killed # # Parts of this module are copied from the subprocess.py file contained # in the Python distribution. # # Copyright (c) 2003-2004 by Peter Astrand <astrand@lysator.liu.se> # # Additions and modifications written by Benjamin Smedberg # <benjamin@smedbergs.u...
the-stack_106_17547
import pandas as pd from abc import abstractmethod import benchutils, os, time class Preprocessor: """Super class of all preprocessor implementations. Inherit from this class and implement :meth:`preprocessing.Preprocessor.preprocess()` if you want to add a new preprocessor class. :param input: abso...
the-stack_106_17550
import unittest from euchre.data_model import FaceCard, Suite, CardDeck, Card, Trick from euchre.move_simulations import update_possible_cards, possible_cards_in_hand from euchre.game_controller import GameController from euchre.players.RandomPlayer import RandomPlayer from itertools import chain class TestMoveSimula...
the-stack_106_17551
# -*- encoding: utf-8 -*- # pylint: disable=E0203,E1101,C0111 """ @file @brief Runtime operator. """ import numpy from ._op import OpRun from ..shape_object import ShapeObjectFct from .op_conv_ import ConvFloat, ConvDouble # pylint: disable=E0611,E0401 class Conv(OpRun): atts = {'auto_pad': 'NOTSET', 'group': 1...
the-stack_106_17554
""" Ansible action plugin to ensure inventory variables are set appropriately and no conflicting options have been provided. """ import re from ansible.plugins.action import ActionBase from ansible import errors # Valid values for openshift_deployment_type VALID_DEPLOYMENT_TYPES = ('origin', 'openshift-enterprise') ...
the-stack_106_17555
from shapely.wkb import loads import json from ... import getTile from ...Core import KnownUnknown def get_tiles(names, config, coord): ''' Retrieve a list of named TopoJSON layer tiles from a TileStache config. Check integrity and compatibility of each, looking at known layers, correct JSON ...
the-stack_106_17557
import argparse from glob import glob import cv2 import numpy as np from tensorflow.keras.applications import InceptionV3 from tensorflow.keras.applications.inception_v3 import preprocess_input from tensorflow.keras.models import model_from_json from utils import paths_to_tensor # Construct the argument parse and pa...
the-stack_106_17559
import unittest import numpy as np from operator import itemgetter from AlphaGo.go import GameState from AlphaGo.mcts import MCTS, TreeNode class TestTreeNode(unittest.TestCase): def setUp(self): self.gs = GameState() self.node = TreeNode(None, 1.0) def test_selection(self): self.nod...
the-stack_106_17560
import speech_recognition def listen(): with speech_recognition.Microphone() as source: recognizer.adjust_for_ambient_noise(source) audio = recognizer.listen(source) try: return recognizer.recognize_sphinx(audio) # or: return recognizer.recognize_google(audio) except speech_recognition.UnknownValueError: ...
the-stack_106_17561
#!/usr/bin/python #-*- coding: utf-8 -*- #cache路径 CACHE_PATH = "./cache/" #缓存合约路径 CACHE_CONTRACT_PATH = "./cache/temp.sol" #缓存路径信息文件 CACHE_PATHINFO_PATH = "./cache/temp_sol.json" #缓存抽象语法树文件 CACHE_AST_PATH = "./cache/temp.sol_json.ast" #源代码保存路径 CONTRACT_PATH = "../../contractExtractor/NonpublicVarAccessdByPublicFuncExt...
the-stack_106_17562
from setuptools import setup description = "Simple command line pomodoro app with visualization of statistics" long_description = """ Simple command line pomodoro app with visualization of statistics. The Pomodoro technique is a time management technique for improving productivity. Check (https://en.wikipedia.org/wik...
the-stack_106_17564
"""保守的指针规划算法""" import math from typing import Any from .algo_base import TouchAction, TouchEvent from chart import Chart from note import Note from utils import distance_of, recalc_pos class Pointer: pid: int pos: tuple[float, float] timestamp: int occupied: int def __init__(self, pid: int, po...
the-stack_106_17572
"""Unit tests for case detection and application.""" from case_restorer import case import unittest class CaseTests(unittest.TestCase): """Tests of the helper methods for the casing system.""" # Helpers. def assertEmpty(self, arg): self.assertTrue(not arg) def assertSimpleTcEqual(self, ...
the-stack_106_17573
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright 2019 Palo Alto Networks, 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 # #...
the-stack_106_17574
import re from base64 import b64encode from functools import partial from typing import Any, Callable, Dict, Optional, Tuple, Union from urllib.parse import quote_plus from hypothesis import strategies as st from hypothesis_jsonschema import from_schema from requests.auth import _basic_auth_str from ... import utils ...
the-stack_106_17575
#!/usr/bin/env python3 import sys import os sys.path.append(os.path.abspath(os.path.dirname(__file__) + '/..')) from asyncdbus import MessageBus import anyio async def main(): async with MessageBus().connect() as bus: # the introspection xml would normally be included in your project, but # this...
the-stack_106_17576
import uuid from datetime import datetime from django.test import TestCase from pillowtop.es_utils import initialize_index_and_mapping from corehq.apps.domain.shortcuts import create_domain from corehq.apps.locations.models import LocationType, SQLLocation from corehq.apps.userreports.app_manager.helpers import clea...
the-stack_106_17581
""" Know more, visit my Python tutorial page: https://morvanzhou.github.io/tutorials/ My Youtube Channel: https://www.youtube.com/user/MorvanZhou Dependencies: tensorflow: 1.1.0 matplotlib numpy """ import tensorflow as tf import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D LR =...
the-stack_106_17582
# -*- coding: utf-8 -*- import json import urllib.request headers = { "Host": "flights.ctrip.com", "User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:56.0) Gecko/20100101 Firefox/56.0", "Referer": "http://flights.ctrip.com/booking/SHA-BJS-day-1.html?DDate1=2018-2-16", "Connection": "keep-alive"...
the-stack_106_17584
def quicksort(lista, inicio=0, fim=None): if fim is None: fim = len(lista) - 1 if inicio < fim: p = lista[fim] indice = inicio for j in range(inicio, fim): if lista[j] <= p: lista[j], lista[indice] = lista[indice], lista[j] indice += ...
the-stack_106_17585
import tensorflow as tf mnist = tf.keras.datasets.mnist (x_train, y_train), (x_test, y_test) = mnist.load_data() x_train, x_test = x_train / 255.0, x_test / 255.0 model = tf.keras.models.Sequential([ tf.keras.layers.Flatten(input_shape=(28, 28)), tf.keras.layers.Dense(128, activation='relu'), tf.keras.layers....
the-stack_106_17586
import importlib.abc import importlib.util import os import platform import re import string import sys import tokenize import traceback import webbrowser from tkinter import * from tkinter.font import Font from tkinter.ttk import Scrollbar import tkinter.simpledialog as tkSimpleDialog import tkinter.messagebox as tkM...
the-stack_106_17587
from flask import Flask, render_template, request, url_for, redirect import csv app = Flask(__name__) @app.route('/') def hello_world(): return render_template('index.html') @app.route('/<string:page_name>') def page_name(page_name ): return render_template(page_name) def write_to_file(data): with...
the-stack_106_17588
# Copyright 2008-2015 Nokia Solutions and Networks # # 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_106_17589
r""" .. _ref_deflection_of_a_hinged_support: Deflection of a Hinged Support ------------------------------ Problem Description: - A structure consisting of two equal steel bars, each of length :math:`l` and cross-sectional area :math:`A`, with hinged ends is subjected to the action of a load :math:`F`. Determin...
the-stack_106_17591
# coding: utf-8 # Copyright (c) Pymatgen Development Team. # Distributed under the terms of the MIT License. from __future__ import division, unicode_literals """ This module implements a EnergyModel abstract class and some basic implementations. Basically, an EnergyModel is any model that returns an "energy" for any...
the-stack_106_17593
# -*- coding: utf-8 -*- """ Created on Mon Nov 16 08:59:34 2020 @author: wantysal """ # Standard library imports import numpy as np from scipy.io import wavfile, loadmat from scipy.signal import resample # Optional package import try: import pyuff except ImportError: pyuff = None def load(file, calib=1, ma...
the-stack_106_17594
""" 1525 medium number of good ways to split a string """ class Solution: def numSplits(self, s: str) -> int: from collections import Counter left = Counter() right = Counter(s) total = 0 for c in s: left[c] += 1 right[c] -= 1 if right...
the-stack_106_17595
from django.core import mail from django.test import TestCase from bluebottle.initiatives.tests.factories import InitiativeFactory from bluebottle.time_based.tests.factories import DateActivityFactory from bluebottle.funding.tests.factories import FundingFactory from bluebottle.test.factory_models.accounts import BlueB...
the-stack_106_17597
import struct import numpy as np dtypes = { 1: np.uint8, 2: np.int8, 3: np.int16, 4: np.int32, 5: np.int64, 6: np.float, 7: np.double, } def write_longs(f, a): f.write(np.array(a, dtype=np.int64)) def code(dtype): for k in dtypes.keys(): if dtypes[k] == dtype: ...
the-stack_106_17598
from __future__ import absolute_import, division, print_function, unicode_literals import torch_glow import unittest class TestSetGlowBackend(unittest.TestCase): def test_set_glow_backend(self): """Test setting the Glow backend type""" backend_name_before = torch_glow.getGlowBackendName() ...
the-stack_106_17599
# --- Day 23: Crab queue --- # The small crab challenges you to a game! The crab is going to mix up some queue, and you have to predict where they'll end up. # The queue will be arranged in a circle and labeled clockwise (your puzzle input). For example, if your labeling were 32415, there would be five queue in the ci...
the-stack_106_17602
# 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 may ...
the-stack_106_17603
#!/usr/bin/env python import sys sys.path.append("..") from models import iresnet from collections import OrderedDict from termcolor import cprint from torch.nn import Parameter import torch.nn.functional as F import torch.backends.cudnn as cudnn import numpy as np import math import torch import torch.nn as nn import ...
the-stack_106_17604
import pytest import numpy as np from numpy.testing import (assert_array_almost_equal, assert_array_equal, assert_allclose) from sklearn.datasets import load_linnerud from sklearn.cross_decomposition._pls import ( _center_scale_xy, _get_first_singular_vectors_power_method, _get_f...
the-stack_106_17605
# coding=utf8 """ translate.py - Willie Translation Module Copyright 2008, Sean B. Palmer, inamidst.com Copyright © 2013-2014, Elad Alfassa <elad@fedoraproject.org> Licensed under the Eiffel Forum License 2. http://willie.dftba.net """ from __future__ import unicode_literals from willie import web from willie.module i...
the-stack_106_17606
import os import subprocess as sp import random as RNG import numpy as np from turbojpeg import TurboJPEG as JPEG reader = JPEG() def read(fname): with open(fname, 'rb') as f: return reader.decode(f.read(), pixel_format=0) min_diff = 1e8 def remove_static_and_sample(frames, num_frames): global mi...
the-stack_106_17608
""" This file contains functions to be used in miscellaneous tasks like comparing simulated to estimated results, etc """ # base import math import numpy as np import statsmodels.api as sm from copy import deepcopy import pandas as pd # viz import matplotlib.pyplot as plt from matplotlib import gridspec import seaborn...
the-stack_106_17610
"""DVXplorer Test. Author: Yuhuang Hu Email : duguyue100@gmail.com """ from __future__ import print_function, absolute_import import numpy as np import cv2 from pyaer.dvxplorer import DVXPLORER from timer import Timer device = DVXPLORER() print("Device ID:", device.device_id) print("Device Serial Number:", device....
the-stack_106_17611
import logging class Logger(object): """ Class to setup and utilize basic logging Args: name: Name of class utilizing logger """ def __init__(self, name): logging.basicConfig( filename=None, level=logging.INFO, format='[%(asctime)s] {%(pathname)...
the-stack_106_17612
#!/usr/bin/env python # # Electrum - lightweight UraniumX 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 withou...
the-stack_106_17613
import os from enum import Enum from parallelm.mlops.mlops_exception import MLOpsException from parallelm.mlops.models.mlobject import MLObject from parallelm.mlops.models.mlobject import MLObjectType from parallelm.mlops.stats.stats_helper import StatsHelper from parallelm.mlops.stats_category import StatCategory cl...
the-stack_106_17614
#app/ecommend.py # Imports from os import path import pandas as pd import pickle import json # Load pickled vectorizer and model with open('pickles/tfidf.pkl', 'rb') as tfidf_pkl: tfidf = pickle.load(tfidf_pkl) with open('pickles/nn_model.pkl', 'rb') as nn_pkl: nn_model = pickle.load(n...
the-stack_106_17616
import json import arcade from .base import Base from .util import arcade_int_to_string import queue import multiprocessing OFFSET = 320 COLOURS = [(200, 100, 100), (100, 200, 100), (100, 100, 200)] class Lobby(Base): def __init__(self, display): self.display = display self.spritelist = arcade....
the-stack_106_17619
"""Functions to make 3D plots with M/EEG data """ from __future__ import print_function # Authors: Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr> # Denis Engemann <denis.engemann@gmail.com> # Martin Luessi <mluessi@nmr.mgh.harvard.edu> # Eric Larson <larson.eric.d@gmail.com> # ...
the-stack_106_17620
import os.path from os.path import basename, exists from os.path import join as pjoin from pathlib import Path from subprocess import CalledProcessError, check_output from tqdm import tqdm from skelshop.io import ShotSegmentedWriter from skelshop.shotseg.base import SHOT_CHANGE def fulldir(path): return os.path...
the-stack_106_17622
# proses memasukan data ke dalam variabel nama = "John Doe" # proses mencetak variabel print(nama) # nilai dan tipe data dalam variabel dapat diubah umur = 20 # nilai awal print(umur) # mencetak nilai umur type(umur) # mengecek tipe data umur umur = "dua puluh satu" # nilai sete...
the-stack_106_17627
# -*- test-case-name: twisted.python.test.test_util -*- # Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. from __future__ import division, absolute_import, print_function import os, sys, errno, warnings try: import pwd, grp except ImportError: pwd = grp = None try: from os import set...
the-stack_106_17628
import math from typing import Any, Dict, Iterator, List, Optional, Tuple, Union import numpy as np import tensorflow as tf import determined as det from determined import keras from determined_common import check ArrayLike = Union[np.ndarray, List[np.ndarray], Dict[str, np.ndarray]] def _is_list_of_numpy_array(x:...
the-stack_106_17629
# Copyright 2020 Soda # 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 #...
the-stack_106_17631
""" Mastermind Game Play: Code Breaker """ import sys from argparse import ArgumentParser from collections import Counter from itertools import product, permutations from random import choice from typing import List, Tuple # variants STANDARD = 0 NO_REPEATS = 1 # number of colors for code BASIC = 6 SUPER = 8 # numbe...
the-stack_106_17632
# -*- coding: utf-8 -*- """ ppstore.dbconnection ~~~~~~~~~~~~~~~~~ (Deprecated) A module containing a class to connect to database, query it, request updates and commit to database. :author: Muzammil Abdul Rehman :copyright: Northeastern University © 2018. :license: Custom BSD, see LICENS...
the-stack_106_17633
# -*- coding: utf-8 -*- from numpy import cos as npCos from numpy import exp as npExp from numpy import pi as npPi from numpy import sqrt as npSqrt from pandas_ta.utils import get_offset, verify_series def ssf(close, length=None, poles=None, offset=None, **kwargs): """Indicator: Ehler's Super Smoother Filter (SSF...
the-stack_106_17634
# python3 from gooey import * import synbiopython import synbiopython.genbabel as stdgen # imput parameters @Gooey(required_cols=2, program_name='genbank to sbol', header_bg_color= '#DCDCDC', terminal_font_color= '#DCDCDC', terminal_panel_color= '#DCDCDC') def main(): ap = GooeyParser() ap.add_argument("-gb", "...
the-stack_106_17635
import os import os.path as osp import numpy as np import pickle from PIL import Image import glob import yaml import torch from torch.utils.data import Dataset from torch.utils.data.dataloader import DataLoader import open3d as o3d import xmuda.data.semantic_kitti.io_data as SemanticKittiIO from xmuda.data.semantic_k...
the-stack_106_17636
import numpy as np import random, os import argparse import copy import tensorflow as tf #from datetime import datetime from Load_Controllers import Load_BBB, Load_Demonstrator from tqdm import tqdm from multiple_tasks import get_task_on_MUJOCO_environment from Dataset import getDemonstrationsFromTask import _pickle ...
the-stack_106_17637
# -*- coding: utf-8 -*- # Copyright 2020 Google LLC # # 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...
the-stack_106_17638
# Copyright (c) 2012 NetApp, Inc. # Copyright (c) 2014 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...
the-stack_106_17639
# Copyright 2018-present Kensho Technologies, LLC. import random from .utils import create_edge_statement, create_vertex_statement, get_random_limbs, get_uuid SPECIES_LIST = ( "Nazgul", "Pteranodon", "Dragon", "Hippogriff", ) FOOD_LIST = ( "Bacon", "Lembas", "Blood pie", ) NUM_FOODS = 2 ...
the-stack_106_17642
############################################################################################################# ## ## Source code for training. In this source code, there are initialize part, training part, ... ## ###########################################################################################################...
the-stack_106_17643
# Copyright 2015 Red Hat, 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 law or a...
the-stack_106_17644
# Copyright (C) 2020 Electronic Arts Inc. All rights reserved. import numpy class Physics: def __init__(self, game): self.game = game def Update(self, verbosity): self.BoardCollisionUpdate(max(0, verbosity - 1)) self.PlayerCollisionUpdate(max(0, verbosity - 1)) def BoardCollisi...
the-stack_106_17648
#!/usr/bin/env python # # Use the raw transactions API to spend bcashs received on particular addresses, # and send any change back to that same address. # # Example usage: # spendfrom.py # Lists available funds # spendfrom.py --from=ADDRESS --to=ADDRESS --amount=11.00 # # Assumes it will talk to a bcashd or BCash-Q...
the-stack_106_17649
class Student: def __init__(self,name): self.name = name self.exp = 0 self.lesson = 0 #call Function #self.AddEXP(10) #student1.name # self = student1 def Hello(self): print('สวัสดีจ้า ผมชื่อ{}'.format(self.name)) def Coding(self): print('{}:กำลังเขียนโปรแกรม..'.format(s...
the-stack_106_17652
# 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_17654
import json from starlette.testclient import TestClient from syndio_backend_test import api, main, sql DATA = [ {"id": 1, "gender": "male"}, {"id": 2, "gender": "male"}, {"id": 3, "gender": "male"}, {"id": 4, "gender": "female"}, {"id": 5, "gender": "female"}, {"id": 6, "gender": "female"}, ]...
the-stack_106_17655
# Adapted from test_file.py by Daniel Stutzbach #from __future__ import unicode_literals import sys import os import unittest from array import array from weakref import proxy from test.test_support import (TESTFN, findfile, check_warnings, run_unittest, make_bad_fd) from UserList impor...
the-stack_106_17661
#!/usr/bin/env python3 # # Copyright 2021 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 ...
the-stack_106_17662
# -*- coding: utf-8 -*- import logging from airflow.hooks.postgres_hook import PostgresHook as AirflowPostgresHook from airflow.exceptions import AirflowException class PostgresHook(AirflowPostgresHook): def update_row(self, table, rows, primary_key=None, commit_every=0): """ A generic way to u...
the-stack_106_17663
import json import os import sys import pika import spotipy from spotipy.oauth2 import SpotifyClientCredentials import imports.broker as broker import imports.db as db from imports.logging import get_logger import imports.requests READING_QUEUE_NAME = "albums" WRITING_QUEUE_NAME = "tracks" MAX_RETRY_ATTEMPTS = 10 l...
the-stack_106_17664
""" WNT Client ========== Simple example on how to communicate with the wirepas network tool services. .. Copyright: Copyright 2019 Wirepas Ltd under Apache License, Version 2.0. See file LICENSE for full license details. """ from .handlers import Backend from .settings import WN...
the-stack_106_17665
############################################################################### # # Metadata - A class for writing the Excel XLSX Metadata file. # # SPDX-License-Identifier: BSD-2-Clause # Copyright 2013-2021, John McNamara, jmcnamara@cpan.org # from . import xmlwriter class Metadata(xmlwriter.XMLwriter): """ ...
the-stack_106_17668
#!/usr/bin/env python3 # Copyright (c) 2014 Wladimir J. van der Laan # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. ''' Run this script from the root of the repository to update all translations from transifex. It will do the foll...
the-stack_106_17669
import random from collections import OrderedDict from datetime import datetime, timedelta import django_tables2 as tables import olympia.core.logger from django.conf import settings from django.contrib.humanize.templatetags.humanize import naturaltime from django.db.models import Count, F, Q from django.template impo...
the-stack_106_17670
"""The ozw integration.""" import asyncio from contextlib import suppress import json import logging from openzwavemqtt import OZWManager, OZWOptions from openzwavemqtt.const import ( EVENT_INSTANCE_EVENT, EVENT_NODE_ADDED, EVENT_NODE_CHANGED, EVENT_NODE_REMOVED, EVENT_VALUE_ADDED, EVENT_VALUE_...
the-stack_106_17672
#!Measurement ''' baseline: after: true before: false counts: 120 detector: H2 mass: 39.862 settling_time: 15.0 default_fits: nominal equilibration: eqtime: 1.0 inlet: H inlet_delay: 3 outlet: V use_extraction_eqtime: true multicollect: counts: 400 detector: L2(CDD) isotope: Ar36 peakcenter:...
the-stack_106_17673
""" Authors: The Vollab Developers 2004-2021 License: BSD 3 clause Plot implied volatility calculated by Fast Fourier Transform. Uses the Lets Be Rational library for fast calculation of Black-Scholes implied volatility. """ import argparse import json import functools import matplotlib.pyplot as pl...
the-stack_106_17674
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import * class AlipayEcoEprintPrinterDeleteModel(object): def __init__(self): self._client_id = None self._client_secret = None self._eprint_token = None self._machine_code = Non...
the-stack_106_17676
import panflute as pf from .meta import Meta, MetaFilter, metapreparemethod from .Number import NumberFilter from . import utils class TableCaptionReplace(MetaFilter, NumberFilter): @metapreparemethod def prepare(self, doc, meta): self.top_level = meta.chaptersDepth if meta.chapters else '' se...
the-stack_106_17677
import codecs import os from setuptools import find_packages, setup VERSION = "0.0.5" AUTHOR = "Free Law Project" EMAIL = "info@free.law" HERE = os.path.abspath(os.path.dirname(__file__)) def read(*parts): """ Build an absolute path from *parts* and and return the contents of the resulting file. Assume...
the-stack_106_17681
from flask import current_app from sqlalchemy import desc, and_ from sqlalchemy.orm import aliased from sqlalchemy.dialects.postgresql import insert from app import db from app.dao.dao_utils import transactional from app.models import InboundSms, InboundSmsHistory, Service, ServiceDataRetention, SMS_TYPE from app.util...
the-stack_106_17682
import math import os from random import random from typing import List, Dict import cv2 import json import numpy as np from pycocotools.coco import COCO from torch.utils.data import Dataset from pedrec.configs.dataset_configs import CocoDatasetConfig, get_coco_dataset_cfg_default from pedrec.configs.pedrec_net_confi...
the-stack_106_17684
import json import sqlite3, pyodbc import time import keyring import networkx as nx import dash import dash_auth import dash_core_components as dcc import dash_html_components as html import pandas as pd import plotly.graph_objs as go from dash.dependencies import Input, Output, State, MATCH, ALL import dash_bootstrap...
the-stack_106_17686
# -*- coding: utf-8 -*- """Implements Session to control USB Raw devices Loosely based on PyUSBTMC:python module to handle USB-TMC(Test and Measurement class) devices. by Noboru Yamamot, Accl. Lab, KEK, JAPAN This file is an offspring of the Lantz Project. :copyright: 2014-2020 by PyVISA-py Authors, see AUTHORS for ...
the-stack_106_17687
''' Function: 游戏结束界面 作者: Charles 微信公众号: Charles的皮卡丘 ''' import sys import pygame # 游戏结束界面 class EndInterface(pygame.sprite.Sprite): def __init__(self, WIDTH, HEIGHT): pygame.sprite.Sprite.__init__(self) self.imgs = ['./resource/imgs/end/gameover.png'] self.image = pygame.image.load(self.imgs[0]).convert() ...
the-stack_106_17691
import json import random import pytest from indy_common.authorize.auth_constraints import AuthConstraintForbidden from indy_common.constants import RS_CONTEXT_TYPE_VALUE, JSON_LD_CONTEXT, RS_SCHEMA_TYPE_VALUE, \ RS_MAPPING_TYPE_VALUE, RS_ENCODING_TYPE_VALUE, RS_CRED_DEF_TYPE_VALUE, RICH_SCHEMA, RICH_SCHEMA_ENCOD...
the-stack_106_17692
# Natural Language Toolkit: Word Sense Disambiguation Algorithms # # Authors: Liling Tan <alvations@gmail.com>, # Dmitrijs Milajevs <dimazest@gmail.com> # # Copyright (C) 2001-2018 NLTK Project # URL: <http://nltk.org/> # For license information, see LICENSE.TXT from nltk.corpus import wordnet def lesk(cont...
the-stack_106_17693
""" This file offers the methods to automatically retrieve the graph Candidatus Peregrinibacteria bacterium GW2011_GWA2_38_36. The graph is automatically retrieved from the STRING repository. References --------------------- Please cite the following if you use the data: ```bib @article{szklarczyk2019string, t...
the-stack_106_17695
import time """ The knapsack problem is a problem in combinatorial optimization: Given a set of items, each with a weight and a value, determine the number of each item to include in a collection so that the total weight is less than or equal to a given limit and the total value is as large as possible. It derives ...
the-stack_106_17696
import pickle from collections import OrderedDict from distutils.version import LooseVersion import cloudpickle import numpy as np import pytest import torch from torch import nn from pytorch_lightning.metrics.metric import Metric, MetricCollection torch.manual_seed(42) class Dummy(Metric): name = "Dummy" ...
the-stack_106_17697
#!/usr/bin/env python -w # # import argparse import os # method should be forward or reverse def Scan(pred_out,threshold,penality,method): print("### Start {} scaning".format(method)) scan_out = [] predict = dict() coor2pas = dict() for pas_id,score in pred_out: chromosome,coor,strand = pa...