text stringlengths 2 999k |
|---|
import uuid
from django.db import models
from django.utils.translation import ugettext_lazy as _
class Conductor(models.Model):
user = models.OneToOneField("users.User", verbose_name=_(""),
on_delete=models.CASCADE)
national_id_number = models.CharField(_("Conductor National I... |
"""A setuptools based setup module.
See:
https://packaging.python.org/guides/distributing-packages-using-setuptools/
https://github.com/pypa/sampleproject
"""
# Always prefer setuptools over distutils
from setuptools import setup, find_packages
from os import path
here = path.abspath(path.dirname(__file__))
... |
import matplotlib.pyplot as plt
from sklearn.datasets import make_blobs
from sklearn.cluster import KMeans
# create dataset
X, y = make_blobs(
n_samples=150, n_features=2,
centers=3, cluster_std=0.5,
shuffle=True, random_state=0
)
km = KMeans(
n_clusters=3, init='random',
n_init=10, max_iter=300,
... |
"""This module provides a set of pytest hooks for generating Adaptavist test run results from test reports."""
from __future__ import annotations
import getpass
import logging
import os
from importlib.metadata import PackageNotFoundError, version
from typing import Any, Literal, NoReturn
import pytest
from _pytest.c... |
from itertools import product
from pyomo.core import *
class Model:
model = AbstractModel()
model.T = Set() # Index Set for time steps of optimization horizon
# Feasible charge powers to ESS under the given conditions
model.Feasible_ESS_Decisions = Set()
# Feasible charge powers to VAC under t... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.1 on 2017-06-03 14:45
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('jobs', '0017_farmjob_ext_tracking_assets'),
]
operations = [
migrations.Add... |
#!/Users/admin/PycharmProjects/ising_model/venv/bin/python
from django.core import management
if __name__ == "__main__":
management.execute_from_command_line()
|
from flask import *
from flask_socketio import SocketIO, send
from globals_web import *
from app.forms import *
from app import helpers, station_model
from werkzeug.utils import secure_filename
import os
app = Flask(__name__)
app.secret_key = "super secret key"
socket_io = SocketIO(app)
@app.route("/station_form")
d... |
import luigi
import subprocess
import os
from os.path import join, dirname, basename, isfile
from ..utils.cap_task import CapTask
from ..constants import MASH_SKETCH_SIZE
from ..config import PipelineConfig
from ..utils.conda import CondaPackage
from ..preprocessing.clean_reads import CleanReads
class Jellyfish(Cap... |
import os
from .. import FileBuilder
from .. import FileComparison
from .file_builder_test import FileBuilderTest
class FileComparisonTest(FileBuilderTest):
"""Tests ``FileBuilder`` with different ``FileComparisons``.
Tests the behavior of ``FileBuilder`` methods when we pass in
different ``FileComparis... |
import asyncio
from loguru import logger
from data import State
from miner import LiteClient, task_benchmark, task_miner, task_statistic_miner
from ws import WebSocketClient
def save_benchmark():
import json
with open('/var/log/gpu_benchmark.json', 'w', encoding='utf-8') as f:
json.dump(... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
print('{0}-{1}-{0}'.format('Good', 'morning'))
print('{}-{}'.format('你', '好'))
print('{name}:{age}'.format(name='Tom', age=18))
x, y = 100, 200
print('{0}-{1}'.format(x, y))
print(f'x: {x}{{显示大括号}}') # 3.6版加入f-string方法
print('%%d x: %d' % x) # C format
print('%%(x)d x:... |
from octopy import *
def PingModule(timeout = Minutes(10), key = "ip", status = Warning, rstatus = RWarning):
return {
"sensor" : {
"ping" : Boolean(timeout),
},
"trigger" : {
"ping_failed" : Match("ping", False)
},
"react" : {
"notify_ping_failed" : Reaction()
.On("ping_failed", 3, 0)
.B... |
import bisect
import numpy as np
from typing import Dict, List
CC_SPOT_RATE = "cc_spot_rate"
ZCB = "zcb"
class YieldCurve:
"""
Class for specifying and extracting rates from a yield curve including interpolation of unspecified points.
"""
def __init__(self):
# Set so that term 0 gives rate =... |
"""
Copyright (c) 2018 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in wri... |
from enum import Enum, auto
class Colors(Enum):
RED = auto()
BLUE = auto()
WHITE = auto()
YELLOW = auto()
GREEN = auto()
def stringToColor(colorString):
colorString = colorString.upper()[0]
colorLookupTable = {
'B': Colors.BLUE,
'G': Colors.GREEN,
'R': ... |
# The MIT License (MIT)
# Copyright (c) 2018 Guy Tordjman. All Rights Reserved.
# 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
# ... |
"""
Test AR Model
"""
from statsmodels.compat.pytest import pytest_warns
from typing import NamedTuple, Union
import datetime as dt
from itertools import product
import numpy as np
from numpy.testing import assert_allclose, assert_almost_equal
import pandas as pd
from pandas import Index, Series, date_range, period_r... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import django.contrib.postgres.fields
class Migration(migrations.Migration):
dependencies = [
('registration', '0006_remove_myuser_interests'),
]
operations = [
migrations.AddField(
... |
"""Test the SteadyPg module.
Note:
We do not test the real PyGreSQL module, but we just
mock the basic connection functionality of that module.
We assume that the PyGreSQL module will detect lost
connections correctly and set the status flag accordingly.
Copyright and credit info:
* This test was contributed by Chri... |
# Copyright 2020 The Feast 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wr... |
#!/usr/bin/python3
import os
import sys
import getopt
import quorum_algorithm
scriptpath = "../"
# Add the directory containing your module to the Python path (wants absolute paths)
sys.path.append(os.path.abspath(scriptpath))
import dt_algorithm
def simulate(max_depth, number_of_quorums, number_of_corrupted_nodes... |
"""Generate mapping graphs over classes, tuples, arrays, etc."""
from . import operations, composite as C
from .abstract import InferenceError, broaden
from .ir import MetaGraph, Graph
from .dtype import Array, List, Tuple, Class, tag_to_dataclass, \
pytype_to_myiatype
from .utils import TypeMap, Overload
from .p... |
"""
Train the model on randomized labels (shuffle along LENS time dimension)
Reference : Barnes et al. [2020, JAMES]
Author : Zachary M. Labe
Date : 2 November 2020
"""
### Import packages
import math
import time
import matplotlib.pyplot as plt
import numpy as np
import keras.backend as K
from keras.layers i... |
#
# Copyright (C) 2019 Databricks, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to i... |
# Copyright 2014 PerfKitBenchmarker 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... |
"""
42. Storing files according to a custom storage system
``FileField`` and its variations can take a ``storage`` argument to specify how
and where files should be stored.
"""
import random
import tempfile
from django.db import models
from django.core.files.base import ContentFile
from django.core.files.storage imp... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# =============================================================================
# @file create_device.py
# @author Albert Puig (albert.puig@cern.ch)
# @date 13.02.2015
# =============================================================================
"""Create device confi... |
""" Get the Bots in any chat*
Syntax: .get_bot"""
from telethon import events
from telethon.tl.types import ChannelParticipantAdmin, ChannelParticipantsBots
from userbot.utils import admin_cmd
@borg.on(admin_cmd(pattern="get_bot ?(.*)"))
async def _(event):
if event.fwd_from:
return
mentions = "**Bots... |
"""
Argo Workflows API
Argo Workflows is an open source container-native workflow engine for orchestrating parallel jobs on Kubernetes. For more information, please see https://argoproj.github.io/argo-workflows/ # noqa: E501
The version of the OpenAPI document: VERSION
Generated by: https://openapi-g... |
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modif... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2018, I.Laghidze
#
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above co... |
# coding: utf-8
# 2021/7/12 @ tongshiwei
UNK = "[UNK]"
PAD = "[PAD]"
|
import json
import os
import time
import testinfra.utils.ansible_runner
testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(
os.environ['MOLECULE_INVENTORY_FILE']
).get_hosts('instance')
def test_health(host):
args = (
"http",
"--ignore-stdin",
"--check-status",
"-... |
"""Test the main file."""
import logging
from src.jobs.main import jobs_main, spark_build
from src.jobs import extract, transform, load
from pyspark.sql import SparkSession
from pytest_mock import MockFixture
from src.jobs.utils.general import EnvEnum
def test_jobs_called(mocker: MockFixture) -> None:
"""Test th... |
#!/usr/bin/env python3
#PYTHON_ARGCOMPLETE_OK
import enum
import logging
from dataclasses import dataclass, replace
from simple_parsing import Serializable
from typing import Dict, Any
from tqdm.auto import tqdm
import torch as th
from torchvision.transforms import Compose
from torch.utils.tensorboard import SummaryW... |
# GENERATED BY KOMAND SDK - DO NOT EDIT
import insightconnect_plugin_runtime
import json
class Component:
DESCRIPTION = "Get task history"
class Input:
LIMIT = "limit"
SKIP = "skip"
TEAM = "team"
class Output:
TASKS = "tasks"
class GetHistoryInput(insightconnect_plugin_runtime.Input)... |
import datetime
import os
import yaml
# Project config.
project = "LXD"
author = "LXD contributors"
copyright = "2014-%s %s" % (datetime.date.today().year, author)
with open("../shared/version/flex.go") as fd:
version = fd.read().split("\n")[-2].split()[-1].strip("\"")
# Extensions.
extensions = [
"myst_pars... |
"""
Helpers to manipulate deferred DDL statements that might need to be adjusted or
discarded within when executing a migration.
"""
from copy import deepcopy
class Reference:
"""Base class that defines the reference interface."""
def references_table(self, table):
"""
Return whether or not t... |
import pytest
import re
from collections import defaultdict
def get_inputs( filename):
"""
Given sentences in the file, split each sentence using delimiters into parent, children, amount of children
Create dicts that describe the parents of any color, and the children and corresponding amount of any color
... |
from sqlalchemy.testing import eq_, ne_, assert_raises, \
expect_warnings, assert_raises_message
import time
from sqlalchemy import (
select, MetaData, Integer, String, create_engine, pool, exc, util)
from sqlalchemy.testing.schema import Table, Column
import sqlalchemy as tsa
from sqlalchemy.engine import url
... |
#!/usr/bin/python
# Import the required modules
import cv2, os
import numpy as np
from PIL import Image
default_label_name = "Label_default.txt"
default_model_name = "Model_default.yml"
def get_images_and_labels(path):
# Append all the absolute image paths in a list image_paths
# We will not read the image ... |
#!/usr/bin/python3
"""
Flask route that returns json response
"""
from api.v1.views import app_views
from flask import abort, jsonify, request
from models import storage, CNC
@app_views.route('/users/', methods=['GET', 'POST'])
def users_no_id(user_id=None):
"""
users route that handles http requests ... |
from flask_restful import Resource, reqparse
from App.ext import db, cache
from App.models import UserModel
parser = reqparse.RequestParser()
parser.add_argument('u_token',type=str)
class AccountResource(Resource):
#现在
def get(self):
parse = parser.parse_args()
token = parse.get('u_token'... |
# Copyright (C) 2021 Catuserbot <https://github.com/sandy1709/catuserbot>
# Ported by @mrismanaziz
# FROM Man-Userbot <https://github.com/mrismanaziz/Man-Userbot>
# t.me/SharingUserbot & t.me/Lunatic0de
import asyncio
from telethon.errors.rpcerrorlist import YouBlockedUserError
from telethon.tl.functions.contacts imp... |
'''Module tests'''
from hangman import check_letter, print_word, pick_a_new_word
def test_check_letter():
'''Module test by correct work function check_letter'''
assert check_letter('t',
'test',
1,
['e'],
['o']) ==... |
from typing import List
def join_numbers(
integers: List[str],
separator: str = ','
) -> int:
return sum(
[
int(hex_number, 16)
for hex_number in integers
]
)
def join_numbers_using_mapfilter(
integers: List[str],
separator: str = ','
) -> int:
ret... |
# Tau Copyright 2019-2020 The Apache Software Foundation
import asyncio
import datetime
import os
import sys
from collections.abc import Iterable
import asyncpg
import discord
from discord import Object, Permissions
from discord.ext import commands
from discord.utils import oauth_url
import ccp
import config
import ... |
import luigi
import mlflow
import mlflow.sklearn
import pickle
from sklearn.linear_model import LogisticRegression
import time
from src.data.external_train_set import ExternalTrainSet
from src.utils.params_to_filename import encode_task_to_filename
from src.utils.extract_x_y import extract_x_and_y
class TrainBaselin... |
#!/usr/bin/env python
from time import sleep
from pymongo import MongoClient
from proauth2 import Proauth2, Proauth2Error
from proauth2.data_stores import mongo_ds
class TestProauth2():
def setup( self ):
self.proauth2 = Proauth2( mongo_ds.DataStore( 'proauth2_tests' ) )
def teardown( self ):
... |
# Time complexity: O(n)
# Approach: Strip + Split + Return length of last element
class Solution:
def lengthOfLastWord(self, s: str) -> int:
return len(s.strip().split()[-1]) |
# -*- coding: utf-8 -*-
#
# Meta testing tests
from __future__ import absolute_import
from pmdarima.utils.testing import assert_raises
def test_assert_raises():
def raise_value_error():
raise ValueError()
def raise_type_error():
raise TypeError()
def innocuous_function():
pass... |
from typing import Union
import numpy as np
import talib
def beta(candles: np.ndarray, period=5, sequential=False) -> Union[float, np.ndarray]:
"""
BETA - Beta
:param candles: np.ndarray
:param period: int - default: 5
:param sequential: bool - default=False
:return: float | np.ndarray
... |
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
with open('requirements.txt') as f:
install_requires = f.read().strip().split('\n')
# get version from __version__ variable in ibme/__init__.py
from ibme import __version__ as version
setup(
name='ibme',
version=version,
description='Language Ex... |
# Source: https://leetcode.com/problems/valid-parentheses/description/
# Author: Paulo Lemus
# Date : 2017-11-18
# Info : #20, Easy, 49 ms, 92.97%
# Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
#
# The brackets must close in the correct order,... |
"""
This example demonstrates training a simple DNN with tf.estimator using the Determined
Native API.
"""
import argparse
import json
import logging
import os
import pathlib
import tarfile
from typing import Callable, Dict, List, Tuple
import requests
import tensorflow as tf
import determined as det
from determined ... |
"""Module for graph transformation utilities."""
from collections.abc import Iterable, Mapping
from collections import defaultdict
import numpy as np
from scipy import sparse
from ._ffi.function import _init_api
from .base import dgl_warning, DGLError
from . import convert
from .heterograph import DGLHeteroGraph, DGL... |
# Copyright 2015, Aiven, https://aiven.io/
#
# This file is under the Apache License, Version 2.0.
# See the file `LICENSE` for details.
from . import argx, client
from aiven.client import envdefault
from aiven.client.cliarg import arg
from aiven.client.speller import suggest
from collections import Counter
from decima... |
"""The hashing module contains all methods and classes related to the hashing trick."""
import sys
import hashlib
import category_encoders.utils as util
import multiprocessing
import pandas as pd
import math
import platform
__author__ = 'willmcginnis', 'LiuShulun'
class HashingEncoder(util.BaseEncoder, util.Unsuper... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
print("\n")
print("-----迭代-----")
mylist = [1, 2, 3]
for i in mylist:
print(i)
print("\n")
print("-----迭代器,用中括号的叫迭代器-----")
print("任何可以用 for in 来迭代读取的都是迭代容器,例如lists,strings,files.这些迭代器非常的便利")
print("你可以想取多少便取多少,但是你得存储所有的值,其中很多值都完全没有必要每次都保持在内存中")
mylist = [x * x for x in r... |
import numpy as np
def top_k_spans(start_probs, end_probs, n, k):
"""
Returns top k non overlapping spans for a passage
sorted by start/end probabilities
"""
probs = []
argmax_spans = []
for i in range(k + 1):
probs.append([])
argmax_spans.append([])
for j in range(n... |
# Copyright (c) 2012-2018, University of Strathclyde
# Authors: Lawrence T. Campbell & Jonathan Smith (Tech-X UK Ltd)
# License: BSD-3-Clause
"""
This script takes the macroparticle beam files and bins the particles in a
2D mesh in the particle z vs energy phase space, and plots the resulting
density mesh in visit.
... |
from pychord import ChordProgression
from chord_manager_cli.chord_manager import chord_transpose
import pytest
__author__ = "Kevin Chaohwa Chang"
__email__ = "kevin.chaohwa.chang@gmail.com"
@pytest.mark.parametrize("test_chord_transpose_original, expected", [
(["E", "B", "G#", "F#"], ChordProgression(["E", "B", ... |
# Copyright 1997 - 2018 by IXIA Keysight
#
# 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, p... |
import os
from setuptools import setup, find_packages
f = open(os.path.join(os.path.dirname(__file__), 'README.rst'))
readme = f.read()
f.close()
setup(
name='djangoembed',
version='0.1.1',
description='rich media consuming/providing for django',
long_description=readme,
author='Charles Leifer',
... |
#encoding=utf-8
# Данный пример поочерёдно включает и выключает каналы модуля. # * Строки со звёздочкой являются необязательными.
#
from pyiArduinoI2Crelay import * # Подключаем библиотеку для работы с реле и силовыми ключами.
from time import sleep ... |
from django.shortcuts import render
from .models import Blog, BlogCategory
#import pagination stuff
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
# Create your views here.
def Blogview(request):
#Set up Pagination
p = Paginator(Blog.objects.all(), 6)
page = request.GET.get('page... |
from rest_framework import serializers
from profiles_api import models
class HelloSerializer(serializers.Serializer):
"""serializes a name field for testing our APIView"""
name = serializers.CharField(max_length = 10)
class UserProfileSerializer(serializers.ModelSerializer):
"""serializes a user profile"... |
from shipping.modules.productshipping.models import Carrier, CarrierTranslation, ProductShippingPrice
from product.models import Product
from product.admin import ProductOptions
from django.contrib import admin
from django.utils.translation import get_language, ugettext_lazy as _
class CarrierTranslation_Inline(admin.... |
import numpy as dp
import queue
q=queue.Queue()
vertex=0
edge=0
line=0
count=0
#with open('F:\\CSE422\\bfs.txt') as file:
# for line in file:
# print(line.rstrip())
# vertex=line
# Edge=line
# break
arr_zeros=dp.zeros((vertex,vertex),dtype=int)
f=open ("F:\\CSE4... |
# Author: Simon Blanke
# Email: simon.blanke@yahoo.com
# License: MIT License
from ..smb_opt.exp_imp_based_opt import ExpectedImprovementBasedOptimization
from ..smb_opt.surrogate_models import EnsembleRegressor
from sklearn.tree import DecisionTreeRegressor
from sklearn.ensemble import GradientBoostingRegressor
fr... |
"""
Unit tests for ``galaxy.web.framework.webapp``
"""
import logging
import re
import sys
import unittest
import galaxy.config
from galaxy.app_unittest_utils import galaxy_mock
from galaxy.webapps.base import webapp as Webapp
log = logging.getLogger(__name__)
class StubGalaxyWebTransaction(Webapp.GalaxyWebTransac... |
""" REST API module for netbox-plugin-config-officer.""" |
# Copyright (C) 2018 Garth N. Wells
#
# SPDX-License-Identifier: MIT
"""This module provides a model for a monitoring station, and tools
for manipulating/modifying station data
"""
class MonitoringStation:
"""This class represents a river level monitoring station"""
def __init__(self, station_id, measure_id... |
'''Helper Management commands to host Django applications on Windows Servers.
'''
__version_info__ = {
'major': 0,
'minor': 2,
'micro': 0,
'releaselevel': 'final',
'serial': 1
}
def get_version():
"""
Return the formatted version information
"""
vers = ["%(major)i.%(minor)i" % __... |
###############################################################################
#
# Tests for XlsxWriter.
#
# SPDX-License-Identifier: BSD-2-Clause
# Copyright (c), 2013-2022, John McNamara, jmcnamara@cpan.org
#
from ..excel_comparison_test import ExcelComparisonTest
from ...workbook import Workbook
class TestCompar... |
number1 = input('please input number 1')
number2 = input('please input number 2')
number3 = int(number1) * int(number2)
print ( str(number1) , " * " , str(number2) ,' = ', str(number3) ) |
# coding: utf-8
"""
OpenAPI Petstore
This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501
The version of the OpenAPI document: 1.0.0
Generated by: https://openapi-generator.tech
"""
... |
from yowsup.structs import ProtocolEntity, ProtocolTreeNode
class IqProtocolEntity(ProtocolEntity):
'''
<iq type="{{get | set}}" id="{{id}}" xmlns="{{xmlns}}" to="{{TO}}" from="{{FROM}}">
</iq>
'''
TYPE_SET = "set"
TYPE_GET = "get"
TYPE_ERROR = "error"
TYPE_RESULT = "result"
TYPE_D... |
#!/usr/bin/env python
# Python 3 str object for Python 2
import os
import os.path
import time
import math
import logging
import re
import struct
log = logging.getLogger(__name__)
try:
import pymoku.li_capnp as schema
except ImportError:
log.info("No Capnp, won't be able to convert binary files")
class Inva... |
# -*- coding: utf-8 -*-
"""
preprocess input data into feature and stores binary as python shelve DB
each chunk is gzipped JSON string
"""
import argparse
import gzip
import json
import subprocess as sp
import shelve
import os
from os.path import dirname, exists, join
import torch
from lsp_model import GPT2Tokenizer
... |
#!/usr/bin/env python
"""This file defines the entry points for typical installations."""
# pylint: disable=g-import-not-at-top
# Argparse runs on import, and maintains static state.
from __future__ import unicode_literals
from grr_response_core.lib import config_lib
from grr_response_core.lib import flags
def Set... |
from typing import Any, Dict, Optional, Tuple
from .enums import MediaType
class Media:
"""Represents a media attachment in a message."""
__slots__ = ("_payload", "_url", "_preview_image_url", "_media_key", "_type", "_width", "_height")
def __init__(self, data: Dict[str, Any]):
self._payload = ... |
from django.db import models
from django.utils.timezone import now
# Create your models here.
# <HINT> Create a Car Make model `class CarMake(models.Model)`:
# - Name
# - Description
# - Any other fields you would like to include in car make model
# - __str__ method to print a car make object
class CarMake(models.Mo... |
"""Generate model from OpenAPI schema."""
import itertools
import typing
from . import column_factory
from . import exceptions
from . import helpers
from . import table_args
from . import types
from . import utility_base
def model_factory(
*, name: str, base: typing.Type, schemas: types.Schemas
) -> typing.Type... |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... |
import os
import pytest
from app.file_storage import clean_up
class MockFs:
@staticmethod
def listdir():
return ["1.txt", "2.txt", "3.txt"]
@staticmethod
def remove():
return
@pytest.fixture
def mock_setting(monkeypatch):
monkeypatch.setenv("FILE_STORAGE", "tmp")
monkeypat... |
"""
mbed tools
Copyright (c) 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 writing,... |
#!/usr/bin/env python
"""
Handle loading the correct C library.
Hazen 11/14
"""
import ctypes
import sys
import os
import re
import storm_analysis
def loadCLibrary(library_filename):
#
# This assumes that all the code that will call C modules is one level
# below the root storm_analysis directory.
... |
'''@file feature_computer.py
contains the FeatureComputer class'''
from abc import ABCMeta, abstractmethod
class FeatureComputer(object):
'''A featurecomputer is used to compute features'''
__metaclass__ = ABCMeta
def __init__(self, conf):
'''
FeatureComputer constructor
Args:
... |
# -*- coding: utf-8 -*-
"""
This code is auto generated from troposphere_mate.code_generator.__init__.py scripts.
"""
import sys
if sys.version_info.major >= 3 and sys.version_info.minor >= 5: # pragma: no cover
from typing import Union, List, Any
import troposphere.detective
from troposphere import Template,... |
#!/usr/bin/env python
import time
import random
import json
from kubernetes import client, config, watch
config.load_kube_config()
v1=client.CoreV1Api()
scheduler_name = "foobar"
def nodes_available():
ready_nodes = []
for n in v1.list_node().items:
for status in n.status.conditions:
... |
# -*- coding: utf-8 -*-
'''
from github import Github
g = Github()
repository = 'https://github.com/python/python-docs-fr'
repoOrg = g.get_organization('python')
# for x in dir(repo): print(x)
repo = repoOrg.get_repo('python-docs-fr')
for x in dir(repo): print(x)
x = repo.get_issues(state='closed')
print(len(list(x)... |
"""inline_tags
Revision ID: a92d92aa678e
Revises: e7004224f284
Create Date: 2018-05-10 15:41:28.053237
"""
import re
from funcy import flatten, compact
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
from redash import models
# revision identifiers, used by Alembic.
revision... |
import unittest
from app.models import User
class UserModelTest(unittest.TestCase):
def setUp(self):
self.new_user = User(password = 'banana')
def test_password_setter(self):
self.assertTrue(self.new_user.pass_secure is not None)
def test_no_access_password(self):
with ... |
"""
This code was modified from the GCN implementation in DGL examples.
Simplifying Graph Convolutional Networks
Paper: https://arxiv.org/abs/1902.07153
Code: https://github.com/Tiiiger/SGC
SGC implementation in DGL.
"""
import argparse, time, math
import numpy as np
import torch
import torch.nn as nn
import torch.nn.f... |
import sys
from . import main
sys.exit(main.main())
|
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.decomposition import PCA
data = pd.read_excel(r"Concrete_Data.xls")
req_col_names = ["Cement", "BlastFurnaceSlag", "FlyAsh", "Water", "Superplasticizer",
"CoarseAggregate", "FineAggregate", "Age", ... |
"""
Copyright (c) 2017, 2018, 2019 Red Hat, Inc
All rights reserved.
This software may be modified and distributed under the terms
of the BSD license. See the LICENSE file for details.
get the image manifest lists from the worker builders. If possible, group them together
and return them. if not, return empty dict af... |
from flask import Flask, jsonify, request
from cashman.model.expense import Expense, ExpenseSchema
from cashman.model.income import Income, IncomeSchema
from cashman.model.transaction_type import TransactionType
app = Flask(__name__)
transactions = [
Income('Salary', 5000),
Income('Dividends', 200),
Expe... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.