text
stringlengths
3.07k
12.6k
import os import sys ROOT_DIR = os.path.dirname(os.path.abspath(os.path.dirname('__file__'))) sys.path.append(ROOT_DIR) import torch from mock import MagicMock from mock import patch from trainers.mask_r_cnn_trainer import MaskRCNNTrainer device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") class ...
""" consensys_utils.flask.app ~~~~~~~~~~~~~~~~~~~~~~~~~ This module implements a WSGI application object. :copyright: Copyright 2017 by ConsenSys France. :license: BSD, see :ref:`license` for more details. """ import flask from .blueprints import register_blueprints from .config import set_app_c...
import torch import torch.nn as nn import torch.nn.functional as F import math from torch.distributions import Normal LOG_SIG_MAX = 2 LOG_SIG_MIN = -10 epsilon = 1e-6 # Initialize Policy weights def weights_init_(m): if isinstance(m, nn.Linear): torch.nn.init.xavier_uniform_(m.weight, gain=1) torc...
from __future__ import absolute_import from __future__ import division from __future__ import print_function import argparse import sys import numpy as np import tensorflow as tf import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec from dataset import load_data, DataSet from vae import VAE from co...
# -*- coding: utf-8 -*- import click import logging from pathlib import Path from dotenv import find_dotenv, load_dotenv import os # The basics import numpy as np import pandas as pd # Sklearn from sklearn.model_selection import train_test_split from sklearn.metrics import classification_report, confusion_matrix # K...
#!/usr/bin/env python # coding: utf-8 # # Desafio 1 # # Para esse desafio, vamos trabalhar com o data set [Black Friday](https://www.kaggle.com/mehdidag/black-friday), que reúne dados sobre transações de compras em uma loja de varejo. # # Vamos utilizá-lo para praticar a exploração de data sets utilizando pandas. Vo...
# -*- coding: utf-8 -*- """ Numeric to word convertor in Turkish Copyright (c) 2017 Munich Artificial Intelligence Laboratories GmbH (M-AILABS) Created: 2017-02-25 ??:?? CET, KA eoner: Added ordinal, percent, .5 (bucuk) handling """ import sys import os import re _comma_number_re = re.compile(r'([0-9][0-9\.]+[0-9...
# -*- coding: utf-8 -*- import concurrent import os from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor import click import logging import urllib.request import tarfile import fastavro as avro import json import gzip import shutil from dotenv import find_dotenv, load_dotenv from url_builder import ...
"""Strawberry object types.""" import enum from dataclasses import dataclass, field from datetime import date, datetime, time from decimal import Decimal from functools import cached_property from typing import List, Optional, Type from uuid import UUID import strawberry from strawberry import ID from strawberry.argu...
#!/usr/bin/env python3 ''' Create or update the archived data files served on request by the download API. This command should be run periodically (ideally once a day) as the tfc_prod user. ''' import csv import fcntl import glob import importlib import logging import os from datetime import date from tempfile impo...
import re from pypinyin import Style, load_phrases_dict from pypinyin.contrib.neutral_tone import NeutralToneWith5Mixin from pypinyin.converter import DefaultConverter from pypinyin.core import Pinyin from pycnnum import num2cn import jieba import numpy as np split_pat = re.compile(r'[:;、,。?!\s,]\s*') num_pat = re.c...
""" File: titanic_github.py Name: <NAME> ---------------------------------- This file builds a machine learning algorithm by pandas and sklearn libraries. We'll be using pandas to read in dataset, store data into a DataFrame, standardize the data by sklearn, and finally train the model and test it on kaggle. Hyperparam...
#!/usr/bin/python import copy import multiprocessing import os import random import tempfile SERVER_PID = os.path.join(tempfile.gettempdir(), 'performa.oms.pid') SERVER_FILE_NAME = os.path.join(tempfile.gettempdir(), 'performa.oms.srv') CLIENT_FILE_NAME = os.path.join(tempfile.gettempdir(), 'performa.oms.cln') UNIQUE_...
from asyncdbus.service import ServiceInterface, signal from asyncdbus import Message, MessageBus from asyncdbus.introspection import Node from asyncdbus.constants import RequestNameReply from asyncdbus.signature import Str, Tuple import pytest class ExampleInterface(ServiceInterface): def __init__(self): ...
''' A minimal example of how to fit a LogisticHazard model with pytorch lightning The point of this example is to make it simple to use the LogisticHazard models in other frameworks that are not based on torchtuples. Original author: <NAME> @rohanshad ''' from typing import Tuple import numpy as np import pandas as p...
''' Code related to the crawler timer thread... mostly stats stuff. TODO: add methods to add one-shot and periodic stuff dynamically Hardwired stuff: "fast" and "slow" set to 1 second and 30 seconds Record delta, Send stats to Carbon TODO rebin to actual "fast" and "slow" durations, instead of my 29 second hack (w...
from .st import * from .mt import makeMask import numpy as np, matplotlib.pyplot as plt, cv2 def Erode_Dilate(mask): def process(mask_, kernel, iters): top_erode1 = cv2.erode(mask_, kernel, iterations=iters) top_dilate = cv2.dilate(top_erode1, kernel, iterations=iters*2) top_erode2 = cv2.erode(top_dilate, kerne...
"Test helper functions" import numpy as np import pytest from sklearn.metrics import mean_squared_error, mean_absolute_error from elnetpy.utils import ( standardize_inputs, destandardize_coefs, get_linear_scorer, score_multiple, check_fitted_model, interpolate_model, ) def test_standardize_i...
#Copyright 2021 Google LLC #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 #https://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # d...
import datetime from flask import Flask, render_template, g, redirect, url_for, Blueprint, request, session, abort, flash from LCNapp import db from LCNapp.auth import login_required, member_required from LCNapp.admin.admin import getDate from LCNapp.forms import MemberUpdate, ChangePassword bp = Blueprint("member",...
""" Author: <NAME> Date: 08/07/2020 """ codes = {'.-': 'A', '-..': 'D', '.': 'E', '--.':'G', '..': 'I', '-.-': 'K', '--': 'M', '-.': 'N', '---': 'O', '.-.': 'R', '...': 'S', '-':'T', '..-':'U','.--':'W'} class Node: def __init__(self, value): self.left = None self.right = None sel...
import os import re import time from configparser import RawConfigParser from urllib.parse import urljoin from urllib.request import urlopen, build_opener from bs4 import BeautifulSoup from financial_statements_downloader.data import Data PARSER = "html5lib" """BeautifulSoup parser.""" WAIT = 1 """Wait seconds afte...
""" Perform panchromatic thresholding. If you plan on using this implementation, please cite our work: @INPROCEEDINGS{Grabowski2021IGARSS, author={Grabowski, Bartosz and Ziaja, Maciej and Kawulok, Michal and <NAME>}, booktitle={IGARSS 2021 - 2021 IEEE International Geoscience and Remote Sensing Symposium}, title={Towa...
# -*- coding: utf-8 -*- import codecs, json import argparse RECORD_DELIM = " " DELIM = u"│" NUM_PLAYERS = 13 parser = argparse.ArgumentParser(description='Script to create dataset') parser.add_argument('-json_root', type=str, default="", help="path to json input") parser.add_argument('-output_fi'...
import os import sys import math try: from PIL import Image, ImageDraw, ImageFont except: print( "\nRequires the Pillow python module to produce font images\nPlease 'pip install pillow'" ) exit(1) def _make_pixel( val ): """ Construct a pixel tuple of (R,G,B,A) from the unsigned integer val. ...
import bpy, bmesh import os import mathutils import math from mathutils import Vector import operator from . import objects_organise class op(bpy.types.Operator): bl_idname = "fbxbundle.pack_bundles" bl_label = "Pack Bundles" bl_description = "Pack bundles in a atlas formation" bl_options = {'REGISTER', 'UNDO'}...
"""A set of reusable query makers. These queries can be used as subqueries in the individual filter() methods of Connector objects """ import datetime from pony import orm def source_query(db, sourceId="", label="", s="", **other_filters): """Construct a (sub)query based on named filters. Returns a pony.q...
""" SCL <<EMAIL>> Copyright (c) 2020 rerobots, Inc. """ import aiohttp from aiohttp import web @web.middleware async def cors_handler(request, handler): """Middleware to add CORS response headers """ response = await handler(request) response.headers['Access-Control-Allow-Origin'] = '*' return res...
# Copyright 2021 ETH Zurich, Media Technology Center # # 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...
from Processor.Utils.imageutils import calc_distance, increment_dict_key_value from Processor.Utils import constants def calc_path_metrics(night_day_time_period_paths, tag_class): all_activity_grouped_by_type = [] all_distances_per_second_window = [] all_perimeter_data = [] all_reappearance_data = [] ...
import numpy as np import random def average_above_zero (items): """ Compute the average of an given array only for positive values. @type items: list @param items: List of positive values @rtype: float @return: Return the average of the list """ # Don't compute if items isn't an List (arr...
import abc import csv import math # TODO: re-think read_csv and node_dict validation procedure class _Node(abc.ABC): """ADT to represent abstract concept of a node. Methods to be implemented by sublcasses: distance_to(self, other) Returns distance to other node. """ # declare em...
#!/usr/bin/env python3 import rospy import os from sensor_msgs.msg import LaserScan from ackermann_msgs.msg import AckermannDriveStamped from f1tenth_gym_ros.msg import RaceInfo current_dir = os.path.abspath(os.path.dirname(__file__)) package_dir = os.path.abspath(os.path.join(current_dir, "..")) import numpy as np ...
from django import forms from django.contrib.auth.forms import UserCreationForm, UserChangeForm from django.contrib.auth import get_user_model, authenticate from .models import Profile, City, Town User = get_user_model() # from django import forms # from django.contrib import admin # from django.contrib.auth.mode...
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. import re from .tflite_profiler import TFLiteProfiler from .tflite_backend import TFLiteBackend from ..interface import BaseParser from nn_meter.builder.backend_meta.utils import Latency, ProfiledResults class TFLiteGPULatencyParser(BaseParser):...
# Copyright Amazon Web Services and 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. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required...
from models import Anchor, AnchorLink, TableOfContents from cms_plugins import AnchorPlugin from cms.utils.placeholder import get_page_from_placeholder_if_exists ################## # Helpful things ################## class Struct: # To allow anonymous objects def __init__(self, **entries): self.__dict__.u...
import json import os import pathlib import re import shlex import subprocess import yaml import constants as C import util def get_override_metadata(dirpath): metadata_file = dirpath.joinpath('metadata.yaml') if metadata_file.exists(): with metadata_file.open() as fin: metadata = yaml.s...
# ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # -------------------------------------------------------------------------- import te...
#=============================================================================== # Copyright 2021 Intel Corporation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.a...
# Copyright (c) 2015 Canonical Ltd # Copyright (c) 2015 Mirantis 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 # # Un...
import warnings import numpy as np import scipy.sparse as sp from typing import Union, Optional, List, Tuple, Any from graphgallery import functional as gf from ..data_type import is_multiobjects __all__ = ['sparse_apply', 'check_and_convert', 'index_select'] _SPARSE_THRESHOLD = 0.5 def sparse_apply(k...
# -*- coding: utf-8 -*- """ Tests for PyInstaller.depend.bytecode """ from types import CodeType from textwrap import dedent, indent import operator from PyInstaller import compat from PyInstaller.depend.bytecode import ( function_calls, recursive_function_calls, any_alias, ) def compile_(x): return...
import discord from discord.ext import commands from QuentiumBot import HandleData, get_translations, is_owner # Basic command configs cmd_name = "help" tran = get_translations() aliases = [] if not tran[cmd_name]["fr"]["aliases"] else tran[cmd_name]["fr"]["aliases"].split("/") class HelpInfos(commands.Cog): """H...
# 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. import math from dataclasses import dataclass, field from typing import List, Optional import torch import torch.nn.functional as F from fair...
import numpy as np from typing import List, Tuple from collections import namedtuple import torch import torch.nn as nn import torch.nn.functional as F from torch.utils.model_zoo import load_url as load_state_dict_from_url from ..utils import box_utils GraphPath = namedtuple("GraphPath", ['s0', 'name', 's1']) # cl...
#!/usr/bin/env python3 # Copyright (C) 2020 The btclib developers # # This file is part of btclib. It is subject to the license terms in the # LICENSE file found in the top-level directory of this distribution. # # No part of btclib including this file, may be copied, modified, propagated, # or distributed except acco...
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable from collections import OrderedDict from .layers import CellStem0, CellStem1, FirstCell, NormalCell, ReductionCell import torchmodul...
import requests import json from datetime import datetime import time def requisicao_api(url,headers): resposta = requests.get(url,headers=headers) if resposta.status_code == 200: return resposta.json() else: return resposta.status_code def monta_quesitos_palavras_chave(lista_palavras_cha...
#!/usr/bin/python # # Copyright (c) 2018. Aphelion Contributors # # 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 applicabl...
import numpy as np import pickle as pkl import networkx as nx import scipy.sparse as sp from scipy.sparse.linalg.eigen.arpack import eigsh import sys import pickle as cPickle def parse_index_file(filename): """Parse index file.""" index = [] for line in open(filename): index.append(int(line.strip()...
# encoding: utf-8 __doc__ = """ RMSD calculators and optimal rotation of sets of coordinates. Two algorithms are provided: 1. The standard SVD decomposition using the numpy library. 2. The qcp quaternion-based method that doesn't need numpy. The qcp method is particularly useful because it allows the library to ...
''' Fourier Accountant Code for computing tight DP guarantees for the subsampled Gaussian mechanism. This module holds common code to evaluate the privacy loss distribution for all computations. The method is described in A.Koskela, J.Jälkö and A.Honkela: Computing Tight Differential Privacy Guarantees Using FFT. arX...
import numpy as np import pandas as pd import logging from sklearn.base import BaseEstimator import pymbar class MBAR(BaseEstimator): """Multi-state Bennett acceptance ratio (MBAR). Parameters ---------- maximum_iterations : int, optional Set to limit the maximum number of iterations perfor...
from scrapy_autoproxy.config import config from scrapy_autoproxy.util import block_if_syncing from scrapy_autoproxy.redis_client import Redis from scrapy_autoproxy.exceptions import RedisDetailQueueEmptyException from scrapy_autoproxy.proxy_objects import Proxy, Detail, Queue import logging import datetime logger = log...
# emacs: -*- mode: python; py-indent-offset: 4; tab-width: 4; indent-tabs-mode: nil -*- # ex: set sts=4 ts=4 sw=4 noet: # ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ## # # See COPYING file distributed along with the datalad package for the # copyright and license terms. # # ## ### ##...
import socket import time import json import threading import sys from queue import Queue import struct MAX_PACKET_LOSS = .15 def max_packet_loss(pl_dict): max_p_loss = 0 for key in pl_dict: if pl_dict[key]['packet_loss'] > max_p_loss: max_p_loss = pl_dict[key]['packet_loss'] return ma...
# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not us...
from preprocessor import * table_headings = [] table_row_elements = [] box = [] try: import pytesseract except: print("xx Cannot import Tesseract, either it's not installed or there is some other error\n") exit(1) def sort_contours(cnts, method="l2r"): reverse = False i = 0 if method == "r2l...
import sqlparse from typing import List, Tuple class Operand: """ Wrapper for any operand made for str(). If it's a token from sqlparse, then use the `normalized` attribute """ def __init__(self, value): self.value = value def __repr__(self): return f'<Operand "{str(self)}">' d...
import numpy as np import math from gym import spaces from ..miniworld import MiniWorldEnv, Room from ..entity import ImageFrame from ..params import DEFAULT_PARAMS 'Importeirung der Objekte -> Ball, Box und Key' from ..entity import Box, Ball, Key 'Importeirung von Ramdom -> Um Zufallszahlen zu generieren' import ran...
import os from functools import partial import re from operator import add, neg import sys import pytest optimize2 = (sys.flags.optimize == 2) if not optimize2: pytest.importorskip("graphviz") from dask.dot import dot_graph, task_label, label, to_graphviz else: pytestmark = pytest.mark.skipif(True, ...
from prucc import * from library import * def compare_prucc(h=6, n_mpr=5, n_pru=5, fix='mpr', u_l='opt'): #h: chosen dataset ''' 1: firewall 1 6: healthcare 2: firewall 2 7: customer 3: domino 8: americas small ...
# Copyright 2018 The TensorFlow Authors. 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 by applica...
#!/usr/bin/env python # Copyright 2015 The LUCI Authors. All rights reserved. # Use of this source code is governed under the Apache License, Version 2.0 # that can be found in the LICENSE file. """Starts a local bot to connect to a local server.""" from __future__ import print_function import argparse import glob i...
from utils import * import torch import torch.nn as nn import torch.nn.functional as F from torch.nn.utils import weight_norm as wn import numpy as np class nin(nn.Module): def __init__(self, dim_in, dim_out): super(nin, self).__init__() self.lin_a = wn(nn.Linear(dim_in, dim_out)) self.di...
# Copyright 2019-2021 ETH Zurich and the DaCe authors. All rights reserved. # Tests reduce expansions for FPGA import dace import numpy as np from dace.fpga_testing import fpga_test def create_reduce_sdfg(wcr_str, reduction_axis, sdfg_name, input_data, output_data, dtype): ''' Build an SDFG that perform the ...
#!/usr/bin/env python # -*- coding: utf-8 -*- import unittest from datetime import datetime from migrate import * class SqliteDatabaseMock(object): def __init__(self): self.database = {} self.committed = False def insert_into_table(self, table_name, record): if table_name not in self...
""" @author: Shimin """ import subprocess import sys from shutil import copyfile from subprocess import Popen, PIPE, STDOUT import time import os import chronqc import datetime import argparse import logging import time import re import os.path as op import traceback try: from . import utils ...
import glob import math import os import random import torch from PIL import Image from torch.utils.data import Dataset from torchvision import transforms from src.data.transforms import StatefulRandomHorizontalFlip def round(x): return math.floor(x + 0.5) class GRIDDataset(Dataset): def __init__(self, pa...
#!/usr/bin/env python from ansible_collections.terryhowe.hashivault.plugins.module_utils.hashivault import hashivault_argspec from ansible_collections.terryhowe.hashivault.plugins.module_utils.hashivault import hashivault_auth_client from ansible_collections.terryhowe.hashivault.plugins.module_utils.hashivault import h...
#!/usr/bin/env python3 import requests from requests.packages.urllib3.exceptions import InsecureRequestWarning import json from py.src.logger import ( log, log_exception, ) from py.src.settings import ( DATABASE, ) from py.src.error import ( CookieInvalidException, MatchQueryException, ) from py.s...
from numpy import tanh, sqrt, exp, sinh, sin, log, arcsin from numpy.random import RandomState from .audio import sinepings, tlike, trange, sine from .noise import pink_noise, white_noise class Percussion: def play(self, velocity): pass class SplashCymbal(Percussion): def __init__(self, base_freq=65...
# the goal of this file is to run all of the 4 independent processes # that are used to control the vision system components as well as update the variables needed for the FSM # global variable updates allow these processes to constantly update each other # 1. objectCenter - finds/localizes the object # 2. pannin...
import logging from itertools import combinations from math import sqrt import numpy as np from PIL import Image, ImageColor from pdst import analysis, parsing log = logging.getLogger(__name__) def fitToBounds(original_size, target_bounds): log.debug(f"Calculating image resize from {original_size}...
from pathlib import Path import platform import PySimpleGUIQt as sg import tendon.py.edit_settings as es from tendon.py.txt2json.convert_text_to_json import convert_text_to_json as t2j #pylint: disable=no-member def disable_from_and_to(window: sg.Window, switch: bool, values): window['range_from'].update(disabled=...
# Copyright 2018 The TensorFlow Probability Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law o...
# !/usr/bin/env python """This module represents an optimized variant of the module genetic2.py. It uses the multiprocessing module instead of the threading module to take advantage of systems with multiple cores. """ import random import multiprocessing import benchbuild.experiments.sequences.polly_stats as polly_st...
''' This benchmark performs convergence tests on a single emulator with variable numbers of input parameters. The example is based on the Rosenbrock function (see https://www.sfu.ca/~ssurjano/rosen.html). This function can be defined in an artibrary number of dimensions, so it provides a useful test for how emulators b...
from numba import njit, prange from .sparse import retain_topk, _map import scipy.sparse as sp import numpy as np import tqdm def normalize_graph(X): col_nnz = np.sqrt(1/np.ravel(X.sum(axis=0))) row_nnz = np.sqrt(1/np.ravel(X.sum(axis=1))) c_diags = sp.diags(col_nnz) r_diags = sp.diags(row_nnz) ma...
from typing import Dict, Union import judo from judo import Backend, tensor from fragile.core.base_classes import BaseEnvironment from fragile.core.states import StatesEnv, StatesModel from fragile.core.typing import StateDict, Tensor class Environment(BaseEnvironment): """ The Environment is in charge of s...
#!/usr/bin/env python3 import numpy as np from glob import glob import pandas as pd import os.path from tqdm import tqdm, trange import sys from collections import defaultdict from scipy.spatial.transform import Rotation from .common import make_process_fun, get_data_length, natural_keys # project v onto u def proj...
import os import argparse import pickle import torch import numpy as np from src.models.api import EvaluationModel, NegSampleGenerator from torch import nn from src.models.ensemble.model_selector import ModelSelector, generate_lookup from src.models.rotate import RotatE from src.models.conve import ConveEvaluationModel...
import torch import torch.nn.functional as F import diff_operators import modules, utils import math import numpy as np def initialize_hji_MultiVehicleCollisionNE(dataset, minWith): # Initialize the loss function for the multi-vehicle collision avoidance problem # The dynamics parameters velocity = data...
import os import yaml import pandas as pd import datetime import json import mlrun from typing import Dict import copy import random import mlrun.feature_store as fstore # Data generator from metrics_gen.deployment_generator import deployment_generator from metrics_gen.static_data_generator import Static_data_generato...
# -*- coding: utf8 -*- from Bio import SeqIO from urllib.request import Request, urlopen from retry import retry from typing import List import sqlite3 import argparse import sqlite3 import csv import re import xml.etree.ElementTree as ET import datetime """ Get the accessions from the DDBJ 16S.fasta header and conver...
# Imports, sorted alphabetically. # Python packages import os import struct # Third-party packages import pyglet from pyglet.gl import * # Modules from this project import globals as G __all__ = ( 'load_image', 'image_sprite', 'hidden_image_sprite', 'vec', 'FastRandom', 'init_resources', 'init_font', 'get_...
#!/usr/bin/env python3 import sys from collections import defaultdict from gazateers import currency_dict, trading_dict, common_dict ratio = 0.6 top_offset = 0.1 # small ###cutoff = 4 ###do_labels = False ###axis_offset = -2.5 ###cutoff = 12 ###do_labels = True ###axis_offset = -2.7 ###col_label_offset = -0.05 ###...
# -*- coding: utf-8 -*- # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the #...
import tkinter as tk import random import os dirname = os.path.dirname(__file__) # fenetre window = tk.Tk() window.title("Chifoumi") window.geometry("400x400") window.config(bg="#7FD7DF") window.iconbitmap(os.path.join(dirname, 'assets/ico.ico')) window.resizable(width=False, height=False) # imag...
import os, re, shutil, json def json_to_params(path): # takes the path to a properly formatted .json file and returns a list of parameters for the read() function with open(path, 'r') as f: json_params = json.load(f) # json_params can be a list of dicts, a list of lists, or a dict of lists but will have to b...
# Copyright 2021 Google LLC # # 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, ...
# -*- coding: utf-8 - # # This file is part of gunicorn released under the MIT license. # See the NOTICE for more information. import importlib.machinery import os import sys import traceback import types from gunicorn import util from gunicorn.arbiter import Arbiter from gunicorn.config import Config, get_default_con...
# -*- coding: utf-8 -*- # # Copyright (C) 2006-2009 Edgewall Software # All rights reserved. # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. The terms # are also available at http://genshi.edgewall.org/wiki/License. # # This software consist...
import copy from abc import ABC, abstractmethod from random import choice as random_choice, sample from wordle import Game, Guess, WordGuessCharPositionalResult, WORDS from wordleTools import WordleTools, KNOWLEDGE class Solver(ABC): def __init__(self, game): self.game = game @abstractmethod def ...
# Ignoring some linting rules in tests # pylint: disable=redefined-outer-name # pylint: disable=missing-docstring import pytest import numpy as np from bingo.chromosomes.multiple_values import SinglePointCrossover, \ SinglePointMutation, MultipleValueChromosomeGenerator from bingo.evolutionary_optimizers.island i...
"""benchmarking through py.test""" import py from py.__.test.item import Item from py.__.test.terminal.terminal import TerminalSession from math import ceil as _ceil, floor as _floor, log10 import timeit from inspect import getsource # from IPython.Magic.magic_timeit units = ["s", "ms", "us", "ns"] scaling = [1, 1...
#!/usr/bin/env python3 # Copyright 2018 Tilde # License: Apache 2.0 import sys import argparse import os import re import glob script_name = sys.argv[0] parser = argparse.ArgumentParser(description="Removes models from past training iterations of " "RNNLM. Can use eithe...
import time import sys from math import pi, degrees from .world import World from .constants import RPS_PER_PERCENTAGE, WHEEL_DIAMETER, PIXELS_PER_METER from typing import Callable class RobotOutOfBounds(Exception): pass class Timeout(Exception): pass class FollowerBot: """ FollowerBot class ...
#!/usr/bin/env python3 """ Copyright (c) 2019 Intel Corporation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable ...