text stringlengths 2 999k |
|---|
from rest_framework.test import APITestCase
class TestFuzzyCountrySearchAPI(APITestCase):
"""
Tests for Fuzzy API
"""
def setUp(self):
self.fuzzy_url = '/api/fuzzy-search/{}/'
self.api_url = self.fuzzy_url.format('country')
def test_search_invalid_type(self):
invalid_types... |
#!/usr/bin/env python3
# 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... |
if a.not<caret>:
print(1) |
import numpy as np
import random
from collections import namedtuple, deque
from model import QNetwork
import torch
import torch.nn.functional as F
import torch.optim as optim
BUFFER_SIZE = int(1e5) # replay buffer size
BATCH_SIZE = 64 # minibatch size
GAMMA = 0.99 # discount factor
TAU = 1e-3 ... |
from django.urls import path
from . import views, scraper
urlpatterns = [
path('', views.index, name='index'),
path('counter', views.counter, name='counter'),
path('count', views.count, name='count'),
path('show', scraper.show, name='show'),
path('fetch', scraper.fetchTaipeiYouBikeAPIData, name='f... |
# Copyright (c) 2017-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
import importlib
import inspect
import re
import types
try:
from django.utils.functional import cached_property # ... |
# Copyright 2021 Injective Labs
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... |
'''
'''
# 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");... |
from random import random, seed
def gen_random() -> int:
return int(random() * 5) + 1
def bad_input_850() -> None:
print("\nHAMURABI: I CANNOT DO WHAT YOU WISH.")
print("GET YOURSELF ANOTHER STEWARD!!!!!")
def bad_input_710(grain_bushels: int) -> None:
print("HAMURABI: THINK AGAIN. ... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2018-09-29 07:33
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('gallerys', '0003_auto_20180928_1244'),
]
operations ... |
"""Subtract node"""
from . import negate, node, number
class Subtract(node.Node):
"""Subtract node"""
def __init__(self, left=None, right=None):
self.left = left
self.right = right
def copy(self):
return Subtract(self.left.copy(), self.right.copy())
def evaluate(self, value... |
import os
import pkg_resources
import re
import redis
import requests
import shutil
import six
import sys
import tempfile
import threading
import time
import webbrowser
from six.moves import shlex_quote as quote
from dallinger import data
from dallinger import db
from dallinger import heroku
from dallinger import recr... |
from abc import abstractmethod
import numpy as np
import rpxdock.homog as hm
from rpxdock.geom import sym
allowed_twocomp_architectures = """
D22 D32 D42 D52 D62 D72 D82
T32 T33 O32 O42 O43 I32 I52 I53
T32D T23D T33D
O32D O23D O42D O24D O43D O34D
I32D I23D I52D I54D I53D I35D
AXEL_1_2_3 AXEL_1_2_4 AXEL_1_2_5 AXEL_1_2_... |
################################
# DIABETES PREDICTION with CART
################################
import pandas as pd
import numpy as np
from sklearn.metrics import *
from sklearn.model_selection import *
from sklearn.tree import DecisionTreeClassifier
import pydotplus
from sklearn.tree import export_graphviz,... |
#
# 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... |
from __future__ import print_function, division, absolute_import
import GPy
import numpy as np
import losbo as safeopt
import scipy
import math
import time
import os
import datetime
import pickle
import multiprocessing as mp
import sys
import pathlib
store_path = str(pathlib.Path(__file__).parent.resolve())
def cal... |
import base64
import binascii
import codecs
import secrets
import discord
from discord.ext import commands
class Encryption(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.group()
async def encode(self, ctx):
""" All encode methods """
if ctx.invoked_subcommand is... |
def parse_html_page(soup):
text = ""
for i in soup.body.descendants:
if i.name == 'section' or i.name == 'article' or i.name == 'main':
for j in i.descendants:
if j.name == 'img':
j['src'] = ''
cc = ''
for c in i.contents:
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'Jan-Piet Mens <jpmens()gmail.com>'
__copyright__ = 'Copyright 2014 Jan-Piet Mens'
__license__ = """Eclipse Public License - v 1.0 (http://www.eclipse.org/legal/epl-v10.html)"""
HAVE_SQLITE=True
try:
import sqlite3
except:
HAVE_SQLITE=False
def ... |
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
import grpc
from google.cloud.tasks_v2beta3.proto import (
cloudtasks_pb2 as google_dot_cloud_dot_tasks__v2beta3_dot_proto_dot_cloudtasks__pb2,
)
from google.cloud.tasks_v2beta3.proto import (
queue_pb2 as google_dot_cloud_dot_tasks__v2beta3... |
# Copyright (c) 2015-2018 Cisco Systems, Inc.
#
# 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... |
from django.db import models
class LastPostTimeStamp(models.Model):
time_stamp = models.BigIntegerField()
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@created: 30.09.19
@author: felix
"""
def split_nums(num: str) -> tuple:
nums = num.split('-')
start = int(nums[0])
try:
end = int(nums[1])
except (IndexError, ValueError):
end = start
return start, end
def parse_ranges(args: str... |
"""A container for specifying and manipulating a graph with distinct inputs and outputs."""
import time
import warnings
from collections import OrderedDict
from typing import Any, Dict, List, NoReturn, Optional, Tuple, Union
import aesara
from aesara.configdefaults import config
from aesara.graph.basic import Apply, C... |
import logging
import warnings
from functools import partial
from .file import File
from .chat import ChatMessage
from .auxo import ARBITRATOR
LOGGER = logging.getLogger(__name__)
GENERICS = [
"roomScore",
"submitChat",
"submitCommand",
"pro",
"room_old",
"upload",
"reconnectTimeout",
]... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
setup.py
Created by Stephan Hügel on 2016-07-25
"""
import sys
from setuptools import setup, Extension
from Cython.Build import cythonize
import numpy
# # Set dynamic RPATH differently, depending on platform
ldirs = []
ddirs = []
if "linux" in sys.platform:
# fr... |
"""
Dveloper: vujadeyoon
Email: vujadeyoon@gmail.com
Github: https://github.com/vujadeyoon/vujade
Title: vujade_lr_scheduler.py
Description: A module for learning rate scheduler
"""
from math import log, exp
def adjust_learning_rate(_opt, _optimizer, _epoch, _type='poly'):
if _type == 'step':
epoch_iter... |
import os
import shutil
from pathlib import Path
import random
class TestSupport:
"""
Macros, utility functions for tests.
"""
THIS_DIR = Path(os.path.dirname(os.path.realpath(__file__)))
PROJECT_DIR = THIS_DIR.parent
SUBJECTS_DIR = PROJECT_DIR / "resources"
class get_playground_path:
... |
# Copyright 2019 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.
"""A wrapper for common operations on a Fuchsia device"""
import logging
import subprocess
class CommandRunner(object):
"""Helper class used to execute co... |
import numpy as np
from tensorflow.keras import backend as k
from image_utils import non_max_suppression
def xywh2minmax(xy, wh):
xy_min = xy - wh / 2
xy_max = xy + wh / 2
return xy_min, xy_max
def iou(pred_mins, pred_maxes, true_mins, true_maxes):
intersect_mins = k.maximum(pred_mins, true_mins)
... |
import base64
import boto3
import collections
import datetime
import importlib
import inspect
import json
import logging
import os
import sys
import traceback
import tarfile
from builtins import str
from werkzeug.wrappers import Response
from mangum import Mangum
# This file may be copied into a project's root,
# so... |
from __future__ import print_function
from time import time
from statsmodels.tsa.arma_mle import Arma
from statsmodels.tsa.api import ARMA
import numpy as np
print("Battle of the dueling ARMAs")
y_arma22 = np.loadtxt(r'C:\Josef\eclipsegworkspace\statsmodels-josef-experimental-gsoc\scikits\statsmodels\tsa\y_arma22.txt... |
#!/usr/bin/env python
import sys
from conv import num2code
def main():
prefix = sys.argv[1]
for i in range(0, 100):
for j in range(0, 100):
sn = prefix + num2code(str(i).zfill(2)) + 'n' + num2code(str(j).zfill(2))
dm = 'r2---' + 'sn-' + sn + '.googlevideo.com'
print... |
import io
from setuptools import find_packages, setup
with io.open('README.md', 'rt', encoding='utf8') as f:
readme = f.read()
setup(
name='pyqum',
version='0.1.0',
url='',
license='BSD',
maintainer='Quela team',
maintainer_email='qubitcool@gmail.com',
description='Q Measurement App',... |
import math
import os
import time
from copy import deepcopy
import torch
import torch.backends.cudnn as cudnn
import torch.nn as nn
import torch.nn.functional as F
def init_seeds(seed=0):
torch.manual_seed(seed)
# Remove randomness (may be slower on Tesla GPUs) # https://pytorch.org/docs/stable/notes/random... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from optionaldict import optionaldict
from teambition.api.base import TeambitionAPI
class StageTemplates(TeambitionAPI):
def get(self):
"""
获取用户自定义的阶段模板
详情请参考
http://docs.teambition.com/wiki/stages-... |
#!/usr/bin/env python3
# Copyright (c) 2020, The OTNS Authors.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# 1. Redistributions of source code must retain the above copyright
# notice, this... |
import numpy as np
import math as math
import matplotlib.pyplot as plt
def generatehistogramfunc(mcmcChainBG, mapResultBG, N, M, B, G, sigma,
figsize1=20, figsize2=6, ncolfig=5, sigmatheory=float('nan'),
savefigname='fig.pdf', plotwhich=[1, 0, 1],
... |
''' Fvtk module implements simple visualization functions using VTK.
The main idea is the following:
A window can have one or more renderers. A renderer can have none, one or more actors. Examples of actors are a sphere, line, point etc.
You basically add actors in a renderer and in that way you can visualize the fore... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author : qichun tang
# @Contact : tqichun@gmail.com
from .hdp import HdpTransformer
from .lda import LdaTransformer
from .lsi import LsiTransformer
from .nmf import NmfTransformer
from .rp import RpTransformer
from .tsvd import TsvdTransformer
|
import cv2 as cv
def canny(img_path='../images/input.jpg', save_path='../images/'):
image = cv.imread(img_path)
gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
blurred = cv.GaussianBlur(gray, (5, 5), 0)
canny = cv.Canny(blurred, 30, 150)
canny_coarse = cv.Canny(blurred, 150, 250)
# print(image.s... |
# pylint: disable=line-too-long, wrong-import-position
"""
This is an example of a Protein viewer app, using the [NGL Viewer](https://github.com/nglviewer/ngl).
You can import it from the `awesome-panel-extensions` package via
`from awesome_panel_extensions.widgets.ngl_viewer import NGLViewer`.
The NGL Viewer ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from os.path import dirname, join as join_path
from setuptools import setup, find_packages
def _read(file_name):
sock = open(file_name)
text = sock.read()
sock.close()
return text
setup(
name = 'weblayer',
version = '0.4.3',
description ... |
def separador():
return "-="*30 |
import json
import os
import pytest
from iopipe import IOpipeCore
from iopipe.contrib.eventinfo import EventInfoPlugin
@pytest.fixture
def iopipe_with_eventinfo():
plugin = EventInfoPlugin()
return IOpipeCore(
token="test-suite",
url="https://metrics-api.iopipe.com",
debug=True,
... |
"""Helpers for managing data files."""
from dataclasses import dataclass
import pandas as pd
__all__ = ["Datasets"]
@dataclass
class _DataSet:
"""Class to hold datasets and related information.
TODO: Add description, provenance, and other metadata here.
"""
url: str
def to_dataframe(self) -> ... |
##############################################################################
# Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-64... |
# -*- coding: utf-8 -*-
#
# Author: Taylor Smith <taylor.smith@alkaline-ml.com>
#
# This is the lynx dataset found in R.
import numpy as np
import pandas as pd
from ..compat import DTYPE
__all__ = [
'load_lynx'
]
def load_lynx(as_series=False, dtype=DTYPE):
"""Annual numbers of lynx trappings for 1821–1934... |
# Copyright (c) 2020 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... |
from testapp import app
import pyexcel as pe
import json
from _compact import OrderedDict, BytesIO
class TestSheet:
def setUp(self):
app.config['TESTING'] = True
self.app = app.test_client()
self.data = [
['X', 'Y', 'Z'],
[1, 2, 3],
[4, 5, 6]
]
... |
from setuptools import setup
packages_yambopy = ['yambopy',
'yambopy.io',
'yambopy.dbs',
'yambopy.bse',
'yambopy.rt',
'yambopy.data',
'yambopy.plot',
'yambopy.tools',
... |
# Copyright 2012 Nebula, 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 agree... |
import torch
from torch import multiprocessing, cuda
from torch.utils.data import DataLoader
import torch.nn.functional as F
from torch.backends import cudnn
import numpy as np
import importlib
import os
import voc12.dataloader
from misc import torchutils, imutils
cudnn.enabled = True
def _work(process_id, model, d... |
import sys
import struct
import mock
import unittest2
import mitogen.core
import mitogen.master
import testlib
from mitogen.core import b
class ConstructorTest(testlib.TestCase):
klass = mitogen.core.Message
def test_dst_id_default(self):
self.assertEquals(self.klass().dst_id, None)
def test... |
# App Imports
from core.models import AssetIncidentReport, StateTransition
from core.tests import CoreBaseTestCase
class StateTransitionModelTest(CoreBaseTestCase):
"Tests state trensition model"
def test_create_incident_report_creates_new_state_transition(self):
incident_report_count = AssetIncident... |
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 3 11:00:38 2017
@author: thuzhang
"""
# Ensemble
# packages
from PredictWindSpd import PredictWindSpd
from Reduced_Noise import NoiseReduce
from Former_Data import FormerData
#from ReadTrueValue import ReadTrueValue
import matplotlib.pyplot as plt
#Consts
StartTime=8... |
import os
import shutil
import string
from os.path import join, dirname, abspath, exists, splitext
import scrapy
from scrapy.command import ScrapyCommand
from scrapy.utils.template import render_templatefile, string_camelcase
from scrapy.exceptions import UsageError
def sanitize_module_name(module_name):
"""Sanit... |
# Copyright 2017 CBSD Project 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 applic... |
from __future__ import absolute_import
import os
from celery import Celery
from real_estate.settings import base
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "real_estate.settings.development")
app = Celery("real_estate")
app.config_from_object("real_estate.settings.development", namespace="CELERY"),
app.autod... |
#create directory path to store face images
faceImagesPath = 'faceImages'
#create directory path to store face metadata and embedded
faceData = 'faceData'
#create directory path to store trained weights
weights = 'weights' |
import hashlib
import hmac
import time
class BitfinexAuth():
def __init__(self, api_key: str, secret_key: str):
self.api_key = api_key
self.secret_key = secret_key
self.last_nonce = 0
def _sign_payload(self, payload) -> str:
sig = hmac.new(self.secret_key.encode('utf8'),
... |
from __future__ import annotations
import json
from typing import Union
from anyio import TASK_STATUS_IGNORED
import voluptuous as vol
from homeassistant.components import websocket_api
from homeassistant.components.trace import async_get_trace, async_list_traces
from homeassistant.components.websocket_api import asy... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import json
import warnings
import pulumi
import pulumi.runtime
from typing import Union
from .. import utilities, tables
class GetCon... |
from twisted.trial.unittest import SynchronousTestCase
from thimble import Thimble
from thimble.test.util import FakeReactor, FakeThreadPool
from twisted.internet.error import ReactorNotRunning
class ExampleSynchronousThing(object):
"""An example thing with some blocking APIs which will be wrapped and
some n... |
import argparse
from collections import defaultdict
from dataclasses import dataclass
from typing import NamedTuple, Sequence, Iterable, Any, List, Dict, Optional, Tuple
import logging
import torch
from torch.fx.passes.graph_manipulation import get_size_of_node
from torch.fx.node import map_arg
from torch.fx._compatib... |
"""
Django settings for Agruppa project.
Generated by 'django-admin startproject' using Django 1.8.6.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""
# Build pa... |
import itertools
import collections
import time
import logging
import numpy as np
import pandas as pd
|
# relative hydration free energy
import numpy as np
from rdkit import Chem
from rdkit.Chem import AllChem
from fe import pdb_writer
from fe import topology
from md import builders
from md import minimizer
from timemachine.lib import potentials, custom_ops
from timemachine.lib import LangevinIntegrator
import functo... |
# Generated by Django 3.1.7 on 2021-02-25 01:11
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('bugtracker_app', '0004_customuser_user'),
]
operations = [
migrations.RemoveField(
model_name='customuser',
name='us... |
from machine import I2C
from utime import sleep_ms
REG_TEMP = const(0x00)
REG_HUMI = const(0x01)
REG_CFG = const(0x02)
REG_SER_ID1 = const(0xfb)
REG_SER_ID2 = const(0xfc)
REG_SER_ID3 = const(0xfd)
CFG_RST = const(0b10000000)
CFG_HEAT_ON = const(0b100000)
CFG_HEAT_OFF = const(0b0)
CFG_MODE_SINGLE = const(0b0)
CFG_MODE... |
# -*- coding: utf-8 -*-
"""
Dummy conftest.py for lantiseaa.
If you don't know what this is for, just leave it empty.
Read more about conftest.py under:
https://pytest.org/latest/plugins.html
"""
# import pytest
|
from .algo import ConstSparsity
__all__ = [
'ConstSparsity'
]
|
# Configuration file for Tracer service
import FWCore.ParameterSet.Config as cms
process = cms.Process("TEST")
process.load("FWCore.Framework.test.cmsExceptionsFatal_cff")
process.Tracer = cms.Service("Tracer")
process.maxEvents = cms.untracked.PSet(
input = cms.untracked.int32(20)
)
process.source = cms.Sour... |
from django.test import TestCase
from app.models.core import User
from app.models import Landscape, Land, Company, BuildingType, Item, Place
from app.core.services.builders.building_builder import BuildingBuilder
class BuildingItemProducingTestCase(TestCase):
def setUp(self):
self.load_data()
self... |
from __future__ import annotations
import json
from dataclasses import (
dataclass,
asdict
)
from typing import List
@dataclass
class PlayerState:
updated: float = 0.0
x: float = 0.0
y: float = 0.0
health: float = 0.0
speed: float = 250.0
@dataclass
class GameState:
player_state... |
import os
from getpass import getpass
import yaml
from netmiko import ConnectHandler
def load_devices(device_file="lab_devices.yml"):
device_dict = {}
with open(device_file) as f:
device_dict = yaml.safe_load(f)
return device_dict
if __name__ == "__main__":
# Code so automated tests will ru... |
import discord
class Ide:
"""Red-Discordbot IDE - a cog port of Alias efficiencies for the lazy bot owner / cog creator
This cog is under construction atm. only useful thing in installing this is the sublime snippets in the data folder.
Place them in Packages/User to use them."""
def __init__(self, b... |
import io
import os
import re
from setuptools import setup, find_packages
scriptFolder = os.path.dirname(os.path.realpath(__file__))
os.chdir(scriptFolder)
# Find version info from module (without importing the module):
with open("src/wizcoin/__init__.py", "r") as fileObj:
version = re.search(
r'^__versio... |
"""
Factories for bootcamp models
"""
from factory import Faker, Sequence, SubFactory, LazyAttribute
from factory.django import DjangoModelFactory
from factory.fuzzy import FuzzyDecimal, FuzzyText
import faker
import pytz
from klasses import models
from profiles.factories import UserFactory
FAKE = faker.Factory.creat... |
# -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""
Exception for errors raised by JKU simulator.
"""
from qiskit import QiskitError
class JKUSimulatorError(QiskitError)... |
import pandas as pd
from datetime import datetime
import pickle
import numpy as np
import plotly.graph_objects as go
from sklearn.preprocessing import StandardScaler
class PredictHost:
def __init__(self, data_path, web_data_path):
self.data_path = data_path
self.web_data_path = web_data_path
... |
import pytest
keras = pytest.importorskip("keras")
np = pytest.importorskip("numpy")
from distributed.protocol import serialize, deserialize, dumps, loads, to_serialize
def test_serialize_deserialize_model():
from numpy.testing import assert_allclose
model = keras.models.Sequential()
model.add(keras.la... |
#使用中间件实现强制某个IP地址只能向/test开头的地址
#发送五次请求提示 |
# Copyright 2018 ARM Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... |
# Generated by Django 2.0.1 on 2018-01-29 18:08
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
ope... |
import numpy as np
from numba import jit
@jit(nopython=True)
def normal_pdf(x, mean=0, sd=1):
"""
Calculate probability of x given X ~ N(mean, sd ** 2)
"""
return 1 / (sd * np.sqrt(2 * np.pi)) \
* np.exp(- 1 / 2 * ((x - mean) / sd) ** 2) |
from pathlib import Path
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from titanic_sample.utils import ON_KAGGLE
DATA_ROOT = Path('../input/titanic' if ON_KAGGLE else './resources')
Categorical_Features = ['Embarked', 'Pclass', 'Sex']
train_path = DATA_ROOT / "train.csv... |
from user_agents import parse as ua_parse
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.utils.encoding import python_2_unicode_compatible
from request.models import Request
from request.tracking.managers import VisitorManager, VisitManager
@python_2_unicode_compati... |
# -*- coding: utf-8 -*-
#
# Configuration file for the Sphinx documentation builder.
#
# This file does only contain a selection of the most common options. For a
# full list see the documentation:
# http://www.sphinx-doc.org/en/stable/config
# -- Path setup ------------------------------------------------------------... |
from uuid import uuid4
from flask import Response
from flask_restful import Resource, request
from blockchain.blockchain import Blockchain
blockchain = Blockchain()
class Node(Resource):
def post(self):
"""
Add new node to blockchain
"""
node_id = blockchain.register_node(reques... |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: chirpstack-api/ns/ns.proto
"""Generated protocol buffer code."""
from google.protobuf.internal import enum_type_wrapper
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from ... |
# Tabish Shaikh's work
import zipfile
import zlib
import json
import os
import pandas
# directories
dir_file = str(os.path.dirname(os.path.realpath(__file__)))
dir_results = dir_file + '\\Results\\'
def downloadResultsAsJSON(csvDir,zipName,jsonName):
# Check for any zip file with the same name
if os.path.exi... |
# coding: utf-8
"""
ELEMENTS API
The version of the OpenAPI document: 2
Generated by: https://openapi-generator.tech
"""
import pprint
import re # noqa: F401
import six
from elements_sdk.configuration import Configuration
class ProxyProfilePartialUpdate(object):
"""NOTE: This class is auto gene... |
import matplotlib.pyplot as plt
DATA = ((1, 3),
(2, 4),
(3, 1),
(4, 2))
# dash_style =
# direction, length, (text)rotation, dashrotation, push
# (The parameters are varied to show their effects,
# not for visual appeal).
dash_style = (
(0, 20, -15, 30, 10),
(1, 30, 0, 15, 10),
(... |
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: MIT. See LICENSE
import frappe
from frappe.desk.reportview import build_match_conditions
def sendmail_to_system_managers(subject, content):
frappe.sendmail(recipients=get_system_managers(), subject=subject, content=content)
@frappe.whit... |
from pydantic import BaseSettings
class Settings(BaseSettings):
BROKER_URL: str
|
import pandas as p
import cv2
from sklearn import model_selection
import tensorflow as tf
from tensorflow.keras.models import Sequential#, Input
from tensorflow.keras.layers import Dense, Dropout, Flatten
from tensorflow.keras.layers import Lambda, Conv2D
from tensorflow.keras.optimizers import Adam
from te... |
from django.test import TestCase
from .models import Image, Profile, Likes
# Create your tests here.
class ImageTest(TestCase):
def setUp(self):
self.profile = Profile(name='dev-kev')
self.profile.save_profile()
self.likes = Likes(likes=0)
self.likes = Likes.save_likes()
s... |
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
import unittest
from pstream import AsyncStream
from tests._async.utils import Driver, Method, expect, AF, AI, run_to_completion
class SortWith(Method):
def __init__(self, args):
super(SortWith, self).__init__(AsyncStream.sort_with, args)
class TestSortWith(unittest.TestCase):
random = ['123', '5... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.