filename
stringlengths
13
19
text
stringlengths
134
1.04M
the-stack_0_8989
# Copyright 2013-2021 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) import glob import os import pytest import llnl.util.filesystem as fs import spack.environment import spack.repo from s...
the-stack_0_8991
from sys import stdin, stdout freq = {} num_women = int(input()) for i in range(num_women): line = stdin.readline().strip().split() country = line[0] if not country in freq: freq[country] = 1 else: freq[country] += 1 for pair in sorted(freq.items()): stdout.write("{} {}\n".format(pair[0], pair[1]))
the-stack_0_8992
"""Snapcast group.""" import asyncio import logging _LOGGER = logging.getLogger(__name__) # pylint: disable=too-many-public-methods class Snapgroup(object): """Represents a snapcast group.""" def __init__(self, server, data): """Initialize.""" self._server = server self._snapshot = ...
the-stack_0_8996
import Adafruit_DHT DHT_SENSOR = Adafruit_DHT.DHT22 DHT_PIN = 4 while True: humidity, temperature = Adafruit_DHT.read_retry(DHT_SENSOR, DHT_PIN) if humidity is not None and temperature is not None: print("Temp={0:0.1f}*C Humidity={1:0.1f}%".format(temperature, humidity)) else: print("DAT...
the-stack_0_8997
""" Copyright 2020 The OneFlow Authors. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agr...
the-stack_0_8998
""" This file offers the methods to automatically retrieve the graph Sphingomonas soli NBRC 100801. The graph is automatically retrieved from the STRING repository. References --------------------- Please cite the following if you use the data: ```bib @article{szklarczyk2019string, title={STRING v11: protein--...
the-stack_0_8999
import base64 import requests from constants import URL, IMAGE_EXTENSION """ http://<URL>/image/all (GET) """ def recover_images(): resource = f"{URL}image" response = requests.get(url=resource) for data in response.json(): image_64_encode = data['encoded_image'] image_64_encode = image...
the-stack_0_9000
from StringIO import StringIO from mimetypes import guess_all_extensions, guess_type import zipfile import logging import os from django.contrib.auth.decorators import login_required import json from django.core.urlresolvers import reverse from django.utils.decorators import method_decorator from django.views.generic i...
the-stack_0_9001
import sys import os SUMMARYSTUFF = """ ## Contents {:.no_toc} * {: toc} """ filetoread = sys.argv[1] fdtoread = open(filetoread) fileprefix = ".".join(filetoread.split('.')[:-1]) filetowrite = fileprefix+".newmd" buffer = "" for line in fdtoread: if line[0:2]=='# ':#assume title title = line.strip()[2:] ...
the-stack_0_9002
"""Worker pool executor base classes.""" import numbers import os import threading import time import datetime import pprint import traceback from schema import Or, And from testplan.common.config import ConfigOption, validate_func from testplan.common import entity from testplan.common.utils.thread import interrupti...
the-stack_0_9004
import os from typing import Optional import time from fastapi import FastAPI from transformers import pipeline from pydantic import BaseModel, PositiveInt, constr import ray from ray import serve app = FastAPI() class Request(BaseModel): text: constr(min_length=1, strip_whitespace=True) min_length: Option...
the-stack_0_9005
# 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_0_9011
from fairseq.models.roberta import RobertaModel from fairseq.data.data_utils import collate_tokens import nltk import random # DOWNLOAD: wget https://storage.googleapis.com/poloma-models/airbnb_model.tar.gz # EXTRACT: tar -xvzf airbnb_model.tar.gz # MAKE SURE model directory points to where you downloaded the model ...
the-stack_0_9014
import asyncio from typing import Any from app.recorder.recorder import Recorder from ib_insync import IB class MarketRecorder(object): def __init__(self, ib: IB, recorder: Recorder) -> None: self._ib = ib self._recorder = recorder self._ib.pendingTickersEvent += self.on_market_data ...
the-stack_0_9015
# -*- coding: utf-8 -*- from collections import OrderedDict import pykintone import numpy as np import pandas as pd from karura.core.dataframe_extension import DataFrameExtension, FType from karura.env import get_kintone_env class Field(): def __init__(self, code, f_type, label, is_unique): self.code = c...
the-stack_0_9018
#!/usr/bin/env python from __future__ import print_function from collections import OrderedDict import re regexes = { 'hybrid-assembly': ['v_pipeline.txt', r"(\S+)"], 'Nextflow': ['v_nextflow.txt', r"(\S+)"], 'FastQC': ['v_fastqc.txt', r"FastQC v(\S+)"], 'MultiQC': ['v_multiqc.txt', r"multiqc, version ...
the-stack_0_9019
# Copyright 2012 OpenStack Foundation # 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 req...
the-stack_0_9020
# Copyright 2020 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_0_9025
""" setup for vmnlcli package """ from setuptools import setup, find_packages with open('README.md') as f: long_description = f.read() # remove header, but have one \n before first headline start = long_description.find('# vmnlcli') assert start >= 0 long_description = '\n' + long_description[sta...
the-stack_0_9028
""" This file offers the methods to automatically retrieve the graph Streptomyces cyaneogriseus subsp. noncyanogenus. The graph is automatically retrieved from the STRING repository. References --------------------- Please cite the following if you use the data: ```bib @article{szklarczyk2019string, title={STR...
the-stack_0_9030
from enum import Enum from typing import List, NamedTuple, Optional # Callable import random # from math import sqrt from generic_search import dfs, node_to_path, Node, bfs # astar class Cell(str, Enum): EMPTY = " " BLOCKED = "X" START = "S" GOAL = "G" PATH = "*" class MazeLocation(NamedTuple...
the-stack_0_9031
""" "vendors" notary into docker and runs integration tests - then builds the docker client binary with an API version compatible with the existing daemon Usage: python docker-integration-test.py This assumes that your docker directory is in $GOPATH/src/github.com/docker/docker and your notary directory, irrespective...
the-stack_0_9034
# 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_0_9035
# wiki/tests.py from django.test import TestCase from django.contrib.auth.models import User from django.urls import reverse from wiki.models import Page class PageListViewTests(TestCase): def test_multiple_pages(self): # Make some test data to be displayed on the page. user = User.objects.create(...
the-stack_0_9036
#!/usr/bin/env python3 from contextlib import ExitStack from time import sleep from urllib.request import urlopen import argparse import json import random import sys import yaml from plumbum import local from dyno_cluster import DynoCluster, DynoSpec from func_test import comparison_test from utils import generate_i...
the-stack_0_9037
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import re import threading import time import sys import math import signal import configparser import audioop import subprocess as sp import argparse import os import os.path import pymumble_py3 as pymumble import pymumble_py3.constants import variables as var import logg...
the-stack_0_9040
import os import importlib.util from setuptools import setup # Boilerplate to load commonalities spec = importlib.util.spec_from_file_location( "setup_common", os.path.join(os.path.dirname(__file__), "setup_common.py") ) common = importlib.util.module_from_spec(spec) spec.loader.exec_module(common) common.KWARGS[...
the-stack_0_9041
#!/usr/bin/env python3 # Copyright (c) 2019-2020 The YEP developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # -*- coding: utf-8 -*- from time import sleep from test_framework.test_framework import YepTestFramework from te...
the-stack_0_9042
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # Copyright (c) 2010 - 2021, Fraunhofer-Gesellschaft zur Foerderung der angewandten Forschung e.V. # All rights reserved. # # SPDX-License-Identifier: BSD-3-Clause # # Redistribution and use in source and binary forms, with or without # modification, are permitted provid...
the-stack_0_9043
#!/usr/bin/env python3 """ Fonctions principales d'assistant de paris """ import copy import datetime import requests import socket import sys import traceback import urllib import urllib.error import urllib.request from itertools import combinations, permutations, product from multiprocessing.pool import ThreadPool ...
the-stack_0_9044
#!/usr/bin/env python3 # # 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 #...
the-stack_0_9045
#!/usr/bin/env python # -*- coding: utf-8 -*- # File: shufflenet.py import argparse import math import numpy as np import os import cv2 import tensorflow as tf from tensorpack import * from tensorpack.dataflow import imgaug from tensorpack.tfutils import argscope, get_model_loader, model_utils from tensorpack.tfutils...
the-stack_0_9046
from elasticsearch import Elasticsearch from rdflib import Graph from constants import CLASS_INDEX, RELATION_INDEX from constants import ENTITY_INDEX from constants import LABEL_PRED_LOWER es = Elasticsearch(['http://geo-qa.cs.upb.de:9200/']) def indexClasses(filepath): g = Graph() g.parse(filepath) fo...
the-stack_0_9047
# -*- coding: utf-8 -*- """Manages custom event formatter helpers.""" class FormattersManager(object): """Custom event formatter helpers manager.""" _custom_formatter_helpers = {} @classmethod def GetEventFormatterHelper(cls, identifier): """Retrieves a custom event formatter helper. Args: id...
the-stack_0_9048
# -*- coding: utf-8 -*- # # Copyright 2014 Google LLC. 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_9050
from flask import jsonify, request, g, url_for, current_app, abort from . import api from ..models import Post, Permission from .decorators import permission_required from .. import db from .errors import forbidden @api.route('/posts/') def get_posts(): page = request.args.get('page', 1, type=int) pagination ...
the-stack_0_9051
#!/usr/bin/env python3 # # author: Michael Brockus # contact: <mailto:michaelbrockus@gmail.com> # license: Apache 2.0 :http://www.apache.org/licenses/LICENSE-2.0 # # copyright 2020 The Meson-UI development team # import subprocess import logging color = { 'green': '\x1B[01;32m', 'blue': '\033[94m', 'bold'...
the-stack_0_9053
# qubit number=2 # total number=25 import pyquil from pyquil.api import local_forest_runtime, QVMConnection from pyquil import Program, get_qc from pyquil.gates import * import numpy as np conn = QVMConnection() def make_circuit()-> Program: prog = Program() # circuit begin prog += H(0) # number=1 pr...
the-stack_0_9054
from __future__ import division import operator import numpy as np from scipy import stats, interpolate #============================================================================== # This library module is full of functions and classes to compute the maximum # mutual information (Capacity) between an input (x) (vol...
the-stack_0_9055
""" Support for MQTT JSON lights. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/light.mqtt_json/ """ import json import logging import voluptuous as vol from homeassistant.components import mqtt from homeassistant.components.light import ( ATTR_BR...
the-stack_0_9058
#!/usr/bin/env python # -*- coding: utf-8 -*- from argparse import ArgumentParser import logging import sys from io import open from os import path from time import time from glob import glob from textblob import Blobber from textblob_aptagger import PerceptronTagger from collections import Counter, defaultdict impo...
the-stack_0_9060
import telraam_data.query as query import telraam_data.download as download from .utils import get_data_keys import datetime as dt import shutil import pandas as pd import pathlib as pl import random import pytest @pytest.fixture() def one_segment(): all_segments = query.query_active_segments() segment_idx = ...
the-stack_0_9062
import time import paho.mqtt.client as paho import httplib2 from urllib import urlencode import json def call_get_arrivals(line): h = httplib2.Http(disable_ssl_certificate_validation=True) # h.add_credentials(intro_username, intro_password) resp, content = h.request("https://api.tfl.gov.uk/Line/"+line+"/Ar...
the-stack_0_9065
import numpy as np import matplotlib.pylab as plt import multiprocessing as mp from matplotlib import figure from data import * FIG = plt.figure() def draw_coord(coord, name, lab=[1.0, 0.0]): color = 1.0 if lab[0] > lab[1] else -1.0 ret = np.zeros(shape=[L,L,1]) coord_x, coord_y = coord coord_x_idx = np.argm...
the-stack_0_9066
import os import math import torch import numpy as np from PIL import Image, ImageDraw from torch.utils.data import random_split, DataLoader from matplotlib import pyplot as plt from data_utils import MyTestDataset, get_test_transforms, my_collate from conf.settings import BASE_DIR from faster_rcnn.predict import pred...
the-stack_0_9067
# -*- coding: utf-8 -*- """Redundancy.""" from proselint.tools import memoize, preferred_forms_check @memoize def check(text): """Suggest the preferred forms.""" err = "redundancy.wallace" msg = "Redundancy. Use '{}' instead of '{}'." redundancies = [ ["rectangular", ["rectangular in...
the-stack_0_9068
# Copyright 2013-2022 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 RPhilentropy(RPackage): """Similarity and Distance Quantification Between Probability Func...
the-stack_0_9069
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """misc helper functions for pyLSV2""" import struct from datetime import datetime def decode_system_parameters(result_set): """decode the result system parameter query :param tuple result_set: bytes returned by the system parameter query command R_PR :retur...
the-stack_0_9070
import pytest from django.db import transaction from django.db.utils import IntegrityError from psqlextra.fields import HStoreField from . import migrations from .util import get_fake_model def test_migration_create_drop_model(): """Tests whether indexes are properly created and dropped when creating and d...
the-stack_0_9071
from json import ( JSONDecodeError, ) import logging import os from pathlib import ( Path, ) import socket import sys import threading from types import ( TracebackType, ) from typing import ( Any, Type, ) from web3._utils.threads import ( Timeout, ) from web3.types import ( RPCEndpoint, ...
the-stack_0_9072
# Thsi is my python cheet sheet # Basic vector maths def SumVector(a,b): sum = [(a[0]+b[0]),(a[1]+b[1])] return sum def ProVector(a,s): pro = [(s*a[0]),(s*a[1])] return pro a = [-1,2] b = [4,5] s = 10 print(f"Sum of a and b is:{SumVector(a,b)}") print(f"Product of a and s is:{ProVector(a,s)}") # Intr...
the-stack_0_9073
# -*- coding: utf-8 -*- # Copyright 2015 Fanficdownloader team, 2019 FanFicFare team # # 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 # # Un...
the-stack_0_9076
from collections import Counter, defaultdict from copy import deepcopy from random import Random import pytest from hypothesis import assume, event from hypothesis.stateful import ( Bundle, RuleBasedStateMachine, consumes, initialize, invariant, rule, ) from hypothesis.strategies import builds,...
the-stack_0_9078
from lost.db import state # def add_user(data_man, user): # '''add user to user meta # Args: # db_man (obj): Project database manager. # user (obj): User object # ''' # user = model.User(idx=user.id, user_name=user.username, # first_name=user.first_name, last_na...
the-stack_0_9079
import os import numpy as np import tifffile as tiff from PIL import Image from sklearn.model_selection import train_test_split from torch.utils.data import DataLoader from torch.utils.data.dataset import Dataset from torch.utils.data.sampler import RandomSampler, SequentialSampler from torchvision.transforms import C...
the-stack_0_9080
""" Module containing raster blocks for spatial operations. """ import math from scipy import ndimage import numpy as np from osgeo import ogr from dask_geomodeling.utils import ( EPSG3857, EPSG4326, POLYGON, get_sr, Extent, get_dtype_min, get_footprint, get_index, shapely_transfor...
the-stack_0_9081
import functools import itertools from collections import (OrderedDict, abc, deque) from operator import is_not from typing import (Any, Hashable, Iterable, MutableMapping, Sequence, ...
the-stack_0_9084
from .fhirbase import fhirbase class EnrollmentRequest(fhirbase): """ This resource provides the insurance enrollment details to the insurer regarding a specified coverage. Args: resourceType: This is a EnrollmentRequest resource identifier: The Response business identifier. s...
the-stack_0_9086
import unittest from unittest.mock import patch, call import argparse from deba.commands.test import add_subcommand class TestCommandTestCase(unittest.TestCase): @patch("builtins.print") def test_run(self, mock_print): parser = argparse.ArgumentParser("deba") subparsers = parser.add_subparser...
the-stack_0_9091
""" Copyright 2017-present, Airbnb 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 agreed to in writing, sof...
the-stack_0_9092
from numpy import nan from pandas import DataFrame, concat, read_sql_table from pandas._testing import assert_frame_equal from df_to_azure import df_to_azure from df_to_azure.db import auth_azure # ############################# # #### APPEND METHOD TESTS #### # ############################# def test_append(): d...
the-stack_0_9094
"""btre URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.1/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-based vi...
the-stack_0_9095
import itertools from typing import Any import torch from torch.autograd import DeviceType from torch.futures import Future from collections import defaultdict, namedtuple from operator import attrgetter from typing import Dict, List, Tuple, Optional import math try: # Available in Python >= 3.2 from contex...
the-stack_0_9096
# -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from builtins import str import six import logging import filecmp import os import re import sys import uuid import json import time import tempfil...
the-stack_0_9098
from collections import OrderedDict from django.utils.functional import cached_property from six import iteritems from slyd.orm.exceptions import ValidationError __all__ = [ 'cached_property', 'cached_property_ignore_set', 'class_property', 'unspecified', 'validate_type', 'AttributeDict', ] ...
the-stack_0_9099
#!/usr/bin/env python3 # Copyright (c) 2016-2018 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 segwit transactions and blocks on P2P network.""" from binascii import hexlify import math import ...
the-stack_0_9102
import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D ## import sys import random ## equation class coeffs = [ [4, 5, 6, 7 ], [0, 9, 10, 11 ], [0, 0, 12, 13 ], [0, 0, 0, 14 ]] def van_der_pol_oscillator_deriv(x, t): nx0 = x[1]...
the-stack_0_9104
#!/usr/bin/env python3 # Pi-Ware main UI from tkinter import * from tkinter.ttk import * from ttkthemes import ThemedStyle import tkinter as tk import os import webbrowser from functools import partial import getpass import json from screeninfo import get_monitors #Set global var username global username username = ge...
the-stack_0_9105
#!/usr/bin/env python # # Copyright 2017 Google 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 ...
the-stack_0_9106
import asyncio import concurrent.futures import json import logging import tempfile import pytest import bitcoinx from aiohttp import web from aiohttp.test_utils import make_mocked_request from bitcoinx import BitcoinTestnet, hex_str_to_hash from typing import List, Union, Dict, Any, Optional, Tuple from concurrent.fu...
the-stack_0_9108
#!/usr/bin/python3 import argparse import multiprocessing as mp import sys import os import webserver import firmware as f from rpi_get_serial import rpi_get_serial if __name__ == "__main__": parser = argparse.ArgumentParser(description='Kuzzle IoT - multi sensor demo', prog="kuzzle-iot-demo-multi-device") ...
the-stack_0_9110
# NAME : Anagram Counting # URL : https://open.kattis.com/problems/anagramcounting # ============================================================================= # Calculate the total as n! / (n<sub>1</sub>!n<sub>2</sub>!...n<sub>k</sub>!) # where the denominator is the product of the factorials of the number of # oc...
the-stack_0_9113
def gen(font, text, out="text.png", vert=2, fw=0, spacing=0, color="black", bg="transparent", width=256, height=256, center=False, wwrap=False, no_crop=False): from . import cli args = [font, text, "--out", out, "--vert", vert, "--fw", fw, "--spacing", spacing, "--color", color, "--bg", bg, "--width", width, ...
the-stack_0_9116
import asyncio import websockets import json import aio_pika import ast import os import logging logger = logging.getLogger('websockets') logger.setLevel(logging.INFO) logger.addHandler(logging.StreamHandler()) class wsServer(object): def __init__(self, portNum=8765): self.portNum = portNum se...
the-stack_0_9119
"""Support for Roku.""" import asyncio from datetime import timedelta import logging from typing import Any, Dict from rokuecp import Roku, RokuConnectionError, RokuError from rokuecp.models import Device import voluptuous as vol from homeassistant.components.media_player import DOMAIN as MEDIA_PLAYER_DOMAIN from hom...
the-stack_0_9121
# Import packages import os import cv2 import sys import numpy as np from timeit import default_timer from threading import Thread from datetime import datetime import uuid import random import dlr from dlr.counter.phone_home import PhoneHome from stream_uploader import init_gg_stream_manager, send_to_gg_stream_manage...
the-stack_0_9124
## LSDMap_SwathPlotting.py ##=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= ## These functions are tools to deal with plotting swaths ##=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= ## SMM ## 20/02/2018 ##=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-...
the-stack_0_9125
import logging from typing import Dict, List from common_utils import labels from controller.invoker.invoker_task_base import TaskBaseInvoker from controller.label_model import label_runner from controller.utils import utils from id_definition.error_codes import CTLResponseCode from proto import backend_pb2 class Ta...
the-stack_0_9126
import logging import os import cv2 import numpy as np from config import GlobalConfig as GlobalConfig from utils.image_modification import get_grayscaled_image from utils.other import get_n_unique_rows cfg = GlobalConfig.get_config() logger = logging.getLogger(__name__) def get_edge_candidate_clusters_from_mask(i...
the-stack_0_9128
"""COMMAND : .cname""" import asyncio import time from telethon.tl import functions from telethon.errors import FloodWaitError from uniborg.util import admin_cmd DEL_TIME_OUT = 60 @borg.on(admin_cmd("cname")) # pylint:disable=E0602 async def _(event): if event.fwd_from: return while True: ...
the-stack_0_9129
# Rule for simple expansion of template files. This performs a simple # search over the template file for the keys in substitutions, # and replaces them with the corresponding values. # # Typical usage: # load("/tools/build_rules/template_rule", "expand_header_template") # template_rule( # name = "ExpandMyTem...
the-stack_0_9131
""" This code is adapted from the source code used in the paper 'Style Change Detection Using BERT (2020)' Title: Style-Change-Detection-Using-BERT Authors: Aarish Iyer and Soroush Vosoughi Date: Jul 18, 2020 Availability: https://github.com/aarish407/Style-Change-Detection-Using-BERT """ import random import re impo...
the-stack_0_9132
import os import unittest import torchtext from seq2seq.evaluator import Predictor from seq2seq.dataset import SourceField, TargetField from seq2seq.models import Seq2seq, EncoderRNN, DecoderRNN class TestPredictor(unittest.TestCase): @classmethod def setUpClass(self): test_path = os.path.dirname(os...
the-stack_0_9133
# coding: utf-8 """ Copyright 2016 SmartBear Software 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_0_9135
import warnings from typing import Callable, Any, Optional, List import torch from torch import Tensor from torch import nn from .._internally_replaced_utils import load_state_dict_from_url from ..ops.misc import ConvNormActivation from ..utils import _log_api_usage_once from ._utils import _make_divisible __all__ ...
the-stack_0_9137
import json from pathlib import Path import random class CocoFilter(): """ Filters the COCO dataset """ def _process_info(self): if 'info' in self.coco: self.info = self.coco['info'] else: self.info = [] def _process_licenses(self): if 'licenses'...
the-stack_0_9139
''' Created by yong.huang on 2016.11.04 ''' from hifive.api.base import RestApi class HFBaseFavoriteRequest(RestApi): def __init__(self,domain=None,port=80): domain = domain or 'hifive-gateway-test.hifiveai.com'; RestApi.__init__(self,domain, port) self.clientId = None self.page = None self.pageSize = None ...
the-stack_0_9140
""" Copyright Snap Inc. 2021. This sample code is made available by Snap Inc. for informational purposes only. No license, whether implied or otherwise, is granted in or to such code (including any rights to copy, modify, publish, distribute and/or commercialize such code), unless you have entered into a separate agree...
the-stack_0_9141
from app import db from models import Company, Colleagues, Admins, Boxes, Ideas from flask import flash, redirect, url_for from helper import instatiate_admin, get_extension, remove_avatar_file, remove_logo_file import os import shutil # to copy files import random import lorem from date import today, add_day, str_to_d...
the-stack_0_9143
from django.db import models from modelcluster.fields import ParentalKey from wagtail.admin.edit_handlers import ( FieldPanel, MultiFieldPanel, PageChooserPanel) from wagtailmenus.models import ( SectionMenu, ChildrenMenu, AbstractMainMenu, AbstractMainMenuItem, AbstractFlatMenu, AbstractFlatMenuItem) fro...
the-stack_0_9144
# -*- coding: utf-8 -*- """ @author: WZM @time: 2021/1/17 17:05 @function: 将原文作者的初始网络结构换成inception v2网络提取特征图 """ import torch import torch.nn as nn import torchvision.models as models from models.spp_net import SpatialPyramidPooling2d def ConvBNReLU(in_channels, out_channels, kernel_size, stride=1, padding=0): ...
the-stack_0_9146
"""Contains the CLI.""" import sys import json import logging import time from logging import LogRecord from typing import ( Callable, Tuple, NoReturn, Optional, List, ) import yaml import click # For the profiler import pstats from io import StringIO # To enable colour cross platform import co...
the-stack_0_9147
import re import bibtexparser import arrow import pprint from bibtexparser.bibdatabase import BibDatabase _HOST = 'https://scholar.google.com{0}' _SCHOLARPUBRE = r'cites=([\w-]*)' _CITATIONPUB = '/citations?hl=en&view_op=view_citation&citation_for_view={0}' _SCHOLARPUB = '/scholar?hl=en&oi=bibs&cites={0}' _CITATIONPUB...
the-stack_0_9148
# coding: utf-8 import json try: from unittest.mock import Mock except Exception: from mock import Mock from critics.core import CriticApp from critics.parsers import Review def test_poll_store(tmpdir): fakemodel = tmpdir.join("fakemodel.json") app = CriticApp(ios=['app1', 'app2'], language=['ru'], pe...
the-stack_0_9149
''' Kattis - textencryption Yet another time wasty problem :( This one is somewhat annoying since the question is rather vague on what to do when the pointer goes back to the same location as a char that has already been used... The key idea for encryptions is: for each new letter in our plain text P[counter], we put ...
the-stack_0_9150
# 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 a...
the-stack_0_9151
# # Copyright 2016 The BigDL 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_9152
# Copyright (c) 2015 Mirantis, 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 agreed to in writin...
the-stack_0_9154
#!/usr/bin/env python3 import os import json import sys import logging from github import Github from pr_info import PRInfo from get_robot_token import get_best_robot_token from commit_status_helper import get_commit NAME = 'Run Check (actions)' TRUSTED_ORG_IDS = { 7409213, # yandex 28471076, # altinity ...
the-stack_0_9157
# Copyright 2016-2020 Blue Marble Analytics 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 ag...