text stringlengths 2 999k |
|---|
# qubit number=4
# total number=34
import cirq
import qiskit
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit import BasicAer, execute, transpile
from pprint import pprint
from qiskit.test.mock import FakeVigo
from math import log2
import numpy as np
import networkx as nx
def bitwise_... |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: kikimr/public/api/grpc/yq_v1.proto
"""Generated protocol buffer code."""
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflectio... |
# coding=utf-8
r"""
This code was generated by
\ / _ _ _| _ _
| (_)\/(_)(_|\/| |(/_ v1.0.0
/ /
"""
from twilio.base import deserialize
from twilio.base import values
from twilio.base.instance_context import InstanceContext
from twilio.base.instance_resource import InstanceResource
from twilio.base... |
# -*- coding: utf-8 -*-
# PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:
# https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code
from ccxt.base.exchange import Exchange
import hashlib
from ccxt.base.errors import ExchangeError
from ccxt.base.errors import Authenticati... |
#!/usr/bin/env python3
# Copyright (c) 2014-2018 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 longpolling with getblocktemplate."""
from decimal import Decimal
from test_framework.test_frame... |
import openai
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from tenacity import retry, wait_random_exponential, stop_after_attempt
from sklearn.metrics import precision_recall_curve
from sklearn.metrics import average_precision_score
@retry(wait=wait_random_exponential(min=1, max=20), stop=... |
import json
import random
import string
import time
from datetime import datetime
from pathlib import Path
import pytest
from test.test_flask_app import app, db, Setting, SubSetting, SimpleModel, DateTest
def random_string(length=20):
"""
return a <length> long character random string of ascii_letters
:... |
#! /usr/bin/env python
# Copyright (c) 2020 Uber Technologies, 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 a... |
# myNN.py
# tested with Python3.7
# author: Elsa Burren
import numpy as np
def sigmoid(x):
return 1 / (1 + np.exp(-x))
class MyNode:
def __init__(self, w):
self.w = w
def update(self, dw):
self.w += dw
def output(self, x):
return sigmoid(np.dot(x, self.w))
class MyHiddenLaye... |
fname = input('Enter a filename: ')
try:
fhandle = open(fname)
except:
print('The filename entered is either invalid or does not exist')
quit()
count = 0
total = 0
for line in fhandle:
line_clean = line.rstrip()
if line_clean.startswith('X-DSPAM-Confidence:'):
count = count + 1
pos... |
#
# PySNMP MIB module ONEACCESS-SSH-CONFIG-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ONEACCESS-SSH-CONFIG-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 20:25:24 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.... |
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
# pose.shape : ({joint_num}, 3)
# index_list : np.arange({joint_num})
def visualizePose(pose, mode=None, fig_scale=1, index_list=None,):
fig = plt.figure()
ax = fig.add_subplot(111 , projection='3d')
for i,p in enumerate(pose):
... |
"""
Functions for Blasi 1993 and Blasi Branca 2001 kinetic reaction schemes for
biomass pyrolysis. See comments in each function for more details.
References:
Blasi, 1993. Combustion Science and Technology, 90, pp 315–340.
Blasi, Branca, 2001. Ind. Eng. Chem. Res., 40, pp 5547-5556.
"""
import numpy as np
def blasi(... |
"""Support for KNX/IP fans."""
from __future__ import annotations
import math
from typing import Any, Final
from xknx import XKNX
from xknx.devices import Fan as XknxFan
from homeassistant.components.fan import SUPPORT_OSCILLATE, SUPPORT_SET_SPEED, FanEntity
from homeassistant.const import CONF_NAME
from homeassista... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import re
from setuptools import setup, find_packages
def get_version():
filepath = os.path.join(
os.path.dirname(__file__),
"interpro7dw",
"__init__.py"
)
with open(filepath) as fh:
text = fh.read()
m = re.sear... |
# Copyright 2021 Dynatrace 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 agreed t... |
from operator import attrgetter
import pyangbind.lib.xpathhelper as xpathhelper
from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType, RestrictedClassType, TypedListType
from pyangbind.lib.yangtypes import YANGBool, YANGListType, YANGDynClass, ReferenceType
from pyangbind.lib.base import PybindBase
from d... |
# 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... |
from shapely.geometry import Point
from shapely.geometry.polygon import Polygon
def getOverlappingEntities(canvasDataArray):
overlapCount = 0
for document in canvasDataArray:
loc = getCoordinates(document)
for newDocument in canvasDataArray:
newLoc = getCoordinates(newDocument)
... |
# -*- coding: utf-8 -*-
from patientMatcher.utils.add import add_node
def test_add_client(database, test_client):
"""Test adding a client with auth token to the database"""
is_client = True
# no clients should be present in demo database
assert database["clients"].find_one() is None
inserted_i... |
table = lv.table(lv.scr_act(), None)
table.set_col_cnt(2)
table.set_row_cnt(4)
table.set_size(200,200)
table.align(lv.scr_act(), lv.ALIGN.CENTER, -15, 0)
# Make the cells of the first row center aligned
table.set_col_width(0,100)
table.set_cell_align(0, 0, lv.label.ALIGN.CENTER)
table.set_cell_align(0, 1, lv.label.AL... |
import os
import shutil
import pytest
from modelkit.assets import errors
from modelkit.assets.manager import AssetsManager
from tests import TEST_DIR
def test_local_manager_no_versions(working_dir):
# This test makes sure that the AssetsManager is able to retrieve files
# refered to by their paths relative ... |
# Copyright 2019 Extreme Networks, 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 i... |
#!/usr/bin/python3 -OO
# Copyright 2007-2020 The SABnzbd-Team <team@sabnzbd.org>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any late... |
from flask import Flask, jsonify, request
from pathlib import Path
app = Flask(__name__, static_url_path='')
@app.route('/')
def index():
return app.send_static_file("index.html")
@app.route('/api/experiments')
def get_experiments():
all_exps = (Path(__file__).parent / "static").glob("[0-9]*_*_1shot_*")
... |
# 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... |
from __future__ import division
import numpy as np
import torch
import torch.nn as nn
from mmcv.cnn import normal_init
from mmdet.core import (AnchorGenerator, anchor_target, delta2bbox, force_fp32,
multi_apply, multiclass_nms)
from ..builder import build_loss
from ..registry import HEADS
@H... |
import os
# supress tensorflow logging other than errors
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
import numpy as np
import tensorflow as tf
from keras import backend as K
from keras.datasets import mnist
from keras.models import Sequential, load_model
from keras.layers import Dense, Dropout, Activation, Flatten
from... |
# coding: utf-8
"""
Swagger Petstore
This is a sample Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). # noqa: E501
OpenAPI spec version: 1.0.0
Contact: apiteam@swagger.io
Generated by:... |
#!/usr/bin/env python
from __future__ import print_function
import io
import os
import subprocess
import sys
import contextlib
from distutils.command.build_ext import build_ext
from distutils.sysconfig import get_python_inc
import distutils.util
from distutils import ccompiler, msvccompiler
from setuptools import Exten... |
import os.path
try:
from bpython._version import __version__ as version
except ImportError:
version = 'unknown'
__version__ = version
package_dir = os.path.abspath(os.path.dirname(__file__))
def embed(locals_=None, args=['-i', '-q'], banner=None):
from bpython.cli import main
return main(args, local... |
colnames=['background', "Gallbladder", "Liver", "Pancreas", "Spleen", "Stomach"]
df = pd.read_csv('test.csv',names=colnames, header=None)
df = df[["Gallbladder", "Liver", "Pancreas", "Spleen", "Stomach"]]
df
|
import json
import os
import subprocess
import sys
import time
from shutil import copyfile
from enum import Enum
import boto3
import ray
from ray.tune import run_experiments
from .tf_serving_utils import export_tf_serving, natural_keys, change_permissions_recursive
from .configuration_list import ConfigurationList
fr... |
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class Thrust(Package):
"""Thrust is a parallel algorithms library
which resembles the C++ St... |
#!/usr/bin/env python
# This file is part of the pyMOR project (https://www.pymor.org).
# Copyright 2013-2021 pyMOR developers and contributors. All rights reserved.
# License: BSD 2-Clause License (https://opensource.org/licenses/BSD-2-Clause)
import pkg_resources
import typer
def _output_rich(filename, status):
... |
import smart_imports
smart_imports.all()
class BaseForm(forms.BaseUserForm):
place = utils_fields.ChoiceField(label='Город')
new_description = bbcode_fields.BBField(label='Новое описание', max_length=places_conf.settings.MAX_DESCRIPTION_LENGTH)
def __init__(self, *args, **kwargs):
super(BaseFor... |
# Copyright: (c) 2014, James Tanner <tanner.jc@gmail.com>
# Copyright: (c) 2018, Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import datetime
import json
import os
im... |
x= float (input('Digite o valor do preço do produto '))
des = (x * 5)/100
print('O valor do produto é {} e o valor depois do desconto de 5% é {}'.format(x,des))
|
"""
Example codes for speech dereverberation based on the WPE variants.
author: Joon-Young Yang (E-mail: dreadbird06@gmail.com)
"""
import os
# os.environ["CUDA_VISIBLE_DEVICES"]=args.gpu_id
import numpy as np
import soundfile as sf
import torch
torch.set_printoptions(precision=10)
from torch_custom.torch_utils imp... |
#!/usr/bin/env python
# coding: utf-8
# # Hierarchical Clustering Lab
# In this notebook, we will be using sklearn to conduct hierarchical clustering on the [Iris dataset](https://archive.ics.uci.edu/ml/datasets/iris) which contains 4 dimensions/attributes and 150 samples. Each sample is labeled as one of the three ty... |
import functools
import os
import pytest
from docker.errors import APIError
from docker.utils import version_lt
from .. import unittest
from ..helpers import BUSYBOX_IMAGE_WITH_TAG
from compose.cli.docker_client import docker_client
from compose.config.config import resolve_environment
from compose.config.environment... |
from django.db import models
# Create your models here.
# from multiselectfield import MultiSelectField
class ListField(models.CharField):
#
# def __init__(self, *args, **kwargs):
# super().__init__(*args, **kwargs)
def get_db_prep_value(self, value, connection=None, prepared=False):
if ... |
import time
import numpy as np
nax = np.newaxis
import pdb
DEBUGGER = None
"""
Routines for forward and reverse AIS. The sequence of distributions is given in terms
of a Problem class, which should provide the following methods:
- init_sample(): return an exact sample from the initial distribution
- init_partition... |
data_fields_store = {
"endpoint_pose": [
'.endpoint_state.pose.position.x',
'.endpoint_state.pose.position.y',
'.endpoint_state.pose.position.z',
'.endpoint_state.pose.orientation.x',
'.endpoint_state.pose.orientation.y',
'.endpoint_state.pose.orientation.z',
... |
### electoral crime and performance paper
# judicial decisions script
# this script uses the trained models to predict sentence categories. i
# use the textual info in the sentences to determine the (class)
# allegations against individual candidates running for office.
# author: andre assumpcao
# by andre.assumpca... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
from morango.models import UUIDField
from kolibri.core.auth.models import AbstractFacilityDataModel
from kolibri.core.auth.models import Facility
from kolibri.core.auth.models import FacilityUser
from kolibri.core.auth.permis... |
"""This package contains modules related to objective functions, optimizations, and network architectures.
To add a custom model class called 'dummy', you need to add a file called 'dummy_model.py' and define a subclass DummyModel inherited from BaseModel.
You need to implement the following five functions:
-- <__... |
# -*- coding: utf-8 -*-
from random import getrandbits
import wx
class Game(wx.Frame):
""" Frame handling the grid and game parameters. """
def __init__(self, amount: int, width: int, origin: int, left: int):
# Non-resizable frame with predefined title and size
wx.Frame.__init__(self, None, ti... |
#---------------------------------------------------------------------------
# Copyright 2019 The Open Source Electronic Health Record Alliance
#
# 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... |
# Ignoring some linting rules in tests
# pylint: disable=redefined-outer-name
# pylint: disable=missing-docstring
import pytest
import numpy as np
from bingo.Base.FitnessFunction import FitnessFunction, VectorBasedFunction
from bingo.Base.ContinuousLocalOptimization import ContinuousLocalOptimization
from bingo.Base.M... |
# nodoctest
# Numerical Sage documentation build configuration file, created by
# sphinx-quickstart on Sat Dec 6 11:08:04 2008.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# The contents of this file are pickled, so don't put values in the namespace
# that aren't pickleable (mo... |
"""
Module that includes all the functions for Subgroup Discovery (SD)
"""
import logging
import math
from enum import Enum
def sd(dataset):
"""
Main function for subgroup discovery. Configure the subgroup to evaluate it
"""
####################### CONFIGURE THIS ##########################... |
from .resnet_upsnet import resnet_50_upsnet, resnet_101_upsnet
|
import numpy as np
#import galpy
#from scipy import weave
# Functions:
# gal_uvwxyz: converts equatorial to galactic coordinates.
# gal_rdpmuv: converts galactic coordinates into equatorial.
# gal_tester: checks to make sure gal_uvwxyz and gal_rdpmuv are inverses
# ballistic: computes a straight-line linear traceba... |
# Copyright 2013-2022 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
from spack.pkg.builtin.boost import Boost
class Clfft(CMakePackage):
"""a software library conta... |
def check_kwargs(input_kwargs, allowed_kwargs, raise_error=True):
"""Tests if the input `**kwargs` are allowed.
Parameters
----------
input_kwargs : `dict`, `list`
Dictionary or list with the input values.
allowed_kwargs : `list`
List with the allowed keys.
raise_error : `bool... |
#!/usr/bin/env python3
#
# author : Michael Brockus.
# contact: <mailto:michaelbrockus@gmail.com>
# license: Apache 2.0 :http://www.apache.org/licenses/LICENSE-2.0
#
# copyright 2020 The Meson-UI development team
#
_MESONUI_THEME = '''\
/*
*/
QMainWindow, QDialog {
border: 0px solid #263238;
background-colo... |
"""
The MIT License (MIT)
Copyright (c) 2015-present Rapptz
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, merg... |
level_map = [
' ',
' ',
' ',
' XX XXX XX ',
' XX P ',
' XXXX XX XX ',
' XXXX XX ',
' XX X XXXX XX XX ',
' X XXXX XX XXX ',
' XXX... |
# -*- coding: utf-8 -*-
"""
astromatch module for calculation of magnitude priors.
@author: A.Ruiz
"""
import os
import warnings
import numpy as np
from astropy import units as u
from astropy.table import Table
from astropy.utils.exceptions import AstropyUserWarning
from scipy.interpolate import interp1d
from scipy.n... |
#!/usr/bin/env python3
import copy
import difflib
import logging
from pathlib import Path
from typing import Dict, Optional, Union
import click
import requests
import rich
import toml
from packaging.specifiers import Specifier
from packaging.version import Version
from rich.logging import RichHandler
from rich.syntax... |
"""
This module is the main part of the library. It houses the Scheduler class
and related exceptions.
"""
from threading import Thread, Event, Lock
from datetime import datetime, timedelta
from logging import getLogger
import os
import sys
from apscheduler.util import *
from apscheduler.triggers import SimpleTrigger... |
#!/usr/bin/env python
# Copyright 2016 Preferred Networks, 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 appl... |
from tests.system.action.base import BaseActionTestCase
class GroupSetPermissionActionTest(BaseActionTestCase):
def test_set_permission_set_true(self) -> None:
self.create_model(
"group/11", {"name": "group_11", "permissions": ["test", "bla"]}
)
response = self.client.post(
... |
import scrapy
class KakaoshoppingSpider(scrapy.Spider):
name = 'kakaoshopping'
allowed_domains = ['shoppinghow.kakao.com']
start_urls = ['http://shoppinghow.kakao.com/']
def parse(self, response):
pass
|
#import the libraries
import numpy as np
import random
# class of random agent
class RandomAgent( object ):
def __init__( self, prob_list ):
self.prob_list = prob_list
def pull( self, bandit_machine ):
if np.random.random() < self.prob_list[ bandit_machine ]:
reward = 1
els... |
#
# OtterTune - models.py
#
# Copyright (c) 2017-18, Carnegie Mellon University Database Group
#
from collections import namedtuple, OrderedDict
from django.contrib.auth.models import User
from django.core.validators import validate_comma_separated_integer_list
from django.db import models, DEFAULT_DB_ALIAS
from djang... |
#!/usr/bin/env python
__author__ = 'kinpa200296'
from myxrange import myxrange
|
import itertools
from operator import mul
import numpy as np
from pgmpy.factors.discrete import DiscreteFactor
from pgmpy.independencies import Independencies
from pgmpy.extern.six.moves import range, zip
from pgmpy.extern import six
class JointProbabilityDistribution(DiscreteFactor):
"""
Base class for Joi... |
import os
import requests
from pyrogram import Client, filters
from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton
REMOVEBG_API = os.environ.get("REMOVEBG_API", "")
UNSCREEN_API = os.environ.get("UNSCREEN_API", "")
PATH = "./DOWNLOADS/"
Bot = Client(
"Remove Background Bot",
bot_token = os.... |
"""Rename action._type to action.type_
Revision ID: 45024170cf6
Revises: 337978f8c75
Create Date: 2014-06-18 14:21:37.202030
"""
# revision identifiers, used by Alembic.
revision = '45024170cf6'
down_revision = '337978f8c75'
from alembic import op
import sqlalchemy as sa
from evesrp.models import ActionType
def u... |
from __future__ import print_function, absolute_import
import torch
import torch.nn as nn
from torch.nn.modules.loss import _Loss
from super_gradients.training.utils import convert_to_tensor
class RSquaredLoss(_Loss):
def forward(self, output, target):
# FIXME - THIS NEEDS TO BE CHANGED SUCH THAT THIS ... |
"""
:Copyright (c) 2021 Chen Yang, Siqi Zhu,Jeffrey Li,Minyi Lei
:license: MIT, see LICENSE for more details.
"""
from app.truthtable.truthTable import *
from app.truthtable.main import *
from flask import g, request, jsonify
from lin.redprint import Redprint
from app.exception.api import QuizNotFound, StrIn... |
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
import argparse
import os
import sys
import time
from collections import defaultdict
import six
from dateutil.relatived... |
# Copyright (c) 2019-2020, NVIDIA CORPORATION.
# 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... |
from django.conf import settings
from django.contrib.contenttypes.fields import GenericRelation
from django.core.exceptions import ValidationError
from django.db import models
from django.urls import reverse
from taggit.managers import TaggableManager
from dcim.choices import InterfaceModeChoices
from dcim.models impo... |
import machine, time
from machine import Pin
__version__ = '0.2.0'
__author__ = 'Roberto Sánchez'
__license__ = "Apache License 2.0. https://www.apache.org/licenses/LICENSE-2.0"
# Modified by R. Levine on 12/26/17 for academic use
class HCSR04:
"""
Driver to use the untrasonic sensor HC-SR04.
The sensor range is b... |
import _plotly_utils.basevalidators
class FamilyValidator(_plotly_utils.basevalidators.StringValidator):
def __init__(
self, plotly_name="family", parent_name="layout.slider.font", **kwargs
):
super(FamilyValidator, self).__init__(
plotly_name=plotly_name,
parent_name=p... |
# Serial test script for initializing problem with preexisting array
# Standard modules
import sys
# Other modules
import logging
import numpy as np
import h5py
# Athena modules
import scripts.utils.athena as athena
sys.path.insert(0, '../../vis/python')
import athena_read # noqa
athena_read.check_nan_flag = True
l... |
"""Test pbtranscript.Classifier."""
import unittest
import os
import os.path as op
from pbtranscript.Classifier import Classifier, PBRead
from pbtranscript.io.DOMIO import DOMRecord
from collections import namedtuple
from test_setpath import DATA_DIR, OUT_DIR, STD_DIR
import filecmp
class Test_Classifier(unittest.Tes... |
from .predict import CoreHDF
from .util import CDFLog, CDFContext
cHDF = CoreHDF()
cLog = CDFLog() |
#!/usr/bin/env python3
"""
This is a simple utility that takes a time as seconds or milliseconds since the unix epoch (midnight 1970-01-01) and attempts to print it as an ISO-8601 string.
It will attempt to guess whether the number you give it is seconds or milliseconds.
"""
import time
from datetime import timezone,... |
from models import Error, ErrorBatch
import traceback
import socket
import warnings
import md5
class CrashLogMiddleware(object):
def process_exception(self, request, exception):
server_name = socket.gethostname()
tb_text = traceback.format_exc()
class_name = exception.__class__.__name... |
#!/usr/bin/python
#
# @author: Gaurav Rastogi (grastogi@avinetworks.com)
# Eric Anderson (eanderson@avinetworks.com)
# module_check: supported
#
# Copyright: (c) 2017 Gaurav Rastogi, <grastogi@avinetworks.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
#
ANSIB... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
This file contains functions for lading reddit data
"""
import os
import json
from copy import deepcopy
import numpy as np
# from tree2branches import tree2branches
#%%
def listdir_nohidden(path):
contents = os.listdir(path)
new_contents = [i for i in conten... |
#!/usr/bin/env python3
import os
import re
from datetime import datetime
from src.date import Date
os.chdir(os.path.dirname(__file__))
def test_parse_date_format_valid():
"""Test that parse_date_format returns a valid format for strftime"""
datetime.strftime(
datetime.now(),
Date().parse("YY... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from collections import namedtuple
import numpy as np
import tensorflow as tf
import six.moves.queue as queue
import scipy.signal
import threading
def discount(x, gamma):
return scipy.signal.lfilter([1], [1... |
"""
Author: Peratham Wiriyathammabhum
"""
import numpy as np
import pandas as pd
import scipy as sp
import matplotlib.pyplot as plt
import scipy.sparse.linalg as linalg
def naivebayes(X):
"""
Perform spectral clustering on an input row matrix X.
mode \in {'affinity','neighborhood','gaussian'}
See: http://www.... |
# 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
# distributed under t... |
from .theoretical_estimates import *
from math import inf, ceil, log2, comb
from prettytable import PrettyTable
from progress.bar import Bar
from scipy.special import binom as binom_sp
from scipy.optimize import fsolve
from warnings import filterwarnings
filterwarnings("ignore", category=RuntimeWarning)
def binom(n,... |
'''
Created on Dec 22, 2014
@author: szirkdas
'''
import comment_information as COMMENT
import favorite_information as FAV
import playlist_information as PLAYLIST
import following_information as FOLLOW
import user_information as USER
import track_information as TRACK
import soundcloud
from py2neo import authenticate,... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
name: 宏景EHR系统多处SQL注入
referer: http://www.wooyun.org/bugs/wooyun-2014-075122
author: Lucifer
description: 1.由于/pos/posbusiness/train_get_code_tree.jsp页面参数codesetid未安全过滤导致SQL延时注射漏洞
2.由于/servlet/sys/option/customreport/tree页面参数id未安全过滤导致SQL延时注射漏洞
3... |
# $ANTLR 3.1.3 Mar 18, 2009 10:09:25 proto_lexer.g 2013-10-23 04:20:51
import sys
from antlr3 import *
from antlr3.compat import set, frozenset
# for convenience in actions
HIDDEN = BaseRecognizer.HIDDEN
# token types
EXPONENT=60
MESSAGE_LITERAL=11
REQUIRED_PROTOBUF_SCOPE_LITERAL=29
STRING_GUTS=54
EQUALS=25
UINT32_... |
from bokeh.charts import BoxPlot, output_file, show
from bokeh.sampledata.autompg import autompg as df
p = BoxPlot(df, values='mpg', label='cyl', outliers=False,
title="MPG Summary (grouped by CYL, no outliers)")
output_file("boxplot.html")
show(p) |
"""Entrypoint for TweetOff"""
from .app import create_app
APP = create_app()
|
import urllib.request
from pathlib import Path
import os
from shutil import rmtree
from tqdm import tqdm # type: ignore
from urllib import robotparser
class DownloadProgressBar(tqdm):
def update_to(self, b=1, b_size=1, t_size=None):
if t_size is not None:
self.total = t_size
self.upda... |
"""Get the local IP address of the Home Assistant instance."""
import voluptuous as vol
from homeassistant.config_entries import SOURCE_IMPORT, ConfigEntry
from homeassistant.const import CONF_NAME
from homeassistant.core import HomeAssistant
import homeassistant.helpers.config_validation as cv
from .const import DOM... |
from django.core.paginator import Paginator
from django.shortcuts import get_object_or_404, redirect, render
from django.urls import reverse
from django.utils.translation import ugettext as _
from django.views.decorators.vary import vary_on_headers
from wagtail.admin import messages
from wagtail.admin.forms.search imp... |
# pylint: skip-file
#- @a defines/binding VarA
#- @b defines/binding VarB
#- @c defines/binding VarC
a = b = c = 1
# TODO(b/137314416): @a ref VarA does not work
#- @x defines/binding VarX
x = (a +
#- @b ref VarB
b +
#- @c ref VarC
c)
#- @y defines/binding VarY
#- @a ref VarA
y = list(a,
#- @b ref VarB
... |
from ._internal.frameworks.tensorflow import load
from ._internal.frameworks.tensorflow import save
from ._internal.frameworks.tensorflow import load_runner
from ._internal.frameworks.tensorflow import import_from_tfhub
__all__ = ["load", "load_runner", "save", "import_from_tfhub"]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.