text stringlengths 2 999k |
|---|
import numpy as np
import matplotlib.pyplot as plt
import h5py
import scipy as sp
from sklearn import mixture
import os
import seaborn as sns
import pandas
import scipy as sp
from scipy import ndimage
class StainCluster(object):
def __init__(self, stain_dataset, interpolate_missing_slices=True, fwh... |
'''
Created on 2 Oct 2017
@author: cheney
'''
#from oxpe2elib.channel import identity
#from oxpe2elib.channel import listener
#from oxpe2elib.channel import pingService
#from oxpe2elib.channel.msg.protocol import protocol
#from oxpe2elib.channel import receivedMessage
#from oxpe2elib.channel.msg import message
class... |
"""
ULauncher Generator Extension
"""
import logging
import secrets
from ulauncher.api.client.extension import Extension
from ulauncher.api.client.EventListener import EventListener
from ulauncher.api.shared.event import KeywordQueryEvent
from ulauncher.api.shared.item.ExtensionResultItem import ExtensionResultItem
fro... |
#!/usr/bin/env python
# //==================================================================
# //函数名: vision.opecv_Canny函数说明
# //作者: dianjixz
# //日期: 2021-10-28
# //功能: 边缘检测函数
# //输入参数: vision.opecv_Canny(img, thr_h, thr_l, size=(0,0),mode=0)
# // py_img 图像对象,PIL图像或bytes图像(如果不是240*240的rg... |
import pytest
@pytest.fixture
def xkom_hotshot_json():
return """
{
"Id": "12345",
"Product": null,
"Price": 50.0,
"OldPrice": 100.0,
"PromotionGainText": "Oszczędź 50 zł",
"PromotionGainTextLines": [
"Oszczędź",
"50 zł"
],
"PromotionGainValue": 50.0,
"Promotion... |
from typing import Callable
import pytest
from eth_tester.exceptions import TransactionFailed
from eth_typing.evm import HexAddress
from web3 import Web3
from web3.contract import Contract
from raiden_contracts.constants import (
MAX_ETH_CHANNEL_PARTICIPANT,
MAX_ETH_TOKEN_NETWORK,
TEST_SETTLE_TIMEOUT_MAX,... |
from django.contrib.auth.forms import UserCreationForm,UserChangeForm
from django.contrib.auth.models import User
from django import forms
class SignupForm(UserCreationForm):
name= forms.TextField(max_length=200)
neighborhood= forms.CharField(max_length=100,widget=forms.TextInput(attrs={'class': 'form-control'}))
... |
from functools import lru_cache
from math import sqrt
num = 600851475143
@lru_cache(maxsize=None)
def find_prime_cofactors(n):
for i in range(int(sqrt(n)), 1, -1):
if n % i == 0:
return {*find_prime_cofactors(i), *find_prime_cofactors(int(n / i))}
return {n}
print(max(find_prime_cofactor... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# Copyright (c) 2013 Julien Danjou <julien@danjou.info>
# Copyright (c) 2013 Will Kahn-Greene <willg@bluesock.org>
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to... |
from typing import Tuple
import pygame
pygame.init()
class BaseApp:
def __init__(self, title="my game", icon_path: str = "./images/icon.png", height: int = 300, width: int = 300,
bg_color: Tuple[int, int, int] = (0, 0, 0)):
self.screen = pygame.display.set_mode((height, width))
s... |
from __future__ import unicode_literals
import unittest
from django.db import connection, migrations, models, transaction
from django.db.migrations.migration import Migration
from django.db.migrations.state import ProjectState
from django.db.models.fields import NOT_PROVIDED
from django.db.transaction import atomic
f... |
# coding=utf-8
"""
Uses /proc/mounts and os.statvfs() to get disk space usage
#### Dependencies
* /proc/mounts
#### Examples
# no exclude filters at all
exclude_filters =,
# exclude everything that begins /boot or /mnt
exclude_filters = ^/boot, ^/mnt
# exclude everything that includes the le... |
from .Water import Water
from .read_water import read_water, read_bytes
from .write_water import compile_water, write_water
from .generate_map import generate_height_map, generate_material_map, generate_x_flow_map, generate_z_flow_map, \
generate_xz_flow_map
|
#
# Copyright 2017 XEBIALABS
#
# 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, subli... |
import unittest
from ford import ford
class FordFulkersonTestCase(unittest.TestCase):
def test_task1(self):
pairs = [
[0, 1, 4], [0, 3, 9], [1, 3, 2],
[1, 4, 4], [3, 2, 1], [3, 5, 6],
[2, 4, 1], [2, 5, 10], [4, 5, 1],
[4, 6, 2], [5, 6, 9]
]
s... |
# -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making BK-BASE 蓝鲸基础平台 available.
Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved.
BK-BASE 蓝鲸基础平台 is licensed under the MIT License.
License for BK-BASE 蓝鲸基础平台:
------------------------------------------... |
class Solution:
def rightSideView(self, root):
res = []
self.dfs(root, 0, res)
return res
def dfs(self, r, n, res):
if not r:
return
if n >= len(res):
res.append(r.val)
self.dfs(r.right, n + 1, res)
self.dfs(r.left, n + 1, res)
|
# Copyright (C) 2019 The Raphielscape Company LLC.
#
# Licensed under the Raphielscape Public License, Version 1.c (the "License");
# you may not use this file except in compliance with the License.
#
# Copyright (C) 2021 TeamUltroid for autobot
# Recode by @mrismanaziz
# FROM Man-Userbot <https://github.com/mrismanazi... |
import itertools
N = int(input())
lst = input().split()
K = int(input())
lst_tuple = list(itertools.combinations(lst, K))
lst_contains_a = [i for i in lst_tuple if 'a' in i]
print(len(lst_contains_a )/len(lst_tuple)) |
"""
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/... |
import peewee as pw
import json
class JSONField(pw.TextField):
def db_value(self, value):
return json.dumps(value)
def python_value(self, value):
try:
if value is not None:
return json.loads(value)
except:
pass
return {}
class Model(wiz.... |
#FUNÇÃO PARA TESTAR ALUNO
def TesteAlunos ():
AlunoA = dict()
AlunoA['Nome'] = str(input('Digite o nome do aluno: '))
AlunoA['Nota1'] = float(input('Digite a nota 1: '))
Nota1= float(AlunoA['Nota1'])
AlunoA['Nota2'] = float(input('Digite a nota 2: '))
Nota2= float(AlunoA['Nota2'])
AlunoA['No... |
import pymc as pm
import numpy as np
count_data = np.loadtxt("../../Chapter1_Introduction/data/txtdata.csv")
n_count_data = len(count_data)
alpha = 1.0/count_data.mean() #recall count_data is
#the variable that holds our txt counts
lambda_1 = pm.Exponentia... |
# -*- coding: utf-8 -*-
"""
Created on Fri Apr 3 17:31:47 2020
@author: NOTEBOOK
"""
#This is a guess number game
import random
def main():
print('Hello, What is your name?')
name = input()
secretnumber = random.randint(1, 10)
print("Well", name, "I am thinking of a number between and including 1-10"... |
# Generated by Django 3.1.1 on 2020-10-27 02:08
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('movie', '0010_auto_20201026_1932'),
]
operations = [
migrations.AlterField(
model_name='movie',
name='teaser',
... |
# -*- coding: UTF-8 -*-
"""
Author: LGD
FileName: __init__.py
DateTime: 2021/1/18 21:11
SoftWare: PyCharm
"""
|
import unittest
class DictNested(dict):
"""
Naive dictionary extension to work with deeply nested keys.
Class provides methods to get values and dictionaries from deeply nested
dictionary and set/reset/delete values in nested dictionary.
"""
def check_input(self, path):
if isinstance(s... |
import pyOcean_cpu as ocean
import sys
def exceptionMsg() :
print("Expected error: %s" % str(sys.exc_info()[1]))
def failTest(command) :
try :
eval(command)
except :
exceptionMsg()
A = ocean.asTensor([1,2,3])
B = ocean.tensor([2,3], ocean.int8) # Only size information is used
print(A.broadcastL... |
"""
Django settings for project project.
Generated by 'django-admin startproject' using Django 3.1.2.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.1/ref/settings/
"""
from pathlib... |
from django import forms
from django.contrib.auth.models import User
class SignupForm(forms.Form):
username = forms.CharField()
email = forms.EmailField()
first_name = forms.CharField()
password1 = forms.CharField()
def clean(self):
data = self.cleaned_data
data['username'] = 'Te... |
# Copyright 2010-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License").
# You may not use this file except in compliance with the License.
# A copy of the License is located at
#
# http://aws.amazon.com/apache2.0
#
# or in the "license" file ac... |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License
import json
from ._status_q import StatusQueue
class StatusMessage:
OperationId = None
Database = None
Table = None
IngestionSourceId = None
IngestionSourcePath = None
RootActivityId = None
_raw = None
def __ini... |
# -*- coding: utf-8 -*-
"""
Created on Sat Oct 11 19:39:06 2014
@author: Eugene Petkevich
"""
class VariableFactory(object):
"""A class for a SAT maker that number variables.
It keeps track of variable numbers
"""
def __init__(self):
"""Create a factory for a SAT-input."""
self.coun... |
# 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 or agreed to in w... |
# Run configurations, set .env
ROOT_URL = "https://opensky-network.org/api"
# Often you have unit testing env variables!
|
"""
Module used to describe all of the different data types
"""
import datetime
class TradeModel:
"""
Enum used to index the different values in a raw trade array
"""
ID = 0
PAIR = 1
MTS_CREATE = 2
ORDER_ID = 3
EXEC_AMOUNT = 4
EXEC_PRICE = 5
ORDER_TYPE = 6
ORDER_PRICE = 7
... |
class Solution:
def isLongPressedName(self, name: str, typed: str) -> bool:
if len(name) == 0: return True
if len(typed) < len(name): return False
a, b = len(name), len(typed)
i, j = 0, 0
while j < b:
if i == a:
if typed[j] != name[a - 1]: return... |
import codecs
import os.path
from setuptools import find_packages, setup
with open("README.md", "r") as fh:
long_description = fh.read()
def read(rel_path):
here = os.path.abspath(os.path.dirname(__file__))
with codecs.open(os.path.join(here, rel_path), 'r') as fp:
return fp.read()
def get_ver... |
"""
Copyright 2017 BlazeMeter 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, software... |
from typing import Generator, Tuple, Union
import json
import pytest
import os
from kat.harness import Query
from abstract_tests import AmbassadorTest, ServiceType, HTTP, AHTTP, AGRPC, Node
from tests.selfsigned import TLSCerts
from ambassador import Config
class AuthenticationGRPCTest(AmbassadorTest):
targe... |
"""Top-level package for synmod."""
__author__ = """Akshay Sood"""
__email__ = "sood.iitd@gmail.com"
__version__ = "0.1.4"
from synmod.master import synthesize # noqa: F401
|
import os
import sys
import io
import base64
import json
import logging
from PIL import Image, ImageDraw
import torch.utils.data
import torchvision
from azureml.core.model import Model
class Inference():
def __init__(self) -> None:
self.max_width = 1080
def predict(self, img, prediction):
mas... |
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("oauth2_provider", "0001_initial"),
]
operations = [
migrations.AddField(
model_name="Application",
name="skip_authorization",
... |
from typing import Union, List, Optional
from pyspark.sql.types import StructType, StructField, StringType, ArrayType, DataType
# This file is auto-generated by generate_schema so do not edit manually
# noinspection PyPep8Naming
class RatioSchema:
"""
A relationship of two Quantity values - expressed as a nu... |
# Copyright 2018 Ocean Protocol Foundation
# SPDX-License-Identifier: Apache-2.0
from osmosis_driver_interface.computing_plugin import AbstractPlugin
class Plugin(AbstractPlugin):
def __init__(self, config=None):
self.config=config
def type(self):
"""str: the type of this plugin (``'On pre... |
"""
Functions to obtain git repository information
"""
import json
import subprocess
import shlex
import sys
from pathlib import Path
def _run_command(path, command):
"""Safely run command in certain path
"""
if not Path(path).is_dir():
raise ValueError('{} is not a directory'.format(path))
o... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import json
import sys
import os
import argparse
import glob
#import cStringIO
reload(sys)
sys.setdefaultencoding("utf-8")
try: import simplejson as json
except: import json
# {"version":"1.0","properties":[{"id":"light_switch","name":"电灯开关","desc":"控制电灯开灭","required":true... |
# Python program to search all
# anagrams of a pattern in a text
MAX=256
# This function returns true
# if contents of arr1[] and arr2[]
# are same, otherwise false.
def compare(arr1, arr2):
for i in range(MAX):
if arr1[i] != arr2[i]:
return False
return True
# This function search for all
# permuta... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union
from ... import _utilities, _tables
from... |
class Solution:
#check one can reach the last index #greedy
def canJump(self, nums: List[int]) -> bool:
n=len(nums)
f=n-1
for i in range(n-2,-1,-1):
if nums[i]+i>=f:
f=i
return f==0
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
| This file is part of the web2py Web Framework
| Copyrighted by Massimo Di Pierro <mdipierro@cs.depaul.edu>
| License: LGPLv3 (http://www.gnu.org/licenses/lgpl.html)
Background processes made simple
---------------------------------
"""
from __future__ import print_fu... |
"""Tests for the Cooperator strategy."""
import axelrod
from .test_player import TestPlayer
C, D = axelrod.Action.C, axelrod.Action.D
class TestCooperator(TestPlayer):
name = "Cooperator"
player = axelrod.Cooperator
expected_classifier = {
"memory_depth": 0,
"stochastic": False,
... |
'''
Author: Danijel Kivaranovic
Title: Neural network (Keras) with sparse data
'''
## import libraries
import numpy as np
np.random.seed(123)
import pandas as pd
import subprocess
from scipy.sparse import csr_matrix, hstack
from sklearn.metrics import mean_absolute_error
from sklearn.preprocessing import StandardS... |
# -*- coding: utf-8 -*-
import subprocess
from os.path import dirname
def git_version():
"""Returns the git version of the module
This function returns a string composed of the abbreviated Git hash of the
module source, followed by the date of the last commit. If the source has
some local modificat... |
#!C:\Users\ROZZI\PycharmProjects\Power\Assignment\venv\Scripts\python.exe
# EASY-INSTALL-ENTRY-SCRIPT: 'setuptools==40.8.0','console_scripts','easy_install-3.5'
__requires__ = 'setuptools==40.8.0'
import re
import sys
from pkg_resources import load_entry_point
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-sc... |
import time
from pathlib import Path
import superannotate as sa
from .test_assign_images import safe_create_project
PROJECT_NAME_CPY = "test image copy 1"
PROJECT_NAME_CPY_MULT = "test image copy mult 2"
PROJECT_NAME_MOVE = "test image move 3"
PROJECT_NAME_CPY_FOLDER = "test image copy folder 4"
def test_image_copy... |
import os,glob
filenames = [os.path.splitext(os.path.basename(f))[0] for f in glob.glob(os.path.dirname(__file__)+"/*.py")]
filenames.remove('__init__')
__all__ = filenames
|
# Generated by Django 4.0.1 on 2022-01-16 18:35
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('core', '0090_auto_20220105_1330'),
]
operations = [
migrations.AlterField(... |
# coding=utf-8
# Copyright 2020 The Edward2 Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... |
#!/usr/bin/python2
# sypy.py: Example interpreter for Symbolic Python.
# Call with command line arguments: <script-file> [input]
import sys
import ast
script = open(sys.argv[1]).read()
if len(sys.argv) > 2:
_ = ast.literal_eval(sys.argv[2])
else:
_ = None
for char in script:
if char.isalnum():
print("In... |
import traceback
from _pydev_bundle.pydev_is_thread_alive import is_thread_alive
from _pydev_imps._pydev_saved_modules import threading
from _pydevd_bundle.pydevd_constants import get_thread_id
from _pydevd_bundle.pydevd_dont_trace_files import DONT_TRACE
from _pydevd_bundle.pydevd_kill_all_pydevd_threads import kill_... |
"""
Support for Sensibo wifi-enabled home thermostats.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/climate.sensibo/
"""
import asyncio
import logging
import aiohttp
import async_timeout
import voluptuous as vol
from homeassistant.const import (
... |
""" -----------------------------------------------------
# TECHNOGIX
# -------------------------------------------------------
# Copyright (c) [2022] Technogix SARL
# All rights reserved
# -------------------------------------------------------
# Keywords to manage aws route53 tasks
# --------------------------... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# ==============================================================================
#
# File Name : thepysec/john/version.py
#
# Creation Date : Fri 28 Dec 2018 03:51:58 PM EET
#
# Last Modified : Sat 16 Mar 2019 04:07:23 PM EET (16:07)
#
# ================... |
"""Climate support for Shelly."""
from __future__ import annotations
import asyncio
import logging
from typing import Any, Final, cast
from aioshelly.block_device import Block
import async_timeout
from homeassistant.components.climate import ClimateEntity
from homeassistant.components.climate.const import (
CURR... |
"""
Segmentation:
data =
{'data': [num_images, c, h, w],
'im_info': [num_images, 4] (optional)}
label =
{'label': [batch_size, 1] <- [batch_size, c, h, w]}
"""
import numpy as np
from utils.image import get_segmentation_image, tensor_vstack
def get_segmentation_test_batch(segdb, config):
... |
from pstraw import Straw, Store
import os
from datetime import datetime
case_dir = os.path.dirname(os.path.abspath(__file__))
# work_parh = os.getcwd()
# 指定
db = Straw('test_db_create',
CONF_PATH=os.path.join(case_dir, 'config.ini'),
SQL_PATH=os.path.join(case_dir, '.'),
LOG_PATH=os.p... |
import os
import pytest
_profile_keyword = "profile"
def pytest_addoption(parser):
default_data_path = os.path.realpath(os.path.join(os.path.dirname(__file__), "data"))
parser.addoption( f"--{_profile_keyword}", action="store_true", default=False, help="run profiling tests" )
parser.addoption( "--data"... |
# 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 ... |
#!/usr/bin/env python
import argparse
import json
import re
from multiprocessing.dummy import Pool as ThreadPool
try:
import urllib.request as urlrequest
from http.cookiejar import CookieJar
except ImportError:
import urllib2 as urlrequest
from cookielib import CookieJar
BT_URL = 'https://www.bluetooth.com'
G... |
import os
import shutil
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple
import yaml
from plotter import __version__
from plotter.consensus.coinbase import create_puzzlehash_for_pk
from plotter.ssl.create_ssl import generate_ca_signed_cert, get_plotter_ca_crt_key, make_ca_cert
from plotter... |
from datetime import datetime
from django.utils.timezone import utc
from unittest import mock
import pytest
from awx.main.models import (JobEvent, ProjectUpdateEvent, AdHocCommandEvent,
InventoryUpdateEvent, SystemJobEvent)
@pytest.mark.parametrize('job_identifier, cls', [
['job_id',... |
from __future__ import absolute_import, division
import copy
import logging
import socket
import time
from kafka.errors import KafkaConfigurationError, UnsupportedVersionError
from kafka.vendor import six
from kafka.client_async import KafkaClient, selectors
from kafka.consumer.fetcher import Fetcher
from kafka.con... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
MIT License
Copyright (c) 2020 Hiroyasu Tsukamoto https://hirotsukamoto.com/
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 restricti... |
import pytest
from dvc.utils.serialize import (
EncodingError,
YAMLFileCorruptedError,
load_yaml,
parse_yaml,
)
def test_parse_yaml_duplicate_key_error():
text = """\
mykey:
- foo
mykey:
- bar
"""
with pytest.raises(YAMLFileCorruptedError):
parse_yaml(text, "mypath... |
import datetime
from django import forms
from django.core.exceptions import ValidationError
from django.utils.translation import ugettext_lazy as _
class RenewBookForm(forms.Form):
renewal_date = forms.DateField(
help_text="Enter a date between now and 4 weeks (default 3).")
def clean_renewal_date(s... |
# CMU 16-726 Learning-Based Image Synthesis / Spring 2022, Assignment 3
# The code base is based on the great work from CSC 321, U Toronto
# https://www.cs.toronto.edu/~rgrosse/courses/csc321_2018/assignments/a4-code.zip
import os
import torch
def to_var(x):
"""Converts numpy to variable."""
if torch.cuda.is... |
class Salary:
def calculate(self, hours: float) -> float:
return self.rate * hours
class Promotable:
def promote(self, _raise: float) -> None: # _raise so it doesn't clash with Python's raise keyword!
self.rate += _raise
class Employee(Salary, Promotable):
def __init__(self, ... |
# Copyright 2022 The Kubric 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 w... |
# Copyright 2017 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... |
#!/usr/bin/env python
# copyright 2014 UNL Nimbus Lab
#
# 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... |
# An example of using the viterbi algorithm to determine the most likely POS tag
# for a given sequence of words.
from learnz.ai.viterbi import viterbi
states = {"verb", "noun"}
# P(A | B) = transition_probabilities[B][A]
transition_probabilities = {
None: {
"verb": 0.25,
"noun": 0.75
},
... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import psutil,sendemail,checkip,time,sendwechat,getconfig
def run():
ip = checkip.ipaddress()
memthreshold=getconfig.key('global','memthreshold')
while True:
meminfo = psutil.virtual_memory()
memusagepre = meminfo.percent
# print memusagepr... |
"""Select platform for Advantage Air integration."""
from homeassistant.components.select import SelectEntity
from .const import DOMAIN as ADVANTAGE_AIR_DOMAIN
from .entity import AdvantageAirEntity
ADVANTAGE_AIR_INACTIVE = "Inactive"
async def async_setup_entry(hass, config_entry, async_add_entities):
"""Set ... |
import argparse
import datetime
import os
import time
import shutil
import torch
import torchvision
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.optim
from torch.nn.utils import clip_grad_norm
from torch.utils.tensorboard import SummaryWriter
from dataset import TSNDataSet
from models imp... |
# 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 ... |
# -*- mode: python; tab-width: 4;
# Copyright (C) 2014 Thema Consulting
#
# This file is part of QuantLib, a free-software/open-source library
# for financial quantitative analysts and developers - http://quantlib.org/
#
# QuantLib is free software: you can redistribute it and/or modify it under the
# terms of the Qua... |
"""
loads the semi-structured drain data, and processes it for the CNN
"""
import numpy as np
import pandas as pd
import time
from sliding_window_processor import collect_event_ids, FeatureExtractor
if __name__ == "__main__":
data_version = "_v5"
data_version = "_tf-idf{}".format(data_version)
# where ... |
# -*- coding: utf-8 -*-
# python imports
from __future__ import unicode_literals
# lib imports
from django.db.models import TextChoices
from django.utils.translation import ugettext_lazy as _
class SKillType(TextChoices):
ADVANCE_TYPE = 'ADVANCE', _('Advance')
INTERMEDIATE_TYPE = 'INTERMEDIATE', _('Intermedi... |
from turtle import *
w = Screen()
#w.tracer(0,0)
w.bgcolor("black")
w.delay(0)
POS_X = 0
POS_Y = 10
DIS_Y = 70
s = 1
class Slider(Turtle):
def __init__(self, x, y , dis , st = f"Slider {s}" ):
global s
s+=1
Turtle.__init__(self)
self.shape("square")
self.s... |
from vumi.transports.vumi_bridge.vumi_bridge import (
GoConversationTransport, GoConversationClientTransport,
GoConversationServerTransport)
__all__ = [
'GoConversationTransport',
'GoConversationClientTransport',
'GoConversationServerTransport',
]
|
#!/usr/bin/env python
# http://www.pythonchallenge.com/pc/def/ocr.html
with open("input.txt") as f:
s = "".join(f.readlines())
print("".join(filter(lambda c: c.isalpha(), s)))
|
# coding: utf-8
"""
Kubernetes
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501
OpenAPI spec version: v1.15.6
Generated by: https://openapi-generator.tech
"""
import pprint
import re # noqa: F401
import six
class V1Deployme... |
"""
Internal hook annotation, representation and calling machinery.
"""
import inspect
import sys
import warnings
from .callers import _legacymulticall, _multicall
class HookspecMarker(object):
""" Decorator helper class for marking functions as hook specifications.
You can instantiate it with a project_name... |
#!/usr/bin/python
# -*- coding:utf-8 -*-
"""
Perceptron
感知机
"""
from functools import reduce
class Perceptron(object):
"""
Desc:
感知器类
Args:
None
Returns:
None
"""
def __init__(self,input_num,activator):
"""
Desc:
初始化感知器
Args:
... |
# Parallel Python Software: http://www.parallelpython.com
# Copyright (c) 2005-2012, Vitalii Vanovschi
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must reta... |
import os.path
from unittest import TestCase
import py_find_injection
SAMPLE_PATH = os.path.realpath(os.path.join(os.path.dirname(__file__), 'samples'))
class TestSimple(TestCase):
def test_good_file(self):
errors = py_find_injection.check(os.path.join(SAMPLE_PATH, 'good_script.py'))
self.asser... |
import boto3
import os
from botocore.exceptions import ClientError, NoCredentialsError
class AWS:
def __init__(self, logger):
self.aws_authenticated = False
self.set_logger(logger)
self._set_account_id()
self._set_region()
self.get_notification_variables()
self.boto... |
import homeassistant.helpers.config_validation as cv
import voluptuous as vol
from .const import ATTR_CONDITION
from .const import ATTR_MESSAGES
from .const import ATTR_SERVICE
MESSAGE_SCHEMA = vol.Schema(
{
vol.Required("name"): cv.string,
vol.Required(ATTR_SERVICE): cv.service,
vol.Optio... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Jan 17 12:15:41 2020
@author: thausmann
"""
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation
class Particle():
pos = []
vel = []
walls = []
def __init__(self, position, walls):
self.pos... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.