content
stringlengths
5
1.05M
def user_greet(): print("hope you Doing well") print("god luck for game") name= input("Hi, what is your name? : ") print(f"welcome {name}... ") user_greet()
#!/usr/bin/env python # ms8607/RFM69 indoor sensor import machine from machine import I2C, Pin, RTC from radios import rfm69 import utime as time import ujson as json import gc import dht NODEID = 4 #unique for each node on same network PARTNERID = 1 NETWORKID = 61 #the same on all nodes that talk to ea...
__author__ = "Zafar Ahmad, Mohammad Mahdi Javanmard" __copyright__ = "Copyright (c) 2019 Tealab@SBU" __license__ = "MIT" __version__ = "1.0.0" __maintainer__ = "Zafar Ahmad" __email__ = "zafahmad@cs.stonybrook.edu" __status__ = "Development" import numpy as np import glob import paf_kernels import protien as pf #TODO:...
""" Tools for dynamic inventories """ import click import osa.utils as utils # The dynamic inventory gets the default folder locations # as options. This makes the folder locations available # for all its sub commands # @osa.cli.entrypoint.group() @click.group() @utils.pass_folder_locations def dynamic_inventory(ctx,...
import speech_recognition as sr import pyttsx3 import pywhatkit import datetime import wikipedia import pyjokes listener = sr.Recognizer() engine = pyttsx3.init() voices = engine.getProperty('voices') engine.setProperty('voice', voices[1].id) def talk(text): engine.say(text) engine.runAndWait() def takeCommand(): ...
#write a flask API which can return square of a number from flask import Flask, jsonify app = Flask(__name__) @app.route('/',methods=["GET"]) def home_page(): message = "Hello , I am learning development of API in GCP " response = {'my_response':message} return jsonify(response) @app.route("/calculate/<i...
class BST: def __init__(self, value): self.value = value self.left = None self.right = None def foo(tree, target, best): if not tree: return best if abs(target - tree.value) < abs(target - best): best = tree.value if tree.value == target: return tree.v...
import socket import enum import os import asyncio from collections import deque # for using stacks from time import time from async_timeout import timeout from .tls_definitions import ( Contents, Handshakes, Protocols, ProtocolCiphers, EcPointFormats, SupportedGroups, TLS_EMPTY_RENEGOTIAT...
""" The minimalist yet fully featured Twitter API and Python toolset. For building your own applications, look at the `Twitter` class. """ from api import *
import os import tensorflow as tf from tensorflow.keras import layers, optimizers, datasets, models import numpy as np import matplotlib.pyplot as plt from sklearn.utils import shuffle def texture_dataset(split_Train_Test=0.9): xAll = np.load('data.npy') yAll = np.load('groundTruth.npy') x = xAll[0:np.in...
from tensortrade.env.default.observers import _create_internal_streams, _create_wallet_source from tensortrade.feed.core import DataFeed, Stream from tensortrade.oms.exchanges import Exchange from tensortrade.oms.services.execution.simulated import execute_order from tensortrade.oms.wallets import Wallet, Portfolio fr...
from recipes.rfc7636_challenge_generator import __recipe__ import click @click.command() @click.option('--code-verifier', '-c', required=True, help='Code verifier string') def main(code_verifier): # noqa: D101 code_challenge = __recipe__.calculate_code_challenge(code_verifier) print(code_chall...
from django.urls import path from . import views urlpatterns = [ path('upload/', views.BatchList.as_view(), name="upload-list"), path('upload/<uuid:pk>/', views.BatchDetail.as_view(), name="upload-detail"), path('profile/', views.ProfileList.as_view(), name="profile-list"), path('profile/<uuid:pk>/', ...
#! /usr/bin/env python3 # coding: utf-8 from __future__ import annotations import sys import time import pendulum import schedule from gargbot_3000 import config, database, greetings from gargbot_3000.health import health from gargbot_3000.journey import journey from gargbot_3000.logger import log def local_hour_a...
#encoding: utf-8 import json from django.conf import settings from base.management import RabbitMQWatcher from agent.models import Client class Command(RabbitMQWatcher): help = 'Agent Heartbeat' def get_config(self): return settings.RABBITMQ['QUEUE_HEARTBEAT'], settings.RABBITMQ['EXC...
from django.contrib import admin from .models import Redditor @admin.register(Redditor) class RedditorAdmin(admin.ModelAdmin): """Settings for the Redditor table in admin page.""" list_display = ('username', 'analysis_date', 'result') list_filter = ['analysis_date', 'result'] search_fields = ['usern...
# -*- coding: utf-8 -* #!/usr/bin/python from dealctrl import * from fun_activity import * import time class deal_6_require_list(dealctrl): def __init__(self,con): dealctrl.__init__(self,con) def run(self): userid=int(self.recvdic['userid']) anum=int(self.recvdic['anum']) order...
import numpy as np import pandas as pd from sklearn import tree from sklearn.ensemble import (AdaBoostClassifier, GradientBoostingClassifier, RandomForestClassifier) from sklearn.feature_extraction.text import (CountVectorizer, HashingVectorizer...
# -*- coding: utf-8 -*- # Generated by Django 1.10.4 on 2017-01-11 03:24 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('courses', '0005_quiz'), ] operations = [ m...
n = int(input()) a = list(map(int, input().split())) s = 0 m = int(10 ** 9 + 7) for i in range(n-1): for j in range(i + 1, n): s += (a[i] ^ a[j]) print(s % m)
from django.test import TestCase, Client from django.urls import reverse class TestImage(TestCase): def setUp(self): self.client=Client() def test_get_image_by_filter_with_no_json(self): response = self.client.post(reverse('get-image')) assert response.status_code,400 def test_ge...
from datacube_ows.wms import handle_wms from datacube_ows.wcs1 import handle_wcs1 from datacube_ows.wcs2 import handle_wcs2 from datacube_ows.wmts import handle_wmts from datacube_ows.ogc_exceptions import WCS1Exception, WCS2Exception, WMSException, WMTSException from datacube_ows.ows_configuration import get_config ...
""" metrics A module to calculate additional baseball statistics based on results produced with ncaa_scraper module created by Nathan Blumenfeld in Spring 2022 """ from collegebaseball import datasets import pandas as pd import numpy as np import warnings warnings.filterwarnings("ignore") # filepath of D1 linear we...
""" Utilities to aid in analysis and publication of NumPy Community Survey results. """ def flatten(data, delimiter=','): """ Expand ragged unicode arrays with ``delimiter``-separated rows into a flat array of individual entries. Parameters ---------- data : numpy.ndarray with unicode dtype ...
import numpy as np import random import torch from torch.backends import cudnn from absl import app, flags from datasets import ML1M, ML100K, Flixster, Douban, YahooMusic from model import GCCF from hyperparameters import hparams from utils import get_adj cudnn.deterministic = True cudnn.benchmark = False seed = 12...
from lineinfile import AtEOF line = "gnusto=cleesh" args = {"inserter": AtEOF()} options = ["--eof"]
import sage from sage.all import * import sys from pprint import pprint with open ("/home/tapir/mausi.txt", "w") as f: f.write("%s" % sys.path) def testDelieriumFunction(): var('x') u = function ("u")(x) d = diff (u,x) assert is_derivative (d) assert not is_derivative (u)
from random import randint import sys class PasswordGenerator: # string of upper characters upper_characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' # string of lower characters lower_characters = 'abcdefghijklmnopqrstuvwxyz' # string of numbers numbers = '0123456789' #string of special charact...
#!/usr/bin/python # # This code is designed soley for the purposes of demonstrating the tools # for timeshifting. # import dvb3 from Axon.Component import component from Kamaelia.Device.DVB.Core import DVB_Multiplex from Kamaelia.Util.PipelineComponent import pipeline from Kamaelia.Internet.Multicast_transceiver impor...
# codeing from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.queryAll), url(r'^page/(\d+)$', views.queryAll), url(r'^post/(\d+)$', views.detail), url(r'^category/(\d+)$',views.queryPostByCid), url(r'^archive/(\d+)/(\d+)$',views.queryPostByCreated), ]
# -*- coding: utf-8 -*- """ Created on Tue Mar 24 14:22:44 2020 @author: asbjornu """ import pytest import schedule_tester def test_open_schedule(): print(schedule_tester) def
# Copyright Contributors to the Packit project. # SPDX-License-Identifier: MIT import os import subprocess from pathlib import Path from click.testing import CliRunner from dist2src.cli import cli from packit.cli.packit_base import packit_base from packit.utils import cwd TEST_PROJECTS_WITH_BRANCHES = [ # %autos...
#Filename : 9x9.py #author by: Thomas.Wu #use for print("------------------Use for to do 9x9----------------") for i in range(1, 10): for j in range(1, i+1): print('{}x{}={}\t'.format(j, i, i*j), end='') print() #V2 #use while print("------------------Use While to 9x9------------------") i = 1 while i...
import facebook import json import mysql.connector token = 'CAAF4ZCgDktEIBALPG0G7JSR4hz9e48jVh8OgZC2lSIzYcaOGZCAZAkc4UZBITmHBXjIfdw00Hg2cp1TVMFsU4dsB5UjbvkMVR2rv63dcdY61L21cPqukYDTYzUAPQV1DZAGmPzvL7vG3ewY9uSEsunZCg6LRcwWdnUZBRE4LPOxYCB1ovlmfUlrcnOe9dzE86weIHaafgiJ2WGhcxVN06ibj' product = "Symantec" #get the product ...
# encoding: utf-8 """Routines for sampling from the Haar measures of the classical compact groups. Algorithms taken from http://arxiv.org/abs/math-ph/0609050. """ from __future__ import division, print_function import numpy as np from scipy.linalg import qr def orthogonal_haar(dim, rgen=np.random): """Returns a...
#!/usr/bin/env python import logging from optparse import OptionParser import os from osgeo import ogr def log_file_fields(filename): print("File: " + filename) source = ogr.Open(filename) for i in range(source.GetLayerCount()): layer = source.GetLayerByIndex(i) layerName = layer.GetName(...
""" Source type-dependencies. Helioviewer JPEG2000 files have stretched images compared to the FITS data. """ from astropy.visualization import LinearStretch __author__ = "Jack Ireland" __email__ = "jack.ireland@nasa.gov" __all__ = ['from_helioviewer_project', 'source_stretch'] def from_helioviewer_project(meta):...
#!/bin/env python # Automatically translated python version of # OpenSceneGraph example program "osgcallback" # !!! This program will need manual tuning before it will work. !!! import sys from osgpypp import osg from osgpypp import osgDB from osgpypp import osgUtil from osgpypp import osgViewer # Translated from...
import json from django.http import JsonResponse from django.shortcuts import render from . import models # Create your views here. from .biz import ticket_biz def left_ticket_list(request): ''' 查询余票页面 :param request: :return: ''' # 所有车站信息,查询需要用到车站编码 stations = models.TS...
from typing import List import numpy as np from objects.order import Order # random.seed(1234) np.random.seed(1234) # torch.manual_seed(1234) # torch.cuda.manual_seed_all(1234) # torch.backends.cudnn.deterministic = True class Vehicle(object): def __init__(self, id: int): self.id = id # This vehicle's...
import typing # noqa: F401 from kubernetes import client # noqa: F401 from kuber import kube_api as _kube_api # noqa: F401 from kuber import definitions as _kuber_definitions # noqa: F401 from kuber import _types # noqa: F401 from kuber.latest.meta_v1 import ListMeta # noqa: F401 from kuber.latest.meta_v1 impor...
import random #User mit der Application vertraut machen print("Das hier ist ein Zufallsgenerator-Würfel-Programm.\n\n" "Das Programm bietet ihnen die Möglichkeit im folgenden " "festzulegen wie viele Würfelseiten ihr Würfel haben soll.\n" "Anschließend dürfen sie dann raten auf welche Würfelseite de...
from dynpric.firms.ferreira2018 import constraint_price_prob_is_positive def test_constraint_price_prob_is_positive(): assert constraint_price_prob_is_positive(1) == [ ((-1,), 0), ] assert constraint_price_prob_is_positive(2) == [ ((-1, 0), 0), ((0, -1), 0), ] assert constr...
# -*- coding: utf-8 -*- # Copyright 2019 New Vector Ltd # # 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...
""" * Copyright (c) 2019 Memfault, Inc. * * Significant portions of this code has been copied from: * https://github.com/memfault/interrupt/tree/master/example/fwup-architecture * * Some modifications have been made by Wavious, LLC. * * SPDX-License-Identifier: MIT """ import argparse import binascii import os import ...
''' Below stack is for PUT mode. The GET mode is almost the same as put mode, just inverse the Source and Destination buckets. And auth the read and write access for ec2 role Dont forget to change the JobTpe to GET in s3_migration_cluster_config.ini ''' import json from aws_cdk import core import aws_cdk.aws_ec2 as ec2...
"""test for profile_loader module.""" from StringIO import StringIO import itertools try: # py3 from unittest import mock except ImportError: # py2 import mock import pytest @pytest.mark.parametrize( 'skip_message, isfile_retval', itertools.product([True, False], repeat=2) ) def test_load_profile(s...
def foo(): return "bipp" def bar(): return foo() def baz(): return bar() def why(): return "elle" if True: baz() else: why()
#!/usr/bin/env python from distutils.core import setup setup( name="hello_project", version="1.0", description="Test project", author="Joe Hamman", author_email="joe@carbonplan.org", url="https://github.com/carbonplan/test-docs-project", packages=["hello_project"], )
# Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: # ans = l1 # while l1 and l2: # tmp1 = l1.next # tmp2 = l2.next ...
#!/usr/bin/env python from random import randint, random def auction(players, start=0, step=1): print("players", players) x = start # x is current price highest_bidder = None while True: print("highest_bidder", highest_bidder, '; x', x) if all(p<x for p in players): retur...
# preprocessor.py # Предварительная обработка # Импорт import numpy as np import nltk.tokenize # Препроцессор from comments_reader import JsonCorpusReader from transformer import TextNormalizer from random import shuffle # Для векторизатора from gensim.models.word2vec import Word2Vec class Preprocessor: def __in...
import os import sys sys.path.append("./") from three_bit_memory import make_batch from pyrnn import CTRNN as RNN from pyrnn.analysis.dimensionality import get_n_components_with_pca from pyrnn.analysis import FixedPoints, list_fixed_points from pyrnn.plot import ( plot_eigenvalues, plot_eigenvalues_magnitude...
import brownie import pytest from brownie import ZERO_ADDRESS, chain YFI = "0x0bc529c00c6401aef6d220be8c6ea1667f6ad93e" YFI_USD_FEED = "0xa027702dbb89fbd58938e4324ac03b58d812b0e1" WETH = "0x82aF49447D8a07e3bd95BD0d56f35241523fBab1" WETH_USD_FEED = "0x5f4ec3df9cbd43714fe2740f5e3616155c5b8419" @pytest.fixture def cal...
inception['n'].isna().sum()
__author__ = 'chase.ufkes' import time import bittrex import datetime import re def lastOrderValue(market, apiKey, apiSecret): api = bittrex.bittrex(apiKey, apiSecret) lastOrder = api.getorderhistory(market, 0) if lastOrder: return lastOrder[0]['PricePerUnit'] else: currentValue = api....
''' https://www.codeeval.com/open_challenges/147/ ''' import sys def main(): with open(sys.argv[1],'r') as word_file: for line in word_file.readlines(): line = line.strip() lower = [c for c in line if c.islower()] upper = [c for c in line if c.isupper()] lratio = len(lower)*1.0/(len(line))*100 uratio...
import os import zipfile from django.conf import settings from django.template import TemplateDoesNotExist #import django.template.loaders.app_directories.Loader import sys from django.utils.importlib import import_module from django.core.exceptions import ImproperlyConfigured import logging from django.template.loader...
#!/usr/bin/env python3 """ Created on 2021-12-23 13:37 @author: johannes """ import pathlib import pandas as pd PATH = pathlib.Path(__file__).parent.parent DATA_PATH = PATH.joinpath("data").resolve() df = pd.read_feather(DATA_PATH.joinpath('testdata')) df['timestamp'] = df['timestamp'].apply(pd.Timestamp) dates = ...
import warnings import sqlite3 from datadog import statsd from connectors.DbConnector import DbConnector from utility import nb_logging from utility.NbConfig import NbConfig import rollbar logger = nb_logging.setup_logger('SqliteClient') STATSD_PREFIX = 'nb.SqliteClient.' class SqliteClient(DbConnector): def...
import torch import torch.nn as nn from torch.nn.parameter import Parameter from .coordconv import CoordConv, AddCoords ''' An alternative implementation for PyTorch with auto-infering the x-y dimensions. ''' class AddSine(AddCoords): def __init__(self, alpha=0.5, beta=None, phase_shift=0.): super(AddSi...
s=input() # Using additional data structures counter=[0 for i in range(256)] # 1-byte chars b=0 for i in s: if counter[ord(i)]==1: b=1 print('NO') break else: counter[ord(i)]=1 if b==0: print('YES') # Without using additional data structures s=sorted(s) for i in range(len...
# -*- coding: utf-8 -*- """ AWattPrice default values """ __author__ = "Frank Becker <fb@alien8.de>" __copyright__ = "Frank Becker" __license__ = "mit" from enum import Enum DEFAULT_CONFIG = """ [general] # Also if set to no debug logs will be outputted. If set to yes the Backend will enable/disable certain # code...
from .error import list as error_list
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # --------------------------------------------------------------------...
# cvworkflow/kkcalcfunctions.py import kkcalc from kkcalc import data from kkcalc import kk import numpy as np import pandas as pd import matplotlib from matplotlib.pyplot import * import matplotlib.pyplot as plt import matplotlib.cm as cm def kkcalc_convert(file_path, *, chemical_formula, density, min_ev, max_ev, ...
''' youtubeAlbumParser.py A python script for parsing a youtube album into individual songs First argument is url of video Second argument is the name for the songs Tom Kelly ''' from bs4 import * # beautiful soup import sys import urllib2 import re try: url = sys.argv[1] except: url = raw_input('...
import numpy as np import pandas as pd from sklearn.preprocessing import LabelEncoder from sklearn.preprocessing import StandardScaler from lasagne.layers import DenseLayer from lasagne.layers import InputLayer from lasagne.layers import DropoutLayer from lasagne.layers import * from lasagne.nonlinearities import softm...
"""An example file showing how to make a geometry. This particular example creates a 2x2 geometry, with 3 regular pins and one Gd-157 2 wt-percent enriched. The geometry is reflected, with reflections going through the center of the Gd-157 pin. Said pin is split into 5 rings. """ import function import openmc impor...
from fonduer.features.models.feature import Feature, FeatureKey __all__ = ["Feature", "FeatureKey"]
""" Sentence Similarity II We can represent a sentence as an array of words, for example, the sentence "I am happy with leetcode" can be represented as arr = ["I","am",happy","with","leetcode"]. Given two sentences sentence1 and sentence2 each represented as a string array and given an array of string pairs simil...
import multiprocessing import time from tqdm import * # list = [1, 2, 3, 4] def func(i): msg = "hello %d" % (list[i]) print ("msg:", msg) time.sleep(3) print("end") list = [1, 2, 3, 4] data = [] if __name__ == "__main__": pool = multiprocessing.Pool(processes = 4) # list = [1, 2, 3, 4] fo...
from .feature import Feature from .models import BaseModel
# Copyright 2019 Rackspace US Inc. 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...
# # All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or # its licensors. # # For complete copyright and license terms please see the LICENSE at the root of this # distribution (the "License"). All use of this software is governed by the License, # or, if provided, by the license below or th...
# Copyright 2014 Amazon.com, Inc. or its affiliates. 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. A copy of # the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" file accompa...
from .core import JuliaError from .core import LegacyJulia as Julia from .ipy.revise import disable_revise, enable_revise from .release import __version__ from .tools import install
import os import unittest import zope.testrunner from zope import component from sparc.testing.fixture import test_suite_mixin from sparc.testing.testlayer import SPARC_INTEGRATION_LAYER from sparc.db.splunk.testing import SPARC_DB_SPLUNK_INTEGRATION_LAYER from zope import schema from zope.interface import Interface c...
# -*- coding: utf-8 -*- """ test_conversation ~~~~~~~ :copyright: (c) 2018 ONSEI GmbH :license: Proprietary """ import pytest from flask_dialogflow.agent import DialogflowConversation from flask_dialogflow.context import ContextManager from flask_dialogflow.conversation import ( V2DialogflowConver...
import os from .CompressionHelper import BROTLI_MAGIC, GZIP_MAGIC from ..EndianBinaryReader import EndianBinaryReader from ..enums import FileType def file_name_without_extension(file_name: str): return os.path.splitext(os.path.basename(file_name))[0] def list_all_files(directory: str): return [ val for subl...
#!/usr/bin/env python3 # # Copyright (c) 2015 - 2022, Intel Corporation # SPDX-License-Identifier: BSD-3-Clause # import sys import unittest import os import pandas import geopmpy.io import geopmpy.agent from integration.test import util from integration.test import geopm_test_launcher class TestIntegration_powe...
import requests from decouple import config def get_route_string(s): if s == 'index': return '/' return '/' + s.replace('_','/').replace('0', ':') def api(url, params = {}, method = 'get'): API_KEY = config('API_KEY', default='') BASE_URL = 'https://admin.studyabacus.com' url = BASE_URL + url headers =...
from bst import BinarySearchTree from dqn_agent import Agent import random import numpy as np import torch import torch.nn as nn import torch.optim as optim import torch.nn.functional as F import torchvision.transforms as T import math MAX_DEPTH = 4 state_size = 10 nodeValues = range(0,11) branchValues...
import matplotlib.pyplot as plt import numpy as np import math from numpy.linalg import inv import matplotlib.colors as colors from matplotlib import cm from matplotlib import rc __author__ = 'ernesto' # if use latex or mathtext rc('text', usetex=False) rc('mathtext', fontset='cm') # auxiliar function for plot tick...
#!/usr/bin/env python # -- encoding: utf-8 -- # # Copyright 2015-2016 Telefónica Investigación y Desarrollo, S.A.U # # This file is part of FI-WARE project. # # 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...
""" Code is generated by ucloud-model, DO NOT EDIT IT. """ import typing from ucloud.core.client import Client from ucloud.services.ipsecvpn.schemas import apis class IPSecVPNClient(Client): def __init__( self, config: dict, transport=None, middleware=None, logger=None ): super(IPSecVPNClie...
# This code is an adaptation of the code published in: # https://github.com/lazyprogrammer/machine_learning_examples import numpy as np ITEMS = 10 DIMENSIONS = 2 # Create NxD normally distributed data matrix data = np.random.randn(ITEMS, DIMENSIONS) # Adding a bias vector of ones to shift the activation curve to th...
import gspread import json from oauth2client.service_account import ServiceAccountCredentials import datetime from pageSpeedTest import * secret_file = 'client_secret.json' # json_key = json.load(open(secret_file)) # OAuth 2 Authorize scope = ['https://spreadsheets.google.com/feeds'] credentials = ServiceAccountCre...
# -*- coding: utf-8 -*- """Helper functions for SQLite database support.""" from __future__ import unicode_literals import os import tempfile try: from pysqlite2 import dbapi2 as sqlite3 except ImportError: import sqlite3 from dfvfs.lib import py2to3 class SQLiteDatabaseFile(object): """SQLite database file...
from mtcnn import MTCNN import cv2 import sys from PIL import Image, ImageDraw, ImageFont def GetFaces(image_name): img = cv2.cvtColor(cv2.imread(image_name), cv2.COLOR_BGR2RGB) detector = MTCNN() detected = detector.detect_faces(img) return detected def SetFaceCount(count): height, width = image...
import random from tkinter import * import tkinter.simpledialog as simpledialog import tkinter.messagebox as messagebox # Make variables pstrength = 0 pdefense = 0 phealth = 0 pmaxhp = 0 pintelligence = 0 pname = "null" mstrength = 0 mdefense = 0 mhealth = 0 mname = "null" mdamge = 0 pdamage = 0 bcounter = 0 message...
# Combination of synthetic graph generators # (first used in subgraph matching and motif mining) import logging import networkx as nx import numpy as np import deepsnap.dataset as dataset class ERGeneratorEdgesCase(dataset.Generator): def __init__(self, sizes, p_alpha=1.3, shift_parameter = 1.0, **kwargs): ...
from pyloa.environment import DefaultPagingEnvironment from pyloa.instance import RandomSequenceGenerator from pyloa.agent import * # vars sequence_size = 1000 max_page = 6 min_page = 1 episodes = 100 # hyperparams params = { 'checkpoint_step': 0, 'instance': { 'type': RandomSequenceGenerator, ...
from subprocess import CalledProcessError import pytest from path import Path from archetypal import ( IDF, EnergyPlusProcessError, EnergyPlusVersion, EnergyPlusVersionError, InvalidEnergyPlusVersion, parallel_process, settings, ) from archetypal.eplus_interface.version import get_eplus_di...
def assertThrowsDeferred(test_suite, deferred, exception_class=None): errs, calls = [], [] deferred.addCallbacks(calls.append, errs.append) test_suite.assertEqual(len(calls), 0, "Expected no callbacks, got {}".format(len(calls))) test_suite.assertEqual(len(errs), 1, "Expected exactly one errback, got {}...
import pkg_resources import yaml def get_ip_detect(name): return yaml.dump(pkg_resources.resource_string('gen', 'ip-detect/{}.sh'.format(name)).decode()) def calculate_ip_detect_public_contents(aws_masters_have_public_ip): return get_ip_detect({'true': 'aws_public', 'false': 'aws'}[aws_masters_have_public_...
import time class TrainingLogger(object): def __init__(self, print_freq=1): self.print_freq = print_freq print("+++++++++++++++ Training initialized +++++++++++++++") self.start = time.time() def log_train_step(self, epoch, epochs, step, train_loader_len, step_losses_me...
import json import threading from threading import Lock from EOSS.explorer.diversifier import activate_diversifier from EOSS.models import EOSSContext, Design from auth_API.helpers import get_user_information from daphne_context.models import UserInformation design_lock = Lock() def add_design(design, session, user...
from unittest import TestCase import mock from cloudshell.cp.azure.common.azure_clients import AzureClientsManager class TesAzureClientsManager(TestCase): def setUp(self): self.cloud_provider = mock.MagicMock() with mock.patch("cloudshell.cp.azure.common.azure_clients.ServicePrincipalCredential...
def make_alphabets(): return [chr(i) for i in range(ord('a'), ord('z') + 1)]