content
stringlengths
5
1.05M
# -*- coding: utf-8 -*- # # Copyright 2018 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requir...
# Licensed under a 3-clause BSD style license - see LICENSE.rst import numpy as np from matplotlib.patches import Polygon from ... import units as u from ...coordinates.representation import UnitSphericalRepresentation from ...coordinates.matrix_utilities import rotation_matrix, matrix_product __all__ = ['Spherica...
# -*- coding: utf-8 -*- """ Created on Sat May 13 18:05:13 2017 @author: azkei Arithmetic Operations using NumPy """ # Generate an array a = np.arange(4) # Sum a+4 # Multiplication a*2 b = np.arange(4,8) # Add 2 arrays together a+b # Minus a-b # Multiply a*b # Multiple array with the sine or square root of the eleme...
from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt import numpy as np # input hand shape should be [5,4,6] def show_hand(hand, fname=None, show_origin=False, view_point="front", scale="fit"): finger_colors = ["#000055", "#111155", "#222255", "#333355", "#444455"] fig, (ax) = plt.subplots(n...
# Sublime Text 3 plugin to place the full path of the currently selected file in the status bar # Place this file in ~/Library/Aplication Support/Sublime Text 3/Packages/User/ import sublime, sublime_plugin class FilePathInStatusBar(sublime_plugin.EventListener): def on_activated(self, view): file_path = "" if ...
#!/usr/bin/env python """ New Drawing class to create new mark and style on axes. """ # from copy import deepcopy, copy from decimal import Decimal import numpy as np import toyplot # from .Admixture import AdmixEdges # for setting values from iterables ITERABLE = (list, tuple, np.ndarray) class GridSetup: "...
import pymongo import time client = pymongo.MongoClient('openshift.flg.jp', 30017) db = client.fx db.fxsetting_log.drop() db.result_backtest.drop() db.result_trade_sim.drop() db.trade_practice.drop() db.trade_practice_weekly.drop()
"""Idea comes from here: https://github.com/keras-team/keras/blob/master/examples/addition_rnn.py """ import os import pickle import numpy as np from manager import Manager from keras.callbacks import TensorBoard, ModelCheckpoint from keras.models import load_model from chatbot.config import PATHS from chatbot.trai...
__version__ = '0.1.46' default_app_config = 'wallets.apps.WalletsConfig'
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Jun 14 11:15:31 2018 @author: Kazuki """ import numpy as np import pandas as pd import os import utils utils.start(__file__) #============================================================================== PREF = 'prev_102_' KEY = 'SK_ID_CURR' os.sys...
import os from unittest import TestCase class Test(TestCase): def load_resource(self, path): base_path = os.path.split(__file__)[0] path = os.path.join(base_path, "files", path) return open(path, 'rb').read()
"""General file method and JSON handling""" import copy import glob import json import imghdr import os import warnings import numpy as np from .data_methods import num_digits __author__ = "Sean Mullan" __copyright__ = "Sean Mullan" __license__ = "mit" def ensure_dir(*paths): """Check if a given directory exis...
import csv from Bio import SeqIO from collections import Counter def read_in_vars(var_handle): vars = [] with open(var_handle) as fi: lines = fi.readlines() for line in lines[1:]: # print() vars.append(line.strip().split(',')) return vars def read_in_genome(...
# MIT License # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, an...
''' Feather the IRAM and NOEMA data together. ''' import numpy as np from spectral_cube import SpectralCube import astropy.units as u import scipy.ndimage as nd from paths import iram_matched_data_path, noema_data_path from constants import co21_freq from cube_analysis.feather_cubes import feather_cube noema_cube...
# -*- coding: utf-8 -*-# # (c) Copyright IBM Corp. 2020. All Rights Reserved. from resilient_lib.ui import Datatable, Tab, Field, create_tab class QRadarTab(Tab): SECTION = "fn_qradar_integration" NAME = "QRadar Offense Details" UUID = "d1ca8936-897b-4a83-8225-01c58db0470b" CONTAINS = [ Field...
from itertools import combinations, product import pytest from permuta import Perm from permuta.misc.union_find import UnionFind from tilings import GriddedPerm, Tiling from tilings.algorithms import ( Factor, FactorWithInterleaving, FactorWithMonotoneInterleaving, ) # -----------------------------------...
# Copyright (c) 2014, Facebook, Inc. # All rights reserved. # # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. An additional grant # of patent rights can be found in the PATENTS file in the same directory. from __future__ import absolute...
import pandas as pd from pipedown.nodes.base.metric import Metric from pipedown.utils.urls import get_node_url class MeanAbsolutePercentageError(Metric): CODE_URL = get_node_url("metrics/mean_absolute_percentage_error.py") def run(self, y_pred: pd.Series, y_true: pd.Series): return 100 * ((y_pred -...
''' Authentication demo example for Jeeves with confidentiality policies. ''' #from macropy.case_classes import macros, case import JeevesLib class User: def __init__(self, userId): self.userId = userId class AuctionContext(): def __init__(self, user, time, bids): self.user = user self.time = time ...
import unittest from brigitte.card import Card class TestCard(unittest.TestCase): value = 2 sign = '♣' def test_init(self): card = Card(self.value, self.sign) self.assertEqual(card.value, str(self.value)) self.assertEqual(card.sign, self.sign) self.assertIsNo...
from django import forms from tally_ho.apps.tally.models.clearance import Clearance from tally_ho.libs.models.enums import actions_prior from tally_ho.libs.models.enums import clearance_resolution class ClearanceForm(forms.ModelForm): class Meta: model = Clearance fields = [ 'center_n...
import torch.utils.data as data import os import os.path import torch import numpy as np import cv2 import json from DatasetGeneration import dividePointCloud data_dir_imgs = '/home/dream/study/codes/PCCompletion/datasets/pix3d/pix3d' HEIGHT = 128 WIDTH = 128 PAD = 35 choice = [torch.Tensor([1, 0, 0]), torch.Tensor(...
from interactions.aop import AffordanceObjectPair from interactions.context import InteractionContext, InteractionSource from interactions.priority import Priority from sims4.tuning.tunable import TunableSimMinute, TunableReference from sims4.utils import classproperty from situations.situation import Situation from si...
import random from operator import add, sub, mul from brain_games.constants import MINIMAL_RANDOM, MAXIMAL_RANDOM def greeting(): return 'What is the result of the expression?' def main_action(): first_el = random.randint(MINIMAL_RANDOM, MAXIMAL_RANDOM) second_el = random.randint(MINIMAL_RANDOM, MAXIMAL...
# This file is designed to perform unit and integration tests on all functions # in parabolic_pde_solver.py # Test have been written with TDD in mind where possible import pytest import numpy as np from math import pi, isclose from unittest.mock import MagicMock from parabolic_pde_solver import pde_solve, diags_m, cr...
from utils.collectors import GitHubVersionCollector from utils.configuration import Configuration class NginxVersionCollector(GitHubVersionCollector): owner = "nginx" repo = "nginx" @staticmethod def get_application_name() -> str: return "nginx" def __init__(self, config: Configuration):...
import pytest from amshared.driverpack import DriverPack def test_driverpack_singleton(drvpack): dp = DriverPack(drvpack, singleton=True, autoinject=False) dp.update(x=1) dp.update(y=2) dp.update(a='one', b='two') dp.update(z=3, c='three') # extra fun_inst = dp['fun'] assert fun_inst is...
from .parser import * from .node import *
import logging import hocort.execute as exe from hocort.classifiers.classifier import Classifier logger = logging.getLogger(__file__) class Kraken2(Classifier): """ Kraken2 implementation of the Classifier abstract base class. """ def build_index(path_out, fasta_in, threads=1, options=[], **kwargs)...
import uuid from django.contrib.auth.mixins import LoginRequiredMixin from django.contrib.auth.decorators import login_required from django.views.generic import ListView, DetailView, CreateView, TemplateView from .models import PostJobModel, ApplicationModel from user_profile.models import UserProfileInfo from users....
import torch from torchvision.transforms import ToPILImage from torchvision.utils import make_grid from matplotlib import pyplot as plt try: import plotly.graph_objects as go except: print('failed to import plotly') from .data import UnannotatedDataset def to_image(tensor, adaptive=False): if len(tensor....
import os def main(): filepath = 'data/raw' for item in os.listdir(filepath): if 'swo' in item: path = os.path.join('data/raw', item) os.remove(path) else: continue if __name__ == '__main__': main()
from datetime import datetime, timedelta from pprint import pprint import requests def next_search_date(start): in_a_week = start.date() + timedelta(days=7) return in_a_week def url_for_date(search_date): url = "https://playtomic.io/api/v1/availability?user_id=me&tenant_id=da776daf-43b3-11e8-8674-5254004...
apiAttachAvailable = u'API\u53ef\u4f9b\u4f7f\u7528' apiAttachNotAvailable = u'\u4e0d\u4f9b\u4f7f\u7528' apiAttachPendingAuthorization = u'\u5f85\u6388\u6743' apiAttachRefused = u'\u62d2\u7edd' apiAttachSuccess = u'\u6210\u529f' apiAttachUnknown = u'\u4e0d\u8be6' budDeletedFriend = u'\u5df2\u4ece\u670b\u53cb\u540d...
import yaml from usecases.configuration.exceptions \ import UnknownConfigurationFileTypeException from usecases.configuration.exceptions \ import InvalidConfigurationFileException class ConfigurationManager(): def __init__(self, configuration_file): self.configuration_file = configuration_file ...
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # --------------------------------------------------------------------...
import logging import sys import os import numpy as np import pickle import tvm import topi from topi.testing import conv2d_nchw_python from tvm import te from tvm import autotvm from tvm.autotvm.tuner import XGBTuner, GATuner, RandomTuner, GridSearchTuner import tvm.contrib.graph_runtime as runtime #from tvm.autotvm...
# -*- coding: utf-8 -*- """ ITU-R BT.2020 Colourspace ========================= Defines the *ITU-R BT.2020* colourspace: - :attr:`colour.models.BT2020_COLOURSPACE`. References ---------- - :cite:`InternationalTelecommunicationUnion2015h` : International Telecommunication Union. (2015). Recommendation ITU-R B...
#!/usr/bin/python import json import argparse def parseArgs( ): parser = argparse.ArgumentParser( description='' ) parser.add_argument( '-r', '--readmeDataFile', required=True, help='Absolute path of the README data file.' ) parser.add_argument( '-m', '--moduleDataFile', required=True, help='Absolute path...
# GENERATED BY KOMAND SDK - DO NOT EDIT import komand import json class Component: DESCRIPTION = "Get a Google document" class Input: DOCUMENT_ID = "document_id" class Output: DOCUMENT = "document" class GetDocumentInput(komand.Input): schema = json.loads(""" { "type": "object", "...
class BaseEncounter(object): """Base encounter class.""" def __init__(self, player, check_if_happens=True): self.p = self.player = player if (check_if_happens and self.check_if_happens()) or not check_if_happens: enc_name = self.__class__.__name__ enc_dict = self.p.game....
# coding=UTF-8 import tensorflow as tf import numpy as np import tools class Net(object): def __init__(self, inputs, labels=None, keep_prop=1.0, trainable=True, training=True, reuse=False, train_mode='all'): self.trainable = trainable self.training = training self.keep_prop = ...
MESSAGE_EMPTY_HASHPARAMSVAL = "Empty HASH or HASHPARAMSVAL" HASH_VALUES_DO_NOT_MATCH = "Hash values do not match" HASHES_DO_NOT_MATCHED = "Hashes do not match" PAYMENT_ALREADY_PROCESSED_OR_NOT_EXISTS = "Payment already processed or not exists" INVALID_CURRENCY_CODE = "Wrong currency code" INVALID_ORDER_ID = "Invalid or...
from __future__ import annotations import threading import random import string from concurrent.futures import ThreadPoolExecutor, wait from typing import Optional, Callable, Any from ..constants import ALL_COMPLETED __all__ = ("Executor", "ThreadManager") class Executor(ThreadPoolExecutor): def __init__(self, ...
import os import re from datetime import datetime use_sample = 0 input_file = os.path.join(os.path.dirname( __file__), "sample.txt" if use_sample else "input.txt") f = open(input_file, "r") lines = f.read().splitlines() starttime = datetime.now() rules = [] my_ticket = [] tickets = [] section = 0 for line in lin...
"""Contains the class for Remote PLIST attributes.""" import logging import os import tempfile # pylint: disable=relative-import try: import bad_wolf import config import curl_requests import misc import option_packs import package import plist except ImportError: from . import bad_wolf...
from __future__ import division from __future__ import print_function from __future__ import absolute_import import os import numpy as np from gym import utils from gym.envs.mujoco import mujoco_env import torch class AntTruncatedObsEnv(mujoco_env.MujocoEnv, utils.EzPickle): """ External forces (sim.data...
""" Creating randomly moving turtle. """ import turtle as t import random as ri #Creating def for Boundary so that it doesn't go out of the window def inside_window(): #reducing boundary from left side left_limit = (-t.window_width() / 2) + 100 #reducing boundary from right side right_limit = (t.windo...
import numpy as np import pandas as pd import matplotlib.pyplot as plt import datetime as dt from pandas_datareader import data import statsmodels.api as sm from statsmodels.tsa.seasonal import STL #dn = np.random.randint(2, size=100)*2-1 #gwalk = np.cumprod(np.exp(dn*0.01))*100 def get_stock(stock,start,end): ...
"""Helper functions and types to aid with Python 2.5 - 3 support.""" import sys import pymongo if pymongo.version_tuple[0] < 3: IS_PYMONGO_3 = False else: IS_PYMONGO_3 = True PY3 = sys.version_info[0] == 3 if PY3: import codecs from io import BytesIO as StringIO # return s converted to binary....
#!/usr/bin/env python from iris_sdk.models.maps.base_map import BaseMap class CallbackSubscriptionMap(BaseMap): url = None user = None expiry = None status = None
#!/usr/bin/env python3 import random from time import sleep, time import smbus from .hsv7segment import HSV7Segment start_time = time() HTML_COLORS = { # name hue sat val 'white': (0, 0, 0.25), 'black': (0, 0, 0), 'red': (0, 1, 0.5), 'maroo...
from molfunc.molecules import FragmentMolecule from molfunc.exceptions import MolFuncCritical import os here = os.path.dirname(os.path.abspath(__file__)) fragments_dir = os.path.join(here, 'fragments_lib') class LibFragmentMolecule(FragmentMolecule): def __init__(self, name, filename): """Fragment with ...
import numpy as np import os import sys import random import torch import torchvision import torchvision.transforms as transforms from utils.dataset_utils import check, separate_data, split_data, save_file from torchvision.datasets import ImageFolder, DatasetFolder random.seed(1) np.random.seed(1) num_clients = 20 num...
from visualizer import Visualizer v = Visualizer("cos(x)", "sin(y)") plt = v.plot_color(skip=2) plt.savefig("./img/vector_field.png")
# stdlib from typing import Any # proj from arpeggio import * def test_zeroormore_eolterm() -> None: def grammar() -> Any: return first, second, EOF def first() -> Any: return ZeroOrMore(["a", "b"], eolterm=True) def second() -> Any: return "a" # first rule should match only first...
import sublime, sublime_plugin, urllib, json class EmailInlineCommand(sublime_plugin.TextCommand): def run(self, edit): region = sublime.Region(0, self.view.size()) content = self.view.substr(region) api_url = 'http://premailer.dialect.ca/api/0.1/documents' values = { 'html' : content, 'adapter' : self...
import matplotlib.pyplot as plt def plot_drift_vertical_lines(log_size, resp_drift=None, label="Concept drift ground truth", lw=3, alpha=0.9): """ Plots vertical lines corresponding to ground truth drifts Parameters: ------------ log_size (int): Size of the event log to plot a...
"""Get invoice by profile id API method.""" from ibsng.handler.handler import Handler class getInvoiceProfileByID(Handler): """Get invoice by profile id method class.""" def control(self): """Validate inputs after setup method. :return: None :rtype: None """ self.is_v...
# -*- coding: utf-8 -*- ########################################################################### # Copyright (c), The AiiDA team. All rights reserved. # # This file is part of the AiiDA code. # # ...
from typing import Tuple from tempo.serve.utils import pipeline, predictmethod def test_class_func_class(): @pipeline( name="classifier", models=[], ) class MyPipeline: @predictmethod def predict(self, X: str) -> str: return X x = MyPipeline() r = x.p...
import warnings if __name__ == '__main__': print('Loading...') warnings.filterwarnings("ignore") import pyfiglet import time from rich.console import Console from rich import print as rprint from sklearn.linear_model import Ridge from pypinyin import lazy_pinyin import nagisa import jieba import regex import n...
import numpy as np from multiagent.core import World, Agent, Landmark, Goal from multiagent.scenario import BaseScenario class Scenario(BaseScenario): def make_world(self): world = World() # add agents world.agents = [Agent() for i in range(1)] for i, agent in enumerate(world.agent...
from ceefax.fonts import get_font, font_list import pytest @pytest.mark.parametrize("fontname", font_list) def test_fonts(fontname): font = get_font(fontname) text = font.text_to_ascii("Hello! ") assert isinstance(text, str)
################################################################################ # Copyright 2021-2022 Advanced Micro Devices, Inc. All rights reserved. # # 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 t...
import json from labboard.BaiduExpress import BaiduExpress from flask import ( Blueprint, request, jsonify, current_app, render_template ) bp = Blueprint("express", __name__, url_prefix="/express") baidu_express = BaiduExpress() @bp.route("/getExpressCompany", methods=["POST"]) def get_express_company(): if ...
import random n = 20000 k = 100 f = open("E.in","w") f.write("%d %d\n"%(n,k)) for i in range(n): f.write("%d "%random.randint(1,1000000)) f.write("\n") f.close()
#!/usr/bin/env python # -*- coding: utf-8 -*- from sqlalchemy import Column, String, text from sqlalchemy.dialects.mysql import BIGINT, TINYINT from trest.db import Model as Base class UserCertification(Base): __tablename__ = 'user_certification' user_id = Column(BIGINT(20), primary_key=True, server_default...
import nltk from libinit import preper_ from nltk.tokenize import word_tokenize nltk.download('vader_lexicon') from nltk.sentiment.vader import SentimentIntensityAnalyzer class Sentiment(): def __init__(self): self.sia = SentimentIntensityAnalyzer() self.preper = preper_ def _singleSent(self...
#!/usr/bin/python import socket MSGLEN=65536 class MySocket(socket.socket): def accept(self): sock, a def accept(self): sock, addr = self._sock.accept() return _socketobject(_sock=sock), addr accept.__doc__ = _realsocket.accept.__doc__ def mysend(self, msg): totalsent = 0 ...
# -*- coding: utf-8 -*- """ EvMore - pager mechanism This is a pager for displaying long texts and allows stepping up and down in the text (the name comes from the traditional 'more' unix command). To use, simply pass the text through the EvMore object: from evennia.utils.evmore import EvMore text = some_lo...
''' ## To work around a conflict between PIL and Image. ## Source: David Goodger's comment at http://sourceforge.net/p/docutils/bugs/137/ try: import PIL.Image import sys sys.modules['Image'] = PIL.Image except ImportError: pass ''' import Image from numpy import * import numpy def image_stack_from_filenam...
import chess.svg import requests import scipy.stats as st import numpy as np import time import config def calc_percs(white, black, draws): n = white + black + draws if n > 0: total_games = n white_perc = white / n black_perc = black / n draw_perc = draws / n return ...
import base64 from Crypto.Cipher import AES #criando uma chave de criptografia chave = "0123456789ABCDEF" aes = AES.new(chave, AES.MODE_ECB) #recebe o arquivo a ser criptografado arquivo = raw_input() #ler o arquivo e corrigir o seu tamanho #o tanho dever ser um multiplo de 16 caracters arq_entrada = open(arquivo, "...
from . import CC from . import default_settings from . import m2det320_resnet101 from . import m2det320_vgg from . import m2det512_vgg from . import m2det704_vgg from . import m2det800_vgg
# Wind Speed from gpiozero import Button class RainGauge: ''' Process rain gauge clicks How do we deal with wind gusts? Locking? ''' RAIN_GAUGE_BUTTON = 24 # GPIO number (Physical pin 18) RAIN_UNIT = 0.518 # mm per button going to/from on/off (need to test this value) def __init__(self, button=RAI...
# -*- coding: utf-8 -*- # Generated by Django 1.11.1 on 2017-05-17 14:49 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('contenttypes', '0002_remove_content_type_name'), ('...
from subprocess import CalledProcessError from typing import List, Tuple from pathlib import Path from concurrent.futures import ThreadPoolExecutor, as_completed, CancelledError import traceback import os import shutil import datetime from flacmirror.misc import format_date from .encode import encode_flac from .optio...
# # PySNMP MIB module CISCO-CABLE-DIAG-CAPABILITY (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-CABLE-DIAG-CAPABILITY # Produced by pysmi-0.3.4 at Mon Apr 29 17:34:26 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python versio...
import cupy import torch import re import math kernel_AdaCoF_updateOutput = ''' extern "C" __global__ void kernel_AdaCoF_updateOutput( const int n, const float* input, const float* weight, const float* offset_i, const float* offset_j, float* output ) { for (int i...
import torch.nn as nn from model.bilstm import BiLSTM from model.crf import CRF class BiLSTM_CRF(nn.Module): def __init__(self, data): super(BiLSTM_CRF, self).__init__() print("build batched lstmcrf...") self.gpu = data.HP_gpu # For CRF, we need to add extra two label START and END...
import discord from discord.ext import commands import json with open(r"cogs\etc\Auth.json", "r") as Auth: loadjson = json.load(Auth) token = loadjson['DiscordToken'] class Bot(commands.Bot): def __init__(self): super().__init__(command_prefix="&") def load_cogs(bot): extensions = ['cogs.status'...
""" test_application ~~~~~~~~~~~~~~~~ Test the Sphinx class. :copyright: Copyright 2007-2020 by the Sphinx team, see AUTHORS. :license: BSD, see LICENSE for details. """ from unittest.mock import Mock import pytest from docutils import nodes from sphinx.errors import ExtensionError from sphinx....
import numpy as np A = [[0.588679, 0.674133, -0.147233, -0.220814], [-0.799857, -0.0946959, 0.00393738, -0.0674015], [0.830193, 0.269214, 0.209219, -0.265506]] A = np.array(A) C = [[-0.144183, 0.539951, 0.827288], [0.258239, -0.533043, 0.480274], [0.561599, -0.350697, -0.85463], [0.801968, 0.579835, -0.14939]] ...
################################################################################ # Copyright 2016-2021 Advanced Micro Devices, Inc. All rights reserved. # # 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 t...
import re import requests # 爬取网站视频 respose=requests.get('http://www.xiaohuar.com/v/') print(respose.status_code)# 响应的状态码 print(respose.content) #返回字节信息 print(respose.text) #返回文本内容 urls=re.findall(r'class="items".*?href="(.*?)"',respose.text,re.S) #re.S 把文本信息转换成1行匹配 url=urls[6] # 这里获取第5个url进入, result=r...
from typing import List, Optional, Generator, Tuple from copy import deepcopy from curses import ascii from .pane import Pane from .mark import Highlight, Mark from .ui import UI from .utils import flatten class BreakTheLoop(Exception): pass class PanesRenderer: """Renders panes with marks and handles user...
import urllib.request import json import getpass import configparser from player_if import Player_IF class IF_Mopidy(Player_IF): name = "Mopidy" color = "#00A2E8" useMopidy = False artistName = "" albumName = "" def __init__(self, config): self.config = config self.useMopidy = self...
from pathlib import Path import random from babeval.vocab import get_vocab NUM_SUBJECT_NOUNS_FROM_EACH_LIST = 50 # some number smaller than length of both singular and plural noun lists NUM_OBJECT_NOUNS_FROM_EACH_LIST = 8 # some number smaller than length of both singular and plural noun lists NUM_ADJECTIVES = 4 N...
# $Id: sccp.py 23 2006-11-08 15:45:33Z dugsong $ # -*- coding: utf-8 -*- """Cisco Skinny Client Control Protocol.""" import dpkt KEYPAD_BUTTON = 0x00000003 OFF_HOOK = 0x00000006 ON_HOOK = 0x00000007 OPEN_RECEIVE_CHANNEL_ACK = 0x00000022 START_TONE = 0x00000082 STOP_TONE = 0x00000083 SET_LAMP = 0x00000086 SET_SPEAKER_...
print("Yes" if len(set(input())) == 2 else "No")
import sqlite3 from bank_bot.settings import TRANSACTION_MODEL_DATA class Transaction(object): def __init__( self, sender_hash, recepient_hash, amount, transaction_hash, created_time=None ): self.sender_hash = sender_hash self.recepient_hash = recepient_hash self.amount = amount...
# -*- coding: utf-8 -*- # Copyright 2018 Alexandre Freitas # # 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 ...
#!/usr/bin/env python """ Core elements of the model for conference resolution for SemEval 2018 This module will contain the dict objects for reference through out the application. Any constant/format/list that is needed across files should be housed here. No functions will be defined here as this will be the root fil...
import pandas as pd import requests from bs4 import BeautifulSoup import utilities as utils def get_page_text(url): html_page = requests.get(url).content soup = BeautifulSoup(html_page, 'lxml') whitelist = ['p', 'strong', 'em', 'b', 'u', 'i', 'h1', 'h2', 'h3'] out = "" for t in soup.find_all(text...
def neural_network(inputs, weight): prediction = weighted_sum(inputs, weight) return prediction def weighted_sum(inputs, weight): output = 0 for i in range(len(inputs)): output += inputs[i] * weights[i] return output number_of_all_rounders = 3 number_of_batsmen = 4 number_of_bowlers = 3 inputs = [number_of_al...
"""pyezviz camera api.""" from __future__ import annotations import datetime from typing import TYPE_CHECKING, Any from .constants import DeviceCatagories, DeviceSwitchType, SoundMode from .exceptions import PyEzvizError if TYPE_CHECKING: from .client import EzvizClient class EzvizCamera: """Initialize Ezv...
# -*- coding: utf-8 -*- from telegram import InlineKeyboardButton, InlineKeyboardMarkup from config import cfg def services_buttons(callback_data_func): services = cfg.get("services") buttons = [] for svc in services: buttons.append( [InlineKeyboardButton(text="%s (%s)" % (svc.name, ...
from warnings import warn from pyhf import Model __all__ = ["correlated_background", "uncorrelated_background"] def __dir__(): return __all__ def correlated_background(signal, bkg, bkg_up, bkg_down, batch_size=None): r""" Construct a simple single channel :class:`~pyhf.pdf.Model` with a :class:`~p...