text
stringlengths
2
999k
from __future__ import annotations import asyncio import weakref import discord import discord.ext.commands from typing import (Tuple, Dict, Union, Optional, Literal, AsyncIterator, Callable, Any, Generic, TypeVar, ContextManager, overload, cast) import discord_client import plugins import plugins.cogs import util....
def plot(txtaddress, filepath): """ @Author: Haoyang Ding plot the interactive treemap html :param txtaddress: txt file address, string :return: None """ from pyecharts import TreeMap f = open(txtaddress, 'r') a = f.read() tree = eval(a) f.close() counter = 0 for i...
from toontown.coghq.SpecImports import * GlobalEntities = {1000: {'type': 'levelMgr', 'name': 'LevelMgr', 'comment': '', 'parentEntId': 0, 'cogLevel': 0, 'farPlaneDistance': 1500, 'modelFilename': 'phase_12/models/bossbotHQ/BossbotMazex4_C', 'wantDoors': 1}, 10...
""" Model Serializers for Ona app """ from rest_framework_json_api import serializers from kaznet.apps.ona.models import Instance, Project, XForm # pylint: disable=too-many-ancestors class XFormSerializer(serializers.ModelSerializer): """ Serializer for XForm Model """ task_name = serializers.Serial...
"""show_forwarding.py NXOS parsers for the following commands * 'show forwarding ipv4' * 'show forwarding ipv4 vrf {vrf}' """ # Python import re import xmltodict #Metaparser from genie.metaparser import MetaParser from genie.metaparser.util.schemaengine import Schema, Any, Or, Optional # import parser uti...
#!/usr/bin/env python3 # Copyright (c) 2014-2016 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test the rawtransaction RPCs. Test the following RPCs: - createrawtransaction - signrawtransacti...
# -*- coding: utf-8 -*- # PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN: # https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code from ccxt.base.exchange import Exchange # ----------------------------------------------------------------------------- try: basestri...
# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: protos/public/modeldb/versioning/Environment.proto from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.protobu...
# coding=utf-8 # Copyright 2022 The Uncertainty Baselines 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 ap...
import threading import pyvoltbootstrap """Provides functionality for the game scripting engine to run scripts in separate threads.""" def filenameToModuleName(filename): """Converts a game data path to a module name.""" if filename.startswith('Scripts/'): filename = filename[8:] if filename.endsw...
from logger import logger logging = logger.getChild('utils.thread_utils') import threading def call_threaded(func, *args, **kwargs): #Call the given function in a daemonized thread and return the thread. def new_func(*a, **k): try: func(*a, **k) except: logging.exception("Thread %d with function ...
# To use this code, make sure you # # import json # # and then, to convert JSON from a string, do # # result = abstract_resource_from_dict(json.loads(json_string)) from dataclasses import dataclass from typing import Any, Callable, List, Optional, Type, TypeVar, cast T = TypeVar("T") def from_str(x: Any) ->...
"""Retrieve test functions from submodules.""" from setuptools import find_packages import pathlib import importlib import sys import os import re import json ROOT = pathlib.Path(__file__).parent.parent # Filched from nose.config.Config().testMatch TESTMATCH = re.compile( os.environ.get('NOSE_TESTMATCH', r'(?:^|[...
################################################################################ # # Class for simple handling of build configurations # ################################################################################ class BuildConfig: def __init__(self): self.ccflags = list() self.cxxflags = list() self...
from django.apps import apps # from rest_framework import serializers from rest_flex_fields import FlexFieldsModelSerializer from .favorite import FavoriteSerializer from .user import UserSerializer __all__ = [ 'FavoriteCollectionSerializer', ] Favorite = apps.get_model(*'favorites.Favorite'.split()) FavoriteCol...
""" OpenAI Gym compatible Driving simulation environment based on Carla. Requires the system environment variable CARLA_SERVER to be defined and be pointing to the CarlaUE4.sh file on your system. The default path is assumed to be at: ~/software/CARLA_0.8.2/CarlaUE4.sh """ from __future__ import absolute_import from __...
from discord.ext import commands import random as rng from collections import Counter from typing import Optional from .utils.formats import plural class RNG(commands.Cog): """Utilities that provide pseudo-RNG.""" def __init__(self, bot): self.bot = bot @commands.group(pass_context=True) asyn...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ description: bot 2.0 Using functions with assignment robot. Staying with what we have covered in class. although not a very practical, it servers as a good example to introduce class. Using the operator module: https://docs.python.or...
import sys from passlib.hash import pbkdf2_sha512 from sqlalchemy import Column, DateTime, String, Integer, Unicode, func from sqlalchemy.ext.declarative import declared_attr, has_inherited_table if sys.version_info < (3, 0): builtins = __import__('__builtin__') else: import builtins __version__ = '0.6' cla...
"""teaching_blog URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.1/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class...
""" examples that illustrate how to query articles using different search options """ from eventregistry import * er = EventRegistry() # search for the phrase "Barack Obama" - both words have to appear together q = QueryArticles(keywords = "Barack Obama") res = er.execQuery(q) # search for articles that mention bot...
from fpdf import FPDF, HTMLMixin import settings from rcheatsheets.contents.base import ContentBlock from rcheatsheets.contents.cheatsheet import CheatSheet from rcheatsheets.utils import mk_tmpfile class PDF(FPDF, HTMLMixin): pass class TOC(ContentBlock): def __init__( self, cheatsheets: l...
# Space: O(1) # Time: O(n) class Solution: def wiggleMaxLength(self, nums): if len(nums) == 1: return 1 if len(nums) == 2: return 1 if nums[0] == nums[1] else 2 res = 1 diff = nums[-1] - nums[-2] for i in range(len(nums)-2,-1,-1): if i == len(nums) - 2: ...
import torch.nn as nn from mmcv.cnn import ConvModule from mmdet.models.builder import HEADS from .bbox_head import BBoxHead @HEADS.register_module() class ConvFCBBoxHeadFeat(BBoxHead): r"""More general bbox head, with shared conv and fc layers and two optional separated branches. .. code-block:: none ...
#!/usr/bin/env python # $Id$ """ ? solutions """ import puzzler from puzzler.puzzles.polysticks1234 import Polysticks1234_3x7DiamondLattice puzzler.run(Polysticks1234_3x7DiamondLattice)
""" This module is a part of HoneySpot project. The module can be used to uncover GasPot honeypot. This is a work in progress and might give false results. """ #TODO: Add more fingerprinting methods import socket __name__ = "GasPot" # __proto__ = [] # Not sure default_port = 10001 # Terminal print codes OKGREEN = '...
"""Views for creating, editing and viewing site-specific user profiles.""" from __future__ import absolute_import from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User from django.core.exceptions import ObjectDoesNotExist from django.core.urlresolvers import reverse from...
# \ <section:top> # powered by metaL: https://repl.it/@metaLmasters/metaL#README.md ## @file from django.apps import AppConfig # / <section:top> # \ <section:mid> class AppConfig(AppConfig): name = 'app' verbose_name = 'Monitoring System' # / <section:mid> # \ <section:bot> # / <section:bot>
import pygame as pg from time import time from .utils import * class Explosion(pg.sprite.Sprite): def __init__(self, *groups): super().__init__(*groups) self.image = explosion_img.subsurface([0, 0, 0, 0]) self.rect = pg.rect.Rect([0, 0, 50, 50]) self.start_time = time() se...
# RUN: %PYTHON %s 2>&1 | FileCheck %s # This file contains small benchmarks with reasonably-sized problem/tiling sizes # and codegen options. from ..core.experts import * from ..core.harness import * from ..core.transforms import * from ..contraction.definitions import * ############################################...
#!/usr/bin/env python import argparse import audioop from googleapiclient.discovery import build import json import math import multiprocessing import os import requests import subprocess import sys import tempfile import wave from autosub.constants import ( LANGUAGE_CODES, GOOGLE_SPEECH_API_KEY, GOOGLE_SPEECH_API...
from base64 import b64encode from changes.constants import Result from changes.models import FailureReason, ItemStat from changes.models.testresult import TestResult, TestResultManager from changes.testutils.cases import TestCase def _stat(jobstep, name): id = jobstep.id return ItemStat.query.filter_by(name=...
# -*- coding: utf-8 -*- import time import csv import numpy as np from sklearn import neighbors def load_data(file): with open(file,'r') as csvfile: lines = csv.reader(csvfile) train_label, train_data = [], [] test_label, test_data = [], [] for i, line in enumerate(lines): ...
# List of global functions which will be used across the project # for various applications from pathlib import Path import datetime import math # Get NASA App Bearer Key def get_nasa_key(): file = get_home_dir() + '/nasa_app_bearer.txt' key = open(file, "r").read() # Return the key return key # Ge...
import requests url = "https://v16-web.tiktok.com/video/tos/alisg/tos-alisg-pve-0037c001/ba6b3bdaf3654b2180e64fa9e0389f9f/?a=1988&br=1108&bt=554&cd=0|0|1&ch=0&cr=0&cs=0&cv=1&dr=0&ds=3&er=&expire=1629907018&ft=9wMeReYO4kag3&l=202108250956500102451441315B2EC96B&lr=tiktok_m&mime_type=video_mp4&net=0&pl=0&policy=3&qs=0&...
"""Heatmaps and reward plotting code for debugging MountainCar.""" import pathlib import pickle from typing import Dict, List, Optional, Sequence, Union import gym import numpy as np from matplotlib import pyplot as plt from stable_baselines3.common import vec_env from imitation.data import rollout, types from imita...
""" This file offers the methods to automatically retrieve the graph Bartonella alsatica. The graph is automatically retrieved from the STRING repository. Report --------------------- At the time of rendering these methods (please see datetime below), the graph had the following characteristics: Datetime: 2021-02...
import sys import os import matplotlib.pyplot as plt import numpy as np import pandas as pd from mirnylib.genome import Genome from pileups import * import cooler from multiprocessing import Pool import h5py from itertools import chain def genome_pileup(c, regions, feature_locations_df, func): matrix_gen = fe...
import argparse import ast import codecs import collections import contextlib import keyword import re import string import sys import tokenize import warnings from typing import Any from typing import cast from typing import Container from typing import Dict from typing import Generator from typing import Iterable fro...
##-***************************************************************************** ## ## Copyright (c) 2009-2011, ## Sony Pictures Imageworks, Inc. and ## Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd. ## ## All rights reserved. ## ## Redistribution and use in source and binary forms, with...
import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText mail_content = "Usted tiene un turno con el medico XXXXXX en la fecha Febrero-1 a las 10 am" #The mail addresses and password sender_address = 'utnprogramacion3@gmail.com' sender_pass = 'h51kolv3' receiver_address = 'ms...
#! /usr/bin/env python """ This macro can be used to merge the information from the accurate HV map derived from pedestal runs studies with the old db map into a new accurate map. """ import sys print "Reading psu-detId map from map.txt" inputMap = open("map.txt", "r") outputFile = open("newMap.txt", "w") for lin...
""" Binary search trees are a data structure that enforce an ordering over the data they store. That ordering in turn makes it a lot more efficient at searching for a particular piece of data in the tree. This part of the project comprises two days: 1. Implement the methods `insert`, `contains`, `get_max`, and `for_eac...
# coding: utf-8 # Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved. # This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may c...
from app import flask_app as application if __name__ == "__main__": application.run()
#coding:utf-8 import os,os.path,traceback,time import pymongo import datetime import config import os """ 扫描db中所有collection进行实践排序 """ def make_bar(conn,collections=[] ): db = conn['Ctp_Tick'] if not collections: collections = db.collection_names() log = open('make-log.txt','w') idx = 0 f...
from setuptools import find_packages, setup import re PACKAGE_NAME = "custom-google-search" PACKAGE_NAME_UNDERLINE = PACKAGE_NAME.replace("-", "_") version = re.search( '^__version__\s*=\s*"(.*)"', open(f'{PACKAGE_NAME_UNDERLINE}/__init__.py').read(), re.M ).group(1) setup( name=PACKAGE_NAME, ...
# Contains routes and functions to pass content to the template layer import requests, json, os, math, bson, re, subprocess, ipdb, logging, time from flask import render_template, request, jsonify, abort, send_from_directory, Response, flash from flask import send_from_directory, redirect, url_for, jsonify from flask_l...
import os from talon import ( Module, actions, app, clip, cron, ctrl, imgui, noise, ui, ) from talon_plugins import eye_mouse, eye_zoom_mouse from talon_plugins.eye_mouse import config, toggle_camera_overlay, toggle_control key = actions.key self = actions.self scroll_amount = 0 cl...
# Copyright 2019 Shift Cryptosecurity AG # # 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...
DEBUG = True EXAMPLE_CLIENT_DOMAIN = 'http://localhost:5000' EXAMPLE_CLIENT_ID = 'example' EXAMPLE_PRIVATE_KEY = "r_UI603r3pD6OPkIki8xx8cQ3-3M7sIUnNNn55D-D-e="
# # PySNMP MIB module ADSL-TC-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ADSL-TC-MIB # Produced by pysmi-0.3.4 at Wed May 1 11:13:44 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 0...
# coding: utf-8 from __future__ import absolute_import from datetime import date, datetime # noqa: F401 from typing import List, Dict # noqa: F401 from openapi_server.models.base_model_ import Model from openapi_server import util class ResponseUploadToCloudModel(Model): """NOTE: This class is auto generated...
# built-in from pathlib import Path # project from flakeheaven._logic import get_exceptions def test_get_exceptions(tmp_path: Path): exceptions = { 'tests/': {'pyflakes': ['+*']}, 'test_*.py': {'pycodestyle': ['+*']}, } # prefix match tests_path = tmp_path / 'tests' tests_path.mk...
#!/usr/bin/env python # # VM Backup extension # # Copyright 2015 Microsoft 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 # # U...
import json import pickle from revscoring.scoring.statistics.classification.counts import Counts def test_counts(): c = Counts( [True, False], [({'prediction': True}, True)] * 10 + [({'prediction': True}, False)] * 20 + [({'prediction': False}, False)] * 30 + [({'predictio...
"""Some tools to work with Python. Not Python2.""" pass
mytuple = ("apple", "banana", "cherry") myit = iter(mytuple) print(next(myit)) print(next(myit)) print(next(myit)) try: print(next(myit)) except StopIteration: print("StopIteration error")
""" This module contains a "session saver" which saves the state of a NumPy session to a file. At a later time, a different Python process can be started and the saved session can be restored using load(). The session saver relies on the Python pickle protocol to save and restore objects. Objects which are not thems...
import unittest, frappe from frappe.utils.safe_exec import safe_exec, get_safe_globals class TestSafeExec(unittest.TestCase): def test_import_fails(self): self.assertRaises(ImportError, safe_exec, 'import os') def test_internal_attributes(self): self.assertRaises(SyntaxError, safe_exec, '().__class__.__call__'...
# -*- coding: utf-8 -*- # # rasa_core documentation build configuration file, created by # sphinx-quickstart on Fri Feb 24 16:18:03 2017. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # #...
# -*- coding: utf-8 -*- from __future__ import unicode_literals, absolute_import from twilio.twiml.messaging_response import MessagingResponse from twilio.rest import Client from .decorators import twilio_view import datetime @twilio_view def say(request, text, voice=None, language=None, loop=None): """ See: htt...
__all__ = ('functions', 'generators', 'load_module', 'simple_module')
import datetime as dt from posts.models import Profile def year(request): """ Добавляет переменную с текущим годом. """ year = dt.datetime.now().year return {'year': year} def user_count(request): """ Добавляет переменную с текущим годом. """ counts = Profile.objects.count() ...
import argparse import os import cv2 from tqdm import tqdm import numpy as np import torch from torch.autograd import Variable def main(): files = [ 'car1.mp4', 'car2.mp4', 'ped1.mp4', 'ped2.mp4', 'ped3.mp4', 'ped4.mp4', 'ped5.mp4', 'ped6.mp4', ...
import numpy as np from chainerrl import explorer class AdditiveGaussian(explorer.Explorer): """Additive Gaussian noise to actions. Each action must be numpy.ndarray. Args: scale (float or array_like of floats): Scale parameter. low (float, array_like of floats, or None): Lower bound of...
from flask import Flask,request import requests from datetime import date import time import random #token used by facebook page to access the webapp verifytoken='1234' #token given by facebook to be added to our responseto be able to use the bkaaieuaireu TOKEN='EAAiEn1AALuYBAF9r4ysLfTgrZA5hTpSTlUo7uDUbBV1iOiagLOmCC...
from japronto import Application # Views handle logic, take request as a parameter and # return the Response object back to the client def hello(request): return request.Response(text='Hello world!') # The Application instance is a fundamental concept. # It is a parent to all the resources and all the settings ...
import os from pathlib import Path from time import process_time from typing import Callable from collect.collector import collect_cpu_time, final_round from timetrial.time.checkpoint_time.checkpoint import checkpoint def cpu_timerun(collect_data=False, average=False, console=False) -> Callable: def wr...
# -*- coding: utf-8 -*- # @Time : 2021/8/16 # @Author : Lart Pang # @GitHub : https://github.com/lartpang
from django.db import models from django.contrib.auth import get_user_model User = get_user_model() # Create your models here. class SiteConfiguration(models.Model): name = models.CharField(max_length=30) icon = models.ImageField(upload_to='icon/', blank=True, null=True) banner = models.ImageField(uploa...
from jitlog.upload import upload
# Python import unittest from unittest.mock import Mock # ATS from pyats.topology import Device # Metaparset from genie.metaparser.util.exceptions import SchemaEmptyParserError, \ SchemaMissingKeyError # Parser from genie.libs.parser.nxos.show_igmp import ShowIpIgmpInterface, \...
# # SPDX-FileCopyrightText: Copyright (c) 1993-2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 # # 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...
from setuptools import setup setup( name='python-amazon-sp-api', version='0.2.3', install_requires=[ "requests", "six~=1.15.0", "boto3~=1.16.39", "cachetools~=4.2.0", "pycryptodome", "pytz", "confuse~=1.4.0", ], packages=['tests', 'tests.api',...
#!/usr/bin/env python3 # Copyright (c) 2017 The Bitcoin Core developers # Copyright (c) 2017-2018 The BitcoinSubsidium Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test the listsincelast RPC.""" from test_fra...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from common import layers from common import tf from common.tf_util import get_attention_mask from .layers.transformer import BertEmbedding from .layers.transformer import BertEncoder class Ebert(layers.Layer): def __init__(self, config): super().__init__(na...
import os import sys import time from typing import Union, List, Tuple print("初始化程序开始执行") print("开始检查依赖") print(r"是否使用 http://pypi.douban.com/simple/ 源") use_i = input(r"[Y/n]") if use_i == "Y" or use_i == 'y': use_i = r"-i http://pypi.douban.com/simple/ --trusted-host pypi.douban.com" else: use_i = "" try: ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # from shiao's tornado.third.renren # sina weibo # oauth2 mixin classes import logging import hashlib import requests import time from tornado import escape from tornado import httpclient from tornado import gen from tornado.escape import json_decode from tornado.httputi...
from collections import Counter class Solution: def shortestSeq(self, big: List[int], small: List[int]) -> List[int]: counter = Counter(small) ret = [] cnt = 0 l, r = 0, 0 for r in range(len(big)): if big[r] in counter: if counter[big[r]] == 1: ...
# -*- coding: utf-8 -*- # Define here the models for your scraped items # # See documentation in: # http://doc.scrapy.org/en/latest/topics/items.html import scrapy class CarsItem(scrapy.Item): """Cars item.""" # info brand_id = scrapy.Field() fct_id = scrapy.Field() series_id = scrapy.Field() ...
from datetime import datetime, timedelta from airflow.models import DAG from airflow.models.baseoperator import chain from rockflow.dags.const import * from rockflow.es_indexs.search import search_setting from rockflow.operators.futu import * from rockflow.operators.symbol import * from rockflow.operators.yahoo impor...
"""Tests for josepy.util.""" import functools import unittest import six from josepy import test_util class ComparableX509Test(unittest.TestCase): """Tests for josepy.util.ComparableX509.""" def setUp(self): # test_util.load_comparable_{csr,cert} return ComparableX509 self.req1 = test_util....
from django.shortcuts import render, redirect from .forms import UserRegisterForm, UserUpdateForm, ProfileUpdateForm from django.contrib import messages from django.contrib.auth.decorators import login_required from django.contrib.auth import views as auth_views def register_view(request): if request.method == "P...
from merlin.modules.activation import Activation, NormalizingActivation from merlin.modules.normalization import Normalization from alchemy.networks.xception import Xception, Xception65 from alchemy.models.deeplab.model import (Decoder, Encoder, ...
from .serializers import NodesSerializer, MacsSerializer, IpHistorySerializer from .models import Nodes, Macs, BtIphistory from core.views import BaseViewSet import core.iptools as iptools import ipaddress class NodeViewSet(BaseViewSet): """Manage Nodes in the database""" queryset = Nodes.objects.all() se...
"""BaseAdapter for the network importer. (c) 2020 Network To Code 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...
from django.apps import AppConfig class HdfsConfig(AppConfig): name = 'hdfs'
import os import itertools import time import copy import random import functools import platform from unittest import mock import pytest from jaraco.classes import properties from jaraco.functools import Throttler, method_cache, retry_call, retry class TestThrottler: @pytest.mark.xfail( os.environ.get(...
import os import sys import argparse import shutil import traceback def main(): cmd_parser = argparse.ArgumentParser(description='Get the precompiled libs from the IDF') cmd_parser.add_argument('--idflibs', default=None, help='the path to the idf libraries') cmd_args = cmd_parser.parse_args() src = c...
# -*- coding: utf-8 -*- # Generated by Django 1.11.11 on 2019-10-21 16:27 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.Cre...
class Adam: """ Apply Gradint Descent algorithm with momuntum """ def __init__(self , beta1 , beta2 , learning_rate , network_layers ): """ C = 0 : refer to momuntum learning_rate = 0.01 : learning rate which used in learning process """ self.beta1 = be...
from pathlib import Path import re from setuptools import setup, find_namespace_packages # Package properties sub_package = "functions" min_python = (3, 6) python_requires = ">=3.6" install_requires = [] extras_require = {"extra": ["sidekick.core"]} # Package properties version_re = re.compile(r"""__version__\s+=\s+[...
#!/usr/bin/env python import subprocess import os import sys import glob import json import traceback import re import logging log = logging.getLogger('run-ci') import time import threading from benchmark import framework_test from benchmark.utils import gather_tests from benchmark.utils import header # Cross-platfor...
#!/usr/bin/env python """ Copyright (c) 2006-2017 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ import re from lib.core.enums import HTTP_HEADER from lib.core.settings import WAF_ATTACK_VECTORS __product__ = "USP Secure Entry Server (United Security Providers)" def de...
import numpy as np from .. import Mesh, Utils from scipy.special import ellipk, ellipe from scipy.constants import mu_0 import properties orientationDict = { "X": np.r_[1.0, 0.0, 0.0], "Y": np.r_[0.0, 1.0, 0.0], "Z": np.r_[0.0, 0.0, 1.0], } def MagneticDipoleVectorPotential( srcLoc, obsLoc, component...
"""The parameters dictionary contains global parameter settings.""" from collections import OrderedDict from os import environ from functools import wraps from devito.tools import Signer, filter_ordered __all__ = ['configuration', 'init_configuration', 'print_defaults', 'print_state', 'add_sub_configurati...
import random player1 = 0 player2 = 0 odd = [1, 3, 5] even = [2, 4, 6] counter = 0 roll = raw_input("say how many times you would like to roll dice: ") while 0 != 1: if counter <= roll: for item in range(int(roll)): dice = random.randint(1, 6) if dice in odd: player1 ...
import click from barique.cli import pass_context, json_loads from barique.decorators import custom_exception, dict_output @click.command('remove') @click.argument("task_id", type=str) @pass_context @custom_exception @dict_output def cli(ctx, task_id): """Remove task with the selected id Output: Dict ""...
import tarfile, os def make_tar(folder_to_backup, dest_folder, compression='bz2'): if compression: dest_ext = '.' + compression else: dest_ext = '' arcname = os.path.basename(folder_to_backup) dest_name = '%s.tar%s' % (arcname, dest_ext) dest_path = os.path.join(dest_folder, dest_nam...