content stringlengths 5 1.05M |
|---|
from django.db import models
class LongLivedAccessToken(models.Model):
access_token = models.CharField(max_length=500, primary_key=True, null=False, default=None)
token_type = models.CharField(max_length=500)
expires_in = models.DateField(default=False)
date_created = models.DateField(default=False)
... |
__all__ = ["get_config"]
|
from io import BytesIO
from typing import List, Optional
from typing_extensions import Self
import requests
from helper import (
encode_varint,
hash256,
int_to_little_endian,
little_endian_to_int,
read_varint,
SIGHASH_ALL
)
from script import Script
from ecc import PrivateKey
class Tx:
... |
# -*- coding: utf-8 -*-
"""Boilerplate:
A one line summary of the module or program, terminated by a period.
Rest of the description. Multiliner
<div id = "exclude_from_mkds">
Excluded doc
</div>
<div id = "content_index">
<div id = "contributors">
Created on Fri Aug 27 17:25:06 2021
@author: Timothe
</div>
"""
f... |
import ibmsecurity.utilities.tools
module_uri="/isam/felb/configuration/services/"
requires_modulers=None
requires_version=None
def get(isamAppliance, service_name, check_mode=False, force=False):
"""
Retrieves layer configuration
"""
return isamAppliance.invoke_get("Retrieving Layer Configuration", ... |
import typing
from typing import Iterable, Optional
from .utils.meta import roundrepr
from .xref import Xref
__all__ = ["Definition"]
class Definition(str):
"""A human-readable text definition of an entity.
Definitions are human-readable descriptions of an entity in the ontology
graph, with some option... |
from django.shortcuts import render, redirect
from apps.session.models import UserProfile, Group, GroupMessage
from django.contrib.auth.decorators import login_required
@login_required(login_url='/session/login/')
def make_group(request):
if request.method != "POST":
return render(request, 'session/make_g... |
from django.http.response import HttpResponse
class PandasJsonResponse(HttpResponse):
"""
An easier way to return a json encoded response from
'Pandas.to_dataframe().to_json()' object
"""
def __init__(self, data, **kwargs):
data = data.reset_index().to_json(orient='records', date_format='... |
import requests
from . import FeedSource, _request_headers
class Coincap(FeedSource):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.nb_coins_included_in_altcap_x = getattr(self, 'nb_coins_included_in_altcap_x', 10)
def _fetch(self):
feed = {}
base... |
# -*- encoding: utf-8 -*-
"""Parser Module.
This module is an interface to the functionalities of pycpasrer,
a Python implementation of a parser for C99 source code. The
pycparser implementation used here is a forked version from
the original one.
.. _Google Python Style Guide:
https://github.com/DonAurelio/pycpa... |
# 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)
# This is a partial copy of Spack Gromacs package
# - modified URL and versions
# - removed Plumed patches
# - calling ori... |
#!/usr/bin/env python3
#Author: Stefan Toman
def is_leap(year):
#custom code starts here
if year % 4 != 0:
return False
if year % 400 == 0:
return True
if year % 100 == 0:
return False
return True
#custom code ends here
if __name__ == '__main__':
year = int(input()... |
# This file is part of sner4 project governed by MIT license, see the LICENSE.txt file.
"""
scheduler.views.queue tests
"""
import json
from http import HTTPStatus
from pathlib import Path
from flask import url_for
from sner.server.scheduler.models import Job, Queue
def test_queue_list_route(cl_operator):
"""q... |
import tensorflow as tf
from voxelgan.loss import generator_loss, discriminator_loss
from voxelgan.optimizer import Optimizer
import numpy as np
class Latent(tf.keras.Model):
'''
The latent
'''
def __init__(self, d) -> None:
super(Latent, self).__init__(name='')
self.input_layer = tf.keras.layers.Input(shape=... |
from pycoin.coins.bcash.Tx import Tx as BcashTx
from pycoin.networks.bitcoinish import create_bitcoinish_network
network = create_bitcoinish_network(
symbol="BCH",
network_name="Bitcoin",
subnet_name="mainnet",
tx=BcashTx,
wif_prefix_hex="80",
sec_prefix="BCHSEC:",
address_prefix_hex="00",
... |
#!/usr/bin/python3
class Config:
"""A class to define how to scan the JSON file"""
@classmethod
def get_configuration(cls):
dict = [
{
"name":"experiments",
"path":["experiments"],
"type":"list",
"sheetName":"Metadata"... |
"""
a)
State Representation: (c1(liters), c2(liters))
Initial State: (0,0)
(Preconds behind the state change)
Operators: (x != 4) fillc1 -> (x, c2_l) => (4, c2_l)
(x != 3) fillc2 -> (c1_l, x) => (c1_l, 3)
(x != 0) emptyc1 -> (x, c2_l) => (0, c2_l)
(x != 0) emptyc2 -> (c1_l, x) => (c1_l... |
from django.conf import settings
from storages.backends.s3boto import S3BotoStorage
class S3MediaStorage(S3BotoStorage):
def __init__(self, *args, **kwargs):
self.bucket_name = settings.AWS_MEDIA_BUCKET_NAME
super(S3MediaStorage, self).__init__(*args, **kwargs)
|
from setuptools import setup
setup(
name='slackython',
version='1.0.0',
packages=[''],
url='https://github.com/Michotastico/slackython',
license='MIT',
author='Michel Llorens',
author_email='mllorens@dcc.uchile.cl',
description='Python library to send slack messages using webhooks ',
... |
# Copyright Contributors to the Amundsen project.
# SPDX-License-Identifier: Apache-2.0
from enum import Enum
from typing import Optional
class Priority(Enum):
P0 = ('P0', 'Blocker')
P1 = ('P1', 'Critical')
P2 = ('P2', 'Major')
P3 = ('P3', 'Minor')
def __init__(self, level: str, jira_severity: s... |
# Connect Four, by Al Sweigart al@inventwithpython.com
import sys
assert sys.version_info.major == 3, 'Run this program on Python 3.'
EMPTY_SPACE = '.'
X_PLAYER = 'X'
O_PLAYER = 'O'
def getNewBoard():
# Note: The board is 7x6, represented by a dictionary with keys
# of (x, y) tuples from (0, 0) to (6, 5), an... |
# -*- coding: utf-8 -*-
#
# Copyright 2012-2015 Spotify AB
#
# 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... |
import torch
from torch import nn, optim
import numpy as np
from util import np_to_cuda
class RandomWD(nn.Module):
def __init__(self, feat_dim, obs_space, act_space, sigma=1., gamma=1., lr=1e-3):
super(RandomWD, self).__init__()
self.feat_dim = feat_dim
self.rf_W = torch.randn((obs_space.s... |
import numpy as np
from regression.base import predict_output
def feature_derivative_ridge(
errors: np.ndarray, feature: np.ndarray, weight: np.ndarray, l2_penalty: float, feature_is_constant: bool = False
) -> np.ndarray:
"""
Compute the derivative of the regression cost function w.r.t L2 norm.
If ... |
from django.db import models, migrations
import lti.utils
class Migration(migrations.Migration):
dependencies = [
('lti', '0007_auto_20170410_0552'),
]
operations = [
migrations.AlterField(
model_name='lticonsumer',
name='consumer_key',
field=models.Ch... |
from datetime import datetime
from typing import (
Any,
Dict,
Iterator,
Optional,
Text,
)
from pynamodb.attributes import (
ListAttribute,
NumberAttribute,
MapAttribute,
UnicodeAttribute,
UTCDateTimeAttribute,
)
from pynamodb.models import Model
from pynamodb.indexes import Glob... |
# Copyright 2021 Peng Cheng Laboratory (http://www.szpclab.com/) and FedLab Authors (smilelab.group)
# 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/LICEN... |
result = (*(x**2 for x in range(5)),)
print(result)
|
"""
ServerService tests.
To run a single test, modify the main code to::
singletest = unittest.TestSuite()
singletest.addTest(TESTCASE("<TEST METHOD NAME>"))
unittest.TextTestRunner().run(singletest)
| Copyright 2017-2022, Voxel51, Inc.
| `voxel51.com <https://voxel51.com/>`_
|
"""
import asyncio
from co... |
def add_argument(parser):
# Client settings
parser.add_argument('--host', default='127.0.0.1')
parser.add_argument('--port', type=int, default=2000)
parser.add_argument('--tm_port', type=int, default=8000)
parser.add_argument('--timeout', type=float, default=5.0)
def from_args(args):
import c... |
from django.http import HttpRequest, HttpResponse
from main.util import render_template
TEMPLATE = "tasks/lesson03/task301.html"
def handler(request: HttpRequest) -> HttpResponse:
name = request.GET.get("name")
context = {
"input_name": name,
"greeting_name": name or "anonymous",
}
... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
import six
from django.utils.html import escape
from sentry.models import Activity, User, Event
ICON = 'https://sentry-hipchat-ac-assets.s3.amazonaws.com/sentry-icon.png'
ICON2X = 'https://sentry-hipchat-ac-assets.s3.amazonaws.com/sentry-icon.png'
ICON_... |
#!/usr/bin/env python3
# Copyright 2021 Yoshi Kadokawa
# See LICENSE file for licensing details.
#
# Learn more at: https://juju.is/docs/sdk
"""Charm the service.
Refer to the following post for a quick-start guide that will help you
develop a new k8s charm using the Operator Framework:
https://discourse.charmhu... |
from tkinter import *
from tkinter.filedialog import askopenfilename
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from tkinter.messagebox import *
rows = 0 #记录数
page_num = 0 #总页数
page_idx = 0 #当前页数
page_show = 25 #每页记录数
arr = np.ones(6)
stock_df = pd.DataFrame(arr) #DataFr... |
from django.conf.urls import url
from . import views
urlpatterns = (
url(r'^$', views.view_content, {'template': 'multicol'}),
url(r'^watch/$', views.view_content, {'template': 'multicol'}),
url(r'^listen/$', views.view_content, {'template': 'multicol'}),
url(r'^read/$', views.view_content, {'templat... |
import youtokentome
import codecs
import os
import torch
from random import shuffle
from itertools import groupby
from torch.nn.utils.rnn import pad_sequence
class SequenceLoader(object):
"""
An iterator for loading batches of data into the transformer model.
For training:
Each batch contains to... |
# http://multivax.com/last_question.html
import logging
import sys
from os.path import basename, exists, join, splitext
from adles.args import parse_cli_args
from adles.interfaces import PlatformInterface
from adles.parser import check_syntax, parse_yaml
from adles.utils import handle_keyboard_interrupt, setup_loggin... |
somaI = 0
for c in range(1, 501, 2):
if (c % 3 == 0):
somaI += c
print(somaI)
|
# This file is referred and derived from project NetworkX
#
# which has the following license:
#
# Copyright (C) 2004-2020, NetworkX Developers
# Aric Hagberg <hagberg@lanl.gov>
# Dan Schult <dschult@colgate.edu>
# Pieter Swart <swart@lanl.gov>
# All rights reserved.
#
# This file is part of NetworkX.
#
# NetworkX is d... |
# Copyright 2019 The Cloud Robotics 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 law or agreed... |
from flask_restplus import Namespace,Resource,fields,reqparse
import Crypto
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
from Crypto import Random
from core import Configs
import pickle
import json
from flask import send_file
import ast
api = Namespace('public_key_exchange_api',description = ... |
from arm.logicnode.arm_nodes import *
class SeparateVectorNode(ArmLogicTreeNode):
"""Splits the given vector into XYZ values."""
bl_idname = 'LNSeparateVectorNode'
bl_label = 'Separate XYZ'
arm_section = 'vector'
arm_version = 1
def init(self, context):
super(SeparateVectorNode, self).... |
import string
import sys
import uuid
from dataclasses import dataclass
from random import choices
from typing import (
Any,
Dict,
List,
Optional,
TYPE_CHECKING,
Tuple,
Type,
Union,
overload,
)
import sqlalchemy
from pydantic import BaseModel, create_model
from pydantic.typing import... |
from sanic import Sanic
from sanic.response import json, file
app = Sanic()
app.static('/', '../dist')
@app.route("/")
async def index(request):
return await file('dist/index.html')
@app.route("/example_post", methods=["POST",])
def create_user(request):
return text("POST data: %s" % request.body)
@app.rou... |
"""
获取youtube视频下的评论
思路:
基于youtube官方的API来获取, 这里是关于如何初始化配置的文档 https://developers.google.com/youtube/v3/getting-started
评论接口文档:https://developers.google.com/youtube/v3/docs/channelSections/list
任意视频地址:https://www.youtube.com/watch?v=FWMIPukvdsQ
"""
import requests
# 在 API Console 配置生成
key = "AIzaSyCtJuC7oMed0xxZYPcid9... |
# (C) Datadog, Inc. 2018-present
# All rights reserved
# Licensed under a 3-clause BSD style license (see LICENSE)
import os
from datadog_checks.base.utils.platform import Platform
CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))
DRIVER_CONFIG_DIR = os.path.join(CURRENT_DIR, 'data', 'driver_config')
def set... |
import pytest
from api.models.utils import rankings
@pytest.fixture
def test_data():
return [1, 11, 101]
def test_rankings(test_data):
"""Tests if ranking works
e.g. 1 returns 1st
11 returns 11th
101 return 101st
"""
assert rankings(test_data[0]) == "1st"
assert rankings(t... |
# Copyright 2015 Google 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 writing, ... |
import logging
import sys
from optparse import make_option
from django.core.management.base import BaseCommand
from celery.task.sets import TaskSet
import amo
from lib.crypto.packaged import sign
from mkt.webapps.models import Webapp
HELP = """\
Start tasks to re-sign web apps.
To specify which webapps to sign:
... |
"""
EBAS IO Setup Instructions: https://git.nilu.no/ebas/ebas-io/-/wikis/home
For my own purposes, I've cloned the ebas-io repository here, and installed with:
pip install ebas-io/dist/ebas_io-3.5.1-py3-none-any.whl
""" |
#!/usr/bin/python
#
# -*- coding: utf-8 -*-
# vim: set ts=4 sw=4 et sts=4 ai:
"""Connect to the streamti.me server and report our stats."""
__author__ = "mithro@mithis.com (Tim 'mithro' Ansell)"
import datetime
import json
import time
import urllib
import urllib2
import argparse
parser = argparse.ArgumentParser()
p... |
# -*- coding: utf-8 -*-
from python_lessons.fixture.group import *
def test_add_group(app, db, json_groups):
group = json_groups
old_groups = db.get_group_list()
app.group.create(group)
new_groups = db.get_group_list()
old_groups.append(group)
sorted_old = sorted(old_groups, key=Group.id_or_ma... |
import os
from pprint import pprint
import numpy as np
import mxnet as mx
import logging
print "testing global optimizer"
class GlobalOptimizer(mx.optimizer.Optimizer):
"""A GlobalOptimizer for the master parameter server.
Parameters
----------
learning_rate : float, optional
learning_rate... |
from mongoengine import connect
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/dev/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '-'
# SECURITY WARNING: don't run with debug turned on in production!... |
from sklearn.linear_model import LinearRegression
import numpy as np
import torch
import pickle
import joblib
import time
import os.path
from os import path
from training.baseline import baseline_inpute
from utils.utils import construct_missing_X_from_mask
def linear_regression(data, args, log_path, load_path):
t... |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from flask import Flask
from sklearn.model_selection import train_test_split
from sklearn.metrics import r2_score, mean_squared_error
from sklearn.preprocessing import MinMaxScaler
from sklearn.neighbors import KNeighborsRegres... |
# -*- coding: utf-8 -*-
from twitter.stream import TwitterStream
from utils.singleton import Singleton
class StreamsHandler(metaclass=Singleton):
""" Represents a streams handler object """
def __init__(self):
""" Creates a streams handler singleton """
self.streams = {}
@staticmethod
def build_ke... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# pylint: disable-msg=no-member
# pylint: disable-msg=arguments-differ
# pylint: disable-msg=import-error
"""
RCNN_model.py is a module for RCNN model
"""
import torch
from torch import nn
import torch.nn.functional as F
__author__ = "Ehsan Tavan"
__organization__ = "Pe... |
from collections import namedtuple
from contextlib import contextmanager, ExitStack
from functools import partial
from typing import ContextManager, Callable, Any, TypeVar, overload
from ._async_value import AsyncValue
def _IDENTITY(x):
return x
T_OUT = TypeVar('T_OUT')
@overload
def compose_values(**value_m... |
from __future__ import absolute_import
from django.core.urlresolvers import reverse
from sentry.testutils import APITestCase
class OrganizationMemberListTest(APITestCase):
def setUp(self):
self.user_1 = self.create_user('foo@localhost', username='foo')
self.user_2 = self.create_user('bar@localho... |
import sys, os.path
sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), '..'))
import os.path
from collections import defaultdict, namedtuple
from mpl_toolkits.basemap import Basemap
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
import matplotlib.pyplot as plt
import py1... |
import pytest
from sqload import load
@pytest.fixture
def q():
return load('tests/queries.sql')
def test_load_all_queries(q):
assert len(q.keys()) == 3
def test_get_query_by_key(q):
assert q['find-all-by-name'] == 'SELECT * FROM users WHERE name = :name'
def test_clean_multiple_lines(q):
sql = 'SEL... |
import sys
from pyteal import *
def contract_account(app_id):
asset_close_to_check = Txn.asset_close_to() == Global.zero_address()
rekey_check = Txn.rekey_to() == Global.zero_address()
linked_with_app_call = And(
Gtxn[0].type_enum() == TxnType.ApplicationCall,
Gtxn[0].application_id() == ... |
import csv
import s2sphere # https://s2sphere.readthedocs.io/en/latest/index.html
import math
import datetime
import numpy
import matplotlib.pyplot as plot
import time
import pyproj as proj
print('NodeExtractor started...')
# general parameters
# minimum frequency-peak to number-of-transmissions rate used in Timo's... |
# -*- coding: utf-8 -*-
import os
from django.test import TestCase
from accounts.factories import CustomUserFactory
from projects.factories import ProjectFactory, ProjectVolumeFactory, ProjectReleaseFactory, ProjectBuildFactory
from projects.models import ProjectVolume
class MarathonAppMixinTest(TestCase):
def t... |
from django.contrib import admin
# Register your models here.
from .models import *
admin.site.register(Question)
admin.site.register(Choice)
admin.site.register(Address)
admin.site.register(PersonalInfo)
admin.site.register(WorkInfo)
admin.site.register(Insignia)
admin.site.register(Education)
admin.site.register(N... |
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from .models import RunResultsModel, ManifestModel, SourcesModel, CatalogModel
class ArtifactReader:
@property
def run_results_artifact(self) -> "RunResultsModel":
"""A reference to the :class:`RunResults` artifact."""
return self.get_a... |
#/usr/bin/python3
#-*- coding: utf-8 -*-
import serial
try:
from geopy.geocoders import Nominatim
geo=True
except:
geo=False
class GpsNeo6():
"""
class de gestion du soc NEO 6M
"""
def __init__(self,port,debit=9600,diff=1):
"""
on initialise les variables... |
'''crie um programa que leia dois valores e mostre um menu:
[1] - somar, [2] - multiplicar, [3] - maior, [4] - novos números, [5] - sair'''
print('{:-^40}'.format('CALCULADORA'))
flag = 5
cont = maior = menor = 0
while flag == 5:
num_1 = int(input('Digite o primeiro número: '))
num_2 = int(input('Digite o segundo núm... |
import logging
import copy
from threading import Thread
from Queue import Queue
class Migrator(object):
def __init__(self, source_registry, artifactory_access, work_queue, workers, overwrite, dir_path):
self.log = logging.getLogger(__name__)
self.source = source_registry
self.target = artif... |
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from dl_classification_model import config,predict
from dl_classification_model import __version__ as _version
def test_single_make_prediction():
""" Test make_prediction function for a single prediction """
# Given
... |
# coding=utf-8
from OTLMOW.OTLModel.BaseClasses.OTLAttribuut import OTLAttribuut
from abc import abstractmethod
from OTLMOW.OTLModel.Classes.Detectie import Detectie
from OTLMOW.OTLModel.Datatypes.DtcAfmetingBxlInM import DtcAfmetingBxlInM
from OTLMOW.OTLModel.Datatypes.DtcTijdsduur import DtcTijdsduur
# Generated wi... |
"""
Copyright (C) 2018-2020 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 i... |
# Faça um programa para uma loja de tintas. O programa deverá pedir o tamanho em metros quadrados da área
# a ser pintada. Considere que a cobertura da tinta é de 1 litro para cada 3 metros quadrados e que a tinta é
# vendida em latas de 18 litros, que custam R$ 80,00. Informe ao usuário a quantidades de latas de ti... |
# Generated by Django 2.1.9 on 2019-08-27 08:24
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('resources', '0079_reservation_extra_questions'),
]
operations = [
migrations.AlterModelOptions(
name='resourcegroup',
... |
from __future__ import absolute_import, division, print_function, unicode_literals
import tensorflow as tf
from tensorflow import keras
from tensorflow.python.client import device_lib
import pre_process_data as pre_data
from keras.callbacks import ModelCheckpoint
import tensorflow_datasets as tfds
import keras
from ker... |
# Copyright 2017 The Bazel 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... |
import hypothesis.extra.numpy as hnp
import hypothesis.strategies as st
import numpy as np
from hypothesis import given
from numpy.testing import assert_allclose
from pytest import raises
from mygrad._utils import reduce_broadcast
from tests.custom_strategies import broadcastable_shape
def test_bad_gradient_dimensio... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Command line utility to parse/report on apache log files.
See: https://github.com/bedge/sqalp/blob/master/README.rst
"""
from __future__ import division, print_function, absolute_import
import argparse
import logging
import re
import sys
from collections import Ordere... |
import sys, getopt, os, json, fnmatch, pprint
#from urllib.request import urlopen, Request
from metacat.util import to_bytes, to_str, TokenLib, epoch
from metacat.webapi import MetaCatClient
import datetime
Usage = """
Usage:
metacat dataset <command> [<options>] ...
Commands and options:
... |
A_33_01_10 = {0: {'A': 0.212, 'C': -0.068, 'E': -0.226, 'D': -0.379, 'G': 0.336, 'F': -0.4, 'I': -0.063, 'H': 0.04, 'K': 0.471, 'M': -0.473, 'L': 0.068, 'N': -0.161, 'Q': 0.078, 'P': 0.401, 'S': -0.051, 'R': 0.324, 'T': -0.023, 'W': -0.034, 'V': 0.151, 'Y': -0.201}, 1: {'A': 0.055, 'C': 0.331, 'E': 0.232, 'D': 0.573, '... |
from tests.data.book_data import BOOKS
from tests.data.library_data import LIBRARIES
from tests.data.library_book_data import LIBRARY_BOOKS, LIBRARY_BOOKS_API
|
import getpass
import os
import configparser
import tableauserverclient as TSC
import argparse
serverObject=""
def exit():
return "exit"
def help():
return ""
def downloadResource(): # TODO HERE: make the function check if the file exists or not
path = r'.\download'
resourceType=""
resourceName=... |
#!/usr/bin/env python
###########################################
# 提供 pyape 初始化的命令行工具
###########################################
import shutil
from pathlib import Path
from pkg_resources import resource_filename
import click
from pyape.tpl import create_from_jinja
basedir = Path(resource_filename('pyape', '__ini... |
# coding=utf-8
# Copyright 2019 The Trax 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 law or a... |
# Bluerred Image Detection
#
# Author: Jasonsey
# Email: 2627866800@qq.com
#
# =============================================================================
"""read training data set from training path"""
import sys
import asyncio
from pathlib import Path
import pickle
import numpy as np
from PIL import Image
from ... |
# Essential imports
import os, sys, re
import pathlib
from .utils import *
# AWS Related imports
import boto
import boto.s3.connection
from boto.s3.key import Key
from boto.exception import NoAuthHandlerFound
bucket = None
bucket_name_final = None
# Command line related imports
import click
import emoji
from pyfiglet... |
# -*- coding: utf-8 -*-
# Resource object code
#
# Created by: The Resource Compiler for PyQt5 (Qt v5.15.2)
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore
qt_resource_data = b"\
\x00\x00\x09\xab\
\x00\
\x00\x54\x9e\x78\x9c\xed\x9c\x6f\x8c\x9c\x45\x1d\xc7\x67\xf7\xb9\
\xb2\x5c\x09\x... |
class filters:
def __init__(self):
self.filters = {}
def set (self, name, function):
if not name in self.filters:
self.filters[name] = []
self.filters[name].append(function)
else:
self.filters[name].append(function)
def get (self, name):
... |
import os
import tarfile
import pickle
__author__ = "Marcin Stachowiak"
__version__ = "1.0"
__email__ = "marcin.stachowiak.ms@gmail.com"
def check_if_file_exists(path):
return(os.path.exists(path))
def create_dir_if_not_exists(path):
if not os.path.exists(path):
os.makedirs(path)
def unpack(path):
... |
"""
write2csv.py
Writes adjacency, chemical and electrical networks to edgelist file.
created: Christopher Brittin
date: 01 November 2018
Synopsis:
python paper_figures figNum [fout]
Parameters:
db (str): Database name
fout (str) : Path to output file
"""
import argparse
import networkx as nx
from conne... |
#!/usr/bin/python
from __future__ import (absolute_import, division, print_function)
# Copyright 2019 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 the Lic... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Wrapper class for ``museval`` implementation of the BSS-Eval metrics (SDR, SIR, SAR).
Contains logic for loading ground truth AudioSignals and estimated
AudioSignals to compute BSS-Eval metrics. The ``mir_eval`` module contains an
implementation of BSS-Eval version 4.
"... |
import re
import yaml
import shlex
import logging
import subprocess
from libla.Extractors import RegularExtractor, UsnExtractor
class ArtifactMapping(object):
def __init__(self):
self._mapping = {}
def set_handler(self, name, handler):
self._mapping[name] = handler
@staticmethod
def ... |
#
import math
#
from steelpy import Formulas
from steelpy import Units
from steelpy import Materials
from steelpy import Sections
#
formulas = Formulas()
units = Units()
#
# -----------------------------------
# Define sections
section = Sections()
#
Dp = 219.10 * units.mm
tp = 14.3 * units.mm
section = Sections()
sect... |
#DeepPasta data examination with same methods for same regions and truth values
from __future__ import print_function
import keras
from keras.models import Sequential, Model, load_model
from keras import backend as K
import tensorflow as tf
import isolearn.keras as iso
import os
import pandas as pd
import numpy as n... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
import numpy as np
class Trainer(object):
def __init__(self, data_manager, model, flags):
self.data_manager = data_manager
self.model = mode... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
def dfs(root):
... |
from django.contrib import admin
from apps.ventas.models import todo_item, Cabecera_Venta
class medicamento_ventaInline(admin.TabularInline):
model = todo_item
class Detalle_VentaAdmin(admin.ModelAdmin):
inlines = (medicamento_ventaInline,)
admin.site.register(Cabecera_Venta, Detalle_VentaAdmin) |
from flask import Flask, render_template, request, url_for
import requests
import json
app = Flask(__name__)
def weather_Forecast(self):
city=self
apiKey='YOUR_API_KEY' #https://home.openweathermap.org/users/sign_up
response= requests.get(f'http://api.openweathermap.org/data/2.5/weather?q={... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.