content
stringlengths
5
1.05M
média = 0 idademaisvelho = 0 nomemaisvelho = '' totmulher20 = 0 for p in range(1, 5): print('-' * 10, '{}ª PESSOA'.format(p), '-' * 10) nome = str(input('Nome: ').strip()) idade = int(input('Idade: ')) sexo = str(input('Sexo [M/F]: ').strip()) média = (média*(p-1)+idade)/p if p == 1 and sexo in ...
import logging import numpy as np X1, Y1, X2, Y2 = range(4) class ImageSegmentation(object): """ Data Structure to hold box segments for images. Box segments are defined by two points: upper-left & bottom-right. """ def __init__(self, width, height): self.height = height self...
# -*- coding: utf-8 -*- from app import app, db, bbcode_parser, redis_store, mail #, q from flask import request, render_template, redirect, url_for, send_from_directory, abort, flash, g, jsonify import datetime import os from PIL import Image import simplejson import traceback from werkzeug.utils import secure_filena...
# Generated by Django 2.2.4 on 2019-09-10 13:37 from django.db import migrations import wagtail.core.blocks import wagtail.core.fields import wagtail.images.blocks class Migration(migrations.Migration): dependencies = [ ('export_readiness', '0055_auto_20190910_1242'), ] operations = [ m...
import opentrons.execute import requests import json import import_ipynb import csv from labguru import Labguru experiment_id = 512 lab = Labguru(login='login@gmail.com', password='123password') # get Labguru elements experiment = lab.get_experiment(experiment_id) plate_element = lab.get_elements_by_type(experiment_...
import collections import os from strictdoc.helpers.sorting import alphanumeric_sort class FileOrFolderEntry: def get_full_path(self): raise NotImplementedError def get_level(self): raise NotImplementedError def is_folder(self): raise NotImplementedError def mount_folder(se...
#!/usr/bin/env python2 import sys sys.path.insert(0, '..') from cde_test_common import * def checker_func(): assert os.path.isfile('cde-package/cde-root/home/pgbovine/CDE/tests/readlink_abspath_test/libc.so.6') generic_test_runner(["python", "readlink_abspath_test.py"], checker_func)
import numpy as np import pysam import subprocess import argparse import utils import os, pdb MIN_MAP_QUAL = 10 def parse_args(): parser = argparse.ArgumentParser(description=" convert bam data format to bigWig data format, " " for ribosome profiling and RNA-seq data ") p...
def rotate(self, nums, k): """ :type nums: List[int] :type k: int :rtype: void Do not return anything, modify nums in-place instead. """ if k is None or k <= 0: return k = k % (len(nums)) end = len(nums)- 1 self.swap(nums,0,end-k) ...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ 使用自己的 svm 进行垃圾邮件分类。 """ import re import numpy as np import scipy.io as scio from nltk.stem import porter from svm import SVC def get_vocabs(): vocabs = {} # 单词的总数 n = 1899 f = open('vocab.txt', 'r') for i in range(n): line = f.readl...
# File: C (Python 2.4) from direct.fsm.FSM import FSM from direct.gui.DirectGui import * from pandac.PandaModules import * from pirates.piratesgui.GuiButton import GuiButton from pirates.piratesgui import PiratesGuiGlobals from pirates.piratesbase import PiratesGlobals from pirates.piratesbase import PLocalizer from p...
from .constants.google_play import Sort from .features.app import app from .features.reviews import reviews __version__ = "0.0.2.3"
class memoize(object): """ Memoize the result of a property call. >>> class A(object): >>> @memoize >>> def func(self): >>> return 'foo' """ def __init__(self, func): self.__name__ = func.__name__ self.__module__ = func.__module__ self.__doc__ = ...
# -*- encoding: utf-8 -*- # Copyright (c) 2019 Stephen Bunn <stephen@bunn.io> # ISC License <https://opensource.org/licenses/isc> """ """ import pathlib # the path to the data directory included in the modules source DATA_DIR = pathlib.Path(__file__).parent / "data" # the path to the store-locations fil...
"""Prometheus collector for Apache Traffic Server's stats_over_http plugin.""" import logging import re import time import requests import yaml from prometheus_client import Metric CACHE_VOLUMES = re.compile("^proxy.process.cache.volume_([0-9]+)") LOG = logging.getLogger(__name__) def _get_float_value(data, keys)...
# # DeepRacer Guru # # Version 3.0 onwards # # Copyright (c) 2021 dmh23 # from src.personalize.reward_functions.follow_centre_line import reward_function NEW_REWARD_FUNCTION = reward_function DISCOUNT_FACTORS = [0.999, 0.99, 0.97, 0.95, 0.9] DISCOUNT_FACTOR_MAX_STEPS = 300 TIME_BEFORE_FIRST_STEP = 0.2
# terrascript/provider/kubernetes.py # Automatically generated by tools/makecode.py (24-Sep-2021 15:20:43 UTC) # # For imports without namespace, e.g. # # >>> import terrascript.provider.kubernetes # # instead of # # >>> import terrascript.provider.hashicorp.kubernetes # # This is only available for 'official' and ...
import os import sys from pathlib import Path import win32api from dotenv import load_dotenv from kivy.config import Config from loguru import logger import stackprinter import trio load_dotenv() logger.remove() logger.add( sys.stdout, colorize=True, format="[ <lr>Wallpaper</> ]" "[<b><fg #3b3b3b>{lev...
from rest_framework import serializers from users.api.serializers import UserSerializer from ..models import Message class MessageSerializer(serializers.ModelSerializer): sender = UserSerializer(read_only=True) receiver = UserSerializer(read_only=True) class Meta: model = Message fields ...
from typing import List, Tuple import difflib from paukenator.nlp import Text, Line from .common import CmpBase class CmpTokens(CmpBase): '''Algorithm that compares texts at word level and detects differences in tokenization (splitting). Comparison works in line-by-line fashion. USAGE: comparer = Cm...
from django.contrib import admin from django.contrib import admin from .models import subCategory admin.site.register (subCategory) # Register your models here.
import requests import convertapi from io import BytesIO from .exceptions import * class Client: def get(self, path, params = {}, timeout = None): timeout = timeout or convertapi.timeout r = requests.get(self.url(path), params = params, headers = self.headers(), timeout = timeout) return self.handle_response(r...
from django.urls import reverse from django.shortcuts import render from django.utils import timezone, crypto from django.core.paginator import Paginator from django.http.response import HttpResponse, HttpResponseRedirect, JsonResponse, FileResponse from django.views.decorators.http import require_http_methods from dja...
from tool.runners.python import SubmissionPy class BebertSubmission(SubmissionPy): def run(self, s): positions = [line.split(", ") for line in s.splitlines()] positions = [(int(x), int(y)) for x, y in positions] # print(positions) obj_less = 10000 # if len(positions) != 6 else 3...
from setuptools import setup, find_packages setup( name='ysedu', version='1.0', author='Yuji Suehiro', packages=find_packages(), url='https://github.com/YujiSue/education', description='Sample codes used for education.' )
import re text = input().lower() word = input().lower() pattern = rf"\b{word}\b" valid_matches = len(re.findall(pattern, text)) print(valid_matches)
import torch def center_of_mass(x, pytorch_grid=True): """ Center of mass layer Arguments --------- x : network output pytorch_grid : use PyTorch convention for grid (-1,1) Return ------ C : center of masses for each chs """ n_batch, chs, dim1, dim2, dim3 = ...
# --------------------------------------------------------------------- # Dispose Request # --------------------------------------------------------------------- # Copyright (C) 2007-2021 The NOC Project # See LICENSE for details # --------------------------------------------------------------------- # Python modules ...
#!/usr/bin/env python3 # This script will run using the default Python 3 environment # where LibreOffice's scripts are installed to (at least in Ubuntu). # This converter is very similar to unoconv but has an option to remove # line numbers, it is also simpler by being more tailored to the use-case. # https://github.c...
# -*- coding: utf-8 -*- """ Created on Sat Feb 23 18:53:28 2019 @author: Rajas khokle Code Title - Time Series Modelling """ import numpy as np import pandas as pd from sqlalchemy import create_engine import matplotlib.pyplot as plt from statsmodels.tsa.seasonal import seasonal_decompose from statsmodels.tsa.statto...
if __name__ == '__main__': import BrowserState else: from . import BrowserState from PyQt5 import QtCore, QtWidgets, QtWidgets # The Sort dialog, with a grid of sorting buttons class SortDialog(QtWidgets.QDialog): # Constant giving the number of search keys MaxSortKeyCount = 6 ############# Signa...
# This script generates the scoring and schema files # Creates the schema, and holds the init and run functions needed to # operationalize the Iris Classification sample # Import data collection library. Only supported for docker mode. # Functionality will be ignored when package isn't found try: from azureml.dat...
#Calculates the median, or middle value, of a list of numbers #The median is the middle value for an odd numbered list, so median of 1,2,3,4,5 # is 3, and the average of the two center values of an even numbered list #median of 1,2,3,4 is (2+3)/2 = 2.5 def median(numbers): med = 0.0 numbers = sorted(numbe...
from .gyaodl import * __copyright__ = '(c) 2021 xpadev-net https://xpadev.net' __version__ = '0.0.1' __license__ = 'MIT' __author__ = 'xpadev-net' __author_email__ = 'xpadev@gmail.com' __url__ = 'https://github.com/xpadev-net/gyaodl' __all__ = [GyaoDL]
import torch from torch.nn import Module from functools import partial import warnings from .kernel_samples import kernel_tensorized, kernel_online, kernel_multiscale from .sinkhorn_samples import sinkhorn_tensorized from .sinkhorn_samples import sinkhorn_online from .sinkhorn_samples import sinkhorn_multiscale from...
import pytest from cookietemple.list.list import TemplateLister """ This test class is for testing the list subcommand: Syntax: cookietemple list """ def test_non_empty_output(capfd): """ Verifies that the list command does indeed have content :param capfd: pytest fixture -> capfd: Capture, as text, o...
import scrapy class ImdbImageSpiderSpider(scrapy.Spider): name = 'imdb_image_spider' allowed_domains = ['https://www.imdb.com/'] file_handle = open("url.txt", "r") temp = file_handle.readline() file_handle.close() temp += "/mediaindex?ref_=tt_ov_mi_sm" tmp = list() tmp.append(temp) ...
''' 伽马变化 ''' import numpy as np import cv2 from matplotlib import pyplot as plt # 定义伽马变化函数 def gamma_trans(img, gamma): # 先归一化到1,做伽马计算,再还原到[0,255] gamma_list = [np.power(x / 255.0, gamma) * 255.0 for x in range(256)] # 将列表转换为np.array,并指定数据类型为uint8 gamma_table = np.round(np.array(gamma_list)).astype(np...
def findSubstring( S, L): """ The idea is very simple, use brute-force with hashing. First we compute the hash for each word given in L and add them up. Then we traverse from S[0] to S[len(S) - total_length], for each index, i f the first substring in L, then we compute the total hash for that partiti...
from dagger.input.from_node_output import FromNodeOutput from dagger.input.protocol import Input from dagger.serializer import DefaultSerializer from tests.input.custom_serializer import CustomSerializer def test__conforms_to_protocol(): assert isinstance(FromNodeOutput("node", "output"), Input) def test__expos...
"""This is a Python demo for the `Sphinx tutorial <http://quick-sphinx-tutorial.readthedocs.org/en/latest/>`_. This demo has an implementation of a Python script called ``giza`` which calculates the square of a given number. """ import argparse def calc_square(number, verbosity): """ Calculate the square o...
# -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division, print_function, unicode_literals from sumy.parsers.html import HtmlParser from sumy.parsers.plaintext import PlaintextParser from sumy.nlp.tokenizers import Tokenizer from sumy.summarizers.lsa import LsaSummarizer as Summa...
from django.db import models from searchEngine.models import InternetResult from search.models import SearchParameters class TwitterUser(models.Model): id = models.CharField(max_length=128, primary_key=True) username = models.CharField(max_length=60) link = models.URLField() avatar = models.TextField...
''' hist_it.py - GPUE: Split Operator based GPU solver for Nonlinear Schrodinger Equation, Copyright (C) 2011-2015, Lee J. O'Riordan <loriordan@gmail.com>, Tadhg Morgan, Neil Crowley. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that th...
from unittest import TestCase from ..mock_ldap_helpers import DEFAULT_DC from ..mock_ldap_helpers import group from ..mock_ldap_helpers import group_dn from ..mock_ldap_helpers import mock_ldap_directory from ..mock_ldap_helpers import person from ..mock_ldap_helpers import person_dn class TestPerson(TestCase): ...
# # DeepRacer Guru # # Version 3.0 onwards # # Copyright (c) 2021 dmh23 # import tkinter as tk import numpy as np from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg from matplotlib.axes import Axes from matplotlib.ticker import PercentFormatter from src.action_space.action import Action from src.analyze...
# # Copyright (c) 2013, Digium, Inc. # Copyright (c) 2018, AVOXI, Inc. # """ARI client library """ import aripy3.client import swaggerpy3.http_client import urllib.parse from .client import ARIClient async def connect(base_url, username, password): """Helper method for easily connecting to ARI. :param base...
import argparse import os.path import shutil import fileinput import re import subprocess import sys import time import os import glob import codecs from pathlib import Path from typing import Dict, List from pyrsistent import pmap, freeze from pyrsistent.typing import PMap, PVector from typing import Ma...
# -*- coding: utf-8 -*- import os import setuptools PACKAGE = 'dockerblade' PATH = os.path.join(os.path.dirname(__file__), 'src/{}/version.py'.format(PACKAGE)) with open(PATH, 'r') as fh: exec(fh.read()) setuptools.setup(version=__version__)
from util import start_game, tapToStart, check_game_state # 从模拟器打开 没运行游戏开始 if __name__ == '__main__': start_game() tapToStart() check_game_state() # main()
import json from datetime import date, datetime, timedelta import pytest from jitenshea.webapi import ISO_DATE, ISO_DATETIME, api from jitenshea.webapp import app app.config['TESTING'] = True api.init_app(app) def yesterday(): return date.today() - timedelta(1) @pytest.fixture def client(): client = app.t...
# -*- coding:utf-8 -*- import os rootdir = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir)) class Config(object): SECRET_KEY = os.environ.get('SECRET_KEY') or 'hard to guess string' SSL_DISABLE = False SQLALCHEMY_COMMIT_ON_TEARDOWN = True SQLALCHEMY_RECORD_QUERIES = True MAIL_S...
## LOX-IPA sim #@ Author Juha Nieminen #import sys #sys.path.insert(0, '/Users/juhanieminen/Documents/adamrocket') import RocketComponents as rc from physical_constants import poise, inches, Runiv, gallons, lbm, \ gearth, atm, psi, lbf from numpy import pi, linspace, cos, radians, sqrt, exp, log, array, ...
import unittest from kaleidoscope.config import GalleryConfigParser class TestGalleryConfigParser(unittest.TestCase): def test_lowercase_key(self): """Lowercase option key is left as is.""" config = GalleryConfigParser() config.read_string("[album]\ntitle: Example\n") self.assertT...
print("hello,world") #print(5 ** 4321) a = 1 if (a < 10 and a > -10): print("fuck you")
# -*- coding: utf-8 -*- """Domain Driven Design framework.""" from ddd_base import ValueObject class RouteSpecification(ValueObject): def __init__(self, api_ref, upstream_ref, policies, tls): super(RouteSpecification, self).__init__() self.api_ref = api_ref self.upstream_ref = upstream_re...
load("//java/private:common.bzl", "has_maven_deps") load("//java/private:dist_info.bzl", "DistZipInfo", "dist_aspect", "separate_first_and_third_party") def _java_dist_zip_impl(ctx): inputs = [] files = [] for file in ctx.files.files: files.append("%s=%s" % (file.basename, file.path)) input...
"""draws the price charts for all the securities in the currently active case""" from multiprocessing.connection import Listener from bokeh.driving import count from bokeh.layouts import layout, column, gridplot, row, widgetbox from bokeh.models import ColumnDataSource, CustomJS, Span from bokeh.plotting import curdoc,...
#function = -x**2 + 2*x - 1 # x = [0,3] import random import easygui import math def representation(interval,precision,no_selected): original_list = [] largest = int(interval*(10**precision)) select_interval = int(largest//no_selected) for i in range(1,largest + 1): str_temp = '' if i %...
import pytz from datetime import datetime from FlaskRTBCTF import create_app, db, bcrypt from FlaskRTBCTF.helpers import handle_admin_pass from FlaskRTBCTF.models import User, Score, Notification, Machine from FlaskRTBCTF.config import organization, LOGGING if LOGGING: from FlaskRTBCTF.models import Logs app = ...
# This file is part of DroidCarve. # # Copyright (C) 2020, Dario Incalza <dario.incalza at gmail.com> # All rights reserved. # __author__ = "Dario Incalza <dario.incalza@gmail.com" __copyright__ = "Copyright 2020, Dario Incalza" __maintainer__ = "Dario Incalza" __email__ = "dario.incalza@gmail.com" from adbutils impo...
import logging _FORMAT = '%(asctime)s:%(levelname)s:%(lineno)s:%(module)s.%(funcName)s:%(message)s' _formatter = logging.Formatter(_FORMAT, '%H:%M:%S') _handler = logging.StreamHandler() _handler.setFormatter(_formatter) logger = logging.getLogger('yatsm') logger.addHandler(_handler) logger.setLevel(logging.INFO) lo...
# Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None def pathSum(root: TreeNode, sum: int) -> [[int]]: temp = [] result = [] def dfs(root: TreeNode, left: int) : if not root : return ...
"""Perform non-linear regression using a Hill function.""" import numpy as np import math from scipy.optimize import curve_fit class Hill: """A Hill function is for modeling a field falloff (i.e. penumbra). It's not a perfect model, but it fits to a function, which is not limited by resolution issues as may ...
### Wet HW2 DIP ### import numpy as np import matplotlib.pyplot as plt import cv2 from scipy import fftpack ########################################################################### ########################################################################### ############################################################...
from pathlib import Path from code_scanner.data_validators import validator from code_scanner.enums import FileType class FileInfo: def __init__(self, full_name: Path, file_type: FileType = FileType.UNKNOWN): """ :param full_name: Absolute folder without file, Path :param file_type: ...
# # Base engine class # Copyright EAVISE # import logging import signal from abc import ABC, abstractmethod import lightnet as ln __all__ = ['Engine'] log = logging.getLogger(__name__) class Engine(ABC): """ This class removes the boilerplate code needed for writing your training cycle. |br| Here is th...
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import yaml import roslib from sensor_msgs.msg import CameraInfo, Image import rospy class CameraInfoPublisher: # Callback of the ROS subscriber. def callback(self, data): self.cam_info.header = data.header self.publish() def __init__...
import numpy as np import pandas as pd import matplotlib.pyplot as plt def cal_Nash(obs_path, predict_array): obs = pd.read_csv(obs_path, index_col=0, parse_dates = True) obs_chl = obs['chla'].iloc[:-1]
import serial import time arduino = serial.Serial("COM5", 9600, timeout=0) time.sleep(5) for i in range(10000): arduino.write(chr(0+48).encode()) arduino.write(chr(1+48).encode()) arduino.write(chr(2+48).encode()) arduino.write(chr(3+48).encode()) arduino.write(chr(4+48).encode()) arduino.write(...
#!/usr/bin/env python3 """ domain2idna - The tool to convert a domain or a file with a list of domain to the famous IDNA format. This submodule contains all helpers that are used by other submodules. Author: Nissar Chababy, @funilrys, contactTATAfunilrysTODTODcom Contributors: Let's contribute to domains2id...
from models.nasnet_do import NASNet_large_do from tensorflow.keras import Model, Input from tensorflow.keras.applications import DenseNet169 from tensorflow.keras.layers import Dropout, UpSampling2D, Conv2D, BatchNormalization, Activation, concatenate, Add from tensorflow.keras.utils import get_file from . import Net...
""" Profile ../profile-datasets-py/standard54lev_o3_trunc/005.py file automaticaly created by prof_gen.py script """ self["ID"] = "../profile-datasets-py/standard54lev_o3_trunc/005.py" self["Q"] = numpy.array([ 4.902533, 4.833692, 4.768255, 4.706048, 4.646861, 4.590505, 4...
# uncompyle6 version 3.7.4 # Python bytecode 3.7 (3394) # Decompiled from: Python 3.7.9 (tags/v3.7.9:13c94747c7, Aug 17 2020, 18:58:18) [MSC v.1900 64 bit (AMD64)] # Embedded file name: T:\InGame\Gameplay\Scripts\Server\rabbit_hole\tunable_rabbit_hole_condition.py # Compiled at: 2018-08-14 18:06:05 # Size of source mod...
# -*- coding: utf-8 -*- """FIFO Simulator.""" from __future__ import annotations import queue from queue import Queue import threading from typing import Any from typing import Dict from typing import Optional from stdlib_utils import drain_queue from xem_wrapper import DATA_FRAME_SIZE_WORDS from xem_wrapper import D...
import sys from pathlib import Path from setuptools import find_packages, setup project_slug = "nptyping" here = Path(__file__).parent.absolute() def _get_dependencies(dependency_file): with open(here / "dependencies" / dependency_file, mode="r", encoding="utf-8") as f: return f.read().strip().split("\n...
from math import pi import numpy as np cm = 0.23 km = 370.0 WIND = 5.0 OMEGA = 0.84 AMPLITUDE = 0.5 CHOPPY_FACTOR = np.array([2.3, 2.1, 1.3, 0.9], dtype=np.float32) PASSES = 8 # number of passes needed for the FFT 6 -> 64, 7 -> 128, 8 -> 256, etc FFT_SIZE = 1 << PASSES # size of the textures storing the waves in...
from datasets.kitti import * from Archs_3D.build_retina3d_model import build_model from Solver.Solver import Solver import operator import logging import os import sys import copy import datetime from datasets.distributed_sampler import * from datasets.dataset_utils import AspectRatioGroupedDataset import numpy as np i...
from __future__ import absolute_import, division, print_function import tensorflow as tf FLAGS = tf.app.flags.FLAGS def create_flags(): # Importer # ======== tf.app.flags.DEFINE_string ('train_files', '', 'comma separated list of files specifying the dataset used for training. multiple ...
""" Original Demo: http://js.cytoscape.org/demos/concentric-layout/ Original Code: https://github.com/cytoscape/cytoscape.js/blob/master/documentation/demos/concentric-layout/code.js Note: This example is broken because layout takes a function as input, i.e. ``` layout: { name: 'concentric', concentric: func...
import json import hikari async def debug(event: hikari.GuildMessageCreateEvent, command: str, config, *args) -> None: await event.message.respond(json.dumps({ "command": command, "args": args, "user": event.message.author.username, }))
from .models import TopLevelDomain,WhoisServer,Domain import json import dateutil.parser from django.db.models.functions import Length import xmltodict import socket import pythonwhois TLD_FIELDS_MAP = { '@name':"name", 'countryCode' : "country_code" , "created": 'created', "changed": 'changed', ...
# Copyright (c) 2020 - for information on the respective copyright owner # see the NOTICE file and/or the repository https://github.com/boschresearch/blackboxopt # # SPDX-License-Identifier: Apache-2.0 import time from typing import Callable import parameterspace as ps from blackboxopt import Evaluation, EvaluationS...
from typing import Iterator # noqa from pyramid.config import Configurator from pyramid.httpexceptions import HTTPInternalServerError from pyramid.response import Response from pyramid.request import Request # noqa import httpretty import pytest import _pytest # noqa import webtest httpretty.HTTPretty.allow_net_c...
from xmlrpc.server import SimpleXMLRPCServer from xmlrpc.server import SimpleXMLRPCRequestHandler import xmlrpc.client import time import ntplib from time import ctime import _thread import math import psutil s = xmlrpc.client.ServerProxy("http://localhost:9700") while(True): per_cpu = psutil.cpu_percent(); ...
from models.connection import get_cnx, tables ballot_table = tables["ballot"] ballot_info = tables["ballot_info"] score_table = tables["scores"] ranks_table = tables["ranks"] class Ballot: @staticmethod def _bool_to_SQL(witness: bool): return 1 if witness else 0 @staticmethod def create_ball...
""" Martin Kersner, m.kersner@gmail.com seoulai.com 2018 Adapted by Gabriela B. to work with python 2.7 and ROS """ from base import Constants from base import Piece import rospy #to print debug info class Rules(object): @staticmethod def get_opponent_type(ptype) : """Get a type of opponent agent. ...
"""Bubble sort Implementation in python.""" def bubble_sort(unsorted_list): """Iterate through an unsorted list and swap elements accordingly.""" # make a copy of the list unsorted_copy = unsorted_list[:] for index in range(len(unsorted_list) - 1): if unsorted_copy[index] > unsorted_copy[ind...
"""Builds a pip package suitable for redistribution. Adapted from tensorflow/tools/pip_package/build_pip_package.sh. This might have to change if Bazel changes how it modifies paths. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import argparse impor...
""" TODO: Insert player name in combat text """ import random as random import threading as threading import config as config import items as items lock = threading.Lock() def link_terminal(terminal): global terminal_output terminal_output = terminal def success(strength, attack_modifier, defense, att...
# Generated by Django 3.2.3 on 2021-05-26 16:20 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('TrafficMan', '0003_alter_violationprocess_options'), ] operations = [ migrations.AlterField( model_name='vehicle', n...
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # --------------------------------------------------------------------...
#!/usr/bin/env python ''' We get the lidar point cloud and use it to determine if there are any obstacles ahead Author: Sleiman Safaoui & Kevin Daniel Email: snsafaoui@gmail.com Github: The-SS Date: Oct 3, 2018 ''' # python from __future__ import print_function import numpy as np import copy import math from numpy ...
from b3get import to_numpy import numpy as np def test_available(): assert dir(to_numpy) def test_wrong_ds(): assert to_numpy(43) == (None, None) def test_008(): imgs, labs = to_numpy(8) assert len(imgs) > 0 assert len(imgs) == 24 assert isinstance(imgs[0], np.ndarray) assert imgs[0]....
"""/** * @author [Jai Miles] * @email [jaimiles23@gmail.com] * @create date 2020-05-20 13:17:50 * @modify date 2020-08-15 14:38:03 * @desc [ Handlers for mode statistics. - ModeStatsHandler TODO: Consider refactoring this into differnet handlers?? ] */ """ ########## # Imports ########## from as...
import re class Particle: def __init__(self, number, position, velocity, acceleration): self.number = number self.position = position self.velocity = velocity self.acceleration = acceleration self.destroyed = False def move(self): for i in range(len(self.accele...
""" Python code for hashing function """ def search(x): if x > 0: if has[x][0] == 1: return True # if X is negative take the absolute value of x. x = abs(x) if has[x][1] == 1: return True return False def insert(a, n): for i in range(0, n): if a[i] >= 0: ...
# -*- coding: utf-8 -*- import numpy as np from votesim.votemethods.ranked import borda def test_wiki_1(): """Test wiki example, https://en.wikipedia.org/wiki/Borda_count, Mar-3-2021 """ # Andrew Brian Catherine David # A B C D d = ( [[1, 3, 2, 4]] * 51 + [[4, 2, 1, 3]]...
from pypy.rpython.memory.gctransform.test.test_transform import rtype from pypy.rpython.memory.gctransform.stacklessframework import \ StacklessFrameworkGCTransformer from pypy.rpython.lltypesystem import lltype from pypy.translator.c.gc import StacklessFrameworkGcPolicy from pypy.translator.translator import Tran...
from applauncher.kernel import ConfigurationReadyEvent import redis class RedisBundle(object): def __init__(self): self.config_mapping = { 'redis': { 'host': {'type': 'string', 'default': 'localhost'}, 'port': {'type': 'integer', 'default': 6379}, ...