content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
"""A GRU layer."""
import numpy
import random
import sys
import theano
from theano.ifelse import ifelse
from theano import tensor as T
from rnnlayer import RNNLayer
class GRULayer(RNNLayer):
"""A GRU layer.
Parameter names follow convention in Richard Socher's CS224D slides.
"""
def create_vars(self, create_... | python |
# ------------------------------------------------------------------------------
#
# Project: pygeofilter <https://github.com/geopython/pygeofilter>
# Authors: Fabian Schindler <fabian.schindler@eox.at>
#
# ------------------------------------------------------------------------------
# Copyright (C) 2021 EOX IT Servic... | python |
import cv2
frameWidth = 700
frameHeight = 500
# number plate cascade
numPlateCascade = cv2.CascadeClassifier("haarcascade_russian_plate_number.xml")
# Threshold for area
minArea = 200
color = (255,0,255)
# video on using webcam
cap = cv2.VideoCapture(0)
cap.set(3, 700) #setting width
cap.set(4, 500) #setting height
cap... | python |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from rest_framework import serializers
from .models import Store
class StoreSerializer(serializers.ModelSerializer):
"""
Serializer for Store model
"""
class Meta:
model = Store
| python |
#
# Incremental Saves
# Save your blend files with an incrementing version number.
#
# Shortcut key: Shift-Ctrl-S
# * This overrides the "Save As" hotkey. If you want to keep Shift-Ctrl-S
# for "Save As", edit the hotkey below to your desired shortcut before
# you load the add-on into Blender.
# * When you disable ... | python |
# coding=utf-8
# Copyright 2019 The TensorFlow Datasets 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 appl... | python |
# @file dsc_translator_test.py
# Tests for the translator for the EDK II DSC data model object
#
# Copyright (c) Microsoft Corporation
#
# SPDX-License-Identifier: BSD-2-Clause-Patent
##
import unittest
import os
import tempfile
from edk2toollib.uefi.edk2.parsers.dsc_parser import DscParser
# from edk2toollib.uefi.edk2... | python |
#!/usr/bin/env python3
# @generated AUTOGENERATED file. Do not Change!
from dataclasses import dataclass
from datetime import datetime
from gql.gql.datetime_utils import DATETIME_FIELD
from gql.gql.graphql_client import GraphqlClient
from functools import partial
from numbers import Number
from typing import Any, Call... | python |
import torch
from torch import nn
from .modules import ConvLeakyReLU, ConvBnLeakyReLU
from .modules import SelfAttention
class MapDiscriminator(nn.Module):
'''
The Map Discriminator
Args:
map_channels (default: int=3): Number of Map input channels
roi_channels (default: int=3): Number of ... | python |
#
# @lc app=leetcode id=1247 lang=python3
#
# [1247] Minimum Swaps to Make Strings Equal
# https://leetcode.com/problems/minimum-swaps-to-make-strings-equal/
#
import unittest
# @lc code=start
class Solution:
def minimumSwap(self, s1: str, s2: str) -> int:
"""s1 and s2 are of equal length and only contain ... | python |
#!/opt/anaconda/bin python
from pageRank import MRpageRank
import time
import sys
import subprocess as sp
outPATH = '/user/lteo01/HW9/output' # Altiscale
#outPATH = '/user/root/HW9/output' # docker
SOURCE = sys.argv[1]
RUNMODE = sys.argv[2]
ITER = sys.argv[3]
D = sys.argv[4]
N = sys.argv[5]
sp.Popen(['hadoop', 'fs'... | python |
#!/usr/bin/env python3
"""
Description: Get pisture collections from www.toutiao.com
Tip: This script comes from https://github.com/smslit/spider-collection/tree/master/ttpic
Link: https://www.smslit.top/2018/06/21/spider-practice-pic-dog/
"""
__author__ = '5km(smslit)'
__date__ = '20180627'
import os
import requests... | python |
from pwtools.sql import sql_column
import pytest
def test_sql_column():
x = sql_column(key='foo',
sqltype='integer',
lst=[1,2,3])
for num, xx in zip([1,2,3], x):
assert xx.sqlval == num
assert xx.fileval == num
x = sql_column(key='foo',
... | python |
# Example usage
# python compute_mask.py swa4D.nii.gz mask.nii.gz
# python compute_mask.py swa*.nii mask.nii.gz
from nipy.neurospin.utils.mask import compute_mask_files
import sys
if __name__ == '__main__':
if len(sys.argv) < 3:
print """Usage : python compute_mask [ -s copyfilename ] inputfilename(s) out... | python |
from datetime import datetime
def convert_epoch_to_utc_datetime(epoch: int) -> datetime:
return datetime.utcfromtimestamp(epoch)
def convert_epoch_to_human_readable_date(epoch: int) -> str:
"""Convert epoch timestamp into a human readable date
Get the date (in UTC)
Args:
epoch (int):
R... | python |
"""
Demonstrates logical operators
"""
b1 = True #Four variables used in the demonstrations below
b2 = False
b3 = False
b4 = True
result1 = b1 and b2 #Result of b1 and'ed with b2
print("b1 and b2 is", result1) ... | python |
import vk_api
import requests
from time import sleep
from source.static.methods import webp_to_png
from os import remove
import logging
class VkApi:
def __init__(self, token: str):
self.vk = vk_api.VkApi(token=token)
self.logger = logging.getLogger('vk')
def get_self_id(self) -> int:
... | python |
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
{
'variables': {
'hb_directory': '../third_party/externals/harfbuzz',
},
'targets': [
{
'target_name': 'harfbuzz',
'type': 'sta... | python |
#!/usr/bin/env python3
import testbench
import socket
class TestVirtualMachine(testbench.TestCase):
def test_binary_exists(self):
sftp = self.ssh.open_sftp()
filename = "/usr/sbin/apache2"
try:
sftp.stat(filename)
except FileNotFoundError:
self.fail("File d... | python |
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
"""
About: Basic example to test quantum connection with Qontainernet
"""
import time
import csv
import os
import numpy as np
from itertools import filterfalse
from comnetsemu.cli import CLI
from comnetsemu.net import Containernet
from mininet.link impo... | python |
import importlib
import inspect
from django import template
from django.template.response import TemplateResponse
from django.urls import resolve, Resolver404
from tag_parser.basetags import BaseNode
register = template.Library()
@register.tag("include_view")
class ImportViewNode(BaseNode):
min_args = 1
max... | python |
from django.apps import AppConfig
class AutoRestConfig(AppConfig):
name = 'auto_rest'
| python |
#!/usr/bin/env python3
# Copyright © 2020 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... | python |
"""Provides named imports for lambda deployment."""
from api_batch_show.main import lambda_handler as api_batch_show_lambda_handler
from api_batch_create.main import lambda_handler as api_batch_create_lambda_handler
from api_workforce_show.main import lambda_handler as api_workforce_show_lambda_handler
from api_batch_... | python |
# -*- coding: utf-8 -*-
__author__ = 'zhiquan'
import re
import codecs
# input_file = codecs.open("data/source.txt", 'rb', encoding='utf8')
# 暂存无页眉页脚原始文本
# output_file = codecs.open("data/source_without_header.txt", 'wb', encoding='utf8')
# 去除页眉页脚
'''page_header_re = re.compile(u"普通高等.*专业介绍")
for line in input_file... | python |
#Uzdevums. Noprasiet lietotājam mēneša algas apjomu un nostrādāto gadu skaitu.
#Izvadiet bonusu.
#Piemērs 5 gadu stāžs, 1000 Eiro alga, bonuss būs 450 Eiro.
salary = float(input("what is your salary "))
years = float(input("How long do you work here "))
bonuss = (years-2)*0.15*salary
bonuss = round(bonuss, 2) # s... | python |
from datetime import date
class TimeInterval(object):
start = None
end = None
def __init__(self, start, end):
assert start is None or isinstance(start, date), \
"start should be a date instance"
assert end is None or isinstance(end, date), \
"end should be a date i... | python |
from aero.Rocket import Rocket
import numpy as np
from aero.Functions.Models.Thrust import Thrust
def Mass_Non_Lin(t: float, Rocket: Rocket):
if t>Rocket.get_burn_time():
mass = Rocket.get_empty_mass() + Rocket.get_motor_mass() - Rocket.get_propel_mass()
dmassdt = 0
else:
tt = np.linsp... | python |
# -*- coding: utf-8 -*-
#
# Common (non-language-specific) configuration for Read The Docs & Sphinx
#
# Based on a Read the Docs Template documentation build configuration file,
# created by sphinx-quickstart on Tue Aug 26 14:19:49 2014.
#
# This file is imported from a language-specific conf.py (ie en/conf.py or
# zh_... | python |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
from django import forms
from .models import Environment,WorkOrder,WorkOrderFlow,WorkOrderGroup,Vars,VarsGroup,ConfigCenter
from django_celery_results.models import TaskResult
class ConfigCenter_form(forms.ModelForm):
class Meta:
model = ConfigC... | python |
import os
from shutil import copyfile
from setuptools import setup
from setuptools.command.install import install
path = os.path.dirname(os.path.realpath(__file__))
unit_dir = os.path.join(path, 'scripts', 'systemd')
class CustomInstallCommand(install):
def run(self):
if os.path.isdir('/etc/systemd/syst... | python |
class Node:
def __init__(self, value):
self.value = value
self.status = False
def mark_node(self):
self.status = True
def reset_node_status(self):
self.status = False
| python |
from typing import Sequence, Dict
import numpy as np
from abm1559.config import rng
from abm1559.utils import (
constants,
)
from abm1559.chain import Block
from abm1559.users import User, User1559
def spawn_poisson_demand(timestep: int, demand_lambda: float, UserClass, rng: np.random.Generator = rng, **kwargs)... | python |
#!/usr/bin/env python3
import numpy as np
import speech_recognition as sr
from subprocess import call
from time import sleep
from topics.date import DateAgent
from topics.time import TimeAgent
from topics.definition import DefinitionAgent
from topics.default import DefaultAgent
from topics.music import MusicAgent
fro... | python |
from fmskill.utils import make_unique_index
import pandas as pd
import warnings
from mikeio import eum
from ..observation import PointObservation, TrackObservation
from ..comparison import PointComparer, TrackComparer
from .abstract import ModelResultInterface, MultiItemModelResult, _parse_itemInfo
class _DataFrameB... | python |
'''
Authors: Nishant Kumar.
Copyright:
Copyright (c) 2018 Microsoft Research
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
... | python |
from ..Channel import Channel
from ..Utilities import counter
demFlowCounter = counter()
class DemandFlow(Channel):
"""
This is a component that will force the solver to assign a specific mass flow rate at a point in the system.
This is also used to initially introduce fluids to the engine.
It is inad... | python |
from django.http import HttpResponse, JsonResponse
from rest_framework.parsers import JSONParser
from rest_framework.authentication import TokenAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.decorators import api_view, permission_classes, \
authentication_classes
fro... | python |
from copy import deepcopy
import math
import rastervision as rv
from genetic.semantic_segmentation_backend import (
SemanticSegmentationBackend)
from genetic.simple_backend_config import (
SimpleBackendConfig, SimpleBackendConfigBuilder)
GP_SEMANTIC_SEGMENTATION = 'GP_SEMANTIC_SEGMENTATION'
class TrainOptio... | python |
"""
This is module should not import any other runez module, it's the lowest on the import chain
"""
import pathlib
import re
from collections import defaultdict
from runez.system import _R, flattened, joined, stringified
def parsed_tabular(content):
"""
Args:
content (str): Tabular output, such as ... | python |
#
# CIN.py
#
# (c) 2020 by Andreas Kraft
# License: BSD 3-Clause License. See the LICENSE file for further details.
#
# ResourceType: ContentInstance
#
from typing import Tuple
from Constants import Constants as C
from Validator import constructPolicy
from .Resource import *
import Utils
# Attribute policies for this... | python |
'''
_ _ _
__| |_ _____ | | | __ _
/ _` \ \ /\ / / _ \| | |/ _` |
| (_| |\ V V / (_) | | | (_| |
\__,_| \_/\_/ \___/|_|_|\__,_|
An official requests based wrapper for the Dwolla API.
This file contains functionality for all OAuth related endpoints.
'''
import constants as c
from ... | python |
import torch
import torch.optim as optim
from torch.autograd import Variable
from dataloader import SVMDataset
from torch.utils.data import DataLoader
import argparse
from tensorboardX import SummaryWriter
import os
from models import SVMRegressor, Generator8, UGen, Critic3, Critic4, Critic8
import re
import pickle
imp... | python |
import unittest
from unittest.mock import patch, call
from unittest.mock import MagicMock
from python_sqs_consumer.processor import S3Processor, S3RecordProcessor, SQSMessageProcessor, SQSMessagesProcessor, SNSRecordProcessor
class TestProcessor(unittest.TestCase):
def test_s3_processor(self):
mock = {"R... | python |
import os, sys
import numpy as np
from data3d.suncg_utils.suncg_preprocess import read_summary
from data3d.suncg_utils.celing_floor_room_preprocessing import preprocess_cfr
PARSED_DIR = '/DS/SUNCG/suncg_v1/parsed'
def rename_file():
file_names = os.listdir(PARSED_DIR)
file_names.sort()
num = len(file_names)
f... | python |
"""
Code to experiment with writing things to xarray datasets, especially
regarding coordinates.
"""
import numpy as np
import xarray as xr
import pandas as pd
NT, NR, NC = (4,5,6)
Lon = np.linspace(-130,-122,NC)
Lat = np.linspace(42,52,NR)
lon, lat = np.meshgrid(Lon,Lat)
time = pd.date_range(start='1/1/2021', perio... | python |
from rest_framework import serializers
from .models import Event
class EventSerializer(serializers.ModelSerializer):
class Meta:
model = Event
fields = ('title', 'body', 'created_on')
| python |
test = { 'name': 'q2_1',
'points': 2,
'suites': [ { 'cases': [ { 'code': '>>> full_data.num_rows == 492\n'
'True',
'hidden': False,
'locked': False},
... | python |
def listtest(tlist):
tlist.append("1")
listtest(tlist)
inlist = ["0"]
listtest(inlist)
print inlist | python |
# -*- coding: utf-8 -*-
from yacs.config import CfgNode
from .builder import build_collate, build_folder, build_transformers, build_loader
from .config import get_datasets_cfg
__all__ = [
'get_datasets_cfg',
'build_collate', 'build_folder', 'build_transformers', 'build_loader',
]
| python |
from flask import render_template, flash, redirect
from app import app
@app.route('/')
@app.route('/index')
def index():
return render_template('index.html',
title='Home'
)
@app.route('/about')
def about():
return render_template('about.html',
title='About'
)
@app.route('/visualizatio... | python |
"""381. Insert Delete GetRandom O(1) - Duplicates allowed
https://leetcode.com/problems/insert-delete-getrandom-o1-duplicates-allowed/
Design a data structure that supports all following operations in average O(1) time.
Note: Duplicate elements are allowed.
insert(val): Inserts an item val to the collection.
... | python |
import numpy as np
from math import sin,cos,pi
class Pose(object):
"""The pose class allows for a posing of objects in 2D space. The pose uses a right-hand coordinate system with counter-clockwise measurement of theta from the x-axis
There are several ways to create a pose:
========... | python |
import operator
from typing import Sequence, Callable, Any, TYPE_CHECKING
import flowsaber
from flowsaber.core.engine.scheduler import Job, TaskManager
if TYPE_CHECKING:
from flowsaber.core.task import Task
from flowsaber.core.flow import Flow
class Solver(object):
"""Multiple knapsack problem solver.
... | python |
#!/usr/bin/python
# Copyright (c) 2018 PythonAnywhere LLP.
# All Rights Reserved
#
## FIXME: this file is a pre-release copy of a built-in PythonAnywhere script.
## remove once the updated version is deployed to live.
import os
import sys
HOME = os.path.expanduser('~')
TMP = '/tmp'
def write_temporary_bashrc(virtu... | python |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
import six
import numpy as np
from gensim.models import Word2Vec
class Word2vecVocabulary(object):
def __init__(self, unknown_token="<UNK>", support_reverse=True):
self._freeze = Fals... | python |
# Generated by Django 3.0.12 on 2021-02-22 13:43
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('users', '0005_auto_20210221_1538'),
]
operations = [
migrations.AddField(... | python |
# -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community
Edition) available.
Copyright (C) 2017-2020 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in co... | python |
#!/usr/bin/env python
from __future__ import absolute_import, print_function
import sys
from collections import Counter, defaultdict
from . import GeminiQuery
from . import sql_utils
try:
from compiler import compile
except ImportError:
basestring = str
from .gemini_constants import *
from .gemini_bcolz impor... | python |
#
# PySNMP MIB module DISMAN-EVENT-MIB (http://pysnmp.sf.net)
# ASN.1 source http://mibs.snmplabs.com:80/asn1/DISMAN-EVENT-MIB
# Produced by pysmi-0.0.7 at Sun Feb 14 00:07:55 2016
# On host bldfarm platform Linux version 4.1.13-100.fc21.x86_64 by user goose
# Using Python version 3.5.0 (default, Jan 5 2016, 17:11:52)... | python |
"""
Outline Tab Serializers.
"""
from django.utils.translation import ngettext
from rest_framework import serializers
from lms.djangoapps.course_home_api.dates.serializers import DateSummarySerializer
from lms.djangoapps.course_home_api.progress.serializers import CertificateDataSerializer
from lms.djangoapps.course_... | python |
from numpy.distutils.fcompiler import get_default_fcompiler
import sys
import os
fcompile = get_default_fcompiler(os.name, sys.platform, True)
install_dir = sys.argv[1]
os.system("python setup.py " +
"config_fc --fcompiler=" + str(fcompile) +
" build_clib --fcompiler=" + str(fcompile) +
... | python |
from dataclasses import dataclass
from sqlalchemy import String
import sqlalchemy_utils as su
import uuid
from ..utils import BaseModel, Column, TimeRecordableCRUD
@dataclass
class Usuario(TimeRecordableCRUD, BaseModel):
__tablename__ = 'usuario'
id: str = Column(su.UUIDType, primary_key=True, default=uuid.... | python |
from .base import *
DEBUG = True
# look into django debug_toolbar app to install for local
| python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@Author : Xiaobo Yang
@Contact : hal_42@zju.edu.cn
@Time : 2021/4/26 21:58
@File : check_img_exits.py
@Software: PyCharm
@Desc :
"""
from imghdr import what
import os.path as osp
__all__ = ["check_img_exits"]
def check_img_exits(img_path: str) -> bool:
... | python |
# Generated by Django 2.0.6 on 2018-06-20 09:20
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('films', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='film',
n... | python |
URL = "https://www.prullenbakvaccin.nl"
FORM = "#location-selector"
| python |
#!/usr/bin/env python
# coding: utf-8
# # Clear Data
# <div style="position: absolute; right:0;top:0"><a href="./tools.ipynb" style="text-decoration: none"> <font size="5">←</font></a>
# <a href="../evaluation.ipynb" style="text-decoration: none"> <font size="5">↑</font></a></div>
#
# This script deletes all files in... | python |
# Duration Collection Generator
# Jacques Mathieu - 11/19/18
MAX_DUR = 5000.0
MIN_DUR = 5.0
def gen_dur_coll(method, params):
if method == "asc":
return gen_asc_dur_coll(params)
def gen_asc_dur_coll(params):
base_dur = params['base_dur']
max_dur = params['max_dur']
if base_dur < MIN_DUR:
... | python |
import asyncio
import websockets
import json
from uuid import uuid4
# On Minecraft, when you type "/connect localhost:3000" it creates a connection
async def mineproxy(websocket, path):
print('Connected')
# Tell Minecraft to send all chat messages. Required once after Minecraft starts
await websocket.sen... | python |
import numpy as np
class BayesBlocks (object):
"""Creates Bayesian blocks from input data.
Based on Scargle et al, 2013
:param data: dict containing one or more of the following keys:
- 't': iterable (1D) containing the times of events or bins.
- 'x': iterable (1D) containing t... | python |
# Generated from /Users/pdodds/src/kodexa/kodexa/resources/selector.g4 by ANTLR 4.9.1
# encoding: utf-8
from antlr4 import *
from io import StringIO
import sys
if sys.version_info[1] > 5:
from typing import TextIO
else:
from typing.io import TextIO
def serializedATN():
with StringIO() as buf:
buf.write(... | python |
from celery import task
from tenant_schemas.utils import tenant_context
@task
def send_all_notification_task(tenant, **kwargs):
with tenant_context(tenant):
pk = kwargs.pop('instance_id')
model = kwargs.pop('model')
created = kwargs.pop('created', False)
send_email = kwargs.pop('se... | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 20 14:09:11 2019
@author: charlie
"""
from grass.pygrass.modules.shortcuts import vector as v
from grass.script import run_command
#create new column in points map to hold lithology
ksn_points_map = 'chan_segs_points_trimmed'
new_col_name = 'lith_... | python |
import numpy as np
import matplotlib.pyplot as plt
# Create some training samples
# To demonstrate L2 regularisations ability to minimize the impact
# of outliers, we fabricate training data where X and Y are roughly
# linearly related and then insert a few outliers into Y.
# Construct X
X = np.linspace(0, 10, 50)
... | python |
from typing import List
from json import dumps
from pathlib import Path
from tdw.controller import Controller
from tdw.tdw_utils import TDWUtils
from tdw.add_ons.object_manager import ObjectManager
from tdw.add_ons.oculus_touch import OculusTouch
from tdw.vr_data.oculus_touch_button import OculusTouchButton
from tdw.ad... | python |
class InputStreamError(Exception):
""" An error occurred while reading source input """
class InputStream(object):
def __init__(self, data):
self.data = data
self.pos = 0
self.line = 1
self.col = 0
def next(self):
self.pos += 1
ch = self.data[self.pos]
... | python |
#!usr/bin/env python3
# -*- coding: utf-8 -*-
import pkgutil
from bwtougu.__main__ import cli
from bwtougu.api.api_base import export_as_api
__all__ = [
'__version__',
'version_info'
]
__version__ = pkgutil.get_data(__package__, 'VERSION.txt').decode('ascii').strip()
version_info = tuple(int(v) if v.isdigit... | python |
# 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 ... | python |
import logging
import os
import secrets
import ssl
import pyotp
import pymongo
from .common import AUTH_DEV_MODE
def get_env_param(name, def_val=None, try_file=False):
val = os.getenv(name, def_val)
if try_file and val and os.path.isfile(val):
with open(val) as fp:
return fp.read().strip(... | python |
# Copyright 2017 The LUCI Authors. All rights reserved.
# Use of this source code is governed under the Apache License, Version 2.0
# that can be found in the LICENSE file.
DEPS = [
'properties',
'step',
'url',
]
def RunSteps(api):
api.url.validate_url(api.properties['url_to_validate'])
def GenTests(api):
... | python |
import requests
from slugify import slugify
from mycroft.util import LOG
API_URL = 'http://localhost:5005/'
MAX_VOLUME = 32
DELTA_VOLUME = 5
def _get(url):
LOG.info(url)
return requests.get(url)
def get(url):
response = _get(url)
return response.ok
def play(speaker):
return get(API_URL + spea... | python |
from django import forms
from django.core.validators import MaxValueValidator
from crispy_forms.helper import FormHelper
from captcha.fields import ReCaptchaField
class ContactForm(forms.Form):
helper = FormHelper()
email = forms.EmailField(
label="Podaj swój email kontaktowy",
widget=forms.Em... | python |
#!/usr/bin/env python3
""" AI Model Data Class.
Provides the AI Model with the required required data
processing functionality.
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,... | python |
import unittest
import package_1.arithmetic
class Test(unittest.TestCase):
def test_add(self) -> None:
self.assertEqual(package_1.arithmetic.add(1, 2), 3)
if __name__ == "__main__":
unittest.main()
| python |
"""Template tags for docs italia app."""
from __future__ import absolute_import
from django import template
from readthedocs.core.resolver import resolve
from ..models import PublisherProject
register = template.Library()
@register.filter
def get_publisher_project(slug):
"""get a publisher project from the slu... | python |
from poetry.core.exceptions.base import PoetryCoreException
__all__ = [clazz.__name__ for clazz in {PoetryCoreException}]
| python |
#PyTorch implementation of Recurrent Batch Normalization
# proposed by Cooijmans et al. (2017). https://arxiv.org/abs/1603.09025
# Source code from: https://github.com/jihunchoi/recurrent-batch-normalization-pytorch
import torch
from torch import nn
from torch.autograd import Variable
from torch.nn import functional, ... | python |
# Collect weather data for predetermined cities
# these are the corresponding cities with:
# - wind
# - solar
# - weather data exists on openweather api
import json
import requests
import pandas as pd
from time import time, sleep
from datetime import datetime
def writeData(title,timetext,data):
histfile = f'{t... | python |
from bs4 import BeautifulSoup
class HtmlParser(object):
def __init__(self, html):
self.soup = BeautifulSoup(html, 'html5lib')
@property
def hrefs(self):
# find all a tag which contains href attribute
a_tags = self.soup.find_all("a", {"href": True})
for tag in a_tags:
... | python |
#!/usr/bin/env python
"""
Main script
Contains: main function
Author: Yasim Ahmad(yaaximus)
Email: yasim.ahmed63@yahoo.com
"""
from Robot import Robot
from Object import Object
import matplotlib.pyplot as plt
from utils.positional import Position
def main():
"""
This is the function for instantiating obj... | python |
from stockfish import Stockfish
import re
# Download link: https://stockfishchess.org/download/
def play_on_console():
stockfish = Stockfish(r"stockfish/stockfish_13_win_x64_bmi2.exe")
usr_move = ""
print(stockfish.get_board_visual())
while(1):
usr_move = str(input("Enter move: "))
... | python |
from .logger import logger
from .ecc import convert_pubkey_to_addr,VerifyingKey,sha256d
class Stack(list):
push = list.append
def peek(self):
return self[-1]
class LittleMachine(object):
def __init__(self):
self.stack = Stack()
self._map = {
"OP_ADD": ... | python |
from django.db import models
class Customer(models.Model):
email = models.EmailField(unique=True)
name = models.CharField(max_length=255)
class Invoice(models.Model):
email = models.EmailField()
amount = models.IntegerField()
class Note(models.Model):
email = models.EmailField()
content = ... | python |
from django.apps import AppConfig
class CrapConfig(AppConfig):
name = 'crap'
| python |
import io
import csv
import requests
import datetime
from config import settings
class Cap(object):
"""
Used for accessing the API from the Harvard Law Caselaw Access Project.
"""
def __init__(self):
"""
Used for authentication.
"""
self.API_KEY = settings.API_KEY
... | python |
#Problem Link: https://www.codechef.com/MARCH21C/problems/NOTIME
n, h, x = map(int, input().split())
li = list(map(int, input().split()))
if max(li)+x>=h:
print("YES")
else:
print("NO")
| python |
# -*- coding: utf-8 -*-
# ---
# jupyter:
# jupytext:
# formats: ipynb,py:light
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.10.3
# kernelspec:
# display_name: wikirecs
# language: python
# name: wikirecs
# ---
... | python |
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras.preprocessing.text import Tokenizer
import numpy as np
sentences=[
'I love my dog',
'I love my cat',
'You love my dog!',
'I love cat-dog!'
]
#set the number of the words as 100
#OOV is out of v... | python |
from app.resources.commentary import Commentary
from app.resources.scorecard import Scorecard
from app.resources.game_play import GamePlay
| python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.