text stringlengths 2 999k |
|---|
"""
Django settings for docs project.
Generated by 'django-admin startproject' using Django 1.10.3.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.10/ref/settings/
"""
import os
#... |
import _plotly_utils.basevalidators
class StartlineValidator(_plotly_utils.basevalidators.BooleanValidator):
def __init__(self, plotly_name="startline", parent_name="carpet.baxis", **kwargs):
super(StartlineValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name... |
#!/usr/bin/python
"""
Script to train/restore model and generate sample text
Usage : train-gru-tf.py to train a model
: train-gru-tf.py --r RESTORE to restore a trained model from an epoch and generate text
"""
import csv
import itertools
import operator
import numpy as np
import nltk
import sys
import os
... |
#!/usr/bin/env python3
from numpy import linspace
import matplotlib.pyplot as plt
import scipy.stats as ss
plt.style.use('seaborn') # pretty matplotlib plots
plt.rcParams['figure.figsize'] = (8,5)
def plot_normal(data_points,x_range,mu,sigma,color,label):
x = x_range
y = ss.norm.pdf(x,mu,sigma)
... |
# coding: utf-8
"""
CloudEndure API documentation
© 2017 CloudEndure All rights reserved # General Request authentication in CloudEndure's API is done using session cookies. A session cookie is returned upon successful execution of the \"login\" method. This value must then be provided within the request hea... |
import os
from cds_dojson.marc21.utils import create_record
from cds_ils.importer.providers.springer.springer import model
marcxml = (
"""<collection xmlns="http://www.loc.gov/MARC21/slim">"""
"""<record>{0}</record></collection>"""
)
def check_transformation(marcxml_body, json_body):
"""Check transfor... |
#-*- coding: utf-8 -*-
import argparse
import os
import pickle
def str2bool(v):
return v.lower() in ('true', '1')
arg_lists = []
parser = argparse.ArgumentParser()
def add_argument_group(name):
arg = parser.add_argument_group(name)
arg_lists.append(arg)
return arg
# Network
net_arg = add_argument_group('N... |
import sys
import os
sys.path.append(os.path.abspath("../"))
from unittest import TestCase
from unittest.mock import patch
from unit_test.util import Util
from icon_rapid7_intsights.actions.get_alerts import GetAlerts
from icon_rapid7_intsights.actions.get_alerts.schema import Input
class TestAddManualAlert(TestCas... |
from ..base.twilltestcase import common, ShedTwillTestCase
emboss_datatypes_repository_name = 'emboss_datatypes_0050'
emboss_datatypes_repository_description = "Datatypes for emboss"
emboss_datatypes_repository_long_description = "Long description of Emboss' datatypes"
emboss_repository_name = 'emboss_0050'
emboss_re... |
import cv2
import time
import mediapipe as mp
class handDetector():
def __init__(self, image_mode= False, max_num_hands =3, min_detection_confidence =0.5, min_tracking_confidence =0.5):
self.image_mode = image_mode
self.max_num_hands = max_num_hands
self.min_detection_confidence = min_dete... |
from django.contrib import admin
from artikel.models import Artikel
admin.site.register(Artikel)
# Register your models here.
|
# -*- coding: utf-8 -*-
"""
pygments.lexers.idl
~~~~~~~~~~~~~~~~~~~
Lexers for IDL.
:copyright: Copyright 2006-2017 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
import re
from pygments.lexer import RegexLexer, words
from pygments.token import Text,... |
from __future__ import division
import numpy as np
from scipy.sparse import csr_matrix, coo_matrix
from scipy.linalg import blas
from pyscf.nao.m_sparsetools import csr_matvec, csc_matvec, csc_matvecs
import math
def chi0_mv(self, v, comega=1j*0.0):
"""
Apply the non-interacting response function to a ve... |
from distutils.core import setup
setup(
name='fastapi_response_log', # How you named your package folder (MyLib)
packages=['fastapi_response_log'], # Chose the same as "name"
version='0.1.3', # Start with a small number and increase it with every change you make
license='MIT', # Chose a license fro... |
"""This module describes the entities and workflow for processing the gisaid dump."""
from __future__ import annotations
from typing import MutableSequence, Sequence
from sqlalchemy import Column, DateTime, ForeignKey, Integer, String, UniqueConstraint
from aspen.database.models.entity import Entity, EntityType
from... |
import json
from model.logger import logger, init_logger
from model.dict import HEROES_LIST_CHINESE
api_key : str = ""
sio_url : str = ""
post_url : str = ""
bot_id : int = 1234567890
groups : list[int]= []
debug : bool = False
mdi_url : str = ""
def Load(config_dir: str):
try:
config : dict = json.load(open(conf... |
#
# Copyright (c) 2021, 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 copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appl... |
# ==========================================================================
#
# Copyright NumFOCUS
#
# 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... |
from typing import Iterator
from torch.utils.data import Sampler
from lightning_rl.storage.IBuffer import Buffer
class EntireBufferSampler(Sampler):
def __init__(
self,
buffer: Buffer,
samples_per_epoch: int,
) -> None:
super().__init__(None)
self.buffer = buffer
... |
# Tests of custom properties for Python programming.
#
# Author: Peter Odding <peter@peterodding.com>
# Last Change: April 27, 2018
# URL: https://property-manager.readthedocs.org
"""Automated tests for the :mod:`property_manager3` module."""
# Standard library modules.
import logging
import os
import random
import s... |
import curl
import pycurl
try:
from cStringIO import StringIO as BytesIO
except:
from io import BytesIO
buf = BytesIO()
c = pycurl.Curl()
c.setopt(c.URL, 'https://repo.anaconda.com/')
c.setopt(c.WRITEFUNCTION, buf.write)
c.perform()
print(buf.getvalue())
assert b'Anaconda, Inc.' in buf.getvalue()
buf.close()... |
# coding=utf-8
# Copyright 2018 The Tensor2Tensor 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... |
# -*- coding: utf-8 -*-
#
# Copyright (c) 2016 - 2022 -- Lars Heuer
# All rights reserved.
#
# License: BSD License
#
"""\
Tests against Segno data URI.
"""
from __future__ import absolute_import
import segno
def test_data_svg():
qr = segno.make_qr('A')
val = qr.svg_data_uri()
assert val
expected = "d... |
# -*- coding: utf-8 -*-
from __future__ import print_function
import os
import sys
from setuptools import setup, find_packages
if __name__ == '__main__':
print('Sopel does not correctly load modules installed with setup.py '
'directly. Please use "pip install .", or add {}/sopel_modules to '
'... |
"""Table constraints.
This module contains constraints that are evaluated within a single table,
and which can affect one or more columns at a time, as well as one or more
rows.
Currently implemented constraints are:
* CustomConstraint: Simple constraint to be set up by passing the python
functions that wi... |
# Copyright 2017 Mycroft AI Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... |
# Software License Agreement (BSD License)
#
# Copyright (c) 2012, Fraunhofer FKIE/US, Alexander Tiderko
# 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 mus... |
import pyglet
from pyglet.gl import *
from robocute.vu import *
from robocute.texture import *
'''
TileStrip
'''
class TileStrip(TextureStrip):
instance = None
instanced = None
def __new__(cls, *args, **kargs):
instance = cls.instance
if not instance:
obj... |
#===== 3DS Games =====#
class ACNL:
TITLE_ID_EUR = 0x0004000000198F00
TITLE_ID_USA = 0x0004000000198E00
TITLE_ID_JAP = 0x0004000000198D00
LATEST_VERSION = 0
GAME_SERVER_ID = 0x00086201
ACCESS_KEY = "d6f08b40"
NEX_VERSION = 31001 #3.10.1
SERVER_VERSION = 4254 #Needs confirmation.
#===== Wii U Games =====#
... |
"""Tracks the latency of a host by sending ICMP echo requests (ping)."""
import asyncio
from datetime import timedelta
from functools import partial
import logging
import re
import sys
from typing import Any, Dict
from icmplib import SocketPermissionError, ping as icmp_ping
import voluptuous as vol
from homeassistant... |
from model.atten_submodules import *
from model.submodels import *
'''
Top-level module which uses a Hierarchical-LSTM-CRF to classify.
If pretrained = False, each example is represented as a sequence of sentences, which themselves are sequences of word tokens. Individual sentences are passed to LSTM_Sentence_... |
import random
class RatingSystem:
_MIN_SCORE = 0
_MAX_SCORE = 100
@classmethod
def get_min_score(cls):
return cls._MIN_SCORE
@classmethod
def get_max_score(cls):
return cls._MAX_SCORE
@classmethod
def get_score(cls, data):
score = cls._get_score(data)
... |
#!/usr/bin/env python3
#
# Copyright 2021 Xiaomi Corporation (Author: Fangjun Kuang)
#
# See ../../../../LICENSE for clarification regarding multiple 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 ... |
import numpy as np
from scipy.signal import get_window
import librosa.util as librosa_util
def window_sumsquare(window, n_frames, hop_length=200, win_length=800,
n_fft=800, dtype=np.float32, norm=None):
"""
# from librosa 0.6
Compute the sum-square envelope of a window function at a gi... |
def get_companies(client, db_rid=None, company_identifier=None, company_name=None, status=None, zip=None,
phone_number=None, fax_number=None, website=None, verbose=False):
"""
Gets Companies with a particular set of optional conditions.
:param client: Pass the authorised connectwise clien... |
import os
import glob
import shutil
import random
root = "./ROI_data"
from_dir = os.path.join(root, "ALL")
train_dir = os.path.join(root, "train")
test_dir = os.path.join(root, "test")
def mkdir(dir):
if not os.path.exists(dir):
os.makedirs(dir)
mkdir(train_dir)
mkdir(test_dir)
ratio_train = 0.8
for... |
"""
Text generation using a character LSTM, specifically we want to
generate new names as inspiration for those having a baby :)
Although this is for name generation, the code is general in the
way that you can just send in any large text file (shakespear text, etc)
and it will generate it.
Programmed by Aladdin Per... |
#! /usr/bin/env python
import sys
import antlr4
from copybook_lexer import copybook_lexer
from copybook_parser import copybook_parser
from copybook_parserListener import copybook_parserListener
class Listener(copybook_parserListener):
# Enter a parse tree produced by copybook_parser#main.
def enterMain(self,... |
{
"targets": [
{
"target_name": "addon",
"include_dirs": [
"<!(node -e \"require('bob-base')\")",
"<!@(node -p \"require('node-addon-api').include\")",
# Use the passthough as a dependency
"./src/passthrough",
"./src"
],
"dependencies": [
"<!... |
from __future__ import absolute_import
import errno
import logging
import operator
import os
import shutil
from optparse import SUPPRESS_HELP
from pip._internal import cmdoptions
from pip._internal.basecommand import RequirementCommand
from pip._internal.cache import WheelCache
from pip._internal.exceptio... |
# This file is a part of Arjuna
# Copyright 2015-2020 Rahul Verma
# Website: www.RahulVerma.net
# 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... |
import json
import os
import platform
from conan.tools.cmake.utils import is_multi_configuration
from conans.errors import ConanException
from conans.util.files import save, load
def _add_build_preset(conanfile, multiconfig):
build_type = conanfile.settings.get_safe("build_type")
configure_preset_name = _con... |
"""
Copyright: Wenyi Tang 2017-2018
Author: Wenyi Tang
Email: wenyi.tang@intel.com
Created Date: Aug 21st 2018
Utility for motion compensation
"""
import numpy as np
import tensorflow as tf
def _grid_norm(width, height, bounds=(-1.0, 1.0)):
"""generate a normalized mesh grid
Args:
width: width of the ... |
import csv
from TexSoup import TexSoup
import os
def main():
file_abstract = []
path = os.listdir('/Akamai_scratch/SpArxiv')
indir = '/Akamai_scratch/arxiv/outdir3'
for root, dirs, filenames in os.walk(indir):
for f in filenames:
try:
#open file
soup... |
##########################################################################
#
# Copyright (c) 2011-2012, John Haddon. All rights reserved.
# Copyright (c) 2011-2013, Image Engine Design Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted prov... |
# Video handling utilities.
#
# Two things in this file
# 1. Kelvinator - simple method of extracting key frames for a video.
# 2. Resize - simple transcoder to create smaller versions of videos.
#
# Requirements:
# 1. ffmpeg
# 2. x264 for transcoding
# 3. Python Imaging: PIL, or Image
#
# For more info on transcodi... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 5/15/20 4:49 PM
# @File : grover.py
# qubit number=4
# total number=32
import cirq
import cirq.google as cg
from typing import Optional
import sys
from math import log2
import numpy as np
#thatsNoCode
from cirq.contrib.svg import SVGCircuit
# Symbols for... |
# services/__init__.py
import os
import connexion
import logging
def create_app(script_info=None):
# instantiate the app
con_app = connexion.FlaskApp(__name__, specification_dir='docs/')
con_app.add_api('api.yaml', options={'swagger_url': '/docs'})
# set config
app_settings = os.getenv('APP_SET... |
# coding: utf-8
"""
Kubernetes
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501
The version of the OpenAPI document: v1.16.14
Generated by: https://openapi-generator.tech
"""
import pprint
import re # noqa: F401
import six
f... |
from collections import OrderedDict
from typing import List
import torch
from torch import nn
from torchvision.models import densenet121, densenet161, densenet169, densenet201, DenseNet
from .common import EncoderModule, _take, make_n_channel_input
__all__ = ["DenseNetEncoder", "DenseNet121Encoder", "DenseNet169Enco... |
def yet_another_package_print():
print 'yet another package print' |
# -*- coding: utf-8 -*-
# Copyright 2020 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 o... |
"""
The Adafruit PCA9685 driver requires an I2C interface defined in
Adafruit_Python_GPIO https://github.com/adafruit/Adafruit_Python_GPIO and this
low-level driver assumes that the code will be run on an embedded single board
computer such as a rpi or beaglebone. It assumes an API that is not provided by
the F232H dri... |
import tensorflow as tf
from garage.misc import logger
logger.set_tensorboard_dir("data/local/histogram_example")
N = 400
for i in range(N):
sess = tf.Session()
sess.__enter__()
k_val = i / float(N)
logger.record_histogram_by_type('gamma', key='gamma', alpha=k_val)
logger.record_histogram_by_type(... |
username = "zhangsan"
userpasswd = 123456
while True:
name = input("请输入你的用户名:")
if name == username:
passwd = int(input("请输入密码:"))
if passwd == userpasswd:
print("恭喜{}用户成功登录".format(username))
else:
print("密码错误,请重新输入")
else:
print("请输入正确的用户名") |
class Solution:
def letterCombinations(self, digits):
"""
:type digits: str
:rtype: List[str]
"""
phone = {'2': ['a', 'b', 'c'],
'3': ['d', 'e', 'f'],
'4': ['g', 'h', 'i'],
'5': ['j', 'k', 'l'],
'6': ['m', 'n... |
from django.template import loader
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import get_object_or_404, render
from django.urls import reverse
from .models import Question, Choice
# Get questions and display them
def index(request):
latest_question_list = Question.objects.ord... |
import numpy as np
import pandas as pd
class Projectile:
def __init__(self, dt: float, A: float, B: float, m: float, xi: float, yi: float, vi: float, angle: float,
g: float) -> None:
#yapf: disable
self.dt : float = dt
self.A : float = A
self.B ... |
version https://git-lfs.github.com/spec/v1
oid sha256:dc5762773db6d7f74cb2bb3982534a03a88ae8d011d2fdd202b610b792f65237
size 11959
|
def linear_search(list, key):
#Returns the number of steps to determine if key is in the list
#Initialize the counter of steps
steps=0
for i, item in enumerate(list):
steps += 1
if item == key:
break
return steps
def binary_search(list, key):
#Returns the number o... |
from cytnx import *
A = zeros([3,4,5],dtype=Type.Double)
print(A)
B = A.astype(Type.Uint64)
print(B)
C = A.astype(Type.Double)
print(C is A)
|
from strategies.abstract_strategy import AbstractStrategy
class BelowRSI(AbstractStrategy):
""" Buying if rsi value is below a given limit """
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.period = kwargs["period"]
self.limit = kwargs["limit"]
def should_buy(self)... |
# Copyright (c) 2012-2021, Mark Peek <mark@peek.org>
# All rights reserved.
#
# See LICENSE file for full license.
from .aws import Action as BaseAction
from .aws import BaseARN
service_name = "Amazon Connect Voice ID"
prefix = "voiceid"
class Action(BaseAction):
def __init__(self, action: str = None) -> None:
... |
# Copyright (c) 2020 NVIDIA Corporation. All rights reserved.
# This work is licensed under the NVIDIA Source Code License - Non-commercial. Full
# text can be found in LICENSE.md
from __future__ import division
import numpy as np
import torch
import torch.nn as nn
import torch.nn.init as init
import torch.nn.functiona... |
#!/bin/python
import time, mmap
with open('/dev/mem', 'r+b') as fd:
region = mmap.mmap(fd.fileno(), (1024*4), offset=0xFF634000)
region[4*0x116:4*0x116+4] = b'\x00\x00\x00\x00'
region[4*0x14A:4*0x14A+4] = b'\x00\x00\x00\x00'
pof = (0).to_bytes(4, 'little')
pon = (1).to_bytes(4, 'little')
ps = time.process_time()... |
# model settings
model = dict(
type='FasterRCNN',
pretrained='torchvision://resnet50',
backbone=dict(
type='ResNet',
depth=50,
num_stages=4,
out_indices=(0, 1, 2, 3),
frozen_stages=1,
norm_cfg=dict(type='BN', requires_grad=True),
style='pytorch'),
... |
"""
Relative Navigation Filter based on UKF/filterpy.
[1] New State Transition Matrices for Relative Motion of Spacecraft Formations in Perturbed Orbits,
A. Koenig, T. Guffanti, S. D'Amico, AIAA 2016-5635
[2] Improved Maneuver-free approach to angles-only navigation for space rendezvous,
J. Sulli... |
"""File contains package initialization data."""
import os
import sys
from .attachment_frame import *
from .console_window import *
from .framed_entry import *
from .labeled_entry import *
from .labeled_radios import *
from .menu_bar import *
from .menu_item import *
from .labeled_file_entry import *
from . import co... |
# gdpyt-analysis: utils: binning
"""
Notes
"""
# imports
import pandas as pd
import numpy as np
from utils.functions import calculate_precision
# scripts
def bin_local_rmse_z(df, column_to_bin='z_true', bins=20, min_cm=0.5, z_range=None, round_to_decimal=5,
df_ground_truth=None, dropna=True, err... |
from typing import Optional
from botocore.client import BaseClient
from typing import Dict
from botocore.paginate import Paginator
from botocore.waiter import Waiter
from typing import Union
from typing import List
class Client(BaseClient):
def analyze_document(self, Document: Dict, FeatureTypes: List) -> Dict:
... |
import numpy as np
import matplotlib.pyplot as plt
from scipy.io import loadmat
def computeCentroids(X, indices, number_of_centroids):
"""
Returns the new centroids by computing the means of the data points
assigned to each centroid.
:param X:
:param indices:
:param number_of_centroids:
:... |
# -*- coding: utf-8 -*-
"""Functions to call when running the function.
This module should contain a function called `run_module`, that is executed
when the module is run with `python -m MODULE_NAME`.
"""
from datetime import datetime
from itertools import product
import time
from typing import Dict, Any
import numpy... |
# Copyright 2017 The Bazel Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable la... |
import sqlite3
import os
import traceback
from .. import data_utils
def get_strs(meta,key,identifier):
identifier_str = 'aportes' if identifier==meta.APORTE else 'deducciones'
key_str = 'obreros' if key==meta.OBREROS else 'empleados'
date = 'semanas' if key==meta.OBREROS else 'quincenas'
return {key:ke... |
from django.conf import settings
from django.core.management.base import BaseCommand
from olympia.accounts.utils import process_sqs_queue
from olympia.core import logger
class Command(BaseCommand):
"""Monitor and process the AWS SQS queue for Firefox Account events.
This function polls the specified SQS queu... |
from subprocess import call
from django.test import TestCase
class TestStyle(TestCase):
def test_flake8(self):
result = call(['flake8', '--exclude', 'migrations,src,settings', '.'])
self.assertEqual(result, 0, "Code is not flake8.")
|
# coding: utf-8
from requests import get
from bs4 import BeautifulSoup as BS
# url buscada
url = 'https://dataquestio.github.io/web-scraping-pages/ids_and_classes.html'
# hora da sopa ..
sopa = BS(get(url).content, 'html.parser')
# buscar pela classe
paragraphs = sopa.find_all(class_='outer-text')
print(paragraphs)
... |
# -*- coding: utf-8 -*-
TRIGGER_TUPLES = [
('contract', 'description', 'WHEN (NEW.is_visible != False)'),
('company', 'company_name', ''),
('contract_property', 'value', ''),
('line_item', 'description', ''),
]
|
"""
NSW Rural Fire Service Feed platform.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/geo_location/nsw_rural_fire_service_feed/
"""
from datetime import timedelta
import logging
from typing import Optional
import voluptuous as vol
from homeassistant... |
from kfp import dsl
from mlrun import mount_v3io
funcs = {}
def init_functions(functions: dict, project=None, secrets=None):
"""
This function will run before running the project.
It allows us to add our specific system configurations to the functions
like mounts or secrets if needed.
In this ca... |
import functools
from factory import Faker, LazyFunction
from chatrooms.apps.common.tests.factories import TortoiseModelFactory
from chatrooms.apps.users.models import User
from chatrooms.apps.users.security import get_password_hash
USER_PASSWORD = 'strongpassword'
class UserFactory(TortoiseModelFactory):
ema... |
class Node(object):
def __init__(self, data):
"""Initialize this node with the given data."""
self.data = data
self.next = None
self.count = 0
def __repr__(self):
"""Return a string representation of this node."""
return 'Node({!r})'.format(self.data)
class Li... |
# Copyright 2020 Huawei Technologies Co., Ltd
#
# 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... |
import unittest
import discord
from bot.exts.moderation.modlog import ModLog
from tests.helpers import MockBot, MockTextChannel
class ModLogTests(unittest.IsolatedAsyncioTestCase):
"""Tests for moderation logs."""
def setUp(self):
self.bot = MockBot()
self.cog = ModLog(self.bot)
sel... |
import json
import boto3
from moto import mock_sqs
from phoenix_letter.main import main
from phoenix_letter_tests.bootstrap import BaseTestCase
class MoveMessagesTestCase(BaseTestCase):
def setUp(self):
self.region = "us-east-1"
self.access_key = "asdjaoisdj"
self.secret_key = "ajshiuah... |
import json
from .base_test import BaseTestCase
class TestRegesterUser(BaseTestCase):
def test_login(self):
self.client.post('api/auth/v1/register', data=json.dumps(
self.registerdata), content_type='application/json')
response = self.client.post('api/auth/v1/login', data=json.dumps(
... |
"""
Django settings for mblog project.
Generated by 'django-admin startproject' using Django 2.2.3.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/ref/settings/
"""
import os
# B... |
"""Script to update vendor dependencies"""
import os
def main():
"""Main function"""
gopath = os.environ["GOPATH"]
terraform_path = os.path.join(*[gopath, "src", "github.com", "willguibr",
"terraform-provider-zpa"])
os.chdir(terraform_path)
os.system("git reset ... |
import datetime
import re
from django.http import HttpResponse
from django.utils.dateparse import parse_datetime
from openpyxl import Workbook
from security.models import credit_sources, disbursement_methods
from security.templatetags.security import (
currency, format_card_number, format_sort_code,
format_re... |
# Copyright 2014 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.
from telemetry.page.page_set import PageSet
class TestSimpleTwoPageSet(PageSet):
def __init__(self):
super(TestSimpleTwoPageSet, self).__init__(
... |
from django.urls import reverse_lazy
from django.views import generic
from django.views.generic import TemplateView
from .forms import CustomUserCreationForm
class HomePageView(TemplateView):
template_name = 'home.html'
class AboutPageView(TemplateView):
template_name = 'about.html'
class SignupPageView(g... |
#!/usr/bin/env python
from __future__ import print_function
import sys
import time
import subprocess
from signal import SIGTERM
import socket
import string
import os
USAGE = 'usage: functional_tests_rpc.py <python> <srcdir> <builddir> [<tests-to-run> | all]'
DEFAULT_TESTS = ['address_book', 'bans', 'blockchain', 'col... |
from .jumbo_api import JumboApi |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# -*- coding: gbk -*-
# Date: 2019/2/13
# Created by 冰河
# Description 确定一个FTP服务器是否允许匿名登录,允许则返回True,不允许返回False
# 博客 https://blog.csdn.net/l1028386804
import ftplib
#确认主机是否存在FTP匿名登录
def anonLogin(hostname):
try:
ftp = ftplib.FTP(hostname)
ftp.login('anon... |
#
# This file is part of snmpfwd software.
#
# Copyright (c) 2014-2019, Ilya Etingof <etingof@gmail.com>
# License: http://snmplabs.com/snmpfwd/license.html
#
import os
import sys
import logging
import socket
import stat
import time
from logging import handlers
from snmpfwd.error import SnmpfwdError
LOG_DEBUG = 0
LOG_... |
# PROGRAMMER: Justin Bellucci
# DATE CREATED: 04_18_2020
# REVISED DATE:
# Imports python modules
import torch
# import torch.nn.functional as F
from torch import nn, optim
# from collections import OrderedDict
from torchvision import models
from workspace_utils import active_sessio... |
#
# FILENAME.
# Dashboard.py - Dashboard Application.
#
# FUNCTIONAL DESCRIPTION.
# The app collects important information in dashboard.
#
# NOTICE.
# Author: visualge@gmail.com (Count Chu)
# Created on 2019/7/20
#
#
# Include standard packages.
#
import argparse
import logging
import pdb
imp... |
# coding: utf-8
# Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved.
# This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may c... |
from functools import partial
import numpy as np
import torch
from torch import nn
from torch.nn import functional as F
from torch.optim import Adam
NON_LINEARITIES = {
"none": lambda x: x,
"gate": lambda x: (torch.sign(x) + 1.) / 2.,
"relu": F.relu,
"sign": torch.sign,
"tanh": torch.tanh,
"s... |
class cYnfElement():
""" Ynf要素クラス
このクラスを継承して、要素を作成する。
過剰かもしれないけど、全要素にツールメソッドを持つ。
順番を入れ替えたり一部を非表示にしたときに、
前後がない単独の状態でも正しく表示できるように。
"""
def __init__(self, prop:dict):
# 必須項目(全要素共通)
self.prop = {
'display': True,
'fill-color': None,
'border-co... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.