content
stringlengths
5
1.05M
from django.shortcuts import render from products.models import Product # Create your views here. def index(request): context = { 'products' : Product.objects.all(), } return render(request,'landing/index.html',context=context) def about(request): return render(request,'landing/about.html') d...
# Evaluates and ranks UIs import pybrain from scipy import * import numpy as np import math import sys from copy import copy import operator as op from UIEnv import UI, UITask from evaluation import evaluation from episodic import EpisodicExperiment from experiment import Experiment from initialParams import initia...
import json from pprint import pprint departureTime_hour = "" departureTime_minute = "" flightNumber = "" aircraftType = "" destination = "" flightStatus = "" baseCost = "" durationInMinutes = "" fl = "lo" new_val = "" with open('/Users/abinavc/AA-Mock-Engine/mock/flightData.json') as f: data = json.loa...
#!/usr/bin/env python # TO DO: Revamp functions to # -compare different Lennard-Jones grid transformations # TO DO: Clean up output # TO DO: Write docstrings # TO DO: Set up checkpoints # Ideas from Prodock by Trosset & Scheraga # TO DO: Grid interpolation with Bezier splines, which provides second derivatives [Ober...
# -*- coding: utf-8 -*- """ Installments """ INSTALLMENTS = 'I' """ Recurring """ RECURRING = 'R' """ Reauthorization """ REAUTHORIZATION = 'H' """ Resubmission """ RESUBMISSION = 'E' """ Delayed """ DELAYED = 'D' """ Incremental """ INCREMENTAL = 'M' """ No Show """ NO_SHOW = 'N' """ Others """ OTHERS = 'C' ...
"""succint json documents. this module uses `semi-indexing` to efficiently deserialize elements of json documents. it does this by combining a succint tree that enables efficient navigation of the document with the `jq` query language for specifying nodes within the document to deserialize. for more details, see `"se...
import os from pathlib import Path from dotenv import load_dotenv from celery import schedules basedir = Path(__file__).resolve().parent load_dotenv(os.path.join(basedir, '.env')) class Config: """ Set base Flask configuration vars. """ # General Config DEBUG = False TESTING = False SEC...
config = dict( experiment = 'qgen', # Experiment - either qgen or dialogue lstm_hidden_units = 100, # Number of hidden units for the LSTM embedding_size = 300, # Word embedding dimension num_layers = 1, # Number of LSTM layers encoder_vocab = 40000, # Vocabulary size on the encoder sid...
# coding: utf-8 # Author: Leo BRUNEL # Contact: contact@leobrunel.com # Python modules import traceback import os import logging logger = logging.getLogger(__name__) # Wizard modules from maya_wizard import wizard_tools # Maya modules import pymel.core as pm # Hook modules try: import maya_hook except: maya...
from masonite.providers import ( RouteProvider, FrameworkProvider, ViewProvider, ExceptionProvider, SessionProvider, QueueProvider, StorageProvider, AuthenticationProvider, AuthorizationProvider, ORMProvider, EventProvider ) PROVIDERS = [ FrameworkProvider, RoutePro...
import re import requests import numpy as np import json import os from collections import OrderedDict import pandas as pd import json #将数组写入json文件方便pandas的读取 def write_list_to_json(list, json_file_name, json_file_save_path): os.chdir(json_file_save_path) with open(json_file_name, 'w') as f: json.dump(...
from part1 import ( gamma_board, gamma_busy_fields, gamma_delete, gamma_free_fields, gamma_golden_move, gamma_golden_possible, gamma_move, gamma_new, ) """ scenario: test_random_actions uuid: 138749984 """ """ random actions, total chaos """ board = gamma_new(5, 2, 4, 2) assert board is...
# coding=utf-8 import logging from nose.plugins.attrib import attr from modelscript.interfaces.environment import Environment from modelscript.test.framework import TEST_CASES_DIRECTORY import os import modelscript.scripts.usecases.parser from modelscript.scripts.usecases.graphviz import ( UsecaseGraphvizPrinte...
# -*- coding: utf-8 -*- from __future__ import unicode_literals # Third Party Stuff from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('conferences', '0012_historicalconferenceproposalreviewer'), ] operations = [ migrations.AddField( ...
from functools import partial from subprocess import PIPE, run from textwrap import dedent import pytest from flake8_annotations import error_codes from testing.helpers import check_source ERR = partial(error_codes.ANN401, lineno=3) TEST_CASES = ( # Type annotations ( dedent( """\ ...
# Generated by Django 2.2.16 on 2020-10-23 07:00 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('sites', '0002_alter_domain_unique'), ('cms', '0022_auto_20180620_1551'), ('djangocms_charts', '0004_auto_20...
# ─┐ ┬┌─┐┌┐┌┌─┐┌┐ ┬ ┬┌┬┐┌─┐ ─┐ ┬┬ ┬┌─┐ # ┌┴┬┘├┤ ││││ │├┴┐└┬┘ │ ├┤ ┌┴┬┘└┬┘┌─┘ # ┴ └─└─┘┘└┘└─┘└─┘ ┴ ┴ └─┘o┴ └─ ┴ └─┘ # Author: SENEX @ XENOBYTE.XYZ # License: MIT License # Website: https://xenobyte.xyz/projects/?nav=dotfiles from bs4 import BeautifulSoup import urllib.request import re import sys # How to use # ---...
__all__ = ['find_fits_files', 'test_fits_keyword', 'test_coordinates', 'test_file_number', 'test_float_input', 'test_float_positive_input', 'test_int_input', 'test_int_positive_input', 'test_int_positive_non_zero_input', 'test_date', 'filter_map'] import numpy as np import glob import hops.pylig...
# # 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...
# Generated by Django 4.0.1 on 2022-03-19 13:31 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('lab', '0016_run_new_status_squashed_0019_rename_new_status_run_status'), ('lab', '0019_alter_run_end_date_alter_run_start_date'), ] operations = [ ...
__all__ = ['WebClient'] import inspect import input_helper as ih import webclient_helper as wh class WebClient(object): """Interact with an API on the web If you need to obtain a token from a login endpoint, define a "login" method when you subclass WebClient and set self._token and self._token_type ...
### imports ### import numpy as np import pandas as pd from matplotlib import pyplot as plt from scipy.integrate import odeint import random as rd ### parameters ### ### E.coli parameters growth_rate = 0.04 e_max_size = 2 e_min_size = 1 ### minicell parameters minicell_production_rate = 0 m_max_size = 1/5 * e_max_...
# -*- coding: utf-8 -*- from optimus.assets.registry import register_assets from optimus.pages.builder import PageBuilder from optimus.utils import initialize def builder_interface(settings, views): """ Build all enabled pages from given views module. Arguments: settings (optimus.conf.model.Setti...
from django.urls import path from . import views app_name='menu' urlpatterns = [ path("",views.menuPage,name='menu'), path("logout",views.logoutPage,name='logout') ]
import cv2 import os import argparse # References: https://blog.csdn.net/bryant_meng/article/details/110079285 # Check test_video.sh in the main directory # Step1: Run video_to_frame to convert low light video to images # Step2: Run test.py to convert low light images to enhanced images # Step3: Run image_to_v...
from cs50 import SQL from flask import Flask, flash, redirect, render_template, request, session, url_for from flask_session import Session from passlib.apps import custom_app_context as pwd_context from tempfile import mkdtemp from passlib.context import CryptContext from helpers import * import helpers # configure a...
from django.core.management.base import BaseCommand from ...utils import get_user_model class Command(BaseCommand): help = "Sync customer data" def handle(self, *args, **options): User = get_user_model() qs = User.objects.exclude(customer__isnull=True) count = 0 total = qs.co...
#!/usr/bin/python import os os.system('geany')
from __future__ import print_function from potentiostat import Potentiostat import sys import time if len(sys.argv) > 1: port = sys.argv[1] else: port = '/dev/ttyACM0' num_sample = 10 sleep_dt = 1.0 dev = Potentiostat(port) dev.set_volt_range('5V') dev.set_curr_range('100uA') dev.set_volt(0.0) volt_list =...
import time import logging import cfg import sensorlogger import logentry import batteryManager import circularlist #import actor abstract import absactor class Actor(absactor.Actor): def __init__(self): self.logger = logging.getLogger("PB.actor.real") self.logger.info("Starting up") self.batteryManagerObj = bat...
import os import traceback from time import time import click from site_speaker.speech.CrtAdapter import CrtAdapter from site_speaker.utils.export import export from site_speaker.utils.files import get_all_files_with_extension, get_base_filename from site_speaker.utils.parsing import get_posts from site_speaker.utils...
# Code listing #8 def rms(varray=[]): """ RMS velocity """ squares = map(lambda x: x*x, varray) return pow(sum(squares), 0.5) def rms(varray=[]): """ Root mean squared velocity. Returns square root of sum of squares of velocities """ squares = map(lambda x: x*x, varray) return pow(...
from flask import render_template, Blueprint, request, redirect, url_for from flask_login import login_required, current_user from project.dataset.form import DatasetForm from project.models import Dataset, College from project import db dataset_blueprint = Blueprint( 'dataset', __name__, template_folder='tem...
"""Definition of a hook. Logger hooks are functions or callable classes that receive all the logging information that should be logged by the instance in any of the calls of the debug, info, warning, error, fatal or critical methods. Example: def hook_function(context: HookContext) -> NoReturn: if 'foo' ...
#!/usr/bin/python """ Copyright 2013 Jack Kelly (aka Daniel) 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 ap...
import numpy as np import os try: import netCDF4 as netCDF except: import netCDF3 as netCDF import matplotlib.pyplot as plt import time import datetime as dt from matplotlib.dates import date2num, num2date import pyroms import pyroms_toolbox from pyroms import _remapping class nctime(object): pass def remap(...
# -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division from __future__ import print_function import csv import numpy as np import os import sys from observations.util import maybe_download_and_extract def ducks(path): """Behavioral and Plumage Characteristics of Hybrid Duck...
def bitIsSet( value, bit ): bitSet = value & (2 ** bit) return True if bitSet > 0 else False def chunks(lst, n): for i in range(0, len(lst), n): yield lst[i:i + n] def getRange(lst, start, length): return lst[start:start + length] def getNiceGlyphName(unicode): glyphNames = [ 'spa...
from ..utils import Object class RemoveNotificationGroup(Object): """ Removes a group of active notifications. Needs to be called only if the notification group is removed by the current user Attributes: ID (:obj:`str`): ``RemoveNotificationGroup`` Args: notification_group_id (:ob...
import json import math import random import webcolors from alive_progress import alive_bar import cairo def do_nothing(): """Do nothing. A dummy function to use in place of alive_bar.""" pass class CairoPainter: """ A class to interface with the Cairo library to draw the map for a given save file....
from abstractplayer import * from element import * from baseclass import * __all__ = ['QAlgorithm', 'QPlayer', 'HumanPlayer'] class QAlgorithm(BaseQ): def __init__(self, alpha, gamma, reward, tie, penalty): self.qmap = ValueMap() self.alpha = Value(alpha) self.gamma = Value(gamma) self.feedback = { Gam...
from __future__ import absolute_import, division, print_function, unicode_literals from gittip.elsewhere import PlatformOAuth2 from gittip.elsewhere._extractors import key from gittip.elsewhere._paginators import header_links_paginator class GitHub(PlatformOAuth2): # Platform attributes name = 'github' ...
from PIL import Image, ImageOps import numpy as np import skimage.io as io from src.models.class_patcher import patcher from src.utils.imgproc import * from skimage.color import rgb2hsv, hsv2rgb class patcher(patcher): def __init__(self, body='./body/body_glaze.png', **options): super().__init__('ぐれーず', b...
class Solution: def reverseBits(self, nums: int) -> int: result = 0 for i in range(32): result <<= 1 if (nums & 1) == 1: result ^= 1 nums >>= 1 return result
# -*- coding: utf-8 -*- """ Created on Thu Aug 29 15:06:21 2019 @author: Ahmed Ali Mohamed ------- Chapter 4 section 3.1 (4.3.1) ------- ******* Finger exercise: When the implementation of fib in Figure 4.7 is used to compute fib(5), how many times does it compute the value of fib(2) on the way to computing fib(5)?...
# Given an integer array arr, sort the integers in arr in ascending order by the number of 1’s in their binary representation and return the sorted array. # # Examples: # $ sortBits([0,1,2,3,4,5,6,7,8]) # $ [0,1,2,4,8,3,5,6,7] def sort_bits(num_list): nums_counted = {} miny = 0 maxy = 0 for num in ...
import timeit import numpy as np from bingo.symbolic_regression.agraph \ import agraph as agraph_module from bingo.symbolic_regression.agraph.evaluation_backend import \ evaluation_backend as pyBackend from bingo.local_optimizers.continuous_local_opt \ import ContinuousLocalOptimization from bingocpp impo...
import json import schedule import time as t import webbrowser import datetime import argparse from selenium import webdriver from selenium.webdriver.common.keys import Keys options = webdriver.ChromeOptions() options.add_argument("--disable-infobars") options.add_argument("--window-size=1280,720") options.add_expe...
from datetime import datetime, timedelta import jwt from django.conf import settings from django.contrib.auth.models import ( AbstractBaseUser, BaseUserManager, PermissionsMixin, ) from django.db import models from sendit.apps.core.base_model import CommonFieldsMixin class UserManager(BaseUserManager): ...
import torch import torch.nn as nn import torch.nn.functional as F from model.general.attention.additive import AdditiveAttention device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") class NewsEncoder(torch.nn.Module): def __init__(self, config, pretrained_word_embedding, writer): supe...
import torch.nn as nn def CrossEntropyLoss(output, target): criterion = nn.CrossEntropyLoss() return criterion(output, target)
from graph4nlp.pytorch.modules.evaluation.cider import CIDEr if __name__ == "__main__": import json scorer = CIDEr(df="corpus") pred_file_path = "/home/shiina/shiina/question/iq/pred.json" gt_file_path = "/home/shiina/shiina/question/iq/gt.json" with open(gt_file_path, "r") as f: gt = json...
import os import openai from dotenv import load_dotenv load_dotenv() openai.api_key = os.getenv("OPENAI_API_KEY") start_sequence = "\nIntelli_AGENT:" restart_sequence = "\n\nUser:" session_prompt = "Intelli_AGENT is a chatbot that reluctantly answers questions.\n\n###\nUser: How many pounds are in a kilogra...
try: from urllib.request import urlopen except ImportError: from urllib import urlopen import re import string def format_normalized_package_name(package_name): # type: (str) -> str """Normalize a package name""" return package_name.replace(".", "-").replace("_", "-").lower() def format_descrip...
import threading class Neighbor(threading.Thread): """The class Neighbor contains the client node socket, ip and host and hold the server node id. Communication is done by this class. The server node sending message, pass through to the main node. Instantiates a new Neighbor. main_node: The Node class...
import pytest from tests.utils import file_response from documenters_aggregator.spiders.chi_animal import Chi_animalSpider test_response = file_response('files/chi_animal.html', url='https://www.cityofchicago.org/city/en/depts/cacc/supp_info/public_notice.html') spider = Chi_animalSpider() parsed_items = [item for i...
#!/usr/bin/env python """ OCRL HW2 Simple: first fit a spline for received waypoints, then a path tracking or PID controller to follow """ from common import * from nav_msgs.msg import Odometry, Path from geometry_msgs.msg import PoseArray, Pose, Twist, PoseStamped from ackermann_msgs.msg import AckermannDriveStamped ...
import argparse import os.path as osp import warnings import numpy as np import onnx import onnxruntime as rt import torch from mmdet.core import (build_model_from_cfg, generate_inputs_and_wrap_model, preprocess_example_input) def pytorch2onnx(config_path, checkpoint_path, ...
import sys import argparse import math import almath as m # python's wrapping of almath import time #import numpy as np from naoqi import ALProxy degree = math.pi/180.0 # radians per degree pi = math.pi exp = math.exp atan2 = math.atan2 def FTarget(target_distance, target_angle): # Attractor ...
try: import tilde except ImportError: import os, sys chk_path = os.path.realpath(os.path.normpath(os.path.join( os.path.dirname(os.path.abspath(__file__)), "../" ))) if not chk_path in sys.path: sys.path.insert(0, chk_path)
from matplotlib import mlab import numpy as np def estimate_decoder(time,s,r,dt,nfft=2**12): ''' Estimates the decoding kernel K and reconstructs the original stimuls Inputs: time: time vector s: stimulus r: response dt: sampling period nfft: number of ...
from pydantic import BaseModel import json class KubeConfigRequest(BaseModel): userId: str configString: str def toJSON(self): return json.dumps(self, default=lambda o: o.__dict__, sort_keys=True, indent=4)
from __future__ import print_function from hashlib import sha1 from rdflib import Graph import re import requests import sys import os import ssl from urllib.parse import urlparse, quote from urllib.request import urlopen from .constants import EXT_BINARY_INTERNAL, EXT_BINARY_EXTERNAL, \ LDP_NON_RDF_SOURCE, MINIMAL...
from unittest.mock import MagicMock from pytest import fixture from slacknewsbot.app import GetHN SLACK_TEXT = "Top 3 from HackerNews:\n>*<https://news.ycombinator.com/item?id=1|1>* - <abc|bcd>" @fixture() def obj(): obj = GetHN.__new__(GetHN) obj.logger = MagicMock() return obj def test_should_crea...
#!/usr/bin/env python # -*- encoding: utf-8 -*- # vim: set et sw=4 ts=4 sts=4 ff=unix fenc=utf8: # Author: Binux<i@binux.me> # http://binux.me # Created on 2014-07-30 12:22:47 import os,sys sys.path.append(os.path.abspath(os.path.dirname(os.path.dirname(__file__))))
"""Notelist CLI Setup script.""" import setuptools as st if __name__ == "__main__": with open("README.md") as f: long_desc = f.read() st.setup( name="notelist-cli", version="0.3.0", description="Command line interface for the Notelist API", author="Jose A. Jimenez", ...
from __future__ import annotations from typing import TYPE_CHECKING, Any, Dict, List, Optional import psycopg2 from sqlalchemy.dialects import postgresql from local_data_api.models import ColumnMetadata from local_data_api.resources.resource import Resource, register_resource_type if TYPE_CHECKING: # pragma: no co...
import collections import bs4 import tornado import tornado.httpclient import tornado.ioloop from tqdm import tqdm import common.mongo import common.settings # taken from https://github.com/tornadoweb/tornado/issues/1400 class BacklogClient(object): def __init__(self): self.max_concurrent_requests = com...
# encoding: utf-8 """ @author: yp @software: PyCharm @file: num_to_rmb.py @time: 2019/8/21 0021 10:17 """ ''' 把一个浮点数分解成整数部分和小数部分字符串 num 需要被分解的浮点数 返回分解出来的整数部分和小数部分。 第一个数组元素是整数部分,第二个数组元素是小数部分 ''' def divide(num): # 将一个浮点数强制类型转换为int型,即得到它的整数部分 integer = int(num) # 浮点数减去整数部分,得到小数部分,小数部分乘以100后再取整得到2...
#No phi nodes are placed # we need a case when no phi function placed for different blocks c = 10 if c: print(c) else: t = 0 print(t)
from django.core.management.base import BaseCommand from edge.models.genome import Genome from edge.io import IO class Command(BaseCommand): def handle(self, *args, **options): if len(args) != 2: raise Exception("Expecting integer genome ID and filename as arguments") try: ...
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 from copy import deepcopy from dataclasses import asdict from typing import List, Dict import os from pre_wigs_validation.enums import ( ValidationConfig, ValidationResult, ValidationEnforcement, ) f...
"""Tests for the AsyncJob web API.""" import json import re import time import pytest from yeti.core.asyncjob import get_active_jobs @pytest.yield_fixture(autouse=True) def wait_for_jobs(): """Faits for active jobs to complete before each test run.""" while get_active_jobs(): time.sleep(0.1) @pyte...
""" 26. Remove Duplicates from Sorted Array Given a sorted array nums, remove the duplicates in-place such that each element appear only once and return the new length. Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. """ class Solution: ...
import asyncio import pytest from click.testing import CliRunner from unittest.mock import Mock from asynctest import CoroutineMock from netcfgbu.cli import probe @pytest.fixture(autouse=True) def _always(netcfgbu_envars, files_dir, monkeypatch): test_inv = files_dir.joinpath("test-small-inventory.csv") mon...
import mablane.bandits from mablane.bandits import BinomialBandit def test_binomial_bandit(): mablane.bandits._BinomialBandit.binomial = lambda n, p: n + p bandit = BinomialBandit(1) assert bandit.pull() == 2 bandit = BinomialBandit(1, 2) assert bandit.pull() == 3
import argparse import datetime import os import pickle import subprocess import numpy as np import pandas as pd from src.general.directory_handling import make_and_cd from simulation_parameters import BindingParameters class ParameterTesting(object): def __init__(self, steps=8, lf=30): self.binding_con...
#!/usr/bin/env python # Copyright 2016-2019 Biomedical Imaging Group Rotterdam, Departments of # Medical Informatics and Radiology, Erasmus MC, Rotterdam, The Netherlands # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obt...
# Copyright 2021 IBM 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 agreed t...
#!/usr/bin/env python # Copyright 2014 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...
def bar(): pass bar()
#!/usr/bin/env python2 from hermes_python.hermes import Hermes from datetime import datetime from pytz import timezone import requests MQTT_IP_ADDR = "localhost" MQTT_PORT = 1883 MQTT_ADDR = "{}:{}".format(MQTT_IP_ADDR, str(MQTT_PORT)) def intent_received(hermes, intent_message): print() print(intent_message.inte...
# coding=utf-8 import time import hashlib import oss2 import os import codecs import json from mov_sdk.nft_api import NftApi, Net def load_json(filename): """ Load data from json file in temp path. """ if os.path.exists(filename): with codecs.open(filename, mode="r", encoding="utf-8") as f: ...
# ref. # https://docs.python.org/3/library/weakref.html#finalizer-objects # https://docs.python.org/3/library/weakref.html#module-weakref # A primary use for weak references is to implement caches or mappings holding large objects, # where it’s desired that a large object not be kept alive solely # because it appears ...
""" RD Project """ from reorder import * from fp_growth import find_frequent_itemsets import glob import itertools import math import sys def assemble_Cohorte(): """ -> Assemble cohorte (i.e list of list) of patient -> create index file for variable in PARAMETERS folder -> return a list of patient patient ve...
from brownie import Box, accounts, network def pp_event(event, prefix='') -> str: lines = [] for i, log in enumerate(event): lines.append('{}log[{}]'.format(prefix, i)) for key, value in log.items(): lines.append('{} {}: {}'.format(prefix, key, value)) return '\...
import yaml as ym import os import sys class config(): #loading configuration file def expose_config(self, gen_conf): config = self.load_config('config.yaml') return config[gen_conf] #function to load configuration file def load_config(self, config_file): #base path to file ...
import os import shutil from ievv_opensource.utils.ievvbuildstatic import pluginbase class Plugin(pluginbase.Plugin): # Copy specified files from staticsources/<packagename>/node_modules/foo/bar/<libfile>.js to static/<packagename>/<version>/node_modules/<libfile>.js def __init__(self, sour...
"""This script walks through how to use the Python API. Covered here: importing GPUdb, instantiating Kinetica, creating a type, creating a table, inserting records, retrieving records, filtering records, aggregating/grouping records, and deleting records. """ from __future__ import print_function import collections ...
ReLU [[0.0553801, 0.190198, -0.0377036, -1.32009, -0.704992], [-0.010481, -0.118571, 0.153946, -0.736114, -1.00878], [0.482564, 0.0565022, 0.0443098, 0.0600691, 0.0020876], [-0.0778212, -0.0577902, -0.153575, 0.0605465, 0.450204], [0.0143941, -0.25066, -0.132743, 0.533158, -0.0781143], [-0.00869665, -0.447464, -0.05171...
from gpiozero import MCP3008 import time adc = MCP3008(channel=1, device=0) while True: print(adc.value) time.sleep(1)
# Try to make process close together and short the method name # # I DON'T WANT BELOW THESE TRASH UNLESS NECESSARY # # # If you do hope use three double quotes(why?), # # try replace " by &dq&, for example: """ -> &dq&&dq&&dq& # myString.replace("&dq&", '"') # # # To show symbol directly, break each & with &/, # # they...
from django.conf import settings from django.conf.urls import include, url from django.conf.urls.static import static from django.contrib import admin admin.autodiscover() urlpatterns = [ url(r'^', include(('misc.urls', 'misc'), namespace='misc')), url(r'^', include(('meetups.urls', 'meetups'), namespace='mee...
from django.shortcuts import render from django.http import HttpResponse from django.contrib import auth import pandas as pd import re from .forms import getFile,getMessage from users.models import UsersDB from Classifiers.QuotientFilter import QuotientFilter from Classifiers.LSH import LSH from Classifiers.Classifier...
"""Test the LADRegressor.""" import numpy as np import pytest from sklearn.utils.estimator_checks import check_estimator from .. import LADRegression, QuantileRegression, ImbalancedLinearRegression, LinearRegression test_batch = [ (np.array([0, 0, 3, 0, 6]), 3), (np.array([1, 0, -2, 0, 4, 0, -5, 0, 6]), 2), ...
# Generated by Django 3.2.7 on 2021-10-13 14:36 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ("okr", "0074_auto_20210915_1024"), ] operations = [ migrations.AddField( model_name="podcast", ...
from pywick.optimizers.lookahead import * from torch.optim import SGD class LookaheadSGD(Lookahead): def __init__(self, params, lr, alpha=0.5, k=6, momentum=0.9, dampening=0, weight_decay=0.0001, nesterov=False): """ Combination of SGD + LookAhead :param params: :param lr: ...
from file_convert import convert_file convert_file('代码整洁之道.md', '代码整洁之道')
from django import forms from .models import MasterField, Source class SourceDataImportForm(forms.ModelForm): # source_name = forms.CharField(max_length=255) # source_file = forms.FileField( # label="Upload a CSV file containing source data") # delimiter = forms.CharField(max_length=255, label='CS...
from cw_eval.evalfunctions import calculate_iou, process_iou from cw_eval import data from shapely.geometry import Polygon class TestEvalFuncs(object): def test_overlap(self): gt_gdf = data.gt_gdf() pred_poly = Polygon(((736348.0, 3722762.5), (736353.0, 3722762.0), ...