text stringlengths 2 999k |
|---|
from great_expectations.render.renderer.content_block.content_block import (
ContentBlockRenderer,
)
from great_expectations.render.types import (
RenderedBulletListContent,
RenderedStringTemplateContent,
)
class ExceptionListContentBlockRenderer(ContentBlockRenderer):
"""Render a bullet list of excep... |
#!/usr/bin/env python
#
# Electrum - Lightweight Bitcoin Client
# Copyright (C) 2015 Thomas Voegtlin
#
# 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... |
# -*- coding: utf-8 -*-
# SPDX-License-Identifier: MIT
from __future__ import absolute_import
from mock import patch
import pytest
from module_build_service import app
from module_build_service.common import models
from module_build_service.common.models import BUILD_STATES, ModuleBuild
from module_build_service.mana... |
# -*- test-case-name: twisted.test.test_factories -*-
#
# Copyright (c) 2001-2004 Twisted Matrix Laboratories.
# See LICENSE for details.
"""Standard implementations of Twisted protocol-related interfaces.
Start here if you are looking to write a new protocol implementation for
Twisted. The Protocol class contains ... |
# -*- coding: utf-8 -*-
"""
AsciiDoc Reader
===============
This plugin allows you to use AsciiDoc to write your posts.
File extension should be ``.asc``, ``.adoc``, or ``asciidoc``.
"""
from pelican.readers import BaseReader
from pelican.utils import pelican_open
from pelican import signals
import six
try:
# a... |
# Generated by Django 2.2.4 on 2019-08-13 12:04
from django.db import migrations
import mdeditor.fields
class Migration(migrations.Migration):
dependencies = [
('blog', '0003_post_clicks'),
]
operations = [
migrations.RemoveField(
model_name='post',
name='excerpt... |
from django.conf.urls import url
from rest_framework.urlpatterns import format_suffix_patterns
from drfpasswordless.views import (ObtainEmailCallbackToken,
ObtainMobileCallbackToken,
ObtainAuthTokenFromCallbackToken,
... |
import distutils.sysconfig
import os
import platform
import re
import sys
def get_python_relative_libdir():
"""Returns the appropropriate python libdir relative to the build directory.
@param exe_path the path to the lldb executable
@return the python path that needs to be added to sys.path (PYTHONPATH)... |
# 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... |
class Engine:
PANDAS = "pandas"
POSTGRES = "postgres"
PRESTO = "Presto"
SPARK = "Spark"
SQL_SERVER = "SqlServer"
known_engines = {PANDAS, POSTGRES, PRESTO, SPARK, SQL_SERVER}
|
#!/usr/bin/env python
# Copyright Contributors to the Open Shading Language project.
# SPDX-License-Identifier: BSD-3-Clause
# https://github.com/imageworks/OpenShadingLanguage
# This shader would ordinarily issue a warning.
# With -Werror, it should be upgraded to an error.
failureok = 1 # this test is expected... |
from multiprocessing import freeze_support
from pathlib import Path
from typing import Dict
from deafwave.full_node.full_node import FullNode
from deafwave.rpc.full_node_rpc_api import FullNodeRpcApi
from deafwave.server.outbound_message import NodeType
from deafwave.server.start_service import run_service
from deafwa... |
"""
Computes putative binding pockets on protein.
"""
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
__author__ = "Bharath Ramsundar"
__copyright__ = "Copyright 2017, Stanford University"
__license__ = "MIT"
import os
import tempfile
import numpy as np
fr... |
# 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 selenium import webdriver
import time
from bs4 import BeautifulSoup
import requests
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
driver = webdriver.PhantomJS()
driver.set_window_size(1120,550)
d... |
# coding=utf-8
# Copyright 2018 The Google AI Language Team 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 ... |
from __future__ import annotations
from decimal import Decimal
def inverse_of_matrix(matrix: list[list[float]]) -> list[list[float]]:
"""
A matrix multiplied with its inverse gives the identity matrix.
This function finds the inverse of a 2x2 matrix.
If the determinant of a matrix is 0, its inverse d... |
# Copyright (c) Ye Liu. All rights reserved.
import nncore
def test_bind_getter():
@nncore.bind_getter('name', 'depth')
class Backbone:
_name = 'ResNet'
_depth = 50
backbone = Backbone()
assert backbone.name == 'ResNet'
assert backbone.depth == 50
|
# Generated by Django 2.1.4 on 2019-03-24 19:19
import datetime
import django.contrib.auth.models
import django.contrib.auth.validators
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
dependencies = [
('auth', '0009_alter_u... |
import os
import click
from yoda.ssh.shell import Shell
from yoda.ssh.config import importHost
# Context obj
class Cmd():
def __init__(self):
self.verbose = False
self.shell = None
self.host = None
pass_cmd = click.make_pass_decorator(Cmd, ensure=True)
class CmdsLoader(click.MultiCommand):
_cmdFolder... |
"""This module supports puzzles that place fixed shape regions into the grid."""
from collections import defaultdict
import sys
from typing import Dict, List
from z3 import ArithRef, Int, IntVal, Or, Solver, PbEq
from .fastz3 import fast_and, fast_eq, fast_ne
from .geometry import Lattice, Point, Vector
from .quadtre... |
def Print():
print('you may want to install beautifulsoup4,not beautfulsoup4')
|
from os.path import abspath, dirname, join
from os import environ, path
_cwd = dirname(abspath(__file__))
basedir = path.abspath(path.dirname(__file__))
class BaseConfiguration(object):
DEBUG = True
SECRET_KEY = 'Test'
CORS = ["http://localhost:4200", "http://127.0.0.1:5000"] |
# File to hold all objects to ease construction of JSON payload.
# Non-PEP8 property declaration used as JSON serializing is 1:1, eg. "clientId = clientId", not "client_id = clientId"
class Client(object):
clientId = ""
clientVersion = "0.0.1"
def __init__(self, client_id, client_version="0.0.1"):
... |
from .utils.defaults import default_depot_path, default_install_dir, default_symlink_dir
from .utils.filters import f_major_version, f_minor_version
from .utils import query_yes_no
from .utils import current_architecture, current_system, current_libc
from .utils import latest_version
from .utils import DmgMounter, TarM... |
# Automatically generated
# pylint: disable=all
get = [{'SupportedArchitectures': ['arm64'], 'SustainedClockSpeedInGhz': 2.3, 'DefaultVCpus': 1, 'DefaultCores': 1, 'DefaultThreadsPerCore': 1, 'ValidCores': [1], 'ValidThreadsPerCore': [1], 'SizeInMiB': 2048, 'EbsOptimizedSupport': 'default', 'EncryptionSupport': 'supp... |
#
# Tic Tac Toe
#
import numpy as np
from gym import spaces
WinMasks = [
[
[1,0,0],
[1,0,0],
[1,0,0],
],
[
[0,1,0],
[0,1,0],
[0,1,0],
],
[
[0,0,1],
[0,0,1],
[0,0,1],
],
[
[1,1,1],
[0,0,0],
... |
###################################################################
""" Summary: Class and Methods for deriving MCSS based MMP's
About: Derive a matched pair based MCSS from a pair molecules
To do: - extend the method enumerate_fragment_properties to also
enumerate self.mol_smi_dict as this would allow th... |
import os
import json
CURRENT_DIR = os.path.dirname(os.path.realpath(__file__))
class Action:
def __init__(self, card, config):
config.pop("action", None)
self.card = card
self.config = config
def env_vars_for_object(self, config, prefix):
env_vars = {}
config.pop("... |
from office365.runtime.client_value_collection import ClientValueCollection
from office365.runtime.queries.service_operation_query import ServiceOperationQuery
from office365.runtime.resource_path import ResourcePath
from office365.sharepoint.base_entity import BaseEntity
from office365.sharepoint.tenant.administration... |
# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
__version__ = '1.18.1333'
# -----------------------------------------------------------------------------
import asyncio
import concurrent
import socket
import time
import math
import random
import certifi
import... |
import csv
def ClassFactory(class_name, dictionary):
return type(class_name, (object,), dictionary)
class CsvReader:
def __init__(self, filepath):
self.data = []
with open(filepath) as csv_files:
csv_data = csv.DictReader(csv_files, delimiter=',')
for row in csv_data... |
# Copyright 2017 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.
import json
import unittest
import mock
from dashboard.pinpoint.models.quest import read_value
from tracing.value import histogram_set
from tracing.value i... |
"""Tests for fan platforms."""
import pytest
from homeassistant.components.fan import FanEntity
class BaseFan(FanEntity):
"""Implementation of the abstract FanEntity."""
def __init__(self):
"""Initialize the fan."""
def test_fanentity():
"""Test fan entity methods."""
fan = BaseFan()
... |
from ynab_api import __version__
def test_version():
assert __version__ == '0.1.0'
|
from vkbottle_types import GroupTypes
from vkbottle_types.events import GroupEventType, UserEventType
from .api import (
ABCAPI,
API,
DEFAULT_REQUEST_VALIDATORS,
DEFAULT_RESPONSE_VALIDATORS,
ABCRequestRescheduler,
ABCRequestValidator,
ABCResponseValidator,
ABCTokenGenerator,
Blockin... |
import cv2 as cv
image = cv.imread() |
# -*- encoding: utf-8
from sqlalchemy.testing import eq_, engines
from sqlalchemy import *
from sqlalchemy import exc
from sqlalchemy.dialects.mssql import pyodbc, pymssql
from sqlalchemy.engine import url
from sqlalchemy.testing import fixtures
from sqlalchemy import testing
from sqlalchemy.testing import assert_raise... |
#!python
# coding=utf-8
import cfg, cmn, vqw
import cookielib, urllib, urllib2, sys, argparse, re, string
import simplem3u8 as sm3u8
import simplejson as json
from urllib2 import Request, urlopen, URLError
from random import random
cmnHandler = cmn.cmnHandler()
_url_re = re.compile(r"""
http(s)?://(\w+.)?wasd\.tv/... |
# Import spacy
import spacy
# Instantiate the English model: nlp
nlp = spacy.load('en', tagger=False, parser= False, matcher = False)
# Create a new document: doc
doc = nlp(article)
# Print all of the found entities and their labels
for ent in doc.ents:
print(ent.label_, ent.text)
""" <script.py> output:
OR... |
import glob
import cv2
import os
def extract_frame(movie_files_dir, out_dir):
movie_files = glob.glob(movie_files_dir)
if not movie_files:
print('movie files are not found.')
return
for movie_file in movie_files:
ext = movie_file.split('.')[-1]
if not ext == 'mp4' or not ... |
#!/usr/bin/env python
from ping360_sonar.sensor import Ping360
from numpy import pi, sqrt, tan, cos, sign
from brping import definitions
class SonarInterface:
samplePeriodTickDuration = 25e-9
firmwareMinTransmitDuration = 5
firmwareMaxTransmitDuration = 500
firmwareMaxSamples = 1200
firmwareM... |
"""
MD Analysis
===========
#. :class:`.MDAnalysis`
Class for converting a molecule to and back from an MDAnalysis object.
"""
import logging
from ...utilities import WrapperNotInstalledException
try:
import MDAnalysis as mda
except ModuleNotFoundError:
mda = None
logger = logging.getLogger(__name__)
c... |
def fact (n):
if n == 1:
return 1
else:
return n*fact(n-1)
print(fact(5)) |
import torch
from torch.optim import Optimizer
class OptimWrapper(Optimizer):
# Mixin class that defines convenient functions for writing Optimizer Wrappers
def __init__(self, optim):
self.optim = optim
def __getstate__(self):
return self.optim.__getstate__()
def __sets... |
import os
from pytest import fixture
@fixture(scope='function')
def environ(request):
origin = dict(os.environ)
@request.addfinalizer
def restore_environ():
os.environ.clear()
os.environ.update(origin)
return os.environ
|
#!/usr/bin/python3
'''
(C) Copyright 2018-2021 Intel Corporation.
SPDX-License-Identifier: BSD-2-Clause-Patent
'''
from apricot import TestWithServers
from test_utils_pool import TestPool
class DestroyRebuild(TestWithServers):
"""Test class for pool destroy tests.
Test Class Description:
This tes... |
import os
import re
import socket
import ttfw_idf
@ttfw_idf.idf_example_test(env_tag='Example_WIFI_Protocols')
def test_examples_protocol_asio_udp_server(env, extra_data):
"""
steps: |
1. join AP
2. Start server
3. Test connects to server and sends a test message
4. Test evaluates rec... |
# Copyright 2020 - 2021 MONAI Consortium
# 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 wri... |
'''
Problem 017
If the numbers 1 to 5 are written out in words: one, two, three, four, five,
then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total.
If all the numbers from 1 to 1000 (one thousand) inclusive were written out in
words, how many letters would be used?
NOTE: Do not count spaces or hyphens. ... |
import _plotly_utils.basevalidators
class TypesrcValidator(_plotly_utils.basevalidators.SrcValidator):
def __init__(
self, plotly_name="typesrc", parent_name="scattergeo.marker.gradient", **kwargs
):
super(TypesrcValidator, self).__init__(
plotly_name=plotly_name,
paren... |
from dataclasses import dataclass, field
from datetime import datetime
from typing import Optional
from .cloud_provider import CloudProvider
from .instance import Instance
from .instance_status import InstanceStatus
@dataclass
class AwsInstance(Instance):
"""Extends Instance to add fields specific to the AWS com... |
"""Basic PDFs are provided here.
Gauss, exponential... that can be used together with Functors to build larger models.
"""
# Copyright (c) 2021 zfit
import contextlib
import numpy as np
import tensorflow as tf
import zfit.z.numpy as znp
from zfit import z
from ..core.basepdf import BasePDF
from ..core.space impor... |
import os
import math
'''
Metric goal is reached
'''
#Sytem settings
dev_mode = False
grid_data_folder = os.path.join(os.getcwd(), 'raw_data_generation', 'input')
raw_data_folder = os.path.join(os.getcwd(), 'raw_data')
datasets_folder = os.path.join(os.getcwd(), 'datasets')
test_data_folder = os.path.join(os.getcwd()... |
#!/usr/bin/env python3
"""
Check lesson files and their contents.
"""
import os
import glob
import re
from argparse import ArgumentParser
from util import (Reporter, read_markdown, load_yaml, check_unwanted_files,
require)
__version__ = '0.3'
# Where to look for source Markdown files.
SOURCE_DIR... |
# Imports
import torch
from labml_nn.transformers.switch import SwitchTransformer, SwitchTransformerLayer, SwitchFeedForward
from labml_nn.transformers import MultiHeadAttention
from labml_nn.transformers.feed_forward import FeedForward
import numpy as np
from transformers import AutoConfig, AutoModel
import torch.nn a... |
import cv2
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-p2', "--path", help="path to input video")
parser.add_argument('-p1', "--spath", help="path where the images should be stored")
parser.add_argument('-n', "--num", help="number from which image label naming starts", type=int)
args = pars... |
# Copyright 2019 Quantapix 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 l... |
"""A proto buffer based logging system for minitaur experiments.
The logging system records the time since reset, base position, orientation,
angular velocity and motor information (joint angle, speed, and torque) into a
proto buffer. See minitaur_logging.proto for more details. The episode_proto is
updated per time s... |
# -*- coding: utf-8 -*-
from unittest import TestCase
import six
from popolo_data.importer import Popolo
EXAMPLE_AREA = {
"id": "area/tartu_linn",
"identifiers": [
{
"identifier": "Q3032626",
"scheme": "wikidata"
}
],
"name": "Tartu linn",
"other_names": ... |
__author__ = 'alvertisjo'
from django.core.serializers import json
import requests
from requests.packages.urllib3 import Timeout
from requests.packages.urllib3.exceptions import ConnectionError
class OpenProductData(object):
def getData(self):
# rowStep=100
# currentPage=0
# #####document... |
#!/usr/bin/python
import argparse
import subprocess
import sys
from aslc.Semantic import compileString
from aslc.GLSLBackend import GLSLBackend
Backend = GLSLBackend
# Parse the command line
argParser = argparse.ArgumentParser(description="AbstractGPU Shading Language Compiler")
argParser.add_argument('inputFiles',... |
from django.views.generic import TemplateView
class HomePageView(TemplateView):
template_name = "home.html"
|
from . import Simulations
from . import Spacecraft
|
"""
@package: jsonutils
@script: test_JsonUtils.py
@purpose: Test Suite for JsonUtils.
@created: Aug 26, 2017
@author: <B>H</B>ugo <B>S</B>aporetti <B>J</B>unior
@mailto: yorevs@hotmail.com
@site: https://github.com/yorevs/homesetup
@license: Please refer to <https://opensource.org/licenses/MIT>
"... |
import threading
import requests
# encryption
import Encrypt
import unicodedata
from ttk import Style, Button, Label, Entry, Progressbar, Checkbutton
from Tkinter import Tk, Frame, RIGHT, BOTH, RAISED
from Tkinter import TOP, X, N, LEFT
from Tkinter import END, Listbox, MULTIPLE
from Tkinter import Toplevel, DISABLE... |
from pipdeptree import get_installed_distributions, build_dist_index, construct_tree
from bs4 import BeautifulSoup
from json import dump, load
from urllib.request import urlretrieve
from pathlib import Path
from unittest import mock
from pkginfo import SDist
from johnnydep.cli import JohnnyDist
import requests
import ... |
#!/usr/local/bin/python3.6
# Substitute average testing value from optimization
import sys
if len(sys.argv) != 2:
sys.stderr.write('Usage: python3.X %s sy_fraction\n' % sys.argv[0])
raise SystemExit(1)
sy_fraction = sys.argv[1]
parameters = []
with open('input_data/infection_parameters.txt','r') as fin:
paramete... |
""" Simple functions to manipulate strings """
# Replace the functions below with your implementation as described in the assignment
def is_rhyme(word1, word2, k):
"""
Returns True if the last k letters of the two words are the same (case sensitive).
Automatically returns False if either word contains le... |
import sys
if len(sys.argv) != 2:
print("Usage: python3 orgmybmarks.py bookmarks.html")
quit()
file = open(sys.argv[1])
# file = open("in.html")
fileout = open("out.html", "w")
hreflist = []
# 读到第一个链接
numm = 1
while True:
line = file.readline()
if not line:
break
if line.find("HREF") == -1:... |
import main
def test_execute():
count = main.results
assert count == 400410 |
import numpy as np
import os
import sys
import matplotlib.pyplot as plt
import chainconsumer
from math import ceil
# pyburst
from . import mcmc_versions
from . import mcmc_tools
from . import burstfit
from . import mcmc_params
from pyburst.observations import obs_tools
from pyburst.plotting import plot_tools
from pybu... |
import socket
import time
from xmlrpclib_to import ServerProxy
import httpretty
import pytest
XML_RESPONSE = """<?xml version="1.0"?>
<methodResponse>
<params>
<param>
<value><string>Test</string></value>
</param>
</params>
</methodResponse>"""
def timeout(request, url, headers)... |
from django.db.models.signals import m2m_changed
from django.dispatch import receiver
from .models import Image
@receiver(m2m_changed, sender=Image.users_like.through)
def users_like_changed(sender, instance, **kwargs):
instance.total_likes = instance.users_like.count()
instance.save()
|
{
"targets": [
{
"target_name": "binding",
"win_delay_load_hook": "true",
"conditions": [
["target_arch == 'x64' or target_arch == 'ia32'", {
"sources": [
"src/binding.cpp",
"src/BLAKE2/sse/blake2b.c",
"src/BLAKE2/sse/blake2bp.c",
"src/BLAKE2/sse/blake2s.c",
"src/BLAKE... |
import numpy as np
import pandas as pd
import pytest
from pandas.testing import assert_frame_equal
@pytest.fixture
def process_test_df():
"Base DataFrame"
return pd.DataFrame(
{"text": ["a_b_c", "c_d_e", np.nan, "f_g_h"], "numbers": range(1, 5)}
)
@pytest.fixture
def test_returns_dataframe():
... |
from __future__ import division
from sympy import (Abs, Catalan, cos, Derivative, E, EulerGamma, exp,
factorial, factorial2, Function, GoldenRatio, I, Integer, Integral,
Interval, Lambda, Limit, log, Matrix, nan, O, oo, pi, Rational, Float, Rel,
S, sin, SparseMatrix, sqrt, summation, Sum, Symbol, symbols, ... |
# model settings
_base_ = [
'../_base_/datasets/coco_instance.py',
'../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py'
]
model = dict(
type='DSC',
pretrained='torchvision://resnet50',
backbone=dict(
type='ResNet',
depth=50,
num_stages=4,
out_indices=(... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Item',
fields=[
('id', models.AutoField(primary... |
"""This file is needed for editable installs (`pip install -e .`).
Can be removed once the following is resolved
https://github.com/pypa/packaging-problems/issues/256
"""
from setuptools import setup
setup()
|
############### Injector Parameters ##################
#
# config - config file used by the compiler pass
# funcList - list of functions that are faulty
# prob - probability that instuction is faulty
# byte - which byte is faulty (0-7) -1 random
# singleInj - one injection per active rank (0 or 1)
# p... |
def num(a):
num = int(a)
if (num < 10):
return (num + num)
elif (num <100):
return (num + num //10 + num % 10)
elif (num <1000):
return (num + num //100 + ( (num //10) % 10) + num % 10)
else:
return (num + num //1000 + ((num //100) % 10) + ((num //10) % 10) + num %10)
count = list(range(10000... |
# -*- 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
from ccxt.base.errors import ExchangeError
class virwox (Exchange):
def describe(self):
... |
from marshmallow import fields
from .field_set import FieldSet, FieldSetSchema
class Destination(FieldSet):
def __init__(self,
address: str = None,
bytes: int = None,
domain: str = None,
ip: str = None,
mac: str = None,
... |
import nltk.corpus
import nltk.tokenize.punkt
import nltk.stem.snowball
from nltk.corpus import wordnet
import string
paths = nltk.data.path
#if '/var/nltk_data' not in paths:
# nltk.data.path.append("/var/nltk_data");
# if '/mnt/vol1/nltk_data' not in paths:
# nltk.data.path.append("/mnt/vol1/nltk_data");
#nltk.d... |
# Generated by Django 2.2.24 on 2021-08-24 10:53
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('vespawatch', '0052_auto_20210824_1131'),
]
operations = [
migrations.AddField(
model_name='managementaction',
name=... |
# coding: utf-8
"""
InsightVM API
# Overview This guide documents the InsightVM Application Programming Interface (API) Version 3. This API supports the Representation State Transfer (REST) design pattern. Unless noted otherwise this API accepts and produces the `application/json` media type. This API uses ... |
# logcall.py
from functools import wraps
def logged(func):
# Idea: Give me a function, I'll put logging
# around it
print('Adding logging to', func.__name__)
@wraps(func)
def wrapper(*args, **kwargs):
print('You called', func.__name__)
return func(*args, **kwargs)
return wra... |
from sympy.utilities.pytest import XFAIL, raises
from sympy import (S, Symbol, symbols, nan, oo, I, pi, Float, And, Or, Not,
Implies, Xor, zoo, sqrt, Rational, simplify, Function)
from sympy.core.compatibility import range
from sympy.core.relational import (Relational, Equality, Unequality,
... |
from flask import Flask, Response
from camera import Camera
import cv2
app = Flask(__name__)
camera = Camera().start()
def gen(camera):
while True:
frame = camera.read()
_, jpeg = cv2.imencode('.jpg', frame)
yield (b'--frame\r\n'
b'Content-Type: image/jpeg\r\n\r\n' + jpeg.... |
from glob import glob
from setuptools import setup
from pybind11.setup_helpers import Pybind11Extension
ext_modules = [
Pybind11Extension(
"PFlib",
# sorted(glob("*.cpp")), # Sort source files for reproducibility
["particle_filter.cpp",],
swig_opts=['-ggdb',],
include_dirs=... |
from sklearn import svm, cluster
from PIL import Image, ImageDraw
import os
import sys
import random
def load_images(dirname):
images = []
for image_name in os.listdir(dirname):
if image_name.startswith('.'):
continue
image = Image.open(dirname + '/' + image_name).convert('1')
x, y = image.size
image = ... |
import logging
import os
import re
import xml.etree.ElementTree as ET
from pathlib import Path
from typing import Any, Tuple, Optional
import pandas as pd
from python import TOPIC_ID, SUBTOPIC, DOCUMENT_NUMBER, DOCUMENT_ID, SENTENCE_IDX, TOKEN_IDX, TOKEN_IDX_TO, \
TOKEN_IDX_FROM, TOKEN, MENTION_ID, EVENT, MENTION... |
"""
Django settings for simplesocial project.
Generated by 'django-admin startproject' using Django 2.0.5.
For more information on this file, see
https://docs.djangoproject.com/en/2.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.0/ref/settings/
"""
import ... |
#!/usr/bin/env python
#coding: utf-8
import sys
from common import reverse_items
if len(sys.argv) != 3:
print("Reverse key and value of all pairs")
print(("Usage: ", sys.argv[0], "[input] [output]"))
exit(1)
reverse_items(sys.argv[1], sys.argv[2])
|
# Copyright (C) 2015-2016 Regents of the University of California
#
# 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 app... |
# mypy: allow-untyped-defs
from unittest import mock
import pytest
from tools.ci.tc import decision
@pytest.mark.parametrize("run_jobs,tasks,expected", [
([], {"task-no-schedule-if": {}}, ["task-no-schedule-if"]),
([], {"task-schedule-if-no-run-job": {"schedule-if": {}}}, []),
(["job"],
{"job-pres... |
"""
Main inputs:
(Change for all fields)
"""
eazypath = '/data2/ken/photoz/eazy-photoz/src/eazy '
working_folder = '/data2/ken/EN1_pani'
photometry_catalog = 'en1_phot_with_zspec.fits'
photometry_format = 'fits'
filter_file = 'EN1_filters.res'
translate_file = 'EN1.translate'
zspec_col = 'z_spec'
flux_col = 'flux'
... |
from bfstpw.models import ForumThread, ForumPost
from datetime import datetime
from django.conf import settings
from django.core.paginator import Paginator
from django.core.urlresolvers import reverse
from django.db.models import Count
from django.http import HttpResponseRedirect
from django.shortcuts import render, ge... |
from lib.utils.util import *
from timm.models.efficientnet_blocks import *
# ChildNet Builder definition.
class ChildNetBuilder:
def __init__(
self,
channel_multiplier=1.0,
channel_divisor=8,
channel_min=None,
output_stride=32,
pad_type='',
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.