content stringlengths 5 1.05M |
|---|
'''
0. 问大家一个问题:Python 支持常量吗?相信很多鱼油的答案都是否定的,
但实际上 Python 内建的命名空间是支持一小部分常量的,比如我们熟悉的
True,False,None 等,只是 Python 没有提供定义常量的直接方式而已。
那么这一题的要求是创建一个 const 模块,功能是让 Python 支持常量。
说到这里大家可能还是一头雾水,没关系,我们举个栗子。
test.py 是我们的测试代码,内容如下:
# const 模块就是这道题要求我们自己写的
# const 模块用于让 Python 支持常量操作
import const
const.NAME = "FishC... |
from Utils.menu import Resto
items = {
1: 3.50,
2: 2.50,
3: 4.00,
4: 3.5,
5: 1.75,
6: 1.50,
7: 2.25,
8: 3.75,
9: 1.25
}
def total(order):
item = [int(n) for n in order]
totals = 0
for unit in item:
totals += items.get(unit)
return totals
cont = int(input(... |
__licence__ = 'MIT'
__author__ = 'kuyaki'
__credits__ = ['kuyaki']
__maintainer__ = 'kuyaki'
__date__ = '2021/03/23'
from collections import defaultdict
from typing import Dict, Optional, Set, List, Iterable
import networkx
from program_slicing.graph.parse import parse, Lang
from program_slicing.graph.cdg import Con... |
'''
Have you got what it takes to be the fuzzbizzard..."
A number will be displayed you have to guess if in a FizzBuzz
the number will be displayed normally or will it show Fizz, Buzz or FizzBuzz!
Enter 0 for normal number
Enter 1 for Fizz
Enter 2 for Buzz
Enter 3 for FizzBuzz
Y... |
"""Module for GitHub webhook functionality."""
from typing import Optional
import sys
import tempfile
from string import Template
from urllib.parse import urlsplit
from threading import Timer
import github.PullRequest as ghp # type: ignore
from github import Github
import pygit2
from pyramid.interfaces import IRespon... |
import logging
import random
import os
from unittest import TestLoader, TestSuite
import unittest.util
from exchangelib.util import PrettyXmlHandler
class RandomTestSuite(TestSuite):
def __iter__(self):
tests = list(super().__iter__())
random.shuffle(tests)
return iter(tests)
# Execute ... |
'''
Get's the file's name from the user
'''
def get_file_name() -> str:
filename = ''
while filename == '':
filename = input("Please enter the name of the Python file you wish to obfuscate: ")
return filename
'''
Opens the file the use wants and returns a
string(?) of all the contents of that file
'''
def get_fi... |
import contextlib
import os
import textwrap
from libqtile.backend.wayland.core import Core
from test.helpers import Backend
wlr_env = {
"WLR_BACKENDS": "headless",
"WLR_LIBINPUT_NO_DEVICES": "1",
"WLR_RENDERER_ALLOW_SOFTWARE": "1",
"WLR_RENDERER": "pixman",
"XDG_RUNTIME_DIR": "/tmp",
}
@contextl... |
#!/usr/bin/python
import os
import sys
import signal
import json
import yfinance as yf
import pandas as pd
import math
import argparse
from datetime import datetime
import matplotlib.pyplot as plt
import numpy as np
g_StocksDB = None
def Load(filename):
if os.path.isfile(filename) is True:
file = open(filename, "r... |
from datetime import datetime
from time import sleep
from celery import shared_task
from celery.exceptions import Reject
from django.db import connections
from django.db.models import Prefetch
from django.utils import timezone
from elasticsearch import ElasticsearchException
from elasticsearch.helpers import BulkIndex... |
#!/usr/bin/env python
# -*- coding: utf8 -*-
"""A script to ensure that our docs are not being utterly neglected."""
import argparse
import os
import sys
IGNORES = {
'pydir': ['tests'],
'pyfile': ['__init__.py'],
'docfile': ['index.rst'],
}
class AddDocIgnores(argparse.Action):
"""Add entries to docf... |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
Convenience functions for `astropy.cosmology`.
"""
from .core import get_current as _get_current
def kpc_comoving_per_arcmin(z, cosmo=None):
""" Separation in transverse comoving kpc corresponding to an
arcminute at redshift `z`.
Paramet... |
# Python - 3.6.0
test.assert_equals(areYouPlayingBanjo('martin'), 'martin does not play banjo')
test.assert_equals(areYouPlayingBanjo('Rikke'), 'Rikke plays banjo')
|
# Generated by Django 3.1.4 on 2020-12-30 17:51
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 argparse
import os
import random
import cv2
import numpy as np
import torch
import torch.backends.cudnn as cudnn
from data import cfg_mnet, cfg_re50
from layers.functions.prior_box import PriorBox
from models.retinaface import RetinaFace
from utils.box_utils import decode
from utils.nms.py_cpu_nms import py_cp... |
from rest_framework.permissions import BasePermission
from acls.business.fields import AclLevelField
from acls.business.permissions import has_object_acl
class CanManageSecretPermission(BasePermission):
def has_object_permission(self, request, view, obj):
if view.action == 'retrieve' or view.action == '... |
from django.core.mail import EmailMultiAlternatives
from django.test import TestCase
from django.test import override_settings
from ai_django_core.mail.backends.whitelist_smtp import WhitelistEmailBackend
@override_settings(EMAIL_BACKEND='ai_django_core.mail.backends.whitelist_smtp.WhitelistEmailBackend',
... |
import json
import os
import sys
import time
import msvcrt
from pick import pick
from termcolor import cprint, colored
from extractor import Extractor
path_to_config = "./config.json"
def extract_data():
config = get_config(path_to_config)
extractor = Extractor(config, restart)
raw_data = extractor.... |
from zenoh_service.core.zenoh_native import ZenohNative
import numpy as np
import time
from datetime import datetime
import logging
###
L = logging.getLogger(__name__)
###
class ZenohNativeGet(ZenohNative):
def __init__(self, _listener=None, _mode="peer", _selector=None, _peer=None, _session_type=None,
... |
# RUN: %PYTHON %s 2>&1 | FileCheck %s
# This file contains simple test cases that combine various codegen options.
from mlir.sandbox.experts import *
from mlir.sandbox.harness import *
from mlir.sandbox.transforms import *
from .definitions import *
fun_name = 'padded_conv1d_nwc_wcf_main'
op_name = 'linalg.conv_1d_... |
import asyncio
import collections
import unittest
from unittest import mock
from aiohttp.multidict import CIMultiDict
from aiohttp.web import Request
from aiohttp.protocol import RawRequestMessage, HttpVersion11
from aiohttp import web
class TestHTTPExceptions(unittest.TestCase):
def setUp(self):
self.l... |
# coding=utf-8
# Copyright 2022 The Google Research 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 applicab... |
# Copyright (C) 2017 MongoDB Inc.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License, version 3,
# as published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARR... |
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 25 16:20:45 2019
@author: Sturla
"""
import numpy as np
import matplotlib.pyplot as plt
days = 59 #Days between 1.jan - 1.mars
lambd = 1.5 #The parameter in the poisson process
def sim_poisson():
'''Simulates the poisson process'''
process_time... |
# Generated by Django 2.2.8 on 2019-12-14 06:50
from django.db import migrations
from ontask import models
def change_action_types(apps, schema_editor):
"""Change the action type for some of the actions."""
Old_Action = apps.get_model('ontask', 'Action')
for action in Old_Action.objects.all():
i... |
#!/usr/bin/env python3
from wsgiref.simple_server import make_server
def page(content, *args):
yield b'<html><head><title>wsgi_example.py</title></head><body>'
yield (content % args).encode('utf-8')
yield b'</body></html>'
def application(environ, start_response):
if environ['PATH_INFO'] == '/':
... |
load("@rules_foreign_cc//tools/build_defs/shell_toolchain/toolchains:toolchain_mappings.bzl", "ToolchainMapping")
ADD_TOOLCHAIN_MAPPINGS = [
ToolchainMapping(
exec_compatible_with = [
"@rules_foreign_cc_toolchains_examples//:fancy_constraint_value",
],
file = "@rules_foreign_cc_... |
import json, subprocess
from .. pyaz_utils import get_cli_name, get_params
def create(resource_group, name, publisher_email, sku_name=None, sku_capacity=None, virtual_network=None, enable_managed_identity=None, enable_client_certificate=None, publisher_name, location=None, tags=None, no_wait=None):
params = get_p... |
import sys
from .antlr import EOF, CommonToken as Tok, TokenStream, TokenStreamException
import struct
from . import ExcelFormulaParser
from re import compile as recompile, match, LOCALE, UNICODE, IGNORECASE, VERBOSE
int_const_pattern = r"\d+\b"
flt_const_pattern = r"""
(?:
(?: \d* \. \d+ ) # .1... |
# 202101 - Daniel Meier
import uuid
import requests
import json
import argparse
import logging
import ipaddress
import os
from datetime import datetime
#################################################################################################
# set args ... |
from bitcoinrpc.authproxy import AuthServiceProxy, JSONRPCException
import discord
from discord.ext import commands
from discord_slash import cog_ext
from discord_slash import SlashCommand
from discord_slash import SlashContext
from decimal import Decimal
import time
import user_db
import config
import utility
class ... |
from django.core.management.base import BaseCommand
from shost import setup
class Command(BaseCommand):
help = 'Setup the app'
def handle(self, *args, **options):
self.stdout.write('Starting setup...')
setup.setup()
self.stdout.write(self.style.SUCCESS('Setup successful!'))
|
from unittest.mock import MagicMock, PropertyMock
import pytest
from aioddd import (
BadRequestError,
BaseError,
ConflictError,
NotFoundError,
UnauthorizedError,
UnknownError,
)
from aioddd.testing import sanitize_objects
from orjson import loads
from pydantic import BaseModel, ValidationError
... |
#
# Copyright (c) 2019-2020 Mike's Pub, see https://github.com/mikespub-org
# Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
import json
import os.path
# from btfs import sessions
# from btfs.auth import AuthorizedUser
from .model import Chunk, Dir, File, Path
PAGE_SIZE = 10
KNOWN... |
# import modules
from math import radians, cos, sin, asin, sqrt
import urllib.request
import urllib
import json
import xml.etree.ElementTree as ET
from operator import itemgetter
import requests
# create class with station coordinates/status, and methods to
# find nearest bikes and docks
class LoadStations:
""" c... |
import numpy as np
def extract_snippets(data,*,times,snippet_size):
M = data.shape[1]
T = snippet_size
L = len(times)
Tmid = int(np.floor(T / 2))
snippets = np.zeros((L, T, M),dtype='float32')
for j in range(L):
t1 = times[j] - Tmid
t2 = t1+snippet_size
snippets[j, :, :]... |
# Copyright (c) 2017-2022 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
from asyncio import ensure_future, gather, get_event_loop, sleep, wait_for
from concurrent.futures import ThreadPoolExecutor
from datetime import timedelta
from typing import Awa... |
"""
Definição de Escala de Tripulação de Transporte Coletivo Utilizando Algoritmo Genético
Daniel Rodrigues Acosta
Universidade Federal do Rio Grande do Sul
Junho/2019
Variáveis Globais
"""
#import classPopulacao as pp
import datetime as dtm
import pandas as pd
import os
import pickle as pk
# Caminhos das Pastas
i... |
"""Unit tests for the Axe report generated by axe-selenium-python accessibility collector."""
import json
from collector_utilities.functions import md5_hash
from .base import AxeSeleniumPythonTestCase
class AxeSeleniumPythonAccessibilityTest(AxeSeleniumPythonTestCase):
"""Unit tests for the axe-selenium-python... |
from .const import *
from .docs import Docs
from .settings import Settings
|
from collections import defaultdict
import pytest
from names import group_names_by_country, data
# another output to test with
data2 = """last_name,first_name,country_code
Poxton,Sydney,CZ
Kynman,Bryant,NL
Mockler,Leese,AF
Gillicuddy,Raffaello,IR
Renyard,Carlo,CO
Beadham,Evonne,CZ
Tunstall,Allissa,IR
Kamenar,Augy,IR... |
'''Meta command which draws a graph of chapters with Graphviz'''
import yaml
from pathlib import Path
from foliant.meta_commands.base import BaseMetaCommand
from foliant.meta.generate import load_meta
from foliant.preprocessors.testrail import Preprocessor as TestRail
class MetaCommand(BaseMetaCommand):
confi... |
# Copyright 2019 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,... |
""" Exceptions for ArgTyper """
from typing import Optional, Text, Callable, TYPE_CHECKING
if TYPE_CHECKING:
from .base import ArgParser
class ArgTyperException(Exception):
""" Thrown on ArgTyper problems """
...
class ArgTyperArgumentException(ArgTyperException):
""" Thrown when something is wro... |
import numpy as np
from joblib import Parallel, delayed
import sklearn.neighbors as neighbors
class KernelDensity(object):
''' Kernel Density for anomaly detection
'''
def __init__(self, kernel: str = 'gaussian', bandwidth: float = 0.2) -> None:
super().__init__()
self.bandwidth = bandwid... |
#!/usr/bin/env python3.7
# -*- coding: utf-8 -*-
# Copyright (c) 2020.
#
# @author Mike Hartl <mike_hartl@gmx.de>
# @copyright 2020 Mike Hartl
# @license http://opensource.org/licenses/gpl-license.php GNU Public License
# @version 0.0.1
class Exemplar:
def inspect(self, content):
del content[0]
... |
from __future__ import print_function
import signal
import copy
import sys
import time
from random import randint
class AlarmException(Exception):
pass
|
"""
Serializers convert data types to serialized data (e.g. JSON) and back again.
Copyright (C) 2020 Nicholas H.Tollervey.
"Commons Clause" License Condition v1.0:
The Software is provided to you by the Licensor under the License, as defined
below, subject to the following condition.
Without limiting other conditio... |
# -*- coding: utf-8 -*-
def morse_to_text(morse):
"""Convert morse code to text.
Args:
morse (str): Morse code.
Returns:
str: Return a text.
"""
CODE = {
'A': '.-', 'B': '-...', 'C': '-.-.',
'D': '-..', 'E': '.', 'F': '..-.',
'G': '--.', 'H... |
import zoo
def makeTheZoo():
return zoo.Zoo("Bill's Wonderland Zoo", getLocations())
def getLocations():
locations = {}
locations.update(one())
locations.update(two())
locations.update(three())
locations.update(four())
locations.update(five())
locations.update(six())
locations.upda... |
"""initial migration
Revision ID: 2ddfd99e0bb4
Revises:
Create Date: 2021-01-25 22:42:56.598121
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
# revision identifiers, used by Alembic.
revision = "2ddfd99e0bb4"
down_revision = None
branch_labels = None
depends_on = None
... |
# -*- coding: utf-8 -*-
"""
Leetcode - Binary search introduction
https://leetcode.com/problems/binary-search
Binary search solution
Created on Sun Oct 21 16:21:01 2018
@author: Arthur Dysart
"""
# REQUIRED MODULES
import sys
# FUNCTION DEFINITIONS
class Solution(object):
def search(self, a, x):
"""
... |
from autobahn.twisted.websocket import WebSocketServerFactory, \
WebSocketServerProtocol
from tws_game.lobby import Lobby
from tws_game.tetris import Tetris
from pprint import pprint
import json
class ClientConnection(WebSocketServerProtocol):
def onOpen(self):
self.factory.register(self)
def... |
"""provides functions to kill the script by raising SystemExit"""
import sys
from typing import List, NoReturn
def assert_empty(blocked_actions: List[str]) -> None:
"""used with validate_perms, which returns list of denied AWS actions"""
if blocked_actions:
err("IAM user missing following permission(s... |
numbers = [10, 25, 54, 86, 89, 11, 33, 22]
new_numbers = list(filter(lambda x: (x%2 == 0) , numbers))
print(new_numbers)
|
import re
from .deep_getattr import deep_getattr
from connexion.resolver import Resolver
class RestyResolverEx(Resolver):
"""
Resolves endpoint functions using REST semantics (unless overridden by specifying operationId)
"""
def __init__(self, default_module_name, collection_endpoint_name='search', **... |
#Changeable parameters
def calc(*number): #can be seen as a list/tuple
#automatically seen
s=0
for n in number:
s=s+n*n
return s
#This input must be a list or tuple without the star mark
def calc(number): #can be seen as a list/tuple
#au... |
import pyx ### vector graphics
import cmath
from file_io import parse_data_file, read_from_pickle, output_to_pickle
from taut import isosig_to_tri_angle
from veering import veering_triangulation
from continent import continent
from boundary_triangulation import boundary_triangulation, tet_face
# def pre_draw_trans... |
from Tkinter import *
def doNothing():
print "okay okay I won't"
root = Tk()
optionsbar = Menu(root)
root.config(menu = optionsbar)
fileMenu = Menu(optionsbar, tearoff = 0 )
optionsbar.add_cascade(label = "File", menu = fileMenu)
fileMenu.add_command(label = "New Project", command = doNothing)
fi... |
#!/usr/bin/python
arr = [2,3,4,3,5,4,6,4,6,9,10,9,2,8,7,8,10,7]
dict1={}
for elem in arr:
dict1.setdefault(elem, 0)
dict1[elem] = dict1.get(elem) + 1
for a in dict1.keys():
if dict1.get(a) == 1:
print a
|
# Generated by Django 4.0 on 2021-12-08 14:40
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('project_first_app', '0004_user_alter_owner_first_name'),
]
operations = [
migrations.AlterField(
model_name='owner',
n... |
'''
This python file implements a wrapper for surface matching (PPF) algorithm in Halcon software
'''
import time
import numpy as np
from scipy.spatial.transform import Rotation as R
'''
Please refer https://pypi.org/project/mvtec-halcon/ for setting up Halcon/Python Interface.
More documentations can be found here: ... |
import math
a = [] # user array
c = []
one = int(1)
zero = int(0)
def perfect_square(x):
return int(math.sqrt(x))**2 == x
def sorted(arr, n):
a1 = [] # index
a2 = [] # perfect squares
for i in range(n):
if(perfect_square(a[i]) == True):
a1.append(i)
a2.append(... |
#
# This script is licensed as public domain.
#
# http://docs.python.org/2/library/struct.html
from xml.etree import ElementTree as ET
from xml.dom import minidom
import os,shutil
import struct
import array
import logging
import bpy
import re
from queue import Queue
from threading import current_thread,main_thread
f... |
from django.test import TestCase
from safedelete.utils import get_deleted_or_not_deleted_filters_dictionary
from safedelete import utils
try:
from unittest.mock import patch
except ImportError:
from mock import patch # for python 2 supporting
class TestFiltersDictionary(TestCase):
@patch.object(utils, ... |
import asyncio
from nats import NATS, Msg
async def main():
nc = NATS()
# It is very likely that the demo server will see traffic from clients other than yours.
# To avoid this, start your own locally and modify the example to use it.
# await nc.connect("nats://127.0.0.1:4222")
await nc.connect("... |
from airflow.hooks.postgres_hook import PostgresHook
from airflow.models import BaseOperator
from airflow.utils.decorators import apply_defaults
class LoadDimensionOperator(BaseOperator):
ui_color = '#80BD9E'
@apply_defaults
def __init__(self,
redshift_conn_id="",
table=... |
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
def countWeight(X, y):
w = np.sum(((X - X.mean()) * (y - y.mean()))) / np.sum((X - X.mean())**2)
return w
def polynomialUni(X, w, degrees):
y = 0
for degree in range(degrees+1):
y = w * (X ** degree)
return y
# Impo... |
import sys
import github.overfl0.stack_overflow_import.stackoverflow as stackoverflow
# Workaround: if the module name starts with 'github.[...]' the github import
# hook will fire for each subpackage
# To prevent that, we rename the module to look like a top level module
stackoverflow.__name__ = 'stackoverflow' # W... |
# MIT License
#
# Copyright (c) 2020 Christopher Friedt
#
# 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, ... |
from flask import Flask, jsonify, request
from flask_cors import CORS
# configuration
DEBUG = True
# instantiate the app
app = Flask(__name__)
app.config.from_object(__name__)
app.config['JSON_SORT_KEYS'] = False #Used to not sort json objects by keys (jsonify) -
# enable CORS
CORS(app, resources={r'/*': {'origins'... |
def julday(month, day, year, hour=12, minute=0, second=0):
'''
NAME:
julday
PURPOSE:
Calculate the Julian Date Number for a given month, day, and year.
Can also take in hours, minutes, and seconds.
INPUTS:
month: Number of the month of the year (1 = jan, ..., 12 = dec)
day: Nu... |
## DranoTheCat's Pink and Blue fireworks
##
## Tilt badge left to make lights move to the left
## Tilt badge right to make lights move to the right
## Boop to change speed -- meh, this effect sucked so disabled
##
from random import randrange
import math
import dcfurs
import badge
import utime
### TESTS FOR PC
#from ... |
"""
stoclust.visualization
Contains functions for visualizing data and clusters.
Functions
---------
heatmap(mat,show_x=None,show_y=None,xlabels=None,ylabels=None,layout=None,**kwargs):
Generates a heatmap of a given matrix:
that is, displays the matrix as a table of colored blocks
such that the colors... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# Copyright 2011-2020, Nigel Small
#
# 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
#
# Unle... |
from . import agent_collection
from . import entity
from . import identity
from . import model
from . import time
from . import world
|
"""
Import as:
import helpers.hparquet as hparque
"""
import logging
import os
from typing import Any, List, Optional
import pandas as pd
import pyarrow as pa
import pyarrow.parquet as pq
import helpers.hdbg as hdbg
import helpers.hintrospection as hintros
import helpers.hio as hio
import helpers.htimer as htimer
... |
from . import scapy_scan, nmap_scan, banner_scan, vulnerability_analysis_menu
__all__ = ["scapy_scan", "nmap_scan", "banner_scan", "vulnerability_analysis_menu"]
|
# Generated by Django 2.0.3 on 2019-06-10 09:54
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('site', '0024_career'),
]
operations = [
migrations.AlterField(
model_name='career',
name='title',
field=... |
import board
import busio
import digitalio
import time
import circuitpython_hmac as hmac
import binascii
from adafruit_wiznet5k.adafruit_wiznet5k import *
import adafruit_wiznet5k.adafruit_wiznet5k_socket as socket
from adafruit_wiznet5k.adafruit_wiznet5k_ntp import NTP #NTP library
import adafruit_wizne... |
"""
Defines the Job Ledger
necessary for jobs being
serviced only once
"""
from collections import deque
__author__: str = "Splice Machine, Inc."
__copyright__: str = "Copyright 2019, Splice Machine Inc. All Rights Reserved"
__credits__: list = ["Amrit Baveja"]
__license__: str = "Proprietary"
__version__: str = "2.... |
import time
from turtle import *
from random import randint
speed(30)
up()
goto(-140, 140)
for i in range(16):
write(i, align='center') # text
right(90)
fd(10)
down()
fd(150)
up()
bk(160)
left(90)
fd(20)
finish_line = xcor() - 20
print('finish line :', finish_line)
tutle_color =... |
from keras.layers.core import Lambda
from keras import backend as K
class RecursiveLoopLayer(Lambda):
"""Class representing RecursiveLoop for keras"""
def __init__(self, maxlend, rnn_size, activation_rnn_size, maxlenh, **kwargs):
super().__init__(self.recursive_loop, **kwargs)
self.rnn... |
"""
Python 3.6
PyTorch 0.4
"""
import logging
import itertools
import torch
import torch.nn.functional as F
import torch.optim as optim
import utils
from Models.AbstractModel import AbstractModel, Models
class InfoGAN(AbstractModel):
""" InfoGAN
InfoGAN: Interpretable Representation Learning by Infor... |
import httpx
import json
import time
import asyncio
import sys
import os
PROJECT = "bench-functions"
FUNCTION = "place-test"
HTTP_ENDPOINT_HOST = "https://us-central1-{}.cloudfunctions.net/{}"
RESULT_FILE_NAME = os.path.join("results", "{}_size={}.json")
async def async_request(client, orch_name, size):
url = ... |
# Tests on main client object
import TestHelperSuperClass
import EllucianEthosPythonClient
import base64
import json
import TestingHelper
import queue
class helpers(TestHelperSuperClass.testClassWithHelpers):
pass
@TestHelperSuperClass.wipd
class test_MainClient_poller(helpers):
def test_notAbleToStartPollerTwice... |
import matplotlib.pyplot as plt
import numpy as np
import math
import keras
# Importar la API keras
from tensorflow.python.keras.models import Sequential
from tensorflow.python.keras.layers import InputLayer, Input
from tensorflow.python.keras.layers import Reshape, MaxPooling2D
from tensorflow.python.keras.layers imp... |
__________________________________________________________________________________________________
sample 108 ms submission
class Solution:
def countVowelPermutation(self, n: int) -> int:
# a -> e
# e -> a, i
# i -> a, e, o, u
# o -> i, u
# u -> a
mod = 1000000007
... |
class Reaction:
""" A (possibly lifted) reaction """
def __init__(self, language, name, parameters, condition, effect):
self.name = name
self.language = language
self.parameters = parameters
self.condition = condition
self.effect = effect
self._check_well_formed... |
import socket
import pytest
from airflow.utils import timezone
from airflow.utils.db import create_session
from airflow.utils.state import State
from pytest_socket import disable_socket, SocketBlockedError
from tests import mocks
from tests.factories import DAGFactory, PythonOperatorFactory
def pytest_runtest_setup... |
import numpy as np
import pandas as pd
dataset = pd.read_csv('Bd-Rainfall-prediction.csv')
dataset.describe()
X = dataset.iloc[:, :-1].values
y = dataset.iloc[:,-1].values
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size =.20,random_... |
def expand_int_list(input):
items = []
if not input:
return items
parts = input.split(',')
for part in parts:
if part.strip() != '':
try:
if '-' in part:
start_stop = part.split('-')
start = start_stop[0]
... |
import datetime
import sqlalchemy
import pytest
from acondbs.db.sa import sa
from acondbs.models import Map
# __________________________________________________________________||
def test_type(app):
'''confirm the type of the date field
'''
with app.app_context():
map = Map.query.filter_by(name='... |
# This is the script without the need of a FFmpeg installation, pure OpenCV
# This is not useful for image processing (eg: find faces) as there will be more lag, around 6 seconds added.
import socket
from time import time
import cv2
import numpy as np
from goprocam import GoProCamera, constants
gpCam = GoProCamera.G... |
from apkdecompiler import APKDecompile
|
from datetime import datetime
from random import randint
from typing import List
from crypto_package.candles.get_candles import get_candles
from pandas import DataFrame, to_datetime
import plotly.graph_objects as go
from plotly.subplots import make_subplots
from .models import AnalysisResult, Trade
def get_candles_... |
import numpy as np
from qiskit import BasicAer
from qiskit.quantum_info import Pauli
from qiskit.aqua import QuantumInstance, aqua_globals
from qiskit.aqua.algorithms import NumPyMinimumEigensolver, VQE
from qiskit.circuit.library import TwoLocal
from qiskit.aqua.components.optimizers import SPSA
from qiskit.aqua.opera... |
# Кожен трансформер має свою вагу, запишемо її у словник
# transformersWeight = { "Оптімус": 5000, "Бамблбі": 2500, "Джаз": 3000 }
# Яка вага всіх трансформерів у словнику?
transformersWeight = { "Оптімус": 5000, "Бамблбі": 2500, "Джаз": 3000 }
total_weight = 0
for value in transformersWeight.values():
to... |
"""
Enables programmatic accessing of most recent docker images
"""
import pkg_resources
import armory
USER = "twosixarmory"
TAG = armory.__version__
TF1 = f"{USER}/tf1:{TAG}"
TF2 = f"{USER}/tf2:{TAG}"
PYTORCH = f"{USER}/pytorch:{TAG}"
ALL = (
TF1,
TF2,
PYTORCH,
)
ARMORY_BASE = f"{USER}/armory:{TAG}"
TF1... |
#! Assignment 2
#! Previously in 1_notmnist.ipynb,
#! we created a pickle with formatted datasets for training, development and testing on the notMNIST dataset.
#! The goal of this assignment is to progressively train deeper and more accurate models using TensorFlow.
#! These are all the modules we'll be using later... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.