content
stringlengths
5
1.05M
# Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. { 'variables': { 'use_system_sqlite%': 0, }, 'target_defaults': { 'defines': [ 'SQLITE_CORE', 'SQLITE_ENABLE_BROKEN_FTS3', ...
n, m = [int(x) for x in input().split()] while n: ans = 1 for x in range(n, n+m): ans *= x for x in range(2, m+1): ans //= x print(ans) n, m = [int(x) for x in input().split()]
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = 'Jason' import re def injection(input_path, weibo_dir_path): ret = [] with open(input_path, 'r') as fr: for line in fr: if line.strip() == '': continue temp_list = re.split(r'\s', line.strip()) ...
# Copyright 2015 Fortinet Inc. # 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...
# 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, ...
import unittest from matrox import Matrix, DimensionError, fill_matrix from matrox.linalg import * class TestMatrixFactorizations(unittest.TestCase): def test_permute_matrix(self): matrix = Matrix([[1, 1, 1], [1, 1, 1], [1, 1, 1]]) permute = permute_matrix(matrix) self.assertEqual(repr(pe...
#! /usr/bin/python3 import boto3 from vectorize import vectorize import io import numpy as np from copy import deepcopy import random from queue import Queue from threading import Thread import time s3 = boto3.client('s3') image_paths = Queue() np_arrs = Queue(maxsize=100) unsuccessful = [] with open('images.txt', ...
import os import numpy as np import tensorflow as tf from utils import save_images, make_dirs from utils import data_loader class Experiments(object): def __init__(self, config, model): self.config = config self.model = model _, self.testloader = data_loader(config) # ...
""" Premium Question """ from bisect import bisect_left from collections import defaultdict import sys __author__ = 'Daniel' class WordDistance: # # @param {string[]} words def __init__(self, words): """ initialize your data structure here. :type words: list[str] """ ...
import tkinter as tk from typing import TYPE_CHECKING, Optional from core.gui.frames.base import DetailsFrame, InfoFrameBase from core.gui.utils import bandwidth_text from core.gui.wrappers import Interface if TYPE_CHECKING: from core.gui.app import Application from core.gui.graph.edges import CanvasEdge ...
from abc import ABC, abstractmethod class BaseExplainer(ABC): def __init__(self, model_to_explain, graphs, features, task): self.model_to_explain = model_to_explain self.graphs = graphs self.features = features self.type = task @abstractmethod def prepare(self, args): ...
# This script contains all of the code necessary for galcv. # We want a function that returns the cosmic variance values for input apparent magnitudes import numpy as np import pandas as pd import os from scipy import integrate from scipy import interpolate # A dictionary of the parameters for which I have the exact...
#self-hosting guide: https://gist.github.com/emxsys/a507f3cad928e66f6410e7ac28e2990f #updated to use scratchcloud from scratchcloud import CloudClient, CloudChange import scEncoder import os, time, json from mcstatus import JavaServer from dotenv import load_dotenv from random import randint #get .env passcodes load_...
import re from openstackinabox.services.cinder.v1 import base from openstackinabox.models.cinder import model from openstackinabox.services.cinder.v1 import volumes class CinderV1Service(base.CinderV1ServiceBase): def __init__(self, keystone_service): super(CinderV1Service, self).__init__(keystone_servi...
from enum import Enum, auto """ Enum of Task status Represents all possible statuses of task """ class TaskStatus(Enum): COMPLETED = auto() UNCOMPLETED = auto() PLANNED = auto() RUNNING = auto() FINISHED = auto() def __json__(self): """ JSON serialization for TaskStatus ...
import numpy as np import random from segmentation.utils import visualize import importlib importlib.reload(visualize) def test_visualize_z_scores(): # Create random Z score z = np.random.uniform(low=-5, high=5, size=(26, 26)) # Assign random phenotype titles pheno_titles = [chr(i) for i in range(ord(...
from django.contrib.auth.mixins import LoginRequiredMixin from django.views.generic import DetailView from django.views.generic.list import ListView from django.views.generic.edit import CreateView, DeleteView, UpdateView, \ FormMixin, FormView from django.urls import reverse_lazy from .models import Machine, Devi...
name = 'bah' version = '2.1' authors = ["joe.bloggs"] uuid = "3c027ce6593244af947e305fc48eec96" description = "bah humbug" private_build_requires = ["build_util"] variants = [ ["foo-1.0"], ["foo-1.1"]] hashed_variants = True build_command = 'python {root}/build.py {install}'
""" Day 08 of the 2021 Advent of Code https://adventofcode.com/2021/day/8 https://adventofcode.com/2021/day/8/input """ def load_data(path): data_list = [] with open(path, "r") as file: for line in file: ref_values, values = line.split(" | ") ref_values = ref_values.split(" ")...
# Copyright 2018 Google Inc. 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 law or a...
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def rotateRight(self, head: ListNode, k: int) -> ListNode: if head == None or head.next == None: return head count = 1 p = head...
# 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, ...
import sys import subprocess import shlex from os import path args = sys.argv usage = ''' Usage: python %s -inkey [public.key] -in [signed.bin] -out [output.bin] ''' % args[0] not_there = False not_there_list = [] for arg in ["-inkey", "-out", "-in"]: if arg not in args: not_there = True not...
# Copyright (c) OpenMMLab. All rights reserved. import math import torch from torch.utils.data import DistributedSampler as _DistributedSampler class DistributedSampler(_DistributedSampler): def __init__(self, dataset, num_replicas=None, rank=None, ...
# A* ALGORITHM class Node: def __init__(self, row, col, value): self.id = str(row) + "-" + str(col) self.row = row self.col = col self.value = value self.distanceFromStart = float("inf") self.estimatedDistanceToEnd = float("inf") self.cameFrom = None # O(W * H * log(W * H)) time and O(W * H) space # W...
#!/usr/bin/env python import re import setuptools def get_info(): with open("README.md", "r") as fh: long_description = fh.read() version = re.search( r'^__version__\s*=\s*"(.*)"', open("experimenting/__init__.py").read(), re.MULTILINE, ).group(1) r...
import factory from .models import Order, Payment class OrderFactory(factory.DjangoModelFactory): class Meta: model = Order name = factory.Sequence(lambda n: "order {}".format(n)) class PaymentFactory(factory.DjangoModelFactory): class Meta: model = Payment order = factory.SubFa...
"""Installation script for coex using setuptools.""" from setuptools import setup setup( name='coex', version='1.0', packages=['coex'], install_requires=['numpy', 'scipy'], author='Adam Rall', author_email='arall@buffalo.edu', license='BSD', keywords='molecular simulation', )
#! python3 # __author__ = "YangJiaHao" # date: 2018/2/13
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright (c) 2019 John Dewey # # 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 t...
""" rec_secret.py Recoveres a secret using the Fuzzy Key Recovery scheme """ import click from fuzzy import RecoverSecret, bytes_to_hex, FuzzyError, FuzzyState def work(words, key_count, secret) -> None: """ 1. re-create the state object from json file 2. call RecoverySecret on the recovery words (words)...
""" Configuration file for Flask and Flask-SQLAlchemy modules. All environment variables are stored in local .env file. """ import os from dotenv import load_dotenv load_dotenv() #load environment variables from .env file class Config(object): db_host = os.environ.get('DB_HOST') db_name = os.environ.get('DB...
""" Find a nearby root of the coupled radial/angular Teukolsky equations. TODO Documentation. """ from __future__ import division, print_function, absolute_import import logging import numpy as np from scipy import optimize from .angular import sep_const_closest, C_and_sep_const_closest from . import radial # TOD...
import base64 import datetime import logging import os import traceback from io import BytesIO import pdfkit from dateutil.relativedelta import relativedelta from django.conf import settings from django.core.exceptions import ObjectDoesNotExist, ValidationError from django.core.files.base import ContentFile from djang...
# AUTOGENERATED! DO NOT EDIT! File to edit: nbs/02_effective_area.ipynb (unless otherwise specified). __all__ = ['EffectiveArea'] # Cell import os import numpy as np from astropy.io import fits class EffectiveArea(object): """ manage the effective area calculation from a CALDB FITS file Must specify either ...
import bpy op = bpy.context.active_operator export_selected = True export_apply = True op.export_format = 'GLB' op.ui_tab = 'GENERAL' op.export_copyright = '' op.export_image_format = 'NAME' op.export_texture_dir = '' op.export_texcoords = True op.export_normals = True op.export_draco_mesh_compression_enable = False o...
from gym.envs.registration import register register( id='maze-v0', entry_point='gym_maze.envs:MazeEnvSample5x5', max_episode_steps=2000, ) register( id='maze-sample-5x5-v0', entry_point='gym_maze.envs:MazeEnvSample5x5', max_episode_steps=10000000000000, ) register( id='maze-empty-5x5-v0'...
from django.views.generic import View from django.http import HttpResponse from django.utils.decorators import method_decorator from stronghold.decorators import public from stronghold.views import StrongholdPublicMixin class ProtectedView(View): """A view we want to be private""" def get(self, request, *arg...
""" Libary of linear regressions. """ import numpy as np from scipy.stats import linregress from astroML.linear_model import TLS_logL from scipy.odr import Model, Data, RealData, ODR import scipy.optimize as op import emcee def mcmc_linear_model(x, y, xerr, yerr, nwalkers=100, nruns=2000, cut=100...
"""Unit test package for siepic_analysis_package."""
''' Created on 08.04.2019 @author: mort ipywidget interface to the GEE for IR-MAD ''' import ee, time, warnings, math import ipywidgets as widgets from IPython.display import display from ipyleaflet import (Map,DrawControl,TileLayer, basemaps,basemap_to_tiles, LayersCo...
# This script tests LED display and speaker of calliope mini from calliope_mini import * import music # list of pitch values. Every value # represents a frequency (Hz) melody = [200, 300, 200, 300, 200, 300, 100, 300, 100, 300, 100, 300, 400, 300, 400, 300, 500, 600, 700, 300, 200] pom = True # image object can b...
""" schedule cog that handles all scheduling tasks which includes scheduled announcements for members """ from discord.ext import commands import random import json import aiocron class Schedule(commands.Cog): def __init__(self, bot, anilist_api, emojis, config): self.bot = bot self.anilist_api = ...
import unittest from zeppos_data_manager.data_cleaner import DataCleaner from datetime import datetime class TestTheProjectMethods(unittest.TestCase): def test_to_date_method(self): self.assertEqual(DataCleaner.to_date('01/01/2020'), datetime.strptime('2020-01-01 00:00:00', '%Y-%m-%d %H:%M:%S')) def ...
import unittest2 from django import test from django.core import exceptions, serializers from django_bitmask_field import BitmaskField, BitmaskFormField from .models import TestModel, ContributingModel, TestForm class TestCase(test.TestCase, unittest2.TestCase): pass class BitmaskFieldTestCase(TestCase): ...
from flask import current_app as app from config.extensions import db class DFCluster(db.Model): """ DF Cluster uniquely identifies a Deepfence on-prem deployment. Unique ID, based on MAC address will be created based on rfc4122 recommendations. Once created, it will be persisted in database and will...
def get_keytaps(target_set, key_capacity): le = len(target_set) if le>sum(key_capacity): return -1 buttons = len(key_capacity) target_set = sorted(target_set, reverse=True) key_capacity = sorted(key_capacity) multipliers = [ 1 for i in range(buttons) ] pointer = 0 keytaps = 0 ...
def test_program_units(library): for program_unit in library.program_units: assert program_unit.program_unit_text def test_library_has_program_units(library): assert library.program_units
# -*- coding: utf-8 -*- """Export / Import of generic python models. This module defines generic filesystem format for python models and provides utilities for saving and loading to and from this format. The format is self contained in a sense that it includes all necessary information for anyone to load it and use i...
#!/usr/bin/env python3 import __future__ import __main__ import _thread import abc import aifc import argparse import array import ast import asynchat import asyncio import asyncore import atexit import audioop import base64 import bdb import binascii import binhex import bisect import builtins import bz2 import calend...
import getopt import sys import string import os.path import jsonpickle import random from model.contact import Contact try: opts, args = getopt.getopt(sys.argv[1:], "n:f:", ["number of contacts", "file"]) except getopt.GetoptError: getopt.usage() sys.exit(2) n = 3 f = "data/contact.json" for o, a in opt...
#-*- encoding:utf-8 -*- #搭建模型所需要的一些模块 import tensorflow as tf import os import h5py import numpy as np def encoder_lstm_layer(layer_inputs,sequence_lengths,num_units,initial_state,is_training = 'True',direction = 'bidirectional'): ''' Build a layer of lstm ''' ''' 参数解释: layer_inputs:[bat...
# Generated by Django 3.0.7 on 2020-06-27 20:57 from django.conf import settings from django.db import migrations class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('entrymeasures', '0003_auto_20200623_2348'), ] operations...
"""Python Script Template.""" from .adversarial_policy import AdversarialPolicy class JointPolicy(AdversarialPolicy): """Given a protagonist and an antagonist policy, combine to give a joint policy.""" def __init__(self, dim_action, action_scale, *args, **kwargs) -> None: super().__init__( ...
print ' -->> Lordran pack was invoked <<-- '
#!/usr/bin/env python import time import os import sys import numpy as np import socket from distributed import Client, LocalCluster import dask from collections import Counter # get our start time global st st=time.time() def test(i,j=10): # get pid, start time, host and sleep for j seconds pid=os.getpid() w...
from flask import Flask, render_template, request, jsonify from flask_cors import CORS from file_processing import write_file, read_lines app = Flask(__name__) CORS(app) @app.route('/') def index(): return render_template('index.html') @app.route('/save_result', methods = ['POST']) def save_result(): params = re...
import subprocess from acquisition import AcquisitionStep class AcquisitionForkStep(AcquisitionStep): """ Class to describe a fork acquisition step. Attributes: command_template (string): command template to execute """ command_template = None def add_extra_arguments(self, parser)...
from .check import Check from .is_cls import Is __all__ = [Check, Is]
"""@package config Contains all config files necessary for simulator Rigid body configuration data """ from config.protobuf import * # Rigid Bodies --------------------------------------------------------------------------------------------------------- # Single Joint Robot # Base Link points_0 = [Point(x=0, y=0, z=0...
import sys, os from time import sleep import numpy ############ projectroot=os.path.split(os.getcwd())[0] sys.path.append(projectroot) sys.path.append(os.path.join(projectroot,'QtForms')) sys.path.append(os.path.join(projectroot,'AuxPrograms')) sys.path.append(os.path.join(projectroot,'OtherApps')) from CreateExperime...
#!/usr/bin/env python3 import wpilib import ctre from magicbot import MagicRobot from robotpy_ext.autonomous.selector import AutonomousModeSelector from networktables import NetworkTables from networktables.util import ntproperty from rev.color import ColorSensorV3, ColorMatch from components import swervedrive,...
# N = int(input()) # A = [0] * N # B = [0] * N # for k in range(N): # A[k] = int(input()) # for k in range(N): # B[k] = A[k] # # print(B) # def array_search(A: list, N: int, x: int): """ Осуществляет поиск числа x в массиве A от 0 до N-1 индекса включительно. Возвращает индекс элемента x в массиве ...
""" SPDX-License-Identifier: Apache-2.0 Copyright 2021 Sergio Correia (scorreia@redhat.com), Red Hat, Inc. """ import json as json_module from typing import IO, Any, Dict, List, Union JSONType = Union[str, int, float, bool, None, Dict[str, Any], List[Any]] _list_types = [list, tuple] try: from sqlalchemy.engine....
import logging import os from configuration_overrider.abstract_overrider import AbstractOverrider log = logging.getLogger(__name__) class EnvironmentOverrider(AbstractOverrider): def get(self, key) -> str: log.info(f"[get|in] ({key})") result = None try: result = os.environ[...
# pylint: skip-file # flake8: noqa ''' OpenShiftCLI class that wraps the oc commands in a subprocess ''' # pylint: disable=too-many-lines from __future__ import print_function import atexit import json import os import re import shutil import subprocess import tempfile # pylint: disable=import-error import ruamel.y...
import warnings from ._version import get_versions __version__ = get_versions()['version'] del get_versions from gisutils.projection import get_proj_str, get_authority_crs from gisutils.projection import project as project_fn from gisutils.raster import get_values_at_points, get_raster_crs, write_raster from gisutils....
from lenstronomy.Plots.model_plot import ModelPlot import numpy as np from lenstronomywrapper.LensSystem.LensSystemExtensions.chain_post_processing import ChainPostProcess from lenstronomywrapper.LensSystem.LensSystemExtensions.lens_maps import ResidualLensMaps import random class MCMCchainNew(object): def __ini...
# Copyright 2021. ThingsBoard # # 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 ...
import unittest from .addr import * class TestAddrParts(unittest.TestCase): def test_st_num_is_valid(self): addrs = [ ("1234 North Fake Street", 1234), ("5678 North Fake Street", 5678), ("9012 North Fake Street", 9012) ] for addr, exp in addrs: ...
from ete3 import NCBITaxa #The first time this will download the taxonomic NCBI database and save a parsed version #of it in `~/.etetoolkit/taxa.sqlite`.May take some minutes ncbi = NCBITaxa() print("ncbi.dbfile", ncbi.dbfile) with open(snakemake.input[0], 'r', encoding='utf8') as fh: genus_list = fh.read().str...
import numpy as np class MatrixFactorization: @classmethod def run(cls, R, P, Q, K, steps=5000, alpha=0.0002, beta=0.02, threshold=0.001): """ Args: R (numpy.ndarray): Rating P (numpy.ndarray): m x K のユーザ行列 Q (numpy.ndarray): n x K のアイテム行列 K...
from keras import backend as K from keras.layers import Layer class ExpandLayer(Layer): def __init__(self, axis, **kwargs): super().__init__(**kwargs) self._axis = axis def call(self, inputs, **kwargs): return K.expand_dims(inputs, axis=self._axis) def compute_output_shape(self, ...
import abc class Response(abc.ABC): def __init__(self): self.output = "" def with_output(self, output): self.output = output return self @abc.abstractmethod def print(self): pass def __eq__(self, other): return isinstance(other, self.__class__) \ ...
# makes KratosMultiphysics backward compatible with python 2.6 and 2.7 from __future__ import print_function, absolute_import, division #makes KratosMultiphysics backward compatible with python 2.6 and 2.7 # Application dependent names and paths import KratosMultiphysics as KM from KratosDemStructuresCouplingApplicati...
from engine import * from grid import Grid class Maze: ''' Class that will generate the maze This is the environment of this program Maybe built in PyGame ''' def __init__(self, title, dim): self.window = Window(title, dim, FPS_CAP=60) self.window.background_color = pygame.Col...
from datetime import datetime import unittest import time import six from salesmachine.version import VERSION from salesmachine.client import Client class TestClient(unittest.TestCase): def fail(self, e, batch): """Mark the failure handler""" self.failed = True def setUp(self): self...
#!/usr/bin/env python # -*- coding: utf-8 -*- # # :Author: snxx # :Copyright: (c) 2021 snxx # For license and copyright information please follow this like: # https://github.com/snxx-lppxx/Cloud-vk-bot/blob/master/LICENSE ''' GitHub: snxx-lppxx/Cloud-vk-bot ''' # Importing modules import vk_ap...
#!/bin/env python # -*coding: UTF-8 -*- """ High level helper methods to load Argo data from any source The facade should be able to work with all available data access point, Usage for LOCALFTP: from argopy import DataFetcher as ArgoDataFetcher argo_loader = ArgoDataFetcher(backend='localftp', ds='phy') or...
from rest_framework.views import APIView from rest_framework.response import Response from rest_framework.viewsets import ReadOnlyModelViewSet, GenericViewSet from rest_framework.mixins import RetrieveModelMixin, CreateModelMixin from django_redis import get_redis_connection from wechat.core.bot import SaveModelMessa...
import pyxb.binding.generate import pyxb.utils.domutils from xml.dom import Node import os.path xsd='''<?xml version="1.0" encoding="UTF-8"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:complexType name="tAddress"> <xs:choice> <xs:sequence> <xs:element name="Line1" type="xs:string"/> ...
#!/usr/bin/env python import rospy from std_msgs.msg import String import threading import time from gps3 import gps3 latitude=0 longitude=0 gps_socket = gps3.GPSDSocket() data_stream = gps3.DataStream() gps_socket.connect() gps_socket.watch() def pos_update(): while True: global latitude,longitude ...
# -*- coding: utf-8 -*- # Copyright 2012 Loris Corazza, Sakis Christakidis # # 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...
""" Detect and recognize faces using dlib served by zerorpc Should be called from a zerorpc client with ZoneMinder alarm image metadata from zm-s3-upload.js. This program should be run in the 'cv' virtual python environment, i.e., $ /home/lindo/.virtualenvs/cv/bin/python ./face_detect_server.py This is part of the s...
"""Voice Assistant base NL processor.""" from abc import ABC, abstractmethod from dataclasses import dataclass from typing import Optional from voiceassistant.utils.datastruct import DottedDict @dataclass class NlpResult: """NLP Result class. Should be a return type of all NL processors. """ inten...
import sys import click from subprocess import check_call DEFAULT_PYTHON_VERSION = "3.6" PYTHON_VERSIONS = ["3.6"] ADDITIONAL_CORE_DEPS = [ 'pyface>=7.0.0-3', 'traitsui>=7.0.0-2', 'requests==2.18.4-1' ] ADDITIONAL_PLATFORM_CORE_DEPS = { 'rh6-x86_64': [ 'lxml==3.7.3-2' ], 'osx-x86_64':...
def parse_range(srange): left, right = [int(e) for e in srange.split('=')[-1].split('..')] return left, right def parse_line(line): line2 = line.strip() if line2.startswith('on '): line3 = line2[3:] light_on = True elif line2.startswith('off '): line3 = line2[4:] ...
from os import listdir from pickle import dump from keras.applications.vgg16 import VGG16 from keras.preprocessing.image import load_img from keras.preprocessing.image import img_to_array from keras.applications.vgg16 import preprocess_input from keras.models import Model import tensorflow as tf #import theano ...
import os, time, errno import mss #https://python-mss.readthedocs.io/en/dev/examples.html import numpy as np import csv import cv2 import dlib import IMDBActors as imdb MONITOR = {'top': 0, 'left': 0, 'width': 1080, 'height': 720} def capture(sct): return sct.grab(MONITOR) KNEWFACES_DIR = 'Resources/KnownPeopleToEn...
from utils import run def test_list_krake_applications(): cmd = "kubectl get po --all-namespaces" response = run(cmd) assert response.returncode == 0 assert "NAMESPACE" in response.output
from functools import partial import jax from jax.flatten_util import ravel_pytree import jax.numpy as jnp import optax import numpy as np from absl import flags from tqdm import tqdm flags.DEFINE_integer('iter_max', 100, help='number of iteration for Hutchison method') FLAGS = flags.FLAGS @jax.pmap def acc_batch(s...
#!/usr/bin/env python3 # encoding: utf-8 # # Copyright (c) 2019 SAP SE or an SAP affiliate company. All rights reserved. # # This file is part of ewm-cloud-robotics # (see https://github.com/SAP/ewm-cloud-robotics). # # This file is licensed under the Apache Software License, v. 2 except as noted # otherwise in the LIC...
""" https://docs/python.org/3/library """ import math from math import sqrt # import modulesexternal.car as car # from modulesexternal import car # better way to do it from modulesexternal.car import info # from modulesexternal.fibo import * from modulesexternal import fibo class ModulesDemo(): def builtin_...
""" activations.py Each of the supported activation functions. """ import torch from utils.dictionary import D_CLAMPED_ABS, D_CLAMPED_LINEAR, D_COS, D_EXP, D_EXP_ABS, D_GAUSS, D_HAT, D_SIGMOID, \ D_SIN, D_TANH def clamped_abs_activation(x): return min(1.0, torch.abs(x) / 3) def clamped_linear_activation(x...
from MiddleKit.Run.MiddleObject import MiddleObject def assertBazIsObjRef(bar): bazAttr = getattr(bar, '_baz') assert isinstance(bazAttr, MiddleObject), ( 'bazAttr=%r, type(bazAttr)=%r' % (bazAttr, type(bazAttr))) def test(store): foos = store.fetchObjectsOfClass('Foo') assert len(foos) == 2 ...
#!/use/bin/env python #coding:utf-8 #Author:WuYa import os def data_dir(data='data',fileName=None): '''查找文件的路径''' return os.path.join(os.path.dirname(os.path.dirname(__file__)),data,fileName)
# Generated by Django 2.2.6 on 2021-08-21 16:40 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('posts', '0023_auto_20210821_1635'), ] operations = [ migrations.RemoveField( model_name='post',...
''' GetQueueAttributes Command ''' import time from .base_command import BaseRSMQCommand from .exceptions import QueueDoesNotExist class GetQueueAttributesCommand(BaseRSMQCommand): ''' Get Queue Attributes from existing queue ''' PARAMS = {'qname': {'required': True, 'value'...
"""Array algorithms""" from .find_peak import * from .two_sum import *
#DataClass.py #-*- coding: utf-8 -*- import numpy as np from sklearn.datasets import fetch_mldata class LabeledSet: def __init__(self,x,y,input_dim,output_dim): self.x = x self.y = y self.input_dim = input_dim self.output_dim = output_dim #Renvoie la dimension de l...