text
stringlengths
3.07k
12.6k
from collections import OrderedDict from dataclasses import dataclass, field import numpy as np import pandas as pd import logging import inspect import torch import math log = logging.getLogger("nprophet.config") def from_kwargs(cls, kwargs): return cls(**{k: v for k, v in kwargs.items() if k in inspect.signatu...
''' From MuGo:https://github.com/yhyu13/MuGo ''' from collections import defaultdict import functools import itertools import operator import random import re import time import utils.gtp as gtp import utils.go as go KGS_COLUMNS = 'ABCDEFGHJKLMNOPQRST' SGF_COLUMNS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVW...
# Copyright (C) 2018-2022 Intel Corporation # SPDX-License-Identifier: Apache-2.0 import os import re import argparse from pathlib import Path import shutil import logging INLINE_LINKS_PATTERN = r'!?\[.*?\]\(([\w\/\-\.]+\.md)\)' REFERENCE_LINKS_PATTERN = r'\[.+\]\:\s*?([\w\/\-\.]+\.md)' INLINE_IMAGES_PATTERN = r'!?\[...
import getpass import subprocess from enum import Enum from typing import List, Dict from helpers import ROOT, Settings, nix_build, run from storage import setup_hugepages, StorageKind class NetworkKind(Enum): NATIVE = 1 CLIENT_NATIVE = 2 TAP = 3 DPDK = 4 DPDK_TAP = 5 def ip(args: List[str]) -> ...
import datetime as dt import json import os import time from os import listdir from os.path import isfile, join from pathlib import Path from . import constants as c TEMPFOLDERNAME = "temp" VIDEOFOLDERNAME = "videos" URLSTEXTFILENAME = "video-serier.txt" def save_to_video_file(video_file, key, element): data = {...
""" Support for OpenTherm Gateway binary sensors. For more details about this platform, please refer to the documentation at http://home-assistant.io/components/binary_sensor.opentherm_gw/ """ import logging from homeassistant.components.binary_sensor import ( BinarySensorDevice, ENTITY_ID_FORMAT) from homeassist...
"""Miscellaneous helpers.""" import collections import fnmatch import glob import itertools import os import random import weakref from typing import Dict, List, Generator def filter_by_type(sequence, type_) -> Generator[object, None, None]: """Filter sequence by type.""" return ( ele for ele in seque...
from collections import namedtuple from unittest.mock import MagicMock, patch import pytest from pytest_httpx import HTTPXMock from gtr.recommender import Preferences class TopArtists: Artist = namedtuple("Artist", "name") def __init__(self, artist_names): self.items = [self.Artist(name=name) for n...
""" Tests for Factor terms. """ from numpy import ( array, ones, ) from zipline.errors import UnknownRankMethod from zipline.modelling.factor import TestingFactor from zipline.utils.test_utils import check_arrays from .base import BaseFFCTestCase class F(TestingFactor): inputs = () window_length = 0...
from copy import deepcopy import numpy as np import matplotlib.pyplot as plt from matplotlib.colors import Normalize from .training import Training from .scoring import Scoring # import warnings # warnings.filterwarnings('error') class BenchmarkProperties: """ Properties for Benchmark class. """ @property ...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ A module to perform various normalizing functions for participant validation data. """ # Python imports import logging # Third party imports # Project imports from constants.validation.participants import normalizers as consts LOGGER = logging.getLogger(__name__) d...
import random import types from typing import Union from World.Character.Constants.CharacterRace import CharacterRace from World.Character.Constants.CharacterClass import CharacterClass from World.Character.Constants.CharacterBaseStats import BASE_STATS, BASE_STATS_MOD from World.Object.Unit.Constants.UnitFlags import...
# Copyright 2017 The Bazel 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 applicable la...
import argparse import torch from torch import nn from torch import optim from torch.autograd import Variable from torchvision import datasets, transforms, models from torchvision.datasets import ImageFolder import torch.nn.functional as F from PIL import Image from collections import OrderedDict import time impor...
# This file is part of the History Store (histore). # # Copyright (C) 2018-2021 New York University. # # The History Store (histore) is released under the Revised BSD License. See # file LICENSE for full license details. """Class for sorting input documents in main-memory or using secondary storage. The functions in t...
# -*- coding: utf-8 -*- """Click commands.""" import os from glob import glob from subprocess import call import click from flask import current_app from flask.cli import with_appcontext from werkzeug.exceptions import MethodNotAllowed, NotFound from sqlalchemy import text HERE = os.path.abspath(os.path.dirname(__fil...
import base64 import os import re import json import tempfile from decimal import Decimal from django.db import transaction from django.db.models import Q, Count from django.http import HttpResponse, JsonResponse from django.utils.decorators import method_decorator from django.views.decorators.csrf import csrf_exempt ...
# Copyright (c) 2014 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 # # Unless required by applicable law or agreed to in writ...
import time import wallet import eosapi import initeos producer = eosapi.Producer() def init(): if not eosapi.get_account('currency'): with producer: r = eosapi.create_account('inita', 'currency', initeos.key1, initeos.key2) assert r if not eosapi.get_account('exchange'): ...
# -*- coding: utf-8 -*- # Copyright (c) 2018, Libermatic and Contributors # See license.txt from __future__ import unicode_literals import frappe import unittest from gwi_customization.microfinance.doctype.microfinance_loanee.test_microfinance_loanee import ( # noqa create_test_loanee, remove_test_loanee, ) ...
import os from django.shortcuts import render from django.shortcuts import render, redirect, get_object_or_404, render_to_response from django.template import RequestContext from django.core.urlresolvers import reverse from django.contrib.auth.decorators import login_required, user_passes_test from django.contrib impo...
''' Finite State Machine algorithm used to assess score of Python found in statements of the form 'Python is ___'. The 2 possible scores are 'positive' and 'negative'. Reference: http://www.python-course.eu/finite_state_machine.php +--------------+-------------+--------------+ | From State | Input | To State...
import math import torch import torch.nn as nn class IBN(nn.Module): def __init__(self, planes): super(IBN, self).__init__() half1 = int(planes/2) self.half = half1 half2 = planes - half1 self.IN = nn.InstanceNorm2d(half1, affine=True) self.BN = nn.BatchNorm2d(half2...
"""Functional tests for the Ruleset features such as: - Configuring a report - Interpolating tags correctly - Adjust the message (headers/body) etc. """ from __future__ import absolute_import import os import tests.util import unittest from tests.util import GTUBE PRE_CONFIG = """ report _REPORT_ """ # Define...
#!/usr/bin/python # # Copyright (c) 2019 <NAME>, (@zikalino) # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', ...
#!/usr/bin/env python # -*- coding: utf-8 -*- import telegram from telegram.ext import Updater, CommandHandler, CallbackQueryHandler import threading import traceback import atexit import datetime import random import string from . import telegram_config class TelegramBot: def __init__(self, token, chat_id, se...
import re import inspect import logging from ..utils.helper import Helper, HelperMode, Item log = logging.getLogger(__name__) async def check_filter(filter_, args): """ Helper for executing filter :param filter_: :param args: :param kwargs: :return: """ if not callable(filter_): ...
# -*- coding: utf-8 -*- from node.compat import STR_TYPE from node.compat import UNICODE_TYPE from node.compat import func_name from node.compat import iteritems from node.interfaces import IAttributeAccess from node.interfaces import INode from zope.interface import implementer from zope.interface.common.mapping impor...
import numpy as np import pandas as pd import math from datetime import datetime import sys from PIL import Image, ImageOps import matplotlib.pyplot as plt from numpy import asarray from src.data.constants import path from src.data.variables import hough_thresholds def find_edge_pixels(gs_array: np.ndarray, phi: int...
#!/usr/bin/env python3 # # Copyright (c) 2015 <NAME> # # 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, modify, mer...
"""This module contains the functions which deal with combined logs.""" import re from heybrochecklog.logfile import LogFile def split_combined(log): """Split a combined log into an array of logs. If there is a single log, return a list with one log inside it. Not relevant for XLD. """ logs = [] ...
# 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 u...
# -*- coding: utf-8 -*- """ Clearing Assignments """ from mathics.builtin.base import ( Builtin, PostfixOperator, ) from mathics.core.expression import Expression from mathics.core.symbols import ( Atom, Symbol, system_symbols, ) from mathics.core.systemsymbols import ( Symbol_Context, Sy...
from flask import Flask from .view_classes import ( BasicView, TrailingSlashView, InheritedTrailingSlashView, OverrideInheritedTrailingSlashView, EnabledHasTrailingSlashView, EnabledNoTrailingSlashView, IndexView ) from nose.tools import eq_ app = Flask('trailing_slash') BasicView.register(...
# -*- coding: utf-8 -*- # __author__ = xiaobao # __date__ = 2019/10/18 19:04:37 # desc: desc # 给定一个包括 n 个整数的数组 nums 和 一个目标值 target。找出 nums 中的三个整数,使得它们的和与 target 最接近。返回这三个数的和。假定每组输入只存在唯一答案。 # 例如,给定数组 nums = [-1,2,1,-4], 和 target = 1. # 与 target 最接近的三个数的和为 2. (-1 + 2 + 1 = 2). # 来源:力扣(LeetCode) # 链接:https://leetcod...
import itertools from gym_mapf.envs import map_name_to_files from gym_mapf.envs.grid import MapfGrid from gym_mapf.envs.mapf_env import MapfEnv def parse_scen_file(scen_file, n_agents): """Return the agent start locations and the goal locations. Args: scen_file (str): path to the scenario...
""" ErrorClass Plugins ------------------ ErrorClass plugins provide an easy way to add support for custom handling of particular classes of exceptions. An ErrorClass plugin defines one or more ErrorClasses and how each is handled and reported on. Each error class is stored in a different attribute on the result, and...
#!/usr/bin/env python """WIP wandb grpc test client.""" from __future__ import print_function import json import logging import os import time import grpc import six from wandb.proto import wandb_internal_pb2 # type: ignore from wandb.proto import wandb_server_pb2 # type: ignore from wandb.proto import wandb_serve...
#### # # Define commonly used classes # import json import logging from datetime import datetime import i2_slack_modules from i2_slack_modules.common import my_own_function_name from slack import WebClient class BotResponse: """ A class used to represent a Slack Response Attributes ---------- te...
#!/usr/bin/env python3 # SPDX-FileCopyrightText: 2021 <NAME> <<EMAIL>> # SPDX-FileCopyrightText: 2019 <NAME> <<EMAIL>> # # SPDX-License-Identifier: MIT """Script to fix weights and flags in the iA Writer Quattro S font files and rename the fonts according with the license requirement. This is derived from https://gith...
"""File with samplers that create points with some kind of ordered structure. """ import torch import warnings from .sampler_base import PointSampler from ..domains.domain1D import Interval from .random_samplers import RandomUniformSampler from ..spaces import Points class GridSampler(PointSampler): """Will samp...
''' Function: 扫雷小游戏 Author: Charles 微信公众号: Charles的皮卡丘 ''' import os import time import pygame from ...utils import QuitGame from ..base import PygameBaseGame from .modules import Mine, TextBoard, MinesweeperMap, EmojiButton '''配置类''' class Config(): # 根目录 rootdir = os.path.split(os.path.abspath(_...
#!/usr/bin/env python """ Selenium-related utility functions for Robot Framework, especially table-related functions. - *Module*: rf_Table_Helpers - *Platform*: Unix, Windows - *Author*: [mailto:<EMAIL>?subject=About rf_Table_Helpers.py|<NAME>] """ __version__ = '0.4.0' import os import requests from robot.librari...
import os import numpy as np import openpyxl as pyxl import sys from building import * from timeutils import * from event import Event from yattag import Doc,indent class TimeSlot: def __init__(self,event): self.events = [event] def add(self,event): self.events.append(event) def sort(self...
import pygame, random, time, sys pygame.init() SCREEN_WIDTH = 1080 SCREEN_HEIGHT = 720 screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT)) pygame.display.set_caption("이미지 불러오기") clock = pygame.time.Clock() screen.fill((255,255,255)) class Predetor(pygame.sprite.Sprite): def __init...
"""Commands for managing and querying issues.""" from github import GithubException from cligh.utils import text_from_editor, get_working_repo, die # Helper functions: def get_working_issue(client, args): """Get an object corresponding to the issue that the user wishes to manipulate. Issues are identified by...
from math import inf from pprint import pprint import sys import types from typing import List, Type, Union def find_max_index(arr: List[int], tracking_index: int) -> int: if tracking_index == 0: return 0 maybe_max_index = find_max_index(arr, tracking_index - 1) if arr[tracking_index] < arr[maybe_max_index]...
# -*- coding: utf-8 -*- """Replication Link Model.""" # system module import datetime from typing import Any, Dict, List, Optional, TYPE_CHECKING, Union # community module from flask import current_app, request import sqlalchemy as sa from sqlalchemy import orm # project module from .base import GUID, MetaDataBase,...
#!/usr/bin/env python ''' This script simulates monoenergetic 6 MeV protons on beryllium target to generate epithermal neutrons. The goal is to study neutron kinematics and proton-beryllium interactions. <NAME>, Feb 2021. <EMAIL> ''' # python3 style print from __future__ import print_function # Physical Units from G...
# -*- coding: utf8 -*- # # Copyright (c) 2016 Linux Documentation Project from __future__ import absolute_import, division, print_function from __future__ import unicode_literals import os import errno import random import unittest from argparse import Namespace from io import StringIO from tldptesttools import Test...
#!/usr/bin/env """This module exists to run useful auxiliary neuston tasks""" import argparse import os import csv import numpy as np from neuston_data import NeustonDataset from torch.utils.data import DataLoader from torchvision import transforms def calc_img_norm(args): tforms=transforms.Compose([transforms....
"""jello - query JSON at the command line with python syntax""" import os import sys import signal import shutil import textwrap from textwrap import TextWrapper import jello from jello.lib import opts, load_json, pyquery, Schema, Json def ctrlc(signum, frame): """exit with error on SIGINT""" sys.exit(1) d...
# Copyright 2020 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, s...
import logging from typing import Dict, List, Optional, Tuple import numpy from injector import Binder, Module, inject, singleton from joblib import Parallel, delayed, parallel_backend from prometheus_client import Counter from prometheus_client.metrics import Gauge from sqlalchemy import and_ from rep0st import util...
# coding: utf-8 from __future__ import absolute_import from __future__ import division from __future__ import print_function import argparse import numpy as np import torch from torch.autograd import Variable, grad from torch.nn.init import xavier_normal from torchvision import datasets, transforms import torchvisio...
import numpy as np import matplotlib as mpl mpl.use('Agg') import matplotlib.pyplot as plt import seaborn as sns import pandas as pd import glob, os.path, os, pickle #global params fig_dims = (12,8) axis_label = 12 legend_label = 12 axis_scale = 2.0 default_abc9_script="&scorr;&sweep;&dc2;&dch -f;&if -W 300 -K 6 -v;&...
import os from datetime import datetime import numpy from amulet import Block, SelectionBox from typing import TYPE_CHECKING, Tuple, Dict import wx from amulet.api.partial_3d_array.base_partial_3d_array import BasePartial3DArray from amulet_map_editor.api.wx.ui.base_select import EVT_PICK from amulet_map_editor.api.w...
# Copyright 2020 The Johns Hopkins University Applied Physics Laboratory LLC # All rights reserved. # Distributed under the terms of the MIT License. import click import sys import os import numpy as np from shapely.geometry.polygon import Polygon from shapely.geometry.multipolygon import MultiPolygon from geopandas ...
#!/usr/bin/env python import csv import math import json import os import requests import sys import time import twitter from afinn import Afinn from collections import Counter from datetime import datetime, timedelta from io import StringIO from pprint import pprint from statistics import mean, median from urllib.pa...
import argparse import os import numpy as np import pandas as pd import atom3d.util.formats as dt import atom3d.splits.splits as splits class MoleculesDataset(): """Internal data set, including coordinates.""" def __init__(self, csv_file, sdf_file, name='molecules'): """Initializes a data set from ...
import json import logging import os # Use Django settings for BASKET_URL if available, but fall back to # env var or default if not. This lets us test without all the setup # that we'd otherwise need for Django. try: from django.conf import settings except (ImportError, AttributeError): # Django not installed...
import discord from discord.ext import commands import json import functools, inspect import random class Memes(commands.Cog): """ 'Memes were a mistake.' - <NAME> Handles simple user-defined commands in the form of command -> response. """ def __init__(self, bot): self.chiaki...
import hashlib import importlib import pytest from types import ModuleType from unittest.mock import Mock, PropertyMock from rfidsecuritysvc.db import dbms class SQLStringNotFound(Exception): pass class MockDb(object): def __init__(self): # Create a mock for the overall database connection ...
import datetime import pytest from dateutil.tz import tzutc, tzoffset import trafaret as t from trafaret import DataError from trafaret.contrib.rfc_3339 import DateTime, Date class TestDateTime: def test_datetime(self): check = DateTime() assert check('2017-09-01 23:59') == datetime.datetime(2017...
from . import base import numpy as np from hdmf.build import GroupBuilder, DatasetBuilder, ReferenceBuilder from pynwb import TimeSeries from pynwb.core import DynamicTable, VectorData from pynwb.misc import Units, DecompositionSeries class TestUnitsIO(base.TestDataInterfaceIO): def setUpContainer(self): ...
import math from props import getNode from auracore import wgs84 import comms.events d2r = math.pi / 180.0 r2d = 180.0 / math.pi sqrt_of_2 = math.sqrt(2.0) gravity = 9.81 # m/sec^2 circle_node = getNode("/task/circle", True) pos_node = getNode("/position", True) vel_node = getNode("/velocity", True...
from discord import Embed, FFmpegPCMAudio, VoiceChannel from discord.ext.commands import Context from discord.ext import commands from discord.utils import get from asyncio import run_coroutine_threadsafe from yt_dlp import YoutubeDL from typing import Optional from core.cls import Bot from re import findall class M...
import codecs import collections import os import numpy as np import tensorflow as tf from bert import tokenization from config import TextConfig class DataUtils(object): def __init__(self, datafile, outdatafile=None): self.datapath = datafile def read_data(self, ): with codecs.open(self.dat...
class DatasetName: affectnet = 'affectnet' rafdb = 'rafdb' fer2013 = 'fer2013' class ExpressionCodesRafdb: Surprise = 1 Fear = 2 Disgust = 3 Happiness = 4 Sadness = 5 Anger = 6 Neutral = 7 class ExpressionCodesAffectnet: neutral = 0 happy = 1 sad = 2 surprise =...
# Training import shutil import os import time from itertools import chain from pprint import pprint from copy import deepcopy import torch import torch.nn as nn from torch.utils.tensorboard import SummaryWriter import cma from datasets.dataset_utils import get_dataset from models.model_utils import get_model import ...
from kalc.interactive import * from kalc.model.search import Balance_pods_and_drain_node from kalc.model.kinds.Deployment import Deployment from kalc.misc.script_generator import generate_compat_header from collections import defaultdict from poodle.schedule import SchedulingError from itertools import combinations, pr...
from gym.wrappers import FrameStack,AtariPreprocessing,Monitor import matplotlib.pyplot as plt from gym.spaces import Box import numpy as np import gym import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torch.distributions import Categorical #Hyperparameters learning_r...
import glob import chainercv.utils import numpy import PIL.Image from PyQt5 import QtWidgets from PyQt5 import QtGui from chainer_wing.subwindows.train_config import TrainParamServer from chainer_wing.subwindows.data_config import AbstractDataDialog from chainer_wing.subwindows.data_config import DataCheckBox from ch...
# Copyright 2015, Pinterest, 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 writ...
""" Originally by https://worksheets.codalab.org/worksheets/0x8fc01c7fc2b742fdb29c05669f0ad7d2 """ import json import os, sys import re import random import numpy as np from random import sample from tqdm import tqdm from collections import Counter from critic.edit_dist_utils import get_all_edit_dist_one, sample_rando...
# # Copyright (c) 2020-2021 Arm Limited and Contributors. All rights reserved. # SPDX-License-Identifier: Apache-2.0 # """Defines a generic Win32 component.""" import logging from abc import ABC, abstractmethod from typing import List, Any, Generator, Optional, NamedTuple, cast import pythoncom import win32com.client ...
import numpy as np import matplotlib.pyplot as plt import itertools def plot_confusion_matrix(cm, classes, title, normalize=False, cmap=plt.cm.Blues, figsize=None): if normalize: cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis] # print("Normalized confusion matrix") # print(cm) if ...
import pygame import SETTINGS import ITEMS import TEXT import random title = TEXT.Text(0,0, "None :-)", SETTINGS.BLACK, "DUGAFONT.ttf", 60) author = TEXT.Text(0,0, "None :-)", SETTINGS.BLACK, "DUGAFONT.ttf", 40) hurt_intensity = 128 dead_intensity = 0 heal_intensity = 85 armor_intensity = 85 fade_value = 0 title_time...
""" @file analyzeData.py @author <NAME> @author <NAME> @date 2011-09-30 @version $Id$ SUMO, Simulation of Urban MObility; see http://sumo.dlr.de/ Copyright (C) 2008-2017 DLR (http://www.dlr.de/) and contributors This file is part of SUMO. SUMO is free software; you can redistribute it and/or modify it under ...
import numpy as np from gym import utils from gym.envs.mujoco import mujoco_env import tensorflow as tf class ReacherEnv(mujoco_env.MujocoEnv, utils.EzPickle): def __init__(self): utils.EzPickle.__init__(self) mujoco_env.MujocoEnv.__init__(self, 'reacher.xml', 2) # def _step(self, a): # ...
import torch from torch import nn import torchvision import urllib.request from module.data_module import preprocessor import os from collections import Counter from torchvision.transforms import Compose, ToTensor, Resize, Normalize import torch.optim as optim from PIL import Image from torch.autograd import Variable i...
# Copyright 2020-2022 OpenDR European Project # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agree...
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2015-2018 CERN. # # Invenio is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. """Minimal Flask application for development. SPHINX-START Install the Invenio defa...
#! /usr/bin/env python """ This module provides an interface for reading and writing to the i2c bus via the smbus module It creates an abstraction that supports reading/writing numeric types and arrays of numeric types. """ from __future__ import print_function """ -----------------------------------------------------...
import datetime import functools from collections import namedtuple from base64 import urlsafe_b64encode, urlsafe_b64decode from validr import T, validator, SchemaError, Invalid, Compiler, builtin_validators from django.core.validators import URLValidator from django.core.exceptions import ValidationError from django....
# MTUOC_tokenizer_cat # Copyright (C) 2020 <NAME> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. #...
# -*- coding: utf-8 -*- # Copyright (c) 2017, <NAME> and <NAME> and contributors # For license information, please see license.txt from __future__ import unicode_literals import frappe from frappe.utils import flt, getdate, get_url from frappe import _ from frappe.model.document import Document from rms.controllers....
# -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division from __future__ import print_function import sys import pyglet from pyglet.window import key import numpy as np import argparse from oculoenv import Environment, RedCursorEnvironment from oculoenv import PointToTargetConte...
from mdp_dp_rl.algorithms.dp.dp_analytic import DPAnalytic from docs.notebooks.utils import print_policy_data, print_value_function, print_q_value_function from stochastic_service_composition.composition import composition_mdp from stochastic_service_composition.services import Service, build_service_from_transitions ...
from db.elastic import Elastic import pandas as pd import os from random import shuffle, seed, choice import elasticsearch from datetime import datetime, timedelta, date from db.postgresql import PostgreSQL from psycopg2.extensions import AsIs from methods.dates import daterange from classes import Location import re i...
# -*- coding: UTF-8 -*- # 离散事件模拟 from random import randint from PrioQueueByHeap import PrioQueue from SQueue import SQueue class Simulation(): def __init__(self, duration): self._eventq = PrioQueue() self._time = 0 #记录当前时间 self._duration = duration #记录模拟总时间 def run(self): while not self._eventq.is_emp...
import sys import json import logging import re import random import os from datetime import timedelta from config import * from utils import * from GridPatternBuilder import GridPatternBuilder, build_habit_groups from ConflictDetector import ConflictDetector from ContextAccessor import ContextAccessor # Device Typ...
""" The ``stt-preprocess.tools.text`` module provides functions to do common text preprocessing steps """ import re from itertools import groupby import os import json import shutil import sys from pathlib import Path def remove_punctuation(input_str): """ Removes punctuations from input string :param inp...
#Import necessary package import requests import re from bs4 import BeautifulSoup import pandas as pd import numpy as np import datetime as dt import configparser import os #Configure parameter config = configparser.ConfigParser() config.read(os.path.join(os.path.dirname(__file__), 'config.ini')) mall = config['genera...
""" ====================== ds.datalake.filesystem ====================== See https://docs.pyfilesystem.org/en/latest/implementers.html# """ from datetime import datetime, timedelta import logging from typing import Text, Optional, Collection, Dict, List, Any, BinaryIO, Mapping from fs.base import FS from fs.info impo...
# -*- coding: utf-8 -*- def create_genus_from_mushrooms(df_mushrooms): # Displaying info about Mushrooms DataFrame print('\nDataFrame "mushrooms" info:') print('\tshape : ', df_mushrooms.shape) print('\tcolumns: ', df_mushrooms.columns) # Keeping only genus from Mushrooms DataFrame to build genus Da...
import turbo_transformers.turbo_transformers_cxx as cxx import torch from .return_type import convert_returns_as_type, ReturnType from .utils import try_convert, convert2tt_tensor, to_param_dict_convert_tt, to_param_dict, create_empty_if_none, AnyTensor from .modeling_bert import BertAttention, BertEmbeddings, BertEnco...
# mbed SDK # SPDX-License-Identifier: Apache-2.0 # Copyright (c) 2011-2013 ARM 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 # # U...
import torch import numpy as np import argparse import h5py from tqdm import tqdm import os import sys import shutil import json import torchvision.transforms as transforms from utils import cv2_greyscale, str2bool, save_h5 def get_transforms(color): MEAN_IMAGE = 0.443728476019 STD_IMAGE = 0.20197947209 ...
# -*- coding: utf-8 -*- # Autor: <NAME> # Datum: Fri Sep 24 14:41:58 2021 # Python 3.8.8 # Ubuntu 20.04.1 """ Replication project for Wojatzki and Zesch (2016). Run from command line to process and classify data. First, the data will be split into a training and a test set (10%), then using 10-fold cros-validation, a ...