content
stringlengths
5
1.05M
"""AWS DynamoDB backed storage In AWS, there will be one Machine executing in the current context, and others executing elsewhere, as part of the same "session". There is one Controller per session. Data per session: - futures (resolved, value, chain, continuations - machine, offset) - machines (probe logs, state - i...
from systemtools.logger import * from systemtools.duration import * from systemtools.file import * from systemtools.basics import * from systemtools.location import * from systemtools.system import * from datastructuretools.basics import ListChunker from collections import defaultdict from sparktools.utils import * fr...
import os from argparse import Namespace, ArgumentParser from logging import Logger from consolebundle.ConsoleCommand import ConsoleCommand from consolebundle.StrToBool import str2Bool from databricks_cli.dbfs.api import DbfsApi from databricks_cli.dbfs.dbfs_path import DbfsPath class DbfsUploadCommand(ConsoleCommand)...
from chunkflow.flow.flow import main main()
import textwrap import requests_mock import transaction from purl import URL from onegov.form import FormCollection from onegov.pay import PaymentProviderCollection def test_setup_stripe(client): client.login_admin() assert client.app.default_payment_provider is None with requests_mock.Mocker() as m: ...
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. """Microbenchmark benchmark example for TCP connectivity. Commands to run: python3 examples/benchmarks/tcp_connectivity.py """ from superbench.benchmarks import BenchmarkRegistry from superbench.common.utils import logger if __name__ == '__m...
# coding=utf-8 from OTLMOW.OTLModel.Datatypes.KeuzelijstField import KeuzelijstField from OTLMOW.OTLModel.Datatypes.KeuzelijstWaarde import KeuzelijstWaarde # Generated with OTLEnumerationCreator. To modify: extend, do not edit class KlUitlaatType(KeuzelijstField): """De verschillende types van uitlaat.""" na...
#!/usr/bin/python """Summarize the results of many RAPPOR analysis runs. Takes a list of STATUS.txt files on stdin, and reads the corresponding spec.txt and log.txt files. Writes a CSV to stdout. Row key is (metric, date). """ import collections import csv import json import os import re import sys # Parse bash '...
"""Django admin site settings for core models.""" from django.contrib import admin from pykeg.core import models from pykeg.core.util import CtoF class UserAdmin(admin.ModelAdmin): list_display = ( "username", "email", "date_joined", "last_login", "is_active", "is_...
# -*- coding: utf-8 -*- """ Created on Thu Feb 28 05:05:15 2019 @author: FC """ import confmap as cm import numpy as np im = cm.HyperbolicTiling('./Reflets.jpg',1,'',600,600) im.transform(sommets=(6,4),nbit=20,backcolor=[255,255,255], delta=1e-3)
from interfacebuilder.misc import * import spglib class interactive_plot: def plot_results(self, jitter=0.05): """ Plots results interactively. Generates a matplotlib interface that allows to select the reconstructed stacks and save them to a file. Args: jitter (float,...
import datetime from python_to_you.extensions.database import db from sqlalchemy_serializer import SerializerMixin class Groups(db.Model, SerializerMixin): __tablename__ = 'groups' id = db.Column(db.Integer, primary_key=True) user_id = db.Column(db.ForeignKey('users.id', ondelete="CASCADE")) create_po...
from lxml import html from time import gmtime, strftime import requests import smtplib import time #from config import Config #config = Config() OTOMOTO_URL = 'https://www.otomoto.pl/osobowe/krakow/kia/ceed/i-2006-2012/-/kombi/?search%5Bfilter_float_price%3Ato%5D=35000&search%5Bfilter_float_year%3Afrom%5D=2010&search...
import os import logging from pathlib import Path logger = logging.getLogger(__name__) # Default Directory Paths # home_dir = os.path.expanduser("~") # Also acceptable home_dir = str(Path.home()) PROJECT_DIR = os.path.join(home_dir, ".ex05", "ruppasur") LOG_DIR = os.path.join(PROJECT_DIR, "logs") DATA_DIR = os.path....
from django.contrib import admin from .models import Info, Book, Student, Issue, Reservation, Class # Register your models here. admin.site.register(Info) admin.site.register(Book) admin.site.register(Class) admin.site.register(Student) admin.site.register(Issue) admin.site.register(Reservation)
""" 스택 자료구조 구현 """ class Node: def __init__(self, data): self.data = data self.next = None class Stack: def __init__(self): self.head = None def push(self, value): new_head = Node(value) new_head.next = self.head self.head = new_head def pop(self): ...
from django.conf import settings from django.contrib import admin from .models import ADGroupMapping, ADGroup, OIDCBackChannelLogoutEvent @admin.register(ADGroupMapping) class ADGroupMappingAdmin(admin.ModelAdmin): pass admin.site.register(ADGroup) if getattr(settings, "HELUSERS_BACK_CHANNEL_LOGOUT_ENABLED", ...
# # QAPI helper library # # Copyright IBM, Corp. 2011 # Copyright (c) 2013 Red Hat Inc. # # Authors: # Anthony Liguori <aliguori@us.ibm.com> # Markus Armbruster <armbru@redhat.com> # # This work is licensed under the terms of the GNU GPL, version 2. # See the COPYING file in the top-level directory. import re from o...
from audobject.core.testing import ( TestObject, )
# Random Walk auf einem orthogonalen Gitter import turtle as t import random as r import math wn = t.Screen() wn.setup(width = 800, height = 800) wn.colormode(255) wn.bgcolor(50, 50, 50) wn.title("Random-Walk (1)") SL = 3 # Schrittlänge def random_walk(x, y): step = r.choice(["N", "S", "E", "W"]) if step ...
# -*- coding: utf-8 -*- # MIT License # # Copyright (c) 2019 Jean-François Boismenu # # See LICENSE at the root of this project for more info. from emnes.nes import NES from emnes.cartridge_reader import CartridgeReader from emnes.cpu import CPU from emnes.memory_bus import MemoryBus __all__ = ["NES", "CartridgeReade...
from checkov.common.models.enums import CheckCategories, CheckResult from checkov.kubernetes.base_spec_check import BaseK8Check class Tiller(BaseK8Check): def __init__(self): name = "Ensure that Tiller (Helm v2) is not deployed" id = "CKV_K8S_34" # Location: container .image suppo...
class ClassCollection(list): def get(self, **kwargs): return self.klass.get(**kwargs)
# The MIT License (MIT) # Copyright (c) 2022 by the xcube development team and contributors # # 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 limitatio...
from api.tests.ver2.test_base import TestBase from api.ver2.utils.strings import v2_url_prefix from api.strings import status_key, data_key, error_key, status_404, \ status_400, status_200 from api.tests.ver2.test_data.register_test_data import * from api.tests.ver2.test_data.office_test_data import correct_office ...
from src.model.charactors import Charactor class Aggressive(Charactor): """ Any person or entity that can fight. """ def __init__(self): super.__init__()
# To run this, download the BeautifulSoup zip file # http://www.py4e.com/code3/bs4.zip # and unzip it in the same directory as this file from urllib.request import urlopen from bs4 import BeautifulSoup import ssl import re # Ignore SSL certificate errors ctx = ssl.create_default_context() ctx.check_hostname = False c...
import tensorflow as tf import tensorflow_probability as tfp import numpy as np def run_tf_example_A(): # EXAMPLE CODE # https://www.tensorflow.org/probability/api_docs/python/tfp/mcmc/sample_annealed_importance_chain tfd = tfp.distributions # Run 100 AIS chains in parallel num_chains = 100 d...
#!/usr/bin/env python # -*- coding: utf-8 -*- from roca.detect import RocaFingerprinter, flatten, drop_none, AutoJSONEncoder import random import base64 import unittest import pkg_resources __author__ = 'dusanklinec' class FprintTest(unittest.TestCase): """Simple Fingerprint tests""" def __init__(self, *a...
from transitions.extensions import GraphMachine from telegram import (ReplyKeyboardMarkup, ReplyKeyboardRemove) class TocMachine(GraphMachine): def __init__(self, **machine_configs): self.machine = GraphMachine( model = self, **machine_configs ) #print(self.machine.s...
from itertools import chain import logging import sys from pyspark.sql import functions as f from pyspark.sql.session import SparkSession from pyspark.sql.window import Window from pyspark.sql.types import ArrayType, StringType spark = SparkSession.builder.getOrCreate() spark.conf.set("spark.sql.execution.arrow.enabl...
from __future__ import absolute_import import sys import os from datetime import date from utilities.TestClass import TestClass import swagger_client from swagger_client.api.measure_evaluation_api import MeasureEvaluationApi from swagger_client.rest import ApiException # Set global variables in the file that can be ac...
import csv import pandas as pd from scipy.stats import pearsonr label = {} with open('dataset/label-result.csv', 'r') as file: i = 0 for row in file: if i == 0: i += 1 continue row = row.split(',') last = row[len(row)-1].split('\n') rest = ','.join(row[1...
# -*- coding: utf-8 -*- from unittest.mock import MagicMock, patch from chaoslib.exceptions import FailedActivity from kubernetes import client, config import pytest from chaosgce.nodepool.actions import create_new_nodepool, delete_nodepool, \ swap_nodepool import fixtures @patch('chaosgce.nodepool.actions.wai...
#! /usr/env/python """ flow_director_d8.py: provides the component FlowDirectorsD8. This components finds the steepest single-path steepest descent flow directions and considers diagonal links between nodes on a raster grid. It is not implemented for irregular grids. For a method that works for irregular grids and do...
from .signer import Signer
""" This module contains "throaway" code for pre-generating a list of stations. TODO: Remove this module when the Fire Weather Index Calculator uses the correct API as source for data. """ import csv import json import re import geopandas from shapely.geometry import Point def fetch_ecodivision_name(latitude: str, l...
import pytest import rpy2.rlike.container as rlc class TestOrdDict(object): def test_new(self): nl = rlc.OrdDict() x = (('a', 123), ('b', 456), ('c', 789)) nl = rlc.OrdDict(x) def test_new_invalid(self): with pytest.raises(TypeError): rlc.OrdDict({}) @pytest...
#!/usr/bin/env python # -*- coding: utf-8 -*- import numpy as np import json from Tools.Logger import logger from Lib.Similarity.Similarity import Similarity class Jaccard(Similarity): def predict(self, doc): results = [] for index in range(self.total): x = self.X[index] ...
import numpy as np from tensorcomlib.tensor import tensor from ..tools.tools import float2front #Tensor Times Matrix def tensor_times_mat(ten,mat,mode): shp = ten.shape ndim = ten.ndims order = float2front(ten.order,mode) newdata = np.dot(mat,unfold(X,mode).data) p = mat.shape[0...
#!/usr/bin/env python3 """ functions related to printing cards """ import sys import os.path def writedict(): """ return the dictionnary """ col = ["♠", "♥", "♦", "♣"] d = {} for i in range(0, 4): for j in range(1, 15): if j <= 10: d[i*14+j] = col[i] + str(j) ...
import os import shutil import sqlite3 import pytz from dateutil import parser from django.conf import settings from django.utils.html import escape from .base import HoursDataSource class DataSource(HoursDataSource): def fetch(self): if settings.VERBOSE: print "Chrome history..." if...
import traceback from typing import Dict, List, Optional, Union import dateparser import demistomock as demisto # noqa: F401 import requests from CommonServerPython import * # noqa: F401 # Disable insecure warnings requests.packages.urllib3.disable_warnings() ''' CONSTANTS ''' DATE_FORMAT = '%Y-%m-%dT%H:%M:%SZ'...
#!/usr/bin/env python3 """ Purpose This script dumps comb table of ec curve. When you add a new ec curve, you can use this script to generate codes to define `<curve>_T` in ecp_curves.c """ # Copyright The Mbed TLS Contributors # SPDX-License-Identifier: Apache-2.0 # # Licensed under the Apache License, Version 2.0 (...
""" Ensures the functionality of PyMotifCounterBase. :author: Athanasios Anastasiou :date: Nov 2021 """ import pytest import re from pymotifcounter.abstractcounter import (PyMotifCounterBase, PyMotifCounterInputTransformerBase, PyM...
#!/usr/bin/env python __author__ = "XXX" __email__ = "XXX" import logging import os import pandas as pd from constants import * from datasets.dataset_loader import DatasetLoader from utils.pandas_utils import remap_columns_consecutive logger = logging.getLogger(__name__) logging.basicConfig(level=os.environ.get("LO...
from typing import Any, Union import metagraph as mg def range_equivalent(a: Union[range, Any], b: Union[range, Any]): """ :return: True if two range like objects have the same start, stop, and step. They need not be the same type. """ return a.start == b.start and a.stop == b.stop and a.step...
"""empty message Revision ID: 5f6cccd86344 Revises: 6ea519fd23ca Create Date: 2021-12-20 14:48:35.949936 """ from alembic import op import sqlalchemy as sa from sqlalchemy.sql import column, table from sqlalchemy.sql.sqltypes import Boolean, String # revision identifiers, used by Alembic. revision = '5f6cccd86344' ...
from typing import Any, Dict import torch from rllib.environment import SystemEnvironment from rllib.environment.systems import InvertedPendulum from exps.inverted_pendulum.util import PendulumReward from curriculum_experiments.environment_parameter import ContinuousParameter from curriculum_experiments.environment_w...
import esphome.codegen as cg from esphome import pins import esphome.config_validation as cv from esphome.const import ( CONF_DELAY, CONF_ID, ) AUTO_LOAD = ["sensor", "voltage_sampler"] CODEOWNERS = ["@asoehlke"] MULTI_CONF = True cd74hc4067_ns = cg.esphome_ns.namespace("cd74hc4067") CD74HC4067Component = cd...
# -*- coding: utf-8 -*- import unittest import numpy as np from . import solve class TestSolver(unittest.TestCase): _FIELDS = [ [ [7, 0, 0, 3, 0, 0, 2, 0, 6], [0, 0, 2, 0, 5, 8, 0, 0, 0], [8, 3, 0, 0, 0, 7, 0, 4, 9], [3, 9, 0, 0, 0, 0, 8, 5, 4], ...
import logging import traceback import pandas as pd from morpher.jobs import MorpherJob """ Select Job makes it possible to access a range of feature selection techniques with a unified interface Upon calling .execute() you can specify the feature selection method and how many features shall be returned. """ class Sel...
from glob import glob import argparse, json, re WORD = re.compile(r'[\w\.]+') def ttJson(name, directory=False): if directory: name = glob(name + "/*.txt") else: name = [name] for ids, fname in enumerate(name): with open("".join(fname.split(".")[:-1]) + ".json", 'w') as writer: ...
#!/usr/bin/env python # -*- coding: utf-8 -*- import os from flask import Flask from werkzeug.serving import run_simple from blueprints.web import web_bp def create_app(config=False): # send global static files to a junk /nostatic path app = Flask(__name__, static_path='/nostatic') # generate configuratio...
# init file for stan fit functions import xidplus.io as io __author__ = 'pdh21' import os output_dir = os.getcwd() full_path = os.path.realpath(__file__) path, file = os.path.split(full_path) stan_path=os.path.split(os.path.split(path)[0])[0]+'/stan_models/' stan_path=os.path.split(os.path.split(path)[0])[0]+'/stan_...
# -*- coding: utf-8 -*- # Author: github.com/madhavajay """Fixes pyo3 mixed modules for import in python""" import importlib import os from typing import Dict, Any, List, Optional # gets the name of the top level module / package package_name = __name__.split(".")[0] # convert the subdirs from "package_name" into a ...
# -*- coding: utf-8 -*- # Generated by Django 1.11.1 on 2017-12-09 20:51 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('registration', '0020_auto_20171209_1510'), ] operations = [ migrations.Alte...
from django.urls import path from . import views app_name = 'modelzoo' urlpatterns = [ path('', views.IndexView.as_view(), name='index'), path('<slug:slug>/', views.DetailView.as_view(), name='detail'), path('nb/<slug:slug>/', views.DetailView_nb.as_view(), name='detail_nb'), path('api/hello/', views.h...
# Copyright 2019 DeepMind Technologies Limited # # 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 agr...
"""tracking school Revision ID: 9abbf14692f8 Revises: d287e378eca6 Create Date: 2022-05-16 08:00:28.857382 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '9abbf14692f8' down_revision = 'd287e378eca6' branch_labels = None depends_on = None def upgrade(): ...
from PyQt5.QtCore import QPointF from PyQt5.QtWidgets import QInputDialog, QMessageBox from gui.main_window.node_editor.items.connection_item import ConnectionItem from gui.main_window.node_editor.items.node_item import NodeItem from gui.main_window.node_editor.node_editor_event_handler import NodeEditorEventHandler f...
from django.conf.urls import url from . import views app_name = 'campaigns' urlpatterns = [ url( r'^$', views.JsonView.response, name='index' ), url( r'^(?P<app_code>[a-zA-Z0-9]+)/info/$', views.info, name='info' ), url( r'^(?P<app_code>[a-zA-Z0-9]+)/services/$', views.services, name='services' ), ]
from django.urls import path from .views import home, CityDetailView, CityCreateView, CityUpdateView, CityDeleteView urlpatterns = [ path("detail/<int:pk>/", CityDetailView.as_view(), name="detail"), path("add/", CityCreateView.as_view(), name="add"), path("update/<int:pk>/", CityUpdateView.as_view(), name...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # @Author : mh import time import os def change_name(path): if not os.path.isdir(path) and not os.path.isfile(path): print("路径错误") return if os.path.isfile(path): # 分割出目录与文件 file_path = os.path.split(path) # 分割出文件与文件扩展名 ...
# -*- coding: utf-8 -*- import time import datetime from openerp import models,fields,api from openerp.tools.translate import _ from math import * from openerp.exceptions import Warning class sale_order(models.Model): _inherit = "sale.order" @api.model def _get_default_location(self): company_id...
from functools import lru_cache import luigi import yaml from servicecatalog_puppet import manifest_utils from servicecatalog_puppet.workflow import tasks class ManifestMixen(object): manifest_file_path = luigi.Parameter() @property @lru_cache() def manifest(self): content = open(self.mani...
import re, os, csv # A function that handles all the defaults and input for scanning information: def scanningAndScannerInfo(f): global captureDate, scannerMake, scannerModel, scannerUser, bitoneRes, contoneRes, scanningOrder, readingOrder, imageCompressionAgent, imageCompressionDate, imageCompressionTool, imageCompr...
__module_name__ = "smileclient-responder" __module_version__ = "0.1" __module_description__ = "Replies to all events in a channel with \":D\"" import hexchat responding_channels = { "##:D" } triggering_commands = { "PRIVMSG", "NOTICE", "JOIN", "PART", "QUIT", "TOPIC", "MODE" } overly_happy_users = { "heddwch" } rejoi...
from flask_wtf import FlaskForm from wtforms import StringField, TextAreaField, SubmitField, PasswordField from wtforms.fields.html5 import DateField from wtforms.validators import DataRequired, EqualTo, Email, Length, ValidationError from book_manage.models import Admin # Register forms class RegistrationForm(FlaskFo...
# -*- coding: utf-8 -*- from django.http import HttpResponseRedirect from maintenance_mode.core import set_maintenance_mode def maintenance_mode_off(request): """ Deactivate maintenance-mode and redirect to site root. Only superusers are allowed to use this view. """ if request.user.is_superuser...
VERSION = '0.0.17' SERVER_URL = 'https://api.weixin.qq.com' COMPANY_URL = 'https://qyapi.weixin.qq.com' SERVER_WAIT_TIME = 4.5 GREETING_WORDS = 'Greeting from itchatmp!' try: import itchatmphttp COROUTINE = True except ImportError: COROUTINE = False
from core.advbase import * from module.bleed import Bleed def module(): return Ieyasu class Ieyasu(Adv): conf = {} conf['slots.a'] = [ 'Resounding_Rendition', 'Flash_of_Genius', 'Moonlight_Party', 'The_Plaguebringer', 'Dueling_Dancers' ] conf['acl'] = """ ...
import pathlib from dotenv import load_dotenv load_dotenv() from pippin.util.utils import Utils load_dotenv(dotenv_path=Utils.get_project_root().joinpath(pathlib.PurePath('.env'))) import argparse import asyncio import getpass from pippin.db.models.wallet import Wallet, WalletLocked, WalletNotFound from pippin.db.tor...
from aws_cdk import ( aws_iam as iam, aws_rds as rds, aws_sqs as sqs, aws_sns as sns, aws_ec2 as ec2, aws_s3 as s3, aws_logs as logs, aws_kms as kms, aws_cloudwatch as cloudwatch, aws_cloudwatch_actions as cloudwatch_actions, aws_secretsmanager as secretsmanager, aws_s3_notification...
import boto3 client = boto3.client('resourcegroupstaggingapi') def get(tag_filters): response = client.get_resources( TagFilters=tag_filters ) return response def human_readable(raw_get_resources_response): return [ {**split_resource_arn(e['ResourceARN']), **{'Tags': collapse_tags(e...
# -*- coding: utf-8 -*- """ This module defines the steps related to the app. """ from behave import step from flybirds.core.global_context import GlobalContext as g_Context from flybirds.utils.dsl_helper import ele_wrap @step("install app[{selector}]") @ele_wrap def install_app(context, selector=None): g_Contex...
import os import shutil import random from pathlib import Path def main(): cdcp_path = os.path.dirname(os.getcwd()) + "/data/cdcp/original" train_dir = cdcp_path + "/train" dev_dir = cdcp_path + "/dev" test_dir = cdcp_path + "/test" train_file_prefix = {f.split(".")[0] for f in os.listdir(train_d...
# -*- coding: utf-8 -*- # Copyright 2013-2014 Eucalyptus Systems, Inc. # # Redistribution and use of this software in source and binary forms, # with or without modification, are permitted provided that the following # conditions are met: # # Redistributions of source code must retain the above copyright notice, # this...
#!/usr/bin/env python """ -*- coding: utf-8 -*- By: "John Hazelwood" <jhazelwo@users.noreply.github.com> Tested with Python 2.6.6 on CentOS 6.5 """ import re import sys import pwd import os import glob import socket import struct import json from pprint import pprint class QuietError(Exception): # All who inher...
# Copyright 2014 Confluent Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, s...
from imgaug import augmenters as iaa import numpy as np class ImgAugTransform: def __init__(self): self.aug = iaa.Sequential([ iaa.Sometimes(0.25, iaa.GaussianBlur(sigma=(0, 3.0))), iaa.Fliplr(0.5), iaa.Affine(rotate=(-20, 20), mode='symmetric'), ]) d...
from setuptools import setup, find_packages import codecs import os here = os.path.abspath(os.path.dirname(__file__)) with codecs.open(os.path.join(here, "README.md"), encoding="utf-8") as fh: long_description = "\n" + fh.read() VERSION = '1.1.1' DESCRIPTION = 'Read HTML data and convert it into python classes....
# coding=utf-8 from __future__ import absolute_import, division, print_function from click import command, pass_context from .docker import docker_version_for_preset from .golang import golang_version_for_preset from ..util.common_options import ansible_output_options from ..util.preset_option import Preset, preset_o...
"""Tests of 0x.order_utils.signature_utils.*.""" from zero_ex.order_utils.signature_utils import ec_sign_order_hash def test_ec_sign_order_hash(): """Test the signing of order hashes.""" assert ec_sign_order_hash() == "stub return value"
import sys import os sys.path.append(os.path.dirname(os.path.realpath(__file__))) from .info import __version__ from . import FASTPT
import numpy as np from scipy.ndimage import convolve, sobel from scipy.interpolate import RectBivariateSpline from scipy.optimize import basinhopping from geometry import calc_bbox, MeshEdgeDetector, Position class Gradient(object): SCHARR = 'Scharr' SOBEL = 'Sobel' SCHARR_KERNEL_X = np.array([[3, 0, -...
# coding: utf8 from __future__ import print_function, absolute_import from pickle import Unpickler, BUILD from spinoff.actor.ref import Ref class IncomingMessageUnpickler(Unpickler): """Unpickler for attaching a `Hub` instance to all deserialized `Ref`s.""" def __init__(self, node, file): Unpickler...
import random no_of_tests = 1000000 #1 million tests def montyhall(): correct_switchdoor = 0 correct_samedoor = 0 incorrect_switchdoor = 0 incorrect_samedoor = 0 switchdoor_actual = 0 samedoor_actual = 0 for test in range(no_of_tests): car = random.randint(0,2) #Door ...
# -*- coding: utf-8 -*- """ :copyright: Copyright 2022 Sphinx Confluence Builder Contributors (AUTHORS) :license: BSD-2-Clause (LICENSE) """ from tests.lib.testcase import ConfluenceTestCase from tests.lib.testcase import setup_builder from tests.lib import parse import os class TestConfluenceExpand(ConfluenceTestCa...
import datetime import logging from typing import List, Tuple import pyspark.sql as spark from pyspark.ml import Pipeline from pyspark.ml.classification import LogisticRegression from pyspark.ml.feature import VectorAssembler from pyspark.mllib.evaluation import RegressionMetrics from pyspark.sql.functions import ex...
"""Verifies that all providers of blockchain data are consistent with others.""" import unittest try: from boltzmann.utils.bitcoind_rpc_wrapper import BitcoindRPCWrapper from boltzmann.utils.bci_wrapper import BlockchainInfoWrapper except ImportError: import sys import os # Adds boltzmann directory ...
# -*- coding: utf-8 -*- from __future__ import unicode_literals, absolute_import from django.contrib.auth.models import AbstractUser from django.core.urlresolvers import reverse from django.db import models from django.utils.encoding import python_2_unicode_compatible from django.utils.translation import ugettext_lazy...
import numpy as np import sys import pickle as pkl import networkx as nx import scipy.sparse as sp from sklearn.preprocessing import LabelEncoder from sklearn.preprocessing import OneHotEncoder def parse_index_file(filename): index = [] for line in open(filename): index.append(int(line.strip())) r...
# Generated by Django 2.2.9 on 2020-02-10 13:26 from django.db import migrations, models import uuid class Migration(migrations.Migration): initial = True dependencies = [] operations = [ migrations.CreateModel( name="Team", fields=[ ("id", models.UUIDFi...
import argparse import os import PIL.Image as Image import numpy as np import tensorflow as tf from utils.app_utils import FPS from dataset.df import visualization_utils as vis_util from object_detection.utils import label_map_util CWD_PATH = os.getcwd() detection_graph = tf.Graph() IMAGE_SIZE = (12, 8) # Path to f...
# -*- coding: utf-8 -*- import sys, os from setuptools import setup, find_packages from codecs import open from os import path here = path.abspath(path.dirname(__file__)) with open(path.join(here, 'README.md'), encoding='utf-8') as f: long_description = f.read() with open(path.join(here, 'version.txt')) as f: ...
import os import sys import matplotlib.pyplot as plt import numpy as np from astropy.io import fits # ------------------------------------------------------------ # Input output = os.path.join(sys.argv[1], "") # ------------------------------------------------------------ stokes_files = output+'output/phase.dat'...
#!/usr/bin/env python # -*- coding: utf-8 -*- """Invoke tasks.""" import os import json import shutil from invoke import task HERE = os.path.abspath(os.path.dirname(__file__)) with open(os.path.join(HERE, 'cookiecutter.json'), 'r') as fp: COOKIECUTTER_SETTINGS = json.load(fp) COOKIECUTTER_SETTINGS['repo_name'] = ...
import json import os import time import argparse import uuid import subprocess32 import sys from datetime import datetime from tzlocal import get_localzone import pytz import logging sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)),"../storage")) sys.path.append(os.path.join(os.path.dirname(os...
import numpy as np arr_time = np.random.exponential(3, 3) print(arr_time) Exec_Time = np.random.exponential(1, 3) print(Exec_Time) for i in range(0,3): print "A(",round(arr_time[i],1),",",round(Exec_Time[i],1),")" ''' Output A(0.3, 1.1) A(2.5, 2.0) A(0.0, 4.7) '''