text stringlengths 2 999k |
|---|
#!/usr/bin/env python
# encoding: utf-8
'''
@author: Jason Lee
@license: (C) Copyright @ Jason Lee
@contact: jiansenll@163.com
@file: jianzhi_offer_47.py
@time: 2019/5/15 15:04
@desc:
'''
class Solution:
def Add(self, num1, num2):
# 异或:两数相加,不考虑进位
# 与: 进位的位置(左移一位)
while num2:
... |
# Copyright 2020 Maruan Al-Shedivat. 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 appli... |
from django.contrib.auth.models import AbstractUser
from django.db.models import CharField, BooleanField
from django.urls import reverse
from django.utils.translation import ugettext_lazy as _
class User(AbstractUser):
# First Name and Last Name do not cover name patterns
# around the globe.
name = CharF... |
import numpy as np
import random
from multiprocessing import Process
from openrec.utils.samplers import Sampler
class _PointwiseSampler(Process):
def __init__(self, dataset, batch_size, pos_ratio, q, chronological=False):
self._dataset = dataset
self._batch_size = batch_size
self.... |
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'send_email_microservice.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
... |
b='Yun Long Man Gou Can Se Xian Mo Shen Po Yao Qu Ran Ju Yin Bai Nie Chou Chom Khau Nia Rong Chuan Nie Li Jiang Kao Ce Chong Zhua Zi Yang Wen Ji Ji Dam Mang Mau Lu Qiu Dun Bao Chan Bo Chi Zhe Mang Ji Miao Yuan Wu Zhi Ping Chong Mi Fei Cuo Meng San Na Mang ... |
import os
import json
import random
import sys
import time
import math
import gflags
import numpy as np
from spinn.util import afs_safe_logger
from spinn.util.data import SimpleProgressBar
from spinn.util.blocks import to_gpu
from spinn.util.misc import Accumulator, EvalReporter
from spinn.util.logging import stats, ... |
# 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... |
import pytest
from unittest.mock import patch
from baserow.contrib.database.views.handler import ViewHandler
@pytest.mark.django_db(transaction=True)
@patch('baserow.ws.registries.broadcast_to_channel_group')
def test_view_created(mock_broadcast_to_channel_group, data_fixture):
user = data_fixture.create_user()... |
def test_axia_user(host):
user = host.user('axia')
assert user.exists
group = host.group('axia')
assert group.exists
assert user.gid == group.gid
def test_axia_binary(host):
binary = host.file('/usr/local/bin/axia')
assert binary.exists
assert binary.user == 'axia'
assert binary.... |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""
A script to read in and store ParlAI tasks in a sqlite database.
Adapted from Adam Fisch's work at github.com/facebo... |
from django.conf.urls import url
import views
urlpatterns = [
url(r'^$', views.ListStudentView.as_view(), name='students-list',),
url(r'^(?P<student_pk>[\d]+)/$', views.DetailStudentView.as_view(), name='student-detail',),
url(r'^(?P<student_pk>[\d]+)/edit$', views.UpdateStudentView.as_view(), name='stude... |
##
# Copyright: Copyright (c) MOSEK ApS, Denmark. All rights reserved.
#
# File: sospoly.py
#
# Purpose:
# Models the cone of nonnegative polynomials and nonnegative trigonometric
# polynomials using Nesterov's framework [1].
#
# Given a set of coefficients (x0, x1, ..., xn), the functions model the
# co... |
import os
import random
import sys
import time
import torch.cuda
from NeuralNet import NeuralNet
import numpy as np
from pytorch_classification.utils import Bar, AverageMeter
import torch.optim as optim
from utils import *
from .OthelloNNet import OthelloNNet as onnet
sys.path.append('../../')
args = dotdict({
... |
from PIL import Image
import requests
import matplotlib.pyplot as plt
import torch
from torch import nn
from torchvision.models import resnet50
import torchvision.transforms as T
torch.set_grad_enabled(False);
import gradio as gr
import io
model = torch.hub.load('facebookresearch/detr', 'detr_resnet50', pretrained=Tru... |
# Copyright 2019 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://www.apache.org/licenses/LICENSE-2.0
#
# or in the "license" file... |
# To-do: Create "nonlinearity" class that includes:
# * f
# * f_inverse
# * f_prime
# * domain
# * range
# To-do: Add a few other nonlinearities.
from autograd import numpy as np
def tanh_plus(x):
"""tanh-like function with infinite range (guaranteeing existence of inverse)"""
return np.sign(x) * np.log(np.... |
# coding=utf-8
# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
# Copyright (c) 2018, NVIDIA CORPORATION. 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 cop... |
import queue
class BinaryTree:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def takeLevelwiseinput():
print('enter the root data:')
rootData = int(input())
if rootData == -1:
return None
root = BinaryTree(rootData)
q = queue.Que... |
# Copyright 2018 The Cirq Developers
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in ... |
import numpy as np
import gym
from gym import spaces
from gym.utils import seeding
class TabularMDPEnv(gym.Env):
"""Tabular MDP problems, as described in [1].
At each time step, the agent chooses one of `num_actions` actions, say `i`,
receives a reward sampled from a Normal distribution with mean `m_i` ... |
#!/usr/bin/env python3
# Copyright (c) 2019-2020 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 that we reject low difficulty headers to prevent our block tree from filling up with useless bloat... |
# -*- coding: utf-8 -*-
import logging
from urllib3.exceptions import ProtocolError
from ocp_resources.resource import NamespacedResource
from ocp_resources.utils import TimeoutExpiredError, TimeoutSampler
from ocp_resources.virtual_machine import VirtualMachine
LOGGER = logging.getLogger(__name__)
def _map_map... |
import fnmatch
from django.db import models
from django.utils.translation import ugettext_lazy as _
from admin_sso import settings
class AssignmentManager(models.Manager):
def for_email(self, email):
if not email:
return None
try:
username, domain = email.split('@')
... |
from __future__ import unicode_literals
import boto.ec2.elb
from boto.ec2.elb.attributes import (
LbAttributes,
ConnectionSettingAttribute,
ConnectionDrainingAttribute,
AccessLogAttribute,
CrossZoneLoadBalancingAttribute,
)
from boto.ec2.elb.policies import Policies
from moto.core import BaseBacken... |
def func(N):
print("func("+str(N)+") を呼び出しました")
if N == 0:
return 0
else:
result = N + func(N-1)
print(str(N)+"までの和 = "+str(result))
return result
if __name__ == "__main__":
func(5) |
from .common import *
## Database
## Imported from dbsettings file now
## EVE Proxy
import raven
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'krabacus',
'USER': 'krabacus',
'PASSWORD': 'nice desu ne',
'HOST': 'localhost', # Or an IP Address ... |
import safenet.safeUtils as safeUtils
import queue
appQueue = queue.Queue()
class lib:
def __init__(self,authlib,applib,fromBytes=None):
self.safe_authenticator = authlib
self.safe_app = applib
class authenticator:
def __init__(self,authlib,applib):
self.lib = lib(authlib,applib)
... |
# -*- coding: utf-8 -*-
import numpy as np
from sktime.classification.shapelet_based import MrSEQLClassifier
from sktime.datasets import load_gunpoint
def test_mrseql_on_gunpoint():
# load training data
X_train, y_train = load_gunpoint(split="train", return_X_y=True)
X_test, y_test = load_gunpoint(split=... |
from __future__ import print_function, division
import time
from copy import deepcopy
import numpy as np
from pymanopt.solvers.linesearch import LineSearchAdaptive
from pymanopt.solvers.solver import Solver
from pymanopt import tools
'''
Authors: Noemie Jaquier and Leonel Rozo, 2019
License: MIT
Contact: noemie.jaq... |
import glob
import os
import emoji
import pytest
from click.testing import CliRunner
from py_sync_dotenv.cli import formatting_engine, main
test_env = """
PRODUCTION=1
DEBUG=0
SECRET_KEY=iu0^cv$mghjfa_vp8vk)e(c_5^cfo7staccjs4+!f#=1a_22-h2
DJANGO_ALLOWED_HOSTS=localhost 127.0.0.1 [::1]
"""
@pytest.mark.parametrize(... |
# Copyright 2012 The Emscripten Authors. All rights reserved.
# Emscripten is available under two separate licenses, the MIT license and the
# University of Illinois/NCSA Open Source License. Both these licenses can be
# found in the LICENSE file.
from __future__ import print_function
import os
import sys
import sub... |
# This file is here just to define MlpPolicy/CnnPolicy
# that work for A2C
from stable_baselines3.common.policies import (
ActorCriticCnnPolicy,
ActorCriticPolicy,
MultiInputActorCriticPolicy,
register_policy,
)
MlpPolicy = ActorCriticPolicy
CnnPolicy = ActorCriticCnnPolicy
MultiInputPolicy = MultiInpu... |
import unittest
import elves
class elvesTestCase(unittest.TestCase):
def test_01_elves_mass_calulation(self):
output = elves.amount_of_fuel_needed([6])
self.assertEqual(output, 0)
def test_02_elves_mass_calulation(self):
output = elves.amount_of_fuel_needed([10])
self.assertEq... |
# Copyright 2014 Red Hat, Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by... |
from core.models import ProviderMachine
from rest_framework import serializers
from api.v2.serializers.summaries import (
ImageSummarySerializer, ImageVersionSummarySerializer,
ProviderSummarySerializer, UserSummarySerializer, LicenseSummarySerializer
)
from api.v2.serializers.fields.base import InstanceSourceH... |
# pragma pylint: disable=missing-docstring, W0212, too-many-arguments
"""
This module contains the backtesting logic
"""
import logging
from collections import defaultdict
from copy import deepcopy
from datetime import datetime, timedelta, timezone
from typing import Any, Dict, List, Optional, Tuple
from pandas impor... |
from Util import Configuration
LOG_MAP = dict()
def check_server(guild_id):
enabled = set()
for cid, info in Configuration.get_var(guild_id, "LOG_CHANNELS").items():
enabled.update(info["CATEGORIES"])
LOG_MAP[guild_id] = enabled
def is_logged(guild, feature):
return guild in LOG_MAP and fea... |
"""
Author: Darren
Date: 13/12/2020
Solving: https://adventofcode.com/2020/day/13
Solution 1 of 2: doing it the hard way
Part 2
------
Input like: 7,13,x,x,59,x,31,19
Find first time where 7 departs at t=0, 13 departs at t=1, x departs at t=2, etc.
Bus ID also represents the duration of each bus loop.
E.g. bus 7 de... |
# Copyright 2016 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 required by applicable law or ag... |
import sys; sys.path.append('../common')
import mylib as utils # pylint: disable=import-error
import re
from itertools import product
from collections import namedtuple, OrderedDict
# Read args
filename = 'input.txt' if len(sys.argv) == 1 else sys.argv[1]
print(filename, '\n')
###########################
# region CO... |
"""
Writes latest git commit hash and date to version.txt file.
"""
import subprocess
def update_version_txt():
try:
commit_hash = subprocess.check_output("git rev-parse --short HEAD", stderr=subprocess.STDOUT).decode().strip()
commit_date = subprocess.check_output("git log -1 --date=short --pret... |
from distutils.core import setup
from pkgutil import walk_packages
import paintera_tools
from paintera_tools import __version__
def find_packages(path, prefix):
yield prefix
prefix = prefix + "."
for _, name, ispkg in walk_packages(path, prefix):
if ispkg:
yield name
setup(name='pai... |
import mxnet as mx
def test_print_summary():
data = mx.sym.Variable('data')
bias = mx.sym.Variable('fc1_bias', lr_mult=1.0)
conv1= mx.symbol.Convolution(data = data, name='conv1', num_filter=32, kernel=(3,3), stride=(2,2))
bn1 = mx.symbol.BatchNorm(data = conv1, name="bn1")
act1 = mx.symbol.Activat... |
# Copyright 2020 DataStax, 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,... |
from flask import render_template
from CTFd.utils.decorators import admins_only
from CTFd.utils.updates import update_check
from CTFd.utils.modes import get_model
from CTFd.models import db, Solves, Challenges, Fails, Tracking
from CTFd.admin import admin
@admin.route("/admin/statistics", methods=["GET"])
@admins_onl... |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as mtick
e_f_star = 5e-5# give a tolerance on the mean squared error of flow prediction
### load MSE on the training/validation/test set
mse_tr = pd.read_csv('Depth5/mse_train.csv')
mse_tr.columns = ['index', 'shapes', '... |
##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
## Created by: Donny You, RainbowSecret
## Microsoft Research
## yuyua@microsoft.com
## Copyright (c) 2019
##
## This source code is licensed under the MIT-style license found in the
## LICENSE file in the root directory of this source tree
##... |
# -*- coding: utf-8 -*-
# Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... |
from itertools import chain, combinations
from cfripper.config.filter import Filter
from cfripper.model.enums import RuleMode
"""
To use this Filter, or any Filter, make sure to include it in the `Config` instantiation.
```python
FILTERS = [allow_http_ports_open_to_world_rules_config_filter]
config = Config(
..... |
# encoding: utf-8
# Copyright 2011 Tree.io Limited
# This file is part of Treeio.
# License www.tree.io/license
"""
Core Trash module forms
"""
from django import forms
from django.utils.translation import ugettext as _
class MassActionForm(forms.Form):
""" Mass action form for Tickets """
action = forms.C... |
"""Constructor APIs"""
from ..._ffi.function import _init_api
_init_api("relay.op._make", __name__)
|
# Implemented by Marcus Botacin, based on Vitor Falcão da Rocha's implementation.
class LDR:
def __init__(self):
self.found_op1 = None
self.found_keyword = False
def check(self, section, address, instruction, op1, op2):
if instruction in ['mov', 'movsx', 'movzx']:
if 'f... |
"""
The trainer handles all the logic for running a val loop, training loop, distributing, etc.. .
"""
import os
import sys
import warnings
import logging
import torch
import torch.distributed as dist
import torch.multiprocessing as mp
import tqdm
from torch.optim.optimizer import Optimizer
from pytorch_lightning.tr... |
# -*- coding: utf-8 -*-
'''
Azure (ARM) Compute Execution Module
.. versionadded:: 2019.2.0
:maintainer: <devops@decisionlab.io>
:maturity: new
:depends:
* `azure <https://pypi.python.org/pypi/azure>`_ >= 2.0.0
* `azure-common <https://pypi.python.org/pypi/azure-common>`_ >= 1.1.8
* `azure-mgmt <https://p... |
# Generated by Django 2.1.5 on 2019-02-25 19:59
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('contenttypes', '0002_remove_content_type_name'),
('comments', '0001_initial'),
]
operations = [
mig... |
#!/usr/bin/env python3
# Copyright (c) 2019 Samsung Electronics Co., Ltd. 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.... |
import binascii
import pyblake2
import unittest
import base58
import sha3
import WavesCrypto
class WavesCryptoTests(unittest.TestCase):
def test_keccak_1(self):
data = binascii.unhexlify(b"0100000000000000000000000000000000000000000000000000000000000000")
kh = sha3.keccak_256()
kh.update... |
import os
import time
from datetime import timedelta
from typing import Any, Dict
from django.core.management.base import BaseCommand
from django.utils.timezone import now as timezone_now
from analytics.lib.counts import COUNT_STATS, CountStat
from analytics.models import installation_epoch
from zerver.lib.timestamp ... |
from collections.abc import Mapping, Sequence
class JsonDict(dict):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
super().__setattr__('_root', self)
def __getattr__(self, key):
if key in self:
return self[key]
return super().__getattribute... |
'''
路径总和 III
给定一个二叉树,它的每个结点都存放着一个整数值。
找出路径和等于给定数值的路径总数。
路径不需要从根节点开始,也不需要在叶子节点结束,但是路径方向必须是向下的(只能从父节点到子节点)。
二叉树不超过1000个节点,且节点数值范围是 [-1000000,1000000] 的整数。
'''
from collections import defaultdict
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.... |
# ===================================================================
#
# Copyright (c) 2014, Legrandin <helderijs@gmail.com>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistributio... |
def doSubtraction:
a=10
b=5
print(a-b)
doSubtraction()#subtraction of two numbers
|
#
#
#
# NOTE: IDS requires that you pass the schema name (cannot pass None)
import unittest, sys
import IfxPy
import config
from testfunctions import IfxPyTestFunctions
class IfxPyTestCase(unittest.TestCase):
def test_197_StatisticsIndexes(self):
obj = IfxPyTestFunctions()
obj.assert_expect(self.run_tes... |
# -*- coding: utf-8 -*-
"""
DARIAH Contribute - DARIAH-EU Contribute: edit your DARIAH contributions.
Copyright 2014 Data Archiving and Networked Services
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... |
from flask import Flask
app = Flask(__name__)
# Flask 视图支持的访问方式是 默认是 GET HEAD OPTIONS、
# OPTIONS 解决跨域问题的 是浏览器访问服务器的白名单和请求方式
# Django如何解决跨域问题
# 在中间件中 前期加入OPTIONS的请求验证的代码
# 中间件
# 客户端--->中间件前期处理--->视图---->中间件后期处理---->客户端
@app.route('/',methods=['POST'])
def View_one():
return 'View_one'
@app.route('/view/2',me... |
from django.urls import include, path
from rest_framework.routers import DefaultRouter
from questions.api import views as qv
router = DefaultRouter()
router.register(r'questions', qv.QuestionViewSet)
urlpatterns = [
path('', include(router.urls)),
path('questions/<slug:slug>/answers/',
qv.AnswerLi... |
import datetime
from telethon import events
from telethon.errors.rpcerrorlist import YouBlockedUserError
from telethon.tl.functions.account import UpdateNotifySettingsRequest
import datetime
import asyncio
from telethon import events
from telethon.errors.rpcerrorlist import YouBlockedUserError
from telethon.tl.function... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# @Author: ss
# @Time: 2020/7/11 4:19 下午
# @File: __init__.py.py |
from django.db import models
from django.utils.translation import gettext_lazy as _
from .time_stamped import TimeStampedModel
class MediaProfile(TimeStampedModel):
portfolio = models.ForeignKey('Portfolio', on_delete=models.CASCADE)
network = models.CharField(max_length=120)
username = models.CharField(m... |
#!/bin/python
import argparse
import glob
import json
import os
import re
import cv2
import numpy as np
from tqdm import tqdm
from lxml import etree
import xml.etree.cElementTree as ET
from dasiamrpn import dasiamrpn
DELAY = 20 # keyboard delay (in milliseconds)
WITH_QT = False
try:
cv2.namedWindow('Test')
... |
from drig.networks.alex_net import AlexNet
from drig.networks.custom_dense import CustomDense
from drig.networks.nigh_google_net import NighGoogLeNet
from drig.networks.tiny_google_net import TinyGoogLeNet
from drig.networks.tiny_vgg_net import TinyVGGNet
from drig.networks.multi_layer_perceptron import MultiLayerPerce... |
# Licensed under a MIT license - see LICENSE
"""MUSE-PHANGS combine module
"""
__authors__ = "Eric Emsellem"
__copyright__ = "(c) 2017-2019, ESO + CRAL"
__license__ = "MIT License"
__contact__ = " <eric.emsellem@eso.org>"
# Importing modules
import numpy as np
import os
from os.path import join as joinpath
import gl... |
# -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# http://doc.scrapy.org/en/latest/topics/items.html
import scrapy
class Book(scrapy.Item):
# define the fields for your item here like:
book_name = scrapy.Field()
book_url = scrapy.Field()
book_author =... |
import discord
from discord.ext import commands
class Events(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
async def on_ready(self):
print('CyberBot is ready!')
def setup(bot):
bot.add_cog(Events(bot)) |
class LogoutPage:
from selenium.webdriver.common.by import By
LOGOUT_BUTTON = (By.CSS_SELECTOR, 'a>i')
TITLE_TEXT = (By.CSS_SELECTOR, 'div h2')
DESCRIBE_TEXT = (By.CSS_SELECTOR, 'div>h4')
def __init__(self, browser):
self.browser = browser
def getTitlePage(self):
return self.br... |
"""[explorerhat]
API library for Explorer HAT and Explorer HAT Pro, Raspberry Pi add-on boards"""
import atexit
import signal
import time
from sys import exit, version_info
import logging
logger = logging.getLogger(__name__)
try:
from smbus import SMBus
except ImportError:
if version_info[0] < 3:
log... |
# Criar um programa para o cadastro do cliente
# Para cadastro de clientes deve pedir os seguintes dados:
# Codigo do cliente, CPF, Nome completo,
# data de nascimento, Estado, Cidade, cep, bairro, rua,
# numero da casa, complemento.
# cod_Cliente = input('Codigo de cliente: ')
# cpf = input('CPF cliente: ')
def ... |
import selenium
from selenium import webdriver
class Driver(object):
def __init__(self, browser):
self.passed = 0
self.failed = 0
self.total = 0
self.browser = browser
def go(self):
self.browser.get("http://localhost/playcanvas/sdk/tests/all_tests.html")
... |
r"""
django-rollbar middleware
There are two options for installing the Rollbar middleware. Both options
require modifying your settings.py file.
The first option is to use
'rollbar.contrib.django.middleware.RollbarNotifierMiddleware' which will
report all exceptions to Rollbar including 404s. This middlware should b... |
"""
ASGI config for gallary project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTI... |
#
# Copyright 2021 Red Hat Inc.
# SPDX-License-Identifier: Apache-2.0
#
"""Unit testing utilities."""
import logging
import random
import re
from faker import Faker
from api.utils import DateHelper
LOG = logging.getLogger(__name__)
class FakeAWSCostData:
"""Object to generate and store fake AWS cost data."""
... |
import math
import numpy as np
from cereal import log
from common.filter_simple import FirstOrderFilter
from common.numpy_fast import clip, interp
from common.realtime import DT_CTRL
from selfdrive.controls.lib.latcontrol import LatControl, MIN_STEER_SPEED
class LatControlINDI(LatControl):
def __init__(self, CP, C... |
# 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... |
#!/usr/bin/env python
from __future__ import print_function
import argparse
import os
import os.path
import numpy as np
import csv
from pycrazyswarm import *
import uav_trajectory
import pycrazyswarm.cfsim.cffirmware as firm
def main():
parser = argparse.ArgumentParser()
parser.add_argument("path",
... |
import matplotlib.pyplot as plt
import numpy as np
class Visualize:
def __init__(self, solved_grid, old_grid):
self.solved_grid = solved_grid
self.old_grid = old_grid
def show_solution(self, cell_dimension=0.1):
cell_text = [[str(el) for el in row] for row in self.solved_grid]
... |
"""
WSGI config for py project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_M... |
import unittest
import scipy
from scipy.integrate import quad
import numpy as np
from dolo.numeric.distribution import *
## Polynomial
def f(x):
return x**2
def f(x):
return x**2
def test_UNormal():
σ = 0.1
μ = 0.2
N = 10
distNorm = UNormal(mu=μ, sigma=σ)
disNorm_gh = distNorm.di... |
#!/bin/env python
# Automatically translated python version of
# OpenSceneGraph example program "osgwidgetinput_"
# !!! This program will need manual tuning before it will work. !!!
import sys
from osgpypp import osgDB
from osgpypp import osgViewer
from osgpypp import osgWidget
# Translated from file 'osgwidgetinp... |
import math
from math import pi
from typing import List
import numexpr
import numpy
def icc(theta: float, a: float, b: float, c: float = 0, d: float = 1) -> float:
"""Item Response Theory four-parameter logistic function [Ayala2009]_, [Magis13]_:
.. math:: P(X_i = 1| \\theta) = c_i + \\frac{d_i-c_i}{1+ e^{-... |
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
np.random.seed(0)
sns.set()
ngui = 0
titree = 1
seasons = ['Summer', 'Autumn', 'Winter', 'Spring']
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
# by month
data = np.zeros((2, 12))
data[ngui] = n... |
import setuptools
from os import path
here = path.abspath(path.dirname(__file__))
with open(path.join(here, "README.md"), encoding="utf-8") as f:
long_description = f.read()
setuptools.setup(
name="fastt5",
version="0.0.5",
license="apache-2.0",
author="Kiran R",
author_email="kiranr8k@gmail.... |
import inspect
import asp.codegen.python_ast as ast
import asp.codegen.cpp_ast as cpp_ast
import asp.codegen.ast_tools as ast_tools
import codepy.cgen
import asp.jit.asp_module as asp_module
from collections import namedtuple
class IfNotDefined(cpp_ast.Generable):
"""
A generable AST node for the 'if not defi... |
import datetime
from django.contrib import admin
from django.db import models
# Create your models here.
from django.utils import timezone
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published') # Human readable name
def __str__(s... |
import pygame
import tradingsim.configuration as configuration
class DotRenderer:
def __init__(self):
self.top_left_x = 0
self.top_left_y = 0
self.scale = 1
self.keys = {v: (k, False) for (k, v) in configuration.RENDERER_KEY_CONFIG.items()}
self.location_highlighted = None... |
#!/usr/bin/env python
"""
Larch: a scientific data processing macro language based on python
"""
import os
import sys
import logging
# note: may need to set CONDA env *before* loading numpy!
if os.name == 'nt':
os.environ['CONDA_DLL_SEARCH_MODIFICATION_ENABLE'] = '1'
import numpy
import time
import warnings
w... |
from sender.sender import *
from sender.signal import *
from sender.server import *
import sys
if len(sys.argv) == 3:
signalId = int(sys.argv[1])
signalRaw = int(sys.argv[2])
signal = Signal(signalId)
server = Server("127.0.0.1", 3334)
sender = Sender(server)
signal.update(signalRaw)
sender.send(signal)
else:... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from mnmt.attention import Attention
class AdditiveAttention(Attention):
"""Bahdanau Attention (mlp)"""
def __init__(self, encoder_hidden_dim, decoder_hidden_dim):
"""
Args:
encoder_hidden_dim:
... |
# Copyright 2018 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... |
from __future__ import unicode_literals
from prompt_toolkit.key_binding import InputProcessor, Registry
from prompt_toolkit.keys import Keys
from prompt_toolkit.inputstream import KeyPress
import unittest
class KeyBindingTest(unittest.TestCase):
def setUp(self):
class Handlers(object):
def ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.