text stringlengths 2 999k |
|---|
import unittest
class SomeClass(unittest.TestCase):
def test_something(self):
<warning descr="Consider utilizing functionality of your testing framework to handle the exception">try</warning>:
x = 3
except ValueError:
print("Try again...")
def do_something(self):
... |
# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and re... |
from pprint import pprint
# Metaclass that will make all class attributes and methods be uppercase
class ToUpper(type):
def __new__(cls, name, bases, namespace):
new_namespace = {}
for attr, value in namespace.items():
if attr.startswith('__'):
new_namespace[attr] = valu... |
import multiprocessing
import concurrent.futures
import sys
import threading
from concurrent.futures import _base
from concurrent.futures.process import _ExceptionWithTraceback, _ResultItem # noqa
from functools import wraps
import os
import nb_log
name = 'bounded_pool_executor'
logger = nb_log.get_logger('BoundedP... |
"""
Class for reading data created by IGOR Pro
(WaveMetrics, Inc., Portland, OR, USA)
Depends on: igor (https://pypi.python.org/pypi/igor/)
Supported: Read
Author: Andrew Davison
Also contributing: Rick Gerkin
"""
from warnings import warn
import numpy as np
import quantities as pq
from neo.io.baseio import BaseIO... |
# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# Copyright (c) 2014, Nicolas P. Rougier. All rights reserved.
# Distributed under the terms of the new BSD License.
# -----------------------------------------------------------------------------
import numpy as np
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu May 23 13:45:44 2019
@author: thomassullivan
"""
import docx
from docx.enum.dml import MSO_THEME_COLOR_INDEX
from objects import Article
def add_hyperlink(paragraph, text, url):
# This gets access to the document.xml.rels file and gets a new relati... |
from .Unet import UNetSeeInDark
import torch.nn as nn
def unet(in_channels, out_channels, **kwargs):
return UNetSeeInDark(in_channels, out_channels)
|
from rest_framework import exceptions, serializers
from api.v2.serializers.summaries import StatusTypeSummarySerializer
from core.models import StatusType
class StatusTypeRelatedField(serializers.RelatedField):
def get_queryset(self):
return StatusType.objects.all()
def to_representation(self, status... |
from merge_sort import merge_sort
def test_zero():
z = []
actual = merge_sort(z)
expected = "Not a valid input"
assert actual == expected
def test_one():
z = [1]
actual = merge_sort(z)
expected = [1]
assert actual == expected
def test_many():
z = [8, 4, 23, 42, 16, 15]
actu... |
from __future__ import absolute_import
import six
from sentry.models import AuthIdentity, AuthProvider
from sentry.testutils import AuthProviderTestCase
from sentry.utils.auth import SSO_SESSION_KEY
class AuthenticationTest(AuthProviderTestCase):
def test_sso_auth_required(self):
user = self.create_user... |
#!/usr/bin/env python3
# Copyright (c) 2014 Wladimir J. van der Laan
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
'''
A script to check that the (Linux) executables produced by gitian only contain
allowed gcc, glibc and libstdc+... |
# Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
from flaskblog import app
if __name__ == "__main__":
app.run(debug=True) |
"""
Flash an LED connected via a FTDI UM232R/245R module using pylibftdi
Optionally supply a flash rate (in Hz, default 1) as an argument
Copyright (c) 2010-2014 Ben Bass <benbass@codedstructure.net>
All rights reserved.
"""
import time
import sys
from pylibftdi import BitBangDevice
def flash_forever(rate):
""... |
# app/__init__.py
from flask import Flask,session
from celery import Celery
from pymongo import MongoClient
import redis
from datetime import timedelta
# Initialize the app
app = Flask(__name__, instance_relative_config=True)
app.secret_key = "super secret key"
# Need to set this to keep session
app.permanent_sessi... |
#!/usr/bin/env python3
# Copyright (c) 2022 oatsu
"""
acousticのファイルをWAVファイルにするまでの処理を行う。
"""
import numpy as np
import pyworld
from hydra.utils import to_absolute_path
from nnmnkwii.io import hts
from nnsvs.gen import gen_world_params
from nnsvs.logger import getLogger
from omegaconf import DictConfig, OmegaConf
from sc... |
"""
A package containing modules for modeling tools.
\b Creation \b Info:
\b Donations: http://adammechtley.com/donations/
\b License: The MIT License
Copyright (c) 2011 Adam Mechtley (http://adammechtley.com)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associa... |
#!usr/bin/python
'''
ABOUT THIS FILE:
- this file contains functions that deal with cgi inputs
LEFT TO DO:
- comments
- comment out cgitb
'''
# ~~~~~~~~~~~~~~~~~~~~~~~~~~
import cgi
import cgitb
cgitb.enable() #comment out when done editing
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def FStoD():
'''
Converts... |
número = int(input('Número inteiro maior que 1: '))
fator = 2
while número > 1:
multiplicidade = 0
while número % fator == 0:
número = número / fator
multiplicidade += 1
if multiplicidade > 0:
print(f'Fator {fator} tem multiplicidade = {multiplicidade}')
fator += 1 |
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'lloydapi.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise Impor... |
from hypothesis import given, example, assume
from hypothesis.strategies import text, tuples, uuids, one_of, none, integers, floats, datetimes
from sentenai import Sentenai
from sentenai.api.stream import Stream
from sentenai.utils import iso8601
import string, unittest, requests_mock, requests, pytest
from datetime i... |
from classes.core.colors import Colors
def print_results(self, element):
if element in self.result:
element_results = self.result[element]
# Section title
# No results
if not element_results["accounts"]:
print("\n" + Colors.BOLD + "└──" + Colors.ENDC + Colors.OKGREEN +... |
import os
from io import BytesIO
import pathlib
import datetime
import random
from typing import Optional
from .pyfatoora import PyFatoora
from .schemas import InvoiceData
from fastapi import FastAPI, Request, Form, File, UploadFile, HTTPException
from fastapi.responses import FileResponse
from starlette.background imp... |
# -*- coding:utf-8 -*-
# @project: BlockShuffleTest
# @filename: train
# @author: 刘聪NLP
# @zhihu: https://www.zhihu.com/people/LiuCongNLP
# @contact: logcongcong@gmail.com
# @time: 2021/9/27 10:51
"""
文件说明:
"""
import torch
import os
import random
import numpy as np
import argparse
import logging
from ... |
from discord import Embed
from discord.ext import commands
from discord.member import Member
from cog.helpers import gifs, strings, rbColor
from random import choice
class Helpers():
def header(table):
header = strings[table]
return choice(header)
def gif(table):
return choice(gifs[ta... |
import pytest
import test.test_utils.ecs as ecs_utils
import test.test_utils.ec2 as ec2_utils
from test.test_utils import get_tensorflow_model_name, request_tensorflow_inference
from test.test_utils import ECS_AML2_CPU_USWEST2, ECS_AML2_GPU_USWEST2
@pytest.mark.model("half_plus_two")
@pytest.mark.parametrize("ecs_in... |
# Lint as: python3
# Copyright 2018, The TensorFlow Federated 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 ... |
"""
Copyright (c) 2020 Alex Forencich
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, publish, distribute... |
#
# This file is part of pyasn1 software.
#
# Copyright (c) 2005-2019, Ilya Etingof <etingof@gmail.com>
# License: http://snmplabs.com/pyasn1/license.html
#
# noinspection PyPep8
int2oct = lambda x: bytes((x,))
null = bytes()
# noinspection PyPep8
oct2int = lambda x: x
# noinspection PyPep8
octs2ints = lambda x: x
# n... |
"""
Model inspired by: https://github.com/natasasdj/anomalyDetection
"""
import tensorflow as tf
from tensorflow.keras.layers import (
Input,
Dense,
Conv2D,
MaxPooling2D,
UpSampling2D,
BatchNormalization,
GlobalAveragePooling2D,
LeakyReLU,
Activation,
concatenate,
Flatten,
... |
SECRET_KEY = '=boqt*+3!33&n&iw1q5t#el$p6pimav9xn0zzhi=_eu300971u'
|
import sys
sys.path.insert(0, '../../')
from Colley import *
fn = sys.argv[1]
games = [l.split(",")[1:6] for l in open(fn, 'r').read().strip().split("\n")]
def weight_fn(notes):
if notes == '':
return 1
if notes == 'OT':
return 0.75
if notes == 'SO':
return 0.5
def print_rankings(ranks):
print "... |
import json
import os
import pytest
from vdb.lib.npm import NpmSource
@pytest.fixture
def test_app_info():
return {"name": "appthreat-vulnerability-db-test", "version": "1.0.0"}
@pytest.fixture
def test_pkg_list():
return ["handlebars|4.1.0", "growl|1.10.0"]
@pytest.fixture
def test_cve_json():
test... |
from .customized_logging import get_logger
|
#!/usr/bin/env python3.8
import os
import sys
import unittest
SCRIPT_DIR = os.path.dirname(
os.path.realpath(os.path.join(os.getcwd(), os.path.expanduser(__file__))))
sys.path.append(
os.path.normpath(os.path.join(SCRIPT_DIR, os.path.pardir, os.path.pardir)))
# pylint: disable=wrong-import-position
from nono... |
my_foods=['pizza','falafel','carrot cake']
friend_foods=my_foods[:]
print("My foods are:")
for my_food in my_foods:
print(my_food)
print("My friend's foods are:")
for friend_food in friend_foods:
print(friend_food)
|
import time
from django.core.management.base import BaseCommand
from django.db import connections
from django.db.utils import OperationalError
class Command(BaseCommand):
"""Django command to pause execution until databse is available"""
def handle(self, *args, **options):
self.stdout.write('Waiting ... |
import sys
import pandas as pd
import numpy as np
def normalized_matrix(filename):
'''To normalize each of the values in the csv file'''
try:
dataset = pd.read_csv(filename) #loading the csv file into dataset
if len(dataset.axes[1])<3:
print("Number of columns should be greater tha... |
'''
xbmcswift2.common
-----------------
This module contains some common helpful functions.
:copyright: (c) 2012 by Jonathan Beluch
:license: GPLv3, see LICENSE for more details.
'''
import urllib
import urllib2
try:
import cPickle as pickle
except ImportError:
import pickle
... |
#!/usr/bin/env python3
(R, C, K), *D = [[*map(int,o.split())] for o in open(0)]
V = [[0] * C for _ in [None] * R]
for r, c, v in D:
V[r - 1][c - 1] = v
dp = [[[-1] * C for _ in [None] * R] for _ in [None] * 4]
dp[0][0][0] = 0
for r in range(R):
for c in range(C):
v = V[r][c]
for i in range(4):... |
from __future__ import division, print_function, absolute_import
__all__ = ['interp1d', 'interp2d', 'lagrange', 'PPoly', 'BPoly', 'NdPPoly',
'RegularGridInterpolator', 'interpn']
import itertools
import warnings
import functools
import operator
import numpy as np
from numpy import (array, transpose, searc... |
from __future__ import division
import os
import sys
import cv2
import numpy as np
import torch
from torchvision.transforms import transforms
sys.path.append(os.path.join(os.getcwd(), 'models', 'detectors', 'yolo'))
from .utils.YOLOmodels import Darknet
from .utils.YOLOutils import load_classes, non_max_suppression... |
#!/usr/bin/env python
# ******************************************************************************
# Copyright 2017-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
... |
# MIT LICENSE Copyright (c) 2018 David Longnecker
# 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, ... |
a=[15,18,66,99,97,88,78]
b=0
temp=0
while b<len(a):
d=b+1
while d<len(a):
if a[b]<a[d]:
temp=a[b]
a[b]=a[d]
a[d]=temp
d+=1
b+=1
print a[0],a[1],a[2] |
import FWCore.ParameterSet.Config as cms
from Configuration.Eras.Era_Run3_dd4hep_cff import Run3_dd4hep
process = cms.Process("G4PrintGeometry",Run3_dd4hep)
process.load('Configuration.Geometry.GeometryDD4hepExtended2021Reco_cff')
from SimG4Core.PrintGeomInfo.g4TestGeometry_cfi import *
process = checkOverlap(proce... |
# Basic Calculator
# assumption: the expression is valid, integers are non-negative
# may have white space
class Solution(object):
def calculate(self, s):
stack = [[]] # for s that starts without "("
num = 0
for i, char in enumerate(s):
if char == ' ':
continue
... |
# This file helps to compute a version number in source trees obtained from
# git-archive tarball (such as those provided by githubs download-from-tag
# feature). Distribution tarballs (built by setup.py sdist) and build
# directories (produced by setup.py build) will contain a much shorter file
# that just contains th... |
# Copyright (C) 2019 The Raphielscape Company LLC.
#
# Licensed under the Raphielscape Public License, Version 1.d (the "License");
# you may not use this file except in compliance with the License.
#
import os
import time
from datetime import datetime
import aiohttp
from github import Github
from userbot import CMD... |
# Copyright 2010-2021 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... |
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
# Create your forms here.
class NewUserForm(UserCreationForm):
email = forms.EmailField(required=True)
class Meta:
model = User
fields = ("username", "email", "password... |
from django.db.models import Q
from rest_framework.filters import BaseFilterBackend
from .models import Project, Dataset, ResearchGroup, GroupMember, GroupViewGrant, ProjectStatistics, Location, User, UserAgent, UserAgentProjectConfig, LocationProject
from rest_framework.exceptions import APIException
class Active... |
#!/usr/bin/env python
import os
import sys
print(os.environ.get('PWD', "none"))
ret_code = os.system("cd example && ./manage.py validate")
sys.exit(ret_code)
|
import unittest
class TestDataTypes(unittest.TestCase):
def test_what_ross_said(self):
self.assertEqual(what_ross_said(), """Let's put aside the fact that you "accidentally" pick up my grandmother's ring.""")
self.assertIs(type(what_ross_said()), str)
def test_hello_something(self):
sel... |
import os
import sys
import argparse
import logging
import time
import math
import traceback
import numpy as np
from scipy.optimize import fmin_l_bfgs_b
from shutil import copy
import igraph
import torch
from torch import nn, optim
from util import *
from dataset import *
from opt_util import *
from... |
from PyQt4 import QtCore, QtGui, uic
from wallet import wallet
from tablemodel import TableModel, ProxyModel
class AddressTableModel(TableModel):
_columns = ['Moniker', 'Address', 'Received']
_alignment = [
QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter,
QtCore.Qt.AlignCenter | QtCore.Qt.AlignV... |
from spytest import st
def _wait(dut, secs):
if st.is_vsonic(dut):
st.wait(secs)
def mac_learn(dut=None, secs=10):
_wait(dut, secs)
def tgen_stats(dut=None, secs=15):
_wait(dut, secs)
def tgen_send(dut=None, secs=15):
_wait(dut, secs)
def nat_stats(dut=None, secs=10):
_wait(dut, secs)
|
# -*- coding: utf-8 -*-
#
# Copyright 2019 Ricequant, Inc
#
# * Commercial Usage: please contact public@ricequant.com
# * Non-Commercial Usage:
# 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 ... |
# coding=utf-8
# Copyright 2021 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... |
import time
from pixels import Pixels, pixels
from alexa_led_pattern import AlexaLedPattern
from google_home_led_pattern import GoogleHomeLedPattern
if __name__ == '__main__':
pixels.pattern = GoogleHomeLedPattern(show=pixels.show)
while True:
try:
pixels.wakeup()
time.sleep(... |
#-*- coding: utf-8 -*-
import urllib.request
import urllib
import http.cookiejar
from bs4 import BeautifulSoup
from PIL import Image
import capcha
import info
import requests
def qiang(dict1):
#列一下要用的url
#登陆页
url_login = 'https://gsdb.bjtu.edu.cn/client/login/'
#选课页
course_url = 'htt... |
import re
import os
from scrapy.spider import BaseSpider
from scrapy.selector import HtmlXPathSelector
from scrapy.http import Request, HtmlResponse
from scrapy.utils.response import get_base_url
from scrapy.utils.url import urljoin_rfc
from urllib import urlencode
import csv
from product_spiders.items import Produc... |
# Load module and example file
import pyvista as pv
from pyvista import examples
import numpy as np
# Load example beam grid
grid = pv.UnstructuredGrid(examples.hexbeamfile)
# Create fictitious displacements as a function of Z location
d = np.zeros_like(grid.points)
d[:, 1] = grid.points[:, 2]**3/250
# Displace orig... |
"""
Python program to find the largest element and its location.
"""
def largest_element(a, loc = False):
""" Return the largest element of a sequence a.
"""
maxval = a[0]
val_loc = 0
try:
for i in range(1, len(a)):
if a[i]> maxval:
maxval = a[i]
... |
# coding: utf-8
"""
maiot Core Engine API
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) # noqa: E501
OpenAPI spec version: 0.1.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
i... |
from random import randint
from typing import Union
import numpy as np
first_timestamp = 1552309186171
open_price = randint(40, 100)
close_price = randint(open_price, 110) if randint(0, 1) else randint(
30, open_price)
max_price = max(open_price, close_price)
high_price = max_price if randint(0, 1) else randint(m... |
"""
Copyright 2017 Islam Elnabarawy
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 ... |
# qubit number=2
# total number=28
import pyquil
from pyquil.api import local_forest_runtime, QVMConnection
from pyquil import Program, get_qc
from pyquil.gates import *
import numpy as np
conn = QVMConnection()
def make_circuit()-> Program:
prog = Program() # circuit begin
prog += H(0) # number=1
pr... |
#!/usr/bin/python3
import json
from collections import OrderedDict
from pathlib import Path
from typing import Dict, Iterator, List, Sequence, Tuple, Union, ValuesView
import eth_event
from brownie._config import _get_data_folder
from brownie.convert.normalize import format_event
from brownie.exceptions import Event... |
matrix = []
for row in range(8):
matrix.append(input().split())
def finding_the_king(matrix):
for row in range(8):
for col in range(8):
current_el = matrix[row][col]
if current_el == "K":
return row, col
# def get_capturint_queens(matrix, king):
#
# (pos_r... |
# (C) Datadog, Inc. 2016
# All rights reserved
# Licensed under Simplified BSD License (see LICENSE)
import logging
import os
import mock
import pytest
import requests
from six import iteritems, iterkeys
from six.moves import range
from datadog_checks.checks.prometheus import PrometheusCheck, UnknownFormatError
from ... |
# Generated by Django 3.0.6 on 2020-05-14 05:32
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Message',
fields=[
('id', models.AutoField(... |
from dash.dependencies import Input, Output
import dash_core_components as dcc
import dash_html_components as html
import dash_bootstrap_components as dbc
import plotly.graph_objs as go
import pandas as pd
from .dash import Dash
df = pd.read_csv("app/data/indicators.csv")
available_indicators = df["Indicator Name"].u... |
import discord
from checks.checks import *
from random import choice
from discord.ext import commands
from discord.ext.commands.cooldowns import BucketType
class NSFW:
"""NSFW Commands 🔞"""
def __init__(self, bot):
self.bot = bot
self.thumbnail = "https://i.imgur.com/ivmKTvu.png"
s... |
import os
_private = os.system
part_config = {"SATU": 1, "DUA": 2, "DICT": {"YO": 1, "MAN": "YOI"}}
full_config = {
"FALCA_SATU": 1,
"FALCA_DUA": 2,
"FALCA_DICT": {"YO": 1, "MAN": "YOI"},
**part_config,
}
class Config:
pass
for k, v in full_config.items():
setattr(Config, k, v)
del k, v
|
import pygame
import random
from os import path
class Move(pygame.sprite.Sprite):
def __init__(self,x,y,player):
pygame.sprite.Sprite.__init__(self)
black = (0,0,0)
self.x = x
self.y = y
if player == "O":
self.image = pygame.transform.scale(O_img,((55,55)))
... |
from sandglass.time.api import API
from sandglass.time.api import ApiDescribeResource
class ApiV1DescribeResource(ApiDescribeResource):
"""
Resource to describe API version 1.
"""
version = "v1"
def describe(self):
resource_info_list = []
for resource in self.resources:
... |
# Copyright 2020 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
# space.py
from __future__ import annotations
import abc
import json
import os
import re
import time
from typing import TYPE_CHECKING, Any, Optional
from typing import Dict, FrozenSet, List, OrderedDict
import discord
from .command import Command, CommandAlias, CommandSimple
if TYPE_CHECKING:
from .deepbluesky i... |
# -*- coding: utf-8 -*-
# Copyright 2017 ProjectQ-Framework (www.projectq.ch)
#
# 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
#
# ... |
from copy import deepcopy
from typing import (Any, List, Optional, Tuple)
import numpy as np
from deap import tools
from fedot.core.log import Log
from fedot.core.optimisers.gp_comp.gp_operators import clean_operators_history, duplicates_filtration, \
num_of_parents_in_crossover
from fedot.core.optimisers.gp_comp... |
"""yolo_with_plugins.py
Implementation of TrtYOLO class with the yolo_layer plugins.
"""
from __future__ import print_function
import ctypes
import numpy as np
import cv2
import tensorrt as trt
import pycuda.driver as cuda
try:
ctypes.cdll.LoadLibrary('./plugins/libyolo_layer.so')
except OSError as e:
ra... |
import numpy as np
import tensorflow as tf
from tensorflow.keras import Sequential
from tensorflow.keras.layers import Dense
from tensorflow.keras.optimizers import Adam
tf.keras.backend.set_floatx('float64')
"""
Critic model
lr = 0.001
l2 weight decay 0.01
gamma = 0.99 for loss
relu,relu,relu
400,300,4
... |
# -*- coding: utf-8 -*-
'''
The core behaviors used by minion and master
'''
# pylint: disable=W0232
from __future__ import absolute_import
# Import python libs
import time
import os
import multiprocessing
import logging
from salt.ext.six.moves import range
# Import salt libs
import salt.daemons.masterapi
from raet ... |
# Membaca file hello.txt dengan fungsi read()
print(">>> Membaca file hello.txt dengan fungsi read()")
file = open("hello.txt", "r")
content = file.read()
file.close()
print(content)
# Membaca file hello.txt dengan fungsi readline()
print(">>> Membaca file hello.txt dengan fungsi readline()")
file = open("hello.txt", "... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import (
setup,
find_packages,
)
def merge_lists(base_list, *other_lists):
new_list = base_list[:]
for other_list in other_lists:
new_list.extend(i for i in other_list if i not in new_list)
return new_list
HYPOTHESIS_REQUIREME... |
from functools import wraps
import werkzeug
import flask
def response(*, mimetype: str = None, template_file: str = None):
def response_inner(f):
# print("Wrapping in response {}".format(f.__name__), flush=True)
@wraps(f)
def view_method(*args, **kwargs):
response_val = f(*arg... |
import qrcode
class QRCode:
def createQR(self,s : str, fileName : str, output : str, type : str):
qr = qrcode.QRCode()
qr.add_data(s)
qr.make()
img = qr.make_image()
img.save(f"{output}/{fileName}.{type}")
|
"""Added user model
Revision ID: 13f5d0b56f51
Revises:
Create Date: 2022-01-17 13:47:04.602002
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = "13f5d0b56f51"
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto g... |
import nltk
from nltk import word_tokenize
from nltk.corpus import stopwords
import sys
# helper class which, tokenizes, lemmatize, normalizes and removes stop words
class Helper:
def __init__(self):
self.StopWords = set(stopwords.words('english'))
self.PorterStemmer = nltk.PorterStemmer()
def T... |
# BSD 3-Clause License
# Copyright (c) 2019, Hugonun(https://github.com/hugonun)
# All rights reserved.
import discord
from gsheet import *
client = discord.Client()
sheet = gsheet()
@client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
@client.event
async de... |
# -*- coding: utf-8 -*-
# !/usr/bin/env python3 -u
# copyright: sktime developers, BSD-3-Clause License (see LICENSE file)
"""Implments algorithms for creating online ensembles of forecasters."""
__author__ = ["William Zheng"]
__all__ = [
"NormalHedgeEnsemble",
"NNLSEnsemble",
"OnlineEnsembleForecaster",
... |
# -*- coding: utf-8 -*-
#
# Pygr documentation build configuration file, created by
# sphinx-quickstart on Mon Jan 19 09:36:56 2009.
#
# This file is execfile()d with the current directory set
# to its containing dir.
#
# The contents of this file are pickled, so don't put values
# in the namespace that aren't pickleab... |
import keras
from datetime import timedelta
from keras.datasets import fashion_mnist
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten
from keras.layers import Conv2D, MaxPooling2D
from keras import backend as K
from keras.optimizers import SGD
from elefas.engine import normalize
fro... |
# coding: utf-8
"""
SpaCy deep_learning_keras.py solution to Kaggle Toxic Comment challenge
"""
from utils import xprint_init, xprint
from framework import Evaluator, set_random_seed, make_submission, set_n_samples
from clf_spacy import ClfSpacy
submission_name = 'spacy_lstm10'
do_submission = True
epochs = 6
d... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Q3: Grooving with GRUs
"""
from __future__ import absolute_import
from __future__ import division
import argparse
import logging
import sys
import time
from datetime import datetime
import tensorflow as tf
import numpy as np
import matplotlib
import matplotlib.pypl... |
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under t... |
"""
Interface to Docker
"""
from __future__ import absolute_import
import logging
import os
from functools import partial
from itertools import cycle, repeat
from time import sleep
try:
import docker
except ImportError:
docker = None
import requests.exceptions
from six import string_types
from six.moves impo... |
# -*- coding: utf-8 -*-
"""
pygments.lexers._csound_builtins
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: Copyright 2006-2020 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
# Opcodes in Csound 6.14.0 using:
# python3 -c "
# import re
# from subprocess ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.