text
stringlengths 184
4.48M
|
|---|
import { render, screen } from "@testing-library/react";
import user from "@testing-library/user-event";
import App from "../App";
describe("App", () => {
it("increments the counter on button click", async () => {
render(<App />);
const buttonCount = await screen.findByRole("button");
expect(buttonCount.innerHTML).toBe("count is 0");
await user.click(buttonCount);
await user.click(buttonCount);
expect(buttonCount.innerHTML).toBe("count is 2");
});
it("shows the alternative counter when the count is greater than 0", async () => {
render(<App />);
const buttonCount = await screen.findByRole("button");
const conditionalCount = await screen.queryByText(/Count is now:/);
expect(conditionalCount).not.toBeInTheDocument();
await user.click(buttonCount);
expect(await screen.queryByText(/Count is now:/)).toBeInTheDocument();
});
});
|
import pytest
import utils.helpers as hp
from config.binance_exchange import BinanceConfig
from unittest.mock import MagicMock
from utils.helpers import Symbol
from generic_test_data import (
BTC_TEST_DATA, ETH_TEST_DATA,
ETALON_BTC_COUNT_OPERATIONS, ETALON_ETH_COUNT_OPERATIONS,
ETALON_BTC_AVG_PRICE, ETALON_ETH_AVG_PRICE,
ETALON_BTC_QUANTITY, ETALON_ETH_QUANTITY
)
@pytest.fixture()
def enter_BTC_symbol():
return [Symbol.BTC_USDT]
@pytest.fixture()
def enter_ETH_symbol():
return [Symbol.BTC_USDT, Symbol.ETH_USDT]
def mock_binance_client(func):
def inner_func(*args, **kwargs):
hp.get_binance_client = MagicMock(return_value=None)
hp.get_trades_info_for_symbol = MagicMock(return_value=BTC_TEST_DATA)
return func(*args, **kwargs)
return inner_func
def test_symbol_in_result_for_BTC(enter_BTC_symbol):
"""
Тестируем, что входные тикеры находятся в результаты get_trades_info
"""
hp.get_binance_client = MagicMock(return_value=None)
hp.get_trades_info_for_symbol = MagicMock(return_value=BTC_TEST_DATA)
trades_info = hp.get_trades_info(enter_BTC_symbol)
assert list(trades_info.keys()) == enter_BTC_symbol
def test_correct_operations_for_BTC_symbols_in_result(enter_BTC_symbol):
"""
Тестируем, что посчитанное количество операций для BTC тикера калькулируются правильно
"""
hp.get_binance_client = MagicMock(return_value=None)
hp.get_trades_info_for_symbol = MagicMock(return_value=BTC_TEST_DATA)
trades_info = hp.get_trades_info(enter_BTC_symbol)
history_for_BTC = hp.get_history_by_symbol_info(trades_info)
assert history_for_BTC[Symbol.BTC_USDT].get(hp.Const.OPERATIONS_AMOUNT) == ETALON_BTC_COUNT_OPERATIONS
def test_correct_operations_for_ETH_symbols_in_result(enter_ETH_symbol):
"""
Тестируем, что посчитанное количество операций для BTC тикера калькулируются правильно
"""
hp.get_binance_client = MagicMock(return_value=None)
hp.get_trades_info_for_symbol = MagicMock(return_value=ETH_TEST_DATA)
trades_info = hp.get_trades_info(enter_ETH_symbol)
history_for_ETH = hp.get_history_by_symbol_info(trades_info)
assert history_for_ETH[Symbol.ETH_USDT].get(hp.Const.OPERATIONS_AMOUNT) == ETALON_ETH_COUNT_OPERATIONS
def test_correct_value_for_BTC_symbols_in_result(enter_BTC_symbol):
"""
Тестируем, что посчитанное среднее значение для BTC тикера калькулируется правильно
"""
hp.get_binance_client = MagicMock(return_value=None)
hp.get_trades_info_for_symbol = MagicMock(return_value=BTC_TEST_DATA)
trades_info = hp.get_trades_info(enter_BTC_symbol)
history_for_BTC = hp.get_history_by_symbol_info(trades_info)
assert history_for_BTC[Symbol.BTC_USDT].get(hp.Const.AVG_SYMBOL_PRICE) == BinanceConfig.safe_round_value(ETALON_BTC_AVG_PRICE)
def test_correct_value_for_ETH_symbols_in_result(enter_ETH_symbol):
"""
Тестируем, что посчитанное среднее значение для ETH тикера калькулируется правильно
"""
hp.get_binance_client = MagicMock(return_value=None)
hp.get_trades_info_for_symbol = MagicMock(return_value=ETH_TEST_DATA)
trades_info = hp.get_trades_info(enter_ETH_symbol)
history_for_ETH = hp.get_history_by_symbol_info(trades_info)
assert history_for_ETH[Symbol.ETH_USDT].get(hp.Const.AVG_SYMBOL_PRICE) == BinanceConfig.safe_round_value(ETALON_ETH_AVG_PRICE)
def test_correct_quantity_for_BTC_symbols_in_result(enter_BTC_symbol):
"""
Тестируем, что посчитанное итоговое количество для BTC тикера калькулируется правильно
"""
hp.get_binance_client = MagicMock(return_value=None)
hp.get_trades_info_for_symbol = MagicMock(return_value=BTC_TEST_DATA)
trades_info = hp.get_trades_info(enter_BTC_symbol)
history_for_BTC = hp.get_history_by_symbol_info(trades_info)
assert history_for_BTC[Symbol.BTC_USDT].get(hp.Const.AVG_SYMBOL_QUANTITY) == BinanceConfig.safe_round_value(ETALON_BTC_QUANTITY)
def test_correct_quantity_for_ETH_symbols_in_result(enter_ETH_symbol):
"""
Тестируем, что посчитанное итоговое количество для ETH тикера калькулируется правильно
"""
hp.get_binance_client = MagicMock(return_value=None)
hp.get_trades_info_for_symbol = MagicMock(return_value=ETH_TEST_DATA)
trades_info = hp.get_trades_info(enter_ETH_symbol)
history_for_ETH = hp.get_history_by_symbol_info(trades_info)
assert history_for_ETH[Symbol.ETH_USDT].get(hp.Const.AVG_SYMBOL_QUANTITY) == BinanceConfig.safe_round_value(ETALON_ETH_QUANTITY)
|
using System.Threading.Tasks;
using AutoMapper;
using modelo.Domain.Gateways;
using modelo.Domain.Entities;
using modelo.Application.Models.PedidoModel;
using modelo.Domain.Gateways.External;
using System;
using System.Collections.Generic;
using modelo.Domain.Services;
namespace modelo.Application.UseCases.PedidoUseCase
{
public class PostPedidoUseCaseAsync : IUseCaseAsync<PedidoPostRequest, Tuple<int, Guid>>
{
private readonly IPedidoGateway _pedidoGateway;
private readonly IPagamentoGateway _pagamentoGateway;
private readonly IProdutoGateway _produtoGateway;
private readonly IClienteGateway _clienteGateway;
private readonly IIdentityService _identityService;
private readonly IMapper _mapper;
public PostPedidoUseCaseAsync(
IPedidoGateway pedidoGateway,
IMapper mapper,
IPagamentoGateway pagamentoGateway,
IProdutoGateway produtoGateway,
IClienteGateway clienteGateway,
IIdentityService identityService)
{
_pedidoGateway = pedidoGateway;
_mapper = mapper;
_pagamentoGateway = pagamentoGateway;
_produtoGateway = produtoGateway;
_clienteGateway = clienteGateway;
_identityService = identityService;
}
public async Task<Tuple<int, Guid>> ExecuteAsync(PedidoPostRequest request)
{
if (request.Produtos == null || request.Produtos.Count == 0)
throw new ArgumentException("Dados do pedido são inválidos");
var pedido = new Pedido();
pedido.AddPagamento(request.Pagamento.Tipo);
foreach (var item in request.Produtos)
{
var produto = await _produtoGateway.GetAsync(item.ProdutoId);
if (produto == null)
throw new KeyNotFoundException("Produto não encontrado");
var itemPedido = new ItemPedido(pedido.Id, item.ProdutoId, item.Observacao);
pedido.AddItemPedido(itemPedido);
}
var userId = _identityService.GetUserId();
if (!string.IsNullOrEmpty(userId))
{
var cliente = await _clienteGateway.GetByUserIdAsync(userId);
pedido.Cliente = cliente;
}
pedido = await _pedidoGateway.AddAsync(pedido);
return new Tuple<int, Guid>(pedido.Senha, pedido.Pagamento.Id);
}
}
}
|
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Vitesse maximale autorisée</title>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
background-color: #000000;
color: gray;
}
#speed {
font-size: 80px;
font-weight: bold;
margin-top: 50px;
color: #ffffff;
}
#position {
font-size: 10px;
font-weight: bold;
margin-top: 50px;
}
#refresh {
font-size: 8px;
margin-top: 10px;
}
#radar {
font-size: 25px;
margin-top: 10px;
color: #ffffff;
}
#slider{
font-size: 15px;
margin-top: 12px;
}
#signature {
font-size: 10px;
margin-top: 10px;
}
</style>
</head>
<body>
<h1>Vitesse maximale autorisée</h1>
<div id="speed">-- km/h</div>
<div id="position">pos: --</div>
<div id="radar">--</div>
<!-- Slider for radar detection range / Curseur pour la distance de détection des radars -->
<div id="slider">
<input type="range" min="200" max="10000" value="1000" step="100" class="slider" id="myRange">
<p>Distance recherche radar: <span id="demo"></span></p>
</div>
<div id="signature">by Stéphane Roddier sroddier@gmail.com <br> openstreetmap.org</div>
<div id="refresh">--</div>
<script>
// Global variables for DOM elements / Variables globales pour les éléments DOM
const radarDetectionSlider = document.getElementById('myRange');
const speedDiv = document.getElementById('speed');
const positionDiv = document.getElementById('position');
const radarDiv = document.getElementById('radar');
const refreshDiv = document.getElementById('refresh');
const demoDiv = document.getElementById('demo');
const overpassApiUrl = 'https://overpass-api.de/api/interpreter';
// Fetch speed limit from Overpass API / Récupérer la limite de vitesse de l'API Overpass
async function fetchSpeedLimit(latitude, longitude) {
const query = `
[out:json];
way[highway](around:25, ${latitude}, ${longitude});
out body;
`;
const response = await fetch(overpassApiUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: `data=${encodeURIComponent(query)}`
});
return await response.json();
}
// Fetch radar data from Overpass API / Récupérer les données du radar de l'API Overpass
async function fetchRadar(latitude, longitude, distance) {
const query = `
[out:json];
nwr[highway=speed_camera](around:${distance}, ${latitude}, ${longitude});
out body;
`;
const response = await fetch(overpassApiUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: `data=${encodeURIComponent(query)}`
});
return await response.json();
}
// Extract max speed from OSM data / Extraire la vitesse maximale
// des données OSM
function getMaxSpeedFromOsmData(osmData) {
if (osmData && osmData.elements) {
for (const element of osmData.elements) {
if (element.tags && element.tags.maxspeed) {
return parseInt(element.tags.maxspeed, 10);
}
}
}
return null;
}
// Extract radar data from OSM data / Extraire les données du radar des données OSM
function getRadar(osmData) {
if (osmData && osmData.elements) {
for (const element of osmData.elements) {
if (element.tags && element.tags.maxspeed) {
return parseInt(element.tags.maxspeed, 10);
}
if (element.tags && element.tags.direction) {
return element.tags.ref+" (Radar feux ?)";
}
}
}
return null;
}
// Update speed and radar data / Mettre à jour les données de vitesse et du radar
async function updateSpeed() {
refreshDiv.innerText = 'rafraichissement';
navigator.geolocation.getCurrentPosition(async position => {
const latitude = position.coords.latitude;
const longitude = position.coords.longitude;
try {
const osmData = await fetchSpeedLimit(latitude, longitude);
const maxSpeed = getMaxSpeedFromOsmData(osmData);
const radarDetectionDistance = document.getElementById('myRange').value;
const osmData2 = await fetchRadar(latitude, longitude, radarDetectionDistance);
const maxSpeedRadar = getRadar(osmData2);
if (maxSpeed) {
document.getElementById('speed').innerText = `${maxSpeed} km/h`;
document.getElementById('position').innerText = `${latitude},${longitude}`;
} else {
document.getElementById('speed').innerText = `Inconnu`;
document.getElementById('position').innerText = `${latitude},${longitude}`;
}
if (maxSpeedRadar){
document.getElementById('radar').innerText = `Radar : ${maxSpeedRadar}`;
}else{document.getElementById('radar').innerText = `--`; }
} catch (error) {
console.error(error);
document.getElementById('speed').innerText = 'Erreur';
}
document.getElementById('refresh').innerText = '';
});
}
//debut de partie maintien ecran allumé
let wakeLock = null;
// Fonction pour demander le verrouillage de veille
const requestWakeLock = async () => {
try {
wakeLock = await navigator.wakeLock.request('screen');
wakeLock.addEventListener('release', () => {
console.log('Wake Lock a été libéré');
});
console.log('Wake Lock est actif');
} catch (err) {
console.error(`${err.name}, ${err.message}`);
}
};
// Lorsque l'onglet devient inactif, tentez de demander à nouveau le verrouillage de veille.
document.addEventListener('visibilitychange', () => {
if (wakeLock !== null && document.visibilityState === 'visible') {
requestWakeLock();
}
});
// Demandez le verrouillage de veille au chargement de la page
window.addEventListener('load', requestWakeLock);
//fin de partie maintien ecran allumé
updateSpeed();
// Update the displayed radar detection distance / Mettre à jour la distance de détection du radar affichée
let slider = document.getElementById("myRange");
let output = document.getElementById("demo");
output.innerHTML = slider.value;
slider.oninput = function() {
output.innerHTML = this.value;
}
// Update speed and radar data every 4 seconds / Mettre à jour les données de vitesse et du radar toutes les 4 secondes
setInterval(updateSpeed, 4000);
</script>
</body>
</html>
|
package com.simon.seckill.exception;
import com.simon.seckill.vo.RespBean;
import com.simon.seckill.vo.RespBeanEnum;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
/**
* 全局异常处理类
*/
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class)
public RespBean ExceptionHandler(Exception e) {
if (e instanceof GlobalException) {
GlobalException globalException = (GlobalException) e;
return RespBean.error(globalException.getRespBeanEnum());
} else if (e instanceof BindException) { // 绑定异常
// 注意是在BindException是在validation包下的,不是在net包
BindException bindException = (BindException) e;
RespBean respBean = RespBean.error(RespBeanEnum.BIND_ERROR);
// 获得控制台的异常信息(先获取所有信息,再获取第一个错误信息)
respBean.setMessage("参数校验异常:" + bindException.getBindingResult().getAllErrors().get(0).getDefaultMessage());
return respBean;
}
return RespBean.error(RespBeanEnum.ERROR);
}
}
|
import java.util.*;
import java.io.*;
public class Course implements Comparable<Course> {
int index;
int id;
int prefVal;
int timeslot;
Room room;
Teacher teacher;
ArrayList<Integer> stuInClass;
Department department;
public Course(int id, int prefVal, int index) {
this.id = id;
this.prefVal = prefVal;
this.index = index;
this.timeslot = 0;
this.room = null;
this.stuInClass = new ArrayList<Integer>(1);
}
public void setIndex(int i) {
this.index = i;
}
public void addDepartment(Department department){
this.department = department;
}
public Department getDepartment(){
return this.department;
}
public int getIndex() {
return this.index;
}
public void setTeacher(Teacher t) {
this.teacher = t;
}
public Teacher getTeacher() {
return this.teacher;
}
public void incrementPeople(int stuId){
stuInClass.add((Integer)stuId);
}
public int sizeofStudents(){
return stuInClass.size();
}
public void setRoom(Room room) {
this.room = room;
}
public Room getRoom() {
return this.room;
}
public void setTime(int time) {
this.timeslot = time;
}
public int getTime() {
return this.timeslot;
}
public int getId() {
return this.id;
}
public int getPrefVal() {
return this.prefVal;
}
public void setId(int id) {
this.id = id;
}
public void setPrefVal(int prefVal) {
this.prefVal = prefVal;
}
public void incrPrefVal() {
this.prefVal++;
}
public String toString() {
return "Course id: " + this.id + " index: " + this.index + " " + " prefVal: " + this.prefVal;
//return "Course " + this.id + " has the students: " + this.prefVal;
}
public String studentsInClass(){
String str = String.format("\t");
for(int i = 0; i<stuInClass.size(); i++){
str += String.format("%d ", stuInClass.get(i));
if (i%30==0 && i!=0) {str += String.format("\n\t\t\t\t\t\t");}
}
return str;
}
public int compareTo(Course b) {
if (this.getPrefVal() > b.getPrefVal()) {
return 1;
}
else if (this.getPrefVal() < b.getPrefVal()) {
return -1;
}
else {
return 0;
}
}
}
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Prog209 Course Project</title>
<link rel="stylesheet" href="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css" />
<link rel="stylesheet" href="/public/stylesheets/index.css">
<script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
<script src="/public/javascripts/index.js"></script>
</head>
<body>
<!-- Start of Home page -->
<div data-role="page" id="home">
<!-- Home page header -->
<div data-role="header" data-theme='b'>
<h1>Open Concept Interior Design</h1>
<div data-role="navbar" data-grid="c">
<ul>
<li><a href="#home" class="ui-button-active">Home</a></li>
<li><a href="#services">Services</a></li>
<li><a href="#contact">Contact Us</a></li>
<li><a href="#appointments">Appointments</a></li>
</ul>
</div>
</div>
<!-- Home page content -->
<div data-role="content" data-theme='b'>
<h2>Welcome to my interior design website. This website was inspired by
the interior design business that I'm starting for my Business class at
Bellevue college. When this website is finished it will display a list of services,
display customer reviews, intake new reviews, and allow prospective
customers to schedule a call with one our interior design consultants.
</h2>
</div>
<!-- Home page footer -->
<div data-role="footer" data-theme='b'>
<h4>Copyrigtht 2020 by Alejandra Valencia</h4>
</div>
</div>
<!-- Start of services page -->
<div data-role="page" id="services">
<!-- services page header -->
<div data-role="header" data-theme='b'>
<h1>Services</h1>
<div data-role="navbar" data-grid="c">
<ul>
<li><a href="#home">Home</a></li>
<li><a href="#services">Services</a></li>
<li><a href="#contact">Contact Us</a></li>
<li><a href="#appointments">Appointments</a></li>
</ul>
</div>
</div>
<!-- services page page content -->
<div data-role="content" data-theme='b'>
<p>Choose a service</p>
<!--<div class="btn-group">-->
<a href="#contact"><button id="kitchen" >Kitchen</button></a>
<!-- Slideshow container -->
<div class="slideshow-container">
<div class="mySlides1">
<img src="../images/kitchen1.jpg" style="width:100%">
</div>
<div class="mySlides1">
<img src="../images/kitchen2.jpg" style="width:100%">
</div>
<!-- Next and previous buttons -->
<a class="prev" onclick="plusSlides(-1, 0)">❮</a>
<a class="next" onclick="plusSlides(1, 0)">❯</a>
</div>
<br>
<!-- End of slideshow container -->
<a href="#contact"><button id="bathroom">Bathroom</button></a>
<!-- Slideshow container -->
<div class="slideshow-container">
<div class="mySlides2">
<img src="../images/bath1.jpg" style="width:100%">
</div>
<div class="mySlides2">
<img src="../images/bath2.jpg" style="width:100%">
</div>
<!-- Next and previous buttons -->
<a class="prev" onclick="plusSlides(-1, 1)">❮</a>
<a class="next" onclick="plusSlides(1, 1)">❯</a>
</div>
<br>
<!-- End of slideshow container -->
</div>
<!-- services page page footer -->
<div data-role="footer" data-theme='b'>
<h4>Copyrigtht 2020 by Alejandra Valencia</h4>
</div>
</div>
<!-- start of contact page -->
<div data-role="page" id="contact">
<!-- contact page header -->
<div data-role="header" data-theme='b'>
<h1>Contact Us</h1>
<div data-role="navbar" data-grid="c">
<ul>
<li><a href="#home">Home</a></li>
<li><a href="#services">Services</a></li>
<li><a href="#contact">Contact Us</a></li>
<li><a href="#appointments">Appointments</a></li>
</ul>
</div>
</div>
<!-- contact page content -->
<div data-role="content" data-theme='b'>
<p>Submit the form below to schedule a consultation</p>
Name <br />
<input type="text" value="" id="name" />
Email <br />
<input type="text" value="" id="email" />
Phone<br />
<input type="number" value="" id="phone" />
Date <br />
<input type="date" value="" id="date" />
Time <br />
<input type="time" value="" id="time" />
<!-- submit & clear btns -->
<a href="#appointments" data-role="button" data-theme="a" id="buttonAdd" data-inline="true">Submit</a>
<input type="button" value="Clear" id="buttonClear" data-inline="true" />
</div>
<!-- contact page footer -->
<div data-role="footer" data-theme='b'>
<h4>Copyrigtht 2020 by Alejandra Valencia</h4>
</div>
</div>
<!-- Start of appointment page -->
<div data-role="page" id="appointments">
<!-- review page header -->
<div data-role="header" data-theme='b'>
<h1>Appointments</h1>
<div data-role="navbar" data-grid="c">
<ul>
<li><a href="#home">Home</a></li>
<li><a href="#services">Services</a></li>
<li><a href="#contact">Contact Us</a></li>
<li><a href="#appointments">Appointments</a></li>
</ul>
</div>
</div>
<!-- review appointment list content -->
<div data-role="content" data-theme='b'>
<p>we're in the appointment list</p>
<div>
<p id="IDparmHere" hidden>change1</p> <!-- hidden a place to stash the movie title -->
</div>
<input type="button" value="Sort By Date" id="buttonSortGenre" data-inline="true" />
<br />
<br />
</div>
<!-- contact page footer -->
<div data-role="footer" data-theme='b'>
<h4>Copyrigtht 2020 by Alejandra Valencia</h4>
</div>
</div>
<!-- Start of page -->
<div data-role="page" id="detailPage">
<!-- page header -->
<div data-role="header" data-theme='a'>
<h1>My Movies</h1>
<div data-role="header" data-theme='b'>
<h1>Appointments</h1>
<div data-role="navbar" data-grid="c">
<ul>
<li><a href="#home">Home</a></li>
<li><a href="#services">Services</a></li>
<li><a href="#contact">Contact Us</a></li>
<li><a href="#appointments">Appointments</a></li>
</ul>
</div>
</div>
</div>
<!-- content -->
<div data-role="content" data-theme='d'>
<div>
<p id="IDparmHere" hidden>change1</p> <!-- hidden a place to stash the movie title -->
<p class="bold" > Here are the details</p>
<p> <span class="bold"> Name: </span> <span id="oneName" </span> </p>
<p><span class="bold"> Email: </span> <span id="oneEmail" </span> </p>
<p><span class="bold"> Phone: </span> <span id="onePhone" </span> </p>
<p><span class="bold"> Date: </span> <span id="oneDate" </span> </p>
<p><span class="bold"> Time: </span> <span id="oneTime" </span> </p>
</div>
</div>
<!-- footer -->
<div data-role="footer" data-theme='a'>
<h1>Copyrigtht 2020 by Kurt Friedrich</h1>
</div>
</div>
<!-- Start of page -->
<div data-role="page" id="refreshPage">
<!-- content -->
<div data-role="content" >
<!-- this page is used to to jump to and then back to a page to force a pagebeforeload event -->
</div>
</div>
</body>
</html>
|
from keras.models import load_model
import cv2
import numpy as np
from functions import ocr
class ImageClassifier:
def __init__(self, model_path, labels_path):
self.model = load_model(model_path, compile=False)
self.class_names = open(labels_path, "r").readlines()
def preprocess_image(self, image_path):
img = cv2.imread(image_path)
img = cv2.resize(img, (224, 224), interpolation=cv2.INTER_AREA)
img = np.asarray(img, dtype=np.float32).reshape(1, 224, 224, 3)
img = (img / 127.5) - 1
return img
def predict(self, image_path):
processed_image = self.preprocess_image(image_path)
prediction = self.model.predict(processed_image)
index = np.argmax(prediction)
class_name = self.class_names[index]
confidence_score = prediction[0][index]
return class_name[2:], confidence_score
def class_handler(class_name, imgPath):
if class_name.rstrip('\n') == 'Judul_Lagu':
ocrString = ocr.perform_ocr(imgPath)
print(f"Img Text ==> {ocrString}")
else:
pass
def main():
model_path = "model/keras_model.h5"
labels_path = "model/labels.txt"
classifier = ImageClassifier(model_path, labels_path)
while True:
image_path = input("Enter the path of the image (or 'exit' to end): ")
if image_path.lower() == 'exit':
break # Exit the loop if the user enters 'exit'
try:
class_name, confidence_score = classifier.predict(image_path)
output_string = f"Class: {class_name}Confidence Score: {str(np.round(confidence_score * 100))[:-2]}%"
print(output_string)
class_handler(class_name, image_path)
except Exception as e:
print(f"Error processing image: {e}")
if __name__ == "__main__":
main()
|
import { Type } from 'class-transformer';
import {
IsEmail,
IsNumberString,
IsString,
Matches,
IsOptional,
IsNotEmpty,
MinLength,
IsNumber,
ValidateNested,
} from 'class-validator';
import { AddressDto, updateAddressDTO } from './addressDto';
export class updateEmployeeDTO {
id: number;
@IsOptional()
first_name: string;
@IsOptional()
last_name: string;
@ValidateNested()
@Type(() => updateAddressDTO)
addressData: updateAddressDTO;
@IsEmail()
@IsOptional()
email: string;
@IsOptional()
@IsString()
@Matches(/^\d{10}$/)
phone_no: string;
@IsOptional()
@IsNumberString()
salary: string;
@IsOptional()
@IsString()
@Matches(/^(?=.*[A-Z])(?=.*[a-z])(?=.*\d)(?=.*[!@#$%^&*()]).{8,}$/)
password: string;
}
|
# プログラミング入門_06
1点相関の分布図
[[_TOC_]]
## 概要
## 準備
```bash
$ cd $HOME
```
```bash
$ cd 2022_PROGRAM
```
```bash
$ mkdir -vp 06
```
```bash
$ cd 06
```
```bash
$ pwd
/work03/gu1/LAB/2022_PROGRAM/06
```
```bash
$ ift
```
もしくは,
```bash
$ source /opt/intel/oneapi/setvars.sh --force
```
### 入力データの構造
```
dset ^hgt.season.1958-2005.BIN
title Z500 DJF NCEP1
undef -9.96921e+36
xdef 144 linear 0 2.5
ydef 73 linear -90 2.5
zdef 1 linear 0 1
tdef 48 linear 00Z01JAN1958 12mo
vars 1
z500 0 99 GPH 500 hPa [m]
endvars
```
経度方向144個,緯度方向73個のデータが各時刻ごとに48個並んでいる
ダイレクト・アクセスで読む
レコード長は, 144x73x4
## プログラム作成
### 入力部
#### プログラム作成
`vi READ_Z500_DJF.f90`
`i`
```FORTRAN
program READ_Z500_DJF
character INDIR*500,INFLE*500,IN*1000
integer::IM=144,JM=73,NM=48
real,allocatable::z(:,:,:)
INDIR="/work01/DATA/NCEP1/12.00.MON.2.SEASON"
!INDIR="/work03/gu1/LAB/2022_PROGRAM/12.12.NCEP_PREPRO/12.00.MON.2.SEASON"
INFLE="hgt.season.1958-2005.BIN"
IN=trim(INDIR)//"/"//trim(INFLE)
allocate(z(IM,JM,NM))
isize=IM*JM*4
open(11,file=IN,action="read",form="unformatted",access="direct",&
recl=isize)
irec=0
do n=1,NM
irec=irec+1
print *,irec
read(11,rec=irec)Z(:,:,n)
end do !n
end program READ_Z500_DJF
```
`Esc`
`:wq`
```bash
$ ifort -assume byterecl 12.00.READ.Z500.DJF.f90 -o READ.Z500.DJF.exe
```
#### 参考
`-assume byterecl`
ifortのダイレクトアクセスのレコード長(open文で recl= で設定する値) の単位は, デフォルトでは,「ワード 」と呼ばれる量である。1ワード=4バイトである。
一般的な「バイト」単位でレコード長を指定するには, コンパイルオプション `-assume byterecl` を指定する必要がある.
#### 実行
```
$ READ.Z500.DJF.exe
```
#### エラーが出た時の対応
##### エラー箇所の特定
```
$ ifort -traceback -assume byterecl 12.00.READ.Z500.DJF.f90 -o READ.Z500.DJF.exe
```
### 計算
#### プログラム作成
```bash
$ cp 12.00.READ.Z500.DJF.f90 14.00.CALC.R1P.f90
```
```bash
$ vi 14.00.CALC.R1P.f90
```
```fortran
program CALC_R1P
character INDIR*500,INFLE*500,IN*1000
integer::IM=144,JM=73,NM=48
real,allocatable::z(:,:,:),CORR(:,:)
real,allocatable,dimension(:)::Z0, Z1,Z0_AN,Z1_AN
integer I0,J0
INDIR="/work01/DATA/NCEP1/12.00.MON.2.SEASON"
!INDIR="/work03/gu1/LAB/2022_PROGRAM/12.12.NCEP_PREPRO/12.00.MON.2.SEASON"
INFLE="hgt.season.1958-2005.BIN"
IN=trim(INDIR)//"/"//trim(INFLE)
allocate(z(IM,JM,NM), Z0(NM), Z1(NM), Z0_AN(NM), Z1_AN(NM))
allocate(CORR(IM,JM))
I0=INT(200/2.5); J0=INT(110/2.5)
! 160W=200E
! 20N=110 (LAT OF SP := -90)
print *,"I0=",I0,"J0=",J0
isize=IM*JM*4
open(11,file=IN,action="read",form="unformatted",access="direct",&
recl=isize)
irec=0
do n=1,NM
irec=irec+1
read(11,rec=irec)Z(:,:,n)
end do !n
close(21)
Z0(:)=Z(I0,J0,:)
! print *,Z0
Z0_AV=SUM(Z0)/FLOAT(NM)
Z0_AN(:)=Z0(:)-Z0_AV
do j=1,JM
do i=1,IM
Z1(:)=Z(I,J,:)
Z1_AV=SUM(Z1)/FLOAT(NM)
Z1_AN(:)=Z1(:)-Z1_AV
Z0_DOT_Z1 = DOT_PRODUCT(Z0_AN, Z1_AN)
Z0MAG2 = DOT_PRODUCT(Z0_AN, Z0_AN)
Z1MAG2 = DOT_PRODUCT(Z1_AN, Z1_AN)
Z0MAG=SQRT(Z0MAG2)
Z1MAG=SQRT(Z1MAG2)
CORR(i,j)=Z0_DOT_Z1/(Z0MAG*Z1MAG)
print *,I,J,Z0_DOT_Z1,Z0MAG,Z1MAG,CORR(i,j)
end do !i
end do !j
end program CALC_R1P
```
```bash
$ ifort -assume byterecl 14.00.CALC.R1P.f90 -o 14.00.CALC.R1P.exe
```
```bash
$ 14.00.CALC.R1P.exe
```
### 出力
```bash
$ cp 14.00.CALC.R1P.f90 16.00.ONE_PNT_CORR.f90
```
`$ vi 14.00.CALC.R1P.f90`
`i`
```Fortran
program CALC_R1P
character INDIR*500,INFLE*500,IN*1000, OFLE*500
integer::IM=144,JM=73,NM=48
real,allocatable::z(:,:,:),CORR(:,:)
real,allocatable,dimension(:)::Z0, Z1,Z0_AN,Z1_AN
integer I0,J0
INDIR="/work01/DATA/NCEP1/12.00.MON.2.SEASON"
!INDIR="/work03/gu1/LAB/2022_PROGRAM/12.12.NCEP_PREPRO/12.00.MON.2.SEASON"
INFLE="hgt.season.1958-2005.BIN"
IN=trim(INDIR)//"/"//trim(INFLE)
OFLE="hgt.DJF.CORR.BIN"
allocate(z(IM,JM,NM), Z0(NM), Z1(NM), Z0_AN(NM), Z1_AN(NM))
allocate(CORR(IM,JM))
I0=INT(200/2.5); J0=INT(110/2.5)
! 160W=200E
! 20N=110 (LAT OF SP := -90)
print *,"I0=",I0,"J0=",J0
isize=IM*JM*4
open(11,file=IN,action="read",form="unformatted",access="direct",&
recl=isize)
irec=0
do n=1,NM
irec=irec+1
read(11,rec=irec)Z(:,:,n)
end do !n
Z0(:)=Z(I0,J0,:)
! print *,Z0
Z0_AV=SUM(Z0)/FLOAT(NM)
Z0_AN(:)=Z0(:)-Z0_AV
do j=1,JM
do i=1,IM
Z1(:)=Z(I,J,:)
Z1_AV=SUM(Z1)/FLOAT(NM)
Z1_AN(:)=Z1(:)-Z1_AV
Z0_DOT_Z1 = DOT_PRODUCT(Z0_AN, Z1_AN)
Z0MAG2 = DOT_PRODUCT(Z0_AN, Z0_AN)
Z1MAG2 = DOT_PRODUCT(Z1_AN, Z1_AN)
Z0MAG=SQRT(Z0MAG2)
Z1MAG=SQRT(Z1MAG2)
CORR(i,j)=Z0_DOT_Z1/(Z0MAG*Z1MAG)
!print *,I,J,Z0_DOT_Z1,Z0MAG,Z1MAG,CORR(i,j)
end do !i
end do !j
open(21,file=OFLE,form="unformatted",access="direct",&
recl=isize)
irec=1
write(21,rec=irec)CORR
close(21)
print *;print '(A,A)','OUTPUT: ',trim(OFLE)
end program CALC_R1P
```
```bash
$ ifort -assume byterecl 16.00.ONE_PNT_CORR.f90 -o ONE_PNT_CORR.exe
```
```
$ ONE_PNT_CORR.exe
```
I0= 80 J0= 44
OUTPUT: hgt.DJF.CORR.BIN
### 作図
```bash
$ vi 16.02.CHK.CORR.sh
```
```bash
#!/bin/bash
CTL=hgt.DJF.CORR.CTL
GS=$(basename $0 .sh).GS
RLON=200;RLAT=20
LATS=0 ;LATN=90
FIG=$(basename $CTL .CTL).eps
HOST=$(hostname);CWD=$(pwd);NOW=$(date -R);CMD="$0 $@"
cat << EOF > ${GS}
'open ${CTL}'
xmax = 1;ymax = 1
ytop=9
xwid = 5.0/xmax;ywid = 5.0/ymax
xmargin=0.5;ymargin=0.1
nmap = 1
ymap = 1
#while (ymap <= ymax)
xmap = 1
#while (xmap <= xmax)
xs = 1.5 + (xwid+xmargin)*(xmap-1);xe = xs + xwid
ye = ytop - (ywid+ymargin)*(ymap-1);ys = ye - ywid
# SET PAGE
'set vpage 0.0 8.5 0.0 11'
'set parea 'xs ' 'xe' 'ys' 'ye
'cc'
# 'set lon ${LONW} ${LONE}'
'set lat ${LATS} ${LATN}'
# 'set lev ${LEV}'
'set t 1'
'set mproj nps'; 'set frame off'; 'set grid on 1 1'
'set ylint 90'; 'set xlint 30'
'set gxout contour'
'd R'
'markplot $RLON $RLAT -m 3 -s 0.1 -c 1'
'circlon 30'
#'circlat 30 90 0.18'
# GET COORDINATES OF 4 CORNERS
'q gxinfo'
line3=sublin(result,3); line4=sublin(result,4)
xl=subwrd(line3,4); xr=subwrd(line3,6)
yb=subwrd(line4,4); yt=subwrd(line4,6)
# HEADER
'set strsiz 0.12 0.14'; 'set string 1 l 3 0'
xx = 0.2
yy=yt+0.5; 'draw string ' xx ' ' yy ' ${FIG}'
yy = yy+0.2; 'draw string ' xx ' ' yy ' ${CMD}'
yy = yy+0.2; 'draw string ' xx ' ' yy ' ${NOW}'
yy = yy+0.2; 'draw string ' xx ' ' yy ' ${HOST}'
yy = yy+0.2; 'draw string ' xx ' ' yy ' ${CWD}'
'gxprint ${FIG}'
'quit'
EOF
grads -bcp "$GS"
rm -vf $GS
echo
if [ -f $FIG ]; then
echo "OUTPUT : "
ls -lh --time-style=long-iso $FIG
fi
echo
echo "DONE $0."
echo
```
```bash
$ 16.02.CHK.CORR.sh
.....
OUTPUT :
-rw-r--r--. 1 gu1 oc 203K 2022-06-10 07:10 hgt.DJF.CORR.eps
```
## 付録
**以下は参考資料**。上記のプログラム実行に必須のものもではない。
入力データ作成に使ったスクリプト (NCAR COMMAND LANGUAGE使用)
12.00.CREATE.1958-2005.DJF.Z500.ncl
```
INFLE="hgt.mon.mean.nc"
OFLE="hgt.season.1958-2005.nc"
f = addfile(INFLE, "r")
print(f)
lev=f->level
dim=dimsizes(lev)
nk=dim(0)
delete(dim)
do k=0,nk-1
if(lev(k).eq.500.)then
print("lev(k)="+lev(k))
kdx=k
end if
end do
time=f->time
utc_date=cd_calendar(time,0)
year = tointeger(utc_date(:,0)) ; Convert to integer for
month = tointeger(utc_date(:,1)) ; use sprinti
dim=dimsizes(time)
nt=dim(0)
delete(dim)
ys=1958
ms=1
ye=2005
me=12
do n=0,nt-1
if(year(n).eq.ys .and. month(n).eq.ms)then
print(year(n)+" "+month(n))
ndx0=n
end if
if(year(n).eq.ye .and. month(n).eq.me)then
print(year(n)+" "+month(n))
ndx1=n
end if
end do
z=f->hgt
z_cut=z(ndx0:ndx1,kdx,:,:)
z_sea = month_to_season(z_cut, "DJF")
printVarSummary(z_sea)
system("rm -f "+OFLE)
out = addfile(OFLE,"c")
out->z500=z_sea
system("ls -lh --time-style=long-iso "+OFLE)
```
14.00.CHK.Z500.ncl (NCAR COMMAND LANGUAGE使用)
```
INFLE="hgt.season.1958-2005.nc"
f = addfile(INFLE, "r")
time=f->time
utc_date=cd_calendar(time,0)
year = tointeger(utc_date(:,0)) ; Convert to integer for
month = tointeger(utc_date(:,1)) ; use sprinti
dim=dimsizes(time)
nt=dim(0)
delete(dim)
print(year(0)+" "+month(0))
print(year(nt-1)+" "+month(nt-1))
z=f->z500
z1=z(0,:,:)
;printVarSummary(z1)
FIG="Z500_DJF_TEST_1958"
TYP="eps"
wks = gsn_open_wks(TYP, FIG)
res = True ; plot mods desired
res@gsnPolar = "NH" ; specify the hemisphere
plot=gsn_csm_contour_map_polar(wks,z1(:,:),res)
```
16.00.NC2BIN.sh (GrADS使用)
```
#!/bin/bash
# Thu, 09 Jun 2022 22:16:53 +0900
# p5820.bio.mie-u.ac.jp
# /work03/gu1/LAB/2022_PROGRAM/12.12.NCEP_PREPRO/12.00.MON.2.SEASON
GS=$(basename $0 .sh).GS
INFLE=hgt.season.1958-2005.nc
BIN=$(basename $INFLE .nc).BIN
rm -f $BIN
HOST=$(hostname); CWD=$(pwd); NOW=$(date -R); CMD="$0 $@"
cat << EOF > ${GS}
# Thu, 09 Jun 2022 22:16:53 +0900
# p5820.bio.mie-u.ac.jp
# /work03/gu1/LAB/2022_PROGRAM/12.12.NCEP_PREPRO/12.00.MON.2.SEASON
'sdfopen ${INFLE}'
'q ctlinfo'; say result
'set x 1 144'
'set t 1 48'
'set fwrite $BIN'
'set gxout fwrite'
'd z500'
'disable fwrite'
'quit'
EOF
grads -bcp "$GS"
rm -vf $GS
ls -lh $BIN
```
16.02.CHK.BIN.sh (GrADS使用)
```
#!/bin/bash
# Thu, 09 Jun 2022 22:25:39 +0900
# p5820.bio.mie-u.ac.jp
# /work03/gu1/LAB/2022_PROGRAM/12.12.NCEP_PREPRO/12.00.MON.2.SEASON
CTL=hgt.season.1958-2005.CTL
GS=$(basename $0 .sh).GS
# LONW= ;LONE=
LATS=0 ;LATN=90; T=48
# LEV=
# TIME=
FIG=$(basename $0 .sh)_T_${T}.eps
# LEVS="-3 3 1"
# LEVS=" -levs -3 -2 -1 0 1 2 3"
# KIND='midnightblue->deepskyblue->lightcyan->white->orange->red->crimson'
# FS=2
# UNIT=
HOST=$(hostname);CWD=$(pwd);NOW=$(date -R);CMD="$0 $@"
cat << EOF > ${GS}
# Thu, 09 Jun 2022 22:25:39 +0900
# p5820.bio.mie-u.ac.jp
# /work03/gu1/LAB/2022_PROGRAM/12.12.NCEP_PREPRO/12.00.MON.2.SEASON
'open ${CTL}'
xmax = 1;ymax = 1
ytop=9
xwid = 5.0/xmax;ywid = 5.0/ymax
xmargin=0.5;ymargin=0.1
nmap = 1
ymap = 1
#while (ymap <= ymax)
xmap = 1
#while (xmap <= xmax)
xs = 1.5 + (xwid+xmargin)*(xmap-1);xe = xs + xwid
ye = ytop - (ywid+ymargin)*(ymap-1);ys = ye - ywid
# SET PAGE
'set vpage 0.0 8.5 0.0 11'
'set parea 'xs ' 'xe' 'ys' 'ye
'cc'
# SET COLOR BAR
# 'color ${LEVS} -kind ${KIND} -gxout shaded'
# 'set lon ${LONW} ${LONE}'
'set lat ${LATS} ${LATN}'
# 'set lev ${LEV}'
'set t $T'
'set mproj nps'
'set gxout contour'
'd z500'
'circlon 30'
#'circlat 30 90 0.18'
# GET COORDINATES OF 4 CORNERS
'q gxinfo'
line3=sublin(result,3); line4=sublin(result,4)
xl=subwrd(line3,4); xr=subwrd(line3,6)
yb=subwrd(line4,4); yt=subwrd(line4,6)
# LEGEND COLOR BAR
#x1=xl; x2=xr
#y1=yb-0.5; y2=y1+0.1
#'xcbar 'x1' 'x2' 'y1' 'y2 ' -fw 0.1 -fh 0.13 -fs $FS -ft 3 -line on -edge circle'
#x=xr
#y=y1
#'set strsiz 0.12 0.15'
#'set string 1 r 3 0'
#'draw string 'x' 'y' ${UNIT}'
# TEXT
#x=xl ;# (xl+xr)/2;
#y=yt+0.2
#'set strsiz 0.12 0.15'
#'set string 1 c 3 0'
#'draw string 'x' 'y' ${TEXT}'
# HEADER
'set strsiz 0.12 0.14'
'set string 1 l 3 0'
xx = 0.2
yy=yt+0.5
'draw string ' xx ' ' yy ' ${FIG}'
yy = yy+0.2
'draw string ' xx ' ' yy ' ${CMD}'
yy = yy+0.2
'draw string ' xx ' ' yy ' ${NOW}'
yy = yy+0.2
'draw string ' xx ' ' yy ' ${HOST}'
yy = yy+0.2
'draw string ' xx ' ' yy ' ${CWD}'
'gxprint ${FIG}'
'quit'
EOF
grads -bcp "$GS"
# rm -vf $GS
echo
if [ -f $FIG ]; then
echo "OUTPUT : "
ls -lh --time-style=long-iso $FIG
fi
echo
echo "DONE $0."
echo
```
18.00.NC2BIN_1PNT.sh (GrADS使用)
```
#!/bin/bash
# Thu, 09 Jun 2022 22:16:53 +0900
# p5820.bio.mie-u.ac.jp
# /work03/gu1/LAB/2022_PROGRAM/12.12.NCEP_PREPRO/12.00.MON.2.SEASON
GS=$(basename $0 .sh).GS
INFLE=hgt.season.1958-2005.nc
#LON=-165;LAT=20
LON=-165;LAT=50
BIN=$(basename $INFLE .nc)_${LAT}_${LON}.BIN
rm -f $BIN
HOST=$(hostname); CWD=$(pwd); NOW=$(date -R); CMD="$0 $@"
cat << EOF > ${GS}
# Thu, 09 Jun 2022 22:16:53 +0900
# p5820.bio.mie-u.ac.jp
# /work03/gu1/LAB/2022_PROGRAM/12.12.NCEP_PREPRO/12.00.MON.2.SEASON
'sdfopen ${INFLE}'
'q ctlinfo'; say result
'set lon ${LON}'
'set lat ${LAT}'
'set t 1 48'
'set fwrite $BIN'
'set gxout fwrite'
'd z500'
'disable fwrite'
'quit'
EOF
grads -bcp "$GS"
rm -vf $GS
ls -lh $BIN
```
18.02.CHK.BIN.1PNT.sh (GrADS使用)
```
#!/bin/bash
#CTL=hgt.season.1958-2005_20_-165.CTL
CTL=hgt.season.1958-2005_50_-165.CTL
GS=$(basename $0 .sh).GS
FIG=$(basename $CTL .CTL).eps
HOST=$(hostname);CWD=$(pwd);NOW=$(date -R);CMD="$0 $@"
cat << EOF > ${GS}
'open ${CTL}'
xmax = 1;ymax = 1
ytop=9
xwid = 5.0/xmax;ywid = 5.0/ymax
xmargin=0.5;ymargin=0.1
nmap = 1; ymap = 1; xmap = 1
xs = 1.5 + (xwid+xmargin)*(xmap-1);xe = xs + xwid
ye = ytop - (ywid+ymargin)*(ymap-1);ys = ye - ywid
# SET PAGE
'set vpage 0.0 8.5 0.0 11'
'set parea 'xs ' 'xe' 'ys' 'ye
'cc'
'set t 1 48'
'set gxout line'; 'set cmark 0'
'd z500'
# GET COORDINATES OF 4 CORNERS
'q gxinfo'
line3=sublin(result,3); line4=sublin(result,4)
xl=subwrd(line3,4); xr=subwrd(line3,6)
yb=subwrd(line4,4); yt=subwrd(line4,6)
# HEADER
'set strsiz 0.12 0.14'
'set string 1 l 3 0'
xx = 0.2
yy=yt+0.5
'draw string ' xx ' ' yy ' ${FIG}'
yy = yy+0.2
'draw string ' xx ' ' yy ' ${CMD}'
yy = yy+0.2
'draw string ' xx ' ' yy ' ${NOW}'
yy = yy+0.2
'draw string ' xx ' ' yy ' ${HOST}'
yy = yy+0.2
'draw string ' xx ' ' yy ' ${CWD}'
'gxprint ${FIG}'
'quit'
EOF
grads -bcp "$GS"
rm -vf $GS
echo
if [ -f $FIG ]; then
echo "OUTPUT : "
ls -lh --time-style=long-iso $FIG
fi
echo
echo "DONE $0."
echo
```
## 上達のためのポイント
**エラーが出た時の対応の仕方でプログラミングの上達の速度が大幅に変わる**。
ポイントは次の3つである
1. エラーメッセージをよく読む
2. エラーメッセージを検索し,ヒットしたサイトをよく読む
3. 変数に関する情報を書き出して確認する
エラーメッセージは,プログラムが不正終了した直接の原因とその考えられる理由が書いてあるので,よく読むことが必要不可欠である。
記述が簡潔なため,内容が十分に理解できないことも多いが,その場合**エラーメッセージをブラウザで検索**してヒットした記事をいくつか読んでみる。
エラーの原因だけでなく,**考えうる解決策**が記載されていることも良くある。
エラーを引き起こしていると思われる箇所の**変数の情報**や**変数の値そのものを書き出して**,**期待した通りにプログラムが動作しているか確認する**ことも重要である。
エラーの場所が特定できれば,エラーの修正の大部分は完了したと考えてもよいほどである。
エラーメッセージや検索してヒットするウェブサイトは英語で記載されていることも多いが,**重要な情報は英語で記載されていることが多い**ので,よく読むようにする。
重要そうに思われるが,一回で理解できないものは,PDFなどに書き出して後で繰り返し読んでみる。どうしても**内容が頭に入らないものは印刷してから読む**。
|
<?php
namespace App\Http\Livewire;
use App\Models\demoCity;
use App\Models\demoCompany;
use App\Models\demoCountry;
use App\Models\demoState;
use Livewire\Component;
class DemoCompanies extends Component
{
public $democountries;
public $demostates;
public $democities;
public $demoname;
public $selectedCountry = null;
public $selectedState = null;
public $selectedCity = null;
public $designTemplate = 'bootstrap';
public function mount()
{
$this->democountries = demoCountry::all();
$this->demostates = collect();
$this->democities = collect();
}
public function render()
{
return view('livewire.'. $this->designTemplate .'.demo-companies', [
'demo-companies' => demoCompany::with('city.state.country')->latest()->take(5)->get()
]);
// return view('livewire.demo-companies');
}
public function updatedSelectedCountry($value)
{
$this->demostate = demoState::where('country_id', $value)->get();
$this->selectedState = null;
}
public function updatedSelectedState($value)
{
if (!is_null($value)) {
$this->democity = demoCity::where('state_id', $value)->get();
}
}
public function storeCompany()
{
$this->validate([
'demoname' => 'required',
'selectedCity' => 'required',
]);
demoCompany::create([
'demoname' => $this->demoname,
'city_id' => $this->selectedCity,
]);
$this->demoname = '';
$this->selectedCountry = null;
$this->selectedState = null;
$this->selectedCity = null;
$this->demostate = collect();
$this->democity = collect();
}
}
|
# RDF::Query::Compiler::SQL
# -----------------------------------------------------------------------------
=head1 NAME
RDF::Query::Compiler::SQL - Compile a SPARQL query directly to SQL.
=head1 VERSION
This document describes RDF::Query::Compiler::SQL version 2.912.
=head1 STATUS
This module's API and functionality should be considered deprecated.
If you need functionality that this module provides,
please L<get in touch|http://www.perlrdf.org/>.
=cut
package RDF::Query::Compiler::SQL;
use strict;
use warnings;
no warnings 'redefine';
use RDF::Query::Error qw(:try);
use Log::Log4perl;
use List::Util qw(first);
use Data::Dumper;
use Math::BigInt;
use Digest::MD5 ('md5');
#use Digest::Perl::MD5 (); #('md5');
use Carp qw(carp croak confess);
use Scalar::Util qw(blessed reftype);
use RDF::Query::Error qw(:try);
######################################################################
my (@NODE_TYPE_TABLES, %NODE_TYPE_TABLES);
our ($VERSION);
BEGIN {
$VERSION = '2.912';
@NODE_TYPE_TABLES = (
['Resources', 'ljr', 'URI'],
['Literals', 'ljl', qw(Value Language Datatype)],
['Bnodes', 'ljb', qw(Name)]
);
%NODE_TYPE_TABLES = map { $_->[0] => [ @{ $_ }[1 .. $#{ $_ }] ] } @NODE_TYPE_TABLES;
}
######################################################################
use constant INDENT => "\t";
=head1 METHODS
=over 4
=cut
=item C<< new ( $parse_tree ) >>
Returns a new compiler object.
=cut
sub new {
my $class = shift;
my $parsed = shift;
my $model = shift;
my $l = Log::Log4perl->get_logger("rdf.query.compiler.sql");
my $stable;
if ($model) {
my $mhash = _mysql_hash( $model );
$l->debug("Model: $model => $mhash\n");
$stable = "Statements${mhash}";
} else {
$stable = 'Statements';
}
my $self = bless( {
parsed => $parsed,
stable => $stable,
vars => {},
from => [],
where => [],
}, $class );
return $self;
}
=item C<< compile () >>
Returns a SQL query string for the specified parse tree.
=cut
sub compile {
my $self = shift;
my $parsed = $self->{parsed};
my $sql;
try {
my $method = uc $parsed->{'method'};
if ($method eq 'SELECT') {
$sql = $self->emit_select();
} else {
throw RDF::Query::Error::CompilationError( -text => "SQL compilation of $method queries not yet implemented." );
}
} catch RDF::Query::Error::CompilationError with {
my $err = shift;
throw $err;
};
return $sql;
}
=item C<< emit_select >>
Returns a SQL query string representing the query.
=cut
sub emit_select {
my $self = shift;
my $parsed = $self->{parsed};
my $level = \do { my $a = 0 };
my @vars = map { $_->name } @{ $parsed->{variables} };
my %select_vars = map { $_ => 1 } @vars;
$self->patterns2sql( $parsed->{'triples'}, $level );
my ($varcols, @cols) = $self->add_variable_values_joins;
my $vars = $self->{vars};
my $from = $self->{from};
my $where = $self->{where};
my $options = $self->{options} || {};
my $unique = $options->{'distinct'};
my $from_clause;
foreach my $f (@$from) {
$from_clause .= ",\n" . INDENT if ($from_clause and $from_clause =~ m/[^(]$/ and $f !~ m/^([)]|LEFT JOIN)/);
$from_clause .= $f;
}
my $where_clause = @$where ? "WHERE\n"
. INDENT . join(" AND\n" . INDENT, @$where) : '';
my @sql = (
"SELECT" . ($unique ? ' DISTINCT' : ''),
INDENT . join(",\n" . INDENT, @cols),
"FROM",
INDENT . $from_clause,
$where_clause,
);
push(@sql, $self->order_by_clause( $varcols, $level ) );
push(@sql, $self->limit_clause( $options ) );
my $sql = join("\n", grep {length} @sql);
return $sql;
}
=item C<< limit_clause >>
Returns a SQL LIMIT clause, or an empty string if the query does not need limiting.
=cut
sub limit_clause {
my $self = shift;
my $options = shift;
if (my $limit = $options->{limit}) {
return "LIMIT ${limit}";
} else {
return "";
}
}
=item C<< order_by_clause >>
Returns a SQL ORDER BY clause, or an empty string if the query does not use ordering.
=cut
sub order_by_clause {
my $self = shift;
my $varcols = shift;
my $level = shift || \do{ my $a = 0 };
my $vars = $self->{vars};
my $options = $self->{options} || {};
my %variable_value_cols = %$varcols;
my $sql = '';
if ($options->{orderby}) {
my $data = $options->{orderby}[0];
my ($dir, @operands) = @$data;
if (scalar(@operands) > 1) {
throw RDF::Query::Error::CompilationError( -text => "Can't sort by more than one column yet." );
}
my $sort = $operands[0];
if (blessed($sort) and $sort->type eq 'VAR') {
my $var = $sort->name;
my @cols = $self->variable_columns( $var );
$sql .= "ORDER BY\n"
. INDENT . join(', ', map { "$_ $dir" } @cols );
} elsif (blessed($sort) and $sort->type eq 'FUNCTION') {
my $uri = $self->qualify_uri( $sort->uri );
my $col = $self->expr2sql( $sort, $level );
my @sort;
foreach my $var (keys %$vars) {
my ($l_sort_col, $r_sort_col, $b_sort_col) = @{ $variable_value_cols{ $var } };
my $varcol = $vars->{ $var };
if ($col =~ /${varcol}/) {
my ($l, $r, $b) = ($col) x 3;
$l =~ s/$varcol/${l_sort_col}/;
$r =~ s/$varcol/${r_sort_col}/;
$b =~ s/$varcol/${b_sort_col}/;
push(@sort, "$l $dir, $r $dir, $b $dir");
last;
}
}
unless (@sort) {
push(@sort, "${col} $dir");
}
$sql .= "ORDER BY\n"
. INDENT . join(', ', @sort);
} else {
throw RDF::Query::Error::CompilationError( -text => "Can't sort by $$data[1][0] yet." );
}
}
return $sql;
}
=item C<< variable_columns ( $var ) >>
Given a variable name, returns the set of column aliases that store the values
for the column (values for Literals, URIs, and Blank Nodes).
=cut
sub variable_columns {
my $self = shift;
my $var = shift;
return map { "${var}_$_" } (qw(Value URI Name));
}
=item C<< add_variable_values_joins >>
Modifies the query by adding LEFT JOINs to the tables in the database that
contain the node values (for literals, resources, and blank nodes).
=cut
sub add_variable_values_joins {
my $self = shift;
my $l = Log::Log4perl->get_logger("rdf.query.algebra.service");
my $parsed = $self->{parsed};
my @vars = map { $_->name } @{ $parsed->{variables} };
my %select_vars = map { $_ => 1 } @vars;
my %variable_value_cols;
my $vars = $self->{vars};
my $from = $self->{from};
my $where = $self->{where};
my @cols;
my $uniq_count = 0;
my (%seen_vars, %seen_joins);
foreach my $var (grep { not $seen_vars{ $_ }++ } (@vars, keys %$vars)) {
my $col = $vars->{ $var };
unless ($col) {
throw RDF::Query::Error::CompilationError "*** Nothing is known about the variable ?${var}";
}
my $col_table = (split(/[.]/, $col))[0];
my ($count) = ($col_table =~ /\w(\d+)/);
$l->debug("var: $var\t\tcol: $col\t\tcount: $count\t\tunique count: $uniq_count\n");
push(@cols, "${col} AS ${var}_Node") if ($select_vars{ $var });
foreach (@NODE_TYPE_TABLES) {
my ($table, $alias, @join_cols) = @$_;
foreach my $jc (@join_cols) {
my $column_real_name = "${alias}${uniq_count}.${jc}";
my $column_alias_name = "${var}_${jc}";
push(@cols, "${column_real_name} AS ${column_alias_name}");
push( @{ $variable_value_cols{ $var } }, $column_real_name);
foreach my $i (0 .. $#{ $where }) {
if ($where->[$i] =~ /\b$column_alias_name\b/) {
$where->[$i] =~ s/\b${column_alias_name}\b/${column_real_name}/g;
}
}
}
}
foreach my $i (0 .. $#{ $from }) {
my $f = $from->[ $i ];
next if ($from->[ $i ] =~ m/^[()]$/);
my ($alias) = ($f =~ m/Statements\d* (\w\d+)/); #split(/ /, $f))[1];
if ($alias eq $col_table) {
# my (@tables, @where);
foreach (@NODE_TYPE_TABLES) {
my ($vtable, $vname) = @$_;
my $valias = join('', $vname, $uniq_count);
next if ($seen_joins{ $valias }++);
# push(@tables, "${vtable} ${valias}");
# push(@where, "${col} = ${valias}.ID");
$f .= " LEFT JOIN ${vtable} ${valias} ON (${col} = ${valias}.ID)";
}
# my $join = sprintf("LEFT JOIN (%s) ON (%s)", join(', ', @tables), join(' AND ', @where));
# $from->[ $i ] = join(' ', $f, $join);
$from->[ $i ] = $f;
next;
}
}
$uniq_count++;
}
return (\%variable_value_cols, @cols);
}
=item C<< patterns2sql ( \@triples, \$level, %args ) >>
Builds the SQL query in instance data from the supplied C<@triples>.
C<$level> is used as a unique identifier for recursive calls.
C<%args> may contain callback closures for the following keys:
'where_hook'
'from_hook'
When present, these closures are used to add SQL FROM and WHERE clauses
to the query instead of adding them directly to the object's instance data.
=cut
sub patterns2sql {
my $self = shift;
my $triples = shift;
my $level = shift || \do{ my $a = 0 };
my %args = @_;
# my %vars = scalar(@_) ? %{ $_[0] } : ();
my $parsed = $self->{parsed};
my $parsed_vars = $parsed->{variables};
my %queryvars = map { $_->name => 1 } @$parsed_vars;
# my (@from, @where);
my $from = $self->{from};
my $where = $self->{where};
my $vars = $self->{vars};
my $add_where = sub {
my $w = shift;
if (my $hook = $args{ where_hook }) {
push(@$where, $hook->( $w ));
} else {
push(@$where, $w);
}
return $w;
};
my $add_from = sub {
my $f = shift;
if (my $hook = $args{ from_hook }) {
push(@$from, $hook->( $f ));
} else {
push(@$from, $f);
}
return $f;
};
my $triple = shift(@$triples);
Carp::confess "unblessed atom: " . Dumper($triple) unless (blessed($triple));
if ($triple->isa('RDF::Query::Algebra::Triple') or $triple->isa('RDF::Query::Algebra::Quad')) {
my $quad = $triple->isa('RDF::Query::Algebra::Quad');
my @posmap = ($quad)
? qw(subject predicate object context)
: qw(subject predicate object);
# $add_from->('(');
my $table = "s${$level}";
my $stable = $self->{stable};
$add_from->( "${stable} ${table}" );
foreach my $method (@posmap) {
my $node = $triple->$method();
my $pos = $method;
my $col = "${table}.${pos}";
if ($node->isa('RDF::Query::Node::Variable')) {
my $name = $node->name;
if (exists $vars->{ $name }) {
my $existing_col = $vars->{ $name };
$add_where->( "$col = ${existing_col}" );
} else {
$vars->{ $name } = $col;
}
} elsif ($node->isa('RDF::Query::Node::Resource')) {
my $uri = $node->uri_value;
my $id = $self->_mysql_node_hash( $node );
$id =~ s/\D//;
$add_where->( "${col} = $id" );
} elsif ($node->isa('RDF::Query::Node::Blank')) {
my $id = $node->blank_identifier;
my $b = "b${$level}";
$add_from->( "Bnodes $b" );
$add_where->( "${col} = ${b}.ID" );
$add_where->( "${b}.Name = '$id'" );
} elsif ($node->isa('RDF::Query::Node::Literal')) {
my $id = $self->_mysql_node_hash( $node );
$id =~ s/\D//;
$add_where->( "${col} = $id" );
} else {
throw RDF::Query::Error::CompilationError( -text => "Unknown node type: " . Dumper($node) );
}
}
# $add_from->(')');
} else {
if ($triple->isa('RDF::Query::Algebra::Optional')) {
throw RDF::Query::Error::CompilationError( -text => "SQL compilation of OPTIONAL blocks is currently broken" );
} elsif ($triple->isa('RDF::Query::Algebra::NamedGraph')) {
$self->patterns2sql( [ $triple->pattern ], $level, %args );
# my $graph = $triple->graph;
# my $pattern = $triple->pattern;
# if ($graph->isa('RDF::Query::Node::Variable')) {
# my $name = $graph->name;
# my $context;
# my $hook = sub {
# my $f = shift;
# if ($f =~ /^Statements/i) {
# my $alias = (split(/ /, $f))[1];
# if (defined($context)) {
# $context =~ s/\D//;
# $add_where->( "${alias}.Context = ${context}" );
# } else {
# $context = "${alias}.Context";
# $vars->{ $name } = $context;
# }
# }
# return $f;
# };
# $self->patterns2sql( [ $pattern ], $level, from_hook => $hook );
# } else {
# my $hash = $self->_mysql_node_hash( $graph );
# my $hook = sub {
# my $f = shift;
# if ($f =~ /^Statements/i) {
# my $alias = (split(/ /, $f))[1];
# $hash =~ s/\D//;
# $add_where->( "${alias}.Context = ${hash}" );
# }
# return $f;
# };
# $self->patterns2sql( [ $pattern ], $level, from_hook => $hook );
# }
} elsif ($triple->isa('RDF::Query::Algebra::Filter')) {
++$$level;
my $expr = $triple->expr;
my $pattern = $triple->pattern;
$self->expr2sql( $expr, $level, from_hook => $add_from, where_hook => $add_where );
++$$level;
$self->patterns2sql( [ $pattern ], $level, %args );
} elsif ($triple->isa('RDF::Query::Algebra::BasicGraphPattern')) {
++$$level;
$self->patterns2sql( [ $triple->triples ], $level, %args );
} elsif ($triple->isa('RDF::Query::Algebra::GroupGraphPattern')) {
++$$level;
$self->patterns2sql( [ $triple->patterns ], $level, %args );
} elsif ($triple->isa('RDF::Query::Algebra::Distinct')) {
$self->{options}{distinct} = 1;
my $pattern = $triple->pattern;
$self->patterns2sql( [ $pattern ], $level, %args );
} elsif ($triple->isa('RDF::Query::Algebra::Limit')) {
$self->{options}{limit} = $triple->limit;
my $pattern = $triple->pattern;
$self->patterns2sql( [ $pattern ], $level, %args );
} elsif ($triple->isa('RDF::Query::Algebra::Offset')) {
$self->{options}{offset} = $triple->offset;
my $pattern = $triple->pattern;
$self->patterns2sql( [ $pattern ], $level, %args );
} elsif ($triple->isa('RDF::Query::Algebra::Sort')) {
$self->{options}{orderby} = [ $triple->orderby ];
my $pattern = $triple->pattern;
$self->patterns2sql( [ $pattern ], $level, %args );
} elsif ($triple->isa('RDF::Query::Algebra::Project')) {
my $pattern = $triple->pattern;
$self->patterns2sql( [ $pattern ], $level, %args );
} else {
throw RDF::Query::Error::CompilationError( -text => "Unknown pattern type '$triple' in SQL compilation." );
}
}
if (scalar(@$triples)) {
++$$level;
$self->patterns2sql( $triples, $level );
}
return;
# return (\%vars, \@from, \@where);
}
=item C<< expr2sql ( $expression, \$level, %args ) >>
Returns a SQL expression for the supplied query C<$expression>.
C<$level> is used as a unique identifier for recursive calls.
C<%args> may contain callback closures for the following keys:
'where_hook'
'from_hook'
When present, these closures are used to add necessary SQL FROM and WHERE
clauses to the query.
=cut
sub expr2sql {
my $self = shift;
my $expr = shift;
my $level = shift || \do{ my $a = 0 };
my %args = @_;
my $equality = do { no warnings 'uninitialized'; ($args{'equality'} eq 'rdf') ? 'rdf' : 'xpath' };
my $from = $self->{from};
my $where = $self->{where};
my $vars = $self->{vars};
my $sql;
my $add_where = sub {
my $w = shift;
$sql ||= $w;
if (my $hook = $args{ where_hook }) {
$hook->( $w );
}
};
my $add_from = sub {
my $f = shift;
if (my $hook = $args{ from_hook }) {
$hook->( $f );
}
};
my $parsed = $self->{parsed};
my $parsed_vars = $parsed->{variables};
my %queryvars = map { $_->name => 1 } @$parsed_vars;
Carp::confess unless ref($expr);
my $blessed = blessed($expr);
if ($blessed and $expr->isa('RDF::Trine::Node')) {
if ($expr->isa('RDF::Trine::Node::Literal')) {
my $literal = $expr->literal_value;
my $dt = $expr->literal_datatype;
my $hash = $self->_mysql_node_hash( $expr );
if ($equality eq 'rdf') {
$literal = $hash;
} else {
if (defined($dt)) {
my $uri = $dt;
my $func = $self->get_function( $self->qualify_uri( $uri ) );
if ($func) {
my ($v, $f, $w) = $func->( $self, $parsed_vars, $level, RDF::Query::Node::Literal->new($literal) );
$literal = $w->[0];
} else {
$literal = qq("${literal}");
}
} else {
$literal = qq('${literal}');
}
}
$add_where->( $literal );
} elsif ($expr->isa('RDF::Query::Node::Blank')) {
my $hash = $self->_mysql_node_hash( $expr );
$add_where->( $hash );
} elsif ($expr->isa('RDF::Query::Node::Resource')) {
my $uri = $self->_mysql_node_hash( $expr );
$add_where->( $uri );
} elsif ($expr->isa('RDF::Query::Node::Variable')) {
my $name = $expr->name;
my $col = $vars->{ $name };
no warnings 'uninitialized';
$add_where->( qq(${col}) );
}
} elsif ($blessed and $expr->isa('RDF::Query::Expression::Function')) {
my $uri = $expr->uri->uri_value;
my $func = $self->get_function( $uri );
if ($func) {
my ($v, $f, $w) = $func->( $self, $parsed_vars, $level, $expr->arguments );
foreach my $key (keys %$v) {
my $val = $v->{ $key };
$vars->{ $key } = $val unless (exists($vars->{ $key }));
}
foreach my $f (@$f) {
$add_from->( @$f );
}
foreach my $w (@$w) {
$add_where->( $w );
}
} else {
throw RDF::Query::Error::CompilationError( -text => "Unknown custom function $uri in FILTER." );
}
} elsif ($blessed and $expr->isa('RDF::Query::Expression')) {
my $op = $expr->op;
my @args = $expr->operands;
if ($op eq '!') {
if ($args[0]->isa('RDF::Query::Expression::Function')) {
if ($args[0]->uri->uri_value eq 'sparql:isbound') {
my $expr = RDF::Query::Expression::Function->new(
RDF::Query::Node::Resource->new('rdfquery:isNotBound'),
$args[0]->arguments
);
$self->expr2sql( $expr, $level, %args );
}
}
} else {
if ($op =~ m#^(=|==|!=|[<>]=?|[*]|/|[-+])$#) {
$op = '<>' if ($op eq '!=');
$op = '=' if ($op eq '==');
my ($a, $b) = @args;
my $a_type = $a->type;
my $b_type = $b->type;
try {
if ($op eq '=') {
if ($a_type eq 'VAR' and $b_type eq 'VAR') {
# comparing equality on two type-unknown variables.
# could need rdf-term equality, so punt to the
# catch block below.
throw RDF::Query::Error::ComparisonError;
}
}
foreach my $data ([$a_type, 'LHS'], [$b_type, 'RHS']) {
my ($type, $side) = @$data;
unless ($type =~ m/^(VAR|LITERAL|FUNCTION)$/) {
if ($op =~ m/^!?=$/) {
# throw to the catch block below.
throw RDF::Query::Error::ComparisonError( -text => "Using comparison operator '${op}' on unknown node type requires RDF-Term semantics." );
} else {
# throw error out of the compiler.
throw RDF::Query::Error::CompilationError( -text => "Cannot use the comparison operator '${op}' on a ${side} ${type} node." );
}
}
}
if ($a_type eq 'VAR') {
++$$level; my $var_name_a = $self->expr2sql( $a, $level, equality => $equality );
my $sql_a = "(SELECT value FROM Literals WHERE ${var_name_a} = ID LIMIT 1)";
if ($b_type eq 'VAR') {
# ?var cmp ?var
++$$level; my $var_name_b = $self->expr2sql( $b, $level, equality => $equality );
my $sql_b = "(SELECT value FROM Literals WHERE ${var_name_b} = ID LIMIT 1)";
$add_where->( "${sql_a} ${op} ${sql_b}" );
} else {
# ?var cmp NODE
++$$level; my $sql_b = $self->expr2sql( $b, $level, equality => $equality );
$add_where->( "${sql_a} ${op} ${sql_b}" );
}
} else {
++$$level; my $sql_a = $self->expr2sql( $a, $level, equality => $equality );
if ($b->type eq 'VAR') {
# ?var cmp NODE
++$$level; my $var_name = $self->expr2sql( $b, $level, equality => $equality );
my $sql_b = "(SELECT value FROM Literals WHERE ${var_name} = ID LIMIT 1)";
$add_where->( "${sql_a} ${op} ${sql_b}" );
} else {
# NODE cmp NODE
++$$level; my $sql_b = $self->expr2sql( $b, $level, equality => $equality );
$add_where->( "${sql_a} ${op} ${sql_b}" );
}
}
} catch RDF::Query::Error::ComparisonError with {
# we can't compare these terms using the XPath semantics (for literals),
# so fall back on RDF-Term semantics.
my $err = shift;
my @w;
my $where_hook = sub {
my $w = shift;
push(@w, $w);
return;
};
foreach my $expr (@args) {
$self->expr2sql( $expr, $level, %args, %args, equality => 'rdf', where_hook => $where_hook )
}
$add_where->("$w[0] ${op} $w[1]");
};
} elsif ($op eq '&&') {
foreach my $expr (@args) {
$self->expr2sql( $expr, $level, %args )
}
} elsif ($op eq '||') {
my @w;
my $where_hook = sub {
my $w = shift;
push(@w, $w);
return;
};
foreach my $expr (@args) {
$self->expr2sql( $expr, $level, %args, where_hook => $where_hook )
}
my $where = '(' . join(' OR ', map { qq<($_)> } @w) . ')';
$add_where->( $where );
} else {
throw RDF::Query::Error::CompilationError( -text => "SQL compilation of FILTER($op) queries not yet implemented." );
}
}
}
return $sql;
}
=item C<< _mysql_hash ( $data ) >>
Returns a hash value for the supplied C<$data> string. This value is computed
using the same algorithm that Redland's mysql storage backend uses.
=cut
sub _mysql_hash {
my $data = shift;
my @data = unpack('C*', md5( $data ));
my $sum = Math::BigInt->new('0');
# my $count = 0;
foreach my $count (0 .. 7) {
# while (@data) {
my $data = Math::BigInt->new( $data[ $count ] ); #shift(@data);
my $part = $data << (8 * $count);
# warn "+ $part\n";
$sum += $part;
} # continue { last if ++$count == 8 } # limit to 64 bits
# warn "= $sum\n";
$sum =~ s/\D//; # get rid of the extraneous '+' that pops up under perl 5.6
return $sum;
}
=item C<< _mysql_node_hash ( $node ) >>
Returns a hash value (computed by C<_mysql_hash> for the supplied C<$node>.
The hash value is based on the string value of the node and the node type.
=cut
sub _mysql_node_hash {
my $self = shift;
my $node = shift;
# my @node = @$node;
# my ($type, $value) = splice(@node, 0, 2, ());
my $data;
Carp::confess 'node a blessed node: ' . Dumper($node) unless blessed($node);
if ($node->isa('RDF::Query::Node::Resource')) {
my $value = $node->uri_value;
if (ref($value)) {
$value = $self->qualify_uri( $value );
}
$data = 'R' . $value;
} elsif ($node->isa('RDF::Query::Node::Blank')) {
my $value = $node->blank_identifier;
$data = 'B' . $value;
} elsif ($node->isa('RDF::Query::Node::Literal')) {
my $value = $node->literal_value;
my $lang = $node->literal_value_language;
my $dt = $node->literal_datatype;
no warnings 'uninitialized';
$data = sprintf("L%s<%s>%s", $value, $lang, $dt);
# warn "($data)";
} else {
return undef;
}
my $hash = _mysql_hash( $data );
return $hash;
}
=item C<< qualify_uri ( $uri ) >>
Returns a fully qualified URI from the supplied C<$uri>. C<$uri> may already
be a qualified URI, or a parse tree for a qualified URI or QName. If C<$uri> is
a QName, the namespaces defined in the query parse tree are used to fully qualify.
=cut
sub qualify_uri {
my $self = shift;
my $uri = shift;
my $parsed = $self->{parsed};
if (ref($uri) and $uri->type eq 'URI') {
$uri = $uri->uri_value;
}
if (ref($uri)) {
my ($abbr, $local) = @$uri;
if (exists $parsed->{namespaces}{$abbr}) {
my $ns = $parsed->{namespaces}{$abbr};
$uri = join('', $ns, $local);
} else {
throw RDF::Query::Error::ParseError ( -text => "Unknown namespace prefix: $abbr" );
}
}
return $uri;
}
=item C<add_function ( $uri, $function )>
Associates the custom function C<$function> (a CODE reference) with the
specified URI, allowing the function to be called by query FILTERs.
=cut
sub add_function {
my $self = shift;
my $uri = shift;
my $code = shift;
if (ref($self)) {
$self->{'functions'}{$uri} = $code;
} else {
our %functions;
$functions{ $uri } = $code;
}
}
=item C<get_function ( $uri )>
If C<$uri> is associated with a query function, returns a CODE reference
to the function. Otherwise returns C<undef>.
=cut
sub get_function {
my $self = shift;
my $uri = shift;
our %functions;
my $func = $self->{'functions'}{$uri} || $functions{ $uri };
return $func;
}
our %functions;
BEGIN {
$functions{ 'sparql:regex' } = sub {
my $self = shift;
my $parsed_vars = shift;
my $level = shift || \do{ my $a = 0 };
my @args = @_;
my (@from, @where);
my (@regex, @literal, @pattern);
if (blessed($args[0]) and $args[0]->isa('RDF::Query::Node::Variable')) {
my $name = $args[0]->name;
push(@literal, "${name}_Value");
push(@literal, "${name}_URI");
push(@literal, "${name}_Name");
} else {
push(@literal, $self->expr2sql( $args[0], $level ));
}
if ($args[1]->type eq 'VAR') {
my $name = $args[0][1];
push(@pattern, "${name}_Value");
push(@pattern, "${name}_URI");
push(@pattern, "${name}_Name");
} else {
push(@pattern, $self->expr2sql( $args[1], $level ));
}
foreach my $literal (@literal) {
foreach my $pattern (@pattern) {
push(@regex, sprintf(qq(%s REGEXP %s), $literal, $pattern));
}
}
push(@where, '(' . join(' OR ', @regex) . ')');
return ({}, \@from, \@where);
};
$functions{ 'sparql:bound' } = sub {
my $self = shift;
my $parsed_vars = shift;
my $level = shift || \do{ my $a = 0 };
my @args = @_;
my (@from, @where);
my $literal = $self->expr2sql( $args[0], $level );
push(@where, sprintf(qq(%s IS NOT NULL), $literal));
return ({}, \@from, \@where);
};
$functions{ 'rdfquery:isNotBound' } = sub {
my $self = shift;
my $parsed_vars = shift;
my $level = shift || \do{ my $a = 0 };
my @args = @_;
my (@from, @where);
my $literal = $self->expr2sql( $args[0], $level );
push(@where, sprintf(qq(%s IS NULL), $literal));
return ({}, \@from, \@where);
};
$functions{ 'http://www.w3.org/2001/XMLSchema#integer' } = sub {
my $self = shift;
my $parsed_vars = shift;
my $level = shift || \do{ my $a = 0 };
my @args = @_;
my (@from, @where);
my $literal = $self->expr2sql( $args[0], $level );
push(@where, sprintf(qq((0 + %s)), $literal));
return ({}, \@from, \@where);
};
$functions{ 'http://www.w3.org/2001/XMLSchema#double' } =
$functions{ 'http://www.w3.org/2001/XMLSchema#decimal' } = sub {
my $self = shift;
my $parsed_vars = shift;
my $level = shift || \do{ my $a = 0 };
my @args = @_;
my (@from, @where);
if ($args[0] eq 'FUNCTION') {
Carp::confess;
}
my $literal = $self->expr2sql( $args[0], $level );
push(@where, sprintf(qq((0.0 + %s)), $literal));
return ({}, \@from, \@where);
};
}
1;
__END__
=back
=head1 AUTHOR
Gregory Williams <gwilliams@cpan.org>
=cut
|
library(readr); library(pastecs); library(stringr); library(data.table)
library(dplyr); library(fda); library(tidyr)
## Function to read in data and time normalize
identify_cycles = function(data, axis, cutoff = -10){
data = fread(data)
colnames(data) = c('frame','tx','ty','tz','rx','ry','rz')
data = data[,.(frame, get(axis))]
colnames(data) = c('frame', axis)
turn_points = turnpoints(data[[axis]])
peaks = extract(turn_points)
data[, turnpoints := peaks]
data[get(axis) > cutoff, turnpoints := 0]
## Add column for index to maintain order
index = 1:nrow(data)
data$Index = index
data$Cycle = NA
cycle = 0
cycle_start = (data[turnpoints == -1])[1]
for(i in 1:length(data[[axis]]) ){
if(data$turnpoints[i] == -1){
cycle = cycle + 1
cycle_start = rbind(cycle_start, data[i])
}
data$Cycle[i] = cycle
}
## Only select unique cycles
cycle_start = unique(cycle_start)
## Add Cycles to cycles_start
cycle_start$Cycle = (1:nrow(cycle_start)) - 1
## Bind data with cycle start, adding the duplicate rows
## That is, so cycle 2 starts at end point of cycle 1 etc.
#data = rbind(cycle_start, data)
#data = data[order(Index)]
return(data)
}
initial_plot = function(cycle_data, axis){
min = cycle_data[turnpoints == -1]
ggplot(cycle_data, aes(x = frame, y = cycle_data[[axis]]))+
geom_line() +
geom_vline(xintercept = min$frame, col = 'red') +
geom_point(data = min, aes(x = frame, y = min[[axis]]), col = 'red')
}
data = "pig10_20150826_ctrl_carrot_1_TMJBUTTER25_sm250.csv"
axis = 'TMJdata1.rz'
cycle_data = identify_cycles(data, axis)
initial_plot(cycle_data, axis)
################################################
##
## Time normalizing function ##
##
#################################################
## Function to interprolate data to make all cycles the same length
## Will call later in our time normalizing function
interpolation_func = function(data, cycle, max_cycle, axis){
max_cyc = max_cycle
data = as.data.table(data)
data = data[Cycle == cycle][,.(frame, get(axis))]
colnames(data) = c('frame',axis)
n = max_cyc-dim(data)[1]
interp = as.data.table(approx(data$frame, data[[axis]], n = n+2 ))
colnames(interp) = c('frame', axis)
data2 = rbind(interp, data)
data2 = data2[order(frame)][,Cycle := cycle]
data2 = data2[2:(max_cyc+1)]
return(data2)
}
time_normalize = function(data, axis, cycles){
data = identify_cycles(data, axis)
## Keep only those cycles we deem good
data = data[Cycle %in% cycles,]
##Calculate cycle lengths
cycle_lengths = data[,.N, by = Cycle]
max_cycle = max(cycle_lengths)
## Now we want to normalize so
## Each cycle to start at frame 0
data = data[,frame := frame - min(frame), by = Cycle]
##Each cycle ends at frame 1
data = data[, frame := frame/max(frame), by = Cycle]
##call Interprolation function on all cycles
data_inter_list = list()
for(i in cycles){
data_inter_list[[i]] = interpolation_func(data, i, max_cycle, axis)
}
data = rbindlist(data_inter_list)
}
data = "pig10_20150826_ctrl_carrot_1_TMJBUTTER25_sm250.csv"
axis = 'TMJdata1.rz'
cycles = c(1,2,3,4,5,7,8,9,10,11)
test1 = time_normalize(data, axis, cycles)
saturated_fd = function(data, axis, cycles, lambda = 1e-12,
norder = 6){
data = time_normalize(data, axis, cycles)
cycle_lengths = data[,.N, by = Cycle]
max_cycle = max(cycle_lengths)
n_cycles = length(cycles)
id = rep(1:max_cycle, n_cycles )
data[,id := id]
data = data[,.(id, Cycle, get(axis))]
colnames(data) = c('id', 'Cycle',axis)
data_wide = dcast(data, id ~ Cycle, value.var = axis )
colnames(data_wide) = c('id', paste0('C', cycles))
data_wide = data_wide[,!c('id'), with = FALSE]
#split 0 to 1 into 84 values (length of our cycles )
samples = seq(0,1,length = 84)
# Define the number of basis functions we want
nbasis = length(samples) + norder -2
# Create basic basis functions with our parameters
mybasis = create.bspline.basis(c(0,1), nbasis, norder, samples)
myfdPar = fdPar(mybasis, 4, lambda)
# Dataset has to be in matrix form
dataset = as.matrix(data_wide)
## Lets make it a fd object based off of our basis functions! woohoo!
myfd = smooth.basis(samples, dataset, myfdPar)$fd
return(myfd)
}
data = "pig10_20150826_ctrl_carrot_1_TMJBUTTER25_sm250.csv"
axis = 'TMJdata1.rz'
cycles = c(1,2,3,4,5,7,8,9,10,11)
myfd1 = saturated_fd(data, axis, cycles)
landmark_reg = function(raw_data, axis, cycles){
fd_obj = saturated_fd(raw_data, axis, cycles)
raw_data = time_normalize(raw_data, axis, cycles)
#fd_obj = deriv.fd(fd_obj, 2)
## Landmark Registration
#First take the splines created from our fd object
#and put into separate data.table
splines = as.data.table(fd_obj$coefs)
#Create an empty list to put things in later
peak_x = list()
#These are the x values on the plots
x_vals = as.matrix(fd_obj$basis$params)
#Loop through all columns in our splines list
for(col in colnames(splines)){
print(col)
c = splines %>% select(col)
#split colname string so we can select appropriate cycle
cyc = as.numeric(strsplit(col, 'C')[[1]][2])
#Select frames for corresponding cycle
print(cyc)
frames = raw_data[Cycle == cyc,][,.(frame)]
print(frames)
#Add column with spline points
frames = frames[,spline := c]
#Now we just want the x value (frame) corresponding to maximum spline point
peak_x[[cyc]] = frames[which.max(frames$spline)]$frame
}
#Unlist our peak_x to use late
peak_x = unlist(peak_x)
print(peak_x)
#Take the mean of it
mean_peak = mean(peak_x)
#Create some W functions and stuff
#Still not 100% certain what these do
wbasisLM = create.bspline.basis(c(0,1), 4, 3, c(0, mean_peak,1))
WfdLM = fd(matrix(0,4,1),wbasisLM)
WfdParLM = fdPar(WfdLM,1,1e-12)
#Throw it all into the landmarkreg function
#peak_x are the points we are landmarking (max vals)
regListLM = landmarkreg(fd_obj, peak_x,mean_peak, WfdParLM, TRUE)
}
data = "pig10_20150826_ctrl_carrot_1_TMJBUTTER25_sm250.csv"
axis = 'TMJdata1.rz'
cycles = c(1,2,3,4,5,7,8,9,10,11)
test = landmark_reg(data, axis, cycles)
|
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style>
div {
width: 200px; height: 200px;
border : 2px solid black;
position: absolute; /*relative와의 차이점? 브라우저 상단(절대위치) vs 화면에 표시되던 원래 위치(상대위치)*/
}
#div1{
background-color: red;
top : -50px;
left : 50px;
}
#div2{
background-color: green;
left : 200px; /*기준이 브라우저 좌측기준으로 오른쪽으로 200px이동했다.*/
top : 200px;
}
#div3{
background-color: blue;
right : 200px; /*브라우저 우측에서 20px만큼*/
bottom : 20px;
}
</style>
</head>
<body>
<h3>CSS position: absolute</h3>
<div id="div1">div1</div>
<div id="div2">div2</div>
<div id="div3">div3</div>
</body>
</html>
|
public class CourtCard extends Card {
public enum Face {
Jack, Queen, King, Joker , A
}
private Face face;
public CourtCard(String color, String suit, Face face) {
super(color, suit);
this.face = face;
}
public Face getFace() {
return face;
}
@Override
public int returnedValue() {
if (face.equals(Face.Jack))
return 11;
if (face.equals(Face.Queen))
return 12;
if (face.equals(Face.King))
return 13;
if(face.equals(Face.A))
return 30;
else
return -1; // Joker
}
@Override
public String toString(){
if(getFace().equals(Face.Joker))
return "Joker Card";
else
return "Face Card , Color: " + getColor() + " | Face: " + getFace() + " | Suit: " + getSuit();
}
}
|
---
import getNavLinks from '../helpers/getNavLinks'
import FooterLinks from "./FooterLinks.astro";
import { Icon } from "astro-icon/components";
const { title, description, copyright, contacts, socialLinks, infoLinks, menu, socialLinksInSection } = Astro.props
const { secondMenu } = getNavLinks(menu)
---
<footer
class="text-gray-500 bg-white px-4 py-5 container-wrapper md:px-8"
>
<div class="gap-6 justify-between md:flex">
<div class="flex-1">
<div class="max-w-xs">
<a href="/" class="text-2xl font-bold text-gray-800">{title}</a>
<p class="leading-relaxed mt-2">
{description}
</p>
<ul class="mt-6 flex flex-wrap gap-x-10 space-y-3 items-center">
{
contacts?.map((contact) => {
return (
<li class="flex items-center gap-x-3">
<div class="flex-none text-gray-400">
<Icon name={contact.icon} class="w-6 h-6" />
</div>
<a
href={`${contact.type}:${contact.value.replace(/\s/g, "")}`}
>
{contact.value}
</a>
</li>
);
})
}
{
socialLinksInSection?.map((link) => {
return (
<li class="flex items-center gap-x-3">
<a class="flex items-center gap-2" href={link.url.cached_url}><Icon name={link.icon} class="w-6 h-6" />{link.value}</a>
</li>
)
})
}
</ul>
</div>
</div>
<div
class="gap-4 mt-10 space-y-6 justify-between grid grid-cols-1 md:grid-cols-2 md:space-y-0 md:mt-0"
>
<div class="space-y-4">
<h6 class="text-gray-800 font-bold text-xl">Навигация</h6>
<ul class="space-y-4">
<FooterLinks links={menu} />
</ul>
</div>
{
secondMenu?.map(({name, list}) => {
return (<div class="space-y-4">
<h6 class="text-gray-800 font-bold text-xl">{name}</h6>
<ul class="space-y-4">
<FooterLinks links={list} />
</ul>
</div>)
})
}
<div class="space-y-4">
<h6 class="text-gray-800 font-bold text-xl">Информация</h6>
<ul class="space-y-4">
<FooterLinks links={infoLinks} />
</ul>
</div>
<div class="space-y-4">
<h6 class="text-gray-800 font-bold text-xl">Социальные сети</h6>
<ul class="flex space-x-2">
{
socialLinks.map(({link, icon}) => <li><a href={link.url}
><Icon name={icon} class="w-10 h-10 hover:underline text-gray-800 focus:text-amber-600 hover:text-amber-600 cursor-pointer" /></a></li>)
}
</ul>
</div>
</div>
</div>
<div class="mt-8 py-6 border-t items-center justify-between sm:flex">
<div class="mt-4 sm:mt-0">
© {new Date().getFullYear()} {copyright}
</div>
</div>
</footer>
|
// SPDX-License-Identifier: MIT
pragma solidity 0.8.9;
import "vesper-pools/contracts/dependencies/openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "../../../interfaces/curve/IDeposit.sol";
import "../CurvePoolBase.sol";
/**
* @title This strategy will deposit collateral token in a Curve 4Pool and earn interest.
* @dev Both Meta and Plain 4Pools implement the same Deposit contract interface
*/
contract Curve4PlainOr4MetaPool is CurvePoolBase {
using SafeERC20 for IERC20;
IDeposit4x public immutable crvDeposit;
constructor(
address pool_,
address crvPool_,
uint256 crvSlippage_,
address masterOracle_,
address swapper_,
address crvDeposit_,
uint256 collateralIdx_,
string memory name_
) CurvePoolBase(pool_, crvPool_, crvSlippage_, masterOracle_, swapper_, collateralIdx_, name_) {
crvDeposit = IDeposit4x(crvDeposit_);
require(crvDeposit.token() == address(crvLp), "invalid-deposit-contract");
}
function _approveToken(uint256 amount_) internal virtual override {
super._approveToken(amount_);
collateralToken.safeApprove(address(crvDeposit), amount_);
crvLp.safeApprove(address(crvDeposit), amount_);
}
function _depositToCurve(uint256 coinAmountIn_) internal virtual override {
if (coinAmountIn_ > 0) {
uint256[4] memory _depositAmounts;
_depositAmounts[collateralIdx] = coinAmountIn_;
uint256 _lpAmountOutMin = _calculateAmountOutMin(address(collateralToken), address(crvLp), coinAmountIn_);
crvDeposit.add_liquidity(_depositAmounts, _lpAmountOutMin);
}
}
function _quoteLpToCoin(uint256 amountIn_, int128 i_) internal view virtual override returns (uint256 _amountOut) {
if (amountIn_ > 0) {
_amountOut = crvDeposit.calc_withdraw_one_coin(amountIn_, i_);
}
}
function _withdrawFromCurve(
uint256 lpAmount_,
uint256 minAmountOut_,
int128 i_
) internal virtual override {
crvDeposit.remove_liquidity_one_coin(lpAmount_, i_, minAmountOut_);
}
}
|
import React, { useEffect, useState } from "react";
import Sidebar from "../partials/Sidebar";
import Header from "../partials/Header";
import Datepicker from "../components/Datepicker";
import DashboardCard07 from "../partials/dashboard/DashboardCard07";
import DashboardCard10 from "../partials/dashboard/DashboardCard10";
import { NavLink } from "react-router-dom";
import api from "../services/api";
function Dashboard() {
const [sidebarOpen, setSidebarOpen] = useState(false);
const [data, setData] = useState([]);
const [filteredData, setFilteredData] = useState([]);
const fetchData = () => {
api
.get("/sales")
.then((response) => {
setData(response.data);
setFilteredData(response.data);
})
.catch((error) => {
console.log(error);
});
};
useEffect(() => {
fetchData();
}, []);
// Função para filtrar dados com base nas datas selecionadas
const handleDateSelect = (selectedDates) => {
if (selectedDates.length === 2) {
const startDate = selectedDates[0].toISOString().split("T")[0];
const endDate = selectedDates[1].toISOString().split("T")[0];
const filtered = data.filter((item) => {
const saleDate = item.sale_created_at.split(" ")[0];
return saleDate >= startDate && saleDate <= endDate;
});
setFilteredData(filtered);
}
};
return (
<div className="flex h-screen overflow-hidden">
{/* Sidebar */}
<Sidebar
sidebarOpen={sidebarOpen}
setSidebarOpen={setSidebarOpen}
/>
{/* Content area */}
<div className="relative flex flex-col flex-1 overflow-y-auto overflow-x-hidden">
{/* Site header */}
<Header
sidebarOpen={sidebarOpen}
setSidebarOpen={setSidebarOpen}
/>
<main>
<div className="px-4 sm:px-6 lg:px-8 py-8 w-full max-w-9xl mx-auto">
{/* Welcome banner */}
{/* <WelcomeBanner /> */}
{/* Dashboard actions */}
<div className="sm:flex sm:justify-between sm:items-center mb-8">
{/* Left: Avatars */}
{/* <DashboardAvatars /> */}
{/* Right: Actions */}
<div className="grid grid-flow-col sm:auto-cols-max justify-start sm:justify-end gap-2">
{/* Filter button */}
{/* <FilterButton /> */}
{/* Datepicker built with flatpickr */}
<Datepicker onSelectDate={handleDateSelect} />
{/* Add view button */}
<NavLink to={"/add-service"}>
<button className="btn bg-indigo-500 hover:bg-indigo-600 text-white">
<svg
className="w-4 h-4 fill-current opacity-50 shrink-0"
viewBox="0 0 16 16"
>
<path d="M15 7H9V1c0-.6-.4-1-1-1S7 .4 7 1v6H1c-.6 0-1 .4-1 1s.4 1 1 1h6v6c0 .6.4 1 1 1s1-.4 1-1V9h6c.6 0 1-.4 1-1s-.4-1-1-1z" />
</svg>
<span className="hidden xs:block ml-2">
Adicionar serviço
</span>
</button>
</NavLink>
</div>
</div>
{/* Cards */}
<div className="w-full flex flex-col space-y-7">
<DashboardCard07 data={filteredData} />
<DashboardCard10 data={filteredData} />
{/* <DashboardCard13 /> */}
</div>
</div>
</main>
</div>
</div>
);
}
export default Dashboard;
|
import { Link } from "react-router-dom";
import Button from "../Button";
import Checkbox from "../Checkbox";
import Form from "../Form";
import Illustration from "../Illustration";
import TextInput from "../TextInput";
import signupImage from "../../assets/images/signup.svg";
export default function Signup() {
return (
<>
<h1>Create an account</h1>
<div className="column">
<Illustration img={signupImage} />
<Form className="signup">
<TextInput type="text" placeholder="Enter name" icon="person" />
<TextInput
type="text"
placeholder="Enter email"
icon="alternate_email"
/>
<TextInput type="password" placeholder="Enter password" icon="lock" />
<TextInput
type="password"
placeholder="Confirm password"
icon="lock_clock"
/>
<Checkbox text="I agree to the Terms & Conditions" />
<Button>
<span>Submit Now</span>
</Button>
<div className="info">
Already have an account? <Link to="/login">Login</Link> instead.
</div>
</Form>
</div>
</>
);
}
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Blogger</title>
<!-- Google Fonts -->
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Barlow+Semi+Condensed:wght@400;500;600;700;800&family=Domine:wght@400;500;600;700&display=swap" rel="stylesheet">
<!-- -->
<!-- Font Awesome CDN -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<!-- -->
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<header class="header">
<div class="header__wrapper u-wrapper padding-inline-sm u-center">
<a class="header__home-link" href="#">
<img src="img/logo.png" alt="logo" class="header__logo-img">
</a>
<nav class="header__nav">
<ul class="header__nav-list">
<li class="header__nav-item">
<a href="#" class="header__nav-link">Blog</a>
</li>
<li class="header__nav-item">
<a href="#" class="header__nav-link">About</a>
</li>
<li class="header__nav-item">
<a href="#" class="header__nav-link">Guides</a>
</li>
<li class="header__nav-item">
<a href="#" class="header__nav-link">Wordpress Deals</a>
</li>
<li class="header__nav-item">
<a href="#" class="header__nav-link">Best WP Hosting</a>
</li>
<li class="header__nav-item">
<a href="#" class="header__nav-link">SML Store</a>
</li>
<li class="header__nav-item">
<a href="#" class="header__nav-link">SEO</a>
</li>
</ul>
<a class ="header__nav-link header__nav-link--search" href="#">
<i class="fa fa-search" aria-hidden="true"></i>
</a>
</nav>
</div>
</header>
<main>
<section class="section-hero u-padding-block-7">
<div class="u-wrapper section-hero__wrapper u-center">
<div class="section-hero__left">
<img src="img/hero.jpg" alt="hero" class="section-hero__img">
</div>
<div class="section-hero__right">
<h1 class="heading-primary u-margin-bottom-5">
Make Blogging Full-Time Business
</h1>
<p class="text-primary">
Learn to launch a successful niche blog and grow it to become financially independent. Learn the field-tested strategies, discover tools which would help you grow your online business. Join our newsletter to stay informed with the latest in SEO and WordPress space!
</p>
<form class="newsletter" action="#">
<input class="newsletter__input" type="text" name="first_name" placeholder="Your Name">
<input class="newsletter__input" type="text" name="email" placeholder="Your Email">
<input class="newsletter__input newsletter__input--btn" type="submit" name="button" value="Join Now.. It's Free!">
</form>
</div>
</div>
</section>
<section class="section-dream u-padding-block-10">
<h2 class="heading-secondary u-center-text u-margin-bottom-8">
<span class="u-inline-block u-border-bottom u-padding-bottom-4">I Want To</span>
</h2>
<div class="u-wrapper section-dream__wrapper u-center">
<div class="dream">
<img src="img/dream-1.png" alt="" class="dream__img">
<h3 class="heading-teritiary u-center-text u-fancy-font u-border-bottom u-border-top u-padding-block-3 u-full-width">Start a Blog</h3>
</div>
<div class="dream">
<img src="img/dream-2.png" alt="" class="dream__img">
<h3 class="heading-teritiary u-center-text u-fancy-font u-border-bottom u-border-top u-padding-block-3 u-full-width">Make Money blogging</h3>
</div>
<div class="dream">
<img src="img/dream-3.png" alt="" class="dream__img">
<h3 class="heading-teritiary u-center-text u-fancy-font u-border-bottom u-border-top u-padding-block-3 u-full-width">Install Wordpress</h3>
</div>
<div class="dream">
<img src="img/dream-4.png" alt="" class="dream__img">
<h3 class="heading-teritiary u-center-text u-fancy-font u-border-bottom u-border-top u-padding-block-3 u-full-width">Master Adsense</h3>
</div>
</div>
</section>
<section class="section-trending u-padding-block-10">
<h2 class="heading-secondary u-center-text u-margin-bottom-8">
<span class="u-inline-block u-border-bottom u-padding-bottom-4">Currently Trending</span>
</h2>
<div class="u-wrapper section-trending__wrapper u-center u-margin-bottom-8">
<div class="post">
<a href="#" class="post__tag">YouTube</a>
<a href="#" class="post__img-link u-margin-bottom-4">
<img class="post__img" src="img/post-1.jpg" alt="img">
</a>
<h3 class="heading-teritiary u-margin-bottom-7">
<a href="#">21+ Smart Ways To Get More YouTube Subscribers in 2022</a>
</h3>
<div class="post__info u-border-bottom u-border-top u-padding-block-3">
<a href="#">Jibin John</a>
<p>0 Comments</p>
</div>
</div>
<div class="post">
<a href="#" class="post__tag">Seo</a>
<a href="#" class="post__img-link u-margin-bottom-4">
<img class="post__img" src="img/post-2.jpeg" alt="img">
</a>
<h3 class="heading-teritiary u-margin-bottom-7">
<a href="#">6 Long Tail Keyword Finder Tool: Learn How To Find Long tail Keywords (2022)</a>
</h3>
<div class="post__info u-border-bottom u-border-top u-padding-block-3">
<a href="#">Jibin John</a>
<p>85 Comments</p>
</div>
</div>
<div class="post">
<a href="#" class="post__tag">Seo</a>
<a href="#" class="post__img-link u-margin-bottom-4">
<img class="post__img" src="img/post-3.jpg" alt="img">
</a>
<h3 class="heading-teritiary u-margin-bottom-7">
<a href="#">How To Build Internal Links for SEO in WordPress?</a>
</h3>
<div class="post__info u-border-bottom u-border-top u-padding-block-3">
<a href="#">Jibin John</a>
<p>95 Comments</p>
</div>
</div>
</div>
<div class="u-center-text">
<a href="#" class="btn-text u-fancy-font">Browse more</a>
</div>
</section>
<section class="section-deals u-padding-block-10">
<h2 class="heading-secondary u-center-text u-margin-bottom-8">
<span class="u-inline-block u-border-bottom u-padding-bottom-4">Today's Popular Deals</span>
</h2>
<div class="u-wrapper section-trending__wrapper u-center u-margin-bottom-8">
<div class="post">
<a href="#" class="post__img-link u-margin-bottom-4">
<img class="post__img" src="img/deal-1.png" alt="img">
</a>
<h3 class="heading-teritiary u-margin-bottom-7">
<a href="#">SiteGround Coupon Code: Up To 63% Discount Offer (2022)</a>
</h3>
</div>
<div class="post">
<a href="#" class="post__img-link u-margin-bottom-4">
<img class="post__img" src="img/deal-2.jpg" alt="img">
</a>
<h3 class="heading-teritiary u-margin-bottom-7">
<a href="#">[Deal Alert] BlueHost Hosting Coupon: Save 66% + Free Domain</a>
</h3>
</div>
<div class="post">
<a href="#" class="post__img-link u-margin-bottom-4">
<img class="post__img" src="img/deal-3.jpg" alt="img">
</a>
<h3 class="heading-teritiary u-margin-bottom-7">
<a href="#">TubeBuddy Discount Coupon Code: Save 25%</a>
</h3>
</div>
</div>
<div class="u-center-text">
<a href="#" class="btn-text u-fancy-font">View More Deals</a>
</div>
</section>
<section class="section-store u-padding-block-10">
<h2 class="heading-secondary u-center-text u-margin-bottom-8">
<span class="u-inline-block u-border-bottom u-padding-bottom-4">Blogger Store</span>
</h2>
<div class="u-wrapper section-store__wrapper u-center">
<div class="store">
<div class="store__left">
<img src="img/item.jpg" alt="book">
</div>
<div class="store__right">
<h3 class="heading-teritiary u-margin-bottom-3">
Earn $1000/Month – The Handbook To Affiliate Marketing (2021 Version)
</h3>
<span class="store__price u-margin-bottom-5">$29.99</span>
<p class="text-primary u-margin-bottom-9">
“The only resource you will ever need to learn about Affiliate marketing” ~ James Rowet Would you like to make money on auto-pilot? Forget about AdSense or display ads, I’m talking about money that requires you to work one time & enjoy the fruits of your labor for years. &
</p>
<div class="store__buttons">
<div>
<a class="u-inline-block u-fancy-font u-padding-block-3 u-border-bottom u-border-top u-margin-right-5" href="#">BUY NOW</a>
<a class="u-inline-block u-fancy-font u-padding-block-3 u-border-bottom u-border-top" href="#">DETAILS</a>
</div>
<div>
<a class="u-inline-block u-fancy-font u-padding-block-3 u-border-bottom u-border-top" href="#">VIEW ALL +</a>
</div>
</div>
</div>
</div>
</div>
</section>
<section class="section-community u-padding-block-10">
<h2 class="heading-secondary u-center-text u-margin-bottom-8">
<span class="u-inline-block u-border-bottom u-padding-bottom-4">Join Blogger Community</span>
</h2>
<div class="u-wrapper section-community__wrapper u-center">
<div class="community">
<div class="community__img u-margin-bottom-3">
<i class="fa fa-twitter" aria-hidden="true"></i>
</div>
<div class="community__details u-border-bottom u-border-top">
<a href="#">
<p href="#" class="community__name u-inline-block u-margin-bottom-3">Twitter</p>
<p href="#" class="community__follow-num">25k Followers</p>
</a>
</div>
</div>
<div class="community">
<div class="community__img u-margin-bottom-3">
<i class="fa fa-instagram" aria-hidden="true"></i>
</div>
<div class="community__details u-border-bottom u-border-top">
<a href="#">
<p href="#" class="community__name u-inline-block u-margin-bottom-3">Instagram</p>
<p href="#" class="community__follow-num">18.5k Subscribers</p>
</a>
</div>
</div>
<div class="community">
<div class="community__img u-margin-bottom-3">
<i class="fa fa-youtube-play" aria-hidden="true"></i>
</div>
<div class="community__details u-border-bottom u-border-top">
<a href="#">
<p href="#" class="community__name u-inline-block u-margin-bottom-3">Youtube</p>
<p href="#" class="community__follow-num">95k Subscribers</p>
</a>
</div>
</div>
<div class="community">
<div class="community__img u-margin-bottom-3">
<i class="fa fa-rss" aria-hidden="true"></i>
</div>
<div class="community__details u-border-bottom u-border-top">
<a href="#">
<p href="#" class="community__name u-inline-block u-margin-bottom-3">RSS Feed</p>
<p href="#" class="community__follow-num">6314 Followers</p>
</a>
</div>
</div>
</div>
</section>
<section class="section-about u-padding-block-10">
<div class="u-wrapper section-about__wrapper u-center">
<div class="about">
<div class="about__left">
<img src="img/person.jpg" alt="person" class="about__profile">
</div>
<div class="about__right">
<h2 class="heading-secondary u-margin-bottom-2">
<span class="u-inline-block u-border-bottom u-padding-bottom-4">Man Behind Blogger</span>
</h2>
<h3 class="heading-teritiary u-margin-bottom-5">
Author | Speaker
</h3>
<p class="text-primary">
Hey Shouter, welcome to the award-winning blog, ShoutMeLoud! I’m Harsh Agrawal, The blogging scientist.
</p>
<p class="text-primary">
I started ShoutMeLoud as a passion, and now it’s empowering more than 900,000+ readers globally by helping to live a boss-free life via blogging & digital marketing.
</p>
<p class="text-primary">
Here at ShoutMeLoud, I cover all the aspects of digital marketing. You will find free content around Blogging, SEO, WordPress, Web-hosting and making money online.
</p>
<p class="text-primary u-margin-bottom-6">
You can read more about SML at the “ About ” page.
</p>
<div class="about__socials u-padding-block-5 u-border-bottom u-border-top">
<span><i class="fa fa-twitter" aria-hidden="true"></i> /jibin</span>
<span><i class="fa fa-youtube-play" aria-hidden="true"></i> /jibin</span>
<span><i class="fa fa-instagram" aria-hidden="true"></i> /jibin</span>
</div>
</div>
</div>
</div>
</section>
<section class="section-learn u-padding-block-10">
<h2 class="heading-secondary u-margin-bottom-2 u-center-text">
<span class="u-inline-block u-border-bottom u-padding-bottom-4">Understand and Learn</span>
</h2>
<div class="u-wrapper section-dream__wrapper u-center">
<div class="dream">
<img src="img/learn-1.png" alt="" class="dream__img">
<h3 class="heading-teritiary u-center-text u-fancy-font u-border-bottom u-border-top u-padding-block-3 u-full-width">Start a Blog</h3>
</div>
<div class="dream">
<img src="img/learn-2.png" alt="" class="dream__img">
<h3 class="heading-teritiary u-center-text u-fancy-font u-border-bottom u-border-top u-padding-block-3 u-full-width">Make Money blogging</h3>
</div>
<div class="dream">
<img src="img/learn-3.png" alt="" class="dream__img">
<h3 class="heading-teritiary u-center-text u-fancy-font u-border-bottom u-border-top u-padding-block-3 u-full-width">Install Wordpress</h3>
</div>
<div class="dream">
<img src="img/learn-4.png" alt="" class="dream__img">
<h3 class="heading-teritiary u-center-text u-fancy-font u-border-bottom u-border-top u-padding-block-3 u-full-width">Master Adsense</h3>
</div>
<div class="dream">
<img src="img/learn-5.png" alt="" class="dream__img">
<h3 class="heading-teritiary u-center-text u-fancy-font u-border-bottom u-border-top u-padding-block-3 u-full-width">Master Adsense</h3>
</div>
<div class="dream">
<img src="img/learn-6.png" alt="" class="dream__img">
<h3 class="heading-teritiary u-center-text u-fancy-font u-border-bottom u-border-top u-padding-block-3 u-full-width">Master Adsense</h3>
</div>
</div>
</section>
<section class="section-course u-padding-block-10">
<h2 class="heading-secondary u-margin-bottom-9 u-center-text">
<span class="u-inline-block u-border-bottom u-padding-bottom-4">Join ShoutUniversity Course</span>
</h2>
<div class="u-wrapper section-course__wrapper u-center">
<div class="section-course__left">
<img src="img/course.png" alt="course" class="section-course__img">
</div>
<div class="section-course__right">
<h3 class="heading-teritiary u-margin-bottom-5">Start your journey towards becoming your own boss</h3>
<p class="text-primary">A structured video training to learn everything about Affiliate marketing, WordPress and more. Instant access + Private Facebook group. 20+ hours of video content.</p>
<p class="text-primary u-margin-bottom-8">Grab the special beta launch price before price increases to $399. Lifetime access!</p>
<a href="#" class="btn--primary">Buy Course</a>
</div>
</div>
</section>
</main>
<footer class="footer u-padding-block-8">
<p class="text-primary u-center-text">© blogger</p>
</footer>
</body>
</html>
|
# Zoo Text-to-CAD UI
This repository is an open-source example of how to quickly get up and running with Zoo's Text-to-CAD API endpoints. It is built using [SvelteKit](https://kit.svelte.dev/).
## Developing
1. Generate a dev API token from https://dev.zoo.dev
2. Set the `VITE_TOKEN` environment variable in `./.env.development` to the generated dev API token
3. Install yarn
4. Install dependencies with `yarn global add vite` and `yarn install`
5. Run the dev server with `yarn dev -- --open`
The full collection of scripts are listed in package.json.
## Building
To create a production version of your app:
```bash
yarn build
```
You can preview the production build with `yarn preview`.
## Before submitting a PR
Please run the following commands to ensure that your code is as ready for review as it can be:
```bash
yarn fmt --fix && yarn test
```
### Running Playwright E2E tests locally
In order to run our Playwright testing suite locally, please set the `PLAYWRIGHT_SESSION_COOKIE` variable within `.env.development` to a token from a logged in local development session. You can retrieve it by:
1. logging in to the project locally using the method outlined above
2. opening the Application tab in your browser developer tools
3. copying out the value of the cookie titled `__Secure-next-auth.session-token` with the domain of `localhost`
Now you should be able to run the `yarn test:integration` and `yarn test` commands successfully.
|
---
title: GüncellemeManifestForBrowserApplication Görev | Microsoft Dokümanlar
ms.date: 11/04/2016
ms.topic: reference
dev_langs:
- VB
- CSharp
- C++
- jsharp
helpviewer_keywords:
- UpdateManifestForBrowserApplication task [WPF MSBuild]
- adding the <hostInBrowser /> element to the application manifest [WPF MSBuild]
- building XBAP projects [WPF MSBuild]
- UpdateManifestForBrowserApplication task [WPF MSBuild], parameters
ms.assetid: 653339f7-654b-4d64-a26a-5c9f27036895
author: ghogen
ms.author: ghogen
manager: jillfra
ms.workload:
- multiple
ms.openlocfilehash: 079eecd6751f168a7beba32eda6d15eda712bd7f
ms.sourcegitcommit: cc841df335d1d22d281871fe41e74238d2fc52a6
ms.translationtype: MT
ms.contentlocale: tr-TR
ms.lasthandoff: 03/18/2020
ms.locfileid: "77631334"
---
# <a name="updatemanifestforbrowserapplication-task"></a>UpdateManifestForBrowserApplication görevi
Bir <xref:Microsoft.Build.Tasks.Windows.UpdateManifestForBrowserApplication> XAML Tarayıcı Uygulaması (XBAP) projesi oluşturulurken, görev ** \<hostInBrowser />** öğesini uygulama bildirimine*\<(projeadı>.exe.manifest)* eklemek için çalıştırılır.
## <a name="task-parameters"></a>Görev parametreleri
|Parametre|Açıklama|
|---------------|-----------------|
|`ApplicationManifest`|Gerekli **ITaskItem[]** parametresi.<br /><br /> `<hostInBrowser />` Öğeyi eklemek istediğiniz uygulama bildirimi dosyasının yolunu ve adını belirtir.|
|`HostInBrowser`|Gerekli **Boolean** parametresi.<br /><br /> Uygulama bildiriminin ** \<hostInBrowser />** öğesini içerecek şekilde değiştirilip değiştirilemeyeceğini belirtir. **Doğruysa,** ** \<entryPoint />** öğesine yeni ** \<bir hostInBrowser />** öğesi dahildir. Öğe ekleme kümülatif: bir ** \<hostInBrowser />** öğesi zaten varsa, kaldırılmaz veya üzerine yazılmamıştır. Bunun yerine, ek ** \<bir hostInBrowser />** öğesi oluşturulur. **Yanlışsa,** uygulama bildirimi değiştirilmez.|
## <a name="remarks"></a>Açıklamalar
XBAP'lar ClickOnce dağıtımı kullanılarak çalıştırılır, bu nedenle dağıtım ve uygulama bildirimlerini destekleyen şekilde yayımlanmalıdır. MSBuild, bir uygulama bildirimi oluşturmak için [GenerateApplicationManifest](generateapplicationmanifest-task.md) görevini kullanır.
Daha sonra, bir tarayıcıdan barındırılacak bir uygulamayı yapılandırmak için, aşağıdaki örnekte gösterildiği gibi uygulama bildirimine ek ** \<bir hostInBrowser />** öğesi eklenmelidir:
```xml
<!--MyXBAPApplication.exe.manifest-->
<?xml version="1.0" encoding="utf-8"?>
<asmv1:assembly ... >
<asmv1:assemblyIdentity ... />
<application />
<entryPoint>
...
<hostInBrowser xmlns="urn:schemas-microsoft-com:asm.v3" />
</entryPoint>
...
/>
```
Öğeyi <xref:Microsoft.Build.Tasks.Windows.UpdateManifestForBrowserApplication> eklemek `<hostInBrowser />` için bir XBAP projesi oluşturulduğunda görev çalıştırılır.
## <a name="example"></a>Örnek
Aşağıdaki örnek, öğenin bir `<hostInBrowser />` uygulama bildirimi dosyasına nasıl dahil edildiğinden nasıl emin olunan gösterilmektedir.
```xml
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<UsingTask
TaskName="Microsoft.Build.Tasks.Windows.UpdateManifestForBrowserApplication"
AssemblyFile="C:\Program Files\Reference Assemblies\Microsoft\Framework\v3.0\PresentationBuildTasks.dll" />
<Target Name="UpdateManifestForBrowserApplicationTask">
<UpdateManifestForBrowserApplication
ApplicationManifest="MyXBAPApplication.exe.manifest"
HostInBrowser="true" />
</Target>
</Project>
```
## <a name="see-also"></a>Ayrıca bkz.
- [WPF MSBuild başvurusu](../msbuild/wpf-msbuild-reference.md)
- [Görev başvurusu](../msbuild/wpf-msbuild-task-reference.md)
- [MSBuild başvurusu](../msbuild/msbuild-reference.md)
- [Görev başvurusu](../msbuild/msbuild-task-reference.md)
- [WPF uygulaması (WPF) oluşturma](/dotnet/framework/wpf/app-development/building-a-wpf-application-wpf)
- [WPF XAML tarayıcı uygulamalarına genel bakış](/dotnet/framework/wpf/app-development/wpf-xaml-browser-applications-overview)
|
import { CustomError, Genre } from '../interfaces';
import { GenreModel } from '../models';
export async function getGenres() {
try {
const genres = await GenreModel.find();
return genres;
} catch (error: any) {
throw new Error(error);
}
}
export async function getGenre(genreId: string) {
try {
const genre = await GenreModel.findById(genreId, 'name');
if (!genre) {
const error: CustomError = new Error('Could not find genre.');
error.statusCode = 404;
throw error;
}
return genre;
} catch (error: any) {
throw error;
}
}
export async function createGenre(input: Genre) {
try {
const genre = await GenreModel.create(input);
return genre;
} catch (error: any) {
throw new Error(error);
}
}
export async function updateGenre(genreId: string, { name }: Genre) {
try {
const genre = await GenreModel.findById(genreId, 'name');
if (!genre) {
const error: CustomError = new Error('Could not find genre.');
error.statusCode = 404;
throw error;
}
genre.name = name;
await genre.save();
return genre;
} catch (error: any) {
throw new Error(error);
}
}
export async function deleteGenre(genreId: string) {
try {
const genre = await GenreModel.findById(genreId);
if (!genre) {
const error: CustomError = new Error('Could not find genre.');
error.statusCode = 404;
throw error;
}
await GenreModel.findByIdAndRemove(genreId);
return genre;
} catch (error: any) {
throw error;
}
}
|
%
% Bales of hay problem in MiniZinc.
%
% From The Math Less Traveled,
% "The haybaler", http://www.mathlesstraveled.com/?p=582
% """
% You have five bales of hay.
%
% For some reason, instead of being weighed individually, they were weighed
% in all possible combinations of two. The weights of each of these
% combinations were written down and arranged in numerical order, without
% keeping track of which weight matched which pair of bales. The weights,
% in kilograms, were 80, 82, 83, 84, 85, 86, 87, 88, 90, and 91.
%
% How much does each bale weigh? Is there a solution? Are there multiple
% possible solutions?
% """
%
% This MiniZinc model was created by Hakan Kjellerstrand, hakank@bonetmail.com
% See also my MiniZinc page: http://www.hakank.org/minizinc
%
include "globals.mzn";
int: n = 5;
array[1..n] of var 0..50: bales;
array[1..10] of int: weights = [80, 82, 83, 84, 85, 86, 87, 88, 90, 91];
% solve satisfy;
solve :: int_search(bales, occurrence, indomain_min, complete) satisfy;
constraint
forall(w in 1..10) (
let {
var 1..n: i,
var 1..n: j
} in
i < j /\
bales[i] + bales[j] = weights[w]
)
/\ increasing(bales)
;
output [
% "bales: " ++ show(bales) ++ "\n"
"bale" ++ show(i) ++ ": " ++ show(bales[i]) ++ "\n"
| i in 1..n
] ++ ["\n"];
|
import axios from "axios";
import { all, call, put, takeLatest } from "redux-saga/effects";
import { IDog } from "../types/types";
import {
fetchDogsFailure,
fetchDogsSuccess
} from "../../actions/dogsActions/dogsActions";
import { dogsTypes } from "../../Actiontypes/dogsTypes";
const getDogs = () =>
axios.get<IDog[]>("https://jsonplaceholder.typicode.com/todos");
function* fetchDogsSaga() {
try {
const response = yield call(getDogs);
yield put(
fetchDogsSuccess({
dogs: response.data
})
);
} catch (e) {
yield put(
fetchDogsFailure({
error: e.message
})
);
}
}
function* dogsSaga() {
yield all([takeLatest(dogsTypes.FETCH_DOG_REQUEST, fetchDogsSaga)]);
}
export default dogsSaga;
|
#BEGIN COPYRIGHT NOTICE
#utilityFuncs -- (c) 2022 Dimitrios Kleftogiannis -- UiB and CCBIO
#Copyright 2022 University of Bergen (UiB), Norway.
#This Program is free software licensed under the MIT License.
#You may only use the source code in this repository in compliance with the license provided in this repository.
#For more details, please refer to the file named "LICENSE.md".
#This Program is distributed as a service to the research community and is experimental in nature and may have hazardous properties.
#The Program is distributed WITHOUT ANY WARRANTY, express or implied. In particular all warranties as to SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR PURPOSE are excluded.
#Published reports of research using this code (or a modified version) should cite the relevant article of this code
#Comments and bug reports are welcome.
#Email to dimitrios.kleftogiannis@uib.no
#I would also appreciate hearing about how you used this code, improvements that you have made to it.
#You are free to modify, extend or distribute this code, as long as this copyright notice is included whole and unchanged.
#END COPYRIGHT NOTICE
#UTILITY
#Different utility functions required by generateFeatures code.
#function to normalise outliers based on quantiles, defautl values are 0.02 and 0.98 but change if needed
remove_outliers <- function(x, na.rm = TRUE, ...) {
qnt <- quantile(x, probs=c(0.02, 0.98), na.rm = na.rm, ...)
H <- 1.5 * IQR(x, na.rm = na.rm)
y <- x
y[x < (qnt[1] - H)] <- NA
y[x > (qnt[2] + H)] <- NA
y
}
#find appropriate cutoffs for DREMI estimation, adopted from the original DREMI implementation in MATLAB (c)
find_data_cutoffs <- function(m,cutoff,num_slices){
X <- m[,1]
Y <- m[,2]
Xmin <- min(X,na.rm = TRUE)
Xmax <- max(X, na.rm = TRUE)
Ymin <- min(Y,na.rm = TRUE)
Ymax <- max(Y,na.rm=TRUE)
Z <- my_kde2D(m,n=num_slices+1,limits=c(Xmin,Xmax,Ymin,Ymax))
bandwidth <- Z$bandwidth
density <- Z$density
Grid_X <- Z$X
Grid_Y <- Z$Y
#round small values of density
density[density<0.00001] <- 0
row=0;
total_cells_so_far = 0;
while(total_cells_so_far<cutoff & row < (num_slices-1)){
row = row+1;
total_cells_so_far = length(find(Y>Grid_Y[num_slices-row,1]));
}
maxy = Grid_Y[num_slices-row,1];
total_cells_so_far = 0;
start_row = 0;
while(total_cells_so_far<cutoff){
start_row <- start_row + 1;
total_cells_so_far <- length(find(Y<Grid_Y[start_row,1]));
}
miny <- Grid_Y[start_row,1];
total_cells_so_far = 0;
col=0;
breakCounter <- 1
while(total_cells_so_far<cutoff & col < (num_slices/2-1)){
col <- col+1;
total_cells_so_far <- length(find(X>Grid_X[1,num_slices-col]));
}
maxx = Grid_X[1,num_slices-col];
total_cells_so_far = 0;
start_col=0;
while(total_cells_so_far<cutoff & start_col <= (num_slices/2)){
start_col = start_col+1;
total_cells_so_far = length(find(X<Grid_X[1,start_col]));
}
minx = Grid_X[1,start_col];
out <- list(minx,miny,maxx,maxy)
return(out)
}
#use this version of kde - based on the original DREMI publication (c)
my_kde2D <- function (data, n = 2^8, limits = NULL) {
ndhist <- function(data, M) {
bins <- zeros(nrow(data), ncol(data))
for (i in 1:ncol(data)) {
bins[, i] <- histc(data[, i], seq(0, 1, 1/M))$bin
bins[, i] <- apply(as.matrix(bins[, i]), 1, function(y) min(y,
M))
}
#i added this part of code to fix the bug
a <- which(bins[,1]>0 & bins[,2]>0)
bins <- bins[a,]
out <- accumarray(bins[all(bins > 0), ], rep((1/nrow(data)),
nrow(data)), M * (ones(1, ncol(data))))
return(out)
}
dct2d <- function(data) {
dct1d <- function(x) {
x <- rbind(x[seq(1, nrow(x), 2), ], x[seq(nrow(x),
2, -2), ])
out <- Re(weights * mvfft(x))
return(out)
}
w <- as.matrix(c(1, 2 * (exp(-(0+1i) * (1:(nrow(data) -
1)) * pi/(2 * nrow(data))))))
weights <- w[, ones(1, ncol(data))]
data <- t(dct1d(t(dct1d(data))))
return(data)
}
idct2d <- function(data) {
idct1d <- function(x) {
y <- Re(ifft_mat(weights * x))
out <- zeros(nrow(data), ncol(data))
out[seq(1, nrow(data), 2), ] <- y[1:(nrow(data)/2),
]
out[seq(2, nrow(data), 2), ] <- y[seq(nrow(data),
nrow(data)/2 + 1, -1), ]
return(out)
}
ifft_mat <- function(x) {
x <- apply(x, 2, function(y) ifft(y))
return(x)
}
w <- as.matrix(exp((0+1i) * (0:(nrow(data) - 1)) * pi/(2 *
nrow(data))))
weights <- w[, ones(1, ncol(data))]
out <- idct1d(t(idct1d(data)))
return(out)
}
K <- function(s) {
if (s == 0) {
out <- (-1)^s/sqrt(2 * pi)
}
else {
out <- (-1)^s * prod(seq(from = 1, to = 2 * s -
1, by = 2))/sqrt(2 * pi)
}
return(out)
}
psi <- function(s, time) {
w <- c((exp(-I * pi^2 * time))) * c(cbind(1, 0.5 * ones(1,
length(I) - 1)))
wx <- t(w * (I^s[1]))
wy <- t(w * (I^s[2]))
out <- (-1)^sum(s) * (wy %*% A2 %*% t(wx)) * pi^(2 *
sum(s))
return(out)
}
func <- function(s, t) {
if (sum(s) <= 4) {
sum_func <- func(c(s[1] + 1, s[2]), t) + func(c(s[1],
s[2] + 1), t)
const <- (1 + 1/2^(sum(s) + 1))/3
time <- c((-2 * const * K(s[1]) * K(s[2])/N/sum_func)^(1/(2 +
sum(s))))
out <- psi(s, time)
}
else {
out <- psi(s, t)
}
return(out)
}
evolve <- function(t) {
sum_func <- func(c(0, 2), t) + func(c(2, 0), t) + 2 *
func(c(1, 1), t)
time <- (2 * pi * N * sum_func)^(-1/3)
out <- (t - time)/time
return(c(out, time))
}
subtract_evolve <- function(t) {
return(t - evolve(t))
}
N <- nrow(data)
n <- 2^ceiling(log2(n))
if (is.null(limits)) {
max <- c(max(data[, 1]), max(data[, 2]))
min <- c(min(data[, 1]), min(data[, 2]))
range <- max - min
max_xy <- max + range/4
min_xy <- min - range/4
}
else {
max_xy <- c(limits[2], limits[4])
min_xy <- c(limits[1], limits[3])
}
scaling <- max_xy - min_xy
data_trans <- (data - repmat(min_xy, N, 1))/repmat(scaling,
N, 1)
data_init <- ndhist(data_trans, n)
data_DCT <- dct2d(data_init)
I <- (0:(n - 1))^2
A2 <- data_DCT^2
t_star <- fzero(subtract_evolve, c(0, 0.1))[[1]]
p_02 <- func(c(0, 2), t_star)
p_20 <- func(c(2, 0), t_star)
p_11 <- func(c(1, 1), t_star)
t_y <- (p_02^(3/4)/(4 * pi * N * p_20^(3/4) * (p_11 + sqrt(p_20 *
p_02))))^(1/3)
t_x <- (p_20^(3/4)/(4 * pi * N * p_02^(3/4) * (p_11 + sqrt(p_20 *
p_02))))^(1/3)
data_DCT_smoothed <- (t(t(exp(-(0:(n - 1))^2 * pi^2 * c(t_x)/2))) %*%
t(exp(-(0:(n - 1))^2 * pi^2 * c(t_y)/2))) * data_DCT
density <- idct2d(data_DCT_smoothed) * (numel(data_DCT_smoothed)/prod(scaling))
grid <- meshgrid(seq(min_xy[1], max_xy[1], by = scaling[1]/(n -
1)), seq(min_xy[2], max_xy[2], by = scaling[2]/(n -
1)))
bw <- sqrt(cbind(t_x, t_y)) * scaling
return(list(bandwidth = bw, density = density, X = grid[[1]],
Y = grid[[2]]))
}
#funtion that estimates the DREMI score - adopted from the original DREMI implementation in MATLAB (c)
compute_dremi <- function(m, markerX,markerY,noise_threshold,set_maxy,maxy,makePlot,myLabel){
#start with the basic parameters from the original script
compute_pvalue <- 0;
set_maxy <- set_maxy;
num_permutations <- 0;
max_yval <- 0;
num_slices <- 8;
non_kde_style <- 0;
min_yval <- 0;
maxy_val <- maxy
use_min_y <- max(c(0, min(m[,2],na.rm = TRUE)));
if(non_kde_style==0){
if(set_maxy==0){
#by default
num_slices <- 256
myMethod <- 'non_averaged_pts'
fixy <- 0
minyval <- 0
maxyval <- max(m[,2],na.rm = TRUE)
fix_limits <- 0
Limits <- c()
Z <- pairwise_visualise(m,markerX,markerY,myMethod,
noise_threshold,
num_slices,
fixy,minyval,maxyval,
fix_limits,Limits,
makePlot,myLabel);
}
else{
#pairwise_visualize(channel1_name, channel2_name,'non_averaged_pts', noise_threshold,'no_plot', 'MinMaxY', use_min_y, maxy_val);
#by default
num_slices <- 256
myMethod <- 'non_averaged_pts'
fixy <- 1
minyval <- 0
maxyval <- max(m[,2],na.rm = TRUE)
fix_limits <- 0
Limits <- c()
minyval <- use_min_y
maxyval <- maxy
Z <- pairwise_visualise(m,markerX,markerY,
myMethod,
noise_threshold,
num_slices,
fixy,minyval,maxyval,
fix_limits,Limits,makePlot,myLabel);
}
points_x <- Z[[1]]
points_y <- Z[[2]]
point_weights <- Z[[3]]
total_slice_samples <- sum(point_weights) * 1000;
samples_x <- c();
samples_y <- c();
for(i in 1:length(points_x)){
num_repeats <- floor(point_weights[i] * 1000);
new_samples_x <- matrix(1,nrow = num_repeats,ncol=1)*points_x[i];
new_samples_y <- matrix(1,nrow = num_repeats,ncol=1)*points_y[i];
samples_x = rbind(samples_x, new_samples_x);
samples_y = rbind(samples_y, new_samples_y);
}
data <- cbind(samples_x, samples_y);
minx <- min(data[,1])
miny <- min(data[,2])
maxx <- max(data[,1])
maxy <- max(data[,2])
}else{
res <- find_data_cutoffs(X,Y, 50, 255);
minx <- res[[1]]
miny <- res[[3]]
maxx <- res[[2]]
maxy <- res[[4]]
}
if(set_maxy==1){
maxy <- maxy_val;
}
if(non_kde_style == 0){
num_slices <- 32
out <- delta_entropyweight_rawdata(data, minx, miny, maxx, maxy,num_slices,num_slices)
}else{
#dremi = delta_entropyreweight(obj, channel1_name, channel2_name, num_slices, num_slices, minx, miny, maxx, maxy)
}
pvalue <- 0;
if(num_permutations == 0){
compute_pvalue <- 0;
}
if(compute_pvalue ==1){
#compute p value after permutations
#TODO once finish with delta_entropy
}
return(out)
}
#argument m is a 2D matrix with X,and Y markers after removing outliers
#markerX and markerY are the names of markers, just to help visualisation labels
#Limits is an array in the format (minx,miny,maxx,maxy)
pairwise_visualise <- function(m,markerX,markerY,
myMethod,
noise_threshold,
num_slices,
fixy,minyval,maxyval,
fix_limits,Limits,
makePlot,myLabel)
{
mySample <- myLabel
#str <- paste('Processing sample:',mySample,' ',markerX,' vs. ',markerY,sep='')
#print(str)
X <- m[,1]
Y <- m[,2]
if(myMethod=='non_averaged_pts'){
avg_pts <- 0
avg_pts_threshold <- noise_threshold;
}else{
avg_pts <- 1
avg_pts_threshold <- 0.9;
}
#utility variables from the original Matlab code
num_slices <- num_slices;
minxval <- 0;
minyval <- minyval;
cutoff <- 50;
draw_contour <- 0;
show_density <- 0;
#make the plot the first time
draw_plot <- makePlot;
avg_pts <- avg_pts;
fix_limits <- fix_limits;
maxyval <- maxyval ;
maxxval <- max(m[,1],na.rm = TRUE);
fixy <- fixy;
visual_threshold <- 0;
axes_specified <- 0;
axes_handle <- 0;
if (fix_limits == 0){
Xmin = minxval;
Xmax = maxxval;
Ymin = minyval;
Ymax = maxyval;
}else{
minx <- Limits[1]
miny <- Limits[2]
maxx <- Limits[3]
maxy <- Limits[4]
Xmin = minx;
Xmax = maxx;
Ymin = miny;
Ymax = maxy;
}
if(fixy == 1){
Ymin = minyval;
Ymax = maxyval;
}
#compute the 2D density,
if(fix_limits == 0){
Z <- my_kde2D(m,n=num_slices,limits=c(Xmin,Xmax,Ymin,Ymax))
}else{
#here we make a change because the code does not work with reduced box
Z <- my_kde2D(m,n=num_slices,limits=c(minx,maxx,miny,maxy))
}
#get the variables we need
bandwidth <- Z$bandwidth
density <- Z$density
Grid_X <- Z$X
Grid_Y <- Z$Y
#round small values of density
density[density<0.00001] <- 0
#weeding out spare ends
row <- 0;
total_cells_so_far <- 0;
while(total_cells_so_far<cutoff & row < (num_slices-1)){
row <- row+1
total_cells_so_far <- length(find(Y>Grid_Y[num_slices-row,1]))
}
maxy <- Grid_Y[num_slices-row,1]
total_cells_so_far <- 0;
start_row <- 0
while(total_cells_so_far<cutoff){
start_row <- start_row + 1
total_cells_so_far <- length(find(Y<Grid_Y[start_row,1]))
}
miny <- Grid_Y[start_row,1]
total_cells_so_far <- 0;
col <- 0
while(total_cells_so_far<cutoff & col < (num_slices/2-1)){
col <- col+1
total_cells_so_far <- length(find(X>Grid_X[1,num_slices-col]))
}
maxx = Grid_X[1,num_slices-col];
total_cells_so_far <- 0;
start_col <- 0;
while(total_cells_so_far<cutoff & start_col <= (num_slices/2)){
start_col = start_col+1;
total_cells_so_far = length(which(X<Grid_X[1,start_col]))
}
minx = Grid_X[1,start_col]
if(fix_limits == 1){
start_row <- 1
start_col <- 1
row <- 0
col <- 0
}
if(fixy==1){
start_row <- 1
row <- 0
}
#filter density
density <- density[start_row:(num_slices-row),start_col:(num_slices-col)]
num_cols <- ncol(density)
num_rows <- nrow(density)
xaxis = Grid_X[1,start_col:(num_slices-col)]
yaxis = Grid_Y[start_row:(num_slices-row),1]
normalized_density <- matrix(0L,nrow = num_rows,ncol = num_cols)
prob_normalized_density <- matrix(0L,nrow = num_rows,ncol = num_cols)
#normalized by column for plotting the data
for(i in 1:num_cols){
#normalized_density(:,i) = density(:,i)/norm(density(:,i),1);
normalized_density[,i] <- density[,i]/max(density[,i],na.rm=TRUE)
prob_normalized_density[,i] <- density[,i]/Norm(density[,i])
}
#now create the side bars
colsum <- colSums(density,na.rm = TRUE);
normalized_colsum <- colsum/max(colsum,na.rm = TRUE);
rowsum <- rowSums(density,na.rm = TRUE);
normalized_rowsum <- rowsum/max(rowsum,na.rm = TRUE);
#the corner is a fudge
#blueval = min(normalized_colsum);
blueval <- 0;
corner <- matrix(1,nrow = 11,ncol = 11)*blueval;
#make the top bar
#yaxis_increment = abs(yaxis(2)-yaxis(1,1));
yaxis_increment <- 0.01;
yaxis_top_bar <- c();
top_bar <- c();
zero_vector <- matrix(0L,nrow = 1,ncol = length(normalized_colsum));
for(i in 1:1){
top_bar <- rbind(top_bar, zero_vector)
yaxis_top_bar <- rbind(yaxis_top_bar, max(yaxis)+(yaxis_increment*i))
}
for(i in 1:10){
top_bar <- rbind(top_bar, normalized_colsum);
yaxis_top_bar <- rbind(yaxis_top_bar, max(yaxis)+(yaxis_increment*i));
}
#make the side bar
#xaxis_increment = abs(xaxis(2)-xaxis(1));
xaxis_increment <- 0.01
xaxis_side_bar <- c()
side_bar <- c()
zero_vector <- matrix(0L,nrow=length(normalized_rowsum),ncol=1)
for(i in 1:1){
side_bar <- cbind(side_bar, zero_vector);
xaxis_side_bar <- cbind(xaxis_side_bar, max(xaxis)+(xaxis_increment*i))
}
for(i in 1:10){
side_bar <- cbind(side_bar, normalized_rowsum)
xaxis_side_bar <- cbind(xaxis_side_bar, max(xaxis)+(xaxis_increment*i))
}
#find the trace through the peak regions for the return value
points_x <- c()
points_y <- c()
point_weights <- c()
if(avg_pts==1){
for(i in 1:num_cols){
max_indices <- which(normalized_density[,i]>= avg_pts_threshold)
# points_y = [points_y mean(Grid_Y(max_indices,i))];
points_x <- cbind(points_x, xaxis[i])
#new_point_y = dot(Grid_Y(start_row+max_indices,start_col+i),normalized_density(max_indices,i));
points_y <- cbind(points_y, mean(yaxis[max_indices]) )
#points_y = [points_y new_point_y];
}
point_weights <- matrix(1,nrow = 1,ncol = length(points_y))
}else{
#this part of the code implements the non average points method
#it is more complicated and it will be skipped for now, since we are working with default parameters
for(i in 1:num_cols){
max_indices <- find(normalized_density[,i]>= avg_pts_threshold)
new_points <- matrix(1,nrow=1,ncol=length(max_indices))*xaxis[i];
new_point_weights <- t(normalized_density[max_indices,i])
new_point_weights <- new_point_weights / (sum(new_point_weights));
points_x <- cbind(points_x, new_points);
y_indices <- max_indices;
new_points_y <- t(yaxis[y_indices]);
points_y <- cbind(points_y, new_points_y);
point_weights <- cbind(point_weights, new_point_weights);
}
}
smoothed_normalized_density <- matrix(0L,nrow = num_rows,ncol = num_cols)
for(i in 1:num_rows){
for(j in 2:(num_cols-1)){
smoothed_normalized_density[i,j] = (normalized_density[i,j-1]+normalized_density[i,j]+normalized_density[i,j+1])/3;
}
}
if(visual_threshold>0){
smoothed_normalized_density <- (smoothed_normalized_density>visual_threshold)*smoothed_normalized_density;
}
matrix_to_plot <- cbind(smoothed_normalized_density, side_bar);
top_bar <- cbind(top_bar, corner)
matrix_to_plot <- rbind(matrix_to_plot,top_bar)
#xaxis_side_bar[1] <- xaxis_side_bar[1]-0.01
#yaxis_side_bar[1] <- yaxis_side_bar[1]-0.01
xaxis_to_plot <- c(xaxis, xaxis_side_bar)
yaxis_to_plot <- c(yaxis, yaxis_top_bar)
#a1 <- sample(1:length(xaxis_to_plot),108)
#a1 <- xaxis_to_plot[a1]
#a2 <- sample(1:length(yaxis_to_plot),108)
#a2 <- yaxis_to_plot[a2]
#FROM NOW ON WE MAKE THE PLOTS
#make the plot
if(draw_plot==1){
if(axes_specified==1){
#here this part of the code is quite similar to the next....but we work with defaults
}else{
#this is the matlab plot
#imagesc(matrix_to_plot,col=jet.colors(12),xlab='marker1',ylab='marker2');
#save the plot
myfile<-paste(plot_dir,myLabel,'.pdf',sep='')
pdf(myfile,onefile = TRUE)
image(x=c(1:ncol(matrix_to_plot)),y=c(1:nrow(matrix_to_plot)),t(matrix_to_plot),
axes=FALSE,xlab=markerX,ylab=markerY,
col = hcl.colors(12, "Spectral", rev = TRUE))
d <- c(1:ncol(smoothed_normalized_density))
d <- quantile(d)
#1,50,100,150,200,ncol(smoothed_normalized_density)
a <- c(d[1],d[2],d[3],d[4],d[5])
a <- round(a)
axis(1,at=a,labels = round(xaxis_to_plot[a],2))
#a <- c(1,50,100,150,200,nrow(smoothed_normalized_density))
d <- c(1:nrow(smoothed_normalized_density))
d <- quantile(d)
a <- c(d[1],d[2],d[3],d[4],d[5])
a <- round(a)
axis(2,at=a,labels = round(yaxis_to_plot[a],2))
dev.off()
}
#additional plot with two colors not implemented
#density_filtered_v1 <- matrix_to_plot>0.6
#matrix_to_plot_v1 <- matrix_to_plot*density_filtered_v1;
#imagesc(matrix_to_plot)
}
#draw contours
if(draw_contour==1){
Z <- kde2D(m,num_slices+1,limits=c(minx, maxx,miny, maxy))
rdensity <- Z$density
rGrid_X <- Z$X
rGrid_Y <- Z$Y
}
#this can be imporeved using ggplot - TODO
if(show_density==1){
f <- kde(m[,1]);
Fx <- approx(f[1,],f[2,],xout=points_x)
Fx <- Fx$y
Fx[Fx<0.00001] <- 0
plot(points_x,Fx,col='black',cex=1);
}
out <- list(points_x,points_y,point_weights,density,normalized_density,
xaxis_to_plot,yaxis_to_plot,top_bar,side_bar)
return(out)
}
# adopted from the original DREMI implementation in MATLAB
delta_entropyweight_rawdata <- function(data, minx, miny, maxx, maxy, num_slicesx, num_slicesy){
fixed_partition <- 0;
#skip the part with extra arguments
if(fixed_partition == 0){
xincrement <- (maxx-minx)/num_slicesx;
yincrement <- (maxy-miny)/num_slicesy;
edges_x <- c(minx);
for(i in 1:(num_slicesx-1)){
edges_x <- cbind(edges_x, edges_x[i]+xincrement);
}
edges_x <- cbind(edges_x, maxx);
edges_y <- c(miny);
for(i in 1:(num_slicesy-1)){
edges_y <- cbind(edges_y, edges_y[i]+yincrement);
}
edges_y <- cbind(edges_y, maxy);
edges <- list()
edges[[1]] <- edges_x;
edges[[2]] <- edges_y;
}
#this part of the code replaces the hist3 implemented in matlab
nbins <- length(edges_x)
x.bin <- edges_x
y.bin <- edges_y
freq <- as.data.frame(table(findInterval(data[,1], x.bin,left.open=TRUE,rightmost.closed=TRUE),
findInterval(data[,2], y.bin,left.open=TRUE,rightmost.closed=TRUE)))
freq[,1] <- as.numeric(freq[,1])
freq[,2] <- as.numeric(freq[,2])
freq2D <- diag(nbins)*0
freq2D[cbind(freq[,1], freq[,2])] <- freq[,3]
#need to be a bit careful here with the transpose operation
hist_bins <- t(freq2D)
hist_bin_totals = colSums(hist_bins);
bin_totals <- t(hist_bin_totals);
num_rows <- nbins
num_cols <- nbins
#here comes the entropy computations
entropy_y <- 0;
column_weights <- matrix(1,nrow=1,ncol=num_cols);
slice_entropies <- matrix(0,nrow=1,ncol=num_cols);
total <- sum(column_weights[1,]);
for(i in 1:num_rows){
p_y = 0;
for(j in 1:num_cols){
column_total = sum(hist_bins[,j]);
if(column_total > 0){
p_y = p_y + (hist_bins[i,j]*(column_weights[j]/column_total));
}
}
p_y <- p_y/total;
if(p_y==0){
p_y <- 0;
log_p_y <- 0;
}else{
log_p_y <- log2(p_y);
}
entropy_y <- entropy_y+(p_y * log_p_y);
}#end of for loop
entropy_y <- -1*entropy_y;
cond_entropy_y <- 0
for(j in 1:num_cols){
slice_entropy_y <- 0;
col_sum <- sum(hist_bins[,j]);
if(col_sum == 0){
next;
}
norm_col_hist <- hist_bins[,j]/col_sum;
for(i in 1:num_rows){
slice_p_y <- norm_col_hist[i];
if(slice_p_y==0){
slice_p_y <- 0;
log_slice_p_y <- 0;
}else{
slice_p_y;
log_slice_p_y <- log2(slice_p_y);
}
slice_entropy_y = slice_entropy_y + (slice_p_y * log_slice_p_y);
}
slice_entropy_y <- -1*slice_entropy_y;
slice_entropies[j] <- slice_entropy_y;
col_prob <- column_weights[1,j]/sum(column_weights[1,]);
cond_entropy_y <- cond_entropy_y + (col_prob * slice_entropy_y);
#print(cond_entropy_y)
}
# slice_entropies
# entropy_y
delta_before_division <- entropy_y - cond_entropy_y;
cond_entropy_y_before_division <- cond_entropy_y;
#normalize this by the size of the grid
smaller_dim <- min(num_rows, num_cols);
log_smaller_dim <- log2(smaller_dim);
#this is supposed to be the maximum achievable value on a grid this
#size
delta <- delta_before_division/log_smaller_dim
cond_entropy_y <- cond_entropy_y/log_smaller_dim
out <- list(delta, entropy_y, cond_entropy_y, hist_bins, data, edges)
return(out)
}
|
/*
* Copyright (c) 2018-2019 Peter Bigot Consulting, LLC
* Copyright (c) 2019-2020 Nordic Semiconductor ASA
*
* SPDX-License-Identifier: Apache-2.0
*/
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <zephyr/kernel.h>
#include <zephyr/init.h>
#include <zephyr/drivers/gpio.h>
#include <zephyr/drivers/adc.h>
#include <zephyr/drivers/sensor.h>
#include <zephyr/logging/log.h>
#include "adc.h"
#define SAADC_CH_PSELP_PSELP_AnalogInput0 (1U)
#define ZEPHYR_USER DT_PATH(zephyr_user)
/* Other boards may use dividers that only reduce battery voltage to
* the maximum supported by the hardware (3.6 V)
*/
#define BATTERY_ADC_GAIN ADC_GAIN_1_6
struct io_channel_config {
uint8_t channel;
};
struct divider_config {
struct io_channel_config io_channel;
struct gpio_dt_spec power_gpios;
/* output_ohm is used as a flag value: if it is nonzero then
* the battery is measured through a voltage divider;
* otherwise it is assumed to be directly connected to Vdd.
*/
uint32_t output_ohm;
uint32_t full_ohm;
};
static const struct divider_config divider_config = {
.io_channel = {
DT_IO_CHANNELS_INPUT(ZEPHYR_USER),
},
};
struct divider_data {
const struct device *adc;
struct adc_channel_cfg adc_cfg;
struct adc_sequence adc_seq;
int16_t raw;
};
static struct divider_data divider_data = {
.adc = DEVICE_DT_GET(DT_IO_CHANNELS_CTLR(ZEPHYR_USER)),
};
int divider_setup(void)
{
const struct divider_config *cfg = ÷r_config;
const struct io_channel_config *iocp = &cfg->io_channel;
const struct gpio_dt_spec *gcp = &cfg->power_gpios;
struct divider_data *ddp = ÷r_data;
struct adc_sequence *asp = &ddp->adc_seq;
struct adc_channel_cfg *accp = &ddp->adc_cfg;
int rc;
if (!device_is_ready(ddp->adc)) {
printk("ADC device is not ready %s", ddp->adc->name);
return -ENOENT;
}
if (gcp->port) {
if (!device_is_ready(gcp->port)) {
printk("%s: device not ready", gcp->port->name);
return -ENOENT;
}
rc = gpio_pin_configure_dt(gcp, GPIO_OUTPUT_INACTIVE);
if (rc != 0) {
printk("Failed to control feed %s.%u: %d",
gcp->port->name, gcp->pin, rc);
return rc;
}
}
*asp = (struct adc_sequence){
.channels = BIT(0),
.buffer = &ddp->raw,
.buffer_size = sizeof(ddp->raw),
.oversampling = 4,
.calibrate = true,
};
*accp = (struct adc_channel_cfg){
.gain = BATTERY_ADC_GAIN,
.reference = ADC_REF_INTERNAL,
.acquisition_time = ADC_ACQ_TIME(ADC_ACQ_TIME_MICROSECONDS, 40),
};
accp->input_positive = SAADC_CH_PSELP_PSELP_AnalogInput0
+ iocp->channel;
asp->resolution = 14;
rc = adc_channel_setup(ddp->adc, accp);
printk("Setup AIN%u got %d", iocp->channel, rc);
return rc;
}
static bool battery_ok;
int battery_setup(void)
{
int rc = divider_setup();
battery_ok = (rc == 0);
printk("Battery setup: %d %d", rc, battery_ok);
return rc;
}
int battery_measure_enable(bool enable)
{
int rc = -ENOENT;
if (battery_ok) {
const struct gpio_dt_spec *gcp = ÷r_config.power_gpios;
rc = 0;
if (gcp->port) {
rc = gpio_pin_set_dt(gcp, enable);
}
}
return rc;
}
int battery_sample(void)
{
int rc = -ENOENT;
if (battery_ok) {
struct divider_data *ddp = ÷r_data;
const struct divider_config *dcp = ÷r_config;
struct adc_sequence *sp = &ddp->adc_seq;
rc = adc_read(ddp->adc, sp);
sp->calibrate = false;
if (rc == 0) {
int32_t val = ddp->raw;
adc_raw_to_millivolts(adc_ref_internal(ddp->adc),
ddp->adc_cfg.gain,
sp->resolution,
&val);
if (dcp->output_ohm != 0) {
rc = val * (uint64_t)dcp->full_ohm
/ dcp->output_ohm;
printk("raw %u ~ %u mV => %d mV\n",
ddp->raw, val, rc);
} else {
rc = val;
printk("raw %u ~ %u mV\n", ddp->raw, val);
}
}
}
return rc;
}
unsigned int battery_level_pptt(unsigned int batt_mV,
const struct battery_level_point *curve)
{
const struct battery_level_point *pb = curve;
if (batt_mV >= pb->lvl_mV) {
/* Measured voltage above highest point, cap at maximum. */
return pb->lvl_pptt;
}
/* Go down to the last point at or below the measured voltage. */
while ((pb->lvl_pptt > 0)
&& (batt_mV < pb->lvl_mV)) {
++pb;
}
if (batt_mV < pb->lvl_mV) {
/* Below lowest point, cap at minimum */
return pb->lvl_pptt;
}
/* Linear interpolation between below and above points. */
const struct battery_level_point *pa = pb - 1;
return pb->lvl_pptt
+ ((pa->lvl_pptt - pb->lvl_pptt)
* (batt_mV - pb->lvl_mV)
/ (pa->lvl_mV - pb->lvl_mV));
}
|
import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core';
@Directive({
selector: '[appRepeat]',
})
export class RepeatDirective {
constructor(
private templateRef: TemplateRef<any>,
private viewContainerRef: ViewContainerRef
) {}
@Input('appRepeat') set render(times: number) {
this.viewContainerRef.clear();
for (let i = 0; i < times; i++) {
this.viewContainerRef.createEmbeddedView(this.templateRef, {});
}
}
}
|
<?php
namespace App\Http\Controllers;
use App\CategoriesNews;
use Illuminate\Http\Request;
use Str;
class CategoriesNewsController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$categories = CategoriesNews::all();
return view('admin.categoriesnews.index', compact('categories'));
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
return view('admin.categoriesnews.create');
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$request->validate([
'title' => 'required|unique:categories_news,title',
]);
try {
$data = $request->all();
$data['slug'] = Str::slug(transliterate($data['title']), '-');
$category = new CategoriesNews();
$category->create($data);
return redirect()->route('categoryNews.index')->withSuccess('Запись успешно добавлена!');
} catch (Extention $e) {
return redirect()->back()->withError('Не удалось записать! Обратитесь в техническую поддержку для решения проблемы');
}
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit(CategoriesNews $categoriesnews)
{
return view('admin.categoriesnews.create')->with(['category' => $categoriesnews]);
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, CategoriesNews $categoriesnews)
{
$request->validate([
'title' => 'required|unique:categories_articles,title',
]);
try {
$data = $request->all();
$data['slug'] = Str::slug(transliterate($data['title']), '-');
$categoriesnews->update($data);
return redirect()->back()->withSuccess('Запись успешно изменена!');
} catch (Extention $e) {
return redirect()->back()->withError('Не удалось записать! Обратитесь в техническую поддержку для решения проблемы');
}
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy(CategoriesNews $categoriesnews)
{
$categoriesnews->delete();
return redirect()->route('categoryNews.index')->withSuccess('Запись успешно удалена!');
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Unity.Services.Core;
using Unity.Services.Authentication;
using System.Threading.Tasks;
using UnityEngine.UI;
using TMPro;
using System;
public class AuthManager : MonoBehaviour
{
public Text logText;
public InputField username;
public InputField password;
public
async void Awake()
{
try
{
await UnityServices.InitializeAsync();
}
catch (Exception e)
{
Debug.LogException(e);
}
}
void SignIn()
{
}
//Note 1: The username is case insensitive; it requires a minimum of
//3 and a maximum of 20 characters and only supports letters, numbers and
//symbols like ., -, @ or _. Note 2: The password is case sensitive; it requires
//a minimum of 8 and a maximum of 30 characters and at least 1 lowercase letter,
//1 uppercase letter, 1 number, and 1 symbol.
public async void SignUpWithUsernamePassword()
{
try
{
AuthenticationService.Instance.ClearSessionToken();
await AuthenticationService.Instance.SignUpWithUsernamePasswordAsync(username.text, password.text);
Debug.Log("SignUp is successful.");
}
catch (AuthenticationException ex)
{
// Compare error code to AuthenticationErrorCodes
// Notify the player with the proper error message
Debug.LogException(ex);
}
catch (RequestFailedException ex)
{
// Compare error code to CommonErrorCodes
// Notify the player with the proper error message
Debug.LogException(ex);
}
}
public async void SignInWithUsernamePassword()
{
try
{
AuthenticationService.Instance.ClearSessionToken();
await AuthenticationService.Instance.SignInWithUsernamePasswordAsync(username.text, password.text);
Debug.Log("SignIn is successful.");
}
catch (AuthenticationException ex)
{
// Compare error code to AuthenticationErrorCodes
// Notify the player with the proper error message
Debug.LogException(ex);
}
catch (RequestFailedException ex)
{
// Compare error code to CommonErrorCodes
// Notify the player with the proper error message
Debug.LogException(ex);
}
}
public void SignOut()
{
try
{
AuthenticationService.Instance.SignOut();
Debug.Log("Signed Out");
}
catch (AuthenticationException ex)
{
// Compare error code to AuthenticationErrorCodes
// Notify the player with the proper error message
Debug.LogException(ex);
}
catch (RequestFailedException ex)
{
// Compare error code to CommonErrorCodes
// Notify the player with the proper error message
Debug.LogException(ex);
}
}
public async Task UpdatePasswordAsync(string currentPassword, string newPassword)
{
try
{
await AuthenticationService.Instance.UpdatePasswordAsync(currentPassword, newPassword);
Debug.Log("Password updated.");
}
catch (AuthenticationException ex)
{
// Compare error code to AuthenticationErrorCodes
// Notify the player with the proper error message
Debug.LogException(ex);
}
catch (RequestFailedException ex)
{
// Compare error code to CommonErrorCodes
// Notify the player with the proper error message
Debug.LogException(ex);
}
}
// Setup authentication event handlers if desired
public void SetupEvents()
{
AuthenticationService.Instance.SignedIn += () => {
// Shows how to get a playerID
Debug.Log($"PlayerID: {AuthenticationService.Instance.PlayerId}");
// Shows how to get an access token
Debug.Log($"Access Token: {AuthenticationService.Instance.AccessToken}");
};
AuthenticationService.Instance.SignInFailed += (err) => {
Debug.LogError(err);
};
AuthenticationService.Instance.SignedOut += () => {
Debug.Log("Player signed out.");
};
AuthenticationService.Instance.Expired += () =>
{
Debug.Log("Player session could not be refreshed and expired.");
};
}
}
|
import React, { useCallback, useEffect } from "react";
import {
Button,
Center,
extendTheme,
Flex,
IconButton,
Image,
Text,
View,
} from "native-base";
import {
createNativeStackNavigator,
NativeStackNavigationOptions,
} from "@react-navigation/native-stack";
import { startRoutes } from "./routes";
import {
createDrawerNavigator,
DrawerContentComponentProps,
DrawerContentScrollView,
DrawerItem,
DrawerItemList,
} from "@react-navigation/drawer";
import { UserTabs } from "../layout/Tabs";
import { useAuth } from "../context/authContext";
import * as SplashScreen from "expo-splash-screen";
import {
AuthenticatedParamList,
InitialParamList,
MainAppParamList,
} from "./navTypes";
import { ValidateInvitationTokenScreen } from "../screens/Auth/ValidateInvitationToken";
import { UserSettingsNavStack } from "../screens/User/UserSettings/UserSettingsNavStack";
import { BusinessTabs } from "../layout/BusinessTabs";
import { RegBusinessNavStack } from "./RegBusinessNavStack";
import { PasswordReset } from "../screens/Auth/PasswordReset";
import { AssistanceVideoView } from "../screens/AdminTeam/AssistanceVideoView";
import { AssistanceVideoListView } from "../screens/AdminTeam/AssistanceVideoListView";
import { DEFAULT_MAIN_COLOR } from "../types/constants";
import * as app_config from "../../config.json";
import {
useFonts,
Roboto_100Thin,
Roboto_100Thin_Italic,
Roboto_300Light,
Roboto_300Light_Italic,
Roboto_400Regular,
Roboto_400Regular_Italic,
Roboto_500Medium,
Roboto_500Medium_Italic,
Roboto_700Bold,
Roboto_700Bold_Italic,
Roboto_900Black,
Roboto_900Black_Italic,
} from "@expo-google-fonts/roboto";
import { useWindowDimensions } from "react-native";
import logo from "../assets/logo.png";
// Define the config
const config = {
useSystemColorMode: false,
initialColorMode: "light",
};
// extend the theme
export const theme = extendTheme({ config });
SplashScreen.preventAutoHideAsync();
export default function AppWrapper() {
let [fontsLoaded] = useFonts({
Roboto_100Thin,
Roboto_100Thin_Italic,
Roboto_300Light,
Roboto_300Light_Italic,
Roboto_400Regular,
Roboto_400Regular_Italic,
Roboto_500Medium,
Roboto_500Medium_Italic,
Roboto_700Bold,
Roboto_700Bold_Italic,
Roboto_900Black,
Roboto_900Black_Italic,
});
const { isAuthenticated, loading, organization, setLoading, logoutUser } =
useAuth();
const dimensions = useWindowDimensions();
const isLargeScreen = dimensions.width >= 768;
useEffect(() => {
if (!loading || !fontsLoaded) {
SplashScreen.hideAsync();
} else {
SplashScreen.preventAutoHideAsync();
}
}, [loading]);
const Stack = createNativeStackNavigator<InitialParamList>();
const LoginRoute = () => {
const excluded_header = ["MainRegister"];
return (
<Stack.Navigator initialRouteName="MainRegister">
<Stack.Group>
{Object.entries(startRoutes).map(([key, route]) => {
const { headerName } = route?.params ?? {};
return (
<Stack.Screen
key={key}
name={route.name}
component={route.screen}
initialParams={route.params}
options={{
title: headerName ?? route.title,
headerShown:
!route.headerHidden &&
excluded_header.indexOf(route.title ?? "") < 0,
headerBackTitle: "Back",
}}
/>
);
})}
</Stack.Group>
</Stack.Navigator>
);
};
function CustomDrawerContent(props: DrawerContentComponentProps) {
return (
<DrawerContentScrollView {...props}>
<Center my={5}>
<Image alt="logo" source={logo} size={"lg"} mt={0} />
<Text fontSize={"xs"} color="gray.300">
v {app_config.APP_VERSION}
</Text>
</Center>
<DrawerItemList {...props} />
</DrawerContentScrollView>
);
}
const MainDrawer = ({ navigation }: any) => {
const Drawer = createDrawerNavigator<AuthenticatedParamList>();
return (
<Drawer.Navigator
initialRouteName="BusinessViews"
drawerContent={(props) => <CustomDrawerContent {...props} />}
>
<Drawer.Screen
name="Home"
component={UserTabs}
options={{
headerShown: true,
}}
/>
{organization && (
<Drawer.Screen
name="BusinessViews"
component={BusinessTabs}
options={{
headerShown: true,
title: "My Business",
headerStyle: {
backgroundColor: DEFAULT_MAIN_COLOR,
},
headerTintColor: "#fff",
headerRight: () => (
<Button
variant={"ghost"}
_text={{ color: "white" }}
_pressed={{ background: "lightBlue.600", shadow: "5" }}
onPress={() => {
navigation.navigate("AssistanceVideoListView");
}}
>
Help
</Button>
),
}}
/>
)}
{isAuthenticated && !organization && (
<Drawer.Screen
name="RegisterBusiness"
component={RegBusinessNavStack}
options={{
headerShown: true,
title: "Register your Business",
}}
/>
)}
<Drawer.Screen
name="UserInfoMainScreen"
component={UserSettingsNavStack}
options={{
headerShown: true,
title: "User Profile",
}}
/>
</Drawer.Navigator>
);
};
const AppModalStack = () => {
if (loading) {
return null;
}
const MainStackNav = createNativeStackNavigator<MainAppParamList>();
const options: NativeStackNavigationOptions = {
presentation: "modal",
headerShown: true,
headerStyle: {
backgroundColor: DEFAULT_MAIN_COLOR,
},
headerTintColor: "#fff",
headerTitleStyle: {
fontWeight: "bold",
},
headerBackTitle: "Back",
headerBackVisible: true,
};
return (
<MainStackNav.Navigator
screenOptions={{ presentation: "containedModal", headerShown: false }}
>
{!isAuthenticated ? (
<MainStackNav.Screen name="Anon" component={LoginRoute} />
) : (
<MainStackNav.Group>
<MainStackNav.Screen name="Auth" component={MainDrawer} />
<MainStackNav.Screen
name="RegBusiness"
component={RegBusinessNavStack}
/>
<MainStackNav.Screen
name="AssistanceVideoListView"
component={AssistanceVideoListView}
options={{
title: "Video Assistance",
...{ options },
}}
/>
<MainStackNav.Screen
name="AssistanceVideoViewPlayback"
component={AssistanceVideoView}
options={{
title: "Video Assistance",
...{ options },
}}
/>
</MainStackNav.Group>
)}
<MainStackNav.Screen
key={"ValidateInvitation"}
name="ValidateInvitation"
component={ValidateInvitationTokenScreen}
/>
<MainStackNav.Screen name="PasswordReset" component={PasswordReset} />
</MainStackNav.Navigator>
);
};
return <AppModalStack />;
}
|
import React from 'react'
import { DeleteIcon } from '../../utils/DeleteIcon';
import { EyeIcon } from '../../utils/EyeIcon';
import {EditIcon} from '../../utils/EditIcon'
import { User } from '@nextui-org/react';
import { Chip } from '@nextui-org/react';
import { Tooltip } from '@nextui-org/react';
import { Table, TableHeader, TableColumn, TableBody, TableRow, TableCell } from '@nextui-org/react';
import AddIcon from '@mui/icons-material/Add';
import { drivers } from '../../data/drivers';
import { Dropdown, DropdownTrigger, DropdownMenu, DropdownItem , Button } from '@nextui-org/react'
const columns = [
{name: "İSİM", uid: "name"},
{name: "ROL", uid: "role"},
{name: "DURUM", uid: "status"},
{name: "", uid: "actions"},
];
const statusColorMap = {
onayli: "success",
onaylidegil: "danger",
};
const FirmDrivers = () => {
const renderCell = React.useCallback((user, columnKey) => {
const cellValue = user[columnKey];
switch (columnKey) {
case "name":
return (
<User
avatarProps={{radius: "lg", src: user.avatar}}
description={user.phone}
name={cellValue}
>
{user.phone}
</User>
);
case "role":
return (
<div className="flex flex-col">
<p className="text-bold text-sm capitalize">{cellValue}</p>
<p className="text-bold text-sm capitalize text-default-400">{user.team}</p>
</div>
);
case "status":
return (
<Chip className="capitalize" color={statusColorMap[user.status]} size="sm" variant="flat">
{cellValue}
</Chip>
);
case "actions":
return (
<div className="relative flex items-center gap-2">
<Tooltip content="Details">
<span className="text-lg text-default-400 cursor-pointer active:opacity-50">
<EyeIcon />
</span>
</Tooltip>
<Tooltip content="Edit user">
<span className="text-lg text-default-400 cursor-pointer active:opacity-50">
<EditIcon />
</span>
</Tooltip>
<Tooltip color="danger" content="Delete user">
<span className="text-lg text-danger cursor-pointer active:opacity-50">
<DeleteIcon />
</span>
</Tooltip>
</div>
);
default:
return cellValue;
}
}, []);
return (
<div className='flex flex-col'>
<Dropdown backdrop='blur'>
<DropdownTrigger>
<Button
className='w-24 text-gray-500 my-3'
variant='bordered'
>
<AddIcon/>
</Button>
</DropdownTrigger>
<DropdownMenu variant="flat" aria-label="Dropdown menu with shortcut">
<DropdownItem key="new" endContent={<AddIcon/>} color='secondary' className='text-secondary'>Şoför ekle</DropdownItem>
</DropdownMenu>
</Dropdown>
<Table aria-label="drivers">
<TableHeader columns={columns}>
{(column) => (
<TableColumn key={column.uid} align={column.uid === "actions" ? "center" : "start"}>
{column.name}
</TableColumn>
)}
</TableHeader>
<TableBody items={drivers}>
{(item) => (
<TableRow key={item.id}>
{(columnKey) => <TableCell>{renderCell(item, columnKey)}</TableCell>}
</TableRow>
)}
</TableBody>
</Table>
</div>
);
}
export default FirmDrivers
|
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateItemCategoriesTable extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up() {
Schema::create( 'item_categories', function( Blueprint $table ) {
$table->integer( 'id' )->primary();
$table->integer( 'pocket_id' );
$table->foreign( 'pocket_id' )->references( 'id' )->on( 'item_pockets' )->onDelete( 'cascade' );
$table->string( 'identifier' );
} );
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down() {
Schema::dropIfExists( 'item_categories' );
}
}
|
@import "quasar/src/css/variables";
$typography-font-family: "IBM Plex Sans", "Roboto", "Helvetica Neue", Helvetica, "-apple-system", Arial, sans-serif;
$primary: #1b7bc4;
$secondary: #31826e;
$accent: #0077c1;
$positive: #21ba45;
$negative: #c10015;
$negative-dark: #ff5722;
$info: #2196f3;
$warning: #f2c037;
$colors: (
primary: $primary,
secondary: $secondary,
accent: $accent,
positive: $positive,
negative: $negative,
negative-dark: $negative-dark,
info: $info,
warning: $warning,
);
$identity-colors: ();
// Generate Color Classes
@mixin generate-color-classes($attribute: "color", $prefix: "-") {
@each $color-group-name, $color-group-map in $identity-colors {
@each $color-name, $color-value in $color-group-map {
&#{$prefix}#{$color-name} {
#{$attribute}: $color-value;
#{$attribute}: var(--q-#{$color-name});
}
}
}
}
// Lighten a color
@function tint($color, $percentage) {
@return mix(white, $color, $percentage);
}
// Darken a color
@function shade($color, $percentage) {
@return mix(black, $color, $percentage);
}
// Populate Identity Color
@each $name, $color in $colors {
// Current color map
$current: ();
// Generate original color
$current: map-merge(
$current,
(
"#{$name}": $color,
)
);
// Generate tints
@for $i from 0 through 4 {
$current: map-merge(
$current,
(
"#{$name}-#{$i}": tint($color, percentage(0.9 - ($i * 0.17))),
)
);
}
// Generate mid color
$current: map-merge(
$current,
(
"#{$name}-5": $color,
)
);
// Generate shades
@for $i from 0 through 4 {
$current: map-merge(
$current,
(
"#{$name}-#{$i + 6}": shade($color, percentage(0.16 + ($i * 0.16))),
)
);
}
// If the map has not been created
@if map-has-key($identity-colors, $name) == false {
$identity-colors: map-merge(
$identity-colors,
(
$name: $current,
)
);
}
}
// Get Identity Color
@function get-color($name: "primary", $index: 10) {
$color-map: map-get($identity-colors, $name);
@return map-get($color-map, "#{$name}-#{$index}");
}
// Default text color
$text-base-color-light: get-color(primary, 10);
$text-base-color-dark: get-color(primary, 0);
$text-default-color-light: rgba($text-base-color-light, 0.8);
$text-default-color-dark: rgba($text-base-color-dark, 0.8);
$text-lighten-color-light: rgba($text-base-color-light, 0.5);
$text-lighten-color-dark: rgba($text-base-color-dark, 0.4);
$text-disabled-color-light: get-color(primary, 2);
$text-disabled-color-dark: get-color(primary, 8);
$input-text-color: $text-base-color-light;
// Default controls color
$controls-base-color-light: get-color(primary, 8);
$controls-base-color-dark: get-color(primary, 0);
$controls-on-color-light: rgba($text-base-color-light, 0.8);
$controls-on-color-dark: rgba($text-base-color-dark, 0.8);
$controls-off-color-light: $controls-base-color-dark;
$controls-off-color-dark: $controls-base-color-light;
$controls-disabled-color-light: $controls-base-color-light;
$controls-disabled-color-dark: $controls-base-color-dark;
// Background Colors
$bg-footer-light: tint(map-get($colors, "primary"), 78%); // #{get-color(primary, 2)}
$bg-header-light: get-color(primary, 0);
$bg-footer-dark: shade(map-get($colors, "primary"), 78%); // #{get-color(primary, 10)}
$bg-header-dark: get-color(primary, 9);
$bg-grad-light: linear-gradient(0deg, $bg-footer-light 0%, $bg-header-light 100%);
$bg-grad-dark: linear-gradient(0deg, $bg-footer-dark 0%, $bg-header-dark 100%);
$bg-footer-grad-light: linear-gradient(to top, $bg-footer-light 30%, rgba($bg-footer-light, 0) 100%);
$bg-footer-grad-dark: linear-gradient(to top, $bg-footer-dark 30%, rgba($bg-footer-dark, 0) 100%);
$dark-page: $bg-footer-dark;
// Separator Border Color
$separator-color: rgba(get-color(primary, 5), 0.2);
$separator-dark-color: rgba(get-color(primary, 5), 0.2);
$breakpoint-xxs-min: 0px;
$breakpoint-xxs-max: 479px;
$breakpoint-xs-min: 480px;
$loader-spinner-sm: 8rem;
$loader-spinner-md: 10rem;
$navbar-button-size: 2rem;
$navbar-button-size-mini: 1.5rem;
$navbar-padding: 0.5rem;
$navbar-padding-mini: 0.25rem;
$navbar-margin-top: 2rem;
$navbar-margin-top-mini: 1.5rem;
$navbar-margin-bottom: 0.5rem;
$navbar-margin-bottom-mini: 0.375rem;
$navbar-button-padding: 0.25rem;
$navbar-button-padding-mini: 0.125rem;
$toolbar-min-height: 48px;
$toolbar-padding: 0 16px;
$toolbar-inset-size: 64px;
// $toolbar-title-font-size : 21px
// $toolbar-title-font-weight : normal
// $toolbar-title-letter-spacing : .01em
// $toolbar-title-padding : 0 12px
$page-header-height: 3.5rem;
$page-header-height-mini: 3rem;
$page-animation-duration: 0.4s;
$page-footer-height: $navbar-button-size + (2 * $navbar-button-padding) + (2 * $navbar-padding) + $navbar-margin-bottom +
$navbar-margin-top;
$page-footer-height-mini: $navbar-button-size-mini + (2 * $navbar-button-padding-mini) + (2 * $navbar-padding-mini) +
$navbar-margin-bottom-mini + $navbar-margin-top-mini;
$button-rounded-border-radius: 2rem;
$dimmed-background: rgba(0, 0, 0, 0.5);
$table-border-color: $separator-color;
$table-dark-border-color: $separator-dark-color;
|
---
title: Referência de Markdown para docs.microsoft.com
description: Conheça os recursos e a sintaxe do Markdown usados na plataforma do Microsoft Docs.
author: meganbradley
ms.author: mbradley
ms.date: 05/18/2018
ms.topic: contributor-guide
ms.prod: non-product-specific
ms.openlocfilehash: 17bc6d3bf2de5077f490bea2f03cddf23d925b78
ms.sourcegitcommit: 203ca15fda2d217f082c74ec648c1f1db323f9f1
ms.translationtype: HT
ms.contentlocale: pt-BR
ms.lasthandoff: 02/04/2019
ms.locfileid: "55712937"
---
# <a name="markdown-reference"></a>Referência de Markdown
Markdown é uma linguagem de marcação leve com sintaxe de formatação de texto sem formatação. A plataforma Docs é compatível com o padrão CommonMark para Markdown, além de algumas extensões personalizadas de Markdown projetadas para oferecer conteúdo mais avançado no docs.microsoft.com. Este artigo oferece uma referência alfabética para uso de Markdown no docs.microsoft.com.
É possível usar qualquer editor de texto para criar em Markdown. Para editores que facilitam a inserção da sintaxe padrão Markdown e das extensões personalizadas do Docs, recomendamos o [VS Code](https://code.visualstudio.com/) com o [Pacote de Criação de Docs](https://aka.ms/DocsAuthoringPack) instalado.
O Docs usa o mecanismo de Markdown Markdig. É possível testar a renderização de Markdown no Markdig em relação aos outros mecanismos em [https://babelmark.github.io/](https://babelmark.github.io/).
## <a name="alerts-note-tip-important-caution-warning"></a>Alertas (Anotação, Dica, Importante, Atenção, Aviso)
"Alertas" é uma extensão de Markdown do Docs para criar citações em bloco que renderizam no docs.microsoft.com com cores e ícones que indicam a importância do conteúdo. Os seguintes tipos de alerta tem suporte:
```markdown
> [!NOTE]
> Information the user should notice even if skimming.
> [!TIP]
> Optional information to help a user be more successful.
> [!IMPORTANT]
> Essential information required for user success.
> [!CAUTION]
> Negative potential consequences of an action.
> [!WARNING]
> Dangerous certain consequences of an action.
```
Esses alertas terão a seguinte aparência no docs.microsoft.com:
> [!NOTE]
> Informações que o usuário deverá notar mesmo se estiver fazendo uma leitura rápida.
> [!TIP]
> Informações opcionais para ajudar um usuário a ter mais êxito.
> [!IMPORTANT]
> Informações essenciais obrigatórias para o êxito do usuário.
> [!CAUTION]
> Possíveis consequências negativas de uma ação.
> [!WARNING]
> Determinadas consequências perigosas de uma ação.
## <a name="code-snippets"></a>Snippets de código
É possível inserir snippets de código nos arquivos Markdown:
```markdown
[!code-<language>[<name>](<codepath><queryoption><queryoptionvalue> "<title>")]
```
## <a name="headings"></a>Títulos
O Docs é compatível com seis níveis de cabeçalhos do Markdown:
```markdown
# This is a first level heading (H1)
## This is a second level heading (H2)
...
###### This is a sixth level heading (H6)
```
- É necessário um espaço entre o último `#` e o texto do cabeçalho.
- Cada arquivo Markdown precisa ter somente um H1.
- O H1 precisa ser o primeiro conteúdo no arquivo após o bloco de metadados YML.
- O H2s aparece automaticamente no menu de navegação direito do arquivo publicado. Os cabeçalhos dos níveis inferiores não, então, use os H2s estrategicamente, de modo a ajudar os leitores a navegarem pelo conteúdo.
- Os cabeçalhos HTML, tais como `<h1>`, não são recomendados. Em alguns casos, eles gerarão avisos de build.
- É possível criar links para cabeçalhos individuais em um arquivo por meio de [indicadores](#bookmark-links).
## <a name="html"></a>HTML
Embora o Markdown seja compatível com HTML embutido, não é recomendável usá-lo para publicar no Docs, exceto no caso de uma lista de valores limitada causar erros de build ou avisos. <!--For more information, see HTML Whitelist. // do we want to add the whitelist? -->
## <a name="images"></a>Imagens
A sintaxe para incluir uma imagem é:
```markdown
![[alt text]](<folderPath>)
Example:

```
Em que `alt text` é uma breve descrição da imagem e `<folder path>` é um caminho relativo para a imagem. O texto alternativo é obrigatório para os leitores de tela para portadores de deficiências visuais. Ele também é útil se há um bug de site em que a imagem não pode ser renderizada.
As imagens devem ser armazenadas em uma pasta `/media` dentro do conjunto de documentos. Os seguintes tipos de arquivo para imagens têm suporte por padrão:
- .jpg
- .png
É possível adicionar suporte a outros tipos de imagem, adicionando-as como recursos ao arquivo docfx.json<!--add link to reference when available--> no conjunto de documentos.
## <a name="links"></a>Links
Na maioria dos casos, o Docs usa links padrão de Markdown para outros arquivos e páginas. Os tipos de links serão descritos nas próximas subseções.
> [!TIP]
> O Pacote de Criação de Docs para VS Code pode ajudar a inserir links relativos e indicadores corretamente sem o tédio de ter que adivinhar os caminhos!
> [!IMPORTANT]
> Não inclua códigos de localidade, como en-us, nos links para sites da Microsoft. Os códigos de localidade embutidos em código impedem que o conteúdo localizado seja renderizado, o que é uma experiência do cliente ruim para os usuários de outros locais e gera grandes custos de localização. Ao copiar uma URL de um navegador, o código de localidade é incluído por padrão. Então, é necessário excluí-lo manualmente ao criar o link. Por exemplo, use:
>
> `[Microsoft](https://www.microsoft.com)`
>
> E não:
>
> `[Microsoft](https://www.microsoft.com/en-us/)`
### <a name="relative-links-to-files-in-the-same-doc-set"></a>Links relativos para arquivos no mesmo conjunto de documentos
Um caminho relativo é o caminho para o arquivo de destino relativo ao arquivo atual. No Docs, é possível usar um caminho relativo para criar um link para outro arquivo do mesmo conjunto de documentos. A sintaxe do caminho relativo é assim:
```markdown
[link text](../../folder/filename.md)
```
Em que `../` indica um nível acima na hierarquia.
- O caminho relativo será resolvido durante o build, incluindo a remoção da extensão .md.
- Você pode usar "../" para vincular ao arquivo na pasta pai, mas esse arquivo precisa estar no mesmo conjunto de documentos. Você não pode usar "../" para vincular a um arquivo em outra pasta do conjunto de documentos.
- O Docs também é compatível com um formato especial de caminho relativo que começa com "~" (por exemplo, ~/foo/bar.md). Essa sintaxe indica um arquivo relativo à pasta raiz de um conjunto de documentos. Esse tipo de caminho também será validado e resolvido durante o build.
> [!IMPORTANT]
> Inclua a extensão de arquivo no caminho relativo. O build valida a existência do arquivo de destino desse caminho relativo. Se o caminho relativo não incluir a extensão de arquivo, provavelmente o build enviará um aviso de link desfeito. Por exemplo, use:
>
> `[link text](../../folder/filename.md)`
>
> E não:
>
> `[link text](../../folder/filename)`
### <a name="site-relative-links-to-other-files-on-docs"></a>Links relativos do site para outros arquivos no Docs
```markdown
[Azure and Linux](/articles/virtual-machines/linux/overview)
```
Não inclua a extensão de arquivo (.md). Isso vincula ao arquivo de visão geral do Linux de fora do conjunto de documentos de "artigos" do Azure.
### <a name="links-to-external-sites"></a>Links para sites externos
```markdown
[Microsoft](https://www.microsoft.com)
```
Link baseado em URL para outra página da Web (precisa incluir https://).
### <a name="bookmark-links"></a>Links com indicadores
Link com indicador para um cabeçalho em outro arquivo no mesmo repositório:
```markdown
[Managed Disks](../../linux/overview.md#managed-disks)
```
Link com indicador para um cabeçalho no arquivo atual:
```markdown
[Managed Disks](#managed-disks)
```
Use uma hashtag seguida pelas palavras do cabeçalho com a pontuação removida e os espaços substituídos por traços.
### <a name="explicit-anchor-links"></a>Links do tipo âncora explícitos
Os links do tipo âncora explícitos que usam a marca HTML `<a>` não são **obrigatórios ou recomendados**, exceto em páginas de hub e de aterrissagem. Use os indicadores conforme descrito acima nos arquivos Markdown em geral. Para páginas de hub e de aterrissagem, use as âncoras desta forma:
`## <a id="AnchorText"> </a>Header text` ou `## <a name="AnchorText"> </a>Header text`
Para criar links para âncoras explícitas, use a seguinte sintaxe:
```markdown
To go to a section on the same page:
[text](#AnchorText)
To go to a section on another page.
[text](FileName.md#AnchorText)
```
### <a name="xref-cross-reference-links"></a>Links XREF (referência cruzada)
Para criar links para páginas de referências de API geradas automaticamente no conjunto de documentos atual ou em outros conjuntos de documentos, use links XREF com a UID (ID exclusiva).
> [!NOTE]
> Para referenciar páginas de referência de API em outros conjuntos de documentos, é necessário adicionar a configuração `xrefService` no arquivo `docfx.json`.
> ```
> "build": {
> ...
> "xrefService": [ "https://xref.docs.microsoft.com/query?uid={uid}" ]
> }
> ```
O UID equivale ao nome de classe e membro totalmente qualificado. Se você adicionar um * após o UID, o link representará a página de sobrecarga, e não uma API específica. Por exemplo, use `List<T>.BinarySearch*` para criar um link para a página BinarySearch Method em vez de para uma sobrecarga específica, como `List<T>.BinarySearch(T, IComparer<T>)`.
Você pode usar uma das seguintes sintaxes:
- Vincule automaticamente: `<xref:UID> or <xref:UID?displayProperty=nameWithType>`
O parâmetro de consulta `displayProperty` opcional produz um texto de link totalmente qualificado. Por padrão, o texto do link mostra apenas o nome do membro ou do tipo.
- Link de Markdown: `[link text](xref:UID)`
Use para personalizar o texto do link exibido.
Exemplos:
- `<xref:System.String>` é renderizado como "String".
- `<xref:System.String?displayProperty=nameWithType>` é renderizado como "System.String".
- `[String class](xref:System.String)` é renderizado como "classe String".
No momento, não há uma maneira simples de localizar os UIDs. <!-- ? -->A melhor maneira de localizar o UID de uma API é exibir a origem da página da API à qual você deseja vincular e localizar o valor de ms.assetid. Os valores de sobrecarga individuais não são mostrados na origem. Estamos trabalhando para fornecer um sistema mais eficiente no futuro.
Quando o UID contém os caracteres especiais \`, \# ou \*, o valor do UID deve ser codificado em HTML como `%60`, `%23` e `%2A`, respectivamente. Às vezes, você verá parênteses codificados, mas, isso não é um requisito.
Exemplos:
- System.Threading.Tasks.Task\`1 se torna `System.Threading.Tasks.Task%601`
- System.Exception.\#ctor se torna `System.Exception.%23ctor`
- System.Lazy\`1.\#ctor(System.Threading.LazyThreadSafetyMode) se torna `System.Lazy%601.%23ctor%28System.Threading.LazyThreadSafetyMode%29`
<!-- leave out of Contributor Guide for now
Using XREF may require some configuration. For more information, see XREF Service.
-->
## <a name="lists-numbered-bulleted-checklist"></a>Listas (Numerada, Com Marcadores, Lista de Verificação)
### <a name="numbered-list"></a>Lista numerada
Para criar uma lista numerada, é possível usar todos os 1s, que são renderizados como uma lista sequencial quando publicados. Para aumentar a legibilidade da origem, é possível aumentar as listas.
Não use letras nas listas, incluindo listas aninhadas. Elas não são renderizadas corretamente quando publicadas no Docs. As listas aninhadas usando números renderizarão como letras minúsculas quando publicadas. Por exemplo:
```markdown
1. This is
1. a parent numbered list
1. and this is
1. a nested numbered list
1. (fin)
```
Isso será renderizado da seguinte forma:
1. Esta é
1. uma lista numerada pai
1. e esta é
1. uma lista numerada aninhada
1. (fim)
### <a name="bulleted-list"></a>Lista com marcadores
Para criar uma lista com marcadores, use `-` seguido de um espaço no início de cada linha:
```markdown
- This is
- a parent bulleted list
- and this is
- a nested bulleted list
- All done!
```
Isso será renderizado da seguinte forma:
- Esta é
- uma lista com marcadores pai
- e esta é
- uma lista com marcadores aninhada
- Concluído!
### <a name="checklist"></a>Lista de verificação
As listas de verificação estão disponíveis para uso no docs.microsoft.com (somente) por meio de uma extensão de Markdown personalizada:
```markdown
> [!div class="checklist"]
> * List item 1
> * List item 2
> * List item 3
```
Esse exemplo é renderizado no docs.microsoft.com desta forma:
> [!div class="checklist"]
> * Item de lista 1
> * Item de lista 2
> * Item de lista 3
Use as listas de verificação no início ou no fim de um artigo para resumir o conteúdo "O que você aprenderá" ou "O que você aprendeu". Não adicione listas de verificação aleatórias ao longo dos seus artigos.
<!-- is this guidance still accurate? -->
## <a name="next-step-action"></a>Ação da próxima etapa
É possível usar uma extensão personalizada para adicionar um botão de ação da próxima etapa a páginas no docs.microsoft.com (somente).
A sintaxe é assim:
```markdown
> [!div class="nextstepaction"]
> [button text](link to topic)
```
Por exemplo:
```markdown
> [!div class="nextstepaction"]
> [Learn about basic style](style-quick-start.md)
```
Isso será renderizado da seguinte forma:
> [!div class="nextstepaction"]
> [Saiba mais sobre o estilo básico](style-quick-start.md)
É possível usar qualquer link com suporte em uma ação de próxima etapa, incluindo um link de Markdown para outra página da Web. Na maioria dos casos, o link de próxima ação será um link relativo a outro arquivo no mesmo conjunto de documentos.
## <a name="section-definition"></a>Definição de seção
<!-- more info about this would be helpful! --> É possível que você precise definir uma seção. Essa sintaxe é mais usada para tabelas de códigos.
Veja o exemplo a seguir:
````
> [!div class="tabbedCodeSnippets" data-resources="OutlookServices.Calendar"]
> ```cs
> <cs code text>
> ```
> ```javascript
> <js code text>
> ```
````
O texto de Markdown do blockquote anterior será renderizado como:
> [!div class="tabbedCodeSnippets" data-resources="OutlookServices.Calendar"]
> ```cs
> <cs code text>
> ```
> ```javascript
> <js code text>
> ```
## <a name="selectors"></a>Seletores
<!-- could be more clear! --> Você pode usar um seletor quando quiser se conectar a diferentes páginas do mesmo artigo. Depois, os leitores podem alternar entre essas páginas.
> [!NOTE]
> Essa extensão funciona de forma diferente entre o docs.microsoft.com e o MSDN. <!-- should we keep info about MSDN? If so say how they differ?-->
### <a name="single-selector"></a>Seletor único
```
> [!div class="op_single_selector"]
> - [Universal Windows](how-to-write-use-markdown.md)
> - [Windows Phone](how-to-write-use-markdown.md)
> - [iOS](how-to-write-use-markdown.md)
> - [Android](how-to-write-use-markdown.md)
> - [Kindle](how-to-write-use-markdown.md)
> - [Baidu](how-to-write-use-markdown.md)
> - [Xamarin.iOS](how-to-write-use-markdown.md)
> - [Xamarin.Android](how-to-write-use-markdown.md)
```
… será renderizada desta forma:
> [!div class="op_single_selector"]
> - [Universal do Windows](how-to-write-use-markdown.md)
> - [Windows Phone](how-to-write-use-markdown.md)
> - [iOS](how-to-write-use-markdown.md)
> - [Android](how-to-write-use-markdown.md)
> - [Kindle](how-to-write-use-markdown.md)
> - [Baidu](how-to-write-use-markdown.md)
> - [Xamarin.iOS](how-to-write-use-markdown.md)
> - [Xamarin.Android](how-to-write-use-markdown.md)
### <a name="multi-selector"></a>Seletor múltiplo
```
> [!div class="op_multi_selector" title1="Platform" title2="Backend"]
> - [(iOS | .NET)](how-to-write-workflows-major.md)
> - [(iOS | JavaScript)](how-to-write-workflows-major.md)
> - [(Windows universal C# | .NET)](how-to-write-workflows-major.md)
> - [(Windows universal C# | Javascript)](how-to-write-workflows-major.md)
> - [(Windows Phone | .NET)](how-to-write-workflows-major.md)
> - [(Windows Phone | Javascript)](how-to-write-workflows-major.md)
> - [(Android | .NET)](how-to-write-workflows-major.md)
> - [(Android | Javascript)](how-to-write-workflows-major.md)
> - [(Xamarin iOS | Javascript)](how-to-write-workflows-major.md)
> - [(Xamarin Android | Javascript)](how-to-write-workflows-major.md)
```
… será renderizada desta forma:
> [!div class="op_multi_selector" title1="Platform" title2="Backend"]
> - [(iOS | .NET)](how-to-write-workflows-major.md)
> - [(iOS | JavaScript)](how-to-write-workflows-major.md)
> - [(Universal do Windows C# | .NET)](how-to-write-workflows-major.md)
> - [(Universal do Windows C# | JavaScript)](how-to-write-workflows-major.md)
> - [(Windows Phone | .NET)](how-to-write-workflows-major.md)
> - [(Windows Phone | JavaScript)](how-to-write-workflows-major.md)
> - [(Android | .NET)](how-to-write-workflows-major.md)
> - [(Android | JavaScript)](how-to-write-workflows-major.md)
> - [(Xamarin iOS | JavaScript)](how-to-write-workflows-major.md)
> - [(Xamarin Android | JavaScript)](how-to-write-workflows-major.md)
## <a name="tables"></a>Tabelas
A maneira mais simples de criar uma tabela em Markdown é usar barras verticais e linhas. Para criar uma tabela padrão com um cabeçalho, siga a primeira linha com uma linha tracejada:
```markdown
|This is |a simple |table header|
|----------|-----------|------------|
|table |data |here |
|it doesn't|actually |have to line up nicely!|
```
Isso será renderizado da seguinte forma:
|Este é |um simples |cabeçalho de tabela|
|----------|-----------|------------|
|tabela |dados |aqui |
|não precisa|se |alinhar corretamente!||
Também é possível criar uma tabela sem um cabeçalho. Por exemplo, para criar uma lista com várias colunas:
```markdown
| | |
| - | - |
| This | table |
| has no | header |
```
Isso será renderizado da seguinte forma:
| | |
| - | - |
| Esta | tabela |
| não tem | cabeçalho |
Você pode alinhar as colunas usando dois-pontos:
```markdown
| |
|------------------|
| right aligned:|
|:left aligned |
|:centered :|
```
É renderizado da seguinte forma:
| |
|------------------|
| alinhado à direita:|
|: alinhado à esquerda |
|: centralizado :|
> [!TIP]
> A Extensão de Criação de Docs para VS Code facilita a adição de tabelas básicas de Markdown!
>
> Também é possível usar um [gerador de tabelas online](http://www.tablesgenerator.com/markdown_tables).
### <a name="mx-tdbreakall"></a>mx-tdBreakAll
> [!IMPORTANT]
> Isso só funciona no site do docs.microsoft.com.
Se você criar uma tabela em Markdown, a tabela poderá se expandir para a barra de navegação direita, ficando ilegível. Você pode resolver isso facilmente permitindo que a renderização do Docs quebre a tabela quando necessário. Basta encapsular a tabela na classe personalizada `[!div class="mx-tdBreakAll"]`.
Aqui temos um exemplo de Markdown de uma tabela com três linhas que será encapsulada por um `div` com o nome de classe `mx-tdBreakAll`.
```markdown
> [!div class="mx-tdBreakAll"]
> |Name|Syntax|Mandatory for silent installation?|Description|
> |-------------|----------|---------|---------|
> |Quiet|/quiet|Yes|Runs the installer, displaying no UI and no prompts.|
> |NoRestart|/norestart|No|Suppresses any attempts to restart. By default, the UI will prompt before restart.|
> |Help|/help|No|Provides help and quick reference. Displays the correct use of the setup command, including a list of all options and behaviors.|
```
Ela será renderizada da seguinte forma:
> [!div class="mx-tdBreakAll"]
> |Nome|Sintaxe|Obrigatório para instalação silenciosa?|Descrição|
> |-------------|----------|---------|---------|
> |Silencioso|/quiet|Sim|Executa o instalador sem exibir interface do usuário e nem prompts.|
> |NoRestart|/norestart|Não|Suprime as tentativas de reinício. Por padrão, a interface do usuário avisará antes de reiniciar.|
> |Ajuda|/help|Não|Oferece ajuda e referência rápida. Exibe o uso correto do comando de instalação, incluindo uma lista com todas as opções e comportamentos.|
### <a name="mx-tdcol2breakall"></a>mx-tdCol2BreakAll
> [!IMPORTANT]
> Isso só funciona no site do docs.microsoft.com.
Algumas vezes, pode ser que você tenha palavras muito longas na segunda coluna de uma tabela. Para garantir que elas sejam divididas da melhor maneira, você pode aplicar a classe `mx-tdCol2BreakAll` usando a sintaxe de wrapper `div`, conforme mostrado anteriormente.
### <a name="html-tables"></a>Tabelas HTML
As tabelas HTML não são recomendadas para o docs.microsoft.com. Elas não são legíveis por humanos na origem – o que é um princípio fundamental do Markdown.
<!--If you use HTML tables and your Markdown is not being rendered between the two tables, you need to add a closing `br` tag after the closing `table` tag.

-->
## <a name="videos"></a>Vídeos
### <a name="embedding-videos-into-a-markdown-page"></a>Inserir vídeos em uma página Markdown
No momento, o Docs é compatível com vídeos publicados em um de três locais:
- YouTube
- Channel 9
- Sistema 'One Player' da Microsoft
Você pode inserir um vídeo com a sintaxe a seguir e o Docs o renderizará.
```markdown
> [!VIDEO <embedded_video_link>]
```
Exemplo:
```markdown
> [!VIDEO https://channel9.msdn.com/Series/Youve-Got-Key-Values-A-Redis-Jump-Start/03/player]
> [!VIDEO https://www.youtube.com/embed/iAtwVM-Z7rY]
> [!VIDEO https://www.microsoft.com/en-us/videoplayer/embed/RE1XVQS]
```
... será renderizado como:
```html
<iframe src="https://channel9.msdn.com/Series/Youve-Got-Key-Values-A-Redis-Jump-Start/03/player" width="640" height="320" allowFullScreen="true" frameBorder="0"></iframe>
<iframe src="https://www.youtube-nocookie.com/embed/iAtwVM-Z7rY" width="640" height="320" allowFullScreen="true" frameBorder="0"></iframe>
<iframe src="https://www.microsoft.com/en-us/videoplayer/embed/RE1XVQS" width="640" height="320" allowFullScreen="true" frameBorder="0"></iframe>
```
E será exibido nas páginas publicadas desta forma:
> [!VIDEO https://channel9.msdn.com/Series/Youve-Got-Key-Values-A-Redis-Jump-Start/03/player]
> [!VIDEO https://www.youtube.com/embed/iAtwVM-Z7rY]
> [!VIDEO https://www.microsoft.com/en-us/videoplayer/embed/RE1XVQS]
> [!IMPORTANT]
> A URL do vídeo do CH9 deve começar com `https` e terminar com `/player`. Caso contrário, a página inteira será inserida, em vez de apenas o vídeo.
### <a name="uploading-new-videos"></a>Fazendo upload de novos vídeos
O upload de todos os novos vídeos devem ser feitos usando o seguinte processo:
1. Entre no grupo **docs_video_users** no IDWEB.
1. Acesse https://aka.ms/VideoUploadRequest e preencha os detalhes do vídeo. Você precisará de (observe que nenhum destes itens será visível para o público):
1. Um título para o vídeo.
1. Uma lista de produtos/serviços que tenham relação com seu vídeo.
1. A página de destino ou (se você ainda não tiver uma página) o conjunto de documentos em que o vídeo será hospedado.
1. Um link para o arquivo MP4 do vídeo (se você não tiver um local para colocar o arquivo, coloque-o aqui temporariamente: `\\scratch2\scratch\apex`). Os arquivos MP4 precisam ter 720p ou mais.
1. Uma descrição do vídeo.
1. Envie (salve) o item.
1. Em dois dias úteis, o upload do vídeo será concluído. O link que você precisa inserir será colocado no item de trabalho e enviado *de volta para você*.
1. Quando você tiver o link, feche o item de trabalho.
1. Em seguida, o link do vídeo poderá ser adicionado à postagem com o uso desta sintaxe:
```markdown
> [!VIDEO https://www.microsoft.com/en-us/videoplayer/embed/RE1XVQS]
```
|
// ignore_for_file: library_private_types_in_public_api
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:lost_mode_app/constants/colors.dart';
// import 'package:lost_mode_app/screens/login.dart';
import 'package:lost_mode_app/screens/onboarding.dart';
import 'package:lost_mode_app/screens/usermap.dart';
import 'package:lost_mode_app/services/service.dart';
import 'package:shared_preferences/shared_preferences.dart';
class SplashScreen extends StatefulWidget {
const SplashScreen({super.key});
@override
_SplashScreenState createState() => _SplashScreenState();
}
class _SplashScreenState extends State<SplashScreen>
with SingleTickerProviderStateMixin {
bool showHome = false;
@override
void initState() {
super.initState();
Authenticatepage();
SystemChrome.setEnabledSystemUIMode(SystemUiMode.immersive);
SharedPreferences.getInstance().then((prefs) {
bool showHome = prefs.getBool('showHome') ?? false;
Future.delayed(const Duration(seconds: 2), () {
setState(() {
showHome = showHome;
});
Navigator.of(context).pushReplacement(
MaterialPageRoute(
builder: (_) => showHome ? const MapScreen() : const Onbording(),
),
);
});
}
);
}
@override
void dispose() {
SystemChrome.setEnabledSystemUIMode(SystemUiMode.manual,
overlays: SystemUiOverlay.values);
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
height: MediaQuery.of(context).size.height,
width: MediaQuery.of(context).size.width,
decoration: const BoxDecoration(
gradient: LinearGradient(
colors: [Colors.blue, Colors.purple],
begin: Alignment.topRight,
end: Alignment.bottomLeft)),
child: const Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
Icons.location_on_outlined,
size: 140,
color: secondarybgcolor,
),
SizedBox(
height: 15,
),
Text(
'Secure and Locate',
style: TextStyle(
fontWeight: FontWeight.w800,
fontSize: 27,
color: Colors.white),
),
SizedBox(
height: 4,
),
Text(
'track your missing or stolen phone',
style: TextStyle(
fontSize: 13,
color: Colors.white,
fontStyle: FontStyle.italic),
),
],
),
),
);
}
Future<void> Authenticatepage() async {
try {
final userData = await getUserDataFromLocalStorage();
final userId = userData['userId'];
final isLoggedIn = userData['isLoggedIn'];
if (userId != null && isLoggedIn) {
final prefs = await SharedPreferences.getInstance();
prefs.setBool('showHome', true);
} else {
final prefs = await SharedPreferences.getInstance();
prefs.setBool('showHome', false);
}
} catch (e) {
print("Error occurred: $e");
// Handle error, show toast or snackbar
}
}
}
|
#include "../../include/mockos/TouchCommand.h"
#include "../../include/mockos/PasswordProxy.h"
#include <iostream>
using namespace std;
TouchCommand::TouchCommand(AbstractFileSystem* afs, AbstractFileFactory* aff) {
this->afs = afs;
this->aff = aff;
}
void TouchCommand::displayInfo() {
cout << "touch - creates an empty file\nUsage:\n\ttouch <filename> [-p]\n\nOptions:\n\t-p: Protect the file with a password" << endl;
}
int TouchCommand::execute(string fName) {
if (fName.empty()) {
return badArguments;
}
int index = fName.find(" ");
if (index == string::npos) {
AbstractFile* newFile = aff->createFile(fName);
if (newFile == nullptr) {
return invalidExtension;
}
int result = afs->addFile(fName, newFile);
if (result != success)
{
delete newFile;
}
return result;
}
if ((fName.substr(index + 1, fName.size() - (index + 1))) == "-p") {
string password;
cout << "Set a password for this file: " << flush;
getline(cin, password);
AbstractFile* newFile = aff->createFile(fName.substr(0, index));
if (newFile == nullptr) {
return invalidExtension;
}
PasswordProxy* protectedFile = new PasswordProxy(newFile, password); // trim off the argument: " -p"
int result = afs->addFile(fName.substr(0, fName.size()-3), protectedFile);
if (result != success)
{
delete newFile;
}
return result;
}
return badArguments;
}
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_strmapi.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: dakim2 <dakim2@student.42seoul.kr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/07/27 15:27:17 by dakim2 #+# #+# */
/* Updated: 2022/07/29 06:14:47 by dakim2 ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
char *ft_strmapi(char const *s, char (*f)(unsigned int, char))
{
int i;
char *re;
i = 0;
re = malloc(sizeof(char) * (ft_strlen(s) + 1));
if (!re)
return (NULL);
while (s[i])
{
re[i] = f(i, s[i]);
i++;
}
re[i] = '\0';
return (re);
}
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
// - Khai báo 1 mảng số nguyên có tên arrayInt
//Cách 1:
let arrayInt = [];
//Cách 2:
// let arrayInt = new Array();
//1. Nhập 5 giá trị số nguyên cho mảng từ bàn phím
// Nhập 5 lần thì sẽ sử dụng vòng lặp for ... i
for (let i = 0; i < 5; i++) {
arrayInt[i] = +prompt("Nhập giá trị cho phần tử thứ " + (i + 1));
//arrayInt[0]=
//arrayInt[1]=
//arrayInt[2]=
//arrayInt[3]=
// arrayInt[4] =
// Ở đây chúng ta dùng hàm prompt để người dùng nhập
// vào giá trị và lưu giá tị đó vào phần tử i của mảng arrayInt
}
//2. hiển thị các phần tử của mảng ->> chúng ta sử dụng vòng lặp để duyệt mảng
console.log("Các phần tử của mảng là")
for (let i = 0; i < arrayInt.length; i++) {
console.log("Phần tử thứ " + (i + 1) + ": " + arrayInt[i]);
//khi i = 0 =>>> in ra phần tử thứ 1 ==> kêt quả sẽ là : Phần tử thứ 1 : giá trị người dùng nhập vào ở ý 1
}
//3. In các phần tử có giá trị chẵn và tính tổng .
let tongChan = 0; // tạo 1 biến tổng tính tổng các số chẵn
console.log("Các phần tử có giá trị chẵn trong mảng là :")
for (let i = 0; i < arrayInt.length; i++) {
if (arrayInt[i] % 2 === 0) {
// nếu arrayInt[i] là số chẵn thì hiển thị ra và tính tổng
console.log("Phần tử thứ " + (i + 1) + ": " + arrayInt[i]);
tongChan += arrayInt[i];
}
}
// kết thúc vong lặp mới in tổng
console.log("Tổng các phần tử chẵn trong mảng là : " + tongChan)
//4. In các phần tử có chỉ số lẻ và tính tổng
let tongChiSoLe = 0; // tạo 1 biến tổng tính tổng
console.log("Các phần tử có vị trí lẻ trong mảng là :")
// duyệt mảng (chú ý ): - i: vị trí từng phần tử(index)
// - arrayInt[i] : giá trị phần tử mảng arrayInt tại vị trí i
for (let i = 0; i < arrayInt.length; i++) {
if (i % 2 !== 0) {
// nếu i là số lẻ thì hiển thị ra và tính tổng
console.log("Phần tử thứ " + (i + 1) + ": " + arrayInt[i] + "(Phần tử có vị trí là " + i + ")");
tongChiSoLe = tongChiSoLe + arrayInt[i];
}
}
// kết thúc vong lặp mới in tổng
console.log("Tổng các phần tử tại vị trí lẻ trong mảng là : " + tongChiSoLe);
// 5. In giá trị phần tử trong mảng là số nguyên tố;
// Ở đây chúng ta sẽ duyệt từng phần tử mảng để kiểm tra xem phần tử đó có phải số nguyên tố không .
console.log("Các số nguyên tố tìm được trong mảng là :")
for (let i = 0; i < arrayInt.length; i++) {
let n = arrayInt[i]; //Lấy ra giá trị phần tử hiện tại lưu vào biến n
// bắt đầu kiểm tra xem n có phải số nguyên tố không
let check = true; // giả sử n là số nguyên tố ứng với check = true
if (n < 2) {
// số nguyên tố phải >= 2
check = false
}
for (let j = 2; j < n; j++) {
if (n % j === 0) { // j là 1 ước của n
// n ko là số nguyên tố
check = false;
break;
}
}
if (check === true) {
//n là só nguyên tố
console.log("Phần tử thứ " + (i + 1) + ": " + n);
}
}
//6.In các phần tử có giá trị max hoặc min
// đầu tiên ta sẽ tìm giá trị max và min
let max = arrayInt[0];// giả sự max = phần tử đầu tiên
let min = arrayInt[0];// giả sử min là phần tử đầu tiên
// tiến hành duyệt mảng và tiến hành so sánh với các phần tử mảng , chú ý bỏ qua phần tử đầu tiên không cần so sánh
for (let i = 1; i < arrayInt.length; i++) {
if (max < arrayInt[i]) {
max = arrayInt[i];
}
if (min > arrayInt[i]) {
min = arrayInt[i]
}
}
// sau khi đã có giá trị max mà min , tiến hành lặp mảng để in ra những phần tử bằng giá tị max và min
console.log("Các phần tử max trong mảng là ")
for (let i = 0; i < arrayInt.length; i++) {
if (max === arrayInt[i]) {
console.log("Phần tử thứ " + (i + 1) + ": " + arrayInt[i]);
}
}
console.log("Các phần tử min trong mảng là ")
for (let i = 0; i < arrayInt.length; i++) {
if (min === arrayInt[i]) {
console.log("Phần tử thứ " + (i + 1) + ": " + arrayInt[i]);
}
}
//7. Sắp xếp mảng giảm dần và in giá trị các phần tử mảng sau khi đã sắp xếp
// Sắp xếp mảng :
// thuật toán sắp xếp chọn
for (let i = 0; i < arrayInt.length - 1; i++) {
for (let j = i + 1; j < arrayInt.length; j++) {
if (arrayInt[i] > arrayInt[j]) {
let temp = arrayInt[i];
arrayInt[i] = arrayInt[j];
arrayInt[j] = temp
}
}
}
// hiển thị mảng --- giống câu 2
console.log("Mảng sau khi đã sắp xếp là")
for (let i = 0; i < arrayInt.length; i++) {
console.log("Phần tử thứ " + (i + 1) + ": " + arrayInt[i]);
}
//8. Nhập vào 1 số nguyên và thống kê có bao nhiêu phần tử như vậy
// Nhập vào 1 số
let number = +prompt("Nhập vào 1 số cần kiểm tra")
// tạo 1 biến để đếm số lần xuất hiện
let count = 0;
// duyệt mảng để tìm kiếm
for (let i = 0; i < arrayInt.length; i++) {
if (arrayInt[i] === number) {
count++;
}
}
console.log("Giá trị " + number + " xuất hiện " + count + " lần.")
</script>
</body>
</html>
|
"""Data structures relevant for managing datasets."""
import math
import uuid
from typing import Dict, List, Union, no_type_check
import torch
from datasets import Audio as HFAudio
from datasets import Dataset, Features, Image, Sequence, Value
from pydantic import BaseModel, Field, ValidationInfo, field_validator
from transformers.image_transforms import to_pil_image
from senselab.audio.data_structures.audio import Audio
from senselab.video.data_structures.video import Video
class Participant(BaseModel):
"""Data structure for a participant in a dataset."""
id: str = Field(default_factory=lambda: str(uuid.uuid4()))
metadata: Dict = Field(default={})
@field_validator("id", mode="before")
def set_id(cls, v: str) -> str:
"""Set the unique id of the participant."""
return v or str(uuid.uuid4())
def __eq__(self, other: object) -> bool:
"""Overloads the default BaseModel equality to correctly check that ids are equivalent."""
if isinstance(other, Participant):
return self.id == other.id
return False
class Session(BaseModel):
"""Data structure for a session in a dataset."""
id: str = Field(default_factory=lambda: str(uuid.uuid4()))
metadata: Dict = Field(default={})
@field_validator("id", mode="before")
def set_id(cls, v: str) -> str:
"""Set the unique id of the session."""
return v or str(uuid.uuid4())
def __eq__(self, other: object) -> bool:
"""Overloads the default BaseModel equality to correctly check that ids are equivalent."""
if isinstance(other, Session):
return self.id == other.id
return False
class SenselabDataset(BaseModel):
"""Class for maintaining SenseLab datasets and functionalities.
Maintains collections of Audios, Videos, and metadata for use of the Senselab tools
and pipelines. Includes the ability to manage Sessions and Participants.
Attributes:
audios: List of Audios that are generated based on list of audio filepaths
videos: List of Videos generated from a list of video filepaths
metadata: Metadata related to the dataset overall but not necessarily the metadata of
indivudal audios in the dataset
sessions: Session ID mapping to Session instance
participants: Mapping of participant ID to a Participant instance
"""
participants: Dict[str, Participant] = Field(default_factory=dict)
sessions: Dict[str, Session] = Field(default_factory=dict)
audios: List[Audio] = []
videos: List[Video] = []
metadata: Dict = Field(default={})
@field_validator("audios", mode="before")
@classmethod
def generate_audios_from_filepaths(cls, v: Union[List[str], List[Audio]], _: ValidationInfo) -> List[Audio]:
"""Generate the audios in the dataset from a list of audio filepaths.
Generates the audios in the dataset by taking in a list of audio filepaths
or a list of Audios
Args:
v: Input for audios attribute that we're validating by generating the Audios if filepaths
are provided or just the list of Audios if pre-generated and passed in
Returns:
List of Audios that instantiates the audios attribute in the dataset
"""
audio_list = []
if len(v) == 0:
return []
else:
for audio in v:
if isinstance(audio, Audio):
audio_list.append(audio)
else:
audio_list.append(Audio.from_filepath(audio))
return audio_list
@field_validator("videos", mode="before")
@classmethod
def generate_videos_from_filepaths(cls, v: Union[List[str], List[Video]], _: ValidationInfo) -> List[Video]:
"""Generate the videos in the dataset from a list of video filepaths.
Generates the videos in the dataset by taking in a list of video filepaths
or a list of Videos
Args:
v: Input for videos attribute that we're validating by generating the Videos if filepaths
are provided or just the list of Videos if pre-generated and passed in
Returns:
List of Videos that instantiates the videos attribute in the dataset
"""
video_list = []
if len(v) == 0:
return []
else:
for video in v:
if isinstance(video, Video):
video_list.append(video)
elif isinstance(video, str):
video_list.append(Video.from_filepath(video))
else:
raise ValueError("Unsupported video list")
return video_list
@classmethod
@no_type_check
def create_bids_dataset(cls, bids_root_filepath: str) -> "SenselabDataset":
"""Create a dataset from a BIDS organized directory.
Creates a new dataset based off of a BIDS directory structure as defined at
https://sensein.group/biometrics-book/updated_bids.html
"""
pass
def create_audio_split_for_pydra_task(self, batch_size: int = 1) -> List[List[Audio]]:
"""Splits the audio data for Pydra tasks.
Creates a split of the audio data that can be used for creating individual Pydra tasks using
the .split functionality. Splits the data such that the inputs for a Pydra workflow are either
optimized for the GPU's batch size or a single Audio per CPU thread.
Args:
batch_size: How to batch Audios for a Pydra task; defaults to 1 since CPU won't batch
Returns:
List of Lists of Audio where each List of Audios will be an input to a Pydra task.
Each of the sublists are either of size 1 for CPUs or at most batch_size for GPU optimization.
Raises:
ValueError if the batch size is invalid (less than 1)
"""
if batch_size > 1:
# Creates batches of at most size batch_size except the last which contains the remainder of audios
return [
self.audios[batch_size * i : min(batch_size * (i + 1), len(self.audios))]
for i in range(math.ceil(len(self.audios) / batch_size))
]
elif batch_size < 1:
raise ValueError("Batch size must be greater than or equal to 1")
else:
return [[audio] for audio in self.audios]
def audio_merge_from_pydra_task(self, audios_to_merge: List[List[Audio]]) -> None:
"""Write later.
Logic Pydra:
audios: List of audios that want to give to task
split: List[List[Audios]] -> task List[Audio]
pydra task(List[Audio]) -> List[Audio]
merge(List[List[Audio]]) <- might be a wrapped instead of List of lists
TODO: Figure out what a merge behavior looks like from Pydra
"""
self.audios = []
for audio_task_input in audios_to_merge:
for audio_output in audio_task_input:
self.audios.append(audio_output)
def add_participant(self, participant: Participant) -> None:
"""Add a participant to the dataset."""
if participant.id in self.participants:
raise ValueError(f"Participant with ID {participant.id} already exists.")
self.participants[participant.id] = participant
def add_session(self, session: Session) -> None:
"""Add a session to the dataset."""
if session.id in self.sessions:
raise ValueError(f"Session with ID {session.id} already exists.")
self.sessions[session.id] = session
def get_participants(self) -> List[Participant]:
"""Get the list of participants in the dataset."""
return list(self.participants.values())
def get_sessions(self) -> List[Session]:
"""Get the list of sessions in the dataset."""
return list(self.sessions.values())
def _get_dict_representation(self) -> Dict:
audio_data: Dict[str, List] = {}
video_data: Dict[str, List] = {}
senselab_dict: Dict[str, Union[Dict[str, List], List]] = {
"participants": [],
"sessions": [],
"audios": audio_data,
"videos": video_data,
"metadata": self.metadata.copy(),
}
participants_data = []
sessions_data = []
video_frames_data = []
video_fps_data = []
video_path_data = []
video_metadata = []
video_audio_data = []
video_audio_metadata = []
audio_waveform_data = []
audio_metadata = []
for participant in self.get_participants():
participants_data.append({"id": participant.id, "metadata": participant.metadata.copy()})
senselab_dict["participants"] = participants_data
for session in self.get_sessions():
sessions_data.append({"id": session.id, "metadata": session.metadata.copy()})
senselab_dict["sessions"] = sessions_data
for audio in self.audios:
audio_waveform_data.append(
{
"array": audio.waveform.T,
"sampling_rate": audio.sampling_rate,
"path": audio.generate_path(),
}
)
audio_metadata.append(audio.metadata.copy())
audio_data["audio"] = audio_waveform_data
audio_data["metadata"] = audio_metadata
for video in self.videos:
video_frames_data.append({"image": [to_pil_image(frame.numpy()) for frame in list(video.frames)]})
video_fps_data.append(video.frame_rate)
video_path_data.append(video.generate_path())
video_metadata.append(video.metadata.copy())
video_audio_data.append(
None
if not video.audio
else {
"array": video.audio.waveform.T.to(torch.float32).numpy(),
"sampling_rate": video.audio.sampling_rate,
"path": video.audio.generate_path(),
}
)
video_audio_metadata.append(None if not video.audio else video.audio.metadata.copy())
video_data["frames"] = video_frames_data
video_data["frame_rate"] = video_fps_data
video_data["path"] = video_path_data
video_data["metadata"] = video_metadata
video_data["audio"] = video_audio_data
video_data["audio_metadata"] = video_audio_metadata
# raise ValueError('fuck')
return senselab_dict
def convert_senselab_dataset_to_hf_datasets(self) -> Dict[str, Dataset]:
"""Converts Senselab datasets into HuggingFace datasets."""
senselab_dict = self._get_dict_representation()
# print(senselab_dict['videos']['audio'][0])
features = Features(
{
"frames": {"image": Sequence(feature=Image())},
"frame_rate": Value("float32"),
"path": Value("string"),
"metadata": {},
"audio": HFAudio(mono=False, sampling_rate=48000),
"audio_metadata": Value("string"),
}
)
audio_dataset = Dataset.from_dict(senselab_dict["audios"]).cast_column("audio", HFAudio(mono=False))
video_dataset = Dataset.from_dict(senselab_dict["videos"], features=features)
# print(video_dataset[0])
hf_datasets = {}
hf_datasets["audios"] = audio_dataset
hf_datasets["videos"] = video_dataset
# TODO: Create datasets for participants and sessions
return hf_datasets
@classmethod
def convert_hf_dataset_to_senselab_dataset(cls, hf_datasets: Dict[str, Dataset]) -> "SenselabDataset":
"""Converts HuggingFace dataset to a Senselab dataset."""
audios = []
videos = []
sessions: Dict[str, Session] = {}
participants: Dict[str, Participant] = {}
if "audios" in hf_datasets:
audio_dataset = hf_datasets["audios"]
for audio in audio_dataset:
audios.append(
Audio(
waveform=audio["audio"]["array"],
sampling_rate=audio["audio"]["sampling_rate"],
orig_path_or_id=audio["audio"]["path"],
metadata=audio["metadata"],
)
)
if "videos" in hf_datasets:
video_dataset = hf_datasets["videos"]
for video in video_dataset:
videos.append(
Video(
frames=video["frames"]["image"],
frame_rate=video["frame_rate"],
metadata=video["metadata"],
orig_path_or_id=video["path"],
audio=Audio(
waveform=video["audio"]["array"],
sampling_rate=video["audio"]["sampling_rate"],
orig_path_or_id=video["audio"]["path"],
)
if video["audio"]
else None,
)
)
if "sessions" in hf_datasets:
pass
if "participants" in hf_datasets:
pass
return SenselabDataset(participants=participants, sessions=sessions, audios=audios, videos=videos)
def __eq__(self, other: object) -> bool:
"""Overloads the default BaseModel equality to correctly check that datasets are equivalent."""
if isinstance(other, SenselabDataset):
return (
self.audios == other.audios
and self.videos == other.videos
and self.participants == other.participants
and self.sessions == other.sessions
)
return False
|
import { nanoid } from "nanoid";
import PropTypes from 'prop-types';
import { Label, Input } from './FilterStyles';
const filterinputId = nanoid();
const Filter = ({handleChange}) => {
return (
<Label htmlFor={filterinputId}>
Find contacts by name
<Input
type="text"
name="filter"
pattern="^[a-zA-Zа-яА-Я]+(([' -][a-zA-Zа-яА-Я ])?[a-zA-Zа-яА-Я]*)*$"
title="Name may contain only letters, apostrophe, dash and spaces. For example Adrian, Jacob Mercer, Charles de Batz de Castelmore d'Artagnan"
id={filterinputId}
onChange={handleChange}
required />
</Label>
)
}
Filter.propTypes = {
handleChange: PropTypes.func.isRequired,
}
export default Filter;
|
import PropTypes from 'prop-types';
import classNamesBind from 'classnames/bind';
import styles from './Displays.module.scss';
const cx = classNamesBind.bind(styles);
const Displays = ({ className, isActive, value }) => {
const classNames = cx({
Displays: true,
Displays_active: isActive,
[className]: !!className,
});
return (
<div className={classNames}>
{value}
</div>
);
};
export default Displays;
Displays.propTypes = {
className: PropTypes.string,
isActive: PropTypes.bool,
value: PropTypes.string.isRequired,
};
Displays.defaultProps = {
className: '',
isActive: false,
};
|
package com.example.nu_mad_sp2023_final_project_10;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.firestore.DocumentReference;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.OnProgressListener;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import android.Manifest;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.Map;
public class MainActivity extends AppCompatActivity implements IfromFragmentToActivity,
CreateMoodFragment.IFromCreateMood,
ChooseMoodAdapter.IFromChooseMoodAdapter,
JournalEntryFragment.IFromJournalEntry,
IcameraFragmentNavigation {
private static final String TAG = "MainActivity";
private static final int PERMISSIONS_CODE = 0x100;
private FirebaseUser currentUser;
private FirebaseFirestore db;
private FirebaseAuth mAuth;
private FirebaseStorage storage;
private User currentLocalUser;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
db = FirebaseFirestore.getInstance();
mAuth = FirebaseAuth.getInstance();
storage = FirebaseStorage.getInstance();
Boolean cameraAllowed = ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED;
Boolean readAllowed = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED;
Boolean writeAllowed = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED;
if(cameraAllowed && readAllowed && writeAllowed) {
Toast.makeText(this, "All permissions granted!", Toast.LENGTH_SHORT).show();
loadJournal();
} else {
requestPermissions(new String[] {
Manifest.permission.CAMERA,
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE
}, PERMISSIONS_CODE);
}
}
@Override
protected void onStart() {
super.onStart();
currentUser = mAuth.getCurrentUser();
loadJournal();
}
@Override
public void fromFragment(boolean toLoginPage) {
if(toLoginPage) {
getSupportFragmentManager().beginTransaction()
.replace(R.id.fragment_container, LoginFragment.newInstance(), "LoginFragment")
.addToBackStack(null).commit();
} else {
getSupportFragmentManager().beginTransaction()
.replace(R.id.fragment_container, RegisterFragment.newInstance(), "RegisterFragment")
.addToBackStack(null).commit();
}
}
private void loadJournal() {
if (currentUser != null) {
getSupportFragmentManager().popBackStack();
populateMainFragment(currentUser);
} else {
getSupportFragmentManager().beginTransaction()
.replace(R.id.fragment_container, HomePageFragment
.newInstance(),"HomePageFragment")
.commit();
}
}
@Override
public void onLogout() {
mAuth.signOut();
currentUser = null;
loadJournal();
}
@Override
public void onMemoryBox() {
getSupportFragmentManager().beginTransaction()
.replace(R.id.fragment_container, MemoryBoxFragment.newInstance(), "MemoryBoxFragment")
.addToBackStack("JournalHomePageFragment")
.commit();
}
@Override
public void onCalendar() {
getSupportFragmentManager().beginTransaction()
.replace(R.id.fragment_container, JournalHomePageFragment.newInstance(currentLocalUser), "JournalHomePageFragmentMemoryBoxFragment")
.addToBackStack("MemoryBoxFragment")
.commit();
}
@Override
public void populateMainFragment(FirebaseUser currentUser) {
this.currentUser = currentUser;
getSupportFragmentManager().popBackStack();
db.collection("users")
.document(currentUser.getEmail())
.get()
.addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
@Override
public void onComplete(@NonNull Task<DocumentSnapshot> task) {
if(task.isSuccessful()){
currentLocalUser = task.getResult()
.toObject(User.class);
//Populating The Main Fragment....
getSupportFragmentManager().beginTransaction()
.replace(R.id.fragment_container, JournalHomePageFragment.newInstance(currentLocalUser),"JournalHomePageFragment")
.commit();
// This is the call that needs to be made when something is pressed in the recylcer "calendar"
// ** pass in the actual date clicked, not today's date (but has to be a Date object) **
}
}
});
}
@Override
public void registerDone(FirebaseUser firebaseUser, User user) {
this.currentLocalUser = user;
this.currentUser = firebaseUser;
// Updating the Firestore structure....
updateFirestoreWithUserDetails(user);
}
@Override
public void onDaySelected(LocalDate date) {
getSupportFragmentManager().beginTransaction()
.replace(R.id.fragment_container, JournalEntryFragment.newInstance(date), "JournalEntryFragment")
.addToBackStack(null).commit();
}
private void updateFirestoreWithUserDetails(User user) {
db.collection("users")
.document(user.getEmail())
.set(user)
.addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void unused) {
// On success populate home screen...
populateMainFragment(currentUser);
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
}
});
}
@Override
public void onMoodCreation(DocumentReference newMoodRef) {
getSupportFragmentManager().popBackStack();
JournalEntryFragment journalEntryFragment = (JournalEntryFragment) getSupportFragmentManager()
.findFragmentByTag("JournalEntryFragment");
journalEntryFragment.updateSelectedMood(newMoodRef);
}
@Override
public void onChooseMood(int position) {
JournalEntryFragment journalEntryFragment = (JournalEntryFragment) getSupportFragmentManager()
.findFragmentByTag("JournalEntryFragment");
journalEntryFragment.updateSelectedMood(position);
}
@Override
public void onCreateMood() {
getSupportFragmentManager().beginTransaction()
.replace(R.id.fragment_container, CreateMoodFragment.newInstance(), "CreateMoodFragment")
.addToBackStack(null).commit();
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(grantResults.length > 0) {
loadJournal();
} else {
Toast.makeText(this, "You must allow Camera and Storage permissions!", Toast.LENGTH_LONG).show();
}
}
@Override
public void fromFragToCam() {
getSupportFragmentManager().beginTransaction()
.replace(R.id.fragment_container, CameraControlFragment.newInstance(), "CameraControlFragment")
.addToBackStack("CameraControl").commit();
}
@Override
public void fromCamToDis(Uri imageUri) {
getSupportFragmentManager().beginTransaction()
.replace(R.id.fragment_container, DisplayPhotoFragment.newInstance(imageUri), "DisplayPhotoFragment")
.addToBackStack("DisplayPhoto").commit();
}
public void fromCamToMem(Uri imageUri) {
StorageReference storageReference = storage.getReference();
storageReference = storageReference.child("images/" + imageUri.getLastPathSegment());
UploadTask uploadImage = storageReference.putFile(imageUri);
uploadImage.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Toast.makeText(MainActivity.this, "Upload Failed! Try again!", Toast.LENGTH_SHORT).show();
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(MainActivity.this, "Upload Successful!", Toast.LENGTH_SHORT).show();
Map<String, Object> im = new HashMap<>();
im.put("image", imageUri);
im.put("storageRef", "images/" + imageUri.getLastPathSegment());
db.collection("users")
.document(currentUser.getEmail())
.collection("images")
.document(imageUri.getLastPathSegment()).set(im);
getSupportFragmentManager().beginTransaction()
.replace(R.id.fragment_container, MemoryBoxFragment.newInstance(), "MemoryBoxFragment")
.addToBackStack("MemoryBox").commit();
}
});
}
@Override
public void fromDisToMem(Uri imageUri, ProgressBar progressBar) {
progressBar.setVisibility(View.VISIBLE);
StorageReference storageReference = storage.getReference();
storageReference = storageReference.child("images/" + imageUri.getLastPathSegment());
UploadTask uploadImage = storageReference.putFile(imageUri);
uploadImage.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Toast.makeText(MainActivity.this, "Upload Failed! Try again!", Toast.LENGTH_SHORT).show();
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(MainActivity.this, "Upload Successful!", Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
Map<String, Object> im = new HashMap<>();
im.put("image", imageUri);
im.put("storageRef", "images/" + imageUri.getLastPathSegment());
db.collection("users")
.document(currentUser.getEmail())
.collection("images")
.document(imageUri.getLastPathSegment()).set(im);
getSupportFragmentManager().beginTransaction()
.replace(R.id.fragment_container, MemoryBoxFragment.newInstance(), "MemoryBoxFragment")
.addToBackStack("MemoryBox").commit();
}
}).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
@Override
public void onProgress(@NonNull UploadTask.TaskSnapshot snapshot) {
double progress = (100.0 * snapshot.getBytesTransferred()) / snapshot.getTotalByteCount();
progressBar.setProgress((int) progress);
}
});
}
@Override
public void onEntryDone() {
getSupportFragmentManager().popBackStack();
}
}
|
require 'rails_helper'
describe "Warehouse API" do
context "GET /api/v1/warehouses/1" do
it "success" do
# Arrange
warehouse = Warehouse.create!(name: 'Aeroporto SP', code: 'GRU', city: 'Guarulhos', area: 100_000,
address: 'Avenida do Aeroporto, 1000', cep: '15000-000',
description: 'Galpão destinado a cargas internacionais')
# Act
#get('/api/v1/warehouses/1')
get "/api/v1/warehouses/#{warehouse.id}" #melhor desta forma pois, diferentemente do SQLite, há bancos de dados que não resetam o id depois dos testes
# Assert
expect(response.status).to eq 200
expect(response.content_type).to include 'application/json' # se fosse eq, daria erro pois => got: "application/json; charset=utf-8"
#expect(response.body).to include('Aeroporto SP')
#expect(response.body).to "alguma string" => response.body --> String em formato JSON
json_response = JSON.parse(response.body) # método do Ruby, converte formato JSON em formato ruby (hash, por padrão)
expect(json_response["name"]).to eq 'Aeroporto SP'
expect(json_response["code"]).to eq 'GRU'
expect(json_response.keys).not_to include("created_at")
expect(json_response.keys).not_to include("updated_at")
end
it "fail if warehouse not found" do
# Arrange
# Act
get('/api/v1/warehouses/99999')
# Assert
expect(response.status).to eq 404
end
end
context "GET /api/v1/warehouses" do
it "list all warehouses" do
# Arrange
first_warehouse = Warehouse.create!(name: 'Aeroporto SP', code: 'GRU', city: 'Guarulhos', area: 100_000,
address: 'Avenida do Aeroporto, 1000', cep: '15000-000',
description: 'Galpão destinado a cargas internacionais')
second_warehouse = Warehouse.create!(name: 'Cuiabá', code: 'CWB', city: 'Cuiabá', area: 10000,
address: 'Avenida dos Jacarés, 2555', cep: '56000-000',
description: 'Galpão no centro do país')
# Act
get '/api/v1/warehouses'
# Assert
expect(response.status).to eq 200
expect(response.content_type).to include 'application/json'
json_response = JSON.parse(response.body)
expect(json_response.class).to eq Array
expect(json_response.length).to eq 2
expect(json_response[0]["name"]).to eq 'Aeroporto SP'
expect(json_response[1]["name"]).to eq 'Cuiabá'
end
it "return empty if there is no warehouse" do
# Arrange
# Act
get '/api/v1/warehouses'
# Assert
expect(response.status).to eq 200
expect(response.content_type).to include 'application/json'
json_response = JSON.parse(response.body)
expect(json_response).to eq []
end
it "and raise an internal error" do
# Arrange
allow(Warehouse).to receive(:all).and_raise(ActiveRecord::QueryCanceled)
# Act
get '/api/v1/warehouses'
# Assert
expect(response).to have_http_status(500)
end
end
context "POST /api/v1/warehouses" do
it "success" do
# Arrange
warehouse_params = { warehouse: {name: "Galpão da Ilha", code: "FLR", city: "Florianópolis",
area: 35_000, address: "Praia do Campech, 100", cep: "88058-300",
description: "Um galpão especializado na região sul" }
}
# Act
post '/api/v1/warehouses', params: warehouse_params
# Assert
#expect(response.status).to eq 201
#expect(response).to have_http_status(:created) ou
expect(response).to have_http_status(201)
expect(response.content_type).to include 'application/json'
json_response = JSON.parse(response.body)
expect(json_response["name"]).to eq 'Galpão da Ilha'
expect(json_response["code"]).to eq 'FLR'
expect(json_response["city"]).to eq 'Florianópolis'
expect(json_response["area"]).to eq 35000
expect(json_response["address"]).to eq 'Praia do Campech, 100'
expect(json_response["cep"]).to eq '88058-300'
expect(json_response["description"]).to eq 'Um galpão especializado na região sul'
end
it "fail if parameters are not complete" do
# Arrange
warehouse_params = { warehouse: {name: "Galpão da Ilha", code: "FLR" } }
# Act
post '/api/v1/warehouses', params: warehouse_params
# Assert
expect(response).to have_http_status(412)
expect(response.body).not_to include('Nome não pode ficar em branco')
expect(response.body).not_to include('Código não pode ficar em branco')
expect(response.body).to include('Cidade não pode ficar em branco')
expect(response.body).to include('Descrição do galpão não pode ficar em branco')
expect(response.body).to include('Endereço não pode ficar em branco')
expect(response.body).to include('CEP não pode ficar em branco')
expect(response.body).to include('Área não pode ficar em branco')
end
it "fail if there is an internal error" do
# Arrange - Mock => interferir na execução do código usando métodos do rspec para disparar um erro
allow(Warehouse).to receive(:new).and_raise(ActiveRecord::ActiveRecordError)
warehouse_params = { warehouse: { name: "Galpão da Ilha", code: "FLR", city: "Florianópolis",
area: 35_000, address: "Praia do Campech, 100", cep: "88058-300",
description: "Um galpão especializado na região sul" }
}
# Act - postar dados completos para criar um galpão
post '/api/v1/warehouses', params: warehouse_params
# Assert - algum erro 500
expect(response).to have_http_status(500)
end
end
end
|
from django.urls import reverse_lazy # Для отложенного вычисления URL-адресов
from django.views.generic import ListView, CreateView, UpdateView, DeleteView
from django.contrib.auth.mixins import UserPassesTestMixin
from django.contrib import messages
from django.shortcuts import redirect
from django.contrib.auth import get_user_model
from django.utils.translation import gettext as _
from task_manager.mixins import CustomLoginRequired
from task_manager.users.forms import UserForm
from django.contrib.messages.views import SuccessMessageMixin
User = get_user_model() # Получаем юзера
class LoginRequiredAndUserSelfCheckMixin(CustomLoginRequired, UserPassesTestMixin):
def test_func(self):
return self.request.user == self.get_object()
def handle_no_permission(self):
if not self.request.user.is_authenticated:
return super().handle_no_permission()
else:
messages.error(
self.request,
_('You do not have permission to modify another user.'))
return redirect('user_list')
# Отображение
class UserListView(ListView):
model = User
template_name = 'users/list.html'
context_object_name = 'users'
# Создание
class UserCreateView(SuccessMessageMixin, CreateView):
model = User()
form_class = UserForm
template_name = 'users/create.html'
success_url = reverse_lazy('login') # отложенное определение URL-адреса
success_message = _("The user has been successfully registered")
# Редактирование
class UserUpdateView(LoginRequiredAndUserSelfCheckMixin, SuccessMessageMixin, UpdateView):
model = User
form_class = UserForm
template_name = 'users/update.html'
success_url = reverse_lazy('user_list') # Перенаправление
success_message = _("User successfully updated") # Флешка и перевод строки через '_'
# Удаление
class UserDeleteView(LoginRequiredAndUserSelfCheckMixin, SuccessMessageMixin, DeleteView):
model = User
template_name = 'users/delete.html'
success_url = reverse_lazy('user_list') # Перенаправление
success_message = _("User successfully deleted")
|
import { Time } from './Time'
/**
* Represents a time interval.
*/
export class TimeInterval {
/**
* The start of the interval.
*/
public start: Time
/**
* The end of the interval.
*/
public end: Time
/**
* Creates a new TimeInterval instance.
* @param start The start of the interval.
* @param end The end of the interval.
* @throws if the start time is after the end time.
*/
constructor(start: Time, end: Time) {
if (start > end) throw new Error('Start time must be before end time')
this.start = start
this.end = end
}
/**
* Returns the duration of the interval as a new Time instance.
*/
public getDuration(): Time {
return this.end.difference(this.start)
}
/**
* Returns the interval as a string, rendering both the start and end times.
* Renders in the format "HH:MM:SS.mmm --> HH:MM:SS.mmm", with the default delimiter being " --> ".
* @param delimiter The delimiter between the start and end times.
* @param msDelimiter The delimiter between seconds and milliseconds.
*/
toString(delimiter = ' --> ', msDelimiter = '.'): string {
return `${this.start.toString(msDelimiter)}${delimiter}${this.end.toString(msDelimiter)}`
}
}
|
import React, { useEffect, useMemo, useRef, useState } from "react";
import flvjs from "flv.js";
import styled from "styled-components";
import { ServerStream } from "interfaces/Stream.interface";
import { StyledButton } from "./styled/styled-button";
type Props = flvjs.MediaDataSource &
flvjs.Config & {
stream: ServerStream;
streamKey: string;
};
export default function ReactFlvPlayer({
type,
isLive,
enableStashBuffer,
stashInitialSize,
hasAudio,
hasVideo,
stream,
streamKey,
}: Props) {
const myRef = useRef<HTMLVideoElement>();
const [player, setPlayer] = useState<flvjs.Player>();
const [quality, setQuality] = useState<number>();
useEffect(() => {
init();
return () => {
setPlayer((player) => {
try {
player?.pause();
player?.unload();
player?.detachMediaElement();
player?.destroy();
return undefined;
} catch {}
});
};
}, [quality]);
const qualities = useMemo(
() =>
stream.streams
.filter((s) => s.info.video.height !== 0)
.map((s) => ({ value: s.info.video.height, name: s.name }))
.sort((a, b) => b.value - a.value),
[stream]
);
const init = () => {
if (player) {
player.destroy();
}
if (flvjs.isSupported()) {
const url = `${process.env.REACT_APP_MEDIA_SERVER}/live/${
qualities.find((q) => q.value === quality)?.name || streamKey
}.flv`;
const flvPlayer = flvjs.createPlayer(
{
type,
isLive,
url,
hasAudio,
hasVideo,
},
{
enableStashBuffer,
stashInitialSize,
}
);
// flvjs.LoggingControl.enableError = false;
flvjs.LoggingControl.enableAll = false;
//@ts-ignore
flvPlayer.attachMediaElement(myRef.current);
flvPlayer.load();
flvPlayer.play();
setPlayer(flvPlayer);
}
};
return (
<PlayerView>
<PlayerWrapper>
<video
autoPlay={true}
controls={true}
muted={true}
//@ts-ignore
ref={myRef}
// style={{ height, width }}
/>
</PlayerWrapper>
<ControlsBar>
<select
value={quality || `${qualities[0]}p`}
onChange={(e) => setQuality(parseInt(e.target.value))}
// name="720"
>
{qualities.map((q) => (
<option key={q.value} value={q.value}>
{q.value}p
</option>
))}
</select>
</ControlsBar>
</PlayerView>
);
}
const PlayerView = styled.div`
display: flex;
flex-direction: column;
padding: 0.5rem;
justify-content: center;
& * {
margin: 0.5rem;
}
`;
const PlayerWrapper = styled.div`
max-width: 60rem;
position: relative;
/* width: 90%; */
aspect-ratio: 16 / 9;
& video {
margin: 0;
width: 100%;
height: auto;
left: 0;
right: 0;
position: absolute;
}
`;
const ControlsBar = styled.div`
display: flex;
`;
|
/* eslint-disable @typescript-eslint/no-explicit-any */
/* eslint-disable no-console */
/* eslint-disable react/jsx-no-bind */
import {
Button,
Flex,
Radio,
RadioGroup,
FormLabel,
Stack,
useToast,
FormErrorMessage,
FormControl,
Input,
} from "@chakra-ui/react";
import { Field, Form, Formik } from "formik";
import { useRouter } from "next/router";
import { useState } from "react";
import * as Yup from "yup";
type ValidationPostProcess = {
sex: string;
pregnant: boolean;
alcohol: boolean;
tobacco: boolean;
caffiene: boolean;
dob: Date;
};
const validation = Yup.object().shape({
sex: Yup.string().oneOf(["M", "F", "O"]).required(),
pregnant: Yup.boolean().required(),
alcohol: Yup.boolean().required(),
tobacco: Yup.boolean().required(),
caffiene: Yup.boolean().required(),
dob: Yup.date().required(),
});
const OnboardingForm = () => {
const [formState, setFormState] = useState(0);
const [submitting, SetSubmitting] = useState(false);
const router = useRouter();
const toast = useToast();
const handleNextPage = () => {
if (formState < 5) {
setFormState(formState + 1);
} else {
SetSubmitting(true);
}
};
const handlePreviousPage = () => {
if (formState > 0) setFormState(formState - 1);
};
function renderForm() {
return (
<Formik
initialValues={{
sex: "O",
pregnant: false,
alcohol: false,
tobacco: false,
caffiene: false,
dob: new Date(),
}}
onSubmit={async (values: any, actions: any) => {
const val: ValidationPostProcess = {
sex: values.sex,
pregnant: values.pregnant === "true",
alcohol: values.alcohol === "true",
tobacco: values.tobacco === "true",
caffiene: values.caffiene === "true",
dob: values.dob,
};
const res = await fetch("/api/postForm", {
method: "POST",
body: JSON.stringify(val),
});
const js = await res.json();
SetSubmitting(false);
actions.resetForm();
if (js.status) {
toast({
title: "You've Signed up!",
description: `Redirecting you to our homepage!`,
status: "success",
duration: 9000,
isClosable: true,
});
router.push("/");
} else {
toast({
title: "Error inserting User",
description: "Not supposed to happen. Contact develpers",
status: "error",
duration: 9000,
isClosable: true,
});
router.push("/");
}
}}
validationSchema={validation}
>
{(props) => (
<Form>
{formState === 0 && (
<Field name="sex">
{({ field, form }: { field: any; form: any }) => {
const { onChange, ...rest } = field;
return (
<FormControl
isInvalid={form.errors.sex && form.touched.sex}
>
<FormLabel htmlFor="sex">Select your Sex?</FormLabel>
<RadioGroup {...rest} id="sex" {...props}>
<Stack direction="column">
<Radio onChange={onChange} {...field} value="M">
Male
</Radio>
<Radio onChange={onChange} {...field} value="F">
Female
</Radio>
<Radio onChange={onChange} {...field} value="O">
Other/Prefer not to answer
</Radio>
</Stack>
</RadioGroup>
<FormErrorMessage>{form.errors.user}</FormErrorMessage>
</FormControl>
);
}}
</Field>
)}
{formState === 1 && (
<Field name="pregnant">
{({ field, form }: { field: any; form: any }) => {
const { onChange, ...rest } = field;
return (
<FormControl
isInvalid={form.errors.pregnant && form.touched.pregnant}
>
<FormLabel htmlFor="pregnant">
Are you Pregnant?
</FormLabel>
<RadioGroup id="pregnant" {...rest} {...props}>
<Stack direction="column">
<Radio onChange={onChange} {...field} value="true">
Yes
</Radio>
<Radio onChange={onChange} {...field} value="false">
No
</Radio>
</Stack>
</RadioGroup>
<FormErrorMessage>
{form.errors.pregnant}
</FormErrorMessage>
</FormControl>
);
}}
</Field>
)}
{formState === 2 && (
<Field name="alcohol">
{({ field, form }: { field: any; form: any }) => (
<FormControl
isInvalid={form.errors.alcohol && form.touched.alcohol}
>
<FormLabel htmlFor="alcohol">
Do you consume Alcohol?
</FormLabel>
<RadioGroup {...field} id="alcohol" {...props}>
<Stack direction="column">
<Radio {...field} value="true">
Yes
</Radio>
<Radio {...field} value="false">
No
</Radio>
</Stack>
</RadioGroup>
<FormErrorMessage>{form.errors.alcohol}</FormErrorMessage>
</FormControl>
)}
</Field>
)}
{formState === 3 && (
<Field name="tobacco">
{({ field, form }: { field: any; form: any }) => (
<FormControl
isInvalid={form.errors.tobacco && form.touched.tobacco}
>
<FormLabel htmlFor="tobacco">
Do you smoke/consume tobacco?
</FormLabel>
<RadioGroup {...field} id="tobacco" {...props}>
<Stack direction="column">
<Radio {...field} value="true">
Yes
</Radio>
<Radio {...field} value="false">
No
</Radio>
</Stack>
</RadioGroup>
<FormErrorMessage>{form.errors.tobacco}</FormErrorMessage>
</FormControl>
)}
</Field>
)}
{formState === 4 && (
<Field name="caffiene">
{({ field, form }: { field: any; form: any }) => (
<FormControl
isInvalid={form.errors.caffiene && form.touched.caffiene}
>
<FormLabel htmlFor="caffiene">
Do you consume Caffiene?
</FormLabel>
<RadioGroup {...field} id="caffiene" {...props}>
<Stack direction="column">
<Radio {...field} value="true">
Yes
</Radio>
<Radio {...field} value="false">
No
</Radio>
</Stack>
</RadioGroup>
<FormErrorMessage>{form.errors.caffiene}</FormErrorMessage>
</FormControl>
)}
</Field>
)}
{formState === 5 && (
<>
<Field name="dob">
{({ field, form }: { field: any; form: any }) => (
<FormControl
isInvalid={form.errors.dob && form.touched.dob}
>
<FormLabel htmlFor="dob">Date of Birth?</FormLabel>
<Input {...field} id="dob" type="date" />
<FormErrorMessage>{form.errors.dob}</FormErrorMessage>
</FormControl>
)}
</Field>
<Button
isLoading={submitting}
size="lg"
colorScheme="blue"
type="submit"
>
Submit
</Button>
</>
)}
</Form>
)}
</Formik>
);
}
return (
<Flex
direction="column"
alignItems="center"
justifyContent="center"
minHeight="25vh"
gap={4}
mb={8}
w="full"
>
{renderForm()}
<Flex
direction="row"
alignItems="center"
justifyContent="center"
gap={4}
w="full"
>
{formState > 0 ? (
<Button size="lg" colorScheme="blue" onClick={handlePreviousPage}>
Previous
</Button>
) : null}
{formState !== 5 && (
<Button size="lg" colorScheme="blue" onClick={handleNextPage}>
{formState === 5 ? <>Submit</> : <>Next</>}
</Button>
)}
</Flex>
</Flex>
);
};
export default OnboardingForm;
|
---
title: "Poisson regression Thesis"
author: "Bo Havinga"
output: html_document
---
Import data
```{r}
BUYquarter <- read.csv("/Users/Bo/Documents/Universiteit RSM/Master/Thesis/Data/BUYquarter.csv")
```
Make subset with the converted customers
```{r}
BUYquarterID <- subset(BUYquarter, event == 1)
```
Add which year they buy
```{r}
BUYquarterID$buyquarter <- BUYquarterID$Start_Date + BUYquarterID$tstop #This is an extra variable that needs to be included in the model
BUYquarterID$buyquarter <- as.factor(BUYquarterID$buyquarter)
BUYquarterID$buyyear <- BUYquarterID$buyquarter
year_buy <- c(`1` = 1, `2` = 1, `3` = 1,
`4` = 1, `5` = 2, `6` = 2,
`7` = 2, `8` = 2, `9` = 3,
`10` = 3, `11` = 3)
library(plyr)
BUYquarterID$buyyear <- mapvalues(BUYquarterID$buyyear, from = names(year_buy), to = year_buy)
season <- c(`1` = 1, `2` = 2, `3` = 3,
`4` = 4, `5` = 1, `6` = 2,
`7` = 3, `8` = 4, `9` = 1,
`10` = 2, `11` = 3)
BUYquarterID$season <- BUYquarterID$buyquarter
BUYquarterID$season <- mapvalues(BUYquarterID$buyquarter, from = names(season), to = season)
```
Remove outliers for dependent variable
```{r}
boxplot(BUYquarterID$revenue, yaxt="n")
Q1 <- quantile(BUYquarterID$revenue, .25)
Q3 <- quantile(BUYquarterID$revenue, .75)
IQR <- IQR(BUYquarterID$revenue)
BUYquarterID_out <- subset(BUYquarterID, BUYquarterID$revenue > (Q1 - 1.5*IQR) & BUYquarterID$revenue < (Q3 + 1.5*IQR))
dim(BUYquarterID_out)
boxplot(BUYquarterID_out$revenue, yaxt="n")
```
How many buys each year
```{r}
BUYquarterID_out$new_rev <- floor((BUYquarterID_out$revenue/CONFIDENTIAL INFORMATION))
sum(BUYquarterID_out$buyyear==1)
sum(BUYquarterID_out$buyyear==2)
sum(BUYquarterID_out$buyyear==3)
library(ggplot2)
ggplot(BUYquarterID_out, aes(x = new_rev)) +
geom_bar(fill = "dark blue") +
xlab("Dependent Variable: revenue_class") +
ylab("Count for Each Revenue Class") +
theme(panel.background = element_rect(fill = "white"),
panel.grid.major = element_line(color = "grey80")) +
scale_x_continuous(breaks = unique(BUYquarterID_out$new_rev))
#Quickly add four rows to better interpreted
new_rows <- data.frame(matrix(0, nrow = 4, ncol = 52))
names(new_rows) <- names(BUYquarterID_out)
# set the values of buyyear and season to 1 for each row
new_rows$buyyear <- 1
new_rows$season <- 1
new_data <- rbind(BUYquarterID_out, new_rows)
# Year
ggplot(new_data, aes(x = buyyear)) +
geom_bar(fill = "dark blue") +
xlab("Buying Year") +
ylab("Number of Converted Customers") +
theme(panel.background = element_rect(fill = "white"),
panel.grid.major = element_line(color = "grey80"))
```
How many buys each quarter
```{r}
library(ggplot2)
ggplot(new_data, aes(x = buyquarter)) +
geom_bar(fill = "dark blue") +
xlab("New Dependent Variable of Revenue: new_rev") +
ylab("Number of Converted Customers") +
theme(panel.background = element_rect(fill = "white"),
panel.grid.major = element_line(color = "grey80"))
# Show season without 23 because Q4 is missing
BUYquarterID_2122 <- subset(new_data, buyyear == 1 | buyyear == 2)
season_order <- factor(BUYquarterID_2122$season, levels = c(1, 2, 3, 4))
ggplot(BUYquarterID_2122, aes(x = season_order))+
geom_bar(fill = "dark blue") +
xlab("Quarter of the Year") +
ylab("Number of Converted Customers") +
theme(panel.background = element_rect(fill = "white"),
panel.grid.major = element_line(color = "grey80"))
# Show season with 23
season_order2 <- factor(new_data$season, levels = c(1, 2, 3, 4))
ggplot(new_data, aes(x = season_order2))+
geom_bar(fill = "dark blue") +
xlab("Quarter of the Year") +
ylab("Number of Converted Customers") +
theme(panel.background = element_rect(fill = "white"),
panel.grid.major = element_line(color = "grey80"))
```
Make new variable for revenue
```{r}
library(ggplot2)
ggplot(BUYquarterID_out, aes(x = new_rev)) +
geom_bar()
```
Average deal size each year
```{r}
mean(BUYquarterID_out[BUYquarterID_out$buyyear == 1, "new_rev"])
mean(BUYquarterID_out[BUYquarterID_out$buyyear == 2, "new_rev"])
mean(BUYquarterID_out[BUYquarterID_out$buyyear == 3, "new_rev"])
mean(BUYquarterID_out$new_rev)
```
Make variables standadized
```{r}
BUYquarterID_out$Employees_s <- scale(BUYquarterID_out$Employees)
BUYquarterID_out$cross_selling_s <- scale(BUYquarterID_out$cross_selling)
BUYquarterID_out$apps_MAU_s <- scale(BUYquarterID_out$apps_MAU)
BUYquarterID_out$Avg.Interactions.per.Contact_s <- scale(BUYquarterID_out$Avg.Interactions.per.Contact)
BUYquarterID_out$Avg.Interactions.per.Contact_lag_s <- scale(BUYquarterID_out$Avg.Interactions.per.Contact_lag)
BUYquarterID_out$tstop_s <- scale(BUYquarterID_out$tstop)
BUYquarterID_out$digital_content_s <- scale(BUYquarterID_out$digital_content)
BUYquarterID_out$events_s <- scale(BUYquarterID_out$events)
BUYquarterID_out$trails_s <- scale(BUYquarterID_out$trails)
BUYquarterID_out$freemium_s <- scale(BUYquarterID_out$freemium)
BUYquarterID_out$digital_content_s_lag <- scale(BUYquarterID_out$digital_content_lag)
BUYquarterID_out$events_s_lag <- scale(BUYquarterID_out$events_lag)
BUYquarterID_out$trails_s_lag <- scale(BUYquarterID_out$trails_lag)
BUYquarterID_out$freemium_s_lag <- scale(BUYquarterID_out$freemium_lag)
```
# Check for correlation
```{r}
# Make datasets for correlation plot
BUYquarterID_outcor_s <- BUYquarterID_out[,c(53,55,54,56,59:62,58)]
BUYquarterID_outcorboth_s <- BUYquarterID_out[,c(53,55,54,56,59,63,60,64,61,65,62,66,58)]
# Rename columns
names(BUYquarterID_outcor_s)[1] = "employees"
names(BUYquarterID_outcor_s)[2] = "avg_apps_built"
names(BUYquarterID_outcor_s)[3] = "cross_selling"
names(BUYquarterID_outcor_s)[4] = "avg_interactions_per_employee"
names(BUYquarterID_outcor_s)[5] = "digital_content_downloads"
names(BUYquarterID_outcor_s)[6] = "event_attendees"
names(BUYquarterID_outcor_s)[7] = "requested_trials"
names(BUYquarterID_outcor_s)[8] = "freemium_users"
names(BUYquarterID_outcor_s)[9] = "end_time"
names(BUYquarterID_outcorboth_s)[1] = "employees"
names(BUYquarterID_outcorboth_s)[2] = "avg_apps_built"
names(BUYquarterID_outcorboth_s)[3] = "cross_selling"
names(BUYquarterID_outcorboth_s)[4] = "avg_interactions_per_employee"
names(BUYquarterID_outcorboth_s)[5] = "digital_content_downloads"
names(BUYquarterID_outcorboth_s)[6] = "digital_content_downloads_lag"
names(BUYquarterID_outcorboth_s)[7] = "event_attendees"
names(BUYquarterID_outcorboth_s)[8] = "event_attendees_lag"
names(BUYquarterID_outcorboth_s)[9] = "requested_trials"
names(BUYquarterID_outcorboth_s)[10] = "requested_trials_lag"
names(BUYquarterID_outcorboth_s)[11] = "freemium_users"
names(BUYquarterID_outcorboth_s)[12] = "freemium_users_lag"
names(BUYquarterID_outcorboth_s)[13] = "end_time"
# Make plots
library(corrplot)
corrplot(cor(BUYquarterID_outcor_s), type = "lower", tl.col = "black", tl.srt = 5, tl.cex = 0.7, cl.cex = 0.7, number.cex = 0.7, addCoef.col = "black")
corrplot(cor(BUYquarterID_outcorboth_s), type = "lower", tl.col = "black", tl.srt = 5, tl.cex = 0.7, cl.cex = 0.7, number.cex = 0.5, addCoef.col = "black")
```
Cluster some industries
```{r}
BUYquarterID_out$Industry[BUYquarterID_out$ID == 16305375] <- "Financial Services"
BUYquarterID_out$Industry[BUYquarterID_out$ID == 2668081] <- "Government"
BUYquarterID_out$Industry[BUYquarterID_out$ID == 1444620] <- "Education"
```
Poisson regressions with average of 50 seeds (training)
```{r}
RMSEdf <- data.frame(model1=as.integer(),model2=as.integer(),model3=as.integer(),model4=as.integer(),model5=as.integer(),model6=as.integer(),model7=as.integer())
MAEdf <- data.frame(model1=as.integer(),model2=as.integer(),model3=as.integer(),model4=as.integer(),model5=as.integer(),model6=as.integer(),model7=as.integer())
PseudoR2df <- data.frame(model1=as.integer(),model2=as.integer(),model3=as.integer(),model4=as.integer(),model5=as.integer(),model6=as.integer(),model7=as.integer())
# Loop through the set.seed values
for (seed in 1:50) {
set.seed(seed)
# Your existing code
trainIndex<- BUYquarterID_out$new_rev %>%
createDataPartition(p = 0.75, list = FALSE)
training <- BUYquarterID_out[trainIndex,]
testing <- BUYquarterID_out[-trainIndex,]
models <- list(
M0 = vglm(new_rev ~ 1, family = pospoisson(), data = training, model = TRUE),
M1 = vglm(new_rev ~ segment + country + Industry, family = pospoisson(), data = training, model = TRUE),
M2 = vglm(new_rev ~ segment + country + Industry + Employees_s + apps_MAU_s, family = pospoisson(), data = training, model = TRUE),
M3 = vglm(new_rev ~ segment + country + Industry + Employees_s + apps_MAU_s + cross_selling_s, family = pospoisson(), data = training, model = TRUE),
M4 = vglm(new_rev ~ segment + country + Industry + Employees_s + apps_MAU_s + cross_selling_s + Avg.Interactions.per.Contact_s + digital_content_s + events_s + trails_s + freemium_s, family = pospoisson(), data = training, model = TRUE),
M5 = vglm(new_rev ~ segment + country + Industry + Employees_s + apps_MAU_s + cross_selling_s + Avg.Interactions.per.Contact_s + digital_content_s + events_s + trails_s + freemium_s + tstop_s, family = pospoisson(), data = training, model = TRUE),
M6 = vglm(new_rev ~ segment + country + Industry + Employees_s + apps_MAU_s + cross_selling_s + Avg.Interactions.per.Contact_s + digital_content_s + events_s + trails_s + freemium_s + Avg.Interactions.per.Contact_lag_s + digital_content_s_lag + events_s_lag + trails_s_lag + tstop_s, family = pospoisson(), data = training, model = TRUE)
)
# Initialize empty vectors to store the metrics for this seed
RMSE_seed <- c()
MAE_seed <- c()
PseudoR2_seed <- c()
# Loop through the models and calculate the metrics for this seed
for (model_name in names(models)) {
predictions <- predict(models[[model_name]], newdata = testing, type = "response")
RMSE_seed <- c(RMSE_seed, RMSE(predictions, testing$new_rev))
MAE_seed <- c(MAE_seed, MAE(predictions, testing$new_rev))
pseudo_r2 <- PseudoR2(models[[model_name]], "McFadden")
PseudoR2_seed <- c(PseudoR2_seed, pseudo_r2)
}
new_rowRMSE <- data.frame(model1 = RMSE_seed[1],
model2 = RMSE_seed[2],
model3 = RMSE_seed[3],
model4 = RMSE_seed[4],
model5 = RMSE_seed[5],
model6 = RMSE_seed[6],
model7 = RMSE_seed[7])
RMSEdf <- rbind(RMSEdf, new_rowRMSE)
new_rowMAE <- data.frame(model1 = MAE_seed[1],
model2 = MAE_seed[2],
model3 = MAE_seed[3],
model4 = MAE_seed[4],
model5 = MAE_seed[5],
model6 = MAE_seed[6],
model7 = MAE_seed[7])
MAEdf <- rbind(MAEdf, new_rowMAE)
new_rowPseudoR2 <- data.frame(model1 = PseudoR2_seed[1],
model2 = PseudoR2_seed[2],
model3 = PseudoR2_seed[3],
model4 = PseudoR2_seed[4],
model5 = PseudoR2_seed[5],
model6 = PseudoR2_seed[6],
model7 = PseudoR2_seed[7])
PseudoR2df <- rbind(PseudoR2df, new_rowPseudoR2)
}
# Create the dataframe
poissonfinal <- data.frame(Model = 1:7,
RMSE = c(mean(RMSEdf$model1), mean(RMSEdf$model2), mean(RMSEdf$model3),
mean(RMSEdf$model4), mean(RMSEdf$model5), mean(RMSEdf$model6),
mean(RMSEdf$model7)),
MAE = c(mean(MAEdf$model1), mean(MAEdf$model2), mean(MAEdf$model3),
mean(MAEdf$model4), mean(MAEdf$model5), mean(MAEdf$model6),
mean(MAEdf$model7)),
PseudoR2 = c(mean(PseudoR2df$model1), mean(PseudoR2df$model2), mean(PseudoR2df$model3),
mean(PseudoR2df$model4), mean(PseudoR2df$model5), mean(PseudoR2df$model6),
mean(PseudoR2df$model7)))
poissonfinal_xtab <- xtable(poissonfinal)
print(poissonfinal_xtab)
print(poissonfinal)
```
# T-test
```{r}
# Pairwise t-tests for RMSE
ttest_RMSE <- list()
pvalue_RMSE <- list()
for (i in 1:6) {
ttest_RMSE[[i]] <- t.test(RMSEdf[[paste0("model", i)]], RMSEdf[[paste0("model", i + 1)]])
pvalue_RMSE[[i]] <- ttest_RMSE[[i]]$p.value
}
# Pairwise t-tests for MAE
ttest_MAE <- list()
pvalue_MAE <- list()
for (i in 1:6) {
ttest_MAE[[i]] <- t.test(MAEdf[[paste0("model", i)]], MAEdf[[paste0("model", i + 1)]])
pvalue_MAE[[i]] <- ttest_MAE[[i]]$p.value
}
# Pairwise t-tests for R-squared
ttest_R2 <- list()
pvalue_R2 <- list()
for (i in 2:6) {
ttest_R2[[i]] <- t.test(PseudoR2df[[paste0("model", i)]], PseudoR2df[[paste0("model", i + 1)]])
pvalue_R2[[i]] <- ttest_R2[[i]]$p.value
}
t.test(AICdf[["model6"]], AICdf[["model7"]])$p.value
# Pairwise t-tests for AIC
ttest_AIC <- list()
pvalue_AIC <- list()
for (i in 1:6) {
ttest_AIC[[i]] <- t.test(AICdf[[paste0("model", i)]], AICdf[[paste0("model", i + 1)]])
pvalue_AIC[[i]] <- ttest_AIC[[i]]$p.value
}
# Pairwise t-tests for BIC
ttest_BIC <- list()
pvalue_BIC <- list()
for (i in 1:6) {
ttest_BIC[[i]] <- t.test(BICdf[[paste0("model", i)]], BICdf[[paste0("model", i + 1)]])
pvalue_BIC[[i]] <- ttest_BIC[[i]]$p.value
}
t.test(BICdf[[paste0("model", 3)]], BICdf[[paste0("model", 3 + 1)]])
# Create a dataframe with models as rows
model_names <- c("model1-model2", "model2-model3", "model3-model4", "model4-model5", "model5-model6", "model6-model7")
# Initialize an empty dataframe
comparison_df <- data.frame(Model = model_names, RMSE = NA, MAE = NA, PseudoR2 = NA) #, AIC = NA, BIC = NA
# Assign the metrics to the dataframe
comparison_df$RMSE[1:6] <- sapply(1:6, function(i) pvalue_RMSE[[i]])
comparison_df$MAE[1:6] <- sapply(1:6, function(i) pvalue_MAE[[i]])
comparison_df$PseudoR2[2:6] <- sapply(2:6, function(i) pvalue_R2[[i]])
#comparison_df$AIC[1:6] <- sapply(1:6, function(i) pvalue_AIC[[i]])
#comparison_df$BIC[1:6] <- sapply(1:6, function(i) pvalue_BIC[[i]])
# Print the resulting dataframe
comparison_df_xtab <- xtable(comparison_df)
print(comparison_df)
print(comparison_df_xtab)
```
# Change back
```{r}
BUYquarterID_out$Industry[BUYquarterID_out$ID == 16305375] <- "Software, Data & Platforms"
BUYquarterID_out$Industry[BUYquarterID_out$ID == 2668081] <- "Nonprofit & IGO"
BUYquarterID_out$Industry[BUYquarterID_out$ID == 1444620] <- "Nonprofit & IGO"
```
# Results best model
```{r}
M6 = vglm(new_rev ~ Industry + segment + country + Employees_s + apps_MAU_s + cross_selling_s + Avg.Interactions.per.Contact_s + digital_content_s + events_s + trails_s + freemium_s + Avg.Interactions.per.Contact_lag_s + digital_content_s_lag + events_s_lag + trails_s_lag + tstop_s, family = pospoisson(), data = BUYquarterID_out)
summary(M6)
```
# Check for unobserved heterogeneity
```{r}
residuals <- residuals(M6, type = "pearson")
dispersion <- sum(residuals^2) / df.residual(M6)
test_statistic <- sum(residuals^2) / dispersion
1 - pchisq(test_statistic, df = df.residual(M6))
```
##### CHECK WITH OUTLIERS #######
# Without outliers included
```{r}
BUYquarterID$new_rev <- floor((BUYquarterID$revenue/10000))
BUYquarterID$Employees_s <- scale(BUYquarterID$Employees)
BUYquarterID$cross_selling_s <- scale(BUYquarterID$cross_selling)
BUYquarterID$apps_MAU_s <- scale(BUYquarterID$apps_MAU)
BUYquarterID$Avg.Interactions.per.Contact_s <- scale(BUYquarterID$Avg.Interactions.per.Contact)
BUYquarterID$Avg.Interactions.per.Contact_lag_s <- scale(BUYquarterID$Avg.Interactions.per.Contact_lag)
BUYquarterID$tstop_s <- scale(BUYquarterID$tstop)
BUYquarterID$digital_content_s <- scale(BUYquarterID$digital_content)
BUYquarterID$events_s <- scale(BUYquarterID$events)
BUYquarterID$trails_s <- scale(BUYquarterID$trails)
BUYquarterID$freemium_s <- scale(BUYquarterID$freemium)
BUYquarterID$digital_content_s_lag <- scale(BUYquarterID$digital_content_lag)
BUYquarterID$events_s_lag <- scale(BUYquarterID$events_lag)
BUYquarterID$trails_s_lag <- scale(BUYquarterID$trails_lag)
BUYquarterID$freemium_s_lag <- scale(BUYquarterID$freemium_lag)
```
# Check for correlation
```{r}
# Make datasets for correlation plot
BUYquarterID_outcor_s <- BUYquarterID_out[,c(53:56,59:62,58)]
BUYquarterID_outcorboth_s <- BUYquarterID_out[,c(53:56,59,63,60,64,61,65,62,66,58)]
# Make plots
library(corrplot)
corrplot(cor(BUYquarterID_outcor_s), type = "lower", tl.col = "black", tl.srt = 35, tl.cex = 0.7, cl.cex = 0.7, number.cex = 0.7, addCoef.col = "black")
corrplot(cor(BUYquarterID_outcorboth_s), type = "lower", tl.col = "black", tl.srt = 35, tl.cex = 0.7, cl.cex = 0.7, number.cex = 0.5, addCoef.col = "black", title = "\n\n Correlation Plot Of Poisson Data")
```
Merge categories for industry
```{r}
# Find the rows with the specified IDs
rows_to_change <- BUYquarterID$ID %in% c(1877638, 16305375)
# Change the Industry values for the specified rows
BUYquarterID$Industry[rows_to_change] <- c("Government", "Financial Services")
```
Poisson regressions with average of 50 seeds
```{r}
AICdf <- data.frame(model1=as.integer(),model2=as.integer(),model3=as.integer(),model4=as.integer(),model5=as.integer(),model6=as.integer(),model7=as.integer())
BICdf <- data.frame(model1=as.integer(),model2=as.integer(),model3=as.integer(),model4=as.integer(),model5=as.integer(),model6=as.integer(),model7=as.integer())
RMSEdf <- data.frame(model1=as.integer(),model2=as.integer(),model3=as.integer(),model4=as.integer(),model5=as.integer(),model6=as.integer(),model7=as.integer())
MAEdf <- data.frame(model1=as.integer(),model2=as.integer(),model3=as.integer(),model4=as.integer(),model5=as.integer(),model6=as.integer(),model7=as.integer())
PseudoR2df <- data.frame(model1=as.integer(),model2=as.integer(),model3=as.integer(),model4=as.integer(),model5=as.integer(),model6=as.integer(),model7=as.integer())
R2df <- data.frame(model1=as.integer(),model2=as.integer(),model3=as.integer(),model4=as.integer(),model5=as.integer(),model6=as.integer(),model7=as.integer())
# Loop through the set.seed values
for (seed in 1:50) {
set.seed(seed)
# Your existing code
trainIndex<- BUYquarterID$new_rev %>%
createDataPartition(p = 0.75, list = FALSE)
training <- BUYquarterID[trainIndex,]
testing <- BUYquarterID[-trainIndex,]
models <- list(
M0 = vglm(new_rev ~ 1, family = pospoisson(), data = training, model = TRUE),
M1 = vglm(new_rev ~ segment + country + Industry, family = pospoisson(), data = training, model = TRUE),
M2 = vglm(new_rev ~ segment + country + Industry + Employees_s + apps_MAU_s, family = pospoisson(), data = training, model = TRUE),
M3 = vglm(new_rev ~ segment + country + Industry + Employees_s + apps_MAU_s + cross_selling_s, family = pospoisson(), data = training, model = TRUE),
M4 = vglm(new_rev ~ segment + country + Industry + Employees_s + apps_MAU_s + cross_selling_s + Avg.Interactions.per.Contact_s + digital_content_s + events_s + trails_s + freemium_s, family = pospoisson(), data = training, model = TRUE),
M5 = vglm(new_rev ~ segment + country + Industry + Employees_s + apps_MAU_s + cross_selling_s + Avg.Interactions.per.Contact_s + digital_content_s + events_s + trails_s + freemium_s + tstop_s, family = pospoisson(), data = training, model = TRUE),
M6 = vglm(new_rev ~ segment + country + Industry + Employees_s + apps_MAU_s + cross_selling_s + Avg.Interactions.per.Contact_s + digital_content_s + events_s + trails_s + freemium_s + Avg.Interactions.per.Contact_lag_s + digital_content_s_lag + events_s_lag + trails_s_lag + tstop_s, family = pospoisson(), data = training, model = TRUE)
)
# Initialize empty vectors to store the metrics for this seed
RMSE_seed <- c()
MAE_seed <- c()
PseudoR2_seed <- c()
# Loop through the models and calculate the metrics for this seed
for (model_name in names(models)) {
predictions <- predict(models[[model_name]], newdata = testing, type = "response")
RMSE_seed <- c(RMSE_seed, RMSE(predictions, testing$new_rev))
MAE_seed <- c(MAE_seed, MAE(predictions, testing$new_rev))
pseudo_r2 <- PseudoR2(models[[model_name]], "McFadden")
PseudoR2_seed <- c(PseudoR2_seed, pseudo_r2)
}
new_rowRMSE <- data.frame(model1 = RMSE_seed[1],
model2 = RMSE_seed[2],
model3 = RMSE_seed[3],
model4 = RMSE_seed[4],
model5 = RMSE_seed[5],
model6 = RMSE_seed[6],
model7 = RMSE_seed[7])
RMSEdf <- rbind(RMSEdf, new_rowRMSE)
new_rowMAE <- data.frame(model1 = MAE_seed[1],
model2 = MAE_seed[2],
model3 = MAE_seed[3],
model4 = MAE_seed[4],
model5 = MAE_seed[5],
model6 = MAE_seed[6],
model7 = MAE_seed[7])
MAEdf <- rbind(MAEdf, new_rowMAE)
new_rowPseudoR2 <- data.frame(model1 = PseudoR2_seed[1],
model2 = PseudoR2_seed[2],
model3 = PseudoR2_seed[3],
model4 = PseudoR2_seed[4],
model5 = PseudoR2_seed[5],
model6 = PseudoR2_seed[6],
model7 = PseudoR2_seed[7])
PseudoR2df <- rbind(PseudoR2df, new_rowPseudoR2)
}
# Create the dataframe
poissonfinal <- data.frame(Model = 1:7,
RMSE = c(mean(RMSEdf$model1), mean(RMSEdf$model2), mean(RMSEdf$model3),
mean(RMSEdf$model4), mean(RMSEdf$model5), mean(RMSEdf$model6),
mean(RMSEdf$model7)),
MAE = c(mean(MAEdf$model1), mean(MAEdf$model2), mean(MAEdf$model3),
mean(MAEdf$model4), mean(MAEdf$model5), mean(MAEdf$model6),
mean(MAEdf$model7)),
PseudoR2 = c(mean(PseudoR2df$model1), mean(PseudoR2df$model2), mean(PseudoR2df$model3),
mean(PseudoR2df$model4), mean(PseudoR2df$model5), mean(PseudoR2df$model6),
mean(PseudoR2df$model7)))
poissonfinal_xtab <- xtable(poissonfinal)
print(poissonfinal_xtab)
print(poissonfinal)
```
# Results best model (model 6)
```{r}
M6 = vglm(new_rev ~ Industry + segment + country + Employees_s + apps_MAU_s + cross_selling_s + Avg.Interactions.per.Contact_s + digital_content_s + events_s + trails_s + freemium_s + Avg.Interactions.per.Contact_lag_s + digital_content_s_lag + events_s_lag + trails_s_lag + tstop_s, family = pospoisson(), data = BUYquarterID)
summary(M6)
```
# Check for unobserved heterogeneity
```{r}
residuals <- residuals(M6, type = "pearson")
dispersion <- sum(residuals^2) / df.residual(M6)
test_statistic <- sum(residuals^2) / dispersion
1 - pchisq(test_statistic, df = df.residual(M6))
```
|
//! # Linux OS utilities
//! A toolbox of small utilities for Linux environments.
//! Useful for fast binary development via the provided signal handling and panic hooks.
use futures::stream::StreamExt;
use log::{error, info};
use signal_hook::consts::signal::*;
use signal_hook_tokio::Signals;
use std::panic;
use tokio::task::JoinHandle;
pub fn signal_init() -> (signal_hook::iterator::Handle, JoinHandle<()>) {
// Termination Signals Initilization
let signals = Signals::new([SIGHUP, SIGTERM, SIGINT, SIGQUIT]).unwrap();
let signals_handle = signals.handle();
let signals_task = tokio::spawn(handle_signals(signals));
(signals_handle, signals_task)
}
#[cfg(target_family = "unix")]
pub async fn signal_wait(
signals_handle: signal_hook::iterator::Handle,
signals_task: JoinHandle<()>,
) {
signals_handle.close();
signals_task.await.unwrap();
}
/// Helper Function: Panic Handler
pub fn panic_handler_init() {
panic::set_hook(Box::new(|panic_info| {
match panic_info.payload().downcast_ref::<String>() {
Some(as_string) => {
error!("PANIC occurred: {}", as_string);
}
None => {
error!("PANIC occurred: {:?}", panic_info);
}
}
if let Some(location) = panic_info.location() {
error!(
"PANIC occurred in file '{}' at line {}",
location.file(),
location.line()
);
} else {
error!("PANIC occurred but can't get location information...");
}
std::process::abort();
}));
info!("SP Scanner [Panic Handler] REGISTERED!");
}
/// Helper Function: Handle of System Termination Signals
#[cfg(target_family = "unix")]
async fn handle_signals(signals: Signals) {
use log::warn;
let mut signals = signals.fuse();
while let Some(signal) = signals.next().await {
match signal {
SIGHUP | SIGTERM | SIGINT | SIGQUIT => {
warn!(
"SP Scanner [Termination signals] [{:?}] RECEIVED! Terminating Tasks & Exiting...",
signal
);
signal_hook::low_level::exit(1);
}
_ => unreachable!(),
}
}
}
|
import React, { useState,useRef } from "react";
import axios from "axios";
export default function EncryptionBox() {
const [selectedAlgorithm, setSelectedAlgorithm] = useState("rsa");
const [numFields, setNumFields] = useState(2);
const [publicKey,setPublicKey] = useState("");
const [primeNumbers, setPrimeNumbers] = useState(Array.from({ length: 6 }, () => "")); // Initialize an array of length 6 with empty strings
const [text, setText] = useState("");
const [isCopied, setIsCopied] = useState(false);
const [isCopied2, setIsCopied2] = useState(false);
const [privateKey, setPrivateKey] = useState("")
const [cipherText, setCipherText] = useState("")
const [modulus, setModulus] = useState("")
const keyInputRef = useRef(null);
const keyInputRef2 = useRef(null);
const [result,setResult] = useState(false);
const handleCopyClick = () => {
const key = keyInputRef.current.value;
navigator.clipboard.writeText(key);
setIsCopied(true);
setTimeout(() => setIsCopied(false), 2000); // Reset tooltip after 2 seconds
};
const handleCopyClick2 = () => {
const key = keyInputRef2.current.value;
navigator.clipboard.writeText(key);
setIsCopied2(true);
setTimeout(() => setIsCopied2(false), 2000); // Reset tooltip after 2 seconds
};
const handleAlgorithmChange = (e) => {
setSelectedAlgorithm(e.target.value);
switch (e.target.value) {
case "rsa":
setNumFields(2);
break;
case "rsa-3":
setNumFields(3);
break;
case "rsa-4":
setNumFields(4);
break;
case "rsa-5":
setNumFields(5);
break;
case "rsa-6":
setNumFields(6);
break;
default:
setNumFields(2);
break;
}
};
const handleTextChange = (e) => {
setText(e.target.value);
console.log(text);
};
const handlePublicKeyChange = (e) => {
setPublicKey(e.target.value);
console.log(publicKey);
}
const handleInputChange = (index, value) => {
const newPrimeNumbers = [...primeNumbers];
newPrimeNumbers[index] = value;
setPrimeNumbers(newPrimeNumbers);
console.log(primeNumbers);
};
const handleSubmit = async(e) => {
e.preventDefault();
if (selectedAlgorithm === "rsa") {
//use axios to send the data to the backend and send plain text, first prime number, second prime number in the body
try {
const response = await axios.post('http://localhost:5000/RSA/encrypt', {
"plainText":text.toString(),
"publicKey": publicKey,
"p": primeNumbers[0].toString(),
"q": primeNumbers[1].toString(),
});
setResult(true)
setPrivateKey(response.data.privateKey)
setCipherText(response.data.cipherText)
setModulus(response.data.modulus)
} catch (error) {
console.error('Error:', error);
}
} else if (selectedAlgorithm === "rsa-3") {
try {
const response = await axios.post('http://localhost:5000/RSA3/encrypt', {
"plainText":text.toString(),
"publicKey": publicKey,
"p": primeNumbers[0].toString(),
"q": primeNumbers[1].toString(),
"r": primeNumbers[2].toString(),
});
setResult(true)
setPrivateKey(response.data.privateKey)
setCipherText(response.data.cipherText)
setModulus(response.data.modulus)
} catch (error) {
console.error('Error:', error);
}
} else if (selectedAlgorithm === "rsa-4") {
try {
const response = await axios.post('http://localhost:5000/RSA4/encrypt', {
"plainText":text.toString(),
"publicKey": publicKey,
"p": primeNumbers[0].toString(),
"q": primeNumbers[1].toString(),
"r": primeNumbers[2].toString(),
"s": primeNumbers[3].toString(),
});
setResult(true)
setPrivateKey(response.data.privateKey)
setCipherText(response.data.cipherText)
setModulus(response.data.modulus)
} catch (error) {
console.error('Error:', error);
}
} else if (selectedAlgorithm === "rsa-5") {
try {
const response = await axios.post('http://localhost:5000/RSA3/encrypt', {
"plainText":text.toString(),
"publicKey": publicKey,
"p": primeNumbers[0].toString(),
"q": primeNumbers[1].toString(),
"r": primeNumbers[2].toString(),
});
setResult(true)
setPrivateKey(response.data.privateKey)
setCipherText(response.data.cipherText)
setModulus(response.data.modulus)
} catch (error) {
console.error('Error:', error);
}
} else if (selectedAlgorithm === "rsa-6") {
try {
const response = await axios.post('http://localhost:5000/RSA/encrypt', {
"plainText":text.toString(),
"publicKey": publicKey,
"p": primeNumbers[0].toString(),
"q": primeNumbers[1].toString(),
});
setResult(true)
setPrivateKey(response.data.privateKey)
setCipherText(response.data.cipherText)
setModulus(response.data.modulus)
} catch (error) {
console.error('Error:', error);
}
}
};
const renderInputFields = () => {
const fields = [];
for (let i = 0; i < numFields; i++) {
fields.push(
<input
key={i}
type="text"
className="w-[550px] h-10 bg-[#2A2A2A] text-white p-4 rounded-xl focus:outline-none my-2"
placeholder={`Prime no.${i + 1}`}
value={primeNumbers[i]}
onChange={(e) => handleInputChange(i, e.target.value)}
/>
);
}
return fields;
};
return (
<div className="flex justify-center">
<div className="bg-[#1A1A1A] w-[80rem] h-[45rem] px-4 rounded-lg my-10">
<h1 className="text-white text-[2rem] font-bold text-center mt-6">Encryption</h1>
<div className="flex justify-between mx-12">
<div className="flex flex-col w-[30rem] h-[30rem] my-10">
<textarea
className="w-[30rem] h-[14.5rem] bg-[#2A2A2A] text-white p-4 rounded-xl focus:outline-none"
placeholder="Enter your text here..."
onChange={(e) =>{handleTextChange(e)}}
></textarea>
<div className="flex justify-end">
<select
id="algo"
className="bg-[#717171] mt-2 h-[2.25rem] border w-[8rem] mr-4 border-gray-300 text-white font-medium text-[12px] rounded focus:ring-[#717171] focus:border-[#717171] block p-2.5 focus:outline-none"
value={selectedAlgorithm}
onChange={handleAlgorithmChange}
>
<option value="rsa">RSA</option>
<option value="rsa-3">RSA-3</option>
<option value="rsa-4">RSA-4</option>
<option value="rsa-5">RSA-5</option>
<option value="rsa-6">RSA-6</option>
</select>
<button className="bg-[#717171] px-4 text-white text-[12px] font-medium my-2 rounded-md h-[2.25rem] w-[6rem] ">
Encrypt
</button>
</div>
{result && <>
<div className="">
<h1 className="text-white text-xl font-bold text-left mt-6">Cipher Text</h1>
<textarea
value={cipherText}
className="w-[30rem] h-[4.5rem] bg-[#2A2A2A] text-white p-4 rounded-xl focus:outline-none mt-4"
placeholder="Encrypted text will appear here..."
></textarea>
<div className="flex items-center w-full">
<h1 className="text-white text-lg font-semibold text-left mr-7 w-full pb-3 mt-6">Private Key</h1>
<input
ref={keyInputRef}
type="text"
className="input input-bordered w-full bg-[#2A2A2A] mt-4 pl-2 text-white py-2 rounded "
value={privateKey}
placeholder="Private Key"
disabled
/>
<button
onClick={handleCopyClick}
className="btn btn-square ml-2 mt-3 font-semibold py-4 px-2 "
>
Copy
</button>
{isCopied && (
<span className="tooltip absolute right-[50rem] font-semibold text-sm ">Text copied</span>
)}
</div>
<div className="flex items-center w-full ">
<h1 className="text-white text-lg font-semibold text-left mr-[9.2rem] pb-3 mt-6">Modulus</h1>
<input
ref={keyInputRef2}
type="text"
className="input input-bordered bg-[#2A2A2A] w-full mt-4 pl-2 text-white py-2 rounded "
placeholder="Modulus"
value={modulus}
disabled
/>
<button
onClick={handleCopyClick2}
className="btn btn-square ml-2 mt-3 font-semibold py-4 px-2 "
>
Copy
</button>
{isCopied2 && (
<span className="tooltip absolute right-[50rem] font-semibold text-sm ">Text copied</span>
)}
</div>
</div>
</>}
</div>
<div className="mt-24 flex flex-col">
<form id="form" className="flex flex-col" onSubmit={handleSubmit}>
{renderInputFields()}
<input
onChange={(e)=>{handlePublicKeyChange(e)}}
type="text"
className="w-full h-10 bg-[#2A2A2A] text-white p-4 rounded-xl focus:outline-none my-2"
placeholder="Enter your public key"
/>
<button onClick={handleSubmit} type="submit" className="bg-[#717171] px-4 text-white text-[12px] font-medium my-2 rounded-md h-[2.25rem] w-[6rem] ">
Submit
</button>
</form>
</div>
<div>{/* Additional content */}</div>
</div>
</div>
</div>
);
}
|
import 'package:FinGlow/presentation/views/Seminarsandevents.dart';
import 'package:FinGlow/presentation/widgets/AccountingandBillingButtonWidget.dart';
import 'package:FinGlow/presentation/widgets/FinancialAdvisorButtonWidget.dart';
import 'package:FinGlow/presentation/widgets/NotificationsButtonWidget.dart';
import 'package:FinGlow/presentation/widgets/PaymentscheduleButtonWidget.dart';
import 'package:FinGlow/presentation/widgets/ProfileButtonWidget.dart';
import 'package:FinGlow/presentation/widgets/SeminarsandeventsButtonWidget.dart';
import 'package:FinGlow/presentation/widgets/ServicesButtonWidget.dart';
import 'package:flutter/material.dart';
class MoreFeaturesView extends StatefulWidget {
const MoreFeaturesView({super.key});
@override
State<MoreFeaturesView> createState() => _MoreFeaturesViewState();
}
class _MoreFeaturesViewState extends State<MoreFeaturesView> {
void _handleProfileTap() {
// ignore: avoid_print
print('Profile tapped!');
}
void _handleNotificationsTap() {
// ignore: avoid_print
print('Notifications tapped!');
}
void _handleFinancialAdvisorTap() {
// ignore: avoid_print
print('Financial Advisor tapped!');
}
void _handleServicesTap() {
// ignore: avoid_print
print('Services tapped!');
}
void _handleSeminarsandeventsTap() {
// ignore: avoid_print
Navigator.push(context, MaterialPageRoute(builder: (context) => const SeminarsandeventsView()));
}
void _handlePaymentscheduleTap() {
// ignore: avoid_print
print('Payment schedule tapped!');
}
void _handleAccountingandBillingTap() {
// ignore: avoid_print
print('Accounting and Billing tapped!');
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: DecoratedBox(
decoration: const BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [
Color.fromRGBO(1, 19, 48, 1),
Color.fromRGBO(4, 38, 92, 1),
],
stops: [0.3, 0.7],
),
),
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
children: [
// Other widgets...
ProfileButtonWidget(onTap: _handleProfileTap),
NotificationsButtonWidget(onTap: _handleNotificationsTap),
FinancialAdvisorButtonWidget(onTap: _handleFinancialAdvisorTap),
ServicesButtonWidget(onTap: _handleServicesTap),
SeminarsandeventsButtonWidget(onTap: _handleSeminarsandeventsTap),
PaymentscheduleButtonWidget(onTap: _handlePaymentscheduleTap),
AccountingandBillingButtonWidget(onTap: _handleAccountingandBillingTap),
// More widgets...
],
),
),
),
);
}
}
|
import React from "react";
import styled, { ThemeProvider } from "styled-components";
import {
Box,
Button,
Typography,
Container,
Stack,
Divider,
Grid,
ButtonGroup,
} from "@mui/material";
import { motion } from "framer-motion";
import theme from "../website-constants/Theme";
import Image from "mui-image";
const TitleText = styled(Typography)`
&& {
display: flex;
justify-content: left;
align-items: left;
font-weight: 700;
margin-bottom: 2rem;
text-align: left;
color: white;
}
`;
const SubGrid = styled(Grid)`
&& {
display: flex;
justify-content: center;
align-items: center;
${"" /* width: 100%; */}
}
`;
const DescriptionText = styled(Typography)`
&& {
display: flex;
justify-content: left;
align-items: left;
${"" /* font-size: 20px; */}
padding-bottom: 1rem;
text-align: left;
line-height: 175%;
color: white;
}
`;
const SplitBoxesGrid = styled(Grid)`
&& {
display: flex;
justify-content: center;
align-items: center;
font-size: 25px;
height: 100%;
gap: 3vw;
padding: 2vw;
}
`;
const VertStack = styled(Stack)`
&& {
display: flex;
justify-content: left;
align-items: left;
}
`;
export default function TextCard({ displayInfo }) {
const titleVariants = {
hidden: { opacity: 0, x: -50 },
visible: { opacity: 1, x: 0, transition: { duration: 1 } }, // Adjust the delay as needed
};
const subtitleVariants = {
hidden: { opacity: 0, x: -50 },
visible: { opacity: 1, x: 0, transition: { duration: 1, delay: 0.5 } }, // Adjust the delay as needed
};
return (
<>
<ThemeProvider theme={theme} key="text-1" border="none">
<SplitBoxesGrid container key="text-2">
<SubGrid item xs={12} md={12} key="text-3">
<VertStack key="text-4">
<TitleText
key="text-5"
variant="h3"
component={motion.div}
initial="hidden"
animate="visible"
variants={titleVariants}
>
{displayInfo.title}
</TitleText>
<DescriptionText
key="text-6"
variant="h6"
component={motion.div}
initial="hidden"
animate="visible"
variants={subtitleVariants}
>
{displayInfo.text}
</DescriptionText>
</VertStack>
</SubGrid>
</SplitBoxesGrid>
</ThemeProvider>
</>
);
}
|
"""
Created on Mon Nov 20 21:18:48 2023
@author: chiu
"""
from docx import Document
from docx.oxml.shared import OxmlElement, qn
def set_cell_edges(cell, edges, color, style, width):
"""
Parameter Type Definition
cell Cell Cell to apply edges
edges str, list, None Cell edges, options are 'top', 'bottom', 'start' and 'end'
color str Edge color
style str Edge style, options are 'single', 'dotted', 'dashed', 'dashdotted' and 'double',
width int, float Edge width in points
"""
kwargs = dict()
for edge in edges:
kwargs[edge] = {'sz': width, 'val': style, 'color': color}
tc = cell._tc
tcPr = tc.get_or_add_tcPr()
# check for tag existence, if none found then create one
tcBorders = tcPr.first_child_found_in("w:tcBorders")
if tcBorders is None:
tcBorders = OxmlElement('w:tcBorders')
tcPr.append(tcBorders)
# list over all available tags
for edge in ('start', 'top', 'end', 'bottom', 'insideH', 'insideV'):
edge_data = kwargs.get(edge)
if edge_data:
tag = 'w:{}'.format(edge)
# check for tag existence, if none found, then create one
element = tcBorders.find(qn(tag))
if element is None:
element = OxmlElement(tag)
tcBorders.append(element)
# looks like the order of attributes is important
for key in ["sz", "val", "color", "space", "shadow"]:
if key in edge_data:
element.set(qn('w:{}'.format(key)), str(edge_data[key]))
def csv_to_docx(df):
document = Document()
table = document.add_table(rows = df.shape[0] + 1, cols = df.shape[1])
for i in range(df.shape[0] + 1):
for j in range(df.shape[1]):
if i == 0:
table.rows[i].cells[j].text = list(df.columns)[j]
set_cell_edges(table.rows[i].cells[j], ['top', 'bottom'], '#000000', 'single', 12)
elif i == df.shape[0]:
table.rows[i].cells[j].text = df.iloc[i-1, j]
set_cell_edges(table.rows[i].cells[j], ['bottom'], '#000000', 'single', 12)
else:
table.rows[i].cells[j].text = df.iloc[i-1, j]
# document.save("data/wordresult1.docx")
return document
|
import React, { Component } from 'react';
import { Modal, Button, Row, Col, Form } from 'react-bootstrap';
export class EditCategoryModal extends Component {
constructor(props) {
super(props);
this.state = {
validationName: "",
};
this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit(event) {
event.preventDefault();
fetch('https://localhost:7187/api/category/' + event.target.id.value, {
method: 'PUT',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
id: event.target.id.value,
name: event.target.name.value
})
})
.then(res => res.json())
.then((result) => {
this.validation(result.errors)
},
(error) => {
alert('Failed')
}
)
}
validation = (e) => {
this.setState({
validationName: e.Name !== undefined ? e.Name[0] : "",
})
}
render() {
const { validationName} = this.state;
return (
<Modal
{...this.props}
size="lg"
aria-labelledby="contained-modal-title-vcenter"
centered
>
<Modal.Header closeButton>
<Modal.Title id="contained-modal-title-vcenter">
Edit Category
</Modal.Title>
</Modal.Header>
<Modal.Body>
<div className="container">
<Row>
<Col sm={6}>
<Form onSubmit={this.handleSubmit}>
<Form.Group controlId="id">
<Form.Label>id</Form.Label>
<Form.Control
type="text"
name="id"
disabled
defaultValue={this.props.id}
placeholder="id"
/>
</Form.Group>
<Form.Group controlId="name">
<Form.Label>name</Form.Label>
<Form.Control
type="text"
name="name"
defaultValue={this.props.name}
placeholder="name"
/>
<p class="text-danger">{validationName}</p>
</Form.Group>
<Form.Group>
<Button variant="primary" type="submit">
Update Category
</Button>
</Form.Group>
</Form>
</Col>
</Row>
</div>
</Modal.Body>
<Modal.Footer>
<Button variant="danger" onClick={this.props.onHide}>Close</Button>
</Modal.Footer>
</Modal>
);
}
}
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script></head>
<body>
<div id="app-7">
<ol>
<!--
现在我们为每个 todo-item 提供 todo 对象
todo 对象是变量,即其内容可以是动态的。
我们也需要为每个组件提供一个“key”,稍后再
作详细解释。
-->
<todo-item
v-for="item in groceryList"
v-bind:todo="item"
v-bind:key="item.id">
</todo-item>
</ol>
</div>
<div id='example-3'>
<input type="radio" id="jack" value="Jack" v-model="checkedNames">
<label for="jack">Jack</label>
<input type="radio" id="john" value="John" v-model="checkedNames">
<label for="john">John</label>
<input type="radio" id="mike" value="Mike" v-model="checkedNames">
<label for="mike">Mike</label>
<br>
<span>Checked names: {{ checkedNames }}</span>
</div>
<div id="example-4">
<input type="text" class="inputField" v-model="message" placeholder="edit me">
<p>Message is: {{ message }}</p>
</div>
<div id="blog-post-demo">
<div :style="{ fontSize: postFontSize + 'em' }">
<blog-post
v-for="post in posts"
v-bind:key="post.id"
v-bind:post="post"
v-on:enlarge="postFontSize += 0.1"
>
</blog-post>
</div>
</div>
<alert-box>
Something bad happened.
</alert-box>
<br>
<input type="text" class="inputField" placeholder="edit me">
<div id='example-6'>
<select v-model="selected" multiple style="width: 50px">
<option>A</option>
<option>B</option>
<option>C</option>
</select>
<br>
<span>Selected: {{ selected }}</span>
</div>
<script src="JS/test.js"></script>
<script src="https://cdn.jsdelivr.net/npm/axios@0.12.0/dist/axios.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/lodash@4.13.1/lodash.min.js"></script>
</body>
</html>
|
import { Component, OnDestroy, OnInit } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { ActivatedRoute, Params, Router } from '@angular/router';
import { Subscription, switchMap } from 'rxjs';
import { Post } from 'src/app/shared/interfaces';
import { PostsService } from '../../services/posts.service';
import { AlertService } from '../shared/services/alert.service';
@Component({
selector: 'app-edit-page',
templateUrl: './edit-page.component.html'
})
export class EditPageComponent implements OnInit, OnDestroy {
public formEditPost: FormGroup;
public submitted: boolean = false;
private editingPost!: Post;
private updateSubscription: Subscription;
private postId: string;
constructor(
private route: ActivatedRoute,
private postsService: PostsService,
private alert: AlertService,
private router: Router
) { }
public ngOnInit(): void {
this.route.params.pipe(
switchMap((params: Params) => {
return this.postsService.getUserPostById(params['id']);
})
).subscribe((post: Post) => {
this.editingPost = post;
this.formEditPost = new FormGroup({
title: new FormControl(post.title, Validators.required),
textContent: new FormControl(post.textContent, Validators.required)
});
});
}
public submitEditPost(): void {
if (this.formEditPost.invalid) {
return;
}
this.submitted = true;
this.route.params.subscribe((params: Params) => this.postId = params['id']);
this.updateSubscription = this.postsService.updatePost(this.postId, {
...this.editingPost,
textContent: this.formEditPost?.value.textContent,
title: this.formEditPost?.value.title
}).subscribe(() => {
this.alert.success('Post was updated.');
});
this.submitted = false;
this.router.navigate(['/admin', 'dashboard']);
}
public ngOnDestroy(): void {
this.updateSubscription?.unsubscribe();
}
}
|
import { useState, useContext } from "react";
import axios from "axios";
import { toast } from "react-toastify";
import { auth } from "../../config/firebaseConfig";
import { signInWithEmailAndPassword } from "firebase/auth";
import { useNavigate, Link } from "react-router-dom";
import { UserContext } from "../../utils/UserContext";
import "./LoginRegister.css";
axios.defaults.withCredentials = true;
const Login = () => {
const navigate = useNavigate();
const { setCurrentUser } = useContext(UserContext);
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const loginUser = (ev) => {
ev.preventDefault();
signInWithEmailAndPassword(auth, email, password)
.then((userCredential) => {
// Signed in
const user = userCredential.user;
setCurrentUser(user);
navigate("/");
user
.getIdToken(true)
.then((idToken) => {
axios.post(
"/api/sessionLogin",
{},
{
headers: {
Authorization: `Bearer ${idToken}`,
},
}
);
})
.catch(function (error) {
console.log(error);
});
})
.catch((error) => {
const errorCode = error.code;
console.log(errorCode);
switch (errorCode) {
case "auth/user-not-found":
toast.error("User does not exist!");
break;
case "auth/invalid-login-credentials":
toast.error("Incorrect Password!");
break;
case "auth/too-many-requests":
toast.error(
"Too many frequent login attempts. Try gain in a few seconds."
);
break;
}
});
};
return (
<main className="login-main">
<div className="register-card">
<h1>Login</h1>
<form action="" className="login-form">
<input
type="email"
placeholder="BC Email"
onChange={(ev) => setEmail(ev.target.value)}
autoComplete="username"
/>
<input
type="password"
placeholder="Password"
onChange={(ev) => setPassword(ev.target.value)}
autoComplete="current-password"
/>
<button type="submit" onClick={loginUser}>
Log In
</button>
</form>
<Link to="/reset-password">Forgot your password?</Link>
<p>
{"Don't have an account?"} <a href="/register">Sign Up Here</a>
</p>
</div>
</main>
);
};
export default Login;
|
package com.amigoscode.testing.customer;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import java.util.Optional;
import java.util.UUID;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.then;
import static org.mockito.Mockito.never;
class CustomerRegistrationServiceTest {
@Mock
private CustomerRepository customerRepository;
@Captor
private ArgumentCaptor<Customer> customerArgumentCaptor;
private CustomerRegistrationService underTest;
@BeforeEach
void setUp() {
MockitoAnnotations.initMocks(this);
underTest = new CustomerRegistrationService(customerRepository);
}
@Test
void itShouldSaveNewCustomer() {
// Given
String phoneNumber = "000099";
Customer customer = new Customer(UUID.randomUUID(), "Maryam", phoneNumber);
// a request
CustomerRegistrationRequest request = new CustomerRegistrationRequest(customer);
// no customer has this phone number -- scenario to skip the if condition
given(customerRepository.selectCustomerByPhoneNumber(phoneNumber)).willReturn(Optional.empty());
// When
underTest.registerNewCustomer(request);
// Then
then(customerRepository).should().save(customerArgumentCaptor.capture());
Customer customerArgumentCaptorValue = customerArgumentCaptor.getValue();
assertThat(customerArgumentCaptorValue).isEqualToComparingFieldByField(customer);
}
@Test
void itShouldSaveNewCustomerWhenIdIsNull() {
// Given
String phoneNumber = "000099";
Customer customer = new Customer(null, "Maryam", phoneNumber);
// a request
CustomerRegistrationRequest request = new CustomerRegistrationRequest(customer);
// no customer has this phone number -- scenario to skip the if condition
given(customerRepository.selectCustomerByPhoneNumber(phoneNumber)).willReturn(Optional.empty());
// When
underTest.registerNewCustomer(request);
// Then
then(customerRepository).should().save(customerArgumentCaptor.capture());
Customer customerArgumentCaptorValue = customerArgumentCaptor.getValue();
assertThat(customerArgumentCaptorValue).isEqualToIgnoringGivenFields(customer, "id");
assertThat(customerArgumentCaptorValue.getId()).isNotNull();
}
@Test
void itShouldNotSaveCustomerWhenCustomerExists() {
// Given
String phoneNumber = "000099";
UUID id = UUID.randomUUID();
Customer customer = new Customer(id, "Maryam", phoneNumber);
// a request
CustomerRegistrationRequest request = new CustomerRegistrationRequest(customer);
// some customer has this phone number -- scenario to go inside if statement
given(customerRepository.selectCustomerByPhoneNumber(phoneNumber)).willReturn(Optional.of(customer));
// When
underTest.registerNewCustomer(request);
// Then
then(customerRepository).should(never()).save(any());
then(customerRepository).should().selectCustomerByPhoneNumber(phoneNumber);
then(customerRepository).shouldHaveNoMoreInteractions();
}
@Test
void itShouldThrowWhenPhoneNumberIsTaken() {
// Given
String phoneNumber = "000099";
Customer customer = new Customer(UUID.randomUUID(), "Maryam", phoneNumber);
Customer customer2 = new Customer(UUID.randomUUID(), "John", phoneNumber);
// a request
CustomerRegistrationRequest request = new CustomerRegistrationRequest(customer);
// some customer has this phone number -- scenario to go inside if statement
given(customerRepository.selectCustomerByPhoneNumber(phoneNumber))
.willReturn(Optional.of(customer2));
// When + Then
assertThatThrownBy(() -> underTest.registerNewCustomer(request))
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining(String.format("phone number [%s] is taken", phoneNumber));
// Finally
then(customerRepository).should(never()).save(any(Customer.class));
}
}
|
# 做一个完整的开发者应该了解多少 HTML 和 CSS?
> 原文:<https://medium.com/hackernoon/how-much-html-and-css-should-you-know-to-develop-4456e2ca8595>
在学习 web 开发和编程之前,每当我看到制作精美的网站时,我总是心存敬畏。
我喜欢阅读文章,网络是我获取当代信息的主要来源。
因此,我接触到了大量令人敬畏的页面,它们不仅看起来很棒,而且为浏览者提供了合理的功能。它激起了我的一个愿望,希望有一天能够以一种让任何人都惊叹的方式向世界展示信息。

Image by [Caleb Dow](https://unsplash.com/@calebscamera?utm_medium=referral&utm_campaign=photographer-credit&utm_content=creditBadge) on Unsplash
作为一名内容创作者,我开始使用 Blogger,写关于金融教育和创业的文章。
在那个时代,Blogger 在定制网站外观方面没有太多的余地。我开始修改并找到了一些教程,教我如何调整博客主题的 CSS 文件。
这时我意识到我需要学习 HTML 和 CSS。
直到我最终接受了这样一个事实,即编辑几行 CSS 代码永远不能让我完全控制我正在制作的网站的外观和功能,我才开始学习。
现在,五年多过去了,我已经知道如何从头开始创建一个网站,甚至把基本的功能放进去。
见鬼,我现在甚至可以编写一个基本博客应用程序的前端和后端代码,甚至可以用 ReactJS 构建一个 T2 电视剧应用程序。
不管我现在的技能有多高级,我都不能否认学习 HTML 和 CSS 是我的基础这个事实。
我理解人们渴望从一门真正的编程语言开始,比如 Ruby、JavaScript 或 Python。但是要构建一个完整的东西,至少对于 web 来说,开发人员应该有不错的 HTML 和 CSS 技能。
然而,web 开发人员不需要成为这方面的专家。
# 做开发者需要那么多 HTML/CSS 吗?
我最初想做一个完整的列表,列出所有的 HTML 标签和 CSS 选择器/属性。然后我意识到我可以引导读者找到更多有用的资源。
然后我会给出一些高层次的建议,以强调 web 开发人员不需要具备李小龙级别的能力就能成为 HTML/CSS 忍者。
要构建一个站点,你只需要使用常见的 HTML 标签,比如:**标题** (h1-h6)、**链接** ( < a >)、**图片** ( < img >)、**无序列表** ( < ul >内有< li >)、 **divs** 和 **spans。**
除此之外还有这些 [**HTML5 语义标签**](https://www.bitdegree.org/learn/html5-semantic-tags/) <表头>、<导航>、<主>、<小节>、<旁注>、<文章>和<页脚>。
在某些情况下还需要很多其他的标签,但是我只包括了那些常用的标签。
对于 CSS,你只需要学习如何**样式文本**(字体属性)**链接**(主要是文本装饰)**调整元素的尺寸和位置**(宽度、边距、填充、浮动、位置)和**样式背景**(背景图像和背景颜色)。
CSS 过渡和动画现在在大多数网站中也无处不在,所以有必要学习它们。
**这里是学习 HTML 和 CSS 的简单但很棒的教程的链接:**
1. [学习 HTML5](https://www.tutorialrepublic.com/html-tutorial/)
2. [学习 CSS3](https://www.tutorialrepublic.com/html-tutorial/)
3. [响应式网页设计](https://learn.shayhowe.com/advanced-html-css/responsive-web-design/)

Image by [Maik Jonietz](https://unsplash.com/@der_maik_) on Unsplash
# 框架和库给了我们 CSS 超能力
如今,我们很幸运拥有工具、库和框架,让我们构建网站的标记和风格变得更加简单和容易。
以前,在 CSS 中完全使用浮动和位置属性来完善页面布局是很困难的。
但是现在我们有了 **FlexBox** 和 **CSS 网格**。拥有这两方面的基本技能将会让你制作出令人难以置信的网页。
除此之外,我们还有提供现成样式的库,如[引导库](https://getbootstrap.com/)、[基础库](https://foundation.zurb.com/)和[语义用户界面](https://semantic-ui.com/)。
我们只需要链接到他们的 CSS 文件(和 JavaScript/jQuery 库),理解他们的类和网格系统,瞧,你就可以构建看起来很棒的站点。
## 在享受乐趣的同时学习 Flexbox 和 CSS 网格
1. [Flexbox Froggy](https://flexboxfroggy.com/) —通过游戏学习 Flexbox
2. [Scrimba 上的 Flexbox 教程](https://scrimba.com/g/gflexbox)
3. [网格花园](http://cssgridgarden.com/) —通过游戏学习 CSS 网格
4. [Scrimba 上的 CSS 网格教程](https://scrimba.com/g/gR8PTE)
唉,似乎以上还不够,我们现在有了 CSS 预处理器(即, [SASS](http://sass-lang.com/) , [LESS](http://lesscss.org/) )。
它们有什么用?
如果你以前做过很多 CSS,你会同意 CSS 代码会变得混乱和难以理解。
这样做的后果是一场噩梦,调试会话会发现 700 多行 CSS 中的哪一部分是罪魁祸首。那些重复的或者多余的选择符会让你的 CSS 变得那么长吗?
我相信 CSS 预处理器的最大价值来自于它如何帮助开发者组织他/她的 CSS 代码。这使得管理具有多个选择器和属性的站点变得容易。
现在,如果你开始 web 开发,你真的渴望开始“实际编程”,那么你会很高兴地知道,有了 CSS 预处理程序,它几乎就像编程一样了。
你可以像使用 JavaScript 或 Ruby 一样使用变量、循环和函数。
SASS Tutorial On YouTube — [click this link for full playlist](https://www.youtube.com/playlist?list=PLUoqTnNH-2XxOt7UsKlTqbfrA2ucGosCR)
# 学习使用 Chrome 开发者工具
有人建立一个网站应该永远,我的意思是永远,忽视使用这个伟大的工具。
火狐也有,但我觉得 Chrome 更容易使用。使用 Chrome 的开发工具,你可以很容易地检查你的网站的 HTML 元素和 CSS 属性,以便修复 bug 或测试你想要加入到你的页面中的新样式,而无需提交到实际的代码中。
# **通过克隆网站快速掌握 HTML/CSS**
开始 web 开发之旅的人必须熟悉 HTML 和 CSS 几个星期(甚至几个月),然后才能开始学习编程。
但是练习建站最好的方法是什么呢?简单回答—克隆现有站点。
这样做会节省你寻找想法的时间和麻烦。一旦你建立了你要克隆的网站的头部或导航部分,你会有很大的自信。
# **最佳学习方式——与编码伙伴一起**
我开始自学网页开发和编程。
虽然你可以自己学到很多东西,但和别人一起工作还是更好。会有很多次你会被一些错误所困扰,因为你写了很多行代码,而你却找不到。
另一双眼睛会把你从这种痛苦中拯救出来。还需要我说更好玩吗?我自己[目前每天都和一个来自世界另一个地方的编码伙伴一起工作](https://hackernoon.com/how-five-weeks-of-remote-pair-programming-helped-me-build-strong-habits-e0493c9ba780)。
我们克隆了热门公司的主页,包括 Mint.com、T2、苹果、T4、新闻周刊和网络新闻。
一路上我们学到了很多。纪律和一致性对于成为一名高技能的 web 开发人员或软件工程师非常重要。
拥有一个负责任的伴侣有助于培养这两种品质。
## 找到一种结构化的学习方法
如果你想接受高强度的软件工程培训,那就去 Microverse.org 吧。
如果你是第一次编写代码,注册预科课程,你将学习(免费)网络开发和软件工程。
如果你是一个高级学习者(你对一些 JavaScript 或任何其他编程语言都很熟悉),那么我会推荐快速通道计划(你只有在完成该计划并找到一份远程软件工程工作后才会付费)。
**在[**Twitter**](https://twitter.com/coachryanv)|[**Github**](https://github.com/rvvergara)上关注我**
|
import torch
from torch import nn, Tensor
from jaxtyping import Float, Int64, Int
from typing import Literal, Tuple, Union, List
from models.positional_encoding import PositionalEncoding
import math
class ForwardDiffusion(nn.Module):
"""Class for forward diffusion process in DDPMs (denoising diffusion probabilistic models).
Attributes
----------
timesteps
max number of supported timesteps of the schedule
start
start value of scheduler
end
end value of scheduler
type
type of scheduler, currently linear and cosine supported
"""
def __init__(self, timesteps: int, start: float=0.0001, end: float=0.02, offset: float=0.008, max_beta: float=0.999, type: Literal["linear", "cosine"]="linear") -> None:
"""Constructor of ForwardDiffusion class.
Parameters
----------
timesteps
total number of timesteps in diffusion process
start
start beta for linear scheduler
end
end beta for linear scheduler
offset
offset parameter for cosine scheduler
max_beta
maximal value to clip betas for cosine scheduler
type
type of scheduler, either linear or cosine
"""
super().__init__()
self.timesteps = timesteps
self.start = start
self.end = end
self.offset = offset
self.type = type
self.max_beta = max_beta
if self.type == "linear":
self.init_betas = self._linear_scheduler(timesteps=self.timesteps, start=self.start, end=self.end)
elif self.type == "cosine":
self.init_betas = self._cosine_scheduler(timesteps=self.timesteps, offset=self.offset, max_beta=self.max_beta)
else:
raise NotImplementedError("Invalid scheduler option:", type)
self.init_alphas = 1. - self.init_betas
self.register_buffer("alphas", self.init_alphas, persistent=False)
self.register_buffer("betas", self.init_betas, persistent=False)
self.register_buffer("alphas_dash", torch.cumprod(self.alphas, axis=0), persistent=False)
self.register_buffer("alphas_dash_prev", torch.cat([torch.tensor([1.0]), self.alphas_dash[:-1]]), persistent=False)
self.register_buffer("alphas_dash_next", torch.cat([self.alphas_dash[1:], torch.tensor([0.0])]), persistent=False)
self.register_buffer("sqrt_alphas_dash", torch.sqrt(self.alphas_dash), persistent=False)
self.register_buffer("sqrt_one_minus_alphas_dash", torch.sqrt(1. - self.alphas_dash), persistent=False)
self.register_buffer("log_one_minus_alphas_dash", torch.log(1. - self.alphas_dash), persistent=False)
self.register_buffer("sqrt_recip_alphas_dash", torch.sqrt(1.0 / self.alphas_dash))
self.register_buffer("sqrt_recipminus1_alphas_dash", torch.sqrt(1.0 / self.alphas_dash - 1.0))
def forward(
self,
x_0: Float[Tensor, "batch channels height width"],
t: Int[Tensor, "batch"]
) -> Float[Tensor, "batch channels height width"]:
"""Forward method of ForwardDiffusion class.
Parameters
----------
x_0
input tensor where noise should be applied to
t
timestep of the noise scheduler from which noise should be chosen
Returns
-------
Float[Tensor, "batch channels height width"]
tensor with applied noise according to schedule and chosen timestep
"""
noise_normal = torch.randn_like(x_0, device=x_0.device)
if True in torch.gt(t, self.timesteps-1):
raise IndexError("t ({}) chosen larger than max. available t ({})".format(t, self.timesteps-1))
sqrt_alphas_dash_t = self.sqrt_alphas_dash[t]
sqrt_one_minus_alphas_dash_t = self.sqrt_one_minus_alphas_dash[t]
x_t = sqrt_alphas_dash_t.view(-1, 1, 1, 1) * x_0
x_t += sqrt_one_minus_alphas_dash_t.view(-1, 1, 1, 1) * noise_normal
return x_t, noise_normal
def forward_flexible(
self,
x_t1: Float[Tensor, "batch channels height width"],
t_1: Int64[Tensor, "batch"],
t_2: Int64[Tensor, "batch"]
) -> Float[Tensor, "batch channels height width"]:
"""Flexible method that enables jumping from/to any timestep in the forward diffusion process.
Parameters
----------
x_t1
batch of (partially noisy) inputs of different stages
t_1
initial timesteps of forward process (that above x_t1 are in at the moment)
t_2
timesteps that we would x_t1 transport to (elements must be larger than corresponding elements in t_1)
"""
diff = t_2 - t_1
if diff[diff<0].shape[0] != 0:
raise ValueError("Timesteps in forward process must increase.")
noise_normal = torch.randn_like(x_t1, device=x_t1.device)
if (True in torch.gt(t_1, self.timesteps-1)) or (True in torch.gt(t_2, self.timesteps-1)):
raise IndexError("t ({}, {}) chosen larger than max. available t ({})".format(t_1, t_2, self.timesteps-1))
batch_sqrt_alphas_dash = torch.zeros((t_1.shape[0]), device=x_t1.device)
batch_sqrt_one_minus_alpha_dash = torch.zeros((t_1.shape[0]), device=x_t1.device)
for sample in range(x_t1.shape[0]):
alphas_interval = self.alphas[t_1[sample]:t_2[sample]+1]
alphas_dash_interval = torch.cumprod(alphas_interval, axis=0)
sqrt_alphas_dash_interval = torch.sqrt(alphas_dash_interval)
sqrt_one_minus_alphas_dash_interval = torch.sqrt(1. - alphas_dash_interval)
batch_sqrt_alphas_dash[sample] = sqrt_alphas_dash_interval[-1]
batch_sqrt_one_minus_alpha_dash[sample] = sqrt_one_minus_alphas_dash_interval[-1]
mean = batch_sqrt_alphas_dash.view(-1, 1, 1, 1) * x_t1
out = mean + batch_sqrt_one_minus_alpha_dash.view(-1, 1, 1, 1) * noise_normal
return out, noise_normal
def _linear_scheduler(self, timesteps, start, end):
return torch.linspace(start, end, timesteps)
def _cosine_scheduler(self, timesteps, offset, max_beta):
"""t is actually t/T from the paper"""
return self._betas_for_alpha_bar(timesteps, lambda t: math.cos((t + offset) / (1.0 + offset) * math.pi / 2) ** 2, max_beta)
def _betas_for_alpha_bar(self, num_diffusion_timesteps, alpha_bar, max_beta):
betas = []
for i in range(num_diffusion_timesteps):
t1 = i / num_diffusion_timesteps # t -> t/T
t2 = (i + 1) / num_diffusion_timesteps
betas.append(min(1 - alpha_bar(t2) / alpha_bar(t1), max_beta))
return torch.tensor(betas)
class DiffusionModel(nn.Module):
"""DiffusionModel class that implements a DDPM (denoising diffusion probabilistic model)."""
def __init__(
self,
backbone: nn.Module,
fwd_diff: ForwardDiffusion,
img_size: int,
time_enc_dim: int=256,
dropout: float=0,
) -> None:
"""Constructor of DiffusionModel class.
Parameters
----------
backbone
backbone module (instance) for noise estimation
fwd_diff
forward diffusion module (instance)
img_size
size of (quadratic) images
time_enc_dim
feature dimension that should be used for time embedding/encoding
dropout
value of dropout layers
"""
super().__init__()
self.model = backbone
self.fwd_diff = fwd_diff
self.img_size = img_size
self.time_enc_dim = time_enc_dim
self.dropout = dropout
self.time_encoder = PositionalEncoding(d_model=time_enc_dim, dropout=dropout)
def forward(
self,
x: Float[Tensor, "batch channels height width"]
) -> Tuple[Float[Tensor, "batch channels height width"], Float[Tensor, "batch channels height width"]]:
"""Predict noise for single denoising step.
Parameters
----------
x
batch of original images
Returns
-------
out
tuple of noise predictions and noise for random timesteps in the denoising process
"""
timesteps = self._sample_timesteps(x.shape[0], device=x.device)
if timesteps.dim() != 1:
raise ValueError("Timesteps should only have batch dimension.", timesteps.shape)
time_enc = self.time_encoder.get_pos_encoding(timesteps)
if time_enc.dim() != 2:
raise ValueError("Time Encoding should be 2 dimensional.", time_enc.shape)
# make (partially) noisy versions of batch, returns noisy version + applied noise
x_t, noise = self.fwd_diff(x, timesteps)
# predict the applied noise from the noisy version
noise_pred = self.model(x_t, time_enc)
return noise_pred, noise
def init_noise(self, num_samples: int):
return torch.randn((num_samples, self.model.in_channels, self.img_size, self.img_size), device=list(self.parameters())[0].device)
def denoise_singlestep(
self,
x: Float[Tensor, "batch channels height width"],
t: Int64[Tensor, "batch"]
) -> Float[Tensor, "batch channels height width"]:
"""Denoise single timestep in reverse direction.
Parameters
----------
x
tensor representing a batch of noisy pictures (may be of different timesteps)
t
tensor representing the t timesteps for the batch (where the batch now is)
Returns
-------
out
less noisy version (by one timestep, now at t-1 from the arguments)
"""
self.model.eval()
with torch.no_grad():
t_enc = self.time_encoder.get_pos_encoding(t)
noise_pred = self.model(x, t_enc)
alpha = self.fwd_diff.alphas[t][:, None, None, None]
alpha_hat = self.fwd_diff.alphas_dash[t][:, None, None, None]
beta = self.fwd_diff.betas[t][:, None, None, None]
noise = torch.randn_like(x, device=noise_pred.device)
# noise where t = 1 should be zero
(t_one_idx, ) = torch.where(t==1)
noise[t_one_idx] = 0
x = 1 / torch.sqrt(alpha) * (x - ((1 - alpha) / (torch.sqrt(1 - alpha_hat))) * noise_pred) + torch.sqrt(beta) * noise
self.model.train()
return x
def sample(
self,
num_samples: int
) -> Union[Float[Tensor, "batch channel height width"], Tuple]:
beta = self.fwd_diff.betas[-1].view(-1,1,1,1)
x = self.init_noise(num_samples) * torch.sqrt(beta)
intermediates = {}
for i in reversed(range(1, self.fwd_diff.timesteps)):
t = i * torch.ones((num_samples), dtype=torch.long, device=list(self.model.parameters())[0].device)
x = self.denoise_singlestep(x, t)
return x
def _sample_timesteps(self, batch_size: int, device: torch.device) -> Int64[Tensor, "batch"]:
return torch.randint(low=1, high=self.fwd_diff.timesteps, size=(batch_size,), device=device)
|
<!DOCTYPE html>
<html lang="en">
<head>
<title>Task</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
</head>
<body>
<div class="jumbotron">
<h3> Task for Terribly Tiny Tales</h3>
<p> From the backend, return the top N most frequently occurring words in this file.</p>
</div>
<div class="container">
<div ng-app="myApp" ng-controller="formCtrl">
<form >
<div class="form-group">
<label for="n">Enter number</label>
<input type="number" class="form-control" id="n" name="n" ng-model="num"
placeholder="Top N most frequently occurring words in this file">
</div>
<button type="submit" onclick="fireRequest()" id="n_submit" class="btn btn-danger" name="Submit">Submit</button>
</form>
<div> Top {{num}} most frequently used worlds in the file are <br>
<table id="words" class="table table-bordered">
<tr class="success">
<th>Word</th>
<th>No. of occurances</th>
</tr>
</table></div>
</div>
</div>
<script>
function fireRequest()
{
var n=$("#n").val();
$.ajax({
url: '/n',
type: "POST",
data: JSON.stringify({
"n":n
}),
dataType: "json",
contentType: "application/json",
complete: function() {
//called when complete
console.log('process complete');
},
success: function(data) {
document.getElementById("words").innerHTML = "<tr class='success'> <th>Word</th> <th>No. of occurances</th> </tr>";
for(var i=0;i<data.data.length;i++){
document.getElementById('words').innerHTML+="<tr><td >"+ data.data[i]+"</td><td>"+ data.data[i+1]+"</td></tr> ";
i++;
}
console.log('process sucess');
},
error: function() {
console.log('process error');
}
});
}
var app = angular.module('myApp', []);
app.controller('formCtrl', function($scope) {
$scope.num = 0;
});
</script>
</body>
</html>
|
import { Component } from '@angular/core';
import {FormControl, FormGroup, Validators} from "@angular/forms";
import {AuthService} from "../../../core/services/auth.service";
@Component({
selector: 'tl-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.scss']
})
export class LoginComponent {
loginForm = new FormGroup({
email: new FormControl<string>('', {nonNullable: true, validators: [
Validators.required,
Validators.pattern('[A-Za-z0-9._%-]+@[A-Za-z0-9._%-]+\\.[a-z]{2,5}$'),
]}),
password: new FormControl<string>('', {nonNullable: true, validators: [
Validators.required,
Validators.minLength(3)
]}),
rememberMe: new FormControl<boolean>(false, {nonNullable: true})
})
constructor(private authService: AuthService) {
}
get email() {
return this.loginForm.get('email')
}
get password() {
return this.loginForm.get('password')
}
onSubmit() {
const value = this.loginForm.value
this.authService.login(value)
}
}
|
// adding new chat documents X
// setting up a real-time listener to get new chats
// updating the username
// updating he room
class Chatroom {
constructor(room, username) {
this.room = room;
this.username = username;
this.chats = db.collection('chats');
}
async addChat(message) {
//format a chat object
const now = new Date();
const chat = {
message,
username: this.username,
room: this.room,
created_at: firebase.firestore.Timestamp.fromDate(now)
};
//save the chat document
const response = await this.chats.add(chat);
return response;
}
getChats(callback) {
this.chats
.where('room', '==', this.room)
.orderBy('created_at')
.onSnapshot((snapshot) => {
snapshot.docChanges().forEach((change) => {
if (change.type === 'added') {
//update the ui
callback(change.doc.data());
}
});
});
}
}
const chatroom = new Chatroom('nba', 'aleksa');
chatroom.getChats((data) => {
console.log(data);
});
|
!pip install textblob
import nltk
nltk.download('punkt')
train = [
('What an amazing weather.', 'pos'),
('this is an amazing idea!', 'pos'),
('I feel very good about these ideas.', 'pos'),
('this is my best performance.', 'pos'),
("what an awesome view", 'pos'),
('I do not like this place', 'neg'),
('I am tired of this stuff.', 'neg'),
("I can't deal with all this tension", 'neg'),
('he is my sworn enemy!', 'neg'),
('my friends is horrible.', 'neg')
]
test = [
('the food was great.', 'pos'),
('I do not want to live anymore', 'neg'),
("I ain't feeling dandy today.", 'neg'),
("I feel amazing!", 'pos'),
('Ramesh is a friend of mine.', 'pos'),
("I can't believe I'm doing this.", 'neg')
]
from textblob.classifiers import NaiveBayesClassifier
cl = NaiveBayesClassifier(train)
print(cl.classify("This is an amazing library!"))
print(cl.accuracy(test))
cl.show_informative_features(4)
|
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<th:block th:replace="~{layout :: linkbootstrapCss}" }></th:block>
</head>
<body>
<header th:replace="~{layout :: header}"></header>
<form th:action="@{/contract/addContractDetail}" th:object="${contractDetailDto}" method="post">
<fieldset class="w-75 mx-auto">
<legend class="text-center my-4"><span class="text-secondary">Others service</span></legend>
<div>
<input type="hidden" th:field="*{contract}" >
</div>
<div class="form-outline w-25 mx-auto my-4">
<select th:field="*{attachService}" class="form-select" aria-label="Disabled select example">
<option value="0" th:text="---attachService---"></option>
<option th:each="attachService : ${attachServiceList}" th:value="${attachService.attachServiceId}"
th:text="${attachService.attachServiceName}"></option>
</select>
</div>
<div>
<label>
Quantity
<input type="number" th:field="*{quantity}" class="form-control" style="text-align: center">
</label>
</div>
<!-- <table class="table align-middle mb-0 bg-white">-->
<!-- <thead class="bg-light">-->
<!-- <tr>-->
<!-- <th>Stt</th>-->
<!-- <th>Attach Service Name</th>-->
<!-- <th>Cost</th>-->
<!-- <th>Unit</th>-->
<!-- <th>Status</th>-->
<!-- <th>Action</th>-->
<!-- </tr>-->
<!-- </thead>-->
<!-- <tbody>-->
<!-- <tr th:each="attachService, stt : ${attachServiceList}">-->
<!-- <th scope="row" th:text="${stt.count}"></th>-->
<!-- <td>-->
<!-- <p class="fw-normal mb-1" th:text="${attachService.attachServiceName}"></p>-->
<!-- </td>-->
<!-- <td>-->
<!-- <p class="fw-normal mb-1" th:text="${attachService.attachServiceCost}"></p>-->
<!-- </td>-->
<!-- <td>-->
<!-- <p class="fw-normal mb-1" th:text="${attachService.attachServiceUnit}"></p>-->
<!-- </td>-->
<!-- <td>-->
<!-- <p class="fw-normal mb-1" th:text="${attachService.attachServiceStatus}"></p>-->
<!-- </td>-->
<!-- <td>-->
<!-- <label>-->
<!-- <button class="btn btn-secondary mt-4 mx-2"> USE SERVICE </button>-->
<!-- </label>-->
<!-- </td>-->
<!-- </tr>-->
<!-- </tbody>-->
<!-- </table>-->
</fieldset>
<div class="text-center">
<button type="submit" class="btn btn-secondary mt-4 mx-2">ADD</button>
<a href="/contract/list">
<button type="button" class="btn btn-warning mt-4 mx-2">Cancel</button>
</a>
</div>
</form>
<footer th:replace="~{layout :: footer}"></footer>
</body>
<th:block th:replace="~{layout :: linkbootstrapJS}" }></th:block>
</html>
|
package transcribe
import (
"bytes"
"database/sql"
"encoding/json"
"fmt"
"io"
"log"
"mime/multipart"
"net/http"
"os"
"path/filepath"
"github.com/redis/go-redis/v9"
)
const (
audioDir = "audio"
openAIEndpoint = "https://api.openai.com/v1/audio/transcriptions"
)
type Transcriber struct {
openAIKey string
db *sql.DB
redis *redis.Client
}
func NewTranscriber(db *sql.DB, redis *redis.Client, openAPIKey string) *Transcriber {
log.Println("Creating new transcriber...")
return &Transcriber{
db: db,
redis: redis,
openAIKey: openAPIKey,
}
}
func (t *Transcriber) AttemptTranscription(filename string) (string, error) {
log.Println("Transcribing audio file:", filename)
file, err := os.Open(filename)
if err != nil {
return "", fmt.Errorf("error opening file %s: %w", filename, err)
}
defer file.Close()
var requestBody bytes.Buffer
writer := multipart.NewWriter(&requestBody)
part, err := writer.CreateFormFile("file", filepath.Base(filename))
if err != nil {
return "", fmt.Errorf("error creating form file: %w", err)
}
_, err = io.Copy(part, file)
if err != nil {
return "", fmt.Errorf("error copying file content: %w", err)
}
err = writer.WriteField("model", "whisper-1")
if err != nil {
return "", fmt.Errorf("error writing form field: %w", err)
}
err = writer.Close()
if err != nil {
return "", fmt.Errorf("error closing multipart writer: %w", err)
}
req, err := http.NewRequest("POST", openAIEndpoint, &requestBody)
if err != nil {
return "", fmt.Errorf("error creating HTTP request: %w", err)
}
req.Header.Set("Content-Type", writer.FormDataContentType())
req.Header.Set("Authorization", "Bearer "+t.openAIKey)
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return "", fmt.Errorf("error making HTTP request: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return "", fmt.Errorf("non-OK HTTP status: %s", resp.Status)
}
body, err := io.ReadAll(resp.Body)
if err != nil {
return "", fmt.Errorf("error reading response body: %w", err)
}
var result map[string]interface{}
err = json.Unmarshal(body, &result)
if err != nil {
return "", fmt.Errorf("error parsing JSON response: %w", err)
}
transcription, ok := result["text"].(string)
if !ok {
return "", fmt.Errorf("unexpected response format: %v", result)
}
fmt.Printf("Transcription of %s: %s\n", filename, transcription)
err = t.Save(filename, transcription)
if err != nil {
return "", fmt.Errorf("error saving transcription to database: %w", err)
}
return transcription, nil
}
func (t *Transcriber) GenerateHeadline(articleText string) (string, error) {
// Prepare request body
requestBody, err := json.Marshal(map[string]interface{}{
"prompt": articleText,
"max_tokens": 20, // Adjust based on desired headline length
})
if err != nil {
return "", err
}
// Create HTTP request
req, err := http.NewRequest("POST", openAIEndpoint, bytes.NewBuffer(requestBody))
if err != nil {
return "", err
}
// Set request headers
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", t.openAIKey))
// Send HTTP request
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
// Parse response
// var result map[string]interface{}
// if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
// return "", err
// }
// Extract headline from response
b := new(bytes.Buffer)
b.ReadFrom(resp.Body)
return b.String(), nil
}
func (t *Transcriber) Save(fileName, transcription string) error {
query := `
INSERT INTO transcriptions (file_name, transcription)
VALUES ($1, $2)
`
_, err := t.db.Exec(query, fileName, transcription)
if err != nil {
return fmt.Errorf("error inserting transcription into database: %w", err)
}
return nil
}
|
package com.evolve.alpaca.document;
import com.evolve.content.ContentFile;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.*;
import org.apache.commons.lang.StringUtils;
import java.time.LocalDateTime;
/**
* POJO that contains information about document's content and category.
*/
@AllArgsConstructor
@Getter
@EqualsAndHashCode
@ToString
public class DocumentEntry {
private final Long id;
@Setter
private String fileName;
private final LocalDateTime dateAdded;
@Setter
private String summary;
private final String mimeType;
private final Long length;
private EntryType entryType;
@Setter
private DocumentCategory category;
@JsonIgnore
public boolean isImageFile() {
return StringUtils.contains(mimeType, "image");
}
public boolean matchesCategory(DocumentCategory documentCategory) {
if (documentCategory == DocumentCategory.DEFAULT && this.category == null) {
return true;
}
return this.category == documentCategory;
}
public static DocumentEntry of(ContentFile contentFile, DocumentCategory documentCategory) {
return new DocumentEntry(contentFile.getId(), contentFile.getName(), contentFile.getCreated(),
contentFile.getSummary(), contentFile.getContentMimeType(), contentFile.getContentLength(),
EntryType.DOCUMENT, documentCategory);
}
public static DocumentEntry category(DocumentCategory category) {
return new DocumentEntry(null, null, null, null, null, null, DocumentEntry.EntryType.CATEGORY, category);
}
public enum EntryType {
CATEGORY,
DOCUMENT
}
}
|
import {ExpressRequestInterface} from "../types/expressRequest.interface";
import {NextFunction, Response} from "express";
import TaskModel from "../models/task";
import {Server} from "socket.io";
import {Socket} from "../types/socket.interface";
import {SocketEventsEnum} from "../types/socketEvents.enum";
import {getErrorMessage} from "../helpers";
export const getTasks = async (
req: ExpressRequestInterface,
res: Response,
next: NextFunction
) => {
try {
if (!req.user) {
return res.sendStatus(401);
}
const tasks = await TaskModel.find({ boardId: req.params.boardId });
res.send(tasks);
} catch (err) {
next(err);
}
};
export const createTask = async (
io: Server,
socket: Socket,
data: { boardId: string; title: string, columnId: string, description: string }
) => {
try {
if (!socket.user) {
socket.emit(
SocketEventsEnum.taskCreateFailure,
"User is not authorized"
);
return;
}
const newTask = new TaskModel({
title: data.title,
description: data.description,
boardId: data.boardId,
userId: socket.user.id,
columnId: data.columnId
});
const savedTask = await newTask.save();
io.to(data.boardId).emit(
SocketEventsEnum.taskCreateSuccess,
savedTask
);
} catch (err) {
socket.emit(SocketEventsEnum.taskCreateFailure, getErrorMessage(err));
}
};
export const updateTask = async (
io: Server,
socket: Socket,
data: { boardId: string, taskId: string, fields: {title?: string, description?: string, columnId?: string} }
) => {
try {
if(!socket.user) {
socket.emit(SocketEventsEnum.taskUpdateFailure, 'User is not authorized')
return
}
const newTask = await TaskModel.findByIdAndUpdate(data.taskId, data.fields, { new: true })
io.to(data.boardId).emit(SocketEventsEnum.taskUpdateSuccess, newTask)
} catch (err) {
socket.emit(SocketEventsEnum.taskUpdateFailure, getErrorMessage(err))
}
};
export const deleteTask = async (
io: Server,
socket: Socket,
data: { boardId: string, taskId: string }
) => {
try {
if(!socket.user) {
socket.emit(SocketEventsEnum.taskDeleteFailure, 'User is not authorized');
return;
}
await TaskModel.findByIdAndDelete({ _id: data.taskId });
io.to(data.boardId).emit(SocketEventsEnum.taskDeleteSuccess, data.taskId);
} catch (err) {
socket.emit(SocketEventsEnum.taskDeleteFailure, getErrorMessage(err))
}
};
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Meflix</title>
<link rel="icon" href="images/logo.jfif" />
<!-- google font link -->
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link
href="https://fonts.googleapis.com/css2?family=Prata&display=swap"
rel="stylesheet"
/>
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link
href="https://fonts.googleapis.com/css2?family=Josefin+Sans:ital,wght@0,100..700;1,100..700&family=Prata&display=swap"
rel="stylesheet"
/>
<!-- font awsome link -->
<link
rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css"
integrity="sha512-SnH5WK+bZxgPHs44uWIX+LLJAJ9/2PkPKZ5QiAj6Ta86w+fsb2TkcmfRyVX3pBnMFcV7oQPJkl9QevSCWr3W6A=="
crossorigin="anonymous"
referrerpolicy="no-referrer"
/>
<!-- css link -->
<link rel="stylesheet" href="style.css" />
</head>
<body>
<!-- navigations section -->
<nav id="navi">
<h1 class="ff-prata">MEFLIX</h1>
<a href="#shows" class="ff-jose">Shows</a>
<a href="#movies" class="ff-jose">Movies</a>
<a href="#anime" class="ff-jose">Anime</a>
<p class="ff-jose">Search <input type="text" placeholder="" /></p>
</nav>
<!-- shows section -->
<section id="shows">
<h1 class="ff-prata">SHOWS</h1>
<div class="shows-container">
<div class="show">
<img src="images/bbtheory.jpg" alt="show-image" />
<h3 class="ff-jose">Big Bang Theory</h3>
</div>
<div class="show">
<img src="images/geekgirl.jpg" alt="show-image" />
<h3 class="ff-jose">Geek Girl</h3>
</div>
<div class="show">
<img src="images/grey.jpg" alt="show-image" />
<h3 class="ff-jose">Grey's Anatomy</h3>
</div>
<div class="show">
<img src="images/howimetyourmother.jpg" alt="show-image" />
<h3 class="ff-jose">How I Met Your Mother</h3>
</div>
<div class="show">
<img src="images/modenfam.jpg" alt="show-image" />
<h3 class="ff-jose">Modern Family</h3>
</div>
<div class="show">
<img src="images/peakyblinder.jpg" alt="show-image" />
<h3 class="ff-jose">Peaky Blinder</h3>
</div>
</div>
</section>
<!-- movies section -->
<section id="movies">
<h1 class="ff-prata">MOVIES</h1>
<div class="movies-container">
<div class="movie">
<img src="images/fallguy.jpg" alt="movie-image" />
<h3 class="ff-jose">Fall Guy</h3>
</div>
<div class="movie">
<img src="images/ghostbuster.jpg" alt="movie-image" />
<h3 class="ff-jose">Ghostbuster</h3>
</div>
<div class="movie">
<img src="images/korem.jpg" alt="movie-image" />
<h3 class="ff-jose">Lorem Ipsum</h3>
</div>
<div class="movie">
<img src="images/planet.jpg" alt="movie-image" />
<h3 class="ff-jose">Planet of the Ape</h3>
</div>
<div class="movie">
<img src="images/spiderman.jpg" alt="movie-image" />
<h3 class="ff-jose">Spiderman:Far from Home</h3>
</div>
<div class="movie">
<img src="images/transformer.jpg" alt="movie-image" />
<h3 class="ff-jose">Transformer:Rise of the Beasts</h3>
</div>
</div>
</section>
<!-- anime section -->
<section id="anime">
<h1 class="ff-prata">ANIME</h1>
<div class="anime-container">
<div class="anime">
<img src="images/boochi.jpg" alt="anime-image" />
<h3 class="ff-jose">Boochi the Rock</h3>
</div>
<div class="anime">
<img src="images/demon.jpg" alt="anime-image" />
<h3 class="ff-jose">Demon Slayer</h3>
</div>
<div class="anime">
<img src="images/jujusu.jpg" alt="anime-image" />
<h3 class="ff-jose">Jujutsu Kaisen</h3>
</div>
<div class="anime">
<img src="images/nichijou.jpg" alt="anime-image" />
<h3 class="ff-jose">Nichijou</h3>
</div>
<div class="anime">
<img src="images/onepiece.jpg" alt="anime-image" />
<h3 class="ff-jose">One Piece</h3>
</div>
<div class="anime">
<img src="images/uncle.png" alt="anime-image" />
<h3 class="ff-jose">Uncle From Another World</h3>
</div>
</div>
</section>
<!-- footer section -->
<footer>
<p class="ff-jose">
Copyright ©2024 <span>Meflix</span> All Rights Reserved
</p>
</footer>
</body>
</html>
|
package ru.kata.spring.boot_security.demo.controllers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import ru.kata.spring.boot_security.demo.Exception.ExceptionInfo;
import ru.kata.spring.boot_security.demo.Exception.UserUsernameExistsException;
import ru.kata.spring.boot_security.demo.models.Role;
import ru.kata.spring.boot_security.demo.models.User;
import ru.kata.spring.boot_security.demo.services.PersonDetailsService;
import ru.kata.spring.boot_security.demo.services.RoleServiceImpl;
import ru.kata.spring.boot_security.demo.services.UserServiceImpl;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.security.Principal;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
@RestController
public class AdminController {
private final UserServiceImpl userService;
private final RoleServiceImpl roleService;
private final PasswordEncoder passwordEncoder;
private final PersonDetailsService personDetailsService;
@Autowired
public AdminController(UserServiceImpl userService, RoleServiceImpl roleService, PasswordEncoder passwordEncoder,
PersonDetailsService personDetailsService) {
this.userService = userService;
this.roleService = roleService;
this.passwordEncoder = passwordEncoder;
this.personDetailsService = personDetailsService;
}
// @GetMapping("/admin")
// public String showAllUsers (Principal principal, Model model) {
// model.addAttribute("users", userService.findAllUsers());
// model.addAttribute("user", personDetailsService.findByUsername(principal.getName()));
// model.addAttribute("roles", roleService.findByIdRoles());
// return "users";
// }
// @GetMapping("/get_user/{id}")
// public ResponseEntity<User> getUser(@PathVariable("id") long id) {
// //userService.removeUser(id);
// System.out.println("looking for user");
//
// return new ResponseEntity<>(personDetailsService.findByUsername("sergey"), HttpStatus.OK);
// }
@GetMapping("/getUser/{id}")
public User getUser(@PathVariable("id") long id) {
return userService.getUserById(id);
}
@GetMapping("/users")
public ResponseEntity<List<User>> getUsers() {
return new ResponseEntity<>(userService.findAllUsers(), HttpStatus.OK);
}
//This works
@PostMapping("users/add")
public ResponseEntity<ExceptionInfo> createUser(@RequestBody User user) {
try {
// Set<Role> roles = new HashSet<>(roleService.getRolesById(ids));//correct here
// user.setRoles(roles);
user.setPassword(passwordEncoder.encode(user.getPassword()));
userService.saveUser(user);
return new ResponseEntity<>(HttpStatus.OK);
} catch (UserUsernameExistsException u) {
throw new UserUsernameExistsException("User with username exists");
}
}
//This works
@DeleteMapping("/users/delete/{id}")
public ResponseEntity<ExceptionInfo> pageDelete(@PathVariable("id") long id) {
userService.removeUser(id);
return new ResponseEntity<>(new ExceptionInfo("User deleted"), HttpStatus.OK);
}
// @PutMapping("/users/update/{id}")
// @ResponseStatus(HttpStatus.OK)
// public User editUser(@PathVariable("id") long id, @RequestBody User user) {
// return userService.updateUser(id, user);
// }
@PutMapping("/users/{id}")
public ResponseEntity<ExceptionInfo> pageEdit(@PathVariable("id") long id,
@RequestBody User user) {
try {
String oldPassword = userService.getUserById(id).getPassword();
if (oldPassword.equals(user.getPassword())) {
System.out.println("TRUE");
// Set<Role> roles = new HashSet<>(roleService.getRolesById(Collections.singletonList(2)));
// user.setRoles(roles);
user.setPassword(oldPassword);
userService.updateUser(user);
} else {
System.out.println("FALSE");
// Set<Role> roles = new HashSet<>(roleService.getRolesById(Collections.singletonList(2)));//correct here!!
// user.setRoles(roles);
user.setPassword(passwordEncoder.encode(user.getPassword()));
userService.saveUser(user);
}
return new ResponseEntity<>(HttpStatus.OK);
} catch (UserUsernameExistsException u) {
throw new UserUsernameExistsException("User with username exists");
}
}
}
//@GetMapping("/add")
//public String pageCreateUser (Model model, Principal principal) {
// model.addAttribute("user", personDetailsService.findByUsername(principal.getName()));
// model.addAttribute("listRoles", roleService.findByIdRoles());
// return "create";
//}
//
// @PostMapping("/new")
// public String pageCreate(@ModelAttribute("user")
// @Valid User user, BindingResult bindingResult,
// @RequestParam("listRoles") List<Integer> roleIds) {
// if (bindingResult.hasErrors()) {
// return "create";
// }
// if (personDetailsService.findByUsername(user.getUsername()) != null) {
// bindingResult.addError(new FieldError("username", "username",
// String.format("User with name \"%s\" already exists!", user.getUsername())));
// return "create";
// }
// Set<Role> roles = new HashSet<>(roleService.getRolesById(roleIds));
// user.setRoles(roles);
// user.setPassword(passwordEncoder.encode(user.getPassword()));
// userService.saveUser(user);
// return "redirect:/admin";
// }
//
// @DeleteMapping("/{id}/delete")
// public String pageDelete(@PathVariable("id") long id) {
// userService.removeUser(id);
// return "redirect:/admin";
// }
//
// @GetMapping("/{id}/update")
// public String pageEditUser(@PathVariable("id") long id, Model model) {
// model.addAttribute("user",userService.getUserById(id));
// model.addAttribute("listRoles", roleService.getAllRoles());
// return "users";
// }
//
// @PutMapping("/{id}/update")
// public String pageEdit(@Valid User user, BindingResult bindingResult,
// @RequestParam("listRoles") List<Integer>roleIds) {
// if (bindingResult.hasErrors()) {
// return "redirect:/admin";
// }
// Set<Role> roles = new HashSet<>(roleService.getRolesById(roleIds));
// user.setRoles(roles);
// user.setPassword(passwordEncoder.encode(user.getPassword()));
// userService.updateUser(user);
// return "redirect:/admin";
// }
|
###############################################################
#
# test_simulation_analysis.R - Analyzes the estimates produced
# by the pacsketch method, and
# a sampling approach.
#
#
# Author: Omar Ahmed
#
###############################################################
# Needed libraries
library(ggplot2)
library(ggpubr)
# Data paths ...
data_path <- "/Users/omarahmed/Downloads/pacsketch_workspace/simulate_exp_test/estimated_attack_ratios.csv"
#############################################################################
#
# This plot will compare the estimated attack ratio from two methods: our
# method called pacsketch and a sampling based approach where we assume we
# have oracle knowledge. It will be box-and-whisker plot, and the y-axis
# will the absolute difference between true attack ratio, and estimated
# difference.
#
#############################################################################
df <- read.csv(data_path, header=TRUE)
plot1<- ggplot(df) +
geom_boxplot(aes(x=as.factor(approach), y=abs(est_attack_ratio-true_attack_ratio)*100,
color=as.factor(approach)), outlier.shape=4) +
theme_classic() +
theme(plot.title = element_text(hjust = 0.5, size=14, face="bold"),
axis.title.x = element_text(size =14,vjust=0),
axis.title.y=element_text(size=14),
legend.position = "none",
legend.text = element_text(size=10),
axis.text=element_text(size=14, color="black")) +
labs(x="Method",
y="|Est. Attack % - True Attack %|",
title="Comparing Pacsketch to Sampling in Estimating Anomalous Percentage") +
scale_y_continuous(breaks=seq(0, 30, 5)) +
scale_color_discrete(labels=c("Pacsketch", "Sampling Oracle")) +
scale_x_discrete(labels=c("Pacsketch", "Sampling Oracle"))
plot1
output_name1 <- "/Users/omarahmed/downloads/simulation_test_boxplot.jpeg"
ggsave(output_name1, plot=plot1, dpi=800, device="jpeg", width=7.5, height=6)
|
import React, { useState } from 'react'
import { GetServerSideProps, NextPage } from 'next'
import { useRouter } from 'next/router';
import { Box, Card, CardContent, Chip, CircularProgress, Divider, Grid, Typography } from '@mui/material'
import AirplaneTicketOutlined from '@mui/icons-material/AirplaneTicketOutlined';
import CreditCardOffOutlined from '@mui/icons-material/CreditCardOffOutlined';
import CreditScoreOutlined from '@mui/icons-material/CreditScoreOutlined';
import { CartList, OrderSummary } from '@/components/cart'
import { AdminLayout, ShopLayout } from '@/components/layouts'
import { dbOrders } from '@/database';
import { IOrder } from '@/interfaces';
interface Props {
order: IOrder
}
const OrderPage: NextPage<Props> = ({ order }) => {
const { _id, isPaid, numberOfItems, shippingAddress, subTotal, total, tax } = order;
const [isPaying, setisPaying] = useState(false);
return (
<AdminLayout
title='Resumen de la orden'
subTitle={`Resumen de la orden ${order._id}`}
icon={<AirplaneTicketOutlined/>}
>
{isPaid ?
<Chip
sx={{ my: 2 }}
label='Orden ya fue pagada'
variant='outlined'
color="success"
icon={<CreditScoreOutlined />}
/> :
<Chip
sx={{ my: 2 }}
label='Pendiente de pago'
variant='outlined'
color="error"
icon={<CreditCardOffOutlined />}
/>
}
<Grid container className='fadeIn'>
<Grid item xs={12} sm={7}>
{/* CartList */}
<CartList products={order.orderItems} />
</Grid>
<Grid item xs={12} sm={5}>
<Card className='summary-card'>
<CardContent>
<Typography variant='h2'>Resumen ({numberOfItems} {numberOfItems > 1 ? 'productos' : 'producto'})</Typography>
<Divider sx={{ my: 1 }} />
<Box display={'flex'} justifyContent={'space-between'}>
<Typography variant='subtitle1'>Dirección de entrega</Typography>
</Box>
<Typography>{shippingAddress.firstName} {shippingAddress.lastName}</Typography>
<Typography>{shippingAddress.address2} {shippingAddress.address2 ? `${shippingAddress.address2}` : ''}</Typography>
<Typography>{shippingAddress.city}</Typography>
<Typography>{shippingAddress.country}</Typography>
<Typography>{shippingAddress.phone}</Typography>
<Divider sx={{ my: 1 }} />
<OrderSummary summaryItems={{ numberOfItems, subTotal, total, tax }} />
<Box sx={{ mt: 3 }} display='flex' flexDirection={'column'}>
{/* TODO */}
<Box
display={'flex'}
justifyContent={'center'}
className='fadeIn'
sx={{ display: isPaying ? 'flex' : 'none' }}>
<CircularProgress />
</Box>
<Box flexDirection={'column'}
sx={{ display: isPaying ? 'none' : 'flex', flex: 1 }}>
{isPaid ?
<Chip
sx={{ my: 2 }}
label='Orden ya fue pagada'
variant='outlined'
color="success"
icon={<CreditScoreOutlined />}
/> :
<Chip
sx={{ my: 2 }}
label='Pendiente de pago'
variant='outlined'
color="error"
icon={<CreditCardOffOutlined />}
/>
}
</Box>
</Box>
</CardContent>
</Card>
</Grid>
</Grid>
</AdminLayout>
)
}
export const getServerSideProps: GetServerSideProps = async ({ req, query }) => {
const { id = "" } = query; // your fetch function here
const order = await dbOrders.getOrderById(id.toString());
if (!order) {
return {
redirect: {
destination: `/admin/orders`,
permanent: false
}
}
}
return {
props: {
order
}
}
}
export default OrderPage
|
Module Pattern
Да имаме променливи вътре които не можем да достъпваме отвън(closure) а само с методите да ги манипулираме.
let moduleObj = {
count: 0,
increase: function () { return count++;},
decrease: function () { return count--;},
print: function () {console.log(counter);}
} // counter е публичен
(Revealing) :
let revModule = (function (){
let count = 0;
function increase() { return count++;}
function decrease() { return count--;}
function print() {console.log(counter);}
return { increase, decrease, print}
})()
|
import './index.css';
import React, { JSX, ReactElement } from 'react';
import { Route, Routes } from 'react-router-dom';
import AddEditPhone from './pages/add-edit-phone';
import { Error } from './pages/error';
import Home from './pages/home';
import Login from './pages/login';
interface IRoute {
path: string;
component: ReactElement;
}
function App(): JSX.Element {
const routes: IRoute[] = [
{
path: '/login',
component: <Login />,
},
{
path: '/',
component: <Home />,
},
{
path: '/add',
component: <AddEditPhone />,
},
{
path: '/edit',
component: <AddEditPhone />,
},
{
path: '*',
component: <Error />,
},
];
return (
<div className="App">
<Routes>
{routes.map((route, i) => {
const { path, component } = route;
return <Route key={i} path={path} element={component} />;
})}
</Routes>
</div>
);
}
export default App;
|
import API from "../../api";
import { BlogInterface } from "../../interface/api/blogAPI";
import Header from "../../components/Header";
import Link from "next/link";
import { BLOG } from "../../config/constRouter";
import { useEffect, useState } from "react";
import { ethers } from "ethers";
import { marketAddress, NFTAddress } from "../../config";
import MARKET from "../../artifacts/contracts/Market.sol/Market.json";
import { Product, ProductSale } from "../../interface";
import { AxiosResponse } from "axios";
import { message } from "antd";
import Web3Modal from "web3modal";
const MyProduct = () => {
const [data, setData] = useState<ProductSale[]>([]);
useEffect(() => {
async function getData() {
const web3Modal = new Web3Modal();
const connection = await web3Modal.connect();
const provider = new ethers.providers.Web3Provider(connection);
const signer = provider.getSigner();
const productContract = new ethers.Contract(
marketAddress,
MARKET.abi,
signer
);
const data = await productContract.getMyItem();
const items = await Promise.all(
data.map(async (d: any) => {
const res: AxiosResponse<Product> =
await API.product.getProduct(d.itemURL);
return { ...d, data: res.data };
})
);
setData(items);
}
getData();
}, []);
return (
<>
<Header />
<div className="w-full max-w-screen-xl mx-auto">
<h1>Danh sách các Product</h1>
<div className="flex flex-row">
{data.map((product: ProductSale) => (
<div
className="w-40 border m-5 cursor-pointer"
key={product.data._id}
>
<h1>Tên: {product.data.name}</h1>
<p>Mô tả: {product.data.description}</p>
<p>Giá: {product.data.price}</p>
</div>
))}
</div>
</div>
</>
);
};
export default MyProduct;
|
// ************ Require's ************
const express = require('express');
const router = express.Router();
const path = require('path');
const multer = require('multer');
// ************ Controller Require ************
const productsController = require('../controllers/productsController');
// SET STORAGE
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, path.join(__dirname, '../../public/images/products'))
},
filename: function (req, file, cb) {
console.log(file);
cb(null, file.fieldname + '-' + Date.now()+ path.extname(file.originalname))
}
});
var upload = multer({
storage,
//VALIDATE IMAGE
fileFilter: (req,file,cb) => {
const acceptedExtensions = ['.jpg', '.jpeg', '.png'];
const ext = path.extname(file.originalname);
if(!acceptedExtensions.includes(ext)){
req.file = file;
}
cb(null, acceptedExtensions.includes(ext));
}
});
/*** GET ALL PRODUCTS ***/
router.get('/', productsController.index);
// /*** CREATE ONE PRODUCT ***/
router.get('/create', productsController.create);
router.post('/create', upload.single('image') ,productsController.store);
// /*** GET ONE PRODUCT ***/
router.get('/detail/:id/', productsController.detail);
// /*** EDIT ONE PRODUCT ***/
router.get('/edit/:id', productsController.edit);
router.put('/edit/:id', productsController.update);
// /*** DELETE ONE PRODUCT***/
router.delete('/delete/:id', productsController.destroy);
module.exports = router;
|
LCD Development Guide
:link_to_translation:`zh_CN:[中文]`
This guide mainly contains the following sections:
.. list::
- `Supported Interface Types`_: Espressif's support for different LCD interfaces in each series of chips.
- `Driver and Examples`_: LCD driver and examples provided by Espressif Systems.
- `Development Framework`_: Develop software and hardware framework for LCD.
- `Development Steps`_: Detailed steps for developing LCD applications.
- `Common Problems`_: Lists common problems in developing LCD applications.
- `Related Documents`_: Links to relevant documentation are listed.
Supported Interface Types
----------------------------
Espressif Systems provides comprehensive support for all interface types introduced in the :ref:`LCD Overview - Driver Interface <LCD_Overview_Driver_Interface>`. Specific support for each series of ESP chips within this section is as follows:
.. list-table::
:widths: 20 20 20 20 20
:header-rows: 1
* - Soc
- SPI(QSPI)
- I80
- RGB
- MIPI-DSI
* - ESP32
- |supported|
-
-
-
* - ESP32-C3
- |supported|
-
-
-
* - ESP32-C6
- |supported|
-
-
-
* - ESP32-S2
- |supported|
- |supported|
-
-
* - ESP32-S3
- |supported|
- |supported|
- |supported|
-
* - ESP32-P4
- |supported|
- |supported|
- |supported|
- |supported|
.. |supported| image:: https://img.shields.io/badge/-Supported-green
.. _LCD_Development_Guide_Driver_and_Examples:
Driver and Examples
---------------------
**LCD Peripheral** Driver is located in the `components/esp_lcd <https://docs.espressif.com/projects/esp-idf/en/latest/esp32s3/api-reference/peripherals/lcd.html>_` directory under **ESP-IDF**. Currently, it supports the ``I2C``, ``SPI (QSPI)``, ``I80``, and ``RGB`` interfaces. The following table lists the LCD driver components officially ported by Espressif based on esp_lcd, and these components will continue to be updated:
.. list-table::
:widths: 10 15
:header-rows: 1
* - LCD Controller
- Interface
* - `st7789 <https://github.com/espressif/esp-idf/blob/master/components/esp_lcd/src/esp_lcd_panel_st7789.c>`_
- SPI/I80
* - `nt35510 <https://github.com/espressif/esp-idf/blob/master/components/esp_lcd/src/esp_lcd_panel_nt35510.c>`_
- SPI/I80
* - `ssd1306 <https://github.com/espressif/esp-idf/blob/master/components/esp_lcd/src/esp_lcd_panel_ssd1306.c>`_
- I2C
* - `gc9b71 <https://github.com/espressif/esp-iot-solution/tree/master/components/display/lcd/esp_lcd_gc9b71>`_
- SPI/QSPI
* - `nv3022b <https://github.com/espressif/esp-iot-solution/tree/master/components/display/lcd/esp_lcd_nv3022b>`_
- SPI
* - `sh8601 <https://github.com/espressif/esp-iot-solution/tree/master/components/display/lcd/esp_lcd_sh8601>`_
- SPI/QSPI
* - `spd2010 <https://github.com/espressif/esp-iot-solution/tree/master/components/display/lcd/esp_lcd_spd2010>`_
- SPI/QSPI
* - `st7701 <https://github.com/espressif/esp-iot-solution/tree/master/components/display/lcd/esp_lcd_st7701>`_
- 3-wire SPI + RGB
* - `st77903_rgb <https://github.com/espressif/esp-iot-solution/tree/master/components/display/lcd/esp_lcd_st77903_rgb>`_
- 3-wire SPI + RGB
* - `st77903 <https://github.com/espressif/esp-iot-solution/tree/master/components/display/lcd/esp_lcd_st77903>`_
- QSPI
* - `st77916 <https://github.com/espressif/esp-iot-solution/tree/master/components/display/lcd/esp_lcd_st77916>`_
- SPI/QSPI
* - `st77922 <https://github.com/espressif/esp-iot-solution/tree/master/components/display/lcd/esp_lcd_st77922>`_
- SPI/QSPI
* - `gc9503 <https://github.com/espressif/esp-bsp/tree/master/components/lcd/esp_lcd_gc9503>`_
- 3-wire SPI + RGB
* - `gc9a01 <https://github.com/espressif/esp-bsp/tree/master/components/lcd/esp_lcd_gc9a01>`_
- SPI
* - `ili9341 <https://github.com/espressif/esp-bsp/tree/master/components/lcd/esp_lcd_ili9341>`_
- SPI
* - `ra8875 <https://github.com/espressif/esp-bsp/tree/master/components/lcd/esp_lcd_ra8875>`_
- Parallel Intel 8080
* - `sh1107 <https://github.com/espressif/esp-bsp/tree/master/components/lcd/esp_lcd_sh1107>`_
- I2C
* - `ssd1681 <https://github.com/espressif/esp-bsp/tree/master/components/lcd/esp_lcd_ssd1681>`_
- SPI
* - `st7796 <https://github.com/espressif/esp-bsp/tree/master/components/lcd/esp_lcd_st7796>`_
- SPI/I80
**Please note:**
.. _LCD_Driver_Component:
- The **st7789**, **nt35510**, and **ssd1306** components are maintained in the `ESP-IDF <https://github.com/espressif/esp-idf/tree/master/components/esp_lcd/src>`_. Other components can be found in the `Espressif IDF Component Registry <https://components.espressif.com/components?q=espressif%2Fesp_lcd>`_.
- Although the models of the **LCD driver IC** might be identical, **different screens** require specific configurations through initialization commands provided by their respective manufacturers. Most driver components support the customization of initialization commands during the initialization of the LCD device. If it is not supported, please refer to the `method <https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/peripherals/lcd.html#steps-to-add-manufacture-specific-initialization>`_.
**LCD Example** is located in the `examples/peripherals/lcd <https://github.com/espressif/esp-idf/tree/master/examples/peripherals/lcd>`_ directory under **ESP-IDF** and the :project:`examples/display/lcd <examples/display/lcd>` directory under **esp-iot-solution**. These serve as a reference for the usage of the LCD driver component.
.. note::
- It is recommended to develop based on ESP-IDF `release/v5.1 <https://github.com/espressif/esp-idf/tree/release/v5.1>`_ and above version branches, because lower versions may lack to support some parts of the important new features, especially for the ``RGB`` interface.
- For LCDs using the ``3-wire SPI + RGB`` interface, please refer to the example `esp_lcd_st7701 - Example use <https://components.espressif.com/components/espressif/esp_lcd_st7701>`_.
Development Framework
-------------------------
Hardware Framework
^^^^^^^^^^^^^^^^^^^^^^^^^
For SPI/I80 LCD, ESP can send **commands** to configure the LCD and transmit **regional color data** to refresh the screen through a single peripheral interface. The LCD driver IC will store the received color data in **full-screen size GRAM** and display **full-screen color data** on the panel at a fixed refresh rate. Importantly, these two processes are performed in asynchronously. The schematic diagram below illustrates the hardware driver framework of SPI/I80 LCD:
.. figure:: ../../../_static/display/screen/lcd_hw_framework_spi_i80.png
:align: center
:scale: 40%
:alt: Hardware driver framework diagram - SPI/I80 LCD
Schematic diagram of hardware driver framework - SPI/I80 LCD
For most RGB LCDs, the ESP needs to use two different interfaces. On one hand, it utilizes the `3-wire SPI` interface to send commands for configuring the LCD. On the other hand, it uses the `RGB` interface to transmit **full-screen color data** for screen refresh. Since the LCD's driver IC does not have a built-in Graphic RAM (GRAM), it directly displays the received color data on the panel, making these two processes synchronous. The following is a schematic diagram of the hardware driving framework for RGB LCDs:
.. figure:: ../../../_static/display/screen/lcd_hw_framework_rgb.png
:align: center
:scale: 40%
:alt: Schematic diagram of hardware driver framework - RGB LCD
Schematic diagram of hardware driver framework - RGB LCD
By comparing these two frameworks, it can be observed that, in contrast to SPI/I80 LCDs, RGB LCDs not only require the ESP to use two interfaces for transmitting commands and color data separately but also require that the ESP provides a full-screen-sized Graphic RAM (GRAM) for screen refresh. Due to the limited space in the on-chip SRAM, GRAM is typically placed in the PSRAM.
For QSPI LCDs, different models of driver ICs may require different driving methods. For example, the *SPD2010* IC has a built-in GRAM, and its driving method is similar to SPI/I80 LCDs. On the other hand, the *ST77903* IC does not have internal GRAM, and its driving method is similar to RGB LCDs. However, both of them use a single peripheral interface to transmit commands and color data. Below are schematic diagrams illustrating the hardware driving frameworks for these two types of QSPI LCDs:
.. figure:: ../../../_static/display/screen/lcd_hw_framework_qspi_with_gram.png
:align: center
:scale: 50%
:alt: Hardware driver framework diagram - QSPI LCD (with GRAM)
Schematic diagram of hardware driver framework - QSPI LCD (with GRAM)
.. figure:: ../../../_static/display/screen/lcd_hw_framework_qspi_without_gram.png
:align: center
:scale: 50%
:alt: Schematic diagram of hardware driver framework - QSPI LCD (without GRAM)
Schematic diagram of hardware driver framework - QSPI LCD (without GRAM)
Software Framework
^^^^^^^^^^^^^^^^^^^^^^^^^
The software development framework primarily consists of three layers: SDK (Software Development Kit), Driver, and APP (Application).
#. **SDK layer**: ESP-IDF serves as the foundational element of the framework. It not only includes ``I2C``, ``SPI (QSPI)``, ``I80`` and ``RGB`` required to drive LCD and other peripherals, it also provides unified APIs through the ``esp_lcd`` component to operate the interface and LCD, such as command and parameter transmission, LCD image refresh, inversion, mirroring and other functions.
#. **Driver layer**: Based on the APIs provided by the SDK, various device drivers can be implemented, and the porting of LVGL (GUI framework) can be implemented by initializing interface devices and LCD devices.
#. **APP layer**: Use the APIs provided by LVGL to implement various GUI functions, such as displaying pictures, animations, text, etc.
.. figure:: ../../../_static/display/screen/lcd_sw_framework.png
:align: center
:scale: 50%
:alt: Schematic diagram of software development framework
Schematic diagram of software development framework
Development Steps
-------------------------
Initialize interface device
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
First, initialize the peripherals corresponding to the LCD interface. Then, create the interface device and get its handle, the data type of the handle should be ``esp_lcd_panel_io_handle_t``. In this way, unified `interface common APIs <https://github.com/espressif/esp-idf/blob/release/v5.1/components/esp_lcd/include/esp_lcd_panel_io.h>`_ can be used for data transmission.
.. note::
For LCDs that only use the ``RGB`` interface, there is no need to create its interface device, please refer directly to :ref:`LCD Initialization <LCD_Initialization>`.
Different types of LCD interfaces require the use of different peripherals. The following describes the device initialization process of several common interfaces:
- :ref:`SPI LCD Introduction - Initialize interface device <spi_initialization_interface_device>`
- :ref:`RGB LCD Introduction - Initialize interface device <rgb_init_interface_device>`
- I80 LCD Introduction - Initialization interface device (to be updated)
- QSPI LCD Introduction - Initializing interface devices (to be updated)
For a more detailed description of this part, please refer to `ESP-IDF Programming Guide <https://docs.espressif.com/projects/esp-idf/en/latest/esp32s3/api-reference/peripherals/lcd.html>`_.
Initialize LCD device
^^^^^^^^^^^^^^^^^^^^^^^^
Since different models of LCD driver ICs may have different commands (registers) and parameters, and different interface types may also use different data formats and driving methods, here first need to use `interface common APIs <https:// github.com/espressif/esp-idf/blob/release/v5.1/components/esp_lcd/include/esp_lcd_panel_io.h>`_ for specific interfaces to port the target LCD driver, then create the LCD device and obtain the data type ``esp_lcd_panel_handle_t`` handle, ultimately enabling applications to pass unified `LCD common APIs <https://github.com/espressif/esp-idf/blob/release/v5.1/components/esp_lcd/include/esp_lcd_panel_ops.h>`_ to operate the LCD device.
.. note::
For LCDs that only use the ``RGB`` interface, there is no need to port its driver components. Please refer directly to :ref:`LCD Initialization <LCD_Initialization>`.
Before porting the driver component, please first try to obtain the components of the target LCD driver IC directly from :ref:`LCD driver component <LCD_Driver_Component>`. If the component does not exist, it can also be porting based on an existing component with the same interface type. LCD drivers with different interface types may have different porting principles. The following describes the porting methods of LCD driver components with several common interfaces:
- :ref:`SPI LCD Introduction - Porting driver components <spi_porting_driver_components>`
- :ref:`RGB LCD Introduction - Porting driver components <rgb_porting_driver_components>`
- I80 LCD Introduction - Porting driver component (to be updated)
- QSPI LCD Introduction - Porting driver component (to be updated)
.. _LCD_Initialization:
Then, the LCD initialization can be realized by using the driver component. The LCD initialization of several common interfaces is explained below:
- :ref:`SPI LCD Introduction - Initialize LCD device <spi_init_lcd>`
- :ref:`RGB LCD Introduction - Initialize LCD device <rgb_initialize_lcd>`
- I80 LCD Introduction - Initialize LCD device (To be updated)
- QSPI LCD Introduction - Initialize LCD device (To be updated)
For a more detailed description of this part, please refer to the `ESP-IDF Programming Guide <https://docs.espressif.com/projects/esp-idf/en/latest/esp32s3/api-reference/peripherals/lcd.html>`_.
Porting LVGL
^^^^^^^^^^^^^^^^^^^^^^^^^
(To be updated)
Design GUI
^^^^^^^^^^^^^^^^^^^^^^^^^
(To be updated)
Common Problems
-------------------------
The following lists some common issues encountered during the development of LCD applications. Please click on the issues to navigate and view the solutions.
* `How to use Arduino IDE to develop GUI for ESP series chips <https://docs.espressif.com/projects/esp-faq/en/latest/software-framework/peripherals/lcd.html#do-esp-series-development-boards-with-screens-support-gui-development-using-the-arduino-ide>`_
* `Maximum Resolution and Frame Rate Supported by ESP Series Chips for LCD <https://docs.espressif.com/projects/esp-faq/en/latest/software-framework/peripherals/lcd.html#what-is-the-maximum-resolution-supported-by-esp-lcd-what-is-the-corresponding-frame-rate>`_
* `How ESP series chips improve LCD rendering frame rate <https://docs.espressif.com/projects/esp-faq/en/latest/software-framework/peripherals/lcd.html#how-can-i-improve-the-display-frame-rate-of-lcd-screens>`_
* `How to increase the PCLK (refresh frame rate) of RGB LCD with ESP32-S3 <https://docs.espressif.com/projects/esp-faq/en/latest/software-framework/peripherals/lcd.html#how-can-i-increase-the-upper-limit-of-pclk-settings-on-esp32-s3-while-ensuring-normal-rgb-screen-display>`_
* `How to solve the problem of screen offset or flickering when driving RGB LCD with ESP32-S3 <https://docs.espressif.com/projects/esp-faq/en/latest/software-framework/peripherals/lcd.html#why-do-i-get-drift-overall-drift-of-the-display-when-esp32-s3-is-driving-an-rgb-lcd-screen>`_
* `How to configure ESP32-S3R8 PSRAM 120M Octal(DDR) <https://docs.espressif.com/projects/esp-faq/en/latest/software-framework/peripherals/lcd.html#how-can-i-enable-psram-120m-octal-ddr-on-esp32-s3r8>`_
Related Documents
-------------------------
* `ESP-IDF Programming Guide- LCD <https://docs.espressif.com/projects/esp-idf/en/latest/esp32s3/api-reference/peripherals/lcd.html>`_
* `ESP-FAQ - LCD <https://docs.espressif.com/projects/esp-faq/en/latest/software-framework/peripherals/lcd.html>`_
* `LVGL Documentation <https://docs.lvgl.io/8.3/>`_
|
import { configureStore, } from '@reduxjs/toolkit';
import { TypedUseSelectorHook, useDispatch, useSelector } from "react-redux"
import counterReducer from './countReducer';
import authReducer from './authReducer';
import globalReducer from './globalReducer';
const store = configureStore({
reducer: {
counter: counterReducer,
authReducer: authReducer,
globalReducer: globalReducer,
}
});
export default store;
// Infer the `RootState` and `AppDispatch` types from the store itself
export type I_ReduxRootState = ReturnType<typeof store.getState>;
// Inferred type: {posts: PostsState, comments: CommentsState, users: UsersState}
export type I_AppDispatch = typeof store.dispatch;
export type I_AppSelector = (state: I_ReduxRootState) => any;
export const useAppDispatch: () => I_AppDispatch = useDispatch;
export const useAppSelector: TypedUseSelectorHook<I_ReduxRootState> = useSelector
|
---- getBoard (chessgame, int)
--- 1. Retrieves initial chessboard position and positions after 5th and 10th half-moves.
SELECT
id,
getBoard(game, 0) as initial_position,
getBoard(game, 5) as position_after_5_half_moves,
getBoard(game, 10) as position_after_10_half_moves
FROM chessgames
WHERE id = 15;
--- 2. Most Common Board States for a Given Opening: What are the most common board states after 10 moves for games that start with the King's Pawn opening.
SELECT
getBoard(game, 10) AS board_state,
COUNT(*) AS frequency
FROM chessgames
WHERE getFirstMoves(game, 1) = '1.e4 '::chessgame
GROUP BY board_state
ORDER BY frequency DESC
LIMIT 10;
---- getFirstMoves(chessgame, int)
-- 1. Displaying full chessgame and truncated to first 2 and 3 full moves for each game
SELECT
id,
game as full_game,
getFirstMoves(game, 4) as first_2_moves_opening,
getFirstMoves(game, 6) as first_3_moves_opening
FROM chessgames;
-- 2. Displaying common openings by categorizing and counting the number of chess games by their opening sequence
SELECT
getFirstMoves(game, 6) as opening_sequence,
COUNT(*) as number_of_games
FROM chessgames
GROUP BY opening_sequence
ORDER BY number_of_games DESC LIMIT 5;
---- hasOpening(chessgame, chessgame)
-- 1. Check each game to determine if the game starts with '1.e4' opening, and providing bool result
SELECT
id,
hasOpening(game, '1.e4'::chessgame) as is_chess_opening
FROM chessgames
LIMIT 15;
-- 2. How many games started with the given sequence of moves?
SELECT count(*)
FROM chessgames
WHERE hasopening(game, '1.d4 Nf6 2.Nf3 g6');
--- hasBoard(chessgame, chessboard, int)
--- 1. Determining if a boardstate appears within the first 10 half-moves by joining chessgame and chessboard
SELECT
cg.id AS game_id,
cb.game_board,
hasBoard(cg.game, cb.game_board, 10) AS board_in_first_10_half_moves
FROM chessgames cg
JOIN chessboards cb ON cg.id = cb.game_id;
-- 2. How many games contain the given board state after 5th half moves?
SELECT count(*)
FROM chessgames
WHERE hasboard(game,
'rnbqkb1r/pp1ppppp/5n2/2p1P3/8/2P5/PP1P1PPP/RNBQKBNR b KQkq - 0 3', 5);
----Integration Testing - Queries
-- 1. Most Common Board States for Specific Openings: What are the most common board states after 8 moves between the Queen’s Gambit and the Sicilian Defense?
SELECT
getFirstMoves(game, 2) AS opening,
getBoard(game, 8) AS board_state,
COUNT(*) AS frequency
FROM chessgames
WHERE getFirstMoves(game, 2) IN ('1.d4 d5 2.c4 '::chessgame, '1.e4 c5 '::chessgame)
GROUP BY opening, board_state
ORDER BY opening, frequency DESC
LIMIT 5;
-- 2. Evolution of Board States in a Specific Opening Variation Objective: How do board states evolve in games with the Queen's Gambit?
SELECT
getBoard(game, 15) AS board_state_at_move_15,
COUNT(*) AS number_of_games
FROM chessgames
WHERE hasOpening(game, '1.d4 d5 2.c4 e6')
GROUP BY board_state_at_move_15
ORDER BY number_of_games DESC
LIMIT 10;
|
# frozen_string_literal: true
require "rails_helper"
require File.join(Rails.root, "spec/shared_contexts/eligibilities/magi_medicaid_application_data")
describe Eligibilities::AptcCsr::ApplyEligibilityOverrides do
let(:current_date) { Date.today }
let(:citizenship_immigration_status_information2) do
{ citizen_status: "not_lawfully_present_in_us",
is_lawful_presence_self_attested: false }
end
let(:override_rules) {::AcaEntities::MagiMedicaid::Types::EligibilityOverrideRule.values}
let(:member_determinations) do
[medicaid_and_chip_member_determination]
end
let(:medicaid_and_chip_member_determination) do
{
kind: 'Medicaid/CHIP Determination',
criteria_met: false,
determination_reasons: [],
eligibility_overrides: medicaid_chip_eligibility_overrides
}
end
let(:medicaid_chip_eligibility_overrides) do
override_rules = ::AcaEntities::MagiMedicaid::Types::EligibilityOverrideRule.values
override_rules.map do |rule|
{
override_rule: rule,
override_applied: false
}
end
end
include_context "setup magi_medicaid application with two applicants"
context "with applicant over 18 not lawfully present" do
let(:product_eligibility_determination2) do
{ is_ia_eligible: false,
is_medicaid_chip_eligible: false,
is_non_magi_medicaid_eligible: false,
is_totally_ineligible: false,
is_without_assistance: false,
is_magi_medicaid: false,
magi_medicaid_monthly_household_income: 6474.42,
medicaid_household_size: 1,
magi_medicaid_monthly_income_limit: 3760.67,
magi_as_percentage_of_fpl: 10.0,
magi_medicaid_category: "parent_caretaker",
magi_medicaid_ineligibility_reasons: ["Applicant did not meet citizenship/immigration requirements"],
member_determinations: member_determinations }
end
context "with applicant 21 or over" do
let(:input_application) do
app_params = mm_application_entity.to_h
app_params[:applicants].first[:age_of_applicant] = 21
app_params[:applicants].first[:citizenship_immigration_status_information] = citizenship_immigration_status_information2
app_params[:tax_households].first[:tax_household_members].first[:product_eligibility_determination] = product_eligibility_determination2
::AcaEntities::MagiMedicaid::Operations::InitializeApplication.new.call(app_params).success
end
let(:input_params) do
{ magi_medicaid_application: input_application }
end
before do
@result = subject.call(input_params)
end
it "should return success" do
expect(@result).to be_success
end
it "should return a MagiMedicaidApplication entity" do
expect(@result.success).to be_a(::AcaEntities::MagiMedicaid::Application)
end
it "should not return medicaid eligible" do
expect(@result.success.tax_households.first.tax_household_members.first.product_eligibility_determination.is_magi_medicaid).to eq(false)
end
end
context "with pregnant applicant 21 or over" do
let(:pregnancy_information2) do
{ is_pregnant: true,
is_post_partum_period: false,
expected_children_count: 1,
pregnancy_due_on: Date.today.next_month }
end
let(:input_application) do
app_params = mm_application_entity.to_h
app_params[:applicants].first[:pregnancy_information] = pregnancy_information2
app_params[:applicants].first[:age_of_applicant] = 21
app_params[:applicants].first[:citizenship_immigration_status_information] = citizenship_immigration_status_information2
app_params[:tax_households].first[:tax_household_members].first[:product_eligibility_determination] = product_eligibility_determination2
::AcaEntities::MagiMedicaid::Operations::InitializeApplication.new.call(app_params).success
end
let(:input_params) do
{ magi_medicaid_application: input_application }
end
before do
pregnant_override_flag = MedicaidGatewayRegistry[:eligibility_override].setting(:mitc_override_not_lawfully_present_pregnant)
allow(pregnant_override_flag).to receive(:item).and_return("true")
@result = subject.call(input_params)
end
it "should return success" do
expect(@result).to be_success
end
it "should return a MagiMedicaidApplication entity" do
expect(@result.success).to be_a(::AcaEntities::MagiMedicaid::Application)
end
it "should return medicaid eligible" do
expect(@result.success.tax_households.first.tax_household_members.first.product_eligibility_determination.is_magi_medicaid).to eq(true)
end
it "should return member_determination determination_reasons 'not_lawfully_present_pregnant'" do
member_determs = @result.success.tax_households.first.tax_household_members.first.product_eligibility_determination.member_determinations
expect(member_determs.first.determination_reasons.first).to eq('not_lawfully_present_pregnant')
end
context "eligibility_overrides" do
it "should accurately record the override rules applied" do
member_determs = @result.success.tax_households.first.tax_household_members.first.product_eligibility_determination.member_determinations
eligibility_overrides = member_determs.first.eligibility_overrides
pregnant_override = eligibility_overrides.detect { |override| override.override_rule == 'not_lawfully_present_pregnant' }
under_twenty_one_override = eligibility_overrides.detect { |override| override.override_rule == 'not_lawfully_present_under_twenty_one' }
chip_eligible_override = eligibility_overrides.detect { |override| override.override_rule == 'not_lawfully_present_chip_eligible' }
expect(pregnant_override.override_applied).to eq(true)
expect(under_twenty_one_override.override_applied).to eq(false)
expect(chip_eligible_override.override_applied).to eq(false)
end
end
end
context "with applicant 19-20 and not pregnant" do
let(:input_application) do
app_params = mm_application_entity.to_h
app_params[:applicants].first[:age_of_applicant] = 19
app_params[:applicants].first[:citizenship_immigration_status_information] = citizenship_immigration_status_information2
app_params[:tax_households].first[:tax_household_members].first[:product_eligibility_determination] = product_eligibility_determination2
::AcaEntities::MagiMedicaid::Operations::InitializeApplication.new.call(app_params).success
end
let(:input_params) do
{ magi_medicaid_application: input_application }
end
before do
under_twenty_one_override_flag = MedicaidGatewayRegistry[:eligibility_override].setting(:mitc_override_not_lawfully_present_under_twenty_one)
allow(under_twenty_one_override_flag).to receive(:item).and_return("true")
@result = subject.call(input_params)
end
it "should return medicaid eligible" do
expect(@result.success.tax_households.first.tax_household_members.first.product_eligibility_determination.is_magi_medicaid).to eq(true)
end
it "should return member_determination determination_reasons 'not_lawfully_present_under_twenty_one'" do
member_determs = @result.success.tax_households.first.tax_household_members.first.product_eligibility_determination.member_determinations
expect(member_determs.first.determination_reasons.first).to eq('not_lawfully_present_under_twenty_one')
end
end
end
context "with applicant not lawfully present and 18 or under" do
let(:product_eligibility_determination3) do
{ is_ia_eligible: false,
is_medicaid_chip_eligible: false,
is_non_magi_medicaid_eligible: false,
is_totally_ineligible: false,
is_without_assistance: false,
is_magi_medicaid: false,
magi_medicaid_monthly_household_income: 6474.42,
medicaid_household_size: 1,
magi_medicaid_monthly_income_limit: 3760.67,
magi_as_percentage_of_fpl: 10.0,
magi_medicaid_category: "parent_caretaker",
chip_ineligibility_reasons: ["Applicant did not meet citizenship/immigration requirements"],
magi_medicaid_ineligibility_reasons: magi_medicaid_ineligibility_reasons,
member_determinations: member_determinations }
end
let(:magi_medicaid_ineligibility_reasons) do
["Applicant did not meet citizenship/immigration requirements"]
end
let(:input_application) do
app_params = mm_application_entity.to_h
app_params[:applicants].first[:age_of_applicant] = 18
app_params[:applicants].first[:citizenship_immigration_status_information] = citizenship_immigration_status_information2
app_params[:tax_households].first[:tax_household_members].first[:product_eligibility_determination] = product_eligibility_determination3
::AcaEntities::MagiMedicaid::Operations::InitializeApplication.new.call(app_params).success
end
let(:input_params) do
{ magi_medicaid_application: input_application }
end
before do
chip_override_flag = MedicaidGatewayRegistry[:eligibility_override].setting(:mitc_override_not_lawfully_present_chip_eligible)
allow(chip_override_flag).to receive(:item).and_return("true")
pregnant_override_flag = MedicaidGatewayRegistry[:eligibility_override].setting(:mitc_override_not_lawfully_present_pregnant)
allow(pregnant_override_flag).to receive(:item).and_return("true")
@result = subject.call(input_params)
end
it "should return chip eligible" do
chip_eligible = @result.success.tax_households.first.tax_household_members.first.product_eligibility_determination.is_medicaid_chip_eligible
expect(chip_eligible).to eq(true)
end
it "should return member_determination determination_reasons 'not_lawfully_present_chip_eligible'" do
member_determs = @result.success.tax_households.first.tax_household_members.first.product_eligibility_determination.member_determinations
expect(member_determs.first.determination_reasons.first).to eq('not_lawfully_present_chip_eligible')
end
context "where applicant MAGI is above Medicaid threshold but NOT above CHIP threshold" do
let(:magi_medicaid_ineligibility_reasons) do
["Applicant did not meet citizenship/immigration requirements", "Applicant's MAGI above the threshold for category"]
end
it "should return chip eligible" do
chip_eligible = @result.success.tax_households.first.tax_household_members.first.product_eligibility_determination.is_medicaid_chip_eligible
expect(chip_eligible).to eq(true)
end
it "should return member_determination determination_reasons 'not_lawfully_present_chip_eligible'" do
member_determs = @result.success.tax_households.first.tax_household_members.first.product_eligibility_determination.member_determinations
expect(member_determs.first.determination_reasons.first).to eq('not_lawfully_present_chip_eligible')
end
end
context "and pregnant" do
let(:pregnancy_information2) do
{ is_pregnant: true,
is_post_partum_period: false,
expected_children_count: 1,
pregnancy_due_on: Date.today.next_month }
end
let(:input_application) do
app_params = mm_application_entity.to_h
app_params[:applicants].first[:pregnancy_information] = pregnancy_information2
app_params[:applicants].first[:age_of_applicant] = 18
app_params[:applicants].first[:citizenship_immigration_status_information] = citizenship_immigration_status_information2
app_params[:tax_households].first[:tax_household_members].first[:product_eligibility_determination] = product_eligibility_determination3
::AcaEntities::MagiMedicaid::Operations::InitializeApplication.new.call(app_params).success
end
let(:input_params) do
{ magi_medicaid_application: input_application }
end
before do
@result = subject.call(input_params)
end
it "should return success" do
expect(@result).to be_success
end
it "should return a MagiMedicaidApplication entity" do
expect(@result.success).to be_a(::AcaEntities::MagiMedicaid::Application)
end
it "should return chip eligible" do
member = @result.success.tax_households.first.tax_household_members.first
expect(member.product_eligibility_determination.is_medicaid_chip_eligible).to eq(true)
end
it "should return member_determination with multiple determination_reasons" do
member_determs = @result.success.tax_households.first.tax_household_members.first.product_eligibility_determination.member_determinations
expected_array = ['not_lawfully_present_pregnant', 'not_lawfully_present_chip_eligible']
expect(member_determs.first.determination_reasons).to match_array(expected_array)
end
end
end
end
|
package edu.uga.cs.attendancetaker;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.QueryDocumentSnapshot;
import com.google.firebase.firestore.QuerySnapshot;
import java.util.ArrayList;
public class DeleteBarcodeActivity extends AppCompatActivity implements MyRecyclerViewAdapter.ItemClickListener {
private static final String TAG = "GoogleActivity";
private FirebaseAuth mAuth;
private GoogleSignInClient mGoogleSignInClient;
MyRecyclerViewAdapter adapter;
ArrayList<String> crns;
String selectedCrn;
Button home;
Button signOut;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_delete_barcode);
home = findViewById(R.id.delete_barcode_home_button);
signOut = findViewById(R.id.delete_barcode_sign_out_button);
home.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(DeleteBarcodeActivity.this, ProfessorMainScreenActivity.class);
startActivity(intent);
}
});
signOut.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
signOut();
}
});
getCrns();
// Configure Google Sign In
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build();
mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
// Initialize Firebase Auth
mAuth = FirebaseAuth.getInstance();
}
private void signOut() {
// Firebase sign out
mAuth.signOut();
// Google sign out
mGoogleSignInClient.signOut().addOnCompleteListener(this,
new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
Intent intent = new Intent(DeleteBarcodeActivity.this, SplashScreenActivity.class);
startActivity(intent);
}
});
}
private void getCrns() {
crns = new ArrayList<>();
// Access a Cloud Firestore instance from your Activity
FirebaseFirestore db = FirebaseFirestore.getInstance();
// Initialize Firebase Auth
mAuth = FirebaseAuth.getInstance();
db.collection("classes")
.whereEqualTo("professor", mAuth.getCurrentUser().getUid())
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (QueryDocumentSnapshot document : task.getResult()) {
Log.d(TAG, document.getId() + " => " + document.getData());
crns.add(document.getId());
}
setUpRecyclerView();
} else {
Log.d(TAG, "Error getting documents: ", task.getException());
}
}
});
}
private void setUpRecyclerView() {
RecyclerView recyclerView = findViewById(R.id.delete_barcode_list);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
adapter = new MyRecyclerViewAdapter(getApplicationContext(), crns);
adapter.setClickListener(this);
recyclerView.setAdapter(adapter);
}
@Override
public void onItemClick(View view, int position) {
selectedCrn = adapter.getItem(position);
// Access a Cloud Firestore instance from your Activity
FirebaseFirestore db = FirebaseFirestore.getInstance();
DocumentReference docRef = db.collection("classes").document(selectedCrn);
docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
@Override
public void onComplete(@NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
if (document.exists()) {
Log.d(TAG, "DocumentSnapshot data: " + document.getData());
deleteClass(selectedCrn);
Intent intent = new Intent(DeleteBarcodeActivity.this, ProfessorMainScreenActivity.class);
startActivity(intent);
} else {
Log.d(TAG, "No such document");
}
} else {
Log.d(TAG, "get failed with ", task.getException());
}
}
});
}
private void deleteClass(String selectedCrn) {
// Access a Cloud Firestore instance from your Activity
FirebaseFirestore db = FirebaseFirestore.getInstance();
db.collection("classes").document(selectedCrn)
.delete()
.addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
Log.d(TAG, "DocumentSnapshot successfully deleted!");
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Log.w(TAG, "Error deleting document", e);
}
});
}
}
|
{
// OOP - Class
class Animal {
// name: string;
// species: string;
// sounds: string;
// constructor(name: string, species: string, sounds: string){
// this.name = name;
// this.species = species;
// this.sounds = sounds;
// };
/*---------------------
Parameter Property
---------------------- */
constructor(public name: string, public species: string, public sounds: string){}
makeSounds() {
console.log(`The ${this.name} says: ${this.sounds}`);
}
}
const dog = new Animal('Germen shepard', 'Dog', 'Ghew Ghew');
const cat = new Animal('Billi', 'Cat', 'mew mew');
cat.makeSounds();
//
}
|
from rest_framework import serializers
from .models import *
from items.models import *
from bodega.models import *
class ItemEnInventoSerializer(serializers.ModelSerializer):
item = serializers.PrimaryKeyRelatedField(queryset=Item.objects.all())
item_nombre = serializers.SerializerMethodField()
class Meta:
model = ItemEnInvento
fields = '__all__'
def get_item_nombre(self, obj):
return obj.item.nombre if obj.item else None
class InventoSerializer(serializers.ModelSerializer):
items = ItemEnInventoSerializer(read_only=True, many=True, required=False, source='itemeninvento_set')
stock_bodega = serializers.SerializerMethodField(read_only=True)
class Meta:
model = Invento
fields = '__all__'
def get_stock_bodega(self, obj):
try:
stock = StockInventoBodega.objects.get(invento = obj)
return stock.cantidad
except:
return str('sin stock')
|
function Watcher(vm, expOrFn, cb) {
this.$cb = cb;
this.$vm = vm;
this.expOrFn = expOrFn;
this.depIds = {};
if (typeof expOrFn === 'function') {
this.getter = expOrFn;
} else {
this.getter = this.parseGetter(expOrFn)
}
this.value = this.get();
}
Watcher.prototype = {
update: function () {
this.run();
},
run: function () {
const value = this.get();//变化后的值
const oldVal = this.value;//变化前的值
if (value !== oldVal) {
this.value = value;
this.$cb.call(this.$vm, value, oldVal);
}
},
addDep: function (dep) {
// 1. 每次调用run()的时候会触发相应属性的getter
// getter里面会触发dep.depend(),继而触发这里的addDep
// 2. 假如相应属性的dep.id已经在当前watcher的depIds里,说明不是一个新的属性,仅仅是改变了其值而已
// 则不需要将当前watcher添加到该属性的dep里
// 3. 假如相应属性是新的属性,则将当前watcher添加到新属性的dep里
// 如通过 vm.child = {name: 'a'} 改变了 child.name 的值,child.name 就是个新属性
// 则需要将当前watcher(child.name)加入到新的 child.name 的dep里
// 因为此时 child.name 是个新值,之前的 setter、dep 都已经失效,如果不把 watcher 加入到新的 child.name 的dep中
// 通过 child.name = xxx 赋值的时候,对应的 watcher 就收不到通知,等于失效了
// 4. 每个子属性的watcher在添加到子属性的dep的同时,也会添加到父属性的dep
// 监听子属性的同时监听父属性的变更,这样,父属性改变时,子属性的watcher也能收到通知进行update
// 这一步是在 this.get() --> this.getVMVal() 里面完成,forEach时会从父级开始取值,间接调用了它的getter
// 触发了addDep(), 在整个forEach过程,当前watcher都会加入到每个父级过程属性的dep
// 例如:当前watcher的是'child.child.name', 那么child, child.child, child.child.name这三个属性的dep都会加入当前watcher
if (!this.depIds.hasOwnProperty(dep.id)) {
dep.addSub(this);
this.depIds[dep.id] = dep;
}
console.log(dep.key,this.depIds)
},
get: function () {
Dep.target = this;
const value = this.getter.call(this.$vm, this.$vm);//这里获取值的时候会触发observe中的get,导致收集依赖
Dep.target = null;
return value;
},
parseGetter: function (exp) {
if (/[^\w.$]/.test(exp)) return;//数字 字母 下划线 汉字
const exps = exp.split('.')
return function (obj) {
for (let i = 0; i < exps.length; i++) {
if (!obj) return
obj = obj[exps[i]]
}
return obj
}
}
};
|
<template>
<div
id="code-editor"
ref="condeEditorRef"
style="min-height: 800px; height: 90vh"
/>
</template>
<script setup lang="ts">
import * as monaco from "monaco-editor";
import { defineProps, onMounted, ref, toRaw, watch, withDefaults } from "vue";
/**
* 定义组件属性类型
*/
interface Props {
value: string;
language?: string;
handleChange: (v: string) => void;
}
const props = withDefaults(defineProps<Props>(), {
value: () => "",
language: () => "java",
handleChange: (v: string) => {
console.log(v);
},
});
const condeEditorRef = ref();
const codeEditor = ref();
const value = ref("hello world");
watch(
() => props.language,
() => {
if (codeEditor.value) {
monaco.editor.setModelLanguage(
toRaw(codeEditor.value).getModel(),
props.language
);
}
}
);
onMounted(() => {
if (!condeEditorRef.value) return;
codeEditor.value = monaco.editor.create(condeEditorRef.value, {
value: props.value,
language: props.language,
automaticLayout: true,
minimap: {
enabled: true,
},
// lineNumbers: "off",
// roundedSelection: false,
// scrollBeyondLastLine: false,
colorDecorators: true,
readOnly: false,
theme: "vs-dark",
});
codeEditor.value.onDidChangeModelContent(() => {
props.handleChange(toRaw(codeEditor.value).getValue());
});
});
// Hover on each property to see its docs!
</script>
|
package com.example.fileapp;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
public class MainActivity extends AppCompatActivity {
String FILE_NAME = "skpsu.txt";
EditText editText;
Button savebtn,loadbtn,crt;
int count;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText=findViewById(R.id.edit_text);
savebtn=(Button)findViewById(R.id.btn_save);
savebtn.setOnClickListener(this::save);
loadbtn=(Button)findViewById(R.id.btn_save2);
loadbtn.setOnClickListener(this::load);
crt=findViewById(R.id.btn_create);
crt.setOnClickListener(this::create);
}
public void save(View v){
if(count==0){
Toast.makeText(getApplicationContext(),"create file",Toast.LENGTH_LONG).show();
}
else{
String text = editText.getText().toString();
FileOutputStream fos = null;
try {
fos = openFileOutput(FILE_NAME,MODE_PRIVATE);
fos.write(text.getBytes());
editText.getText().clear();
Toast.makeText(this,"Data is Saved in"+getFilesDir(),Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(fos!=null){
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
public void load(View v){
if(count==0){
Toast.makeText(this,"create file",Toast.LENGTH_LONG).show();
}
FileInputStream fis = null;
try {
fis = openFileInput(FILE_NAME);
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
String text;
while ((text = br.readLine()) != null){
sb.append(text).append("\n");
editText.setText(sb.toString());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
if(fis!=null){
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public void create(View v){
count = 1;
Toast.makeText(getApplicationContext(),"file created successfully",Toast.LENGTH_LONG).show();
}
}
|
@extends('layouts.app')
@section('content')
<div class="container">
<div class="row">
<div class="col-md-12 col-md-offset-2">
<div class="panel panel-default bg-white">
<div class="panel-heading">
<img alt="Dalvkot HRMS" src="{{ asset('profile_picture/1569380903.png') }}" class="img-responsive">
</div>
<div class="panel-body">
<form class="form-horizontal" method="POST" action="{{ route('login') }}" style="padding-bottom: 10px;">
{{ csrf_field() }}
<div class="form-group{{ $errors->has('email') ? ' has-error' : '' }}">
<label for="email" class="col-md-12 control-label">{{ __('E-Mail Address') }}</label>
<div class="col-md-12">
<input id="email" type="email" class="form-control" name="email" value="{{ old('email') }}" required autofocus>
@if ($errors->has('email'))
<span class="help-block">
<strong style="color: red;">{{ $errors->first('email') }}</strong>
</span>
@endif
</div>
</div>
<div class="form-group{{ $errors->has('password') ? ' has-error' : '' }}">
<label for="password" class="col-md-4 control-label">{{ __('Password') }}</label>
<div class="col-md-12">
<input id="password" type="password" class="form-control" name="password" required>
@if ($errors->has('password'))
<span class="help-block">
<strong style="color: red;">{{ $errors->first('password') }}</strong>
</span>
@endif
</div>
</div>
<div class="form-group">
<div class="col-md-12 col-md-offset-4">
<button type="submit" class="btn btn-primary">
{{ __('Login') }}
</button>
<a href="{{ route('password.request') }}" class="float-right">
{{ __('Forgot Your Password?') }}
</a>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
@endsection
|
# Vega UI 🌌
Vue 3 UI library for easy development.
> **WARNING!**\
> This package is in the early stages of development. Use it at your own risk.
## Table of contents
- 🚀 [Getting Started](#install)
- 🏠 [Layout component](#vegalayout)
- 🛠 [Props](#props)
- 🛠 [Slots](#slots)
- 🎫 [Sidebar component](#vegasidebar)
- 🛠 [Props](#props-1)
- 🛠 [Slots](#slots-1)
- 🔗 [Sidebar Toggle component](#vegasidebartoggle)
- 🛠 [Props](#props-2)
- 🛠 [Slots](#slots-2)
- 🐠 [Lorem Ipsum component](#vegaloremipsum)
# Install
```shell
npm install vega-ui
```
# Import
Full Import
```js
// main.ts
import { createApp } from 'vue'
import App from './App.vue'
import VegaUI from 'vega-ui'
import 'vega-ui/dist/style.css'
const app = createApp(App)
app.use(VegaUI)
app.mount('#app')
```
Manually import
```vue
<template>
<div style="height: 100vh">
<VegaLayout>
<VegaLoremIpsum />
</VegaLayout>
</div>
</template>
<script setup>
import { VegaLayout } from 'vega-ui'
import 'vega-ui/dist/style.css'
</script>
```
> **Note**\
> styles.css very important. Don't forget import it!
# VegaLayout
Page layout component.
Simple example:
```vue
<template>
<div style="height: 100vh">
<VegaLayout
:header-first="true"
header-background="#005689"
aside-left-width="350px"
aside-left-border="#dcdfe6"
aside-left-background="#fff"
content-background="#ececec"
>
<template #header>
<div></div>
</template>
<template #aside-left>
<div></div>
</template>
<template #default>
<VegaLoremIpsum />
</template>
</VegaLayout>
</div>
</template>
<script setup>
import { VegaLayout } from 'vega-ui'
import 'vega-ui/dist/style.css'
</script>
```
> **Note**\
> If you want to create a full-page layout with a fixed header, you need to set `height: 100vh` for the parent DOM element.\
With this setup, only the content inside `<template #default>` will be scrollable.
Example above will give you a following structure:
```
+-------------------------------------+
| HEADER |
| |
|------------------------------------++
| | ||
| ASIDE | CONTENT ||
| | ||
| | ||
| | ||
| | ||
| | scroll ------->||
+------------------------------------++
```
Layouts can be nested:
```vue
<div style="height: 100vh">
<VegaLayout
:header-first="true"
header-background="#005689"
aside-left-width="350px"
aside-left-border="#dcdfe6"
aside-left-background="#fff"
content-background="#ececec"
>
<template #header>
<div></div>
</template>
<template #aside-left>
<div></div>
</template>
<template #default>
<VegaLayout
header-border="#dcdfe6"
aside-right-width="350px"
aside-right-border="#dcdfe6"
>
<VegaLoremIpsum />
</VegaLayout>
</template>
</VegaLayout>
</div>
```
Example above will give you a following structure:
```
+-----------------------------------------------------------------+
| HEADER 1 |
| |
|---------+-------------------------------------------------------|
| ASIDE 1 | HEADER 2 | ASIDE 2 |
| | | |
| |---------------------------------------------+ |
| | CONTENT 2 | |
| | | |
| | | |
| | | |
| | | |
| | | |
| | | |
+---------|---------------------------------------------|---------+
```
## Props
### content-background
Content background. You can pass a string in HEX, RGB format. Default value is 'none'.
Example
```vue
<VegaLayout content-background="#005689" />
```
### header-height
Header height. You can pass a string with valid css value. Default value is '80px'.
Example
```vue
<VegaLayout header-height="100px" />
```
### header-border
Header border color. You can pass a string in HEX, RGB format. Default value is 'none'.
Example
```vue
<VegaLayout header-border="#005689" />
```
### header-background
Header background color. You can pass a string in HEX, RGB format. Default value is 'none'.
Example
```vue
<VegaLayout header-background="#fff" />
```
### header-shadow
Header shadow. You can pass any valid css [box-shadow](box-shadow) value as string. Default value is 'none'.
Example
```vue
<VegaLayout header-shadow="0 10px 20px #0000000d" />
```
### header-padding
Header left and right padding. You can pass a string with valid css value. Default value is '2rem'.
Example
```vue
<VegaLayout header-padding="40px" />
```
### aside-left-width
Left aside width. You can pass a string with valid css value. Default value is 'initial'.
Example
```vue
<VegaLayout aside-left-width="200px" />
```
### aside-left-border
Left aside border color. You can pass a string in HEX, RGB format. Default value is 'none'.
Example
```vue
<VegaLayout aside-left-border="#005689" />
```
### aside-left-background
Left aside background. You can pass a string in HEX, RGB format. Default value is 'none'.
Example
```vue
<VegaLayout aside-left-background="#fff" />
```
### aside-right-width
Right aside width. You can pass a string with valid css value. Default value is 'initial'.
Example
```vue
<VegaLayout aside-right-width="350px" />
```
### aside-right-border
Right aside border color. You can pass a string in HEX, RGB format. Default value is 'none'.
Example
```vue
<VegaLayout aside-right-border="#005689" />
```
### aside-right-background
Right aside background. You can pass a string in HEX, RGB format. Default value is 'none'.
Example
```vue
<VegaLayout aside-right-background="#fff" />
```
### header-first
Header must be on top of asides. Default value is 'false'.
Example
```vue
<VegaLayout header-first />
```
## Slots
### header
Header custom content
Example
```vue
<VegaLayout>
<template #header>
<div>Hello World!</div>
</template>
</VegaLayout>
```
### aside-left
Left aside custom content
Example
```vue
<VegaLayout>
<template #aside-left>
<ul>
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>
</template>
</VegaLayout>
```
### aside-right
Right aside custom content
Example
```vue
<VegaLayout>
<template #aside-right>
<ul>
<li>Neil Armstrong</li>
<li>Alan Bean</li>
<li>Peter Conrad</li>
<li>Edgar Mitchell</li>
<li>Alan Shepard</li>
</ul>
</template>
</VegaLayout>
```
### default
Content on page
Example
```vue
<VegaLayout>
<div>Bunch of awesome content</div>
</VegaLayout>
```
# VegaSidebar
Sidebar with state memory.\
Component out of the box provide a hide/show button.
By default, it is places in top right corner and uses vega icon, but you can override this.\
In addition, the sidebar saves its show/hide state in local storage, so when page reloads, it will be in same state as before.
Simple example:
```vue
<template>
<div style="height: 100vh">
<VegaLayout>
<template #aside-left>
<VegaSidebar name="my-sidebar" title="SIDEBAR TITLE" />
</template>
<template #default>
<VegaLoremIpsum />
</template>
</VegaLayout>
</div>
</template>
<script setup>
import { VegaLayout, VegaSidebar } from 'vega-ui'
import 'vega-ui/dist/style.css'
</script>
```
## Props
### name
Name of sidebar. Used as a key to store state of sidebar in local storage. You can pass any string. Default value is 'vega-sidebar'.
Example
```vue
<VegaSidebar name="left-sidebar-1" />
```
### title
Sidebar title. You can pass any string. Default value is ''.
Example
```vue
<VegaSidebar title="My title" />
```
### width
Sidebar width in opened state. You can pass a string with valid css value. Default value is '350px'.
Example
```vue
<VegaSidebar width="300px" />
```
### width-min
Sidebar width in closed state. You can pass a string with valid css value. Default value is 'calc(2rem * 2 + 24px)'.
Example
```vue
<VegaSidebar width-min="0" />
```
### header-height
Sidebar header height. You can pass a string with valid css value. Default value is '80px'.
Example
```vue
<VegaSidebar header-height="100px" />
```
### padding
Sidebar left and right padding. You can pass a string with valid css value. Default value is '2rem'.
Example
```vue
<VegaSidebar padding="20px" />
```
### gap
Gap between header and content. You can pass a string with valid css value. Default value is '16px'.
Example
```vue
<VegaSidebar gap="0" />
```
### background
Sidebar background. You can pass a string in HEX, RGB format. Default value is 'none'.
Example
```vue
<VegaSidebar background="#fff" />
```
## Slots
### default
Sidebar content
Example
```vue
<VegaSidebar>
<div>My sidebar content</div>
</VegaSidebar>
```
### header
Header custom content.
Example
```vue
<VegaSidebar>
<template #header>
<div>SIDEBAR HEADER</div>
</template>
</VegaSidebar>
```
### title
Custom title.
Example
```vue
<VegaSidebar>
<template #title>
<div>Custom title</div>
</template>
</VegaSidebar>
```
### toggle-button
Custom toggle button.
Example
```vue
<VegaSidebar>
<template #toggle-button>
<button>click me!</button>
</template>
</VegaSidebar>
```
# VegaSidebarToggle
Button to control the state of the sidebar. Associates with a specific sidebar using the "name" prop.
## Props
### name
Name of associated sidebar. Used as a key to store state of sidebar in local storage. You can pass any string. Default value is 'vega-sidebar'.
Example:
```vue
<VegaSidebarToggle name="left-sidebar-1" />
```
### show-if
Show toggle button only when associated sidebar is in certain state.\
If you want to show toggle button only when sidebar is closed, set `show-if` to "false"".\
Default value is "null"
Example:
```vue
<VegaSidebarToggle :show-if="false" />
```
### also-close
Automatically close sidebars with given names after changing the state of main associated sidebar.
```vue
<VegaSidebarToggle name="left-sidebar-1" :also-close="['right-sidebar-1', 'right-sidebar-2']" />
```
## Slots
### default
Displayed button content. By default contains vega arrow icon.
Example:
```vue
<VegaSidebarToggle name="may-sidebar">
<CustomIcon />
</VegaSidebarToggle>
```
# VegaLoremIpsum
Simple content placeholder.
Example
```vue
<VegaLoremIpsum />
```
|
ary = [5,7,9,0,3,1,6,2,4,8]
## 조금더 직관적인 코드
def quick_srt(ary):
if len(ary) <=1 :## 리스트 데이터의 개수가 1개 이하면 종료
return ary
pv = ary[0] # 첫번째 요소 피봇 설정
tail = ary[1:] # 피봇을 제외한 나머지를 꼬리로 설정
left_side = [x for x in tail if x <= pv] # 피봇보다 작은 데이터를 모두 왼쪽으로
right_side = [x for x in tail if x > pv] # 피봇보다 큰 데이터를 오른쪽으로
return quick_srt(left_side) + [pv] + quick_srt(right_side)
## 왼쪽, 피봇, 오른쪽 을 합침
## 왼쪽은 왼쪽끼리 다시 퀵정렬, 오른쪽은 오른쪽만 퀵정렬
## 계속 리스트를 더하고 더하면 정렬된 데이터가 반환됨
print(quick_srt(ary))
|
<?php
use App\Http\Controllers\AdminController;
use App\Http\Controllers\StudentController;
use App\Http\Controllers\AuthController;
use App\Http\Controllers\TeacherController;
use App\Models\Student;
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider and all of them will
| be assigned to the "web" middleware group. Make something great!
|
*/
Route::get('/', function () {
return view('index');
})->name('home');
Route::get('/login', [AuthController::class, 'login'])->name('login');
Route::post('/login', [AuthController::class, 'loginPost'])->name('login.post');
Route::get('/logout', [AuthController::class, 'logout'])->name('logout');
Route::get('/teacher_registration', [AuthController::class, 'teacherRegistration'])->name('teacherRegistration');
Route::post('/teacher_registration', [AuthController::class, 'teacherRegistrationPost'])->name('teacherRegistration.post');
Route::get('/student_registration', [AuthController::class, 'studentRegistration'])->name('studentRegistration');
Route::post('/student_registration', [AuthController::class, 'studentRegistrationPost'])->name('studentRegistration.post');
Route::group(['middleware' => 'auth'], function () {
//Admin Routes:
Route::get('/admin/sessions', [AdminController::class, 'session_list'])->name('adminSessionList');
Route::get('/admin/sessions/create', [AdminController::class, 'session_create'])->name('adminSessionCreate');
Route::post('/admin/sessions/create', [AdminController::class, 'session_createPost'])->name('adminSessionCreate.post');
Route::delete('/admin/sessions/{id}/delete', [AdminController::class, 'session_delete'])->name('adminSessionDelete');
Route::get('/admin/sessions/{id}/edit', [AdminController::class, 'session_edit'])->name('adminSessionEdit');
Route::post('/admin/sessions/{id}/edit', [AdminController::class, 'session_editPost'])->name('adminSessionEdit.post');
Route::get('/admin/questions', [AdminController::class, 'question_list'])->name('adminQuestionList');
Route::get('/admin/users', [AdminController::class, 'user_list'])->name('adminUserView');
Route::get('/admin/users/{id}/edit', [AdminController::class, 'user_edit'])->name('userEdit');
Route::post('/admin/users/{id}/edit', [AdminController::class, 'user_editPost'])->name('adminUserEdit.post');
Route::get('/admin/sessions_with_students', [AdminController::class, 'session_list_students'])->name('adminShowStudentsList');
Route::get('/admin/sessions_with_students/{id}', [AdminController::class, 'session_show_students'])->name('adminShowStudents');
Route::get('/admin/sessions_with_students/{sessionID}/unenroll/{studentID}', [AdminController::class, 'session_student_unenroll'])->name('studentUnenroll');
//Student Routes:
Route::get('/student/sessions', [StudentController::class, 'session_list'])->name('studentSessionList');
Route::get('/student/enrolledsessions', [StudentController::class, 'enrolled_session_list'])->name('studentEnrolledSessionList');
Route::post('/student/sessions/{id}/enroll', [StudentController::class, 'session_enroll'])->name('studentSessionEnroll');
Route::post('/student/sessions/{id}/Unenroll', [StudentController::class, 'session_Unenroll'])->name('studentSessionUnEnroll');
Route::get('/student/sessions/{id}/dashboard', [StudentController::class, 'session_dashboard'])->name('studentSessionDashboard');
Route::get('/student/sessions/{id}/post-question', [StudentController::class, 'session_post_question'])->name('studentSessionPostQuestion');
Route::post('/student/sessions/{id}/post-question', [StudentController::class, 'session_post_question_post'])->name('studentSessionPostQuestion.post');
Route::get('/student/sessions/{sessionID}/see-answer/{questionID}', [StudentController::class, 'session_see_answer'])->name('studentSessionSeeAnswer');
//Teacher Routes
Route::get('/teacher/sessions', [TeacherController::class, 'session_list'])->name('teacherSessionList');
Route::get('/teacher/enrolledsessions', [TeacherController::class, 'enrolled_session_list'])->name('teacherEnrolledSessionList');
Route::post('/teacher/sessions/{id}/enroll', [TeacherController::class, 'session_enroll'])->name('teacherSessionEnroll');
Route::post('/teacher/sessions/{id}/Unenroll', [TeacherController::class, 'session_Unenroll'])->name('teacherSessionUnEnroll');
Route::get('/teacher/sessions/{id}/dashboard', [TeacherController::class, 'session_dashboard'])->name('teacherSessionDashboard');
Route::get('/teacher/sessions/{sessionID}/view-question/{questionID}', [TeacherController::class, 'session_answer_question'])->name('teacherSessionAnswerQuestion');
Route::get('/teacher/sessions/{sessionID}/edit-question/{questionID}', [TeacherController::class, 'session_update_answer'])->name('teacherSessionUpdateAnswer');
Route::post('/teacher/sessions/{sessionID}/answer-question/{questionID}', [TeacherController::class, 'session_answer_question_post'])->name('teacherSessionAnswerQuestion.post');
//Chart Visuals
Route::get('/admin/statistics/statSessionList', [AdminController::class, 'session_list_stat'])->name('adminStat');
Route::get('/admin/statistics/{id}/statSessionCharts', [AdminController::class, 'adminCharts'])->name('adminCharts');
});
|
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>角色管理</title>
<#include "../common/link.ftl">
<%--左右移动的按钮--%>
<script>
function moveAll(src,target) {
//事件中获取到左边'selfRoles'的全部的option移动'allRoles'
$("."+target).append($("."+src+">option"))
}
function moveSelected(src,target) {
//事件中获取到左边'selfRoles'的全部的option移动'allRoles'
$("."+target).append($("."+src+">option:selected"))
}
//这个放在页面加载完成,是因为现在不是点击事件是先加载完成之后获取他的id
$(function () {
$('#btn_submit').click(function () {
//设置右边的下拉框在提交之前自动帮我们选中
$('.selfPermissions >option').prop('selected',true);
$('#editForm').submit();//提交表单
})
//去重
//解决:页面加载完,拿左边两边的option 对比,遍历左边每个角色,若已经在右边列表内,则需要删除。
//1.把已有的角色id放入一个数组中(右边)
var ids = [];
$(".selfPermissions > option").each(function (i, ele) {
ids.push( $(ele).val());
})
//2.遍历所有的角色(左边)
$(".allPermissions > option").each(function (i, ele) {
//3.判断是否存在ids数组中,如果是就删除掉自己
var id = $(ele).val();
if($.inArray(id,ids)!=-1){
$(ele).remove();
}
})
})
</script>
</head>
<body class="hold-transition skin-blue sidebar-mini">
<div class="wrapper">
<#include "../common/navbar.ftl">
<!--菜单回显-->
<#--<c:set var="currentMenu" value="role"/>-->
<#assign currentMenu="role"/>
<#include "../common/menu.ftl">
<div class="content-wrapper">
<section class="content-header">
<h1>角色编辑</h1>
</section>
<section class="content">
<div class="box">
<form class="form-horizontal" action="/role/saveOrUpdate.do" method="post" id="editForm">
<input type="hidden" value="${(role.id)!}" name="id">
<div class="form-group" style="margin-top: 10px;">
<label for="name" class="col-sm-2 control-label">角色名称:</label>
<div class="col-sm-6">
<input type="text" class="form-control" id="name" name="name" value="${(role.name)!}" placeholder="请输入角色名称">
</div>
</div>
<div class="form-group">
<label for="sn" class="col-sm-2 control-label">角色编号:</label>
<div class="col-sm-6">
<input type="text" class="form-control" id="sn" name="sn" value="${(role.sn)!}" placeholder="请输入角色编号">
</div>
</div>
<div class="form-group " id="role">
<label for="role" class="col-sm-2 control-label">分配权限:</label><br/>
<div class="row" style="margin-top: 10px">
<div class="col-sm-2 col-sm-offset-2">
<select multiple class="form-control allPermissions" size="15">
<#--<c:forEach items="${permissions}" var="permission">-->
<#list permissions as permission>
<option value="${permission.id!}">${permission.name!}</option>
</#list>
<#--</c:forEach>-->
</select>
</div>
<div class="col-sm-1" style="margin-top: 60px;" align="center">
<div>
<a type="button" class="btn btn-primary" style="margin-top: 10px" title="右移动"
onclick="moveSelected('allPermissions', 'selfPermissions')">
<span class="glyphicon glyphicon-menu-right"></span>
</a>
</div>
<div>
<a type="button" class="btn btn-primary " style="margin-top: 10px" title="左移动"
onclick="moveSelected('selfPermissions', 'allPermissions')">
<span class="glyphicon glyphicon-menu-left"></span>
</a>
</div>
<div>
<a type="button" class="btn btn-primary " style="margin-top: 10px" title="全右移动"
onclick="moveAll('allPermissions', 'selfPermissions')">
<span class="glyphicon glyphicon-forward"></span>
</a>
</div>
<div>
<a type="button" class="btn btn-primary " style="margin-top: 10px" title="全左移动"
onclick="moveAll('selfPermissions', 'allPermissions')">
<span class="glyphicon glyphicon-backward"></span>
</a>
</div>
</div>
<div class="col-sm-2">
<select multiple class="form-control selfPermissions" size="15" name="ids">
<#--<c:forEach items="${role.permissions}" var="permission">-->
<#list (role.permissions)! as permission>
<option value="${permission.id!}">${permission.name!}</option>
</#list>
<#--</c:forEach>-->
</select>
</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-1 col-sm-6">
<button id="btn_submit" type="button" class="btn btn-primary">保存</button>
<button type="reset" class="btn btn-danger">重置</button>
</div>
</div>
</form>
</div>
</section>
</div>
<#include "../common/footer.ftl">
</div>
</body>
</html>
|
package hh.getData.guideline.FunderSource;
import lombok.Data;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.stream.Collectors;
@Data
@RestController
@CrossOrigin
@RequestMapping("/funderSource/")
public class FunderSourceController {
private final FunderSourceService funderSourceService;
@GetMapping("getAll/")
public ResponseEntity<List<FunderSourceDto>> getAll() {
try {
List<FunderSource> funderSources = funderSourceService.getAllFunderSources();
List<FunderSourceDto> funderSourceDto = funderSources.stream()
.map(FunderSourceDto::from)
.collect(Collectors.toList());
return new ResponseEntity<>(funderSourceDto, HttpStatus.OK);
} catch (Exception e) {
return new ResponseEntity<>(null, HttpStatus.NOT_FOUND);
}
}
@GetMapping("getById/id/{id}")
public ResponseEntity<FunderSourceDto> getFunderSourceById(@PathVariable Long id) {
try {
FunderSource funderSource = funderSourceService.getFunderSourceById(id);
if (funderSource != null) {
return new ResponseEntity<>(FunderSourceDto.from(funderSource), HttpStatus.OK);
} else {
return new ResponseEntity<>(null, HttpStatus.NOT_FOUND);
}
} catch (Exception e) {
return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
@PostMapping("create/")
public ResponseEntity<FunderSourceDto> addFunderSource(@RequestBody FunderSourceDto funderSourceDto) {
try {
FunderSource funderSource = funderSourceService.createFunderSource(FunderSource.from(funderSourceDto));
return new ResponseEntity<>(FunderSourceDto.from(funderSource), HttpStatus.OK);
} catch (Exception e) {
return new ResponseEntity<>(null, HttpStatus.BAD_REQUEST);
}
}
@DeleteMapping("delete/id/{id}")
public ResponseEntity<Boolean> deleteFunderSource(@PathVariable Long id) {
try {
return new ResponseEntity<>(funderSourceService.deleteFunderSource(id), HttpStatus.OK);
} catch (Exception e) {
return new ResponseEntity<>(null, HttpStatus.OK);
}
}
@PutMapping("update/id/{id}")
public ResponseEntity<FunderSourceDto> editFunderSource(@PathVariable Long id, @RequestBody FunderSourceDto funderSourceDto) {
try {
FunderSource editedFunderSource = funderSourceService.updateFunderSource(id, FunderSource.from(funderSourceDto));
return new ResponseEntity<>(FunderSourceDto.from(editedFunderSource), HttpStatus.OK);
} catch (Exception e) {
return new ResponseEntity<>(null, HttpStatus.NOT_FOUND);
}
}
@GetMapping("getByFundTypeName/fundTypeName/{fundTypeName}")
public ResponseEntity<FunderSourceDto> getFunderSourceByName(@PathVariable("fundTypeName") String fundTypeName) {
try {
FunderSource funderSource = funderSourceService.getFunderSourceByName(fundTypeName);
if (funderSource != null) {
return new ResponseEntity<>(FunderSourceDto.from(funderSource), HttpStatus.OK);
} else {
return new ResponseEntity<>(null, HttpStatus.NOT_FOUND);
}
} catch (Exception e) {
return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
@PutMapping("inactive/id/{id}")
public ResponseEntity<String> changeStatusToInactive(@PathVariable Long id) {
try {
funderSourceService.changeStatusToInactive(id);
return new ResponseEntity<>(null, HttpStatus.OK);
} catch (Exception e) {
return new ResponseEntity<>("Failed to change status record with ID " + id, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
@PutMapping("active/id/{id}")
public ResponseEntity<String> changeStatusToActive(@PathVariable Long id) {
try {
funderSourceService.changeStatusToActive(id);
return new ResponseEntity<>(null, HttpStatus.OK);
} catch ( Exception e) {
return new ResponseEntity<>("Failed to change status record with ID " + id, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
@DeleteMapping("deleteAll/")
public ResponseEntity<String> deleteAllFunderSources() {
try {
funderSourceService.deleteAllFunderSources();
return new ResponseEntity<>("All funder sources have been deleted.", HttpStatus.OK);
} catch (Exception e) {
return new ResponseEntity<>("Failed to delete all funder sources.", HttpStatus.INTERNAL_SERVER_ERROR);
}
}
}
|
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PrefixedByPoP\Symfony\Component\Cache\Adapter;
use PrefixedByPoP\Psr\SimpleCache\CacheInterface;
use PrefixedByPoP\Symfony\Component\Cache\PruneableInterface;
use PrefixedByPoP\Symfony\Component\Cache\ResettableInterface;
use PrefixedByPoP\Symfony\Component\Cache\Traits\ProxyTrait;
/**
* Turns a PSR-16 cache into a PSR-6 one.
*
* @author Nicolas Grekas <p@tchwork.com>
* @internal
*/
class Psr16Adapter extends AbstractAdapter implements PruneableInterface, ResettableInterface
{
use ProxyTrait;
/**
* @internal
*/
protected const NS_SEPARATOR = '_';
/**
* @var object
*/
private $miss;
public function __construct(CacheInterface $pool, string $namespace = '', int $defaultLifetime = 0)
{
parent::__construct($namespace, $defaultLifetime);
$this->pool = $pool;
$this->miss = new \stdClass();
}
protected function doFetch(array $ids) : iterable
{
foreach ($this->pool->getMultiple($ids, $this->miss) as $key => $value) {
if ($this->miss !== $value) {
(yield $key => $value);
}
}
}
protected function doHave(string $id) : bool
{
return $this->pool->has($id);
}
protected function doClear(string $namespace) : bool
{
return $this->pool->clear();
}
protected function doDelete(array $ids) : bool
{
return $this->pool->deleteMultiple($ids);
}
/**
* @return mixed[]|bool
*/
protected function doSave(array $values, int $lifetime)
{
return $this->pool->setMultiple($values, 0 === $lifetime ? null : $lifetime);
}
}
|
package test;
class Outer {
private int num1 = 10;
private static int num2 = 20;
public static class Inner {
private int num3 = 30;
private static int num4 = 40;
public void print() {
// System.out.println("Num1 : " +num1); //NOT OK
Outer out = new Outer();
System.out.println("Num1 : " + out.num1);
System.out.println("Num2 : " + num2);
System.out.println("Num3 : " + this.num3);
System.out.println("Num4 : " + Inner.num4);
}
}
}
class Program {
public static void main(String[] args) {
Outer.Inner in = new Outer.Inner();
in.print();
}
}
|
/*-
* SPDX-License-Identifier: BSD-2-Clause
*
* Copyright (c) 2023 Maarten L. Hekkelman
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "MMenu.hpp"
#include "MApplication.hpp"
#include "MError.hpp"
#include "MFile.hpp"
#include "MPreferences.hpp"
#include "MStrings.hpp"
#include "MUtils.hpp"
#include "MWindow.hpp"
#include "mrsrc.hpp"
#include <mxml/document.hpp>
#include <algorithm>
#include <cstring>
#include <iostream>
#undef AppendSubmenu
// --------------------------------------------------------------------
MMenu *MMenu::CreateFromResource(const char *inResourceName, bool inPopup)
{
using namespace std::literals;
MMenu *result = nullptr;
mrsrc::istream rsrc("Menus/"s + inResourceName + ".xml");
mxml::document doc(rsrc);
// build a menu from the resource XML
auto root = doc.find_first("/menu");
if (root != doc.end())
result = Create(*root, inPopup);
return result;
}
MMenu *MMenu::Create(const mxml::element &inXMLNode, bool inPopup)
{
std::string label;
if (inXMLNode.name() == "menu")
{
label = GetLocalisedStringForContext("menu", inXMLNode.get_attribute("label"));
if (label.length() == 0)
throw std::runtime_error("Invalid menu specification, label is missing");
}
MMenu *menu = new MMenu(inXMLNode.get_attribute("id"), label, inPopup);
int section = 0;
for (auto item : inXMLNode)
{
if (item.name() == "separator")
{
++section;
continue;
}
if (item.name() == "item")
{
label = GetLocalisedStringForContext("menu", item.get_attribute("label"));
menu->AppendItem(section, label,
item.get_attribute("cmd"), item.get_attribute("check") == "check");
}
if (item.name() == "radio-item")
{
std::vector<std::string> channels;
for (auto &channel : item)
channels.emplace_back(channel.get_attribute("label"));
menu->AppendRadioItems(section, channels, item.get_attribute("action"));
}
else if (item.name() == "menu")
menu->AppendSubmenu(section, Create(item, false));
}
return menu;
}
void MMenu::Popup(MWindow *inHandler, int32_t inX, int32_t inY, bool inBottomMenu)
{
mImpl->Popup(inHandler, inX, inY, inBottomMenu);
}
// --------------------------------------------------------------------
std::unique_ptr<MMenuBar> MMenuBar::sInstance;
MMenuBar::MMenuBar()
: MMenu(MMenuImpl::CreateBar(this))
{
}
void MMenuBar::Init(const std::string &inMenuResourceName)
{
mrsrc::istream rsrc("Menus/" + inMenuResourceName + ".xml");
mxml::document doc(rsrc);
mxml::element *node = &doc.front();
if (node->name() != "menubar")
throw std::runtime_error("Invalid menubar specification");
sInstance.reset(new MMenuBar());
for (auto item : *node)
{
if (item.name() == "menu")
sInstance->AppendSubmenu(0, MMenu::Create(item, false));
}
}
void MMenuBar::AddToWindow(MWindowImpl *inWindowImpl)
{
mImpl->AddToWindow(inWindowImpl);
}
|
<?php
class VentaModel implements JsonSerializable{
private $VentaID;
private $UsuarioID;
private $DetalleVenta;
private $FechaVenta;
private $TotalVenta;
private $Estado;
public function getVentaID()
{
return $this->VentaID;
}
public function setVentaID($VentaID)
{
$this->VentaID = $VentaID;
}
public function getUsuarioID()
{
return $this->UsuarioID;
}
public function setUsuarioID($UsuarioID)
{
$this->UsuarioID = $UsuarioID;
}
public function getFechaVenta()
{
return $this->FechaVenta;
}
public function setFechaVenta($FechaVenta)
{
$this->FechaVenta = $FechaVenta;
}
public function getTotalVenta()
{
return $this->TotalVenta;
}
public function setTotalVenta($TotalVenta)
{
$this->TotalVenta = $TotalVenta;
}
public function getEstado()
{
return $this->Estado;
}
public function setEstado($Estado)
{
$this->Estado= $Estado;
}
public function getDetalleVenta()
{
return $this->DetalleVenta;
}
public function setDetalleVenta($DetalleVenta)
{
$this->DetalleVenta = $DetalleVenta;
}
public function jsonSerialize()
{
return [
'VentaID' => $this->VentaID,
'UsuarioID' => $this->UsuarioID,
'FechaVenta' => $this->FechaVenta,
'TotalVenta' => $this->TotalVenta,
'Estado' => $this->Estado,
];
}
public function save(){
$conn = new conexion();
$query = "EXEC SP_CrearVenta :iduser, :fecha, :json";
try{
$r = $conn->getConnection()->prepare($query);
$r->bindValue(":iduser", $this->UsuarioID);
$r->bindValue(":fecha", $this->FechaVenta);
$r->bindValue(":json", json_encode($this->DetalleVenta));
$r->execute();
//echo $r->fetchAll(PDO::FETCH_ASSOC);
}catch(PDOException $e){
echo $e;
}
}
}
?>
|
# 질문 리스트
## 🎈 프론트엔드에서 컴포넌트란? (개인적인 생각)
리액트 공식 문서에 컴포넌트의 정리를 보면 "컴포넌트를 통해 UI를 재사용 가능한 개별적인 여러 조각으로 나누고, 각 조각을 개별적으로 살펴볼 수 있습니다."와 같습니다.
이 구절에서 볼 수 있듯이 컴포넌트는 재사용 가능한 개별적인 여러 조각이라고 말할 수 있습니다. 우리는 여기서 컴포넌트는 확장성있고 재사용 가능해야하고 독립적이여야 합니다. 그러기 위해서는 컴포넌트는 단일 책임을 가지는 컴포넌트로 구성되어야 합니다. 이러한 컴포넌트들은 테스트하기 좋고 가독성도 좋습니다. 우리가 이러한 재사용 가능한 컴포넌트를 사용하면 DRY 원칙을 지키며 중복 없는 코드를 작성할 수 있습니다.
이때 API를 호출하는 로직이 포함되어있거나 비즈니스 로직이 포함되어 있는 경우에는 좀 더 유연하고 융통성 있는 컴포넌트를 만들어야 합니다. 이러한 컴포넌트를 만들 때 패턴들의 기본적인 베이스는 제어의 역전이 발판으로 되어 있는데, 해당 컴포넌트에게 제어권을 넘겨주고 흐름에 맞게 통제 또는 해당 로직을 구현하고 이 흐름에 대한 호출은 외부 라이브러리가 해주는 방식으로 간단한 API를 만들 수 있으며 이렇게 하면 재사용 가능한 컴포넌트를 만들 수 있습니다.
제가 흔히 많이 사용하고 있는 custom hook도 예를 들 수가 있는데 이 custom hook을 생성하여 사용하면 비즈니스 로직을 분리할 수 있으며 우리는 이 custom hook으로 필요한 컴포넌트에 맞게 사용할 수 있습니다. 따라서 제어권은 해당 컴포넌트가 가지고 있고 해당 통제권을 넘겨주어 해당 컴포넌트에서 직접 로직을 호출하는 것이 아닌 컴포넌트 밖의 custom hook에서 호출하게 하여 관심사를 분리함으로써 컴포넌트를 재사용할 수 있습니다.
여기서 주의해야할 점은 결국 모든 원칙은 트레이드오프임으로 관심사에 따른 분리와 재사용성의 확대를 위해 제어 위임을 적절하게 하고 너무 어렵지 않게 사용성도 높이는 그 사이의 최적을 찾아내는건 각자의 개발자의 몫이라고 생각합니다.
잘 설계된 컴포넌트는 (외부로 제어를 위임하여) 재사용 가능하고 확장 가능한 단일 책임 원칙을 따르는 테스트 용이한 컴포넌트라고 생각합니다.
## 🎈 리액트 Hooks의 장점
Hooks를 사용하면 로직의 재사용이 가능하고 관리가 쉽다는 것입니다. 함수 안에서 다른 함수를 호출하는 것으로 새로운 hook을 만들어 볼 수 있습니다. 기존의 class component는 여러 단계의 상속으로 인해 전반적으로 복잡성과 오류 가능성을 증가시켰습니다. 하지만 function component에 hooks를 도입하면서 class component가 가지고 있는 기능을 모두 사용할 수 있음은 물론이고 기존 class component 복잡성, 재사용성의 단점들까지 해결됩니다.
## 🎈 Class Component와 Function Component의 차이점에 대해서 설명하세요.
class component는 여러 단계의 상속으로 이루어져 있습니다. 그리하여 복잡성과 오류 가능성을 증가시켰습니다. 결국 class component는 테스트하기 어렵습니다. 이로 인해 Function Component가 탄생하게 되었고, class component는 라이플 사이클을 가지면 이로인해 각각 생명주기 메소드에 대해 알고 있어야 합니다. 또한, class Component에서 this 사용은 어려움을 느낄 수도 있습니다. 하지만 Function Component는 이러한 기능을 hook을 사용하여 생명주기에 원하는 동작을 하게 합니다.
## 🎈 virtual DOM이 무엇인가요? virtual DOM이 좋은 이유에 대해서 설명하세요.
virtual DOM은 실제 DOM의 변화를 최소화 시켜주는 역할을 합니다. virtual DOM을 사용하는 이유는 효율성 때문입니다. virtual DOM을 활용하면 실제 DOM을 바꾸는 것보다 시간 복잡도가 낮아집니다. 만약 HTML 파일에 20개의 변화가 생기면 과정 역시 20회가 이루어집니다. 하지만 virtual DOM은 변화된 부분만 가려내여 실제 DOM에 전달하기에 실제 DOM은 1회로 인식하여 단 한번만의 렌더링 과정만 거치게 됩니다.
### 공식 문서
가상 DOM(VDOM)은 UI의 이상적인 또는 "virtual" 표현이 메모리에 유지되고 ReactDOM과 같은 라이브러리에 의해 "real" DOM과 동기화되는 프로그래밍 개념입니다. 이 프로세스를 reconciliation(재조정) 이라고 합니다 .
이 접근 방식은 React의 선언적 API를 가능하게 합니다.: React에 UI를 원하는 상태를 지정하면 DOM이 해당 상태와 일치하는지 확인합니다. 이러한 방식은 앱 구축에 사용해야 하는 어트리뷰트 조작, 이벤트 처리, 수동 DOM 업데이트를 추상화합니다.
“virtual DOM”은 특정 기술이라기보다는 패턴에 가깝기 때문에 사람들마다 의미하는 바가 다릅니다. React의 세계에서 “virtual DOM”이라는 용어는 보통 사용자 인터페이스를 나타내는 객체이기 때문에 React elements와 연관됩니다. 그러나 React는 컴포넌트 트리에 대한 추가 정보를 포함하기 위해 “fibers”라는 내부 객체를 사용합니다. 또한 React에서 “virtual DOM” 구현의 일부로 간주할 수 있습니다.
> [공식 문서](https://reactjs.org/docs/faq-internals.html)
## 🎈 웹 성능 향상을 위해 최적화를 해 본 경험이 있나요? 혹은 useMemo와 useCallback 메소드를 활용해 최적화하는 원리에 대해서 설명하세요.
`useMemo`와 `useCallback`은 성능 최적화를 위해서 사용되는 Hook입니다. 이 때, `useMemo`는 특정 결과 값을 재사용하는 반면에 `useCallback`은 특정함수를 새로 만들지 않고 재사용하고 싶을 때 사용합니다. 이 둘은 dependency 리스트를 이용하여 그 중 하나가 변경이 되면 결과에 대해 변경됩니다.
> [When to `useMemo` and `useCallback`](https://github.com/saseungmin/frontend-tech-interview/blob/main/react/when-to-useMemo-and-useCallback.md)
## 🎈 React Concurrent Mode
자바스크립트는 싱글스레드 기반 언어이다보니 동시에 처리가 불가능합니다. 그래서 React는 자바스크립트이고 따라서 동일한 제한 사항에 묶여있습니다. 현재로서는, React가 [재조정(Reconciliation)](https://ko.reactjs.org/docs/reconciliation.html) 과정을 한번 시작하면, 이 과정이 완전히 끝나기 전까지는 이를 멈출 수 없습니다. 그러면 브라우저의 메인 UI 스레드는 사용자 입력을 받는 등의 다른 작업을 실행할 수 없게 됩니다.
그래서 concurrent mode가 탄생하게 되었는데 여러 작업을 동시에 처리하도록 하는 방식인데, 실제로는 동시로 작업이 수행되지는 않습니다. 전환이 빠르기 떄문에 그렇게 보이는 것입니다. 그래서 여러 작업을 작은 단위로 나눈뒤 그 작업들 간의 우선순위를 정해서 그 작업을 수행하는 방식입니다.
Concurrent mode를 사용하면 사용자 경험에서 아주 중요한 역할을 합니다. 사용자가 필요로하는 중요한 부분을 우선순위를 높게하고 불필요한 부분에는 delay를 걸어주어 사용자경험을 향상시킬 수 있습니다.
- https://reactjs.org/blog/2022/03/29/react-v18.html#what-is-concurrent-react
- https://velog.io/@cadenzah/react-concurrent-mode
## 🎈 Hydrate란?
Hydrate는 SSR에서 사용되는 개념입니다. SSR의 경우 pre-rendering를 통해 완성된 HTML을 클라이언트에게 전달합니다. 이렇게 서버에서 렌더링된 정적 페이지를 클라이언트에게 보내고, react는 번들링된 JavaScript 코드를 클라이언트에게 보냅니다. 클라이언트는 전달받은 HTML과 JS코드를 매칭하는 Hydrate를 수행합니다. Hydrate란 전송받은 JavaScript들이 이전에 보내진 HTML DOM 요소 위에서 한번 더 렌더링 하게 되면서 각각 자기 자리를 찾아가며 매칭되는 것입니다. Hydrate 후에는 클릭과 같은 이벤트나 모듈들이 적용되어 사용자 조작이 가능해집니다.
즉, Hydrate는 클라이언트 측 JavaScript가 정적 호스팅 또는 서버 측 렌더링을 통해 전달되는 정적 HTML 요소에 이벤트 핸들러를 첨부하여 동적 웹 페이지로 변환하는 기술입니다.
React 18 이전에는 한 번 hydration이 시작되면 전체 트리가 완전히 hydration이 되기 전까지는 유저는 hydration이 불필요한 다른 영역과 상호작용을 할 수 없었습니다. 하지만 react 18 버전에서 suspense를 사용한 concurrent mode를 사용할 수 있게 되면서 필요한 부분만 hydration이 가능하며, 기존에 hydration을 하기 위해서는 모두 불러와야하는 문제도 lazy를 사용한 코드 스플리팅으로 해결할 수 있게 되었습니다.
## 🎈 React Query
### `staleTime` vs `cacheTime`
`staleTime`은 데이터가 fresh 상태에서 stale 상태로 변경되는데 걸리는 시간입니다. 기본값은 0분으로 즉시 변경됩니다. fresh 상태일 때는 쿼리 인스턴스가 새롭게 mount 되어도 네트워크 fetch가 일어나지 않습니다. 또한, `staleTime`이 지나지 않았다면 unmount 후 mount 되어도 fetch가 일어나지 않습니다.
`cacheTime`은 데이터가 inactive(비활성) 상태일 때 캐싱된 상태로 남아있는 시간으로 기본값은 5분입니다. 쿼리 인스턴스가 unmount 되면 데이터는 inactive 상태로 변경되며, 캐시는 `cacheTime`만큼 유지됩니다. `cacheTime`이 지났을 경우에는 가비지 컬렉터 수집 대상이 됩니다. 만약 `cacheTime`이 지나기 전에 쿼리 인스턴스가 다시 mount 되면, 데이터를 fetch하는 동안 캐시 데이터를 보여줍니다.
> https://tanstack.com/query/latest/docs/react/guides/caching
### `isLoading` vs `isFetching`
`isFetching`은 데이터가 fetch될 때 `true`일 뿐만 아니라, 캐싱 데이터가 있어서 백그라운드에서 fetch 되더라도 `true`입니다.
`isLoading`은 캐싱된 데이터가 없을 때 fetch 경우에만 `true`입니다.
## 🎈 Reference
- https://velog.io/@ye-ji/React-%EC%98%88%EC%83%81-%EB%A9%B4%EC%A0%91-%EC%A7%88%EB%AC%B8-%EB%A6%AC%EC%8A%A4%ED%8A%B8
|
@extends('patient.layouts.app')
@section('content')
<div class="w-full p-6 mx-auto">
<form class="relative" enctype="multipart/form-data" onsubmit="handleFormSubmission()" id="main-form" action="{{ route('updateMedicalData', $medicalData->id) }}" method="post">
@csrf
<div class="flex flex-wrap -mx-3">
<div class="w-full max-w-full px-3 shrink-0 lg:flex-0 lg:w-6/12">
<h4 class="dark:text-white mx-3">Add New Medical Data</h4>
</div>
</div>
@if($errors->any())
<div class="bg-red-300 text-white rounded-3 p-6 my-5">
<ul>
@foreach($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif
<div class="flex flex-wrap mt-6 -mx-3">
<div class="w-full max-w-full px-3 mt-6 shrink-0 lg:flex-0 lg:w-8/12 lg:mt-0">
<div class="relative flex flex-col min-w-0 break-words bg-white border-0 dark:bg-gray-950 dark:shadow-soft-dark-xl shadow-soft-xl rounded-2xl bg-clip-border">
<div class="flex-auto p-6">
<h5 class="font-bold dark:text-white">Information</h5>
<div class="flex flex-wrap -mx-3">
<div class="w-full max-w-full px-3 flex-0">
<label class="mt-6 mb-2 ml-1 font-bold text-xs text-slate-700 dark:text-white/80" for="title">Document Title</label>
<input type="text" value="{{$medicalData->title}}" name="title" placeholder="title" class="{{ $errors->has('title') ? 'border-red-500' : 'border-gray-300' }} focus:shadow-soft-primary-outline dark:bg-gray-950 dark:placeholder:text-white/80 dark:text-white/80 text-sm leading-5.6 ease-soft block w-full appearance-none rounded-lg border border-solid border-gray-300 bg-white bg-clip-padding px-3 py-2 font-normal text-gray-700 outline-none transition-all placeholder:text-gray-500 focus:border-black focus:outline-none" value="{{ old('UserName') }}"/>
@error('title')
<p class="text-red-500 text-xs mt-1">{{ $message }}</p>
@enderror
</div>
</div>
<div class="flex flex-wrap mt-4 -mx-3">
<div class="w-full max-w-full px-3 flex-0">
<label class="mb-2 ml-1 font-bold text-xs text-slate-700 dark:text-white/80" for="description">Description</label>
<textarea name="description" id="description" placeholder="Explain Category" class="focus:shadow-soft-primary-outline dark:bg-gray-950 dark:placeholder:text-white/80 dark:text-white/80 text-sm leading-5.6 ease-soft block w-full appearance-none rounded-lg border border-solid border-gray-300 bg-white bg-clip-padding px-3 py-2 font-normal text-gray-700 outline-none transition-all placeholder:text-gray-500 focus:border-fuchsia-300 focus:outline-none" rows="4" required>{{$medicalData->description}}</textarea>
</div>
</div>
<button type="submit" id="submit-fr" href="javascript:;" class="inline-block float-right px-8 py-2 mt-16 mb-0 font-bold text-right text-white uppercase align-middle transition-all border-0 rounded-lg cursor-pointer hover:scale-102 active:opacity-85 hover:shadow-soft-xs dark:bg-gradient-to-tl dark:from-slate-850 dark:to-gray-850 bg-gradient-to-tl from-gray-900 to-slate-800 leading-pro text-xs ease-soft-in tracking-tight-soft shadow-soft-md bg-150 bg-x-25">Create Student</button>
</div>
</div>
</div>
<div class="w-full max-w-full px-3 shrink-0 lg:flex-0 lg:w-4/12">
<div class="relative flex flex-col h-full min-w-0 break-words bg-white border-0 dark:bg-gray-950 dark:bg-opacity-20 dark:backdrop-blur-xl dark:shadow-soft-dark-xl rounded-2xl bg-clip-border">
<div class="flex-auto p-6">
<h5 class="font-bold dark:text-white">Upload Medical Documents</h5>
<div class="flex flex-wrap justify-center items-center -mx-3">
<div class=" w-full">
<div class="flex justify-center">
<video id="webcamPreview" class=" h-100 w-full" width="100%" height="100%" style="display: none; object-fit: cover;" autoplay muted></video>
</div>
<button id="captureBtn" type="button" class="ml-4 mt-4 px-8 py-8 font-bold text-white bg-red-500 rounded-full border-1 border-white cursor-pointer" style="display: none;"></button>
</div>
<div id="img-placeholder" class="w-full max-w-full !flex justify-center" style="display: none;">
<img id="previewImage" class=" w-full mt-4 h-100 object-cover" src="{{ asset('') }}" alt="">
</div>
<div class="w-3/12 mt-4">
<button id="openWebcamBtn" type="button" class="font-bold text-white bg-gray-500 py-2 px-5 rounded-full whitespace-nowrap cursor-pointer"><i class="fas text-white mr-2 fa-camera"></i>Open Camera</button>
</div>
<div class="w-full flex items-end max-w-full ">
<div class=" mr-2 max-w-full">
<label class="mt-6 mb-2 font-bold text-xs text-slate-700 dark:text-white/80" for="notes">Or Upload Documents</label>
<div dropzone class="dropzone !min-h-fit focus:shadow-soft-primary-outline dark:bg-gray-950 dark:placeholder:text-white/80 dark:text-white/80 text-sm leading-5.6 ease-soft block w-full appearance-none rounded-lg border border-solid border-gray-300 bg-white bg-clip-border px-3 py-2 font-normal text-gray-700 outline-none transition-all placeholder:text-gray-500 focus:border-fuchsia-300 focus:outline-none" id="dropzone">
<input type="file" name="stu-img" multiple onchange="previewFile()" />
<input type="file" name="webcam_capture_file" id="webcamCaptureFile" multiple style="display: none;">
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</form>
</div>
@endsection
@push('scripts')
<script>
const startDatePicker = flatpickr("#startDatePicker", {
dateFormat: "Y-m-d", // Set your desired date format
});
</script>
<script>
document.addEventListener('DOMContentLoaded', function () {
// Function to preview the selected file or webcam capture
const fileInput = document.querySelector('input[name="stu-img"]');
fileInput.addEventListener('change', previewFile);
function previewFile() {
const placeholder = document.getElementById('img-placeholder');
const webcamPreview = document.getElementById('webcamPreview');
const previewImage = document.getElementById('previewImage');
if (fileInput.files.length > 0) {
const file = fileInput.files[0];
previewImage.src = URL.createObjectURL(file);
placeholder.style.display = 'block'; // Show the image placeholder
} else if (webcamPreview.srcObject) {
placeholder.style.display = 'block';
} else {
previewImage.src = "{{ asset('assets/img/upload-default.png') }}";
placeholder.style.display = 'none'; // Hide the image placeholder
}
}
// Capture and submit the webcam image
const openWebcamBtn = document.getElementById('openWebcamBtn');
const webcamPreview = document.getElementById('webcamPreview');
const captureBtn = document.getElementById('captureBtn');
const webcamCaptureFileInput = document.getElementById('webcamCaptureFile');
const previewImage = document.getElementById('previewImage');
let webcamStream;
openWebcamBtn.addEventListener('click', async () => {
try {
if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
webcamStream = await navigator.mediaDevices.getUserMedia({ video: true });
webcamPreview.srcObject = webcamStream;
webcamPreview.play();
captureBtn.style.display = 'block';
webcamPreview.style.display = 'block';
} else {
console.error('getUserMedia is not supported in this browser');
}
} catch (error) {
console.error('Error accessing webcam:', error);
}
});
captureBtn.addEventListener('click', () => {
if (webcamStream) {
const canvas = document.createElement('canvas');
canvas.width = webcamPreview.videoWidth;
canvas.height = webcamPreview.videoHeight;
const ctx = canvas.getContext('2d');
ctx.drawImage(webcamPreview, 0, 0, canvas.width, canvas.height);
canvas.toBlob((blob) => {
const file = new File([blob], 'webcam_capture.png', { type: 'image/png' });
// Update the previewImage after setting the files
previewImage.src = URL.createObjectURL(file);
// Stop webcam stream after capturing
webcamStream.getTracks().forEach(track => track.stop());
webcamStream = null;
// Manually create a File object and assign it to the hidden webcamCaptureFileInput
const webcamCaptureFileInput = document.getElementById('webcamCaptureFile');
const webcamCaptureFile = new File([blob], 'webcam_capture.png', { type: 'image/png' });
// Here, manually assign the File object to the input files
webcamCaptureFileInput.files = createFileList([webcamCaptureFile]);
// Hide the webcam preview element
webcamPreview.style.display = 'none';
captureBtn.style.display = 'none';
previewImage.style.display = 'block';
}, 'image/png');
}
});
function createFileList(items) {
const dataTransfer = new DataTransfer();
items.forEach(item => {
dataTransfer.items.add(item);
});
return dataTransfer.files;
}
// Function to handle form submission
function handleFormSubmission() {
// You can add any additional form validation here if needed
// Disable the submit button to prevent double submission
const submitButton = document.getElementById('submit-fr');
submitButton.disabled = true;
// Show a loading indicator inside the submit button
submitButton.innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> Loading...';
// Manually append the webcamCaptureFile to the form data
const form = document.querySelector('#main-form');
const webcamCaptureFileInput = document.getElementById('webcamCaptureFile');
const webcamCaptureFile = webcamCaptureFileInput.files[0];
if (webcamCaptureFile) {
const formData = new FormData(form);
formData.append('webcam_capture_file', webcamCaptureFile);
// Submit the form with the updated formData
fetch(form.action, {
method: form.method,
body: formData,
})
.then(response => {
if (response.redirected) {
// If the response is a redirect, redirect the user to the provided URL
window.location.href = response.url;
} else {
return response.json();
}
})
.then(data => {
// Handle the response as needed
console.log(data);
// Show SweetAlert on success
Swal.fire({
icon: 'success',
title: 'Student added successfully!',
showConfirmButton: false,
timer: 1500
});
})
.catch(error => {
console.error('Error submitting form:', error);
})
.finally(() => {
// Enable the submit button and restore its original content
submitButton.disabled = false;
submitButton.innerHTML = 'Create Student';
});
} else {
// If no webcam capture file, submit the form as usual
form.submit();
}
}
// Add an event listener to the "Create Student" button
const submitButton = document.getElementById('submit-fr');
submitButton.addEventListener('click', function (event) {
// Prevent the default form submission
event.preventDefault();
// Call the function to handle form submission
handleFormSubmission();
});
});
</script>
<script>
document.addEventListener('DOMContentLoaded', function() {
// Get the phone input element
var phoneInput = document.querySelector('input[name="phone"]');
// Add an event listener for the input event
phoneInput.addEventListener('input', function() {
// Get the value of the input
var inputValue = phoneInput.value.trim();
// Check if the input starts with '94'
if (!inputValue.startsWith('94')) {
// If not, add '94' to the beginning
phoneInput.value = '94' + inputValue;
}
// Check if '0' is used after '94'
if (inputValue.startsWith('940')) {
// Remove the '0' after '94'
phoneInput.value = '94' + inputValue.slice(3);
}
});
// Add an event listener for form submission (optional)
// You can add additional validation logic here if needed
document.querySelector('form').addEventListener('submit', function(event) {
var inputValue = phoneInput.value.trim();
// Validate if '94' is present and '0' is not used after '94'
if (!inputValue.startsWith('94') || inputValue.startsWith('940')) {
alert('Invalid phone number format');
event.preventDefault(); // Prevent form submission
}
});
});
</script>
@endpush
|
<html>
<head>
<script type="text/javascript">
/**
No matter where a function is invoked from, or even how it is invoked, its lexical scope is only defined by where the function was declared.
*/
function foo(a){
var b = a*2;
function bar(c){
//var c = 42;
console.log(a,b,c) //2,4,6 or in case of shadowing, when var c = 42 is not commented out, 2,4,42
}
bar(a*3);
}
foo(2);
</script>
</head>
</html>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.