text stringlengths 2 999k |
|---|
"""Backend URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based... |
# django imports
from django.db import models
from django.contrib.auth.models import User
from django.contrib.auth.models import Group
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.utils.translation import ugettext_lazy as _
# pe... |
from ..entity import (
EntitySchema,
SecondaryEntity,
)
from ..fields import (
ListField,
StringField,
EntityField,
)
from ..secondary.related_judgement import RelatedJudgement
from ..validators import validate_string
class JudgementSpecificationSchema(EntitySchema):
"""
https://github.com... |
from pysys.basetest import BaseTest
import time
import json
"""
Validate collectd-mapper messages that are published
on tedge/measurements
Given a configured system
When we start the collectd-mapper with sudo in the background
When we start tedge sub with sudo in the background
When we start two publishers to publi... |
from __future__ import absolute_import
try:
from io import BytesIO
except ImportError:
from StringIO import StringIO as BytesIO
import qrcode
from reportlab.platypus.flowables import Image
from ..styles import styles
def qrcode_image(data):
# create QRCode object
code = qrcode.QRCode(
b... |
# Copyright 2019 Nokia
# Copyright 2020 ENEA
#
# 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... |
# Implementation based on Tensorflow Keras and Haiku
# Tensorflow: https://github.com/tensorflow/tensorflow/blob/v2.2.0/tensorflow/python/keras/layers/core.py#L127-L224
# Haiku: https://github.com/deepmind/dm-haiku/blob/master/haiku/_src/basic.py#L293#L315
import typing as tp
import haiku as hk
import jax.numpy as jn... |
from lib.common import helpers
import base64
class Module:
def __init__(self, mainMenu, params=[]):
self.info = {
'Name': 'ListDirectory',
'Author': ['@harmj0y'],
'Description': ('ls'),
'Background' : False,
'OutputExtension' : None,
... |
# 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... |
import os
import pytest
import sys
import ray
import pathlib
import json
import time
from dataclasses import asdict
from pathlib import Path
from jsonschema import validate
import ray._private.usage.usage_lib as ray_usage_lib
import ray._private.usage.usage_constants as usage_constants
from ray._private.usage.usage_l... |
import sys
if not "tinypy" in sys.version:
from boot import *
import tokenize,parse,encode
def _compile(s,fname):
tokens = tokenize.tokenize(s)
t = parse.parse(s,tokens)
r = encode.encode(fname,s,t)
return r
def _import(name):
if name in MODULES:
return MODULES[name]
py = name+".p... |
from abc import ABCMeta, abstractmethod
from typing import (
TYPE_CHECKING,
Any,
Dict,
List,
NamedTuple,
NewType,
Optional,
Sequence,
Tuple,
TypeVar,
Union,
)
from pydantic import BaseModel
if TYPE_CHECKING:
from splitgraph.cloud.models import ExternalTableRequest
Chan... |
# MIT License
#
# Copyright (C) IBM Corporation 2019
#
# 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, merge... |
"""
Fastberry Main (Core-Methods)
"""
from starlette.middleware.base import BaseHTTPMiddleware as BaseMiddleware
from strawberry.extensions import Extension as BaseExtension
from strawberry.permission import BasePermission
from . import config
# from .config import Settings
from .config import Settings as Fastbe... |
#!/usr/bin/env python3
import hashlib
import base58
import binascii
#BC = KMD
#80 = BTC
#A6 = GAME
#B0 = EMC2
#C6 = GIN
#B0 = AYA
#3A = TCL
#B0 = LTC
prefixList = ['KMD', 'BC', 'BTC', '80', 'GAME', 'A6', 'EMC2', 'B0',
'GIN', 'C6', 'AYA', 'B0', 'TCL', '3A', 'LTC', 'B0']
private_key_WIF = input('Enter WIF... |
from openeo_udf.api.datacube import DataCube
from openeo_udf.api.udf_data import UdfData
from typing import Dict, Callable
import xarray
import numpy
import pandas
from pandas import Series
def apply_timeseries(series: Series, context:Dict)->Series:
"""
Do something with the timeseries
:param series:
... |
"""
Just to test database functions,
outside of Flask.
We want to open our MongoDB database,
insert some memos, and read them back
"""
import arrow
# Mongo database
from pymongo import MongoClient
import CONFIG
try:
dbclient = MongoClient(CONFIG.MONGO_URL)
db = dbclient.busytimes
collection = db.dated
e... |
s = set([1,2,3])
print(s)
s.discard(2)
print(s)
s.discard(4)
print(s)
|
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# Copyright (c) "Neo4j"
# Neo4j Sweden AB [http://neo4j.com]
#
# This file is part of Neo4j.
#
# 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
#... |
"""
DNS TXT Fingerprinting of Online Vendor verification string
This is an example on how you can use the fingerprint JSON
file to enable detecting txt strings in your own code, you
don't need to use Redjoust to get that functionality etc.
The JSON file is however maintained by Redjoust for Redjoust
But how you use i... |
"""
topojson - a powerful library to encode geographic data as topology in Python!🌍
===============================================================================
**topojson** is a Python package with the aim of creating TopoJSON topology.
Main Features
-------------
- Aims to create TopoJSON for _any_ geographic ... |
"""
datass submodule for handling pandas.DataFrame objects
"""
|
import argparse
import os
from liquidcss.workspace import WorkSpace
from liquidcss.settings import Settings, Messages
from liquidcss.utils import display_output
"""
Command: liquidcss init
Description:
Initializes the WorkSpace.
Optional Arguments:
[--reset -r] : Resets the WorkSpace.
[--hard, -hr] : Re... |
try:
from gmpy2 import is_strong_prp
except ImportError:
is_strong_prp = None
def odd_primes_below_n(n):
""" Returns a list of odd primes less than n. """
sieve = [True] * (n // 2)
for i in range(3, int(n ** 0.5) + 1, 2):
if sieve[i // 2]:
sieve[i * i // 2::i] = [False] * ((n-i... |
# Copyright 2019-2020 Josh Pieper, jjp@pobox.com.
#
# 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 a... |
# flake8: noqa
corr = signal.correlate(
alien_signal,
signal.boxcar(sample_length),
mode='same'
) / sample_length # divide by sample length to normalize output
# plot stuff
plt.figure()
plt.plot(corr)
plt.plot(clock, corr[clock], 'ro')
plt.axhline(0.5, ls='--', color='gray')
# decode the aline message
a... |
from rest_framework import authentication, permissions
from rest_framework.mixins import ListModelMixin
from rest_framework.viewsets import GenericViewSet
from .serializers import OrderSerializer
from .models import Order
from .mixins import OrdersMixin
class OrderView(GenericViewSet, OrdersMixin, ListModelMixin):
... |
# Copyright 2019 RedLotus <ssfdust@gmail.com>
# Author: RedLotus <ssfdust@gmail.com>
#
# 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
#
# Unles... |
from unittest.mock import MagicMock, patch
import pytest
import prefect
from prefect.client import Client
from prefect.engine.result_handlers import (
AzureResultHandler,
GCSResultHandler,
JSONResultHandler,
LocalResultHandler,
ResultHandler,
S3ResultHandler,
)
from prefect.serialization.resul... |
"""
============================
Simple Differential Rotation
============================
The Sun is known to rotate differentially, meaning that the rotation rate
near the poles (rotation period of approximately 35 days) is not the same as
the rotation rate near the equator (rotation period of approximately 25 days)... |
#!/usr/bin/python
from __future__ import (absolute_import, division, print_function)
# Copyright 2019-2020 Fortinet, Inc.
#
# 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 3 of th... |
class Solution:
def finalPrices(self, A: List[int]) -> List[int]:
# for i in range(len(prices)):
# for j in range(i+1, len(prices)):
# if prices[j]<=prices[i]:
# prices[i] -= prices[j]
# break
# return prices
stack = []
... |
from dnnv.properties import *
import numpy as np
N1 = Network("N1")
N2 = Network("N2")
x = Image(__path__.parent / "input_7.npy")
epsilon = Parameter("epsilon", type=float)
true_class = 8
other_class = 5
Forall(
x_,
Implies(
((x - epsilon) < x_ < (x + epsilon)) & (0 <= x_ <= 1),
And(
... |
"""Functionality for aligning protein sequences in ProteinNet vs SidechainNet."""
import numpy as np
from Bio import Align
from sidechainnet.structure.build_info import NUM_COORDS_PER_RES, PRODY_CA_DIST
from sidechainnet.utils.download import ASTRAL_ID_MAPPING, determine_pnid_type
from sidechainnet.utils.measure impo... |
'''
Created on Mar 8, 2016
@author: PJ
'''
from BaseScouting.api_scraper_FIRST.PopulateResultsFromApi import PopulateRegionalResults
class PopulateRegionalResults2015(PopulateRegionalResults):
def __init__(self):
from Scouting2015.model import Team, Competition, OfficialMatch, OfficialMatchScoreResult
... |
import os
import torch
import torch.nn as nn
import logging
import time
from torch.nn.parallel import DistributedDataParallel as DDP
from lib.models.builder import build_model
from lib.models.loss import CrossEntropyLabelSmooth
from lib.models.utils.dbb.dbb_block import DiverseBranchBlock
from lib.dataset.builder impo... |
package(
default_visibility = ["//visibility:public"],
)
load(
"@gust//defs/toolchain/ts:tsc.bzl",
"ts_module",
)
load(
"@gust//defs/toolchain/style:rules.bzl",
"style_binary",
"style_library",
)
load(
"@npm_bazel_labs//:index.bzl",
"ts_proto_library",
)
load(
"@npm_bazel_rollup... |
"""Symbolic quaterion operations, dynamics and rotations."""
import numpy as np
import sympy
def derivative(quat, omega, renorm_gain=0):
[q0, q1, q2, q3] = quat
[p, q, r] = omega
err = 1 - (q0**2 + q1**2 + q2**2 + q3**2)
q0dot = -0.5 * (p*q1 + q*q2 + r*q3) + renorm_gain*err*q0
q1dot = -0.5 * (-p... |
# Copyright (c) 2021 PaddlePaddle 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 appli... |
#!/usr/bin/env python
# (c) 2013, Sebastien Goasguen <runseb@gmail.com>
#
# This file is part of Ansible,
#
# Ansible 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 3 of the License, or
# (at ... |
# Copyright 2020 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... |
import networkx as nx
import numpy as np
from challenge import Challenge
class ChallengeSolution(Challenge):
########################################################################
# Load data #
################################################... |
from collections import namedtuple
knapsack_item = namedtuple("knapsack_item", ["weight", "value"])
max_weight = 15
items = [
knapsack_item(weight=2, value=2),
knapsack_item(weight=1, value=2),
knapsack_item(weight=12, value=4),
knapsack_item(weight=1, value=1),
knapsack_item(weight=4, value=10),... |
from __future__ import absolute_import, division, print_function
import scitbx.array_family.flex # import dependency
import boost.python
ext = boost.python.import_ext("scitbx_rigid_body_ext")
from scitbx_rigid_body_ext import *
import math
from scitbx import matrix
class pickle_import_trigger(object): pass
@boost.py... |
# -*- coding: utf8 -*-
from explicates.model.annotation import Annotation
from . import BaseFactory, factory, repo
class AnnotationFactory(BaseFactory):
class Meta:
model = Annotation
@classmethod
def _create(cls, model_class, *args, **kwargs):
annotation = model_class(*args, **kwargs)
... |
# Copyright (C) 2018-2021 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import logging as log
import numpy as np
from openvino.tools.mo.ops.non_max_suppression import NonMaxSuppression
from openvino.tools.mo.front.extractor import FrontExtractorOp
class NonMaxSuppressionV2Extractor(FrontExtractorOp):
... |
import json
from typing import get_args
from rest_framework import serializers
from posthog.api.documentation import (
FilterActionSerializer,
FilterEventSerializer,
OpenApiTypes,
PropertySerializer,
extend_schema_field,
)
from posthog.constants import (
ACTIONS,
BREAKDOWN_TYPES,
DISPL... |
from deuce.drivers.storage.metadata import MetadataStorageDriver
from deuce.drivers.storage.metadata.cassandra import CassandraStorageDriver
from deuce.tests.test_sqlite_storage_driver import SqliteStorageDriverTest
# Explanation:
# - The SqliteStorageDriver is the reference metadata driver. All
# other drivers sho... |
from discord.ext import commands
class AlphaCtx(commands.Context):
@property
def session(self):
return self.bot.session
|
# smop -- Simple Matlab to Python compiler
# Copyright 2011-2014 Victor Leikehman
"""
Calling conventions:
call site: nargout=N is passed if and only if N > 1
func decl: nargout=1 must be declared if function may return
more than one return value. Otherwise optional.
return value: return (x,y,z)[:narg... |
from filebeat import BaseTest
import os
"""
Contains tests for filtering.
"""
class Test(BaseTest):
def test_dropfields(self):
"""
Check drop_fields filtering action
"""
self.render_config_template(
path=os.path.abspath(self.working_dir) + "/test.log",
filt... |
import utils
class TXInput(object):
""" Represents a transaction input
Args:
txid (string): Transaction ID.
vout (int): Transaction output value.
sig (string): Signature.
pubkey (string): Public key.
Attributes:
_tx_id (bytes): Transaction ID.
... |
import parse
def parse_name(text: str) -> str:
patterns = (
"my name is {name}",
"i'm {name}",
"i am {name}",
"call me {name}",
"{name}",
)
for pattern in patterns:
result = parse.parse(pattern, text)
if result:
# Switch the commented out... |
#!/usr/bin/env python2
# The MIT License (MIT)
#
# Copyright (c) 2018-2021 Cristian Beltran
#
# 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 limitatio... |
"""TensorFlow workspace initialization. Consult the WORKSPACE on how to use it."""
# Import third party config rules.
load("//tensorflow:version_check.bzl", "check_bazel_version_at_least")
load("//third_party/gpus:cuda_configure.bzl", "cuda_configure")
load("//third_party/gpus:rocm_configure.bzl", "rocm_configure")
lo... |
# 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.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import copy
import json
import math
from multip... |
# -*- coding: utf-8 -*-
# Scrapy settings for healthlaw project
#
# For simplicity, this file contains only settings considered important or
# commonly used. You can find more settings consulting the documentation:
#
# http://doc.scrapy.org/en/latest/topics/settings.html
# http://scrapy.readthedocs.org/en/late... |
# -*- coding: utf-8 -*-
__license__ = u'''
Copyright (c) 2007-2009, Mărieş Ionel Cristian
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... |
from chepstow.agent import *
import unittest
class AgentTest(unittest.TestCase):
def test_something(self):
agent = Agent()
agent.run(0.1)
self.assertIsNone(None)
|
# Copyright 2021 NREL
# 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
# distri... |
import datetime
import logging
from typing import Any, Dict, List, Optional, Union
from uuid import UUID
from django.core.exceptions import ValidationError
from django.core.validators import URLValidator, validate_email
from django.db import IntegrityError, transaction
from django.http import HttpRequest, HttpResponse... |
"""
Trellis Stacked Bar Chart
=========================
This is an example of a horizontal stacked bar chart using data which contains crop yields over different regions and different years in the 1930s.
"""
# category: bar charts
import altair as alt
from vega_datasets import data
source = data.barley()
alt.Chart(so... |
# coding: utf-8
"""
TeamCity REST API
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) # noqa: E501
OpenAPI spec version: 2018.1
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
im... |
"""Integration tests for DNSMadeEasy"""
from unittest import TestCase
import pytest
from lexicon.tests.providers.integration_tests import IntegrationTestsV2
# Hook into testing framework by inheriting unittest.TestCase and reuse
# the tests which *each and every* implementation of the interface must
# pass, by inhe... |
# process_results.py
# -*- coding: utf-8 -*-
# @Author: Sidharth Mishra
# @Date: 2017-05-17 14:42:23
# @Last Modified by: Sidharth Mishra
# @Last Modified time: 2017-05-17 16:49:27
"""
Processes the results.txt obtained by running either Simplicial Complex C++ program or the
Apriori C++ port and uses the word_map.... |
# Written by Dr Daniel Buscombe, Marda Science LLC
# for the USGS Coastal Change Hazards Program
#
# MIT License
#
# Copyright (c) 2020, Marda Science LLC
#
# 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... |
"""Module for phasar LinearConstantAnalysis analyses."""
import typing as tp
from pathlib import Path
from benchbuild import Project
from benchbuild.extensions import compiler, run, time
from benchbuild.utils import actions
from benchbuild.utils.cmd import mkdir
from plumbum import local
from varats.data.reports.empt... |
# ***** BEGIN GPL LICENSE BLOCK *****
#
#
# 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 later version.
#
# This program is distribute... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
import sys
import logging
import psutil
from . import UI
from .. import event
logger = logging.getLogger(__name__)
def flush_stdin():
try:
import termios # linux
termios.tcflush(sys.stdin, termios.TCIOFLUSH)
... |
# -*- coding: utf-8 -*-
# pass in Python3.6
def run_EQCatlog(data):
# part 1 ----------import and set loginfo---------- #
import pandas as pd
import matplotlib.pyplot as plt
import pathlib
# output logging
import geoist as gi
gi.log.setname('Datist_EQCatlog')
gi.log.info('EQCat... |
#!/usr/bin/python
#
# SPDX-License-Identifier: Apache-2.0
#
from __future__ import absolute_import, division, print_function
__metaclass__ = type
from ansible.module_utils._text import to_native
from ..module_utils.module import BlockchainModule
from ..module_utils.utils import (get_console, get_identity_by_module,... |
from bson.objectid import ObjectId
from flask import Blueprint, render_template, request, session
from flask.helpers import flash, url_for
from werkzeug.utils import redirect
from ..extentions.database import mongo
produto = Blueprint("produto", __name__, url_prefix="/produtos")
@produto.route("/list")
def listProdu... |
import numpy as np
from pycocotools.coco import COCO
from .custom import CustomDataset
from .registry import DATASETS
@DATASETS.register_module
class VGDatasetUnSeen130(CustomDataset):
CLASSES = (
"chain",
"vent",
"laptop",
"propeller",
"goggles",
... |
# 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 PyPot(PythonPackage):
"""
This open source Python library provide several solvers for ... |
import cv2
import numpy as np
import copy
from tensorflow.python.lib.io import file_io
import io
from PIL import Image
def url2img(uri):#IO function compliant to loading gs:// url images
file= file_io.FileIO(uri, mode='rb')
file = file.read()
img= Image.open(io.BytesIO(file)).convert('RGB')
return np.asarray(im... |
from .significance_calculation import (
analyze_on_off,
analyze_wobble,
setup_logging,
)
from .hdu_table import (
add_icrs_position_params,
create_event_list,
create_hdu_index_hdu,
create_obs_index_hdu,
get_pointing_params,
get_timing_params,
set_expected_pos_to_reco_altaz,
)
_... |
import re
from functools import reduce
def completely_invalid_sum(defs, ticket):
invalid, s = False, 0
for val in ticket:
found = False
for ((x1, x2), (y1, y2)) in defs:
if (x1 <= val <= x2) or (y1 <= val <= y2):
found = True
break
if not fou... |
from torch import nn
from torch.nn import Module
def determine_conv_class(n_dim, transposed=False):
if n_dim is 1:
if not transposed:
return nn.Conv1d
else:
return nn.ConvTranspose1d
elif n_dim is 2:
if not transposed:
return nn.Conv2d
else:
... |
from test_vars import *
set_paths("../tests/imgs/hsl/to-grayscale")
pyifx.hsl.to_grayscale(img_list)
call_error_test("pyifx.hsl.to_grayscale", [10000]) |
import hashlib
import os
import cryptography.exceptions
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.ciphers import aead
from cryptography.hazmat.primitives.kdf.scrypt import Scrypt
import _replicat_adapters
from .. import exceptions
_backend = default_backend()
clas... |
# 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... |
import requests
from API.library.support.data import edo
def get_current_agent_information(client):
url = edo + '/en/api/1.0/agent'
current_agent_information = requests.get(url, headers=client)
return current_agent_information
|
'''
neurosynth: plugin for the deepdive python package
functions for working with neurosynth database
'''
from neurosynth.base.dataset import Dataset
from neurosynth.base.dataset import FeatureTable
from wordfish.plugins.pubmed.functions import get_articles
from neurosynth.analysis import meta
from scipy.stats import... |
import pytest
from path import Path
@pytest.fixture()
def raw_hub_data():
test_dir = Path(__file__).parent
hub_data_file = test_dir / 'raw_hub_data.json'
return hub_data_file.read_text()
|
# coding: utf-8
from __future__ import unicode_literals, print_function, division, absolute_import
def str2bool(v):
return v.lower() in (
'yes', 'true', 't', '1') if isinstance(v, basestring) else v
|
import logging
logger = logging.getLogger( __file__ )
def CustomSQLQuery( sql, args ):
from django.db import connection
cursor = connection.cursor()
# Data retrieval operation - no commit required
cursor.execute( sql, args )
rows = cursor.fetchall()
cursor.execute( "COMMIT" )
return rows
... |
import torch.nn as nn
import torch.nn.functional as F
class Model(nn.Module):
def __init__(self, config):
super(Model, self).__init__()
self.conv1 = nn.Conv2d(3, 16, (3, 3), padding=1)
self.conv1_bn = nn.BatchNorm2d(16)
self.conv2 = nn.Conv2d(16, 32, (3, 3), padding=1, s... |
import radix
t=radix.init_tree()
for e in [b"romane",b"romanus",b"romulus",b"rubens",b"ruber",b"rubicon",b"rubicundus"]:
radix.insert(t,e)
radix.print_tree(t)
print(radix.delete(t,b"ruber"))
print(radix.delete(t,b"invalid_key"))
radix.print_tree(t)
|
import torch
import torch.nn as nn
import string
import os
import time
import random
from torch.functional import Tensor
from utils import Utils
from recurrent_neural_network import RecurrentNeuralNetwork
from typing import List, Tuple, Any
class Program():
def __init__(self, learning_rate: float = 0.005, iterations... |
import collections
Endpoint = collections.namedtuple("Endpoint", ["index", "value", "start"])
T = int(input())
for t in range(1, T + 1):
N, L1, R1, A, B, C1, C2, M = map(int, input().split())
endpoints = [Endpoint(0, L1, True), Endpoint(0, R1 + 1, False)]
for i in range(1, N):
x = (A * L1 + B * R1... |
import os
import numpy as np
import cv2.cv2 as cv2
from imutils.video import FPS
import argparse
import datetime
import time
import uuid
import random
import pyimgur
from store_image import storeImage
from linebot import LineBotApi
from fire import getName, getDevice, getLink, getAll
from bigdataProxy import injectNoti... |
import pytest
import numpy as np
from numpy.testing import assert_allclose
from sklearn.exceptions import NotFittedError
from proglearn.transformers import TreeClassificationTransformer
class TestTreeClassificationTransformer:
def test_init(self):
TreeClassificationTransformer()
assert True
... |
import logging
import json
from django.contrib.auth.mixins import LoginRequiredMixin
from django.http import HttpResponse, QueryDict, HttpResponseRedirect
from django.core.urlresolvers import reverse, reverse_lazy
from django.views.generic import (
CreateView,
DetailView,
ListView,
UpdateView,
Del... |
import abc
import enum
from dataclasses import dataclass
from typing import Optional, Sequence
from .common import Location, Address, GeoPoint
class Confidence(enum.Enum):
LOW = 0
PARTIAL = 1
EXACT = 2
class Precision(enum.Enum):
APPROXIMATE = 0
GEOMETRIC_CENTER = 1
RANGE_INTERPOLATED = 2
... |
#!/usr/bin/env python
# coding: utf-8
import re
from os import path
from pathlib import Path
try:
from pip._internal.req import parse_requirements
except ImportError:
from pip.req import parse_requirements
from setuptools import setup, find_packages
root_dir = path.abspath(path.dirname(__file__))
package_na... |
"""Unit tests for the trackerchart module."""
import pandas as pd
import pytest
import trackerchart as tc
def test_filter_date_range():
columns = ["date", "fruit"]
data = [
["2021-10-09", "apple"],
["2021-10-10", "banana"],
["2021-10-11", "calamansi"],
["2021-10-12", "durian"... |
#### 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 = Tangible()
result.template = "object/tangible/mission/shared_mission_recon_target.iff"
result.attribute_template_... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union
from .. import _utilities, _tables
__al... |
#!/usr/bin/env python
import io
import os
import sys
import unittest
pkg_root = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) # noqa
sys.path.insert(0, pkg_root) # noqa
from tests import config # initialize the test environment
from tests import CLITestMixin
from tests.infra.testmode import testmo... |
#!/usr/bin/env python3
# Copyright (c) 2014-2017 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 the walletupgrade functionality.
- 1) start one Human_Charity_Coin_Protocold node from an pre-HD ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.