content
stringlengths
5
1.05M
# This file is part of the GBI project. # Copyright (C) 2013 Omniscale GmbH & Co. KG <http://omniscale.com> # # 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/licens...
#!/usr/bin/python # -*- coding: utf-8 -*- from django.test import TestCase, TransactionTestCase from django.test import Client from django.contrib.auth.models import User from trading.controller import axfd_utils, useraccountinfomanager from trading.models import * from tradeex.controllers.crypto_utils import CryptoUt...
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from __future__ import annotations import dataclasses from logging import Logger from typing import Any, Dict, List, O...
class ProjectLocationSet(APIObject,IDisposable,IEnumerable): """ An set that contains project locations. ProjectLocationSet() """ def Clear(self): """ Clear(self: ProjectLocationSet) Removes every project location from the set,rendering it empty. """ pass def Contains(self,item): ...
import json import requests from ..settings import Settings class Client: settings = Settings() def __init__(self,session=None): if session is None: self.session = requests.Session() else: self.session = session self.session.headers.update({'apikey':self.settings...
''' Page Rank Implemented page rank program based on fact that a website is more important if it is linked to by other important websites using recursive mathematical expression and random surfer probability distribution. ''' # Importing Libraries import os import random import re import sys import math # De...
# Author: Kimia Nadjahi # Some parts of this code are taken from https://github.com/skolouri/swgmm import numpy as np import ot # import HilbertCode_caller # import swapsweep def mOT(x, y, k, m): n = x.shape[0] if k < int(n / m): inds1 = np.split(np.random.permutation(n)[: int(n / m) * m], int(n / m...
from unittest import TestCase from apps.algorithms.mean import Mean from apps.algorithms.standart_deviation import StandartDeviation from apps.algorithms.z_value import ZValue __author__ = 'cenk' class ZValueTest(TestCase): def setUp(self): pass def test_algorithm_with_list(self): data_lis...
from regression_tests import * class TestUpxDetectionSegfault(Test): settings = TestSettings( tool='fileinfo', input='sample.ex', args='--json' ) # Ensures that PE files without sections do not crash fileinfo upon # execution. # See https://github.com/avast/retdec/issues/82...
from typing import Callable import numpy as np from pandas import DataFrame from .converter import ConverterAbs, interpret from .utils import INTER_STR_SEP class VarReplace(ConverterAbs): """Replaces the variable with some formula Transform all occurrences of the variable varname in the model with the ...
import math f = open("input.txt", "r") data = [] pattern = [0, 1, 0, -1] for char in f.read(): data += [int(char)] data *= 10000 outputOffset = "" for i in range(7): outputOffset += str(data[i]) outputOffset = int(outputOffset) for loop in range(100): for i in range(outputOffset + 9): total...
############################################################################## # # Copyright (c) 2009 Zope Foundation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOF...
""" System-level calls to external tools, directory creation, etc. Authors: Thomas A. Hopf """ import os from os import path import tempfile import subprocess import urllib.request import shutil import requests class ResourceError(Exception): """ Exception for missing resources (files, URLs, ...) """...
import pytest from elkconfdparser import errors from elkconfdparser import parser class TestDropStack: @pytest.mark.parametrize( "input_root, input_stack, expected_root, expected_stack", [ ({}, [], {}, []), ({}, [1], {}, [1]), ({}, [2, 1], {1: [2]}, []), ...
from itertools import chain, islice, starmap, cycle from operator import add def drop(n,xs): return islice(xs,n,None) def take(n,xs): return list(islice(xs,n)) class iself: def __init__(self, xs_ctor, nvp_max=4): self.xs_ctor=xs_ctor; self.nvp_max=nvp_max def __iter__(self): buf = [] ref_ivp = [0]; n ...
def facto_iterative(n): fac = 1 for i in range(n): fac = fac * (i+1) return fac number = int(input("Enter some value\n")) print(facto_iterative(number)) def facto_recursive(n): if n ==1: return 1 else: return n * facto_recursive(n-1) number = int(input("Enter some value\n"...
from django.conf.urls import url, include from website.views import index urlpatterns = [ url(r'^$', index, name='index') ]
#!/usr/bin/env python """Pipeline script for data pre-processing.""" import os import glob import numpy as np from ugali.analysis.pipeline import Pipeline import ugali.preprocess.pixelize import ugali.preprocess.maglims from ugali.utils.logger import logger components = ['pixelize','density','maglims','simple','spl...
#!/usr/bin/env python import logging import warnings import numpy as np from numpy.lib.ufunclike import isposinf from scipy.stats import chi EPS = 1e-8 class MultiVariateNormalDistribution(object): def __init__(self, shift, scale, cov, dim=None): # main components self.shift = shift self...
import mongoengine from .trace import WrappedConnect # Original connect function _connect = mongoengine.connect def patch(): setattr(mongoengine, "connect", WrappedConnect(_connect)) def unpatch(): setattr(mongoengine, "connect", _connect)
from sklearn.cluster import KMeans from collections import Counter import numpy as np import cv2 #for resizing image def get_dominant_color(image, k=4, image_processing_size = None): """ takes an image as input returns the dominant color of the image as a list dominant color is found by running k ...
#!/usr/bin/env python # Copyright (c) 2015-2021 Vector 35 Inc # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to # deal in the Software without restriction, including without limitation the # rights to use, copy, mo...
"""Cart-related forms and fields.""" from django import forms from django.conf import settings from django.core.exceptions import NON_FIELD_ERRORS, ObjectDoesNotExist from django.utils.translation import npgettext_lazy, pgettext_lazy from django_countries.fields import LazyTypedChoiceField, countries from ..core.excep...
#!/usr/bin/env python # Copyright 2008 by Jonathan Tang # 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 ...
import subprocess import sys import pkg_resources def get_bin_path(package_name: str, name: str) -> str: bin_name = name if sys.platform == "win32": bin_name = bin_name + ".exe" return pkg_resources.resource_filename(package_name, f"bin/{bin_name}") import pkg_resources def multiply_ext(lhs: ...
""" """ import copy def insert_sort(data): result = copy.deepcopy(data) for i in range(1, len(result)): key = result[i] left = i - 1 while left >= 0 and result[left] > key: result[left + 1] = result[left] left -= 1 result[left + 1] = key return resu...
import requests, os url = "https://ftp.ncbi.nlm.nih.gov/refseq/H_sapiens/annotation/GRCh38_latest/refseq_identifiers/GRCh38_latest_genomic.fna.gz" r = requests.get(url, allow_redirects=True) open("GRCh38_latest_genomic.fna.gz", "wb").write(r.content) os.system("gzip -d GRCh38_latest_genomic.fna.gz")
from typing import IO, Tuple import cv2 as cv import numpy as np from ..ModelBase import Justify, rgb from ..AbstractPlot import AbstractPlot from ..Typing import * def _pos(pos: POS_T) -> Tuple[int, int]: return (int(pos[0]*10), int(pos[1]*10)) def _pts(pts: PTS_T): res = [] for pos in pts: r...
import logging from rich.logging import RichHandler FORMAT = "%(message)s" logging.basicConfig(level="INFO", format=FORMAT, datefmt="[%X]", handlers=[RichHandler()]) log = logging.getLogger("rich")
import pandas as pd import h5py from collections import defaultdict from tqdm import tqdm import sys from pathlib import Path import warnings warnings.filterwarnings('ignore') def die(message, status=1): """Print an error message and call sys.exit with the given status, terminating the process""" print(messag...
from .process import Command as ProcessCommand from .sample_video import Command as SampleCommand class Command: name = "video_process" help = "sample video into images and process the images" def add_basic_arguments(self, parser): SampleCommand().add_basic_arguments(parser) ProcessComman...
import json import logging import pytest AED_CLOUD_ACTIVITY_EVENT_DICT = json.loads( """{ "url": "https://www.example.com", "syncDestination": "TEST_SYNC_DESTINATION", "sharedWith": [{"cloudUsername": "example1@example.com"}, {"cloudUsername": "example2@example.com"}], "cloudDriveId": "TEST_CLOUD...
from django.contrib import admin from django.utils.translation import gettext_lazy as _ from playexo.models import Answer, HighestGrade class EvalListFilter(admin.SimpleListFilter): # Human-readable title which will be displayed in the # right admin sidebar just above the filter options. title = _('Eval...
#!/usr/bin/python3.6 # -*- coding: utf-8 -*- # @Time : 2021/5/20 下午11:47 # @Author : Joselynzhao # @Email : zhaojing17@forxmail.com # @File : DataFrame.py # @Software: PyCharm # @Desc :
# libraries import numpy as np import matplotlib.pyplot as plt import seaborn as sns import pandas as pd import os,sys import matplotlib.dates as mdates import matplotlib as mpl from matplotlib.colors import ListedColormap from mpl_toolkits.axes_grid1.inset_locator import inset_axes from matplotlib.offsetbox import Anc...
# Pyrogram - Telegram MTProto API Client Library for Python # Copyright (C) 2017-2018 Dan Tès <https://github.com/delivrance> # # This file is part of Pyrogram. # # Pyrogram is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published # by the Free S...
from usure.preprocessing.cleaning.twittercorpuscleaner import TwitterCorpusCleaner def can_remove_all_id_test(): cleaner = TwitterCorpusCleaner() text = "\"406449856862232577\",\"\"Las despedidas no deberian existir\"\"" cleaned_text = "\"\"Las despedidas no deberian existir\"\"" procesed_text = clean...
# Exercício Python 067 # Mostre a tabuada de varios números, um de cada vez, para cada valor digitado pelo usuário # Programa interrompido quando N for negativo while True: print('=-=' * 14) n = int(input('Você quer saber a tabuada de qual valor? ')) if n < 0: break contador = 0 while conta...
# Generated by Django 2.1.1 on 2018-09-19 19:46 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('custom', '0001_initial'), ] operations = [ migrations.AddField( model_name='riskfield', ...
# AUTOGENERATED BY NBDEV! DO NOT EDIT! __all__ = ["index", "modules", "custom_doc_links", "git_url"] index = {"say_hello": "00_core.ipynb", "say_bye": "00_core.ipynb", "optimize_bayes_param": "01_bayes_opt.ipynb", "ReadTabBatchIdentity": "02_tab_ae.ipynb", "TabularPandasIdentity": ...
import tensorflow as tf import numpy as np print(tf.__version__) from tensorflow.contrib.learn.python.learn.datasets import base IRIS_TRAINING="iris_training.csv" IRIS_TEST="iris_test.csv" traning_set=base.load_csv_with_header(filename=IRIS_TRAINING,features_dtype=np.float32,target_dtype=np.int) test_set=base.load...
# -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # -------------------------------------------------------------------------- def cf_...
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import argparse import logging from collections import namedtuple from flask import Flask from flask_cors import CORS from threading import Thread from builtins import ...
import os import tornado.web import tornado.ioloop from tornado.options import define, options, parse_command_line from tornado_face.face.views import RegisterHandler, InitDbHandler, LoginbHandler define('port', default=8090, type=int) def make_app(): return tornado.web.Application(handlers=[ (r'/regis...
import cv2 import numpy as np import pandas as pd import matplotlib.pyplot as plt import glob from IPython.display import clear_output from numpy import expand_dims from keras.preprocessing.image import load_img from keras.preprocessing.image import img_to_array from keras.preprocessing.image import ImageDataGenerator...
from typing import Dict, List, Optional, Tuple, Union import numpy as np from key_door import constants, wrapper try: import cv2 import matplotlib from matplotlib import cm from matplotlib import pyplot as plt from mpl_toolkits.axes_grid1 import make_axes_locatable except: raise AssertionError...
# @file: Individual that contains the 'DNA' for each individual in the population # @author: Daniel Yuan from random import randint, uniform class Individual(object): def __init__(self, vector, search_range, dimension=None): # Ensure that Indidual has assert(search_range and (vector or dimension)) self....
#!/usr/bin/python #coding=utf8 import pandas as pd def readBigData(filePath,delim,header=None): reader = pd.read_csv(filePath,header=None,delimiter=delim, iterator=True) loop = True chunkSize = 100000 chunks = [] while loop: try: chunk = reader.get_chunk(chunkSize) c...
#!/usr/bin/env python def gcd_mod(a, b): ''' Divison based version. From: The Art of Computer Programming, Volume 2, pages 319-320 ''' while b > 1: # t holds the value of b while the next remainder b is being calculated. t = b b = a % b a = t return a def gcd_...
#!/usr/bin/env python3 ''' This script ... ''' import argparse # https://docs.python.org/3/library/argparse.html import itertools import os import screed import networkx as nx from tqdm import tqdm from panprimer.utils import \ load_graph, \ mask_nodes, \ extract_color, \ neighbors, \ orient_nod...
class Solution(object): def missingNumber(self, nums): """ :type nums: List[int] :rtype: int """ # 0,1,...,n-1,n,sum of arrary (if no missing number) will be sum = n*(n+1)/2 # delete all existing nums will leave the number that is missing from the array n = le...
from .tikzeng import * #define new block def block_2ConvPool( name, botton, top, s_filer=256, n_filer=64, offset="(1,0,0)", size=(32,32,3.5), opacity=0.5 ): return [ to_ConvConvRelu( name="ccr_{}".format( name ), s_filer=str(s_filer), n_filer=(n_filer,n_filer), offset=offset...
import sys class MyStack: """push-down スタッククラス""" def __init__(self, stacksize): """コンストラクタ(初期化)""" # フィールド self.mystack = [ ' ' for i in range(stacksize) ] self.top = -1; def pushdown(self, data): """プッシュダウン""" self.top += 1 ...
"""Merkle Tree backed by LevelDB. Operates (and owns) a LevelDB database of leaves which can be updated. """ import plyvel import math import struct import merkle def _down_to_power_of_two(n): """Returns the power-of-2 closest to n.""" if n < 2: raise ValueError("N should be >= 2: %d" % n) log_n...
#!/usr/bin/python # coding=utf-8 print('{0:.3f}'.format(1.0/3)) print('{0:_^11}'.format('kai')) print(r'\'{name}\' wrote\n "{book}"'.format(name='kai', book='good book')) # print('kai', end=' ') //python3 # print('is') # print('good man') s = '''This is Multi Line String Second Line Third Line''' print(s) number ...
import constants as c import logging import rosbag import os import multiprocessing topics_to_check = set([ '/TactileSensor4/Accelerometer', '/TactileSensor4/Dynamic', '/TactileSensor4/EulerAngle', '/TactileSensor4/Gyroscope', '/TactileSensor4/Magnetometer', '/TactileSensor4/StaticData', '/...
import setuptools __version__ = '1.0' setuptools.setup( name="msfbe", version=__version__, url="https://github-fn.jpl.nasa.gov/methanesourcefinder/msf-be.git", author="Caltech/Jet Propulsion Laboratory", description="MSF-BE API.", long_description=open('README.md').read(), package_dir={...
#!/usr/bin/env python # -*- coding: iso-8859-15 -*- # -*- Mode: python -*- from lib.common import * ################################################################ # Code borrowed and adapted from Impacket's rpcdump.py example # ################################################################ class RpcDump(object): ...
@Counter def say_hello(): print("hello") say_hello() say_hello() say_hello() say_hello() assert say_hello.count == 4
"""Unit test package for xlavir."""
import numpy as np from pathlib import Path import pandas as pd from tensorflow.keras.models import load_model import sys import inspect cpath = Path(inspect.getfile(sys.modules[__name__])).resolve().parent def transform_features(x, f="cos"): if f == "cos": return np.cos(x) elif f == "sin": re...
from abc import ABC #Abstract Base Classes from collections.abc import MutableSequence class Playlist(MutableSequence): filmes = Playlist()
import yaml import json import os from autoremovetorrents import logger from autoremovetorrents.task import Task from autoremovetorrents.compatibility.open_ import open_ def test_task(qbittorrent_mocker): # Loggger lg = logger.Logger.register(__name__) # Set root directory root_dir = os.path.join(os.p...
a, b, c = list(map(int, input().split())) tot = 0 if abs(a - b) < abs(c - b): tot = abs(c - b) else: tot = abs(a - b) print(tot - 1)
import sys import getopt from jiaowu import JiaoWu if __name__=='__main__': username = input('学号: ') password = input('统一认证密码: ') jiaowu = JiaoWu(username, password) # 登录 if jiaowu.login(): print('登录成功!') else: print('登录失败!请检查用户名和密码') exit() # 查询课表 year = ...
# -*- coding: utf-8 -*- # Generated by Django 1.10.6 on 2017-04-16 00:36 from __future__ import unicode_literals import ckeditor.fields from django.db import migrations, models import django.db.models.deletion import school.options.tools class Migration(migrations.Migration): dependencies = [ ('website'...
#!/usr/bin/python import sys import pickle sys.path.append("../tools/") import numpy as np import matplotlib.pyplot as plt from functions import * from feature_format import featureFormat, targetFeatureSplit from tester import dump_classifier_and_data ### Task 1: Select what features you'll use. ### features_list is...
class Solution: def maxNumOfSubstrings(self, s: str) -> List[str]: start, end = {}, {} for i, c in enumerate(s): if c not in start: start[c] = i end[c] = i def checkSubstring(i): curr = i right = end[s[curr]] ...
import asyncio import datetime import gettext import math import os import random import pyrogram import speech_recognition import time import youtube_dl from datetime import timedelta from pyrogram.raw import types as raw_types from pyrogram.raw.functions import phone from pyrogram import types from pyrogram.raw imp...
from django.db import models # Create your models here. class Todo(models.Model): ident = models.CharField(max_length=50, primary_key=True) desc = models.CharField(max_length=500) group = models.IntegerField(default=0) schedule_date = models.DateField(blank=False) finish_date = models.DateField(nul...
import argparse from mmap import * from pathlib import Path from ctypes import * from .common import * class DisplayVariable(BigEndianStructure): _pack_ = 1 _fields_ = [("valid", c_uint8), ("type", c_uint8), ("sp_word", c_uint16), ("desc_len_words", c_...
""" Copyright (c) 2016-2020 The scikit-optimize developers. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of con...
_base_ = '../faster_rcnn/faster_rcnn_x101_64x4d_fpn_1x_coco.py' model = dict( roi_head=dict( bbox_head=dict( num_classes=22 ) ) ) dataset_type = 'CaltechDataset' classes = ('bobcat', 'opossum', 'empty', 'coyote', 'racoon', 'bird', 'dog', 'cat', 'squirrel', 'rabbit', 'skunk', 'lizard', 'rodent',...
#!/usr/bin/python # -*- coding: utf-8 -*- # # CarMonitor EnviroPHAT Polling Thread and LED Interface # # Author: Patrick Schmidt <patrick@ealp-net.at> # License: Apache License, Version 2.0 # # See: https://shop.pimoroni.de/products/enviro-phat # See: https://learn.pimoroni.com/tutorial/sandyj/getting-started-with-env...
# Copyright 2014 Facebook, Inc. # You are hereby granted a non-exclusive, worldwide, royalty-free license to # use, copy, modify, and distribute this software in source code or binary # form for use in connection with the web services and APIs provided by # Facebook. # As with any software that integrates with the Fa...
from twozerofoureight import * game_board = board() game_board.generate_newpiece("start") game_board.generate_newpiece("start") game_board.print_board("normal") def move(direction): original_board = list(game_board.board_list) if direction == "left": game_board.move_left_right("left") elif direction == "right"...
# -*- coding: utf-8 -*- import unittest import httpreplay class TestHttp(unittest.TestCase): def test_request(self): r = httpreplay.interpret_http("POST / HTTP/1.0\r\nConnection: close\r\n\r\n1234", True) self.assertEqual(r.body, "1234")
import sys import re import random from libs.playerCommandsLib import Commands from libs.playerCommandsLib import playerCommand from libs.decs.itemDecs import * from libs.decs.eventDecs import * from libs.decs.NpcDecs import * from libs.decs.playerDec import * from libs.decs.structureDecs import * from li...
import os cur_dir = os.path.dirname(os.path.abspath(__file__)) num_questions = 0 with open(f"{cur_dir}/input") as f: cur_group = set() initialized = False for line in f: if line == "\n": num_questions += len(cur_group) cur_group = set() initialized = False ...
from .multisource_dataset import MultiSourceDataset from .streaming_multisource_dataset import StreamingMultiSourceDataset from .multilingual_translation_task import MultilingualTranslationTask
""" An example of the 'science' theme. """ import numpy as np import matplotlib.pyplot as plt plt.style.use(['science']) x = np.linspace(0.75, 1.25, 201) def model(x, p): return x ** (2 * p + 1) / (1 + x ** (2 * p)) fig, ax = plt.subplots() for p in [10, 15, 20, 30, 50, 100]: ax.plot(x, model(x, p), labe...
from django.shortcuts import render # Create your views here. from rest_framework import viewsets from .serializers import ( TmDataSerializer, CycleSerializer ) from .models import ( Tm, Cycle ) class TmViewSet(viewsets.ModelViewSet): serializer_class = TmDataSerializer queryset = Tm.objects.a...
import pygame from modules import basic_classes from modules import basic_globals from modules.gamemaker_functions import * from games.grarantanna import grarantanna_gun import os class Player(basic_classes.UpdatableObj): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self....
#!/usr/bin/python # A tool to quickly generate large skip, load, xfail list for Rally in case of customized cloud policies # # How to use: # 1. Prepare a list of testcases you want to include (e.g. rally verify show | grep failed > cases.list) # 2. Prepare a complete list of testcases with ids (cd ~/.rally/verifica...
import neuralnet as n import numpy as np net = n.NeuralNet([2, 4, 1]) net.train(np.array([[0, 1]]), np.array([[1]]))
import collections import functools import typing from hat.event.common.data import EventType class Subscription: """Subscription defined by query event types""" def __init__(self, query_types: typing.Iterable[EventType], cache_maxsize: typing.Optional[int] = 0): se...
# EPAN_NI.py (flowsa) # !/usr/bin/env python3 # coding=utf-8 """ Projects / FLOWSA / Years = 2012 Eliminated all columns with fraction in the title. """ import io import pandas as pd import xml.etree.ElementTree as ET from esupy.remote import make_url_request def url_file(url): url_array = url.split("get/") u...
from __future__ import division # LIBTBX_SET_DISPATCHER_NAME prime.viewstats ''' Author : Uervirojnangkoorn, M. Created : 9/19/2014 Description : View convergence and other stats for post-refinement. ''' import matplotlib.pyplot as plt import sys import numpy as np if len(sys.argv)==1: print 'Use prime.view...
import os import sys sys.path.append( os.path.normpath( os.path.join(os.path.abspath(__file__), "..", "..", "..", "common") ) ) from env_indigo import * indigo = Indigo() indigo.setOption("timeout", "2000") t = indigo.loadMolecule( "N(C1N=CC=C2C=1C=C(C1C=CC=CC=1)C(C1C=CC(C3(NC(=O)OC(C)(C)C)CC4(OC...
from recoder.embedding import AnnoyEmbeddingsIndex import pytest import numpy as np def test_build_index(): embeddings_mat = np.random.rand(1000, 128) index = AnnoyEmbeddingsIndex(embeddings=embeddings_mat) index.build(index_file='/tmp/test_embeddings') index_loaded = AnnoyEmbeddingsIndex() index_loaded...
#!/usr/bin/env python """ Contains the proxies.BaseProxy class definition for all inherited proxy classes Please note that this module is private. The proxies.BaseProxy class is available in the ``wpipe.proxies`` namespace - use that instead. """ from .core import numbers, datetime, si, in_session, try_scalar __all__...
import json import os import sys #usr_part = "\n".join([e for i,e in enumerate(utterances) if i%2==0])+"\n" global DOT_CHAR DOT_CHAR = "@DOT" def historify_src(utterances, even=True): #helper function to add the entire dialogue history as src parity = 0 if even else 1 assert set([bool(utt.strip()) == ...
from typing import Mapping, Tuple, Union from uqbar.containers import UniqueTreeList from .Attachable import Attachable from .Attributes import Attributes class TableCell(UniqueTreeList, Attachable): """ A Graphviz HTML table. :: >>> import uqbar.graphs >>> table_cell = uqbar.graphs.Ta...
import os os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' import tensorflow as tf import time import utils import datasets from NetworkLib import GlimpseNet, LocationNet, ContextNet, ClassificationNet, RecurrentNet, BaselineNet from visualizer import * from config import Config class DRAM(object): def __init__(self): ...
from collections import OrderedDict TARGETS = OrderedDict([('2.5', (2, 5)), ('2.6', (2, 6)), ('2.7', (2, 7)), ('3.0', (3, 0)), ('3.1', (3, 1)), ('3.2', (3, 2)), ('3.3', (3, 3)), ...
# Testoob, Python Testing Out Of (The) Box # Copyright (C) 2005-2006 The Testoob Team # # 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 # # Un...
#! /usr/bin/env python3 from sim import Simulation if __name__ == "__main__": sim = Simulation(ants=5, x=100, y=100, num_rivers=20) sim.run()
def Golden_eagle(thoughts, eyes, eye, tongue): return f""" {thoughts} ,:=+++++???++?+=+= {thoughts} :+?????\$MUUUUUUUUUMO+??~ {thoughts} :+I??\$UUUUMUMMMMUUMUMUUMUUMM???I+: {thoughts} ...
num_rows = int(input()) matrix = [input().split(", ") for _ in range(num_rows)] first_diag = [matrix[i][i] for i in range(len(matrix))] second_diag = [matrix[i][-(i + 1)] for i in range(len(matrix))] print(f"First diagonal: {', '.join(first_diag)}. Sum: {sum(map(int, first_diag))}") print(f"Second diagonal: {', '.jo...
import random from time import sleep itens = ["Rock", "Paper", "Scissors"] computer = random.choice(itens) print("-"*24) print("Scissors, Paper and Rock") print("-"*24) print("Your Options") print("[1] Rock\n[2] Paper\n[3] Scissors") player = int(input("Choose one option: ")) print("-"*17) print("Sci...