text stringlengths 2 999k |
|---|
# coding=utf-8
# Copyright 2021 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... |
"""Support for non-delivered packages recorded in AfterShip."""
from __future__ import annotations
import logging
from typing import Any, Final
from pyaftership.tracker import Tracking
import voluptuous as vol
from homeassistant.components.sensor import (
PLATFORM_SCHEMA as BASE_PLATFORM_SCHEMA,
SensorEntity... |
"""plot_neighbourhoods.py
Plot the neighbourhoods of all classes for the city specified as an input with the following color codes
* Black: where the class is over-represented (with 99% CI)
* Light grey: where the class is 'normally' represented
* White: where the class is under-represented
"""
import sys
import math
... |
"""Main App for API"""
from django.apps import AppConfig
class ApiConfig(AppConfig):
"""API Config"""
default_auto_field = 'django.db.models.BigAutoField'
name = 'api'
|
from enum import Enum
class Network(str, Enum):
Ethereum = "ethereum"
Polygon = "polygon"
Arbitrum = "arbitrum"
BinanceSmartChain = "binancesmartchain"
Avalanche = "avalanche"
Fantom = "fantom"
xDai = "xdai"
def __str__(self):
return self.value
class Currency(str, Enum):
... |
#
# Copyright (c) 2008-2015 Citrix Systems, 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 l... |
#!/usr/bin/env python
r"""
This module provides robot keyword execution functions such as run_key..
"""
import gen_print as gp
from robot.libraries.BuiltIn import BuiltIn
###############################################################################
def run_key(keyword_buf,
quiet=None,
test... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('reddit', '0041_auto_20160708_0601'),
... |
# --------------
import pandas as pd
from sklearn.model_selection import train_test_split
df = pd.read_csv(path)
print(df.head())
print(df.info())
columns = ["INCOME", "HOME_VAL",'BLUEBOOK','OLDCLAIM','CLM_AMT']
for col in columns:
df[col] = df[col].map(lambda x: str(x).replace("$","").replace(",",""))
X = df.dro... |
"""
Mask R-CNN
Train on the toy Balloon dataset and implement color splash effect.
Copyright (c) 2018 Matterport, Inc.
Licensed under the MIT License (see LICENSE for details)
Written by Waleed Abdulla
------------------------------------------------------------
Usage: import the module (see Jupyter notebooks for ex... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from sceptre import __version__
from setuptools import setup, find_packages
from os import path
with open("README.md") as readme_file:
readme = readme_file.read()
with open("CHANGELOG.md") as history_file:
history = history_file.read()
install_requirements = [
... |
import github3
from unittest import TestCase
from mock import patch, NonCallableMock
class TestAPI(TestCase):
def setUp(self):
self.mock = patch('github3.api.gh', autospec=github3.GitHub)
self.gh = self.mock.start()
def tearDown(self):
self.mock.stop()
def test_authorize(self):
... |
# import the necessary packages
import argparse
import imutils
import cv2
class ShapeDetector:
def __init__(self):
pass
def detect(self, c):
# initialize the shape name and approximate the contour
shape = "unidentified"
peri = cv2.arcLength(c, True)
approx = cv2.approx... |
# -*- coding: utf-8 -*-
u"""elegant lattice parser.
:copyright: Copyright (c) 2015 RadiaSoft LLC. All Rights Reserved.
:license: http://www.apache.org/licenses/LICENSE-2.0.html
"""
from __future__ import absolute_import, division, print_function
import re
from sirepo.template.line_parser import LineParser
# a map o... |
#### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Intangible()
result.template = "object/draft_schematic/chemistry/shared_medpack_disease_strength_a.iff"
result.at... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Execut Context Module."""
import math
from typing import Any, Dict, Optional, TYPE_CHECKING
from pyppeteer import helper
from pyppeteer.connection import CDPSession
from pyppeteer.errors import ElementHandleError, NetworkError
if TYPE_CHECKING:
from pyppeteer.el... |
# 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 applicable ... |
import platform
import os.path
import subprocess # nosec - see usage below
from django.conf import settings
from django.core.management.base import BaseCommand, CommandError
BIN_PATH = (
'http://download.gna.org', 'wkhtmltopdf', '0.12', '0.12.3',
'wkhtmltox-0.12.3_linux-generic-amd64.tar.xz',
)
class Com... |
import subprocess
import time
from priorityqueue import *
def leerEntrada():
FORMATO = {'0': 0, '1': 1, 'I': 2, 'X': 3} #Mover esto a una funcion duplica el tiempo total de leerEntrada()
inicio, final = (0, 0), (0, 0)
with open("./salida_intermedia.txt", "r") as entrada:
mapa = [[FORMATO[char] ... |
from .param_space_optimizer import ParameterSpaceOptimizer
from typing import Tuple, Dict, List
import pandas as pd
def _ternary_search(func, left, right, absolute_precision, debug=False):
"""
taken from wikipedia article on ternary search
"""
while True:
if abs(right - left) < absolute_pr... |
from abc import abstractmethod
from typing import List
from selenium.webdriver.chrome.webdriver import WebDriver
from .deafults import default_driver, default_store_path
from .Event import Event
class Source:
"""Abstract class used as super class and to create custom sources classes
Paramaters
---------... |
with open('hopedale.txt', 'r') as hopedale_file:
# Read and skip the description line.
hopedale_file.readline()
# Keep reading and skipping comment lines until we read the first piece
# of data.
data = hopedale_file.readline().strip()
while data.startswith('#'):
data = hopedale_file.read... |
#
# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
# its licensors.
#
# For complete copyright and license terms please see the LICENSE at the root of this
# distribution (the "License"). All use of this software is governed by the License,
# or, if provided, by the license below or th... |
# 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 ... |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: protobufs/services/team/actions/get_team.proto
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as ... |
import tensorflow as tf
from ocnn import *
class AutoEncoderOcnn:
def __init__(self, flags):
self.flags = flags
def octree_encoder(self, octree, training, reuse=False):
debug_checks = {}
flags = self.flags
depth, nout = flags.depth, flags.nout
channel = [4, nout, 128, 64, 32, 16, 8]
wit... |
import pytest
import nvme as d
import time
import logging
TEST_SCALE = 10 #1, 10
# trim
@pytest.mark.parametrize("repeat", range(TEST_SCALE))
@pytest.mark.parametrize("lba_count", [8, 8*1024, 0]) # 4K, 4M, all
def test_trim_time_one_range(nvme0, nvme0n1, lba_count, repeat, qpair):
buf = d.Buffer(4096)
... |
# -*- coding: utf-8 -*-
import functools
import httplib as http
from furl import furl
from flask import request
from framework import status
from framework.auth import Auth, cas
from framework.flask import redirect # VOL-aware redirect
from framework.exceptions import HTTPError
from framework.auth.decorators import ... |
import os
import KratosMultiphysics
from KratosMultiphysics import Logger
Logger.GetDefaultOutput().SetSeverity(Logger.Severity.WARNING)
import KratosMultiphysics.DEMApplication as DEM
import KratosMultiphysics.KratosUnittest as KratosUnittest
from KratosMultiphysics.DEMApplication.DEM_analysis_stage import DEMAnalysis... |
'''
Contains code for working with the Inference Engine.
You'll learn how to implement this code and more in
the related lesson on the topic.
'''
import os
import sys
import logging as log
from openvino.inference_engine import IENetwork, IECore
class Network:
'''
Load and store information for working with th... |
#!/usr/bin/env python
#
# Copyright 2020 Espressif Systems (Shanghai) PTE 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 req... |
import torch
from torch.distributions.uniform import Uniform
from torch.distributions.utils import broadcast_all
from torch.distributions.kl import register_kl, kl_divergence
import torch.nn.functional as F
EPS = 1e-5
class MixtureD0C01(torch.distributions.Distribution):
def __init__(self, logits0, cont, v... |
# Import modules
from os.path import join as opj
from nipype.interfaces.ants import Registration
from nipype.interfaces.utility import IdentityInterface
from nipype.interfaces.io import SelectFiles, DataSink
from nipype import Workflow, Node
from nipype.interfaces.fsl import Info
# Specify variables
experiment_dir = '... |
from utils import *
__author__ = 'kq'
def normalize_game_count(data: pd.DataFrame) -> Dict[str, float]:
"""
Normalization of game count to account for variance in sample size
:param data:
:return:
"""
counter = data.groupby(SPORT).date.count()
return 1 / (counter / counter.max())
def lo... |
"""
US Holidays
Many historical holidays were derived from the pdf at
etc/NYSE-Historical-Closings.pdf. Originally posted at
http://s3.amazonaws.com/armstrongeconomics-wp/2013/07/NYSE-Closings.pdf # noqa
These were originally added in
https://github.com/rsheftel/pandas_market_calendars/pull/30
"""
from dateutil.rel... |
# Copyright 2022 Google
#
# 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 writing, soft... |
# -*- coding: utf-8 -*-
__author__ = ["Junhao Wen", "Jorge Samper-Gonzalez"]
__copyright__ = "Copyright 2016-2018 The Aramis Lab Team"
__credits__ = ["Junhao Wen"]
__license__ = "See LICENSE.txt file"
__version__ = "0.1.0"
__status__ = "Development"
import os
from os import path
import json
import numpy as np
import p... |
# Copyright 2019 kkAyataka
#
# Distributed under the MIT License.
# https://opensource.org/licenses/MIT
import calmet_db
def metrics_cmd(args):
# args
mettype = args.type
year = args.year
# initialize
db = calmet_db.CalMetDB()
db.open()
if mettype == 'week':
metrics = db.get_per_... |
__version__ = "1.13.4"
|
#!/usr/bin/env python3
"""
Model representation of a docXRefSectType from doxygen
<xsd:complexType name="docXRefSectType">
<xsd:sequence>
<xsd:element name="xreftitle" type="xsd:string" minOccurs="0" maxOccurs="unbounded" />
<xsd:element name="xrefdescription" type="descriptionType" />
</xsd:sequence>
<x... |
"""
This file offers the methods to automatically retrieve the graph Streptococcus sp. ACC21.
The graph is automatically retrieved from the STRING repository.
Report
---------------------
At the time of rendering these methods (please see datetime below), the graph
had the following characteristics:
Datetime: 202... |
import tkinter as tk
root = tk.Tk()
root.title('.config()')
root.geometry('350x150')
lb = tk.Label()
lb['text'] = 'ラベル'
print(lb.config())
root.mainloop()
|
'''Gradient penalty functions.
'''
import torch
from torch import autograd
def contrastive_gradient_penalty(network, input, penalty_amount=1.):
"""Contrastive gradient penalty.
This is essentially the loss introduced by Mescheder et al 2018.
Args:
network: Network to apply penalty through.
... |
import cadquery
from cadquery import BoxSelector
from math import pi, cos, sqrt
from cqparts.params import *
from .base import ScrewDrive, register
class AcentricWedgesScrewDrive(ScrewDrive):
count = IntRange(1, None, 4)
width = PositiveFloat(0.5)
acentric_radius = PositiveFloat(None) # defaults to wid... |
"""Módulo dos formulários relativos aos usuários da aplicação."""
from flask_ckeditor import CKEditorField
from flask_wtf import FlaskForm
from flask_wtf.file import FileField
from wtforms import BooleanField, EmailField, PasswordField, StringField, SubmitField
from wtforms.validators import DataRequired, EqualTo, Len... |
#!/usr/bin/python
'''
Add this to ~/.lldbinit
command script import ~/.lldb/block.py
'''
import lldb
import commands
import shlex
import optparse
def __lldb_init_module (debugger, dict):
debugger.HandleCommand('command script add -f block.block_disass_command block_disass')
print 'The "block_disass" command has be... |
from django.urls import path
from api.fill_database import fill_wassit, fill_models, fill_documents, historicalDict, fill_dicos
from api.fill_database import fill_maany
from api.serializers import MeaningAppearsSerializer
from . import process
from django.conf.urls import url, include
from django.contrib.auth.models ... |
######################################################################
#
# File: b2sdk/v1/bucket.py
#
# Copyright 2021 Backblaze Inc. All Rights Reserved.
#
# License https://www.backblaze.com/using_b2_code.html
#
######################################################################
from .download_dest import Abstrac... |
"""@file galaxycluster.py
The GalaxyCluster class
"""
import pickle
import warnings
from .gcdata import GCData
from .dataops import compute_tangential_and_cross_components, make_radial_profile
from .theory import compute_critical_surface_density
from .plotting import plot_profiles
class GalaxyCluster():
"""Object... |
# Copyright 2017-2020 TensorHub, 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 writ... |
# Generated by Django 2.2.13 on 2021-02-12 05:00
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('picha', '0001_initial'),
]
operations = [
migrations.RenameModel(
old_name='Picha',
new_name='Picture',
),
]
|
class Solution:
# my solution
def prefixesDivBy5(self, A: List[int]) -> List[bool]:
res = []
tmp = 0
for n in A:
tmp = tmp * 2 + n
res.append(tmp % 5 == 0)
return res
# faster solution
# https://leetcode.com/problems/bina... |
import tsbenchmark as tsb
import tsbenchmark.api
def main():
task = tsb.api.get_task()
# task = tsb.api.get_local_task(data_path='/home/newbei/code/DAT/TSBenchmark/tsbenchmark/datas2',
# dataset_id=890686, random_state=9527, max_trails=1, reward_metric='rmse')
from hypert... |
class Solution:
def findMedianSortedArrays(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: float
"""
m, n = len(nums1), len(nums2)
if m > n:
nums1, nums2, m, n = nums2, nums1, n, m
imin, imax, half_len = 0, m... |
# encoding: utf-8
"""
@author: liaoxingyu
@contact: sherlockliao01@gmail.com
"""
import torch
import torch.nn.functional as F
from fastreid.utils import comm
from fastreid.layers import GatherLayer
from .utils import concat_all_gather, euclidean_dist, normalize
def softmax_weights(dist, mask):
max_v = torch.ma... |
# DRUNKWATER TEMPLATE(add description and prototypes)
# Question Title and Description on leetcode.com
# Function Declaration and Function Prototypes on leetcode.com
#762. Prime Number of Set Bits in Binary Representation
#Given two integers L and R, find the count of numbers in the range [L, R] (inclusive) having a pr... |
""" Functions for file writing."""
import os
import netCDF4
from cloudnetpy import utils, version
from cloudnetpy.metadata import COMMON_ATTRIBUTES
from cloudnetpy.products import product_tools
def update_attributes(cloudnet_variables, attributes):
"""Overrides existing CloudnetArray-attributes.
Overrides ex... |
import json
import torch
from core.utils import download_ckpt
def model_zoo(name, zoo_path="configs/model_zoo.json"):
zoo = json.load(open(zoo_path))
if name in zoo:
ckpt = download_ckpt(**zoo[name])
else:
ckpt = torch.load(name, map_location="cpu")
return ckpt
|
from SudokuSolver.Logger import Logger, LOGLEVEL
from SudokuSolver.SudokuBoard import SudokuBoard
import numpy as np
class SudokuSolver(object):
logger: Logger
board: SudokuBoard
def log(self,string):
"""
Logger
Parameters
----------
string
Returns
... |
import unittest
from ddt import ddt
from ddt import file_data
from google_analytics_pipeline.core.enrichment.utm import UTMParamsEnrichmentFn
@ddt
class TestUTMEnrichment(unittest.TestCase):
def setUp(self):
self.maxDiff = None
self.test_fn = UTMParamsEnrichmentFn().process
@file_data("../... |
# pylint: disable=invalid-name,no-self-use,protected-access
from collections import namedtuple
import os
import pytest
from flaky import flaky
from numpy.testing import assert_almost_equal
import torch
from allennlp.common.testing import ModelTestCase
from allennlp.training.metrics.wikitables_accuracy import SEMPRE_A... |
from datetime import datetime, timezone
class ScanResult:
def __init__(self, target_data, config):
self.result = {
"ip": target_data['target'],
"scan_reason": target_data["scan_reason"],
"tags": target_data["tags"],
"scan_id": target_data["scan_id"],
"agent_version": config.NATLAS_VERSION,
"agen... |
import unittest
import ujson
from nanohttp import context, json, text, RestController, configure
from nanohttp.contexts import Context
from restfulpy.controllers import JsonPatchControllerMixin
class BiscuitsController(RestController):
@json
def put(self, id_: int = None):
result = {}
result... |
import datetime
from walrus.tests.base import WalrusTestCase
from walrus.tests.base import db
cache = db.cache(name='test.cache')
@cache.cached(timeout=60)
def now(seed=None):
return datetime.datetime.now()
class Clock(object):
@cache.cached_property()
def now(self):
return datetime.datetime.... |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... |
"""Hook abstract class entity."""
from abc import ABC, abstractmethod
from pyspark.sql import DataFrame
class Hook(ABC):
"""Definition of a hook function to call on a Dataframe."""
@abstractmethod
def run(self, dataframe: DataFrame) -> DataFrame:
"""Run interface for Hook.
Args:
... |
# Generated by Django 2.0.5 on 2018-06-17 02:55
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='AdminNotified',
fields=[
... |
#!/usr/bin/env python
import sys
import os
module_dir = os.path.dirname(os.path.realpath(__file__))
module_dir += '/modules'
sys.path.append(module_dir)
import exodus
database_path = "baseline.g"
#Test outputing c-type arrays and numpy arrays
array_types = ['ctype', 'numpy']
for array_type in array_types:
e = exo... |
# -*- coding: utf-8 -*- {{{
# vim: set fenc=utf-8 ft=python sw=4 ts=4 sts=4 et:
#
# Copyright 2020, Battelle Memorial Institute.
#
# 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... |
# Generated by Django 3.2.5 on 2022-01-06 20:58
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('origins', '0083_alter_nomen_taxon_rank_group'),
]
operations = [
migrations.RenameField(
model_name='nomen',
old_name='type_... |
# Copyright 2008-2010, 2012-2014, 2016-2017 by Peter Cock. All rights reserved.
#
# This file is part of the Biopython distribution and governed by your
# choice of the "Biopython License Agreement" or the "BSD 3-Clause License".
# Please see the LICENSE file that should have been included as part of this
# package.
"... |
# -*- coding: utf-8 -*-
from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import pre_delete
from django.contrib.sessions.models import Session
from mathics.core.definitions import Definitions, autoload_files
from mathics.core.evaluation import Evaluation, Output
f... |
from theseus.registry import Registry
def get_instance(config, registry: Registry, **kwargs):
# ref https://github.com/vltanh/torchan/blob/master/torchan/utils/getter.py
assert "name" in config
config.setdefault("args", {})
if config.get("args", None) is None:
config["args"] = {}
return r... |
# Copyright 2018 The MACE 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... |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
import numpy as np
class HumanBody(object):
def __init__(self):
self.skeleton = self.get_skeleton()
self.skeleton_sorted_by_level = self.sort_skeleton_by_level(
self.skeleton)
self.imu_edges = self.get_i... |
import platform
import pytest
import dartpy as dart
import numpy as np
def collision_groups_tester(cd):
size = [1, 1, 1]
pos1 = [0, 0, 0]
pos2 = [0.5, 0, 0]
simple_frame1 = dart.dynamics.SimpleFrame()
simple_frame2 = dart.dynamics.SimpleFrame()
sphere1 = dart.dynamics.SphereShape(1)
sphe... |
# By Sam the Great from forums
# That freaking superhero has been frequenting Udacity
# as his favorite boss battle fight stage. The 'Udacity'
# banner keeps breaking, and money is being wasted on
# repairs. This time, we need you to proceduralize the
# fixing process by building a machine to automatically
# search thr... |
# -*- coding: utf-8 -*-
#
# social_media_analytics documentation build configuration file, created by
# sphinx-quickstart.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuratio... |
"""W&B rich data types like Image, Audio, etc. and JSON conversion functions.
A lot of functions take a "key" parameter. These are the dot-separated
Summary/History keys that we use on the front end.
Many also take a "step" parameter. These should be integer step numbers for
values saved in History and the string "su... |
from __future__ import print_function
import os
import sys
import boto3
import configargparse
import requests
# -----------------------------------------------------------------------------
# Process
# -----------------------------------------------------------------------------
def verify_file(options):
path,... |
#!/usr/bin/env python3
import argparse
import gzip
import json
import logging
from pathlib import Path
import tqdm
from . import site, utils
from .case import Case
def fetch_diffs(case_dir: Path, rev_dir: Path):
case = Case.load(case_dir)
logging.info('fetching case diffs...')
revids = [
(page.... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import sys
import six
import pytest
from _pytest.mark import EMPTY_PARAMETERSET_OPTION
from _pytest.mark import MarkGenerator as Mark
from _pytest.nodes import Collector
from _pytest.nodes import No... |
# -*- coding: utf-8 -*-
# Define here the models for your spider middleware
#
# See documentation in:
# http://doc.scrapy.org/en/latest/topics/spider-middleware.html
from scrapy import signals
class RedditCrawlerSpiderMiddleware(object):
# Not all methods need to be defined. If a method is not defined,
# sc... |
# Copyright (c) 2015 Red Hat, Inc.
# Copyright (c) 2015 SUSE Linux Products GmbH
# 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.... |
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
Commands for telling a worker to load tests or run tests.
@since: 12.3
"""
from twisted.protocols.amp import Boolean, Command, Unicode
NativeString = Unicode
class Run(Command):
"""
Run a test.
"""
arguments = [(b"testCas... |
# coding: utf-8
import re
import six
from huaweicloudsdkcore.utils.http_utils import sanitize_for_serialization
class ListProductsRequest:
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The ke... |
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.utils.translation import ugettext as _
from guardian.admin import GuardedModelAdmin
from userena.models import UserenaSignup
from userena.utils import get_profile_model
class UserenaSignupInline(admin.StackedInline):
mode... |
r'''
The Dual Arrhenius Michaelis-Menten (DAMM) soil decomposition model (from
Davidson et al. 2012).
$$
R_H = V_{\mathrm{max}}\, \frac{S_X}{K_{M_S} + S_X} \frac{O_2}{K_{M_{O_2}} + O_2}
$$
NOTE: The only term in the equation that is not unitless (either intrinsically
or because the units cancel out) is `V_max`; there... |
import os
import random
import time
from flask import Flask, request, render_template, session, flash, redirect, \
url_for, jsonify
from flask_restful import Api, Resource
app = Flask(__name__)
class Hello(Resource):
def get(self):
return jsonify({'hello': 'docker cloud'})
api = Api(app)
api.add_... |
import numpy as np
import matplotlib.pyplot as plt
from pprint import pprint
import matplotlib.patches
def massplotrc():
## tex
plt.rcParams['text.usetex'] = True
plt.rcParams['font.family'] = 'serif'
plt.rcParams['font.serif'] = []
plt.rcParams['text.latex.preamble'] = []
## rc
plt.rcParams['font.size'] = 7
... |
# -*- coding: utf-8 -*-
import os
from urllib.parse import quote_plus, urlencode
from plexapi import media, utils
from plexapi.base import Playable, PlexPartialObject
from plexapi.exceptions import BadRequest, NotFound
class Video(PlexPartialObject):
""" Base class for all video objects including :class:`~plexap... |
# coding: utf-8
from typing import List
from pydantic import BaseModel
from .link_item import LinkItem
from .link_data_class import LinkDataClass
class LinkData(BaseModel):
modules: List[LinkItem]
enums: List[LinkItem]
constants: List[LinkItem]
typedef: List[LinkItem]
classes: LinkDataClass
|
#!c:\users\gaurav\desktop\projects\url_shortening_service\scripts\python.exe
from django.core import management
if __name__ == "__main__":
management.execute_from_command_line()
|
import ffmpeg
import cv2
import uuid
import os
import base64
import numpy as np
def save_video_to_file(file, vid, fps):
writer = cv2.VideoWriter(file.name, cv2.VideoWriter_fourcc('M','J','P','G'), fps, (vid.shape[2], vid.shape[1]))
for img in vid:
writer.write(np.flip(img, axis=2))
writer.release(... |
from itertools import chain, combinations, compress, groupby, product
from math import comb
from typing import List, Optional
import numpy as np
from pymatgen.analysis.interface_reactions import InterfacialReactivity
from pymatgen.analysis.phase_diagram import GrandPotentialPhaseDiagram, PhaseDiagram
from pymatgen.cor... |
""""
Modified by Harrison McCarty - Autonomous Robotics Club of Purdue
Copyright © Krypton 2021 - https://github.com/kkrypt0nn
Description:
"""
import json
import os
import platform
import random
import sys
import discord
from discord.ext import commands, tasks
from discord.ext.commands import Bot
if not os.path.isf... |
from contextlib import contextmanager
from distutils.sysconfig import get_config_var
from io import open as io_open
import os
from os.path import join, exists
import shutil
import sys
import tempfile
from textwrap import dedent
from multiprocessing import Pool
from unittest import TestCase, main
try:
from unittest... |
__version__ = '0.0.6'
from wavencoder.models.wav2vec import Wav2Vec
from wavencoder.models.wav2vec2 import Wav2Vec2
from wavencoder.models.sincnet import SincNet, SincConvLayer
from wavencoder.models.lstm_classifier import LSTM_Classifier
from wavencoder.models.lstm_classifier import LSTM_Attn_Classifier
from wavenc... |
# base generator with common functionality
import re
from pseudo.pseudo_tree import Node
from pseudo.code_generator_dsl import Placeholder, Newline, Action, Function, SubTemplate, SubElement, PseudoType, Whitespace, Offset, INTERNAL_WHITESPACE, NEWLINE
from pseudo.middlewares import AugAssignmentMiddleware
LINE_FIRS = ... |
"""Auto-generated file, do not edit by hand. GY metadata"""
from ..phonemetadata import NumberFormat, PhoneNumberDesc, PhoneMetadata
PHONE_METADATA_GY = PhoneMetadata(id='GY', country_code=592, international_prefix='001',
general_desc=PhoneNumberDesc(national_number_pattern='[2-46-9]\\d{6}', possible_length=(7... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.