text stringlengths 184 4.48M |
|---|
import React from 'react'
import Navbar from './navbar'
import img from './1682586072.png'
import img1 from './hand.png'
import img2 from '../component/../fa.avif'
import img3 from '../component/../download (2).png'
import { NavLink } from 'react-router-dom'
export default function News1(){
return(
<div className='home' >
<Navbar/>
<section>
<h5>HOW AI AND ML WILL IMPACT SOFTWARE DEVELOPMENT</h5><br/>
<div className="container">
<img src={img} width="100%" height="100%"/><br/><br/>
<div>
<img src={img2} width="5%" height='5%'></img>
<img src={img3} width="3%" height='3%'></img>
</div><br/>
<div className='news1details' >
<h5>NEWS DETAILS</h5>
<p><b>What Is Artificial Intelligence And Machine Learning?</b></p>
<p>AI stands for Artificial Intelligence, which is a branch of computer science that aims to create intelligent machines that can perform tasks that typically require human intelligence, such as recognizing speech, interpreting images, and making decisions. AI includes various techniques such as machine learning,
natural language processing, and computer vision.</p>
<p>Machine learning (ML) is a subset of AI that involves training computer algorithms to learn from data and make predictions or decisions without being explicitly programmed. ML algorithms are designed to improve their performance over time as they are exposed to more data. There are three main types of machine learning: supervised learning, unsupervised learning, and reinforcement learning.</p>
<p>Supervised learning involves training an algorithm on a labeled dataset, where the correct output is already known, to make predictions on new, unlabeled data. Unsupervised learning involves training an algorithm on an unlabeled dataset to find patterns or groupings within the data. Reinforcement learning involves training an algorithm to make decisions based on rewards or punishments received for specific actions.</p>
<p>Together, AI and ML have many practical applications, from self-driving cars and voice assistants to fraud detection and predictive maintenance in industrial settings.</p>
</div>
<div className='imagenews1'>
<img src={img1}/>
</div><br/><br/>
<div className='news1details'>
<h5>Impact Of Artificial Intelligence And Machine Learning In software development</h5>
<p>Artificial intelligence (AI) and machine learning (ML) are rapidly transforming the way we approach software development. These technologies have the potential to make software development more efficient, more accurate, and more user-friendly, revolutionizing the way we create software applications.</p>
</div>
<div className='news1details'>
<h6 >Automated Code Generation</h6>
<p>One area where AI and ML are having a significant impact is in automated code generation. AI-powered tools can analyze large datasets of code and generate new code that fits specific requirements. This can save developers a significant amount of time and effort, particularly when it comes to repetitive tasks or code that is required in multiple applications.</p>
<p>AI can be used to identify patterns in existing code, learn how to replicate those patterns, and generate new code that is both efficient and effective. Additionally, AI-powered code generators can analyze data sets and automatically generate code based on the insights gained from that data.</p>
</div>
<div className='news1details'>
<h6>Improved Testing and Quality Assurance
</h6>
<p>AI and ML are also making a significant impact on the way we test software applications. With the help of machine learning algorithms, developers can identify bugs and errors in code more quickly and accurately than traditional manual testing methods.</p>
<p>ML algorithms can analyze large datasets of code to identify patterns of bugs and errors, as well as to predict potential issues before they arise. By doing so, they can significantly reduce the time and effort required for testing and quality assurance.</p>
</div>
<div className='news1details'>
<h6>
Natural Language Processing
</h6>
<p>Natural language processing (NLP) is another area where AI and ML are making a significant impact. NLP is a field of AI that focuses on teaching machines to understand and interpret human language.
In the context of software development, NLP can be used to create chatbots and virtual assistants that can understand and respond to user queries. These chatbots and virtual assistants can be used to provide support to users, answer frequently asked questions, and even troubleshoot common problems.</p>
</div>
<div className='news1details'>
<h6>Conclusion
</h6>
<p>AI and ML are rapidly transforming the field of software development, providing developers with powerful tools and techniques that can make software development more efficient, accurate, and user-friendly. From automated code generation to improved testing and quality assurance, NLP, predictive analytics, and continuous integration and delivery, these technologies have the potential to significantly improve the software development process.</p>
<p>While AI and ML are not likely to replace human developers entirely, they will certainly reshape the way we approach software development. As these technologies continue to develop and mature, we can expect to see even more exciting applications in the field of software development, improving the quality and functionality of software applications and enhancing the user experience for millions of users around the world.</p>
</div>
<div>
<h5>OTHER NEWS</h5>
</div>
</div>
<div className="container-news">
<div class="col-lg-4">
<div class="card mb-5 mb-lg-0">
<div class="card-body">
<h2>Artificial Intelligence</h2><hr/>
<img src={img} height="130%" width="100%"/>
<p>How AI And ML Will Impact Software Development</p>
<p>Impact Of Artificial Intelligence And Machine Learning In software development Artificial in...
</p>
<NavLink to ="/news1">Read More</NavLink>
</div>
</div>
</div><br/>
<div class="col-lg-4">
<div class="card mb-5 mb-lg-0">
<div class="card-body">
<h2>Artificial Intelligence</h2><hr/>
<img src={img} height="130%" width="100%"/>
<p>How AI And ML Will Impact Software Development</p>
<p>Impact Of Artificial Intelligence And Machine Learning In software development Artificial in...
</p>
<NavLink to ="/news2">Read More</NavLink>
</div>
</div>
</div><br/>
<div class="col-lg-4">
<div class="card mb-5 mb-lg-0">
<div class="card-body">
<h2>Artificial Intelligence</h2><hr/>
<img src={img} height="130%" width="100%"/>
<p>How AI And ML Will Impact Software Development</p>
<p>Impact Of Artificial Intelligence And Machine Learning In software development Artificial in...
</p>
<NavLink to ="/news3">Read More</NavLink>
</div>
</div>
</div><br/>
</div><br/><br/>
</section>
</div>
)
} |
# coding=utf-8
#
# average_past_single.py - Calculates the average of past measurements for a single channel
#
# Copyright (C) 2015-2020 Kyle T. Gabriel <mycodo@kylegabriel.com>
#
# This file is part of Mycodo
#
# Mycodo is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Mycodo is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Mycodo. If not, see <http://www.gnu.org/licenses/>.
#
# Contact at kylegabriel.com
#
import threading
import time
from flask_babel import lazy_gettext
from mycodo.controllers.base_controller import AbstractController
from mycodo.databases.models import Conversion
from mycodo.databases.models import CustomController
from mycodo.mycodo_client import DaemonControl
from mycodo.utils.database import db_retrieve_table_daemon
from mycodo.utils.influx import add_measurements_influxdb
from mycodo.utils.influx import average_past_seconds
from mycodo.utils.system_pi import get_measurement
from mycodo.utils.system_pi import return_measurement_info
def constraints_pass_positive_value(mod_controller, value):
"""
Check if the user controller is acceptable
:param mod_controller: SQL object with user-saved Input options
:param value: float or int
:return: tuple: (bool, list of strings)
"""
errors = []
all_passed = True
# Ensure value is positive
if value <= 0:
all_passed = False
errors.append("Must be a positive value")
return all_passed, errors, mod_controller
measurements_dict = {
0: {
'measurement': '',
'unit': '',
}
}
FUNCTION_INFORMATION = {
'function_name_unique': 'average_past_single',
'function_name': 'Average (Past, Single)',
'measurements_dict': measurements_dict,
'enable_channel_unit_select': True,
'message': 'This function acquires the past measurements (within Max Age) for the selected measurement, averages '
'them, then stores the resulting value as the selected measurement and unit.',
'options_enabled': [
'measurements_select_measurement_unit',
'custom_options'
],
'custom_options': [
{
'id': 'period',
'type': 'float',
'default_value': 60,
'required': True,
'constraints_pass': constraints_pass_positive_value,
'name': lazy_gettext('Period (seconds)'),
'phrase': lazy_gettext('The duration (seconds) between measurements or actions')
},
{
'id': 'start_offset',
'type': 'integer',
'default_value': 10,
'required': True,
'name': 'Start Offset',
'phrase': 'The duration (seconds) to wait before the first operation'
},
{
'id': 'max_measure_age',
'type': 'integer',
'default_value': 360,
'required': True,
'name': 'Measurement Max Age',
'phrase': 'The maximum allowed age of the measurement'
},
{
'id': 'select_measurement',
'type': 'select_measurement',
'default_value': '',
'options_select': [
'Input',
'Math',
'Function'
],
'name': 'Measurement',
'phrase': 'Measurement to replace "x" in the equation'
}
]
}
class CustomModule(AbstractController, threading.Thread):
"""
Class to operate custom controller
"""
def __init__(self, ready, unique_id, testing=False):
threading.Thread.__init__(self)
super(CustomModule, self).__init__(ready, unique_id=unique_id, name=__name__)
self.unique_id = unique_id
self.log_level_debug = None
self.timer_loop = time.time()
self.control = DaemonControl()
# Initialize custom options
self.period = None
self.start_offset = None
self.select_measurement_device_id = None
self.select_measurement_measurement_id = None
self.max_measure_age = None
# Set custom options
custom_function = db_retrieve_table_daemon(
CustomController, unique_id=unique_id)
self.setup_custom_options(
FUNCTION_INFORMATION['custom_options'], custom_function)
def initialize_variables(self):
controller = db_retrieve_table_daemon(
CustomController, unique_id=self.unique_id)
self.log_level_debug = controller.log_level_debug
self.set_log_level_debug(self.log_level_debug)
self.timer_loop = time.time() + self.start_offset
def loop(self):
if self.timer_loop < time.time():
while self.timer_loop < time.time():
self.timer_loop += self.period
device_measurement = get_measurement(self.select_measurement_measurement_id)
if not device_measurement:
self.logger.error("Could not find Device Measurement")
return
conversion = db_retrieve_table_daemon(
Conversion, unique_id=device_measurement.conversion_id)
channel, unit, measurement = return_measurement_info(
device_measurement, conversion)
average = average_past_seconds(
self.select_measurement_device_id,
unit,
channel,
self.max_measure_age,
measure=measurement)
if not average:
self.logger.error("Could not find measurement within the set Max Age")
return False
measurement_dict = {
0: {
'measurement': self.channels_measurement[0].measurement,
'unit': self.channels_measurement[0].unit,
'value': average
}
}
if measurement_dict:
self.logger.debug(
"Adding measurements to InfluxDB with ID {}: {}".format(
self.unique_id, measurement_dict))
add_measurements_influxdb(self.unique_id, measurement_dict)
else:
self.logger.debug(
"No measurements to add to InfluxDB with ID {}".format(
self.unique_id)) |
import React, {useEffect, useRef, useState} from "react";
import {addTodo, getTodo, patchTodo} from "../utils/api";
import {useDispatch} from "react-redux";
import {add_todo} from "../store/actions";
import {IFetchTodo, ITodoListProps} from "../utils/interfaces";
import { useNavigate, useParams} from "react-router-dom";
export const TodoList: React.FC<ITodoListProps> = ({edit}) => {
const dispatch = useDispatch()
const [title, setTitle] = useState<string>('')
const navigate = useNavigate()
const {id} = useParams()
const input = useRef<HTMLInputElement>(null)
const postTodo = async () : Promise<any> => {
const data : IFetchTodo= {
title,
date: new Date().toString(),
deleted: false,
chosen: false,
complete: false
}
try {
const response = await addTodo(data)
dispatch(add_todo({
...data,
id: response.name
}))
setTitle('')
} catch (e) {
alert(e)
}
}
const changeHandler = (e: React.ChangeEvent<HTMLInputElement>) : void => {
setTitle(e.target.value)
}
const onSubmitHandler = (e : React.FormEvent<HTMLFormElement>) : void=> {
e.preventDefault()
title.trim() && postTodo()
}
useEffect(() => {
if (edit) {
getTodo(id || '').then(todo => {
if(todo) {
input.current!.focus()
setTitle(todo.title)
} else {navigate('/')}
})
}
},[])
const saveTodoHandler = (e : React.FormEvent<HTMLFormElement>): void => {
e.preventDefault()
patchTodo(id || '',{title}).then(_ => navigate('/'))
}
if (edit) {
return (
<div className={'todo_wrapper mT-4'}>
<div className="row">
<form className="col s10 m12" onSubmit={saveTodoHandler}>
<div className="row">
<div className="input-field col s11">
<i className="material-icons prefix">create</i>
<input id="icon_telephone" type="tel" className="validate" value={title} onChange={changeHandler} ref={input}/>
<label htmlFor="icon_telephone">Edit Todo</label>
<a className={'submit-a'}>
<i role={'button'} className="material-icons prefix">check</i>
<button type={'submit'}>b</button>
</a>
</div>
</div>
</form>
</div>
</div>
)
}
return (
<div className={'todo_wrapper'}>
<div className="row">
<form className="col s10 m12" onSubmit={onSubmitHandler}>
<div className="row">
<div className="input-field col s11">
<i className="material-icons prefix">create</i>
<input id="icon_telephone" type="tel" className="validate" value={title} onChange={changeHandler}/>
<label htmlFor="icon_telephone">New Todo</label>
</div>
<div className="input-field col s1">
<button type={'submit'} className="btn-floating pulse btn-large waves-effect waves-light indigo">
<i className="material-icons">add</i>
</button>
</div>
</div>
</form>
</div>
</div>
)
} |
Setting a Schema Registry ID rangeCloudera Docs
Setting a Schema Registry ID range
Learn how to set an ID range for schemas in Schema Registry using Cloudera
Manager.
An ID range that is unique to a Schema Registry instance can be set in Cloudera
Manager on the Schema Registry service’s configuration page. Configuring an ID range
does not alter already existing schemas.
Ensure that the cluster, its hosts, and all its services are healthy.
Ensure that Schema Registry is commissioned and running.
Ensure that you have access to all credentials that are required to access
and use Schema Registry.
Plan ahead and designate ID ranges for each Schema Registry instance. Ensure
that the planned ranges do not overlap.
Ensure that the ID range you plan to configure has enough IDs. Base the size
of your range on the approximate number of schemas you expect to have.
In Cloudera Manager, select the Schema Registry service.
Go to Configuration.
Find and configure the following properties:
ID Offset Range Minimum
ID Offset Range Maximum
Configure the properties according to your planned ID ranges. For example, if
you want to have an ID range of 1-100, set ID Offset Range
Minimum to 1 and ID Offset Range
Maximum to 100.
Click Save Changes.
Restart Schema Registry.
When new schemas are added, either through the UI or the API, the schema IDs are
allocated from the configured range.
Parent topic: ID ranges in Schema Registry |
import { Component } from "react";
import Axios from "axios";
import Cookies from "universal-cookie";
import md5 from "md5";
import { ToastContainer, toast } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";
import { useState } from "react";
import { loginFields } from "../constants/formFields";
import Input from "./Input";
const fields = loginFields;
let fieldsState = {};
fields.forEach((field) => (fieldsState[field.id] = ""));
const baseUrl = "http://localhost:4000/users";
const cookies = new Cookies();
function Login() {
const [username, setUsername] = useState("");
const [password, setPassword] = useState("");
const [email, setEmail] = useState("");
const [full_name, setFullName] = useState("");
const [userInputError, setUserInputError] = useState(false);
const [hasError, setHasError] = useState(false);
const notifyError = (text) =>
toast.error(text, {
position: "top-right",
autoClose: 5000,
hideProgressBar: false,
closeOnClick: true,
pauseOnHover: true,
draggable: true,
progress: undefined,
theme: "colored",
});
function handleChange(name, value) {
if (name == "username") {
let regex = new RegExp("^[a-zA-Z0-9]+$");
if (regex.test(value)) {
console.log(name, value);
setUsername(value);
} else {
console.log("El nombre de usuario no debe tener espacios");
notifyError("El nombre de usuario no debe tener espacios");
}
}
if (name == "password") {
let regex = new RegExp("^[a-zA-Z0-9]+$");
if (regex.test(value)) {
console.log(name, value);
setPassword(value);
} else {
console.log("La contraseña no admite espacios");
notifyError("La contraseña no admite espacios");
}
}
if (name === "email") {
console.log(name, value);
setEmail(value);
}
if (name === "full_name") {
let regex = new RegExp("^[a-zA-Z ]+$");
if (regex.test(value)) {
console.log(name, value);
setFullName(value);
} else {
notifyError("El nombre completo del usuario no debe tener numeros");
}
}
}
return (
<>
<form className="mt-8 space-y-6">
<div className="-space-y-px">
<div>
<Input
atributo={{
id: "username",
name: "username",
placeholder: "Ingrese su nombre de usuario",
type: "text",
}}
value={username}
handleChange={handleChange}
/>
</div>
<div>
<Input
atributo={{
id: "full_name",
name: "full_name",
placeholder: "Ingrese su nombre completo",
type: "text",
}}
handleChange={handleChange}
/>
</div>
<div>
<Input
atributo={{
id: "email",
name: "email",
placeholder: "Ingrese su correo electronico",
type: "email",
}}
handleChange={handleChange}
/>
</div>
<div>
<Input
atributo={{
id: "password",
name: "password",
placeholder: "Ingrese su contrasena",
type: "password",
}}
value={password}
handleChange={handleChange}
/>
</div>
</div>
<button
className="group relative w-full flex justify-center py-2 px-4 border border-transparent btn btn-primary"
// onClick={toast}
>
Iniciar Sesión
</button>
</form>
<ToastContainer />
</>
);
}
export default Login; |
//
// EditTableViewController.swift
// ConvenienceStore
//
// Created by jr on 2022/10/26.
//
import UIKit
import Foundation
class EditTableViewController: UITableViewController, UITextFieldDelegate {
var thing:Item?
var isSelectedPhoto = false //是否選擇相片
var pkvStore:UIPickerView!
var pkvComment:UIPickerView!
let storeArray = ["","7-11","Family","Hi-Life","OK"]
let commentArray = ["","🤩","😐","😥","🤔"]
@IBOutlet weak var photoImageView: UIImageView!
@IBOutlet weak var storeTextField: UITextField!
@IBOutlet weak var itemTextField: UITextField!
@IBOutlet weak var datePicker: UIDatePicker!
@IBOutlet weak var priceTextField: UITextField!
@IBOutlet weak var discountSwitch: UISwitch!
@IBOutlet weak var commentTextField: UITextField!
//MARK: - View Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
updateUI()
//顯示要修改的資料
editorUpdateUI()
//顯示日期選擇
createDatePicker()
//顯示滾輪
createPickerView()
//點背景退鍵盤及PickerView
dismissKeyboardFromBackground()
//點選照片觸發選單功能(選擇相簿或拍照)
photoImageView.isUserInteractionEnabled = true
//數字鍵盤及上方Tabbar
priceTextField.keyboardType = .numberPad
priceTextField.setKeyboardButton()
}
func updateUI(){
tableView.separatorStyle = .none
photoImageView.image = UIImage(systemName: "photo.fill")
storeTextField.placeholder = "Pleace type the store."
itemTextField.placeholder = "Pleace type the item."
priceTextField.placeholder = "How much it is?"
commentTextField.placeholder = "Comment here!"
let font = UIFont.systemFont(ofSize: 18, weight: .regular)
storeTextField.font = font
itemTextField.font = font
priceTextField.font = font
commentTextField.font = font
}
//修改資料傳到編輯頁,顯示之前的記錄(讀檔)
func editorUpdateUI(){
if thing != nil{
storeTextField.text = thing?.store
itemTextField.text = thing?.item
datePicker.date = thing!.date
priceTextField.text = thing?.price.description
commentTextField.text = thing?.comment
//有圖片名字才去讀出url
if let imageName = thing?.photoName{
let photoURL = Item.documentsDirectory.appendingPathComponent(imageName).appendingPathExtension("jpg")
photoImageView.image = UIImage(named: photoURL.path)
}
}
}
//MARK: - Target Action
//Tap Gesture選照片或拍照
@IBAction func selectPhoto(_ sender: UITapGestureRecognizer) {
let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)//選單樣式
let photoAction = UIAlertAction(title: "Choose photo", style: .default) { action in
self.selectphoto()
}
let cameraAction = UIAlertAction(title: "Take picture", style: .default) { action in
self.takePicture()
}
let cancelAction = UIAlertAction(title: "Cancel", style: .default)
alertController.addAction(photoAction)
alertController.addAction(cameraAction)
alertController.addAction(cancelAction)
present(alertController, animated: true)
}
//建立日期選擇器
func createDatePicker(){
print("date")
//選擇日期時的呈現樣式
datePicker.datePickerMode = .date
datePicker.preferredDatePickerStyle = .compact
datePicker.locale = .autoupdatingCurrent
//預設為今天
datePicker.date = .now
}
//建立的滾輪
func createPickerView(){
//滾輪上done,cancel按鈕設計另外寫在TextField檔案裡的setKeyboardButton()
//選擇店家滾輪
pkvStore = UIPickerView()
pkvStore.delegate = self
pkvStore.dataSource = self
pkvStore.tag = 1 //此處的tag編碼與store在storyboard的textField的tag編碼相同
storeTextField.setKeyboardButton()
//將輸入store欄位的鍵盤替換為滾輪 //inputView 是 text filed 輸入時從下方冒出的輸入區塊
storeTextField.inputView = pkvStore
//選擇評論滾輪
pkvComment = UIPickerView()
pkvComment.delegate = self
pkvComment.dataSource = self
pkvComment.tag = 4
commentTextField.setKeyboardButton()
commentTextField.inputView = pkvComment //鍵盤替換為滾輪
}
//return鍵盤
//<方法一>從 UITextField 連結 IBAction,Event 選擇 Did End On Exit
@IBAction func dismissItemKeyboard(_ sender: Any) {
}
//點背景退鍵盤
func dismissKeyboardFromBackground(){
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(dismissKeyboard))
tapGesture.cancelsTouchesInView = false
tableView.addGestureRecognizer(tapGesture)
}
@objc func dismissKeyboard(){
self.tableView.endEditing(true)
}
// MARK: - Table view data source
override func shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -> Bool {
if storeTextField.text?.isEmpty == false, itemTextField.text?.isEmpty == false, priceTextField.text?.isEmpty == false, commentTextField.text?.isEmpty == false{
return true
}else if storeTextField.text?.isEmpty == true{
let alertController = UIAlertController(title: "\(Message.store.rawValue)", message: "Where you bought the item?", preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "OK", style: .default))
present(alertController, animated: true)
}else if itemTextField.text?.isEmpty == true{
let alertController = UIAlertController(title: "\(Message.item.rawValue)", message: "What did you buy?", preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "OK", style: .default))
present(alertController, animated: true)
}else if priceTextField.text?.isEmpty == true{
let alertController = UIAlertController(title: "\(Message.price.rawValue)", message: "How much it is?", preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "OK", style: .default))
present(alertController, animated: true)
}else if commentTextField.text?.isEmpty == true{
let alertController = UIAlertController(title: "\(Message.comment.rawValue)", message: "How about it?", preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "OK", style: .default))
present(alertController, animated: true)
}
return false
}
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
//準備傳遞資料
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
var photoName:String?
let store = storeTextField.text ?? ""
let item = itemTextField.text ?? ""
let date = datePicker.date
let price = Int(priceTextField.text ?? "0") ?? 0
let discount = discountSwitch.isOn
let comment = commentTextField.text ?? ""
//如果選擇照片
if isSelectedPhoto{
if let item = thing{ //修改:改照片就用原本名字
photoName = item.photoName
}
if photoName == nil{ //新增:取新名字
photoName = UUID().uuidString
}
//圖片呼叫data,透過data存檔到指定的路徑
//compressionQuality(0~1)來減少圖片容量
let photoData = photoImageView.image?.jpegData(compressionQuality: 0.7)
//圖片路徑:先讀出「資料夾」加上「圖片名稱」加上「副檔名」
let photoURL = Item.documentsDirectory.appendingPathComponent(photoName!).appendingPathExtension("jpg")
//將圖片存入路徑位置=>write是複寫,存入後之前的會被覆蓋掉
//<方法一>try? photoData?.write(to: photoURL)
//<方法二>
do{
let _ = try photoData?.write(to: photoURL)
}catch{
print("can't get photoURL")
}
}
thing = Item(photoName:photoName,store: store, item: item, date: date, price: price, discount: discount, comment: comment)
}
}
//MARK: - UIImagePickerControllerDelegate
extension EditTableViewController:UIImagePickerControllerDelegate ,UINavigationControllerDelegate{
//跳出相簿
func selectphoto(){
let imageContriller = UIImagePickerController()
imageContriller.sourceType = .photoLibrary
imageContriller.delegate = self
imageContriller.allowsEditing = true //選取後的照片是否能編緝
present(imageContriller, animated: true)
}
//選擇照片
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
isSelectedPhoto = true
//型態為 originaImage,其它型態有影片、修改過的圖片等等
let picture = info [UIImagePickerController.InfoKey.originalImage] as! UIImage //Any型別轉型成UIImage,才可將照片加到Imageview上
photoImageView.contentMode = .scaleAspectFit
photoImageView.image = picture
//照片存入相簿
UIImageWriteToSavedPhotosAlbum(picture, nil, nil, nil)
//選完照片後退掉畫面
dismiss(animated: true)
}
func takePicture(){
let controller = UIImagePickerController()
controller.sourceType = .camera
controller.delegate = self
present(controller, animated: true)
}
}
//MARK: - UIPickerViewDataSource
extension EditTableViewController:UIPickerViewDelegate,UIPickerViewDataSource{
//有幾個滾輪
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
//一個滾輪裡有幾行(row)
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
switch pickerView.tag{
case 1:
return storeArray.count
case 4:
return commentArray.count
default:
return 0 //隨便給值 因為不會飽到default段
}
}
//滾輪裡顯示陣列資料
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
switch pickerView.tag{
case 1:
return storeArray[row]
case 4:
return commentArray[row]
default:
return "Nothing"
}
}
//滾輪滾動到特定位置時TextField顯示該文字
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
switch pickerView.tag{
case 1:
storeTextField.text = storeArray[row]
case 4:
commentTextField.text = commentArray[row]
default:
break
}
}
} |
import { useNavigate } from 'react-router-dom';
import React from "react";
function HomePage(){
const navigate = useNavigate()
const [showModal, setShowModal] = React.useState(false)
return(
<div>
<div className='bg-green-300 max-w-xs p-5 rounded-md mx-auto my-24 flex flex-col items-center shadow-lg'>
<button type='submit' className="text-white px-2 font-bold bg-gray-400 rounded-md hover:bg-gray-700 mx-auto"
onClick={()=>navigate(`/Usuarios`)}>
Lista de Usuarios
</button>
<button type='submit' className="text-white my-4 px-2 font-bold bg-gray-400 rounded-md hover:bg-gray-700 mx-auto"
onClick={()=>navigate(`/Registro`)}>
Registrar Usuario
</button>
</div>
<>
<button
className="text-white my-4 px-2 font-bold bg-yellow-400 rounded-md hover:bg-yellow-700 mx-auto shadow-lg"
type="button"
onClick={() => setShowModal(true)}
>
Ayuda
</button>
{showModal ? (
<>
<div
className="justify-center items-center flex overflow-x-hidden overflow-y-auto fixed inset-0 z-50 outline-none focus:outline-none scrollbar"
>
<div className="relative w-auto my-6 mx-auto max-w-3xl">
<div className="border-0 rounded-lg shadow-lg relative flex flex-col w-full bg-white outline-none focus:outline-none">
<h1 className='my-4 mx-4 font-bold'>
Cómo se calcula el Índice de Masa Corporal (IMC):
</h1>
<div className="overflow-y-auto h-32 text-left my-2 mx-2 max-h-3xl">
<p>
El IMC se calcula dividiendo el peso de una persona en kilogramos
por el cuadrado de su estatura en metros. La fórmula es:
</p>
<p className='my-3'>
IMC=Peso (kg)/Estatura (m)^2
</p>
<p className='font-bold my-4'>Interpretación del IMC:</p>
<p className='my-2'>
El IMC se interpreta utilizando las siguientes categorías de estado
de peso estándar, aplicables a adultos de 20 años o más, independientemente
de su género y tipo de cuerpo
</p>
<p className='my-2'>
Bajo Peso (IMC por debajo de 18.5)
</p>
<p className='my-3'>
Indica que la persona puede tener un peso insuficiente en relación con su estatura.
Un bajo peso puede estar asociado con riesgos para la salud y requerir atención médica.
Normal (IMC 18.5 – 24.9)
</p>
<p className='my-3'>
Representa un rango considerado saludable en términos de peso corporal en relación con la estatura.
Menor riesgo de problemas de salud relacionados con el peso.
Sobrepeso (IMC 25.0 – 29.9)
</p>
<p className='my-3'>
Indica un exceso de peso en relación con la estatura. Aumenta el riesgo de desarrollar
problemas de salud como enfermedades cardiovasculares y diabetes.
Obesidad (IMC 30.0 o más)
</p>
<p className='my-3'>
Representa un rango considerado saludable en términos de peso corporal en relación con la estatura.
Menor riesgo de problemas de salud relacionados con el peso.
Sobrepeso (IMC 25.0 – 29.9)
</p>
<p className='my-3'>
Indica un exceso de peso en relación con la estatura. Aumenta el riesgo de desarrollar problemas de salud
como enfermedades cardiovasculares y diabetes.
Obesidad (IMC 30.0 o más)
</p>
<p className='my-3'>
Se refiere a un nivel de peso significativamente más alto de lo saludable en relación con la estatura.
Asociado con un mayor riesgo de diversas condiciones médicas. Uso del IMC como Herramienta de Detección
</p>
<p className='my-3'>
El IMC se utiliza como una herramienta de detección inicial para evaluar el peso corporal,
pero no diagnostica la grasa corporal ni la salud de un individuo de manera completa.
Para determinar si el exceso de peso representa un riesgo para la salud, se deben realizar
evaluaciones adicionales. Esto incluye mediciones del grosor de los pliegues cutáneos,
evaluaciones de la alimentación, actividad física y antecedentes familiares
</p>
<p className='my-3'>
Es fundamental tener en cuenta que la interpretación del IMC debe ser realizada por profesionales de la salud,
ya que cada persona es única y pueden existir otros factores que influyan en su salud general. Un proveedor
de atención médica puede brindar una evaluación completa y personalizada para determinar la salud y
el bienestar de un individuo.
</p>
</div>
<div className="flex items-center justify-end p-6 border-t border-solid border-blueGray-200 rounded-b">
<button
className="text-red-500 background-transparent font-bold uppercase px-6 text-sm outline-none focus:outline-none mr-1 mb-1 ease-linear transition-all duration-150"
type="button"
onClick={() => setShowModal(false)}
>
Close
</button>
</div>
</div>
</div>
</div>
<div className="opacity-25 fixed inset-0 z-40 bg-black"></div>
</>
) : null}
</>
</div>
)
}
export default HomePage |
package com.chslcompany.moviesapp.feature_movies.presentation
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.wrapContentHeight
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.ImageNotSupported
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.core.graphics.drawable.toBitmap
import androidx.navigation.NavHostController
import coil.compose.AsyncImagePainter
import coil.compose.rememberAsyncImagePainter
import coil.request.ImageRequest
import coil.size.Size
import com.chslcompany.moviesapp.BuildConfig
import com.chslcompany.moviesapp.feature_movies.presentation.favorites.viewmodel.FavoriteViewModel
import com.chslcompany.moviesapp.feature_movies.util.RatingBar
import com.chslcompany.moviesapp.feature_movies.util.Screens
import com.chslcompany.moviesapp.feature_movies.util.getAverageColor
import com.example.core.model.Movie
@OptIn(ExperimentalFoundationApi::class)
@Composable
fun MovieItem(
bottomNavController : NavHostController? = null,
movie: Movie,
navHostController: NavHostController,
viewModel: FavoriteViewModel
) {
val imageState = rememberAsyncImagePainter(
model = ImageRequest.Builder(LocalContext.current)
.data(BuildConfig.IMAGE_BASE_URL + movie.backdrop_path)
.size(Size.ORIGINAL)
.build()
).state
val defaultColor = MaterialTheme.colorScheme.secondaryContainer
var dominantColor by remember {
mutableStateOf(defaultColor)
}
Column(
modifier = Modifier
.wrapContentHeight()
.width(200.dp)
.padding(8.dp)
.clip(RoundedCornerShape(28.dp))
.background(
Brush.verticalGradient(
colors = listOf(
MaterialTheme.colorScheme.secondaryContainer,
dominantColor
)
)
)
.combinedClickable(
onClick = {
navHostController.navigate(Screens.Details.rout + "/${movie.id}")
},
onLongClick = {
viewModel.addFavorite(movie)
bottomNavController?.navigate(Screens.FavoriteMovieList.rout)
},
onDoubleClick = {
viewModel.removeFavorite(movie)
navHostController.navigate(Screens.Home.rout)
}
)
) {
if (imageState is AsyncImagePainter.State.Error) {
Box(
modifier = Modifier
.fillMaxWidth()
.padding(6.dp)
.height(250.dp)
.clip(RoundedCornerShape(22.dp))
.background(MaterialTheme.colorScheme.primaryContainer),
contentAlignment = Alignment.Center
) {
Icon(
modifier = Modifier.size(70.dp),
imageVector = Icons.Rounded.ImageNotSupported,
contentDescription = movie.title
)
}
}
if (imageState is AsyncImagePainter.State.Success) {
dominantColor = getAverageColor(
imageBitmap = imageState.result.drawable.toBitmap().asImageBitmap()
)
Image(
modifier = Modifier
.fillMaxWidth()
.padding(6.dp)
.height(250.dp)
.clip(RoundedCornerShape(22.dp)),
painter = imageState.painter,
contentDescription = movie.title,
contentScale = ContentScale.Crop
)
}
Spacer(modifier = Modifier.height(6.dp))
Text(
modifier = Modifier.padding(start = 16.dp, end = 8.dp),
text = movie.title,
color = Color.White,
fontSize = 15.sp,
maxLines = 1
)
Row (
modifier = Modifier
.fillMaxWidth()
.padding(start = 16.dp, bottom = 12.dp, top = 4.dp)
) {
RatingBar(
starsModifier = Modifier.size(18.dp),
rating = movie.vote_average / 2
)
Text(
modifier = Modifier.padding(start = 4.dp),
text = movie.vote_average.toString().take(3),
color = Color.LightGray,
fontSize = 14.sp,
maxLines = 1,
)
}
}
} |
---
layout: post
title: counting paths
date: 2014-09-19
...
Consider the grid below. If you can only move right and down, how many distinct
paths are possible from the upper left corner to the lower right corner?

This problem can be solved in a number of ways. The most obvious is to manually
count each path individually (brute force). This solution is reasonable for very
small grids, but as the grid size increases, it quickly becomes impractical and
highly inefficient, and there is a much more elegant and efficient solution.
## Recursion to the Rescue
This problem is an excellent example of a problem that can be solved relatively
easily by dividing the problem into much smaller problems, solving each of those,
and combining the answers to solve the bigger problem. The simplest case of the
general problem of counting paths on a grid is counting the number of possible
paths that can be taken on a straight line. Obviously, there is only one possible
path if you are constrained to a single line, so this simple case is easily
solved. The grid above can be divided into straight lines, but right now we lack
a way to combine this simple cases.
To see the method to combine these subproblems, consider the square in the
lower left corner of the grid. There is one path from the bottom-left corner or
the top-right corner to the bottom-right corner, and there are two paths from
the top-left to bottom-right. The number of paths is the sum of the number of
paths from the vertex one edge down and the number of paths from the vertex one
edge to the right. We now have the tools to define a function taking two
coordinates and returning the number of paths to the bottom-right corner.
<img src='./assets/grid.png' width='50%' alt='grid'></img>
```
#Base cases
paths(x,0) = 1
paths(0,y) = 1
paths(x,y) = paths(x-1, y) + paths(x, y-1)
```
In this recursive algorithm, the base cases are the vertices on the bottom and
right edges of the grid. The value at all other vertices is calculated using the
recursive formula above. The total number of paths of a grid of `m` squares by
`n` squares is `paths(m, n)`.
This recursive algorithm can be implemented in a relatively straightforward
manner in any language.
## Dynamic Programming
If you analyze the necessary function calls of the recursive algorithm above,
you will notice that many calls are repeated. The larger the grid gets, the
more repeated calls are made. Each time the function is called with the same
arguments, it yields exactly the same answer, so repeating the computation is
wasteful and terribly inefficient.
A simple idea can lead to tremendous increases in speed in this algorithm, and
the same concept can be applied in a wide range of problems. The idea is that
each time a subproblem is completed, the value associated with that subproblem
is cached (recorded somewhere and remembered). This process is known as
_memoization_.
```
memo = 2d array
paths(x, y):
if x is 0 or y is 0 return 1
otherwise
if memo[x,y] is not set:
memo[x,y] = paths(x-1,y) + paths(x,y-1)
return memo[x,y]
else
return memo[x,y]
```
Instead of wastefully repeating the same calculations over and over again, the
algorithm 'remembers' whether the calculation has been completed already and
simply returns the prior result if it has. This relatively simple change to the
algorithm has amazingly significant effects for the performance and efficiency
of the algorithm.
## Analytic Solution
I feel that the recursive solution discussed above is more interesting, but for
the more mathematically inclined it is worth noting that there is an analytic
solution. If each distinct path is viewed as a sequence of moves (either down
or left), the solution is equivalent to the number of `m+n` symbol words with
`m` moves down and `n` moves right, or `(m+n) choose m`.
## See Also:
- [Counting Lattice Paths - Good Diagrams](http://www.robertdickau.com/lattices.html)
- [AoPS Block Walking](http://www.artofproblemsolving.com/Wiki/index.php/Block_walking)
- [Wikipedia: Dynamic Programming](http://en.wikipedia.org/wiki/Dynamic_programming) |
"use client"
import React, { useEffect, useState } from 'react';
async function loadServices() {
const response = await fetch('/api/services');
const data = await response.json();
return data.services;
}
function ServicesList() {
const [services, setServices] = useState([]);
useEffect(() => {
const fetchData = async () => {
const result = await loadServices();
setServices(result);
};
fetchData();
}, []);
return (
<section className="text-gray-600 body-font bg-blue-100">
<div className="container px-5 py-24 mx-auto">
<div className="flex flex-col">
<div className="h-1 bg-gray-200 rounded overflow-hidden">
<div className="w-24 h-full bg-blue-600"></div>
</div>
<div className="flex flex-wrap sm:flex-row flex-col py-6 mb-12">
<h1 className="sm:w-2/5 text-gray-900 font-medium title-font text-2xl mb-2 sm:mb-0">Servicios</h1>
<p className="sm:w-3/5 leading-relaxed text-base sm:pl-10 pl-0">Con ejercicio terapéutico, educación y fisioterapia soy el encargado de asistrir una recuperación de la que tú debes ser protagonista.</p>
</div>
</div>
<div className="flex flex-wrap sm:-m-4 -mx-4 -mb-10 -mt-4">
{services.map((service) => (
<div key={service.id} className="p-4 md:w-1/3 sm:mb-0 mb-6">
<div className="rounded-lg h-64 overflow-hidden">
<img alt="content" className="object-cover object-center h-full w-full" src={service.image} />
</div>
<h2 className="text-xl font-medium title-font text-gray-900 mt-5">{service.title}</h2>
<p className="text-base leading-relaxed mt-2">{service.description}</p>
<a href="#" className="text-blue-600 inline-flex items-center mt-3">Aprender Más
<svg fill="none" stroke="currentColor" strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" className="w-4 h-4 ml-2" viewBox="0 0 24 24">
<path d="M5 12h14M12 5l7 7-7 7"></path>
</svg>
</a>
</div>
))}
</div>
</div>
</section>
);
}
export default ServicesList; |
package com.ohgiraffers.section01.object.run;
import com.ohgiraffers.section01.object.book.Book;
public class Application1 {
// Object 클래스의 toString
public static void main(String[] args) {
/*
* Object
*
* 모든 클래스는 Object 클래스의 후손이다.
* 따라서 Object 클래스가 가진 메소드를 자신의 것처럼 사용 할 수 있다.
* 또한 부모클래스가 가지는 메소드를 오버라이딩 하여 사용하는 것도 가능하다.
*
* Object 클래스의 메소드 중 많이 오버라이딩해서 사용하는 메소드들
* toStirng(), equals(), hashCode()
* */
Book book1 = new Book(1, "홍길동전", "허균", 50000);
Book book2 = new Book(2, "목민심서", "정약욕", 30000);
Book book3 = new Book(2, "목민심서", "정약용", 30000);
System.out.println("book1.toString = " + book1.toString());
System.out.println("book2.toString = " + book2.toString());
System.out.println("book3.toString = " + book3.toString());
System.out.println("boo1 = " + book1);
System.out.println("boo2 = " + book2);
System.out.println("boo3 = " + book3);
}
} |
import jQuery from 'jquery';
import { Model } from '../model';
import { buildSearchResults } from './searchResults';
function getPaginationHtml() {
// const pagesCount = Model.pagesCount;
// const currentPage = Model.currentPage;
const { currentPage, pagesCount } = Model;
const prevButton = `
<li class="js-btn-prev ${currentPage === 0 ? 'disabled' : ''}">
<a href="#">
<span class="sprite sprite-arrow-left-icon"></span>
</a>
</li>
`;
const nextButton = `
<li class="js-btn-next ${currentPage === pagesCount - 1 ? 'disabled' : ''}">
<a href="#">
<span class="sprite sprite-arrow-right-icon"></span>
</a>
</li>
`;
const paginationHtml = [...new Array(pagesCount)] // spread
.map(function(v, index) {
return `
<li class="js-btn-page ${currentPage === index ? 'active' : ''}">
<a href="#">${index + 1}</a>
</li>`;
})
.join('');
return `${prevButton}${paginationHtml}${nextButton}`;
}
function attachEvents() {
const prevButton = jQuery('.search-pagination .js-btn-prev a');
const nextButton = jQuery('.search-pagination .js-btn-next a');
const pageButtons = jQuery('.search-pagination .js-btn-page a');
prevButton.on('click', function(e) {
e.preventDefault();
if (Model.currentPage > 0) {
changePage(Model.currentPage - 1);
}
});
nextButton.on('click', function(e) {
e.preventDefault();
if (Model.currentPage < Model.pagesCount - 1) {
changePage(Model.currentPage + 1);
}
});
pageButtons.each(function(index, elem) {
jQuery(elem).on('click', function(e) {
e.preventDefault();
if (index !== Model.currentPage) {
changePage(index);
}
});
});
}
function buildPagination() {
const container = jQuery('.search-pagination');
container.html(getPaginationHtml());
attachEvents();
}
function changePage(page) {
Model.currentPage = page;
buildPagination();
buildSearchResults();
}
buildPagination();
buildSearchResults(); |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//*-----------------------------
using SalonBelleza.EntidadesDeNegocio;
using SalonBelleza.AccesoADatos;
namespace SalonBelleza.LogicaDeNegocio
{
/// <summary>
/// Esta clase es de la entidad Servicio de la capa Logica de De Negocio
/// Esta clase contiene Los metodos CRUD de Servicio
///
/// </summary>
public class ServicioBL
{
/// <summary>
/// Metodo para crear un Nuevo Servicio.
/// </summary>
/// <param name="pServicio">Se espera un objeto del Tipo Servicio, con sus valores llenos</param>
/// <returns>Retorna una tarea Asyncrona</returns>
///
public async Task<int> CrearAsync(Servicio pServicio)
{
return await ServicioDAL.CrearAsync(pServicio);
}
/// <summary>
/// Metodo para Modificar un Servicio si encuentra coincidencia en la base de datos.
/// </summary>
/// <param name="pServicio">Se espera un objeto del Tipo Servicio, con sus valores llenos</param>
/// <returns>Retorna una tarea Asyncrona</returns>
///
public async Task<int> ModificarAsync(Servicio pServicio)
{
return await ServicioDAL.ModificarAsync(pServicio);
}
/// <summary>
/// Metodo para Eliminar un servicio si encuentra un Id como coincidencia.
/// </summary>
/// <param name="pServicio">Se espera un objeto del Tipo Servicio, con sus valores llenos</param>
/// <returns>Retorna una tarea Asyncrona</returns>
///
public async Task<int> EliminarAsync(Servicio pServicio)
{
return await ServicioDAL.EliminarAsync(pServicio);
}
/// <summary>
/// Metodo para Obtener un Servicio Por ID
/// </summary>
/// <param name="pServicio">Se espera un objeto del Tipo Cliente, con sus valores llenos</param>
/// <returns>Retorna una tarea Asyncrona</returns>
///
public async Task<Servicio> ObtenerPorIdAsync(Servicio pServicio)
{
return await ServicioDAL.ObtenerPorIdAsync(pServicio);
}
/// <summary>
/// Metodo para Obtener Todos los Servicios
/// </summary>
/// <returns>Retorna una tarea Asyncrona</returns>
///
public async Task<List<Servicio>> ObtenerTodosAsync()
{
return await ServicioDAL.ObtenerTodosAsync();
}
/// <summary>
/// Metodo para Buscar un Cliente Async
/// </summary>
/// <param name="pServicio">Se espera un objeto del Tipo Usuario, con sus valores llenos</param>
/// <returns>Retorna una tarea Asyncrona</returns>
///
public async Task<List<Servicio>> BuscarAsync(Servicio pServicio)
{
return await ServicioDAL.BuscarAsync(pServicio);
}
}
} |
// React
import React, { useState } from 'react';
import { FormProvider, useForm } from 'react-hook-form';
import { useDispatch } from 'react-redux';
// MUI
import { styled } from '@mui/styles';
import { Stack, Box, Grid, Typography } from '@mui/material';
// App Components
import Fade from 'components/Common/Fade';
import InputField from 'components/Common/InputField';
// API
import { updateDealId, fetchOverview } from 'store/reducers/concept';
// Utilities
import { appColors } from 'theme/variables';
import PropTypes from 'prop-types';
import parse from 'html-react-parser';
import _ from 'lodash';
// Grid
const StyledGridItem = styled(Grid)({
fontSize: '1rem',
'&:nth-of-type(even)': {
color: appColors.darkGray,
},
});
// Tag
const StyledTag = styled(Box)(({ isColored, theme }) => ({
paddingLeft: '0.8rem',
paddingRight: '0.8rem',
border: isColored
? `1px solid ${theme.palette.secondary.main}`
: `1px solid ${appColors.darkGray}`,
borderRadius: 4,
color: isColored ? theme.palette.secondary.main : appColors.darkGray,
backgroundColor: appColors.lighterGray,
textTransform: 'capitalize',
}));
// Div
const StyledDiv = styled('div')(() => ({
display: 'flex',
flexWrap: 'wrap',
'& .MuiBox-root': {
marginRight: 10,
marginBottom: 10,
},
}));
// Counter
const StyledCounter = styled('div')(() => ({
display: 'flex',
width: 18,
height: 18,
color: 'white',
borderRadius: 9,
alignItems: 'center',
justifyContent: 'center',
fontSize: '0.7rem',
backgroundColor: appColors.lightViolet,
}));
const ProjectNavigationAccordionDetails = ({ data }) => {
const methods = useForm();
const [dealId, setDealId] = useState('');
const [isEditing, setEditing] = useState(false);
const dispatch = useDispatch();
const {
concept,
objectives,
formats,
lang,
additional_info,
partner_market,
} = data;
const objectivesData = !_.isEmpty(objectives.elements)
? objectives.elements.map((objective) => ({
value: objective,
isTagged: true,
isColored: false,
}))
: [];
const productMarketsData = !_.isEmpty(partner_market)
? partner_market.map((product) => ({
value: product,
isTagged: true,
}))
: [];
const languagesData = !_.isEmpty(lang)
? lang.map((language) => ({
value: language,
isTagged: true,
}))
: [];
// Facebook format
const facebookStaticFormatData = !_.isEmpty(formats.facebook.static)
? formats.facebook.static.map((format) => ({
value: format,
isTagged: true,
isColored: true,
}))
: [];
const facebookVideoFormatData = !_.isEmpty(formats.facebook.video)
? formats.facebook.video.map((format) => ({
value: format,
isTagged: true,
isColored: true,
}))
: [];
// Google format
const googleDisplayFormatData = !_.isEmpty(formats.google.display)
? formats.google.display.map((format) => ({
value: format,
isTagged: true,
isColored: true,
}))
: [];
const googleVideoFormatData = !_.isEmpty(formats.google.video)
? formats.google.video.map((format) => ({
value: format,
isTagged: true,
isColored: true,
}))
: [];
// Youtube format
const youtubeVideoFormatData = !_.isEmpty(formats.youtube.video)
? formats.youtube.video.map((format) => ({
value: format,
isTagged: true,
isColored: true,
}))
: [];
const datasets = [
// Deal ID
{
title: 'Deal ID',
descriptions: [
{
value: concept.deal_id ?? '-',
isTagged: false,
isEditable: true,
},
],
},
// Concept name
{
title: 'Concept Name',
descriptions: [
{
value: concept.name ?? '',
isTagged: false,
},
],
},
// Objectives
!_.isEmpty(objectivesData)
? {
title: 'Objectives',
descriptions: objectivesData,
}
: {},
// Product/Markets
!_.isEmpty(productMarketsData)
? {
title: 'Product/Markets',
descriptions: productMarketsData,
}
: {},
// Languages
!_.isEmpty(languagesData)
? {
title: 'Language',
descriptions: languagesData,
}
: {},
// Format
{
title: 'Format',
descriptions: [
{
value: 'Facebook & Instagram (<b>Video</b>)',
isTagged: false,
},
],
counter:
facebookStaticFormatData.length +
facebookVideoFormatData.length +
youtubeVideoFormatData.length +
googleDisplayFormatData.length +
googleVideoFormatData.length,
},
!_.isEmpty(facebookVideoFormatData)
? {
title: '',
descriptions: facebookVideoFormatData,
}
: {
title: '',
descriptions: [
{
value: '-- No Format Available --',
isTagged: false,
},
],
},
// Facebook & Instagram Static
!_.isEmpty(facebookStaticFormatData)
? {
title: '',
descriptions: [
{
value: 'Facebook & Instagram (<b>Static</b>)',
isTagged: false,
},
],
}
: {},
!_.isEmpty(facebookStaticFormatData)
? {
title: '',
descriptions: facebookStaticFormatData,
}
: {},
// Youtube Video
!_.isEmpty(youtubeVideoFormatData)
? {
title: '',
descriptions: [
{
value: 'Youtube (<b>Video</b>)',
isTagged: false,
},
],
}
: {},
!_.isEmpty(youtubeVideoFormatData)
? {
title: '',
descriptions: youtubeVideoFormatData,
}
: {},
// Google Display
!_.isEmpty(googleDisplayFormatData)
? {
title: '',
descriptions: [
{
value: 'Google (<b>Display</b>)',
isTagged: false,
},
],
}
: {},
!_.isEmpty(googleDisplayFormatData)
? {
title: '',
descriptions: googleDisplayFormatData,
}
: {},
// Google Video
!_.isEmpty(googleVideoFormatData)
? {
title: '',
descriptions: [
{
value: 'Google (<b>Video</b>)',
isTagged: false,
},
],
}
: {},
!_.isEmpty(googleVideoFormatData)
? {
title: '',
descriptions: googleVideoFormatData,
}
: {},
!_.isEmpty(additional_info)
? {
title: 'Additional Info',
descriptions: [
{
value: additional_info,
isTagged: false,
},
],
}
: {
title: 'Additional Info',
descriptions: [
{
value: '-- No Additional Info Available --',
isTagged: false,
},
],
},
];
const renderDescription = (data) => {
return data.descriptions.map((description, index) => {
if (description.isTagged) {
return (
<StyledTag key={index} isColored={description.isColored}>
{description.value}
</StyledTag>
);
} else {
if (description.isEditable && isEditing) {
return (
<Fade key={index} in={true}>
<FormProvider {...methods}>
<InputField
name="deal_id"
placeholder="Deal ID"
variant="input"
content={dealId}
onKeyPress={(e) => {
if (e.key == 'Enter') {
if (isEditing) {
setEditing(false);
dispatch(
updateDealId({
id: concept.id,
deal_id: e.target.value,
})
);
setDealId(e.target.value);
dispatch(
fetchOverview({
conceptId: concept.uuid,
partnerId: concept.partner_uuid,
})
);
}
}
}}
/>
</FormProvider>
</Fade>
);
} else {
return (
<Typography
key={index}
variant="span"
sx={{ whiteSpace: 'pre-line' }}
>
{parse(description.value)}
</Typography>
);
}
}
});
};
return (
<Grid container spacing={1.8} ml={0.5} mt={0}>
{datasets.map((data, index) => {
if (_.isEmpty(data)) {
return;
}
return (
<React.Fragment key={index}>
<StyledGridItem item xs={2}>
<Stack direction="row" alignItems="center">
{data.title}
{data.counter > 0 && (
<StyledCounter>{data.counter}</StyledCounter>
)}
</Stack>
</StyledGridItem>
<StyledGridItem item xs={10}>
<StyledDiv
onDoubleClick={() => {
if (index === 0 && !isEditing) {
setEditing(true);
}
}}
>
{renderDescription(data)}
</StyledDiv>
</StyledGridItem>
</React.Fragment>
);
})}
</Grid>
);
};
ProjectNavigationAccordionDetails.propTypes = {
data: PropTypes.object.isRequired,
};
export default ProjectNavigationAccordionDetails; |
import { AsyncPipe } from '@angular/common';
import { ChangeDetectionStrategy, Component } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { ColumnConfig, ColumnType, TableComponent as TableComponentFromLib } from '@bolzplatzarena/components';
import { TranslateModule } from '@ngx-translate/core';
import { delay, interval, mergeMap, of, startWith } from 'rxjs';
import { Hero } from '../../models/hero';
import { HeroType } from '../../models/hero-type';
@Component({
selector: 'app-table',
templateUrl: './table.component.html',
changeDetection: ChangeDetectionStrategy.OnPush,
standalone: true,
imports: [
AsyncPipe,
TableComponentFromLib,
TranslateModule,
],
})
export class TableComponent {
protected readonly data: Hero[] = [
{
name: 'Thor',
level: 100,
type: HeroType.Hammer,
health: 1000,
birthday: new Date(1970, 11, 14),
},
{
name: 'Captain',
level: 100,
type: HeroType.Fighter,
health: 1000,
birthday: new Date(1930, 1, 1),
},
{
name: 'Captain America',
level: 100,
type: HeroType.Fighter,
health: 12000,
birthday: new Date(1934, 8, 18),
},
{
name: 'Nick Fury',
level: 100,
type: HeroType.Fighter,
health: 10400,
birthday: new Date(1932, 7, 1),
},
{
name: 'Black Window',
level: 120,
type: HeroType.Spy,
health: 2000,
birthday: new Date(1931, 1, 1),
},
{
name: 'Iron Man',
level: 80,
type: HeroType.Scientist,
health: 3000,
birthday: new Date(1931, 1, 1),
},
{
name: 'Hulk',
level: 120,
type: HeroType.Fighter,
health: 1000,
birthday: new Date(1931, 1, 23),
},
{
name: 'Doc Brown',
level: 120,
type: HeroType.Scientist,
health: 1000,
birthday: new Date(1931, 1, 12),
},
{
name: 'Spider Man',
level: 120,
type: HeroType.Fighter,
health: 4000,
birthday: new Date(1991, 3, 1),
},
{
name: 'Hawk Eye',
level: 110,
type: HeroType.Fighter,
health: 6000,
birthday: new Date(1991, 2, 1),
},
{
name: 'Loki',
level: 110,
type: HeroType.Fighter,
health: 1000,
birthday: new Date(1991, 1, 1),
},
];
protected readonly config: { [key: string]: ColumnConfig<Hero> } = {
'name': { type: ColumnType.Unknown, cssClass: 'tw-w-32' },
'birthday': { type: ColumnType.Date, cssClass: 'tw-w-32' },
'type': { type: ColumnType.Enum, args: HeroType, cssClass: 'tw-w-32' },
'level': { type: ColumnType.Number, cssClass: 'tw-w-32' },
'health': { type: ColumnType.Number, cssClass: 'tw-w-32' },
'custom': { type: ColumnType.Unknown, getter: (hero: Hero) => `${hero.name} ${hero.level}` },
};
protected readonly data$ = interval(3000).pipe(
mergeMap(() => of(this.data).pipe(
delay(1500),
startWith(null),
)),
takeUntilDestroyed(),
);
protected die(hero: Hero): void {
alert(`Die: ${hero.name}`);
}
protected view(hero: Hero): void {
alert(`View: ${hero.name}`);
}
} |
<!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>Create Product</title>
</head>
<!--LIBRERIAS -->
<!--Librería cdn que provee bootstrap, permite acceder a todos los elementos de diseño de la librería-->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-KyZXEAg3QhqLMpG8r+8fhAXLRk2vvoC2f3B09zVXn8CA5QIVfZOJ3BCsw2P0p/We" crossorigin="anonymous">
<div class="col-lg-6 offset-sm-3">
<form (ngSubmit)= "createProduct()" #form="ngForm" class="form-horizontal" >
<fieldset>
<!-- Form Name -->
<!-- <legend>{{edit?"Update Product":"Create Product"}}</legend> -->
<!-- Text input-->
<div class="form-group">
<label class="col-md-12 control-label" for="category">Product Category</label>
<div class="col-md-12">
<input id="category" name="category" type="text" [(ngModel)]="product.category"
placeholder="Product Category" class="form-control input-md" required="">
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class="col-md-12 control-label" for="name">Product name</label>
<div class="col-md-12">
<input id="name" name="name" type="text" [(ngModel)]="product.name"
placeholder="Product name" class="form-control input-md" required="">
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class="col-md-12 control-label" for="unitValue">Product unitValue</label>
<div class="col-md-12">
<input id="unitValue" name="unitValue" type="number" [(ngModel)]="product.unitValue"
placeholder="Product unitValue" class="form-control input-md" required="">
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class="col-md-12 control-label" for="stock">Product stock</label>
<div class="col-md-12">
<input id="stock" name="stock" type="number" [(ngModel)]="product.stock"
placeholder="Product stock" class="form-control input-md" required="">
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class="col-md-12 control-label" for="stock">Product description</label>
<div class="col-md-12">
<input id="description" name="description" type="text" [(ngModel)]="product.description"
placeholder="Product description" class="form-control input-md" required="">
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class="col-md-12 control-label" for="image">Product Image</label>
<div class="col-md-12">
<input id="image" name="image" type="text" [(ngModel)]="product.image"
placeholder="Product Image" class="form-control input-md" required="">
</div>
</div>
<!-- Button (Double) -->
<div class="form-gro+*9-++++++up">
<label class="col-md-12 control-label" for="sumit"></label>
<div class="col-md-12">
<button id="sumit" name="sumit" class="btn btn-primary">Save</button>
<a id="cancel" name="cancel" class="btn btn-danger" [routerLink]="['/product/list']" routerLinkActive="router-link-active" >Cancel</a>
</div>
</div>
</fieldset>
</form>
</div> |
package com.sample.pianoguide
import android.app.Activity
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothManager
import android.bluetooth.le.BluetoothLeScanner
import android.bluetooth.le.ScanCallback
import android.bluetooth.le.ScanResult
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.util.Log
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.material3.Button
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.core.app.ActivityCompat.startActivityForResult
import androidx.core.content.ContextCompat
import androidx.core.content.ContextCompat.getSystemService
import com.sample.pianoguide.MainActivity.Companion.ENABLE_BT
import com.sample.pianoguide.ui.theme.PianoguideTheme
class MainActivity : ComponentActivity() {
// TODO: lazy
var blManager: BluetoothManager? = null
var blAdapter: BluetoothAdapter? = null
private var bluetoothLeScanner: BluetoothLeScanner? = null
private var scanning = false
private val handler = Handler()
// Stops scanning after 10 seconds.
private val SCAN_PERIOD: Long = 10000
// private val leDeviceListAdapter = BaseAdapter()
// Device scan callback.
// private val leScanCallback: ScanCallback = object : ScanCallback() {
// override fun onScanResult(callbackType: Int, result: ScanResult) {
// super.onScanResult(callbackType, result)
// leDeviceListAdapter.addDevice(result.device)
// leDeviceListAdapter.notifyDataSetChanged()
// }
// }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
blManager = ContextCompat.getSystemService(this, BluetoothManager::class.java)
Log.d("zzz", "blManager = $blManager")
blAdapter = blManager?.adapter
bluetoothLeScanner = blAdapter?.bluetoothLeScanner
var buttonText: String = "send json"
val btEnable: () -> Unit = {
blAdapter?.let {
Log.d("zzz", "adapter not null")
if (!it.isEnabled) {
val enableBtIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
startActivityForResult(
this,
enableBtIntent,
ENABLE_BT,
null
)
} else {
setContent {
ShowBlueToothList()
}
}
}
}
setContent {
PianoguideTheme {
// A surface container using the 'background' color from the theme
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
BluetoothButton(
btEnable,
buttonText,
modifier = Modifier
.wrapContentSize(),
)
}
}
}
}
// private fun scanLeDevice() {
// if (!scanning) { // Stops scanning after a pre-defined scan period.
// handler.postDelayed({
// scanning = false
// bluetoothLeScanner.stopScan(leScanCallback)
// }, SCAN_PERIOD)
// scanning = true
// bluetoothLeScanner.startScan(leScanCallback)
// } else {
// scanning = false
// bluetoothLeScanner.stopScan(leScanCallback)
// }
// }
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == ENABLE_BT &&
resultCode == RESULT_OK &&
data != null &&
data.data != null) {
// scan
// setContent {
// ShowBlueToothList()
// }
}
}
companion object {
const val ENABLE_BT = 9
}
}
@Composable
fun Greeting(name: String, modifier: Modifier = Modifier) {
Text(
text = "Hello $name!",
modifier = modifier
)
}
@Composable
fun BluetoothButton(enableBtClick: () -> Unit, buttonText: String, modifier: Modifier = Modifier) {
Button(
onClick = enableBtClick)
{
Text(text = buttonText)
}
}
@Preview(showBackground = true)
@Composable
fun ButtonPreview() {
PianoguideTheme {
BluetoothButton({}, "send json")
}
} |
import unittest
import types
import asyncio
import random
# 1. 普通汉书
def function():
return 1
# 2. 生成器函数
def generator():
yield 1
# 3. 异步函数(协程)
async def async_function():
return 1
# 4. 异步生成器
async def async_generator():
yield 1
def run(coroutine):
try:
coroutine.send(None)
except StopIteration as e:
return e.value
async def await_coroutine():
result = await async_function()
class Potato:
@classmethod
def make(cls, num, *args, **kws):
potatos = []
for i in range(num):
potatos.append(cls.__new__(cls, *args, **kws))
return potatos
all_potatos = Potato.make(5)
async def take_potatos(num):
count = 0
while True:
if len(all_potatos) == 0:
await ask_for_potato()
potato = all_potatos.pop()
yield potato
count += 1
if count == num:
break
async def ask_for_potato():
await asyncio.sleep(random.random())
all_potatos.extend(Potato.make(random.randint(1, 10)))
async def buy_potatos():
bucket = []
async for p in take_potatos(3):
bucket.append(p)
class AsyncTest(unittest.TestCase):
"""
Test the add function from the mymath library
"""
def test_async1(self):
self.assertTrue(type(function) is types.FunctionType)
self.assertTrue(type(generator()) is types.GeneratorType)
self.assertTrue(type(async_generator()) is types.AsyncGeneratorType)
# self.assertTrue(type(async_function()) is types.CoroutineType)
run(await_coroutine())
def test_async2(self):
loop = asyncio.get_event_loop()
res = loop.run_until_complete(buy_potatos())
loop.close() |
"use client";
import { NextPage } from "next";
import Link from "next/link";
import { usePathname } from "next/navigation";
import s from "@/components/ui/header/navigation/navigation.module.scss";
type Link = {
path: string;
label: string;
};
interface Props {
links: Link[];
}
const Navigation: NextPage<Props> = ({ links }) => {
const pathname = usePathname();
return (
<nav className={s.nav}>
{links.map((el) => {
const isActive = pathname === el.path;
return (
<Link className={!isActive ? s.nav_active : s.nav_inactive} href={el.path}>
{el.label}
</Link>
);
})}
</nav>
);
};
export default Navigation; |
const baseUrl = 'https://pokeapi.co/api/v2/pokemon/';
let currentPokemonIndex = 1;
function displayPokemon() {
const url = `${baseUrl}${currentPokemonIndex}`;
fetch(url)
.then(response => response.json())
.then(data => {
const name = data.name;
const number = data.id;
const type = data.types[0].type.name;
const image = data.sprites.front_default;
document.getElementById('pokemon-name').innerText = name;
document.getElementById('pokemon-number').innerText = `#${number}`;
document.getElementById('pokemon-type').innerText = `Type: ${type}`;
document.getElementById('pokemon-image').src = image;
})
.catch(error => console.error('Error fetching Pokemon:', error));
}
function changePokemon(direction) {
if (direction === 'next') {
currentPokemonIndex++;
} else if (direction === 'previous') {
currentPokemonIndex = Math.max(1, currentPokemonIndex - 1);
}
displayPokemon();
}
function searchPokemon() {
const searchTerm = document.getElementById('search-input').value.toLowerCase();
fetch(`${baseUrl}${searchTerm}`)
.then(response => response.json())
.then(data => {
currentPokemonIndex = data.id;
displayPokemon();
})
.catch(error => {
// Caso a pesquisa não encontre, exibir o Pokémon mais próximo
console.error('Error searching Pokemon:', error);
searchClosestPokemon(searchTerm);
});
}
function searchClosestPokemon(searchTerm) {
fetch(baseUrl)
.then(response => response.json())
.then(data => {
const pokemonList = data.results;
const closestPokemon = pokemonList.reduce((closest, pokemon) => {
const distance = levenshteinDistance(searchTerm, pokemon.name);
return distance < closest.distance ? { distance, pokemon } : closest;
}, { distance: Infinity, pokemon: null });
currentPokemonIndex = closestPokemon.pokemon.url.split('/').slice(-2, -1)[0];
displayPokemon();
})
.catch(error => console.error('Error searching closest Pokemon:', error));
}
// Função para calcular a distância de Levenshtein entre duas strings
function levenshteinDistance(a, b) {
if (a.length === 0) return b.length;
if (b.length === 0) return a.length;
const matrix = Array.from({ length: a.length + 1 }, () => Array(b.length + 1).fill(0));
for (let i = 0; i <= a.length; i++) {
matrix[i][0] = i;
}
for (let j = 0; j <= b.length; j++) {
matrix[0][j] = j;
}
for (let i = 1; i <= a.length; i++) {
for (let j = 1; j <= b.length; j++) {
const cost = a[i - 1] === b[j - 1] ? 0 : 1;
matrix[i][j] = Math.min(
matrix[i - 1][j] + 1,
matrix[i][j - 1] + 1,
matrix[i - 1][j - 1] + cost
);
}
}
return matrix[a.length][b.length];
}
// Exibição inicial
displayPokemon(); |
import './style.css'
import { Todo } from './model/todo.ts'
import LocalStorage from './storage/localstorage.ts'
import ModelRepository from './repository/modelRepository.ts'
import todoTemplate from './model/todoTemplate.html?raw'
import render from './templates/template.ts'
const repository = new ModelRepository(Todo, new LocalStorage('Todo'))
function getFilter (): string {
return (document.getElementById('filter-select') as HTMLSelectElement).value
}
function renderTodos (todos: Todo[]): void {
const filter = getFilter()
const app = document.querySelector('#app') as HTMLDivElement
app.replaceChildren()
app.innerHTML = ''
const nodes = todos
.filter((e) => {
switch (filter) {
case 'done':
return e.done
case 'skip':
return e.skip
default:
return true
}
})
.map(e => {
const checkContext = { doneChecked: '', skipChecked: '' }
checkContext.doneChecked = e.done ? 'checked' : ''
checkContext.skipChecked = e.skip ? 'checked' : ''
return render(todoTemplate, e, checkContext)
})
app.innerHTML = nodes.join('')
}
renderTodos(repository.getAll());
(document.querySelector('#new-todo') as HTMLButtonElement).addEventListener('click', () => {
const elem = document.querySelector('#new-todo-text') as HTMLTextAreaElement
const value = elem.value === '' ? 'empty' : elem.value
elem.value = ''
const newTodo = new Todo(value, false, false)
repository.add(newTodo)
renderTodos(repository.getAll())
});
(document.getElementById('filter-select') as HTMLSelectElement).addEventListener('change', () => { renderTodos(repository.getAll()) })
document.addEventListener('renderTodos', () => {
renderTodos(repository.getAll())
})
document.addEventListener('todoEventDelete', (e) => {
const target = e.target as HTMLButtonElement
const todo: Todo | null = repository.get(+target.value)
if (todo !== null) {
repository.remove(todo)
renderTodos(repository.getAll())
}
})
document.addEventListener('todoEventToggleDone', (e) => {
const target = e.target as HTMLInputElement
const todo = repository.get(+target.value)
if (todo !== null) {
todo.toggleDone()
repository.set(todo)
renderTodos(repository.getAll())
}
})
document.addEventListener('todoEventToggleSkip', (e) => {
const target = e.target as HTMLInputElement
const todo = repository.get(+target.value)
if (todo !== null) {
todo.toggleSkip()
repository.set(todo)
renderTodos(repository.getAll())
}
}) |
from diffusion_kinetics.optimization.forward_model_kinetics import forwardModelKinetics
from diffusion_kinetics.optimization.forward_model_kinetics import calc_lnd0aa
from diffusion_kinetics.optimization.dataset import Dataset
import math as math
import torch as torch
import numpy as np
class DiffusionObjective:
def __init__(
self,
data: Dataset,
time_add: list,
temp_add: list,
omitValueIndices=[],
stat: str = "chisq",
geometry: str = "spherical",
punish_degas_early:bool = True
):
"""
This function forward models a set of MDD parameters and returns a residual based on the specified misfit statistic.
Args:
data (Dataset): the dataset to be used for the objective function.
time_add (list): the times of the extra heating steps to be added to the dataset.
temp_add array (list): the temperatures of the extra heating steps to be added to the dataset.
omitValueIndices (list, optional): the indices of the values to be omitted from the objective function. Defaults to [].
stat (str, optional): the statistic to be used for the objective function. Defaults to "chisq".
geometry (str, optional): the geometry of the sample. Defaults to "spherical".
punish_degas_early(bool, optional): Tells the model whether to punish proposed fits that degas before the modeled experiment is complete
"""
self.dataset = data
self.time_add = time_add
self.temp_add = temp_add
# Add total moles information for priors
self.total_moles = torch.sum(torch.tensor(self.dataset.M))
self.total_moles_del = torch.sqrt(
torch.sum(torch.tensor(self.dataset.delM) ** 2)
)
self.stat = stat
time = self.dataset._thr * 3600
if time_add.numel() > 0:
self.tsec = torch.cat([time_add, time])
self._TC = torch.cat([temp_add, self.dataset._TC])
self.extra_steps = True
else:
self.tsec = time
self._TC = self.dataset._TC
self.extra_steps = False
self.lnd0aa = torch.tensor(self.dataset["ln(D/a^2)"])
self.lnd0aa[-1] = 0
indices = np.where(np.isinf(self.lnd0aa))
self.lnd0aa[self.lnd0aa == -np.inf] = 0
self.lnd0aa[self.lnd0aa == -np.inf] = 0
self.lnd0aa[torch.isnan(self.lnd0aa)] = 0
self.omitValueIndices = torch.isin( torch.arange(len(self.dataset)), torch.tensor(omitValueIndices) ).to(torch.int)
omitValueIndices_lnd0aa = omitValueIndices + (indices[0].tolist())
self.omitValueIndices_lnd0aa = torch.isin(
torch.arange(len(self.dataset)), torch.tensor(omitValueIndices_lnd0aa)
).to(torch.int)
# Add locations where uncertainty (and measurement value) is zero to the list of values to ignore
indices_chisq = np.where(data.uncert == 0)
omitValueIndices_chisq = omitValueIndices + (indices_chisq[0].tolist())
self.omitValueIndices_chisq = torch.isin(
torch.arange(len(self.dataset)), torch.tensor(omitValueIndices_chisq)
).to(torch.int)
self.plateau = torch.sum(
((torch.tensor(self.dataset.M) - torch.zeros(len(self.dataset.M))) ** 2)
/ (data.uncert**2)
)
self.Fi = torch.tensor(data.Fi)
self.trueFracFi = self.Fi[1:] - self.Fi[0:-1]
self.trueFracFi = torch.concat((torch.unsqueeze(self.Fi[0], dim=-0), self.trueFracFi), dim=-1)
self.geometry = geometry
self.Daa_uncertainty = torch.tensor(self.dataset["Daa uncertainty"])
self.Daa_uncertainty[self.Daa_uncertainty == -np.inf] = 0
self.Daa_uncertainty[self.Daa_uncertainty == -np.inf] = 0
self.Daa_uncertainty[torch.isnan(self.Daa_uncertainty)] = 0
data.uncert[data.uncert == 0] = torch.min(data.uncert[data.uncert != 0]) * 0.1
self.exp_moles = torch.tensor(data.M)
self.added_steps = len(time_add)
self.punish_degas_early = punish_degas_early
def __call__(self, X):
return self.objective(X)
def grad(self, X):
return self.grad(X)
def objective(self, X):
# This function calculates the fraction of gas released from each domain
# in an MDD model during the heating schedule used in the diffusion
# experiment. Then the fractions released from each domain are combined in
# proportion to one another as specified by the MDD model, and the
# diffusivity of each step is calculated. A residual is calculated as prescribed by the user.
# If the constraint function removes all possible models for this step, return empty list
if X.size == 0:
return([])
# Determine whether or not moles are being calculated and save to variable if yes
if len(X) % 2 != 0:
total_moles = X[0]
X = X[1:]
# Forward model the results so that we can calculate the misfit.
# If the mineral is diffusive enough that we're correcting for laboratory storage and irradiation:
# if self.extra_steps == True:
Fi_MDD, punishmentFlag = forwardModelKinetics(
X,
self.tsec,
self._TC,
geometry=self.geometry,
added_steps=self.added_steps,
)
# Create a punishment flag if the user specified. If the experiment degassed before the end of the temperature steps,
# then we add an extra value to the misfit calculated at each step. We do this by multiplying the misfit value
# at each step that degassed too early by 10. This punishes the model and "teaches" it that we don't want the experiment
# to degas too early. This is not recommended for experiments where the sample was fused or melted in final steps.
if self.punish_degas_early == True:
punishmentFlag = punishmentFlag * 10 + 1
else:
punishmentFlag = 1
# Objective function calculates Fi in cumulative form. Switch into non-cumulative space for calculations.
trueFracMDD = Fi_MDD[1:] - Fi_MDD[0:-1]
trueFracMDD = torch.concat(
(torch.unsqueeze(Fi_MDD[0], dim=0), trueFracMDD), dim=0
)
# If only one history was tested in a 1D shape, we need to put it into a column shape in 2-d so that
# it is the correct dimensions for the calculations below. If only one history was tested,
# trueFracMDD will have just 1 dimension.
if len(trueFracMDD.shape) < 2:
trueFracMDD = torch.unsqueeze(trueFracMDD, 1)
# Assign to a variable since we need to modify the shape of this variable depending on the size of X
trueFracFi = self.trueFracFi
if (
self.stat.lower() == "l1_frac"
or self.stat.lower() == "l2_frac"
or self.stat.lower() == "percent_frac"
or self.stat == "lnd0aa"
or self.stat == "lnd0aa_chisq"
):
trueFracFi = torch.tile(
trueFracFi.unsqueeze(1), [1, trueFracMDD.shape[1]]
)
# If you're using percent_frac, we'll reassign all the values that are 0 to
# 10% of the minimum size in seen in the experiment to avoid "divide by zero" errors.
# We ignore zero steps when calculating the misfit anyway.
if self.stat == "percent_frac":
trueFracFi[trueFracFi == 0] = (
torch.min(trueFracFi[trueFracFi != 0]) * 0.1
)
# If using l1_frac_cum, make that variable the correct shape.
elif self.stat.lower() == "l1_frac_cum":
Fi = torch.tile(self.Fi.unsqueeze(1), [1, Fi_MDD.shape[1]])
# If nothing above is true, then you're using a calc that involves moles and you'll need to calculate
# the predicted moles for each step.
else:
moles_MDD = trueFracMDD * total_moles
# Create the multiplier mask which will show values of 1 for values we want to include in the misfit, and
# zero for those we don't.
# This one is specific for lnd0aa (DREW TO ADD BETTER COMMENT)
if self.stat.lower() == "lnd0aa" or self.stat.lower() == "lnd0aa_chisq":
multiplier = 1 - torch.tile(
self.omitValueIndices_lnd0aa.unsqueeze(1),
[1, trueFracMDD.shape[1]],
)
# This one is specific for chi_sq (DREW TO ADD BETTER COMMENT)
elif self.stat.lower() == "chisq":
multiplier = 1 - torch.tile(
self.omitValueIndices_chisq.unsqueeze(1),
[1, trueFracMDD.shape[1]],
)
# This is the last multiplier contianing user-specified indices.
else:
multiplier = 1 - torch.tile(
self.omitValueIndices.unsqueeze(1), [1, trueFracMDD.shape[1]]
)
# This is a giant if statement to decide which misfit statistic you're using.
# It calculates the misfit as appropriate.
if self.stat.lower() == "chisq":
misfit = torch.sum(
multiplier
* ((self.exp_moles.unsqueeze(1) - moles_MDD) ** 2)
/ (self.dataset.uncert.unsqueeze(1) ** 2),
axis=0,
)
elif self.stat.lower() == "l1_moles":
misfit = misfit = torch.sum(
multiplier * (torch.abs(self.exp_moles.unsqueeze(1) - moles_MDD)),
axis=0,
)
elif self.stat.lower() == "l2_moles":
misfit = torch.sum(
(multiplier * ((self.exp_moles.unsqueeze(1) - moles_MDD) ** 2)),
axis=0,
)
elif self.stat.lower() == "l1_frac":
misfit = torch.sum(
multiplier * (torch.abs(trueFracFi - trueFracMDD)), axis=0
)
elif self.stat.lower() == "l1_frac_cum":
misfit = torch.sum(multiplier * (torch.abs(Fi - Fi_MDD)), axis=0)
elif self.stat.lower() == "l2_frac":
misfit = torch.sum(
(multiplier * (trueFracFi - trueFracMDD) ** 2), axis=0
)
elif self.stat.lower() == "percent_frac":
misfit = torch.sum(
multiplier * (torch.abs(trueFracFi - trueFracMDD)) / trueFracFi,
axis=0,
)
elif self.stat.lower() == "lnd0aa":
lnd0aa_MDD = calc_lnd0aa(
Fi_MDD, self.tsec, self.geometry, self.extra_steps, self.added_steps
)
lnd0aa_MDD[lnd0aa_MDD == -np.inf] = 0
lnd0aa_MDD[lnd0aa_MDD == np.inf] = 0
lnd0aa_MDD[torch.isnan(lnd0aa_MDD)] = 0
misfit = torch.sum(
multiplier * ((lnd0aa_MDD - self.lnd0aa.unsqueeze(1)) ** 2),
axis=0,
)
elif self.stat.lower() == "lnd0aa_chisq":
lnd0aa_MDD = calc_lnd0aa(
Fi_MDD, self.tsec, self.geometry, self.extra_steps, self.added_steps
)
lnd0aa_MDD[lnd0aa_MDD == -np.inf] = 0
lnd0aa_MDD[lnd0aa_MDD == np.inf] = 0
lnd0aa_MDD[torch.isnan(lnd0aa_MDD)] = 0
if len(lnd0aa_MDD.shape) < 2:
lnd0aa_MDD = torch.unsqueeze(lnd0aa_MDD ,1)
misfit = multiplier * ((torch.exp(lnd0aa_MDD) - torch.exp(self.lnd0aa.unsqueeze(1)))** 2/ self.Daa_uncertainty.unsqueeze(1))
nan_rows = (torch.isnan(misfit).any(dim=1)) | (torch.isinf(misfit).any(dim=1))
misfit = torch.sum(misfit[~nan_rows], axis=0)
return misfit * punishmentFlag |
<!DOCTYPE html>
<html lang="en">
<head>
<title>Portfolio Website-Brad</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- linking css file -->
<link rel="stylesheet" href="style.css">
<!-- bootstrap CDN -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
<!-- font awesome -->
<script src="https://kit.fontawesome.com/31149d48b0.js" crossorigin="anonymous"></script>
</head>
<body >
<!-- load javascript after loading all html content -->
<script src="script/script.js"></script>
<nav class="navbar navbar-expand-lg fixed-top navbarScroll">
<div class="container">
<a class="navbar-brand" href="#">SUYOG SINHA</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav ms-auto">
<li class="nav-item active">
<a class="nav-link" href="#home">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#about">About</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#skills">skills</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#contact">Contact</a>
</li>
</ul>
</div>
</div>
</nav>
<section class="bgimage" id="home">
<div class="container-fluid">
<div class="row">
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 hero-text">
<img src="images/" class= "imageAboutPage" alt="">
<h2 class="hero_title">Hi, it's me Suyog</h2>
<p class="hero_desc">I am a Web Developer</p>
</div>
</div>
</div>
</section>
<section>
<div class="container mt-4 pt-4">
<h1 class="text-center">About Me</h1>
<div class="row mt-4">
<div class="col-lg-4">
<img src="images/1657883753686.jpeg" class= "imageAboutPage" alt="">
</div>
<div class="col-lg-8">
<p> Ability To desgin a responsive Website and can Develop Web Application
</p>
<div class="row mt-3">
<div class="col-md-6">
<ul>
<li>Name: Suyog Sinha</li>
<li>Age: 21</li>
<li>Occupation: Web Developer</li>
</ul>
</div>
</div>
<div class="row mt-3">
</div>
</div>
</div>
</section>
<section id="Projects">
<div class="container">
<h1 class="text-center">skills</h1>
<div class="row">
<div class="col-lg-4 mt-4">
<div class="card servicesText">
<div class="card-body">
<i class="fas servicesIcon fa-clock"></i>
<h4 class="card-title mt-3">Website Development</h4>
<p class="card-text mt-3">Some quick example text to build on the card title and make up the bulk of the card's content.
Some quick example text to build on the card title and make up the bulk of the card's content.
</p>
</div>
</div>
</div>
<div class="col-lg-4 mt-4">
<div class="card servicesText">
<div class="card-body">
<i class='fas servicesIcon fa-layer-group'></i>
<h4 class="card-title mt-3">Website Design</h4>
<p class="card-text mt-3">Some quick example text to build on the card title and make up the bulk of the card's content.
Some quick example text to build on the card title and make up the bulk of the card's content.
</p>
</div>
</div>
</div>
<div class="col-lg-4 mt-4">
<div class="card servicesText">
<div class="card-body">
<i class='far servicesIcon fa-check-circle'></i>
<h4 class="card-title mt-3">Website Deployment</h4>
<p class="card-text mt-3">Some quick example text to build on the card title and make up the bulk of the card's content.
Some quick example text to build on the card title and make up the bulk of the card's content.
</p>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-lg-4 mt-4">
<div class="card servicesText">
<div class="card-body">
<i class="fab fa-python"></i>
<h4 class="card-title mt-3">Python</h4>
<p class="card-text mt-3">Some quick example text to build on the card title and make up the bulk of the card's content.
Some quick example text to build on the card title and make up the bulk of the card's content.
</p>
</div>
</div>
</div>
<div class="col-lg-4 mt-4">
<div class="card servicesText">
<div class="card-body">
<i class='fas servicesIcon fa-shield-alt'></i>
<h4 class="card-title mt-3">DevOps</h4>
<p class="card-text mt-3">Some quick example text to build on the card title and make up the bulk of the card's content.
Some quick example text to build on the card title and make up the bulk of the card's content.
</p>
</div>
</div>
</div>
<div class="col-lg-4 mt-4">
<div class="card servicesText">
<div class="card-body">
<h4 class="card-title mt-3">Django</h4>
<p class="card-text mt-3">Some quick example text to build on the card title and make up the bulk of the card's content.
Some quick example text to build on the card title and make up the bulk of the card's content.
</p>
</div>
</div>
</div>
</div>
</div>
</section>
<section id="contact">
<div class="container mt-3 contactContent">
<h1 class="text-center">Contact Me</h1>
<div class="row mt-4">
<div class="col-lg-6">
<!-- to edit google map goto https://www.embed-map.com type your location, generate html code and copy the html -->
<div style="max-width:100%;overflow:hidden;color:red;width:500px;height:500px;">
<div id="embedmap-canvas" style="height:100%; width:100%;max-width:100%;">
<iframe style="height:100%;width:100%;border:0;" frameborder="0" src="https://www.google.com/maps/embed/v1/place?q=Bhopal,+Madhya+Pradesh,+India&key=AIzaSyBFw0Qbyq9zTFTd-tUY6dZWTgaQzuU17R8">
</iframe>
</div>
<a class="googlemaps-html" href="https://www.embed-map.com" id="get-data-forembedmap">https://www.embed-map.com</a>
<style>#embedmap-canvas img{max-width:none!important;background:none!important;font-size: inherit;font-weight:inherit;}
</style>
</div>
</div>
<div class="col-lg-6">
<!-- form fields -->
<form>
<input type="text" class="form-control form-control-lg" placeholder="Name">
<input type="email" class="form-control mt-3" placeholder="Email">
<input type="text" class="form-control mt-3" placeholder="Subject">
<div class="mb-3 mt-3">
<textarea class="form-control" rows="5" id="comment" name="text" placeholder="Project Details"></textarea>
</div>
</form>
<button type="button" class="btn btn-success mt-3">Contact Me</button>
</div>
</div>
</div>
</section>
</body>
<footer id="footer">
<div class="container-fluid">
<!-- social media icons -->
<div class="social-icons mt-4">
<a href="https://www.instagram.com/" target="_blank"><i class="fab fa-instagram"></i></a>
<a href="https://github.com/" target="_blank"><i class="fab fa-github"></i></a>
<a href="https://www.linkedin.com/" target="_blank"><i class="fab fa-linkedin"></i></a>
</div>
</div>
</footer>
</html> |
#include <bits/stdc++.h>
using namespace std;
void tabulateLCS(vector<vector<int>>& dp, string& text1, string& text2) {
int n = dp.size() - 1;
int m = dp[0].size() - 1;
for (int i = 0; i <= n; ++i) {
for (int j = 0; j <= m; ++j) {
if (i == 0 || j == 0)
dp[i][j] = 0;
else if (text1[i - 1] == text2[j - 1])
dp[i][j] = 1 + dp[i - 1][j - 1];
else
dp[i][j] = max(dp[i][j - 1], dp[i - 1][j]);
}
}
}
string lcs(vector<vector<int>>& dp, string& text1, string& text2) {
int n = dp.size();
int m = dp[0].size();
int i = n;
int j = m;
string result;
while (i > 0 && j > 0) {
if (text1[i - 1] == text2[j - 1]) {
result.push_back(text1[i - 1]);
--i;
--j;
} else {
if (dp[i - 1][j] > dp[i][j - 1])
--i;
else
--j;
}
}
reverse(result.begin(), result.end());
return result;
}
int main() {
string text1;
string text2;
cin >> text1 >> text2;
vector<vector<int>> dp(text1.size() + 1, vector<int> (text2.size() + 1, -1));
tabulateLCS(dp, text1, text2);
string result = lcs(dp, text1, text2);
cout << result;
return 0;
} |
package frc.robot.subsystems;
import edu.wpi.first.wpilibj2.command.SubsystemBase;
import edu.wpi.first.wpilibj.motorcontrol.Spark;
import frc.lib.bluecrew.util.BlinkinValues;
import frc.robot.Constants;
import frc.lib.bluecrew.util.RobotState;
public class BlinkinSubsystem extends SubsystemBase implements Constants.Misc, Constants.GameStateConstants, BlinkinValues {
private final Spark blinkinOutput;
RobotState rs = RobotState.getInstance();
/**
* The Singleton instance of this BlinkinSubsystem. Code should use
* the {@link #getInstance()} method to get the single instance (rather
* than trying to construct an instance of this class.)
*/
private final static BlinkinSubsystem INSTANCE = new BlinkinSubsystem();
/**
* Returns the Singleton instance of this BlinkinSubsystem. This static method
* should be used, rather than the constructor, to get the single instance
* of this class. For example: {@code BlinkinSubsystem.getInstance();}
*/
@SuppressWarnings("WeakerAccess")
public static BlinkinSubsystem getInstance() {
return INSTANCE;
}
/**
* Creates a new instance of this BlinkinSubsystem. This constructor
* is private since this class is a Singleton. Code should use
* the {@link #getInstance()} method to get the singleton instance.
*/
private BlinkinSubsystem() {
blinkinOutput = new Spark(BLINKIN_PORT);
}
@Override
public void periodic() {
switch (rs.getShooterMode()) {
case SPEAKER -> {
switch (rs.getRobotCycleStatus()) {
case NO_NOTE_CANT_SEE_SPEAKER ->
blinkinOutput.set(RED);
case NO_NOTE_SEES_SPEAKER ->
blinkinOutput.set(RED_ORANGE);
case HAS_NOTE_CANT_SEE_SPEAKER ->
blinkinOutput.set(YELLOW);
case HAS_NOTE_SEES_SPEAKER -> {
switch (rs.getShooterStatus()) {
case READY ->
blinkinOutput.set(DARK_GREEN);
case UNREADY ->
blinkinOutput.set(BLUE_GREEN);
}
}
}
}
case PICKUP -> {
if (!rs.hasNote()) {
if (rs.isNoteIsAvailable()) {
blinkinOutput.set(HEARTBEAT_BLUE);
} else {
blinkinOutput.set(HEARTBEAT_RED);
}
} else blinkinOutput.set(LAWN_GREEN);
}
case AMP -> {
if (rs.hasNote()) {
switch (rs.getShooterStatus()) {
case READY -> blinkinOutput.set(DARK_GREEN);
case UNREADY -> blinkinOutput.set(BLUE_GREEN);
}
} else blinkinOutput.set(RED_ORANGE);
}
}
}
public void setColorMode(double mode) {
blinkinOutput.set(mode);
}
} |
package FindMedian;
/**
* The FindMedian class contains methods for finding the median value of an array of integers. If the array has an odd
* number of elements, the median is the middle element. If the array has an even number of elements, the median is the
* average of the two middle elements. The class uses the quickselect algorithm to find the kth smallest element in the
* array, where k is the middle index or the average of the two middle indices depending on whether the array length is
* even or odd.
* @author Adam Zieman
*/
public class FindMedian {
/**
* This method finds the median value of an array of integers. If the array has an odd number of elements, the
* median is the middle element. If the array has an even number of elements, the median is the average of the two
* middle elements. The method uses the findMiddleElement() method to find the kth smallest element in the array,
* where k is the middle index or the average of the two middle indices depending on whether the array length is
* even or odd.
* @param arr the array of integers
* @return the median value of the array
*/
public static double findMedian(int[] arr) {
// Check if the length of the array is even or odd
/* If the array length is even, find the two middle elements by finding the kth smallest element at indices
k = length / 2 and k = length / 2 + 1. Take the average of the two middle elements and return the result.*/
if (arr.length % 2 == 0) {
int kElement = arr.length / 2;
int leftMidElement = findMiddleElement(arr, 0, arr.length - 1, kElement);
int rightMidElement = findMiddleElement(arr, 0, arr.length - 1, kElement + 1);
return (leftMidElement + rightMidElement) / 2.0;
}
/* If the array length is odd, find the middle element by finding the kth smallest element at index k =
(length + 1) / 2 and return it. */
else {
int middleIndex = (arr.length + 1) / 2;
return findMiddleElement(arr, 0, arr.length - 1, middleIndex);
}
}
/**
* The findMiddleElement method recursively finds the kth smallest element in an integer array by using
* the quickselect algorithm.
* @param arr the integer array to be searched
* @param left the leftmost index of the array
* @param right the rightmost index of the array
* @param k the rank of the element to be found
* @return the kth smallest element in the array
*/
private static int findMiddleElement(int[] arr, int left, int right, int k) {
// Base case. If the left and right indices are equal, the current subarray contains only one element.
if (left == right) {
return arr[left];
}
// Partition the array and get the index of the pivot element and its rank in the partitioned array.
int pivotIndex = partition(arr, left, right);
int pivotRank = pivotIndex - left + 1;
// Base case. If the pivot element is the kth smallest element, return it.
if (k == pivotRank) {
return arr[pivotIndex];
}
// If the kth smallest element is on the left side of the pivot, recursively search the left subarray.
else if (k < pivotRank) {
return findMiddleElement(arr, left, pivotIndex - 1, k);
}
// If the kth smallest element is on the right side of the pivot, recursively search the right subarray.
else {
return findMiddleElement(arr, pivotIndex + 1, right, k - pivotRank);
}
}
/**
* Partitions an array into two sections, one containing elements less than or equal to
* the pivot value, and the other containing elements greater than the pivot value.
* @param arr the array to be partitioned
* @param left the leftmost index of the partition range
* @param right the rightmost index of the partition range
* @return the index of the pivot element after partitioning
*/
private static int partition(int[] arr, int left, int right) {
int pivotValue = arr[right]; // sets the pivot element to the rightmost element in the partition range
int index = left - 1; // sets the index to keep track of the index of the last element that is LTE to the pivot
/* Iterate through the partition range and move any elements that are LTE to the pivot value to the left side
of the partition range by swapping them with the elements at the current index. */
for (int leftIndex = left; leftIndex < right; leftIndex++) {
if (arr[leftIndex] <= pivotValue) {
index++;
int temp = arr[index];
arr[index] = arr[leftIndex];
arr[leftIndex] = temp;
}
}
/* Once all elements LTE to the pivot value have been moved to the left side of the partition range, swap the
pivot element with the element at the index following the last LTE element. */
int temp = arr[index + 1];
arr[index + 1] = arr[right];
arr[right] = temp;
return index + 1; // Return the index of the pivot element after partitioning.
}
} |
> McKusick, Marshall K., et al. "A fast file system for UNIX." ACM Transactions on Computer Systems (TOCS) 2.3 (1984): 181-197.
# ffs
“a fast file system for unix”: alternative implementation of the unix file system (ufs) with better performance.
other sources:
- implementation: https://github.com/openbsd/src/blob/master/sys/ufs/ffs/fs.h
- https://github.com/openbsd/src/blob/master/sys/ufs/ffs/fs.h
- https://gunkies.org/wiki/BSD_Fast_File_System
- https://slideplayer.com/slide/9894780/
- https://blog.koehntopp.info/2023/05/06/50-years-in-filesystems-1984.html
- https://www.youtube.com/watch?v=1BbMBdGPoHM
- https://en.m.wikipedia.org/wiki/Marshall_Kirk_McKusick
- http://www.cse.unsw.edu.au/~cs9242/02/lectures/09-fs/node4.html
# introduction
_unix operating system_
- the os is the intermediary software layer between programs and the computer hardware that manages resources like memory, cpu etc.
- unix is a family of operating systems.
- what’s special about unix is that “everything is a file(descriptor)” - even interprocess communication and peripheral access.
_fs / file system_
- data structure that the operating system uses to control how data is stored and retrieved from a storage device.
- the storage device can be: SSDs, magnetic tapes, optical discs, tmpfs, main memory/RAM as a temporary file system, remote/virtual file
- SDDs were invented in 1989 and became commercially available in 1991
_fs architecture_
usually 2 or 3 layers, often combined:
- logical file system: has API for file operations like `OPEN`, `CLOSE`, `READ`, etc. and manages file descriptors.
- virtual file system: allows multiple instances of the physical file system to be used concurrently.
- physical file system: processes physical operations on blocks of the storage device (ie. disk). interacts with the device drivers.
_addresses on a hard disk drive: CHS_
- see: https://en.m.wikipedia.org/wiki/Cylinder-head-sector
- addresses of each physical data-block on a hard disk drive
```txt
// hierarchy of a file system
disk drive
multiple disk drive partitions
a single file system
files (directories are special files)
inode / file decriptor
data blocks
```
_disk drive_
- physical space that stores file-systems
- is partitioned into disk-partitions
_file system_
- logical system which contains files
- directories are also just files, that point to other files
- every file has an associated file-descriptor called ‘inode’
_inodes (block index node)_
- see: https://en.m.wikipedia.org/wiki/Inode_pointer_structure
- link to all data-blocks for that file (and other things like file ownership, last mod timestap, access times)
- we assume that the first 8 data-blocks of each file are reserved for the inode itself (actually somewhere between 5-13)
- inodes may reference ‘indirect blocks’ that contain other block indixes
_data-blocks_
- actual data located on the physical disk (which can also store addresses to other disk blocks)
_super block_
- very critical, describes the file system
- placed in the beginning of each partitionn
- immutable data like: num of data blocks in fs, max num files
# ufs vs. ffs comparison
### // ufs
_disk partitions_
- subdivision of physical space on a disk drive that doesn’t overlap
- can store max 1 file-system
_file-system_
- starts with super-block
_inode_
- each indirect level (no matter at what depth) can hold 128 indirect-block-addresses
_data-blocks_
- each have 512 bytes
_super block_
- also stores pointer to the ‘free list’ (linked list of all free blocks in the system)
### // ffs
_disk partitions_
- logical disk partitions, file-systems can span multiple partitions
- is divided into ‘cylinder groups’ which are consecutive on the disk
_cylinder-groups_
- each contain ‘bookkeeping’:
- redundant super-block copy
- static number of inodes (usually 1 inode for each 2048 bytes in cylinder group for extra redundancy)
- bitmap describing available space in group (this replaces the old ‘free list’)
- space usage within cylinder group
- the bookkeeping data isn’t placed at the top of the platter because that’s the place most likely to get damaged — a sequentially increasing offset is used (the blocks spiral from the outside into the center)
- the remaining space is used for data blocks.
_file-system_
- starts with super-block as well but it’s replicated during file-system creation to protect against corruption and catastrophic loss
- replicas are only accessed when corruption is detected
- must be min 4096 bytes large if files are max 2^32 bytes to limit max 2 levels of indirection
# ufs
original 512 byte system, introduced with 4.2 BSD, developed by bell labs.
_why ufs had to be improved_
- low reliability because there was just one copy of the super block
- low throughput that doesn’t suffice for applications or mapping files into virtual address spaces
- provides ~2% of the maximum disk bandwidth
- ~20kb/s per arm: very long seek times because of low locality
150mb ufs had 4mb of inodes followed by 146mb of data
inodes of files in same directory weren’t placed close to eachother
data blocks of the same file weren’t placed on the same cylinder (max 512 bytes per disk transaction):
- limited read-ahead
- small block size
- seek for every 512 byte
_initial optimization: 2x basic block size (from 512b to 1024b)_
- 2x more throughput, +2% disk bandwitdth usage
- each disk transfer accessed twice as much data leading to the need of less indirect blocks
- degradation
- because ‘free list’ allocation and block placement was random transfer rates went from 157kb/s down to 30kb/s in a few weeks
- the only way to restore performance was to dump, rebuild, restore entire fs or run a process that reorders allocations.
# ffs
used in FreeBSD, NetBSD, OpenBSD, NeXTStep, Solaris
## fragments
_fragments to avoid fragmentation_
- bigger data-blocks lead to more waste
- if we pick 4096b data-blocks instead of 1024b, we save 4 transactions
- but bigger blocks are not always better: most unix systems store many small files
- based on experience this leads to wasted space (no user data) on blocks
- we split data-blocks into smaller parts called fragments
- fragment size (2,4,8) is specified when file system is created and must be >512b
_NFS: fragment storage allocation_
- ‘blockmap’ in each each cylinder group also records available space at fragment level
example: 4096 block size / 1024 fragment size:
- X = fragment is in use
- O = fragment is free
- fragments of adjoining blocks cannot be used as a full block, but fragments in the same block (like 0-3) could be merged into a full block.
- creating file: if we don’t find all the fragments we just take another full block and return a single fragment.
- appending file:
a) enough space in current block, just extend
b) no space in remaining fragments - move parts to whole new block, repeat recursively
this can lead to a lot of reallocations and be pretty slow
## free space reserve parameter
_free space reserve_
- performance degrades by overfilling the system
- layout policy has the parameter called “free space reserve” that avoids 100% utilization so throughput is good (less time searching for free blocks).
- the parameter can be changed any time.
- based on experience:
- waste ufs 1024b = 11.8%
- waste ffs 4096b/512b with ‘free space reserve’ set at 5% = 6.9% + 5%
## layout policies
_layout policies_
1. global policy routines
fs wide summary information
place inodes, data-blocks
calculate rotationally optimal placements for files and directories
decide when it’s worth it to switch cylinders and sacrifice locality
ideally none of the cylinder groups should ever become completely full
2. local allocation routines
layout policy
based on inodes we can tell which files are in the same directory
locally optimal scheme to lay out data blocks
- put inodes (if files are in the same directory) in the same cylinder-group
- put new directory inodes in cylinder-groups that are relatively empty
- put all data-blocks for the same file in the same cylinder-group at ‘rotationally optimal positions’ (after calculating these)
‘rotationally optimal blocks’ are either consecutive or rotationally delayed and are ideal for systems that don’t need processor intervention between multiple data transfers.
super-block contains a vector of lists called ‘rotational layout table’ to know how disk sectors are placed
4 level allocation strategy:
1. use next available block which is rotationally closest to requested block
2. else use blocks within the same cylinder-group
3. else use the quadratic hash of the cylinder-group-number to repeat
4. else search linearly
## parameterization
_parameterization_
- ffs adapts itself to underlying hardware (processor speed, storage transfer speeds, number of blocks per track, disk spin rate, …) for optimal allocation
- ffs tries to allocate new blocks on the same cylinder as the previous block for the same file.
# benchmarking
based on empirical studies
test programs measure rate at which user programs can transfer data to or from a file without performing any processing on it.
data must be large enough that OS buffering doesn’t affect results.
tests ran 3x consecutively.
10% free space reserve (with 0% the results are half as good).
(disk) bandwidth is given per filesystem.
no degradation: throughput stays high over longer timeperiods
speedup: 2x less disk accesses for inode seeks (close to 8x for large flat directories)
the larger block size contributes most to the speedup.
there is some slowdown because of block (re)allocation.
but net cost for each byte allocated is the same for ufs and ffs.
writes are slower because kernel must do some work.
throughput / bandwidth usage could also be improved by:
- aligning address spaces:
slow memory-to-memory operations: disk buffer → systems address space → data buffers in users address space
this could be mitigated by aligning the address spaces but it was too complex for this OS.
- preallocating multiple blocks / batch allocating (used in DEMOS fs) when a file is growing fast and then releasing the unused fragments
not included because it only makes up 10% of write calls and the current rates are limited by the number of available processors
- chaining together kernel operations to read multiple blocks in a single transaction by taking into consideration how many blocks are skipped while processing data
this could push the bandwidth usage above 50%
# final result
higher throughput rates
more flexible allocation policies (bigger blocks for bigger files, smaller blocks for smaller files)
clusters data that is accessed sequentially
10x faster file access rate than traditional unix fs
some functional enhancements that i don’t care about (better api, lock mechanisms, improved namespace)
_key takeaways_
> “The global policies try to balance the two conflicting goals of localizing data that is concurrently accessed while spreading out unrelated data.”
- “increase the locality of reference to minimize seek latency [… but don’t take it to the extreme or it leads to] a single huge cluster of data resembling the old file system”
- “[cluster related information, ] but […] also try to spread unrelated data among different cylinder groups”
- “improve the layout of data to make larger transfers possible”
- improve granularity of allocs, but also merge blocks together where necessary
in general: large data-blocks in the same cylinder lead to spill-overs of smaller ones
- add redundancy for resilience |
---
output: html_document
runtime: shiny
title: Law of Large Numbers
---
```{css, echo = FALSE}
.shiny-frame{height: 810px;}
```
```{r, echo=FALSE, warning = FALSE}
# Load libraries
library(shiny)
library(ggplot2)
plot_law_of_large_numbers <- function(simulations, repetitions, distribution) {
set.seed(42) # Set a seed for reproducibility
df <- data.frame()
names = c("IID standard normal", "IID Student-t(5)", "IID Bernoulli with p=0.25", "AR(1) with rho=0.8 and N(0,1) increments", "Random walk with N(0,1) increments")
for (i in 1:repetitions) {
if (distribution == "IID standard normal") {
data <- sample(1:6, simulations, replace = TRUE) # Simulate drawing from a fair 6-sided die
} else if (distribution == "IID Student-t(5)") {
data <- rnorm(simulations) # Generate random numbers from a normal distribution
} else if (distribution == "IID Bernoulli with p=0.25") {
data <- runif(simulations) # Generate random numbers from a uniform distribution
}
average <- cumsum(data) / (1:simulations) # Calculate the cumulative average
temp_df <- data.frame(Simulations = 1:simulations, Average = average, Repetition = factor(i)) # Create a temporary data frame
df <- rbind(df, temp_df) # Append the temporary data frame to the main data frame
}
actual_mean <- ifelse(distribution == "Dice", 3.5, ifelse(distribution == "Uniform", 0.5, 0))
ggplot(df, aes(x = Simulations, y = Average, color = Repetition)) +
geom_line(size = 0.5) +
geom_hline(yintercept = actual_mean, color = "black", linetype = "dashed") +
labs(x = "Number of Simulations", y = "Average",
title = paste("Law of Large Numbers for", distribution, "Distribution")) +
scale_color_discrete(name = "Repetition")+
theme_minimal()
}
ui <- fluidPage(
titlePanel("Law of Large Numbers"),
sidebarLayout(
sidebarPanel(
selectInput("distribution", "Distribution:",
choices = c("IID standard normal", "IID Student-t(5)", "IID Bernoulli with p=0.25"), selected = "IID standard normal"),
sliderInput("simulations", "Number of Simulations:", min = 1, max = 1000, value = 1000),
sliderInput("repetitions", "Number of Repetitions:", min = 1, max = 10, value = 5)
),
mainPanel(
plotOutput("plot")
)
)
)
server <- function(input, output) {
output$plot <- renderPlot({
plot_law_of_large_numbers(input$simulations, input$repetitions, input$distribution)
})
}
shinyApp(ui = ui, server = server)
``` |
# Direct messages
**Direct messages (DMs)** are conversations with other users that happen outside
of a [stream](/help/streams-and-topics). DMs work well for one-off messages,
usually with just one or two others.
If you find yourself frequently conversing with the same person or group, it
often works better to [create a private stream](/help/create-a-stream) for your
conversations. This lets you organize your discussion into topics, and add or
remove participants as needed.
## Send a DM
{!send-dm.md!}
## Access a DM
If using Zulip in a browser or desktop, there are several ways to access an existing DM conversation.
* Click on **Direct messages** near the top of the left sidebar to access
recent DM conversations.
* Click on any user in the right sidebar.
* Start typing a user's name in the [search](/help/search-for-messages) bar.
You'll be able to select DMs with that user.
* Open the compose box, and enter a list of users on the **To:**
line. Type <kbd>Ctrl</kbd> + <kbd>.</kbd> to open that conversation.
## Access all DMs
{start_tabs}
{tab|desktop-web}
{relative|message|direct}
{tab|mobile}
1. Tap the **Direct messages**
( <img src="/static/images/help/mobile-dm-tab-icon.svg" alt="direct messages" class="help-center-icon"/> )
tab at the bottom of the app.
{end_tabs}
## Related articles
* [Typing notifications](/help/typing-notifications)
* [Open the compose box](/help/open-the-compose-box) |
<template>
<Message :msg="msg" v-show="msg" />
<div>
<form id="Contato" method="POST" @submit="createConjunto">
<div class="input-container">
<label for="nome">Nome</label>
<input type="text" id="nome" name="nome" v-model="nome">
</div>
<div class="input-container">
<label for="nome">E-mail</label>
<input type="text" id="nome" name="email" v-model="email">
</div>
<div class="input-container">
<label for="mensagem">Mensagem</label>
<input type="text" id="mensagem" name="mensagem" v-model="mensagem" placeholder="Digite sua mensagem">
</div>
<div class="input-container">
<label for="blusa">Escolha sua blusa:</label>
<select name="blusa" id="blusa" v-model="blusa">
<option value="">Selecione</option>
<option v-for="blusa in blusas" :key="blusa.id" :value="blusa.tipo">{{ blusa.tipo }}</option>
</select>
</div>
<div class="input-container">
<label for="sobreblusa">preferencia do que vestir?</label>
<select name="sobreblusa" id="sobreblusa" v-model="sobreblusa">
<option value="">Selecione</option>
<option v-for="sobreblusa in sobreblusas" :key="sobreblusa.id" :value="sobreblusa.tipo">{{ sobreblusa.tipo }}</option>
</select>
</div>
<div id="opcionais-container" class="input-container">
<label id="opcionais-title" for="opcionais">Selecione os opcionais:</label>
<div class="checkbox-container" v-for="opcional in opcionaisdata" :key="opcional.id">
<input type="checkbox" name="opcionais" v-model="opcionais" :value="opcional.tipo">
<span>{{ opcional.tipo }}</span>
</div>
</div>
<div class="input-container">
<input class="submit-btn" type="submit" value="Enviar mensagem">
</div>
</form>
<br>
<div class="tel">
<label for="Telefone">TELEFONES</label>
<p class="texts">+55 (11)3088-0757</p>
</div>
<div class="emails">
<label for="email">E-MAIL</label>
<p class="texts">renee@reneetrajar.com.br</p>
</div>
</div>
</template>
<script>
import Message from './Message'
export default {
name: "Contato",
data() {
return {
blusas: null,
sobreblusas: null,
opcionaisdata: null,
nome: null,
blusa: null,
sobreblusa: null,
opcionais: [],
status: "Solicitado",
msg: null
}
},
methods: {
async getRoupas() {
const req = await fetch('http://localhost:3000/roupas')
const data = await req.json()
this.blusas = data.blusas
this.sobreblusas = data.sobreblusas
this.opcionaisdata = data.opcionais
},
async createConjunto(e) {
e.preventDefault()
const data = {
nome: this.nome,
sobreblusa: this.sobreblusa,
blusa: this.blusa,
opcionais: Array.from(this.opcionais),
status: "Solicitado"
}
const dataJson = JSON.stringify(data)
const req = await fetch("http://localhost:3000/conjuntos", {
method: "POST",
headers: { "Content-Type" : "application/json" },
body: dataJson
});
const res = await req.json()
console.log(res)
this.msg = "Pedido realizado com sucesso!"
// clear message
setTimeout(() => this.msg = "", 3000)
// limpar campos
this.nome = ""
this.sobreblusa = ""
this.blusa = ""
this.opcionais = []
}
},
mounted () {
this.getRoupas()
},
components: {
Message
}
}
</script>
<style scoped>
#Contato {
max-width: 400px;
margin: 0 auto;
}
.input-container {
display: flex;
flex-direction: column;
margin-bottom: 20px;
}
label {
font-weight: medium;
margin-bottom: 15px;
color: #1C86A4;
font-family:Cormorant;
}
input#mensagem {
width: 300px;
height: 150px;
word-wrap: break-word;
overflow: hidden;
}
input, select {
padding: 5px 10px;
width: 300px;
}
#opcionais-container {
flex-direction: row;
flex-wrap: wrap;
}
#opcionais-title {
width: 100%;
}
.checkbox-container {
display: flex;
align-items: flex-start;
width: 50%;
margin-bottom: 20px;
}
.checkbox-container span,
.checkbox-container input {
width: auto;
}
.checkbox-container span {
margin-left: 6px;
font-weight: bold;
color:#014561;
}
.submit-btn {
background-color: #014561;
border-radius:4px;
color:#FFF;
border: 1px solid #014561;
padding: 10px;
font-size: 16px;
font-family: Lato;
cursor: pointer;
transition: .5s;
}
.submit-btn:hover {
background-color: transparent;
color: #FFF;
background-color:#00628b;
}
.placeholder {
overflow: hidden;
}
select[data-v-aae30ed8] {
padding: 12px 6px;
margin-right: 12px;
margin-bottom: 10px;
border-radius: 4px;
}
.tel{
margin-left:30px;
margin-top: -764px;
}
.emails{
margin-left:30px;
}
.texts{
font-weight: bold;
color: #014561;
}
</style> |
/*
* The MIT License
*
* Copyright 2013 RBC1B.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package uk.org.rbc1b.roms.controller.personchange;
import org.springframework.stereotype.Component;
import uk.org.rbc1b.roms.db.PersonChange;
/**
* Generates the models for changes to person.
*
* @author ramindursingh
*/
@Component
public class PersonChangeModelFactory {
private static final String BASE_URI = "/person-changes";
/**
* Generates the uri used to update the table.
*
* @param personChangeId personchange id
* @return uri
*/
public static String generatorUri(Integer personChangeId) {
return personChangeId != null ? BASE_URI + "/" + personChangeId : BASE_URI;
}
/**
* Create the model.
*
* @param personChange personChange
* @return model
*/
public PersonChangeModel generatePersonChangeModel(PersonChange personChange) {
PersonChangeModel model = new PersonChangeModel();
model.setPersonChangeId(personChange.getPersonChangeId());
model.setPersonId(personChange.getPersonId());
model.setOldForename(personChange.getOldForename());
model.setOldSurname(personChange.getOldSurname());
if (personChange.getOldAddress() != null) {
model.setOldStreet(personChange.getOldAddress().getStreet());
model.setOldTown(personChange.getOldAddress().getTown());
model.setOldCounty(personChange.getOldAddress().getCounty());
model.setOldPostcode(personChange.getOldAddress().getPostcode());
}
model.setOldEmail(personChange.getOldEmail());
model.setOldMobile(personChange.getOldMobile());
model.setOldTelephone(personChange.getOldTelephone());
model.setOldWorkPhone(personChange.getOldWorkPhone());
model.setNewForename(personChange.getNewForename());
model.setNewSurname(personChange.getNewSurname());
if (personChange.getNewAddress() != null) {
model.setNewStreet(personChange.getNewAddress().getStreet());
model.setNewTown(personChange.getNewAddress().getTown());
model.setNewCounty(personChange.getNewAddress().getCounty());
model.setNewPostcode(personChange.getNewAddress().getPostcode());
}
model.setNewEmail(personChange.getNewEmail());
model.setNewMobile(personChange.getNewMobile());
model.setNewTelephone(personChange.getNewTelephone());
model.setNewWorkPhone(personChange.getNewWorkPhone());
model.setComment(personChange.getComment());
model.setUpdateUri(generatorUri(personChange.getPersonChangeId()));
return model;
}
} |
import React from "react"
import axios from "axios"
const qs = require("qs")
function Oppurtunities() {
const [val, setVal] = React.useState({
fullName: "",
email: "",
number: "",
about: ""
});
const [finalVal, setIt] = React.useState("Apply for your dream job today")
const [fade, setFade] = React.useState("")
const [afterFade, setAfterFade] = React.useState("")
const [required, setReq] = React.useState("")
function handleClick() {
const selected1 = document.getElementById("dropdown")
const role = selected1.options[selected1.selectedIndex].text
const selected2 = document.getElementById("most-like")
const pos = selected2.options[selected2.selectedIndex].text
const { fullName, email, number, about } = val
if (fullName === "" || email === "" || number === "" || about === "") {
setReq("Input all the required fields")
}
else {
const details = {
fullName,
email,
number,
role,
pos,
about
}
axios.post("http://localhost:5000/form", qs.stringify(details)).then(res => {
if (res) {
setVal({
fullName: "",
email: "",
number: "",
about: ""
})
setIt("Thank you for applying, we will get back to you soon")
setFade("fadep")
setAfterFade("after")
setReq("")
}
else
{
console.log("NO")
setReq("Server error, try again later")
}
})
}
}
function handleChange(event) {
const { name, value } = event.target;
setVal(prevValue => {
return {
...prevValue,
[name]: value
};
});
}
return (
<div>
<div className="oppContainer">
<h1>Find the best oppurtunity waiting for you</h1>
<p>Lorem ipsum dolor sit, amet consectetur adipiipisci dicta iste modi, distinctio impedit fugit maxime voluptatem.</p>
</div>
<div className="job">
<h3>{finalVal}</h3>
</div>
<form className={fade} onSubmit={(e) => { e.preventDefault() }}>
<input name="fullName" value={val.fullName} onChange={handleChange} type="text" placeholder="Your Name (Required)" />
<input name="email" value={val.email} onChange={handleChange} type="email" placeholder="Your Email (Required)" />
<input name="number" value={val.number} onChange={handleChange} type="text" placeholder="Your Phone Number (Required)" />
<div class="rightTab1">
<label htmlFor="which">What is your current role?</label>
<div id="which">
<select id="dropdown" name="currentPos" class="dropdown">
<option disabled value>Select an option</option>
<option value="student">Student</option>
<option value="job">Full Time Job</option>
<option value="remote-job">Remote Job</option>
<option value="intern">Intern</option>
<option value="other">Other</option>
</select>
</div>
</div>
<div class="rowTab">
<div class="labels">
<label htmlFor="most-like">Which position would you like to apply for? </label>
</div>
<div class="rightTab">
<select id="most-like" name="mostLike" class="dropdown">
<option disabled defaultValue value>Select an option</option>
<option value="front-end">Front-end</option>
<option value="fullstack">Fullstack</option>
<option value="projectManager">Project Manager</option>
<option value="javaDeveloper">Java Developer</option>
<option value="artificialintelligenceExpert">AI expert</option>
</select>
</div>
</div>
<div >
<textarea name="about" value={val.about} onChange={handleChange} id="" cols="30" placeholder="Explain a bit about yourself (Required)" rows="5" ></textarea>
</div>
<div >
<p id="required"> {required} </p>
</div>
<div className="subBtn">
<button type="submit" onClick={handleClick} > Submit</button>
</div>
</form>
<div className={afterFade}>
</div>
</div>
)
}
export default Oppurtunities |
const express = require("express");
const app = express();
const mongoose = require("mongoose");
const Product = require("./test/product.model");
const productRoute = require("./routes/product.route");
// middleware
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
// routes
app.use("/api/products", productRoute);
app.get("/", (req, res) => {
res.send("Hello from node api");
res.end();
});
// app.post("/api/products", async (req, res) => {
// // try {
// // const product = await Product.create(req.body);
// // res.status(200).json(product);
// // } catch (error) {
// // res.status(500).json({ message: error.message });
// // }
// });
// app.get("/api/products", async (req, res) => {
// try {
// const products = await Product.find({});
// res.status(200).json(products);
// } catch (error) {
// res.status(500).json({
// message: error.message,
// });
// }
// });
// get single product
// app.get("/api/products/:id", async (req, res) => {
// // try {
// // const { id } = req.params;
// // const product = await Product.findById(id);
// // res.status(200).json(product);
// // } catch (error) {
// // res.status(500).json({ message: error.message });
// // }
// });
// update product
// app.put("/api/products/:id", async (req, res) => {
// try {
// const { id } = req.params;
// const product = await Product.findByIdAndUpdate(id, req.body);
// if (!product) {
// return res.status(404).json({ message: "product not found" });
// }
// const updatedProduct = await Product.findById(id);
// res.status(200).json(updatedProduct);
// } catch (error) {
// res.status(500).json({ message: error.message });
// }
// });
// app.delete("/api/products/:id", async (req, res) => {
// try {
// const { id } = req.params;
// const product = await Product.findByIdAndDelete(id);
// if (!product) {
// return res.status(404).json({ message: "product not found" });
// }
// res.status(200).json({ message: "Product deleted successfully" });
// } catch (error) {
// res.status(500).json({ message: error.message });
// }
// });
mongoose
.connect(
"mongodb+srv://turjot:YyJwK4kLXJ7BCD3K@backend.gcp9brp.mongodb.net/Node-API?retryWrites=true&w=majority&appName=backend"
)
.then(() => {
console.log("Connected to database");
const port = process.env.PORT || 3000;
app.listen(port, () => console.log(`Listening on port ${port}...`));
})
.catch(() => {
console.log("Connection failed!");
}); |
// requires
const express = require('express');
const path = require('path');
const Get = require('./Controllers/Read');
const Create = require('./Controllers/Create');
const Delete = require('./Controllers/Delete');
const Update = require('./Controllers/Update');
const Middlewares = require('./Controllers/MiddleWares');
const DataBase = require('./DAL/DB');
const cors = require('cors');
require('dotenv').config();
const port = 3000;
const app = express();
// middlewares
app.use(express.json());
app.use(cors());
// activate DB
DataBase();
// Serve static files from the React app
app.use(express.static(path.join(__dirname, '../surveysway/build')));
// Posts
app.post('/Register', (req, res) => { Create.Register(req, res); });
app.post('/PublishSuervey', (req, res) => { Create.PublishSuervey(req, res); });
app.post('/GetguestToken', (req, res) => { Create.GetguestToken(req, res); });
app.post('/SignIn', Middlewares.RefreshSurveyListByDate, (req, res) => { Create.SignIn(req, res); });
app.post('/GetNewToken', (req, res) => { Create.GetNewToken(req, res); });
// Reads
app.get('/Login', (req, res) => { Get.Login(req, res); });
app.get('/PullUserDetails', (req, res) => { Get.PullUserDetails(req, res); });
app.get('/ForgotPassword', (req, res) => { Get.ForgotPassword(req, res); });
app.get('/PullUserSurveys', (req, res) => { Get.PullUserSurveys(req, res); });
app.get('/PullOldUserSurveys', (req, res) => { Get.PullOldUserSurveys(req, res); });
app.get('/PullAllSurveys', (req, res) => { Get.PullAllSurveys(req, res); });
app.post('/GetSurveys', (req, res) => { Create.GetSurveys(req, res); });
app.get('/ReadPublicSurveys', (req,res)=>{Get.ReadPublicSurveys(req,res)})
// Updates
app.put('/UpdateUserDetails', (req, res) => { Update.UpdateUserDetails(req, res); });
app.put('/Vote', (req, res) => { Update.Vote(req, res); });
app.put('/EditPasword', (req, res) => { Update.EditPasword(req, res); });
// Deletes
app.delete('/DeletTargetSurvey', (req, res) => { Delete.DeleteSurvey(req, res); });
//The "catchall" handler: for any request that doesn't match one above, send back React's index.html file.
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, '../surveysway/build/index.html'));
});
app.listen(port, () => {
console.log(`server running on port ${port}`);
}); |
use std::{
fs::File,
io::{Read, Write},
path::Path,
sync::Arc,
};
use zarrs::{
array::{Array, ZARR_NAN_F32},
array_subset::ArraySubset,
storage::{ReadableStorageTraits, ReadableWritableStorageTraits},
};
// const ARRAY_PATH: &'static str = "/array";
const ARRAY_PATH: &str = "/";
fn write_array_to_storage<TStorage: ReadableWritableStorageTraits>(
storage: Arc<TStorage>,
) -> Result<Array<TStorage>, Box<dyn std::error::Error>> {
use zarrs::array::{chunk_grid::ChunkGridTraits, codec, DataType, FillValue};
// Create an array
let array = zarrs::array::ArrayBuilder::new(
vec![8, 8], // array shape
DataType::Float32,
vec![4, 4].into(), // regular chunk shape
FillValue::from(ZARR_NAN_F32),
)
.bytes_to_bytes_codecs(vec![
#[cfg(feature = "gzip")]
Box::new(codec::GzipCodec::new(5)?),
])
.dimension_names(Some(vec!["y".into(), "x".into()]))
// .storage_transformers(vec![].into())
.build(storage, ARRAY_PATH)?;
// Write array metadata to store
array.store_metadata()?;
// Write some chunks (in parallel)
let _ = (0..2)
// .into_par_iter()
.try_for_each(|i| {
let chunk_grid: &Box<dyn ChunkGridTraits> = array.chunk_grid();
let chunk_indices: Vec<u64> = vec![i, 0];
if let Some(chunk_subset) = chunk_grid.subset(&chunk_indices, array.shape())? {
array.store_chunk_elements(
&chunk_indices,
vec![i as f32; chunk_subset.num_elements() as usize],
)
// let chunk_shape = chunk_grid.chunk_shape(&chunk_indices, &array.shape())?;
// let chunk_array = ndarray::ArrayD::<f32>::from_elem(chunk_shape.clone(), i as f32);
// array.store_chunk_ndarray(&chunk_indices, &chunk_array.view())
} else {
Err(zarrs::array::ArrayError::InvalidChunkGridIndicesError(
chunk_indices.to_vec(),
))
}
})?;
println!(
"The array metadata is:\n{}\n",
serde_json::to_string_pretty(&array.metadata()).unwrap()
);
// Write a subset spanning multiple chunks, including updating chunks already written
array.store_array_subset_elements::<f32>(
&ArraySubset::new_with_start_shape(vec![3, 3], vec![3, 3]).unwrap(),
vec![0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9],
)?;
// Store elements directly, in this case set the 7th column to 123.0
array.store_array_subset_elements::<f32>(
&ArraySubset::new_with_start_shape(vec![0, 6], vec![8, 1])?,
vec![123.0; 8],
)?;
// Store elements directly in a chunk, in this case set the last row of the bottom right chunk
array.store_chunk_subset_elements::<f32>(
// chunk indices
&[1, 1],
// subset within chunk
&ArraySubset::new_with_start_shape(vec![3, 0], vec![1, 4])?,
vec![-4.0; 4],
)?;
Ok(array)
}
fn read_array_from_store<TStorage: ReadableStorageTraits>(
array: Array<TStorage>,
) -> Result<(), Box<dyn std::error::Error>> {
// Read the whole array
let subset_all = ArraySubset::new_with_start_shape(vec![0, 0], array.shape().to_vec())?;
let data_all = array.retrieve_array_subset_ndarray::<f32>(&subset_all)?;
println!("The whole array is:\n{:?}\n", data_all);
// Read a chunk back from the store
let chunk_indices = vec![1, 0];
let data_chunk = array.retrieve_chunk_ndarray::<f32>(&chunk_indices)?;
println!("Chunk [1,0] is:\n{data_chunk:?}\n");
// Read the central 4x2 subset of the array
let subset_4x2 = ArraySubset::new_with_start_shape(vec![2, 3], vec![4, 2])?; // the center 4x2 region
let data_4x2 = array.retrieve_array_subset_ndarray::<f32>(&subset_4x2)?;
println!("The middle 4x2 subset is:\n{:?}\n", data_4x2);
Ok(())
}
// https://github.com/zip-rs/zip/blob/master/examples/write_dir.rs
fn zip_dir(
it: &mut dyn Iterator<Item = walkdir::DirEntry>,
prefix: &str,
writer: File,
method: zip::CompressionMethod,
) -> zip::result::ZipResult<()> {
let mut zip = zip::ZipWriter::new(writer);
let options = zip::write::FileOptions::default().compression_method(method);
let mut buffer = Vec::new();
for entry in it {
let path = entry.path();
let name = path.strip_prefix(Path::new(prefix)).unwrap();
if path.is_file() {
println!("Storing file {name:?} <- {path:?}");
#[allow(deprecated)]
zip.start_file_from_path(name, options)?;
let mut f = File::open(path)?;
f.read_to_end(&mut buffer)?;
zip.write_all(&buffer)?;
buffer.clear();
} else if !name.as_os_str().is_empty() {
println!("Storing dir {name:?} <- {path:?}");
#[allow(deprecated)]
zip.add_directory_from_path(name, options)?;
}
}
zip.finish()?;
Result::Ok(())
}
fn zip_array_write_read() -> Result<(), Box<dyn std::error::Error>> {
use walkdir::WalkDir;
use zarrs::{
node::Node,
storage::{storage_adapter::ZipStorageAdapter, store},
};
// Create a store
let path = tempfile::TempDir::new()?;
let mut zarr_dir = path.path().to_path_buf();
zarr_dir.push("hierarchy.zarr");
let store = Arc::new(store::FilesystemStore::new(&zarr_dir)?);
write_array_to_storage(store)?;
// Write the store to zip
let mut path_zip = path.path().to_path_buf();
path_zip.push("zarr_array.zip");
let file = File::create(&path_zip).unwrap();
zip_dir(
&mut WalkDir::new(&zarr_dir).into_iter().filter_map(|e| e.ok()),
zarr_dir.to_str().unwrap(),
file,
zip::CompressionMethod::Stored,
)?;
println!("Created zip {path_zip:?}\n");
let store = Arc::new(store::FilesystemStore::new(&path_zip)?);
let store = Arc::new(ZipStorageAdapter::new(store)?);
let array = Array::new(store.clone(), ARRAY_PATH)?;
read_array_from_store(array)?;
// Show the hierarchy
let node = Node::new_with_store(&*store, "/").unwrap();
let tree = node.hierarchy_tree();
println!("The zarr hierarchy tree is:\n{}", tree);
Ok(())
}
fn main() {
if let Err(err) = zip_array_write_read() {
println!("{}", err);
}
} |
<template>
<!--
通用数据字典下拉列表
用法 <com-dict :val.sync="data.value" dict-name="thatName" :is-all="false" />
editor lianglei
-->
<el-select
:value="val"
v-bind="$attrs"
@change="onChange"
@clear="onClear"
>
<el-option
v-for="item in options"
:key="item.value"
:label="item.label"
:value="item.value"
/>
</el-select>
</template>
<script>
import { localDict } from '@/settings.js'
export default {
name: 'ComDict',
components: {},
props: {
val: {
type: [String, Number],
default: null
},
dictName: {
type: String,
required: true
},
isAll: { // 是否显示全部
type: Boolean,
default: false
},
allLabel: { // 全部的label名称
type: [String, Number],
default: '全部'
},
allValue: { // 全部的默认值
type: [String, Number],
default: null
},
filterStr: { // 过滤,正则条件,匹配的则被过滤掉
type: [String],
default: null
}
},
data() {
return {
options: []
}
},
computed: {},
watch: {},
mounted() {
this.init()
},
methods: {
init() {
let temp_ = localDict[this.dictName]
if (temp_ && Array.isArray(temp_)) {
if (this.filterStr !== null) {
temp_ = temp_.filter(v => {
return !(new RegExp('^(' + this.filterStr + ')$').test(v.value))
})
}
if (this.isAll) {
this.options = [{
value: this.allValue,
label: this.allLabel
}].concat(temp_)
} else {
this.options = [].concat(temp_)
}
} else {
console.error('字典', this.dictName, '不存在或非数组类型!')
}
},
onChange(value) {
console.log('--onChange--', value)
this.$emit('update:val', value)
const cur_ = this.options.filter(item => {
return item.value === value
})
this.$emit('change', cur_.length ? cur_[0] : {})
},
onClear() {
}
}
}
</script>
<style>
</style> |
package com.ruoxu.pattern.observer;
import java.util.ArrayList;
import java.util.List;
/**
* Created by wangli on 16/12/23.
*/
public class ObservableImp<T> implements Observable {
private List<T> datas;
private List<Subscriber> subscribers = new ArrayList<>();
@Override
public void registerObserver(Subscriber subscriber) {
subscribers.add(subscriber);
}
@Override
public void unregisterObserver(Subscriber subscriber) {
if (subscribers.indexOf(subscriber) >= 0) {
subscribers.remove(subscriber);
}
}
@Override
public void notifyDataChange() {
for(int i=0;i<subscribers.size();i++) {
Subscriber subscriber = subscribers.get(i);
subscriber.receive();
}
}
@Override
public void setDatas(List datas) {
this.datas = datas;
}
@Override
public List getDatas() {
return datas;
}
} |
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ProductRegistration.aspx.cs" Inherits="WebAppAssignmnet10.ProductRegistration" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-4bw+/aepP/YC94hEpVNVgiZdgIC5+VKNBQNGCHeKRQN+PtmoHDEXuppvnDJzQIu9" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.1/dist/js/bootstrap.bundle.min.js" integrity="sha384-HwwvtgBNo3bZJJLYd8oVXjrBZt8cqVSpeBNS5n7C8IVInixGAoxmnlMuBnhbgrkm" crossorigin="anonymous"></script>
<title>Product Example</title>
<style type="text/css">
.auto-style1 {
width: 198px;
}
.auto-style2 {
width: 240px;
}
.auto-style3 {
width: 309px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div class="con">
<div class="row">
<div class="col-md-1"> Product Details</div>
</div>
<div class="row" >
<div class ="col-md-1"><asp:Image runat="server" ID="Image3" ImageUrl="~/Images/ps1.jpg"
width="450" Height="150" CssClass ="img-fluid" /></div>
</div>
</div>
<table class="w-100">
<tr>
<td class="auto-style1">Product Name</td>
<td class="auto-style2">
<asp:TextBox ID="TxtProName" runat="server"></asp:TextBox>
</td>
<td class="auto-style3">
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="TxtProName" ErrorMessage="Please Enter Product Name First" ForeColor="Red"></asp:RequiredFieldValidator>
</td>
<td> </td>
</tr>
<tr>
<td class="auto-style1">Category</td>
<td class="auto-style2">
<asp:DropDownList ID="DdlCategory" runat="server">
</asp:DropDownList>
</td>
<td class="auto-style3">
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="DdlCategory" ErrorMessage="Please Select the Category First" ForeColor="Red"></asp:RequiredFieldValidator>
</td>
<td> </td>
</tr>
<tr>
<td class="auto-style1">Price</td>
<td class="auto-style2">
<asp:TextBox ID="TxtPrice" runat="server"></asp:TextBox>
</td>
<td class="auto-style3">
<asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ControlToValidate="TxtPrice" ErrorMessage="Please Enter numeric Values Only" ForeColor="Red"></asp:RequiredFieldValidator>
</td>
<td>
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ControlToValidate="TxtPrice" ErrorMessage="Price Must be Numeric Value" ForeColor="Red" ValidationExpression="^\d+(\.\d+)?$"></asp:RegularExpressionValidator>
</td>
</tr>
<tr>
<td class="auto-style1">Description</td>
<td class="auto-style2">
<asp:TextBox ID="DdlDes" runat="server" TextMode="MultiLine"></asp:TextBox>
</td>
<td class="auto-style3">
<asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server" ControlToValidate="DdlDes" ErrorMessage="Please Enter the Description" ForeColor="Red"></asp:RequiredFieldValidator>
</td>
<td> </td>
</tr>
<tr>
<td class="auto-style1">Release Date</td>
<td class="auto-style2">
<asp:Calendar ID="CalReleaseDate" runat="server" BackColor="White" BorderColor="#3366CC" BorderWidth="1px" CellPadding="1" DayNameFormat="Shortest" Font-Names="Verdana" Font-Size="8pt" ForeColor="#003399" Height="82px" Width="122px">
<DayHeaderStyle BackColor="#99CCCC" ForeColor="#336666" Height="1px" />
<NextPrevStyle Font-Size="8pt" ForeColor="#CCCCFF" />
<OtherMonthDayStyle ForeColor="#999999" />
<SelectedDayStyle BackColor="#009999" Font-Bold="True" ForeColor="#CCFF99" />
<SelectorStyle BackColor="#99CCCC" ForeColor="#336666" />
<TitleStyle BackColor="#003399" BorderColor="#3366CC" BorderWidth="1px" Font-Bold="True" Font-Size="10pt" ForeColor="#CCCCFF" Height="25px" />
<TodayDayStyle BackColor="#99CCCC" ForeColor="White" />
<WeekendDayStyle BackColor="#CCCCFF" />
</asp:Calendar>
</td>
<td class="auto-style3"> </td>
<td> </td>
</tr>
<tr>
<td class="auto-style1"> </td>
<td class="auto-style2">
<asp:Button ID="BtnRegister" runat="server" OnClick="BtnRegister_Click" Text="Register Product" />
</td>
<td class="auto-style3"> </td>
<td> </td>
</tr>
<tr>
<td class="auto-style1"> </td>
<td class="auto-style2"> </td>
<td class="auto-style3"> </td>
<td> </td>
</tr>
</table>
<asp:Label ID="lblInfo" runat="server" Text="Label"></asp:Label>
<asp:ValidationSummary ID="ValidationSummary1" runat="server" ShowMessageBox="True" ShowSummary="False" />
</form>
</body>
</html> |
import type { Meta, StoryObj } from "@storybook/react";
import { fn } from "@storybook/test";
import { DemoButton } from "./DemoButton";
// More on how to set up stories at: https://storybook.js.org/docs/writing-stories#default-export
const meta = {
title: "Example/Button",
component: DemoButton,
parameters: {
// Optional parameter to center the component in the Canvas. More info: https://storybook.js.org/docs/configure/story-layout
layout: "centered",
},
// This component will have an automatically generated Autodocs entry: https://storybook.js.org/docs/writing-docs/autodocs
tags: ["autodocs"],
// More on argTypes: https://storybook.js.org/docs/api/argtypes
argTypes: {},
// Use `fn` to spy on the onClick arg, which will appear in the actions panel once invoked: https://storybook.js.org/docs/essentials/actions#action-args
args: { onClick: fn() },
} satisfies Meta<typeof DemoButton>;
export default meta;
type Story = StoryObj<typeof meta>;
// More on writing stories with args: https://storybook.js.org/docs/writing-stories/args
export const Default: Story = {
args: {
label: "Save",
},
};
export const Success: Story = {
args: {
label: "Save",
state: "success",
},
};
export const Error: Story = {
args: {
label: "Save",
state: "error",
},
}; |
using Dapper;
using Discount.API.Entities;
using Microsoft.Extensions.Configuration;
using Npgsql;
using System.Threading.Tasks;
namespace Discount.API.Repositories
{
public class DiscountRepository : IDiscountRepository
{
private readonly IConfiguration _configuration;
public DiscountRepository(IConfiguration configuration)
{
this._configuration = configuration;
}
public async Task<bool> CreateDiscount(Coupon coupon)
{
using var connection = new NpgsqlConnection(_configuration.GetValue<string>("DatabaseSettings:ConnectionString"));
var affected = await connection.ExecuteAsync("INSERT INTO Coupon(ProductName,Description,Amount) VALUES (@ProductName,@Description,@Amount)",
new {ProductName = coupon.ProductName, Description = coupon.Description, Amount = coupon.Amount});
if (affected == 0)
return false;
return true;
}
public async Task<bool> DeleteDiscount(string productName)
{
using var connection = new NpgsqlConnection(_configuration.GetValue<string>("DatabaseSettings:ConnectionString"));
var affected = await connection.ExecuteAsync("DELETE FROM Coupon WHERE ProductName = @ProductName",
new { ProductName = productName});
if (affected == 0)
return false;
return true;
}
public async Task<Coupon> GetDiscount(string productName)
{
using var connection = new NpgsqlConnection(_configuration.GetValue<string>("DatabaseSettings:ConnectionString"));
var coupon = await connection.QueryFirstOrDefaultAsync<Coupon>("SELECT * FROM Coupon WHERE ProductName = @ProductName", new { ProductName = productName});
if (coupon == null)
return new Coupon { Amount = 0 , Description = "No Disc", ProductName = "No Discount"};
return coupon;
}
public async Task<bool> UpdateDiscount(Coupon coupon)
{
using var connection = new NpgsqlConnection(_configuration.GetValue<string>("DatabaseSettings:ConnectionString"));
var affected = await connection.ExecuteAsync("UPDATE Coupon SET ProductName = @ProductName,Description = @Description ,Amount = @Amount WHERE Id =@Id)",
new { ProductName = coupon.ProductName, Description = coupon.Description, Amount = coupon.Amount, Id = coupon.Id });
if (affected == 0)
return false;
return true;
}
}
} |
import SwiftUI
import Foundation
import Firebase
class RestaurantManager: ObservableObject {
@Published var restaurants: [Restaurant] = []
private var groupId: String
init(groupId: String) {
self.groupId = groupId
fetchRestaurants()
}
func fetchRestaurants() {
let db = Firestore.firestore()
let groupRef = db.collection("Groups")
// Restaurants are stored in votingRestaurants attribute in Firebase group collection (groupRef.document(groupId).votingRestaurants)
groupRef.document(groupId).addSnapshotListener { snapshot, error in
guard error == nil else {
print(error!.localizedDescription)
return
}
if let snapshot = snapshot {
self.restaurants.removeAll()
let data = snapshot.data()
print("Printing data")
print(data)
// Convert data to Restaurant objects
if let restaurants = data?["votingRestaurants"] as? [[String: Any]] {
for restaurant in restaurants {
let id = restaurant["id"] as? String ?? ""
let name = restaurant["name"] as? String ?? ""
let distance = restaurant["distance"] as? Int ?? 0
let menuArray = restaurant["menu"] as? [[String: Any]] ?? []
let usersVoted = restaurant["usersVoted"] as? [String] ?? []
var dayMenu = DayMenu()
for menuItem in menuArray {
if let mealName = menuItem["name"] as? String {
dayMenu.meals.append(Meal(name: mealName))
}
}
let newRestaurant = Restaurant(id: id, name: name, menu: dayMenu, distance: distance, usersVoted: usersVoted)
self.restaurants.append(newRestaurant)
}
self.restaurants.sort { $0.usersVoted.count.description > $1.usersVoted.count.description }
}
print(self.restaurants)
}
}
}
func updateRestaurantsInGroup(){
let db = Firestore.firestore()
let groupRef = db.collection("Groups").document(groupId)
// Update the votingRestaurants attribute in the group with the new list of restaurants
groupRef.updateData([
"votingRestaurants": restaurants.map { restaurant in
[
"id": restaurant.id,
"name": restaurant.name,
"distance": restaurant.distance,
"menu": restaurant.menu.meals.map { meal in
["name": meal.name]
},
"usersVoted": restaurant.usersVoted
]
}
]) { error in
if let error = error {
print(error.localizedDescription)
return
}
print("Restaurants updated in group")
}
}
func voteForRestaurant(groupId: String, restaurantId: String, userId: String){
let db = Firestore.firestore()
let groupRef = db.collection("Groups").document(groupId)
var restaurantToVote = restaurants.first { $0.id == restaurantId }
if let index = restaurants.firstIndex(where: { $0.id == restaurantId }) {
restaurantToVote?.usersVoted.append(userId)
restaurants[index] = restaurantToVote!
}
updateRestaurantsInGroup()
}
func getRestaurantVotes(restaurantId: String) -> Int {
let restaurant = restaurants.first { $0.id == restaurantId }
return restaurant?.usersVoted.count ?? 0
}
} |
<template>
<div>
<checkView
ref="checkRef"
title="提现余额"
@confirmHandle="confirmHandle"
>
<template v-slot:content>
<div>
<div class="withdraw-money">可提现金额:{{ balance / 100 || 0 }}元</div>
<a-form layout="vertical" :model="formState">
<a-form-item label="本次提现金额">
<a-input v-model:value="formState.withdrawal" placeholder="请输入提现金额" />
</a-form-item>
<a-form-item label="支付宝账户姓名">
<a-input v-model:value="formState.aliPayName" placeholder="请输入姓名" />
</a-form-item>
<a-form-item label="支付宝账户">
<a-input v-model:value="formState.aliPayAccount" placeholder="请输入账户信息" />
</a-form-item>
</a-form>
</div>
</template>
</checkView>
</div>
</template>
<script lang="ts" setup>
import { ref, UnwrapRef, reactive, toRefs } from 'vue'
import checkView from '@/components/modal/check.vue'
import { postwithdrawal } from '@/api/withdrawal'
import { message } from 'ant-design-vue';
// const amount = 60
interface Props {
balance?: number
}
interface FormState {
withdrawal: any;
aliPayName: string;
aliPayAccount: string;
}
const props = withDefaults(
defineProps<Props>(), {
balance: 0
}
)
const { balance } = toRefs(props)
const formState: UnwrapRef<FormState> = reactive({
withdrawal: '',
aliPayName: '',
aliPayAccount: ''
});
const checkRef = ref<any>(null)
const confirmHandle = async () => {
console.log(formState)
const { withdrawal, aliPayName, aliPayAccount } = formState
console.log(withdrawal, aliPayName, aliPayAccount)
if ( !withdrawal || !aliPayName || !aliPayAccount) return message.info('请完整填写相关信息!')
const { code, data } = await postwithdrawal({
balance: balance.value,
withdrawal: withdrawal * 100,
aliPayName,
aliPayAccount
})
if (code === 0 && data) {
message.success('申请提现成功!')
checkRef.value.handleOk()
} else {
message.error('申请提现失败!')
}
}
defineExpose({
checkRef
})
</script>
<style lang="scss" scoped>
.withdraw-money{
padding: 0 0 20px 0;
}
</style> |
import React, { useState, useCallback, useEffect, useRef } from 'react';
import useEventListenerMemo from '../../../hooks/useEventListenerMemo';
import useQuery from '../../../hooks/useQuery';
import {
LoopTimebarBackground,
LoopTimebarContainer,
LoopPins,
LoopTimebarEnabled,
Backdrop,
} from './StyledComponents';
export const timeToSeconds = (time) => {
if (!time) return null;
return parseInt(
time
.replace('s', '')
.replace(/h|m/g, ':')
.split(':')
.reduce((acc, time) => 60 * acc + +time)
);
};
const secondsToHHMMSS = (s) => {
try {
return new Date(s * 1000).toISOString().substr(11, 8);
} catch (e) {
return '';
}
};
const Loopbar = ({
twitchVideoPlayer,
loopEnabled,
duration = twitchVideoPlayer.getDuration(),
}) => {
const queryStartTime = useQuery().get('start');
const querylist = useQuery().get('list');
const querylistName = useQuery().get('listName');
const urlStartTime = useQuery().get('t') || queryStartTime || null;
const urlEndTime = useQuery().get('end') || null;
const listName = querylist || querylistName || null;
const [start, setStart] = useState({
time: 0,
pos: 0,
active: false,
});
const [end, setEnd] = useState({
time: 0,
pos: 0,
active: false,
});
const ref = useRef();
const endTimeRef = useRef();
const handleResizeMouseUp = () => {
setStart((cur) => ({ ...cur, active: false }));
setEnd((cur) => ({ ...cur, active: false }));
seek();
setAndStartTimer();
};
const setAndStartTimer = useCallback(() => {
const currrentTime = twitchVideoPlayer.getCurrentTime();
clearTimeout(endTimeRef.current);
endTimeRef.current = setTimeout(() => {
twitchVideoPlayer.seek(start.time);
setTimeout(() => {
setAndStartTimer();
}, 10000);
}, ((end.time || duration || twitchVideoPlayer.getDuration()) - currrentTime) * 1000);
return () => clearTimeout(endTimeRef.current);
}, [duration, end.time, start.time, twitchVideoPlayer]);
const resize = useCallback(
(e) => {
if (!end.active && !start.active) return false;
const mouseX = Math.max(e.clientX - 20, 0);
const newObj = {
time: (duration || twitchVideoPlayer.getDuration() / ref.current.clientWidth) * mouseX,
pos: mouseX,
active: true,
};
if (start.active) setStart(newObj);
if (end.active) setEnd(newObj);
},
[duration, end, start, setStart, setEnd, twitchVideoPlayer]
);
const seek = () => {
const currrentTime = twitchVideoPlayer.getCurrentTime();
if (start.time > currrentTime) twitchVideoPlayer.seek(start.time);
if (end?.time && end?.time < currrentTime) twitchVideoPlayer.seek(end.time);
window.history.pushState(
{},
document.title,
`${window.location.origin + window.location.pathname}?start=${new Date(start.time * 1000)
.toISOString()
.substr(11, 8)}&end=${new Date(end.time * 1000).toISOString().substr(11, 8)}${
listName ? `&list=${listName}${loopEnabled ? `&loop=${loopEnabled}` : ''}` : ''
}`
);
};
const loopVideo = () => {
if (start && urlStartTime) {
twitchVideoPlayer.seek(timeToSeconds(urlStartTime));
} else {
twitchVideoPlayer.seek(0);
}
};
useEventListenerMemo('mouseup', handleResizeMouseUp, window, end.active || start.active);
useEventListenerMemo('mousemove', resize, window, end.active || start.active);
useEventListenerMemo(window?.Twitch?.Player?.ENDED, loopVideo, twitchVideoPlayer);
useEventListenerMemo(window?.Twitch?.Player?.PLAYING, setAndStartTimer, twitchVideoPlayer);
useEffect(() => {
const startTime = timeToSeconds(urlStartTime);
const endTime = timeToSeconds(urlEndTime);
setStart({
time: startTime,
pos: startTime / (duration || twitchVideoPlayer.getDuration() / ref.current?.clientWidth),
active: false,
});
setEnd({
time: endTime,
pos: endTime / (duration || twitchVideoPlayer.getDuration() / ref.current?.clientWidth),
active: false,
});
}, [duration, urlEndTime, urlStartTime, twitchVideoPlayer]);
return (
<>
{(end?.active || start?.active) && <Backdrop />}
<LoopTimebarContainer ref={ref} active={end?.active || start?.active}>
<LoopTimebarBackground>
<LoopTimebarEnabled
left={start.pos}
width={end.pos ? `${end.pos - start.pos}px` : `calc(100% - ${start.pos || 0}px)`}
>
<LoopPins
style={{ left: '0px', borderRadius: '5px 2px 2px 5px' }}
onMouseDown={() => setStart((cur) => ({ ...cur, active: true }))}
active={start.active}
>
<p>{secondsToHHMMSS(start?.time)}</p>
</LoopPins>
<p id='loopedDuration'>{secondsToHHMMSS(end?.time - start?.time)}</p>
<LoopPins
style={{ right: '0px', borderRadius: '2px 5px 5px 2px' }}
onMouseDown={() => setEnd((cur) => ({ ...cur, active: true }))}
active={end.active}
>
<p>{secondsToHHMMSS(end?.time)}</p>
</LoopPins>
</LoopTimebarEnabled>
</LoopTimebarBackground>
</LoopTimebarContainer>
</>
);
};
export default Loopbar; |
import React from 'react';
import { useEffect } from 'react';
import { useState } from 'react';
import { useParams } from 'react-router-dom';
import { baseUrl, getUserLogado } from '../../auth/auth';
import Botao from '../../components/Botao/Botao';
import Header from '../../components/Header/Header';
import Modal from '../../components/Modal/Modal';
import TabMenu from '../../components/TabMenu/TabMenu';
import { RemoveItem } from '../Perfil/styled';
import './Vaga.css'
function Vaga() {
const userLogado = getUserLogado()
const [userCandidato, setUserCandidato] = useState(null)
const { idVaga } = useParams()
const [modalSucessoOpen, setModalSucessoOpen] = useState(false)
const [modalEditarOpen, setModalEditarOpen] = useState(false)
const [modalRemoverOpen, setModalRemoverOpen] = useState(false)
const [modalSkillOpen, setModalSkillOpen] = useState(false)
const [buscaSkill, setBuscaSkill] = useState('')
const [vaga, setVaga] = useState(null)
const [glossary, setGlossary] = useState([])
useEffect(() => {
buscarVaga()
fetch(`${baseUrl()}/skill/glossary`, {
method: 'GET'
})
.then(async res => {
if (res.ok) {
let json = await res.json()
setGlossary(json)
}
})
if (userLogado.tipo === 'candidato')
buscaPerfil()
}, [])
useEffect(() => {
const descricao = document.getElementById('html-descricao')
if (descricao != null)
descricao.innerHTML = vaga?.descricao.replaceAll('\n', '<br/>')
}, [vaga])
function buscarVaga() {
fetch(`${baseUrl()}/vaga/${idVaga}`, {
method: 'GET'
})
.then(async res => {
if (res.ok) {
let vaga = await res.json()
setVaga(vaga)
}
})
}
function editarHandler(e) {
e.preventDefault()
const form = e.target
const data = {
id: idVaga,
cargo: form.querySelector('#cargo').value,
qtdVagas: form.querySelector('#qtd-vagas').value,
salario: form.querySelector('#salario').value,
dataEncerramento: form.querySelector('#dtEncerramento').value.split('-').reverse().join('/'),
descricao: form.querySelector('#descricao').value,
}
fetch(`${baseUrl()}/vaga`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data)
})
.then(async res => {
if (res.ok) {
setModalEditarOpen(false)
buscarVaga()
}
})
}
function removerHandler() {
fetch(`${baseUrl()}/vaga/${idVaga}`, {
method: 'DELETE'
})
.then(async res => {
if (res.ok) {
setModalRemoverOpen(false)
window.location.replace('/vagas')
}
})
}
function adicionarSkillHandler(e) {
e.preventDefault()
const form = e.target
const data = {
id: form.querySelector('#input-hard-skill').value,
nivel: form.querySelector('#nivel-hard-skill').value,
tipo: 'H'
}
fetch(`${baseUrl()}/vaga/${idVaga}/skill`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data)
})
.then(async res => {
if (res.ok) {
setModalSkillOpen(false)
buscarVaga()
}
})
}
function removerSkillHandler(id) {
fetch(`${baseUrl()}/vaga/${idVaga}/skill/${id}`, {
method: 'DELETE'
})
.then(async res => {
if (res.ok) {
setModalSkillOpen(false)
buscarVaga()
}
})
}
function buscaPerfil() {
fetch(`${baseUrl()}/candidato/perfil/${userLogado.id}`, {
method: 'GET'
})
.then(async res => {
if (res.ok) {
const json = await res.json()
setUserCandidato(json);
}
else
setUserCandidato(null)
})
}
function calcularMatch() {
const candidatoSkills = userCandidato?.skills
const vagaSkills = vaga?.skillsDesejadas
if (vagaSkills?.length > 0) {
let pontosPossiveis = vagaSkills?.length * 100
let pontosFeitos = 0
vagaSkills?.forEach(skill => {
for (let index = 0; index < candidatoSkills?.length; index++) {
if (candidatoSkills[index].id === skill.id) {
pontosFeitos += 50
if (candidatoSkills[index].nivel >= skill.nivel)
pontosFeitos += 50
}
}
})
let porcentagem = Math.round((pontosFeitos * 100) / pontosPossiveis)
if (porcentagem < 0)
porcentagem = 0
else if (porcentagem > 100)
porcentagem = 100
return porcentagem
}
return 100
}
function corMatch(match) {
if (match <= 40) {
return 'var(--barra3)'
} else if (match <= 70) {
return 'var(--barra2)'
} else {
return 'var(--barra1)'
}
}
function realizarCandidaturaHandler() {
const data = {
candidato: {
idCandidato: userLogado.id
},
vaga: {
id: idVaga
}
}
fetch(`${baseUrl()}/candidatura`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data)
})
.then(async res => {
if (res.ok) {
setModalSucessoOpen(true)
buscarVaga()
}
})
}
return (
<>
<Header />
<main className="container">
<div className="vaga">
{
vaga != null &&
<>
<div>
<img src={`data:image/png;base64,${vaga?.empresa?.fotoEmpresa}`} alt="Logo" />
<h1>{vaga?.empresa.nome}</h1>
</div>
{
userLogado.tipo === 'candidato'
? <p>
<span>Match Level: </span>
<strong style={{ backgroundColor: corMatch(vaga?.match) }}>
{calcularMatch()}%
</strong>
</p>
: <></>
}
<p>
<span>Inscrição até: </span> {vaga.dataEncerramento}
</p>
<p>
<span>Salário: </span> R${vaga.salario.toFixed(2)}
</p>
<p>
<span>Cargo: </span> {vaga.cargo}
</p>
<p>
<span>Hard Skills: </span>
{
vaga.skillsDesejadas.map((skill, index) => {
let aux = skill.descricao + ' (' + skill.nivel + ')'
return <React.Fragment key={index}>
{aux}
{
userLogado.tipo === 'empresa' &&
userLogado.id === vaga?.empresa.id &&
<RemoveItem className="centro" onClick={() => removerSkillHandler(skill.id)} style={{ position: 'static', transform: 'translateY(5%)' }}>
<i className="fi fi-recycle-bin"></i>
</RemoveItem>
}
 
</React.Fragment>
})
}
{
vaga.skillsDesejadas.length === 0 ? 'Nenhuma' : ''
}
</p>
<p>
<span>Vagas Dísponiveis: </span>{vaga.qtdVagas}
</p>
<p>
<span>Descrição: </span>
<br />
<span id='html-descricao'></span>
</p>
</>
}
{
vaga == null &&
<strong style={{ fontSize: '20px', fontWeight: 900, textAlign: "center", width: '100%' }}>
Vaga não encontrada
</strong>
}
{/* OPCOES CANDIDATO */}
{
userLogado.tipo === 'candidato' &&
vaga !== null &&
<div className="botoes">
{
vaga?.candidaturas?.filter(c => c.candidato.idCandidato === userLogado.id) < 1
? <Botao tipo='cheio' cor='azul' onClick={realizarCandidaturaHandler}>
Me Candidatar
</Botao>
: <Botao tipo='cheio' cor='cinza' onClick={() => {}}>
Já Inscrito
</Botao>
}
<Modal isOpen={modalSucessoOpen} setOpen={setModalSucessoOpen} titulo="Sucesso">
<i className="fi fi-check-mark-circle candidatura-realizada-check"></i>
<span>Candidaduta realizada!</span>
</Modal>
</div>
}
{/* OPCOES EMPRESA */}
{
userLogado.tipo === 'empresa' &&
userLogado.id === vaga?.empresa.id &&
<div className="botoes">
{
glossary.length > 0 &&
<Botao tipo='vazio' cor='azul' onClick={() => setModalSkillOpen(true)}>
<i className="fi fi-plus-square"></i>
Skill
</Botao>
}
<Botao tipo='vazio' onClick={() => setModalEditarOpen(true)}>
<i className="fi fi-setting"></i>
Editar
</Botao>
<Botao tipo='cheio' cor='vermelho' onClick={() => setModalRemoverOpen(true)}>
<i className="fi fi-close"></i>
Remover
</Botao>
{/* EDITAR VAGA */}
<Modal isOpen={modalEditarOpen} setOpen={setModalEditarOpen} titulo="Editar Vaga" afterOpen={() => { }}>
<form action="" style={{ width: '100%', display: 'flex', flexWrap: 'wrap', justifyContent: 'space-between' }} onSubmit={editarHandler}>
<div className="form__group col-12 cargo" style={{ marginTop: 0 }}>
<label htmlFor="cargo">Cargo</label>
<input type="text" required className="form__control" placeholder="Cargo" name="cargo" id="cargo" defaultValue={vaga?.cargo} />
</div>
<div className="form__group col-6 grupo">
<label htmlFor="qtd-vagas">Vagas Dísponiveis</label>
<input type="numeric" required className="form__control" placeholder="Vagas Dísponiveis" name="qtd-vagas" id="qtd-vagas" defaultValue={vaga?.qtdVagas} />
</div>
<div className="form__group col-6 money">
<label htmlFor="salario">Salário</label>
<input type="numeric" required className="form__control" placeholder="Salário" name="salario" id="salario" defaultValue={vaga?.salario.toFixed(2)} />
</div>
<div className="form__group col-12 data">
<label htmlFor="dtEncerramento">Data de Encerramento</label>
<input type="date" className="form__control" required name="dtEncerramento" id="dtEncerramento" placeholder="dd/mm/aaaa"
defaultValue={vaga?.dataEncerramento.split('/').reverse().join('-')} />
</div>
<div className="form__group col-12 mensagem">
<label htmlFor="descricao">Descrição</label>
<textarea type="area" name="descricao" required id="descricao" className="form__control" placeholder="Descrição" autoComplete="off"
defaultValue={vaga?.descricao}></textarea>
</div>
<div className="botoes">
<Botao tipo='vazio' cor='azul'>
Atualizar
</Botao>
</div>
</form>
</Modal>
{/* REMOVER VAGA */}
<Modal isOpen={modalRemoverOpen} setOpen={setModalRemoverOpen} titulo="Confirmação" afterOpen={() => { }}>
<span>Deseja realmente remover a vaga? Essa ação é permanente e não será possível acessar as candidaturas da vaga mais.</span>
<div className="botoes">
<Botao tipo='vazio' cor='vermelho' onClick={removerHandler}>
Confirmar
</Botao>
</div>
</Modal>
{/* MODAL DE ADICIONAR SKILL */}
<Modal isOpen={modalSkillOpen} setOpen={setModalSkillOpen} titulo="Adicionar Skill" afterOpen={() => { }}>
<form action="" style={{ width: '100%', display: 'flex', flexWrap: 'wrap', justifyContent: 'space-between' }} onSubmit={adicionarSkillHandler}>
<div id='secao-hard-skill' style={{ width: '100%' }}>
<div className="form__group col-12 busca" id='div-busca-hard-skill'>
<label htmlFor="busca-hard-skill">Buscar Hard Skill</label>
<input type="text" className="form__control" placeholder="Hard Skill" name="busca-hard-skill" id="busca-hard-skill"
onChange={(e) => setBuscaSkill(e.target.value)} />
</div>
<div className="form__group col-12" id='div-hard-skill'>
<label htmlFor="input-hard-skill">Selecionar Hard Skill</label>
<select className="form__control" required name="input-hard-skill" id="input-hard-skill">
{
glossary.filter(skill => skill.descricao.toLowerCase().includes(buscaSkill.toLowerCase())).map(skill => (
<option value={skill.id} key={skill.id}>{skill.descricao}</option>
))
}
</select>
</div>
<div className="form__group col-12">
<label htmlFor="nivel-hard-skill">Nível da Hard Skill</label>
<select className="form__control" required name='nivel-hard-skill' id='nivel-hard-skill'>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
</select>
</div>
</div>
<div className="botoes">
<Botao tipo='vazio' cor='azul'>
Cadastrar
</Botao>
</div>
</form>
</Modal>
</div>
}
</div>
</main>
<TabMenu />
</>
)
}
export default Vaga; |
import { render, screen } from '@woographql/testing';
import { ProductImage } from '.';
import { useProductContext, ProductContext } from '@woographql/client/ProductProvider';
// Mock hooks and components
jest.mock('@woographql/client/ProductProvider', () => ({
useProductContext: jest.fn(() => ({
get: jest.fn(),
})),
}));
describe('ProductImage component', () => {
const mockedUseProductContext = useProductContext as jest.MockedFunction<typeof useProductContext>;
afterEach(() => {
jest.clearAllMocks();
});
it('renders correctly', () => {
const mockProduct = {
image: {
sourceUrl: 'https://example.com/image.jpg',
altText: 'Test Image',
},
};
mockedUseProductContext.mockImplementationOnce(() => ({
get: (field) => mockProduct.image[field as keyof typeof mockProduct.image],
} as ProductContext));
render(<ProductImage product={mockProduct as any} />);
const img = screen.getByAltText('Test Image') as HTMLImageElement;
expect(img).toBeInTheDocument();
expect(img.src).toBe('https://example.com/image.jpg');
});
it('does not render if no image source url', () => {
const mockProduct = {
image: {
sourceUrl: '',
altText: 'Test Image',
},
};
mockedUseProductContext.mockImplementationOnce(() => ({
get: (field) => mockProduct.image[field as keyof typeof mockProduct.image],
} as ProductContext));
render(<ProductImage product={mockProduct as any} />);
expect(screen.queryByAltText('Test Image')).not.toBeInTheDocument();
});
}); |
<!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>CSS 예제</title>
<script src="../js/jquery.min.js"></script>
<style>
.box{
width: 300px; height: 300px; border: 1px solid #000;
margin-top: 30px; text-align: center; line-height: 300px;
}
.selected{
background: yellow;
}
</style>
</head>
<body>
<button class="btn-add">add class</button>
<button class="btn-remove">remove class</button>
<button class="btn-toggle">toggle class</button>
<button class="btn-css1">background : red</button>
<button class="btn-css2">border-width : 3px, font-size : 30px</button>
<div class="box">박스</div>
<script>
/*
A.addClass('B') : A 요소의 클래스에 B 클래스를 추가
A.removeClass('B') : A 요소의 클래스에 B 클래스를 삭제
A.toggleClass('B') : A 요소의 클래스에 B 클래스가 있으면 삭제,
없으면 B 클래스를 추가
A.hasClass('B') : A요소의 클래스에 B클래스가 있으면 true, 없으면 false
A.css('속성명', '값') : A클래스의 스타일로 속성명에 값을 설정
A.css({속성명 : 값, 속성명 : 값}) : A클래스의 css 스타일로 객체를 설정
A.css('속성명') : A클래스의 속성명에 해당하는 css스타일 값을 가져옴
*/
$('.btn-add').click(function(){
$('.box').addClass('selected');
});
$('.btn-remove').click(function(){
$('.box').removeClass('selected');
});
$('.btn-toggle').click(function(){
$('.box').toggleClass('selected');
});
$('.btn-css1').click(function(){
$('.box').css('background', 'red');
});
$('.btn-css2').click(function(){
$('.box').css({
'border-width' : '3px',
'font-size' : '30px'
});
});
let border = $('.box').css('border');
console.log(border);
</script>
</body>
</html> |
import 'package:flutter/material.dart';
class ReclamationCard extends StatelessWidget {
final String title;
final String description;
final bool status;
final String createdAt;
final String updatedAt;
final VoidCallback onUpdateStatus;
final VoidCallback ondelete;
ReclamationCard({
required this.title,
required this.description,
required this.status,
required this.createdAt,
required this.updatedAt,
required this.onUpdateStatus,
required this.ondelete,
});
@override
Widget build(BuildContext context) {
return Card(
elevation: 3,
margin: const EdgeInsets.all(10),
child: Padding(
padding: const EdgeInsets.all(15),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
Text(
title,
style: const TextStyle(
fontSize: 18,
fontWeight: FontWeight.bold,
),
),
IconButton(onPressed: ondelete, icon: const Icon(Icons.delete))
],
),
const SizedBox(height: 10),
Text(
description,
style: const TextStyle(
fontSize: 16,
),
),
const SizedBox(height: 10),
Row(
children: [
Icon(
status ? Icons.check : Icons.close,
color: status ? Colors.green : Colors.red,
),
const SizedBox(width: 5),
Text(
status ? 'Resolved' : 'Pending',
style: TextStyle(
color: status ? Colors.green : Colors.red,
fontWeight: FontWeight.bold,
),
),
],
),
const SizedBox(height: 10),
Text(
'Created At: $createdAt',
style: const TextStyle(
color: Colors.grey,
),
),
const SizedBox(height: 5),
Text(
'Updated At: $updatedAt',
style: const TextStyle(
color: Colors.grey,
),
),
const SizedBox(height: 10),
status == false
? TextButton(
onPressed: onUpdateStatus,
child: const Text(
'Update Status',
style: TextStyle(color: Colors.blue),
),
)
: const SizedBox()
],
),
),
);
}
} |
# CI/CD Product Recipe
Product Compatibility: IWX 5.3.1
## Introduction
This product recepie is responsible for migration of Infoworks artifacts from lower environment(Dev/QA) to higher environment(Prod).
<br>
Supports Infoworks version 5.2 onwards
## Table of Contents
- [Introduction](#introduction)
- [Prerequisites](#prerequisites)
- [Installation](#installation)
- [Usage](#usage)
- [Authors](#authors)
# CICD Flow



# Prerequisites
- The deployment server VM should have access to the Github repository and should be given read/write access.
- The deployment server VM should be able to talk to the source and target IWX environments on the 3001/443 port
- The Secrets with the connection details to Pre-Prod/QA environments should be created before executing the migration
- The Target/upper Infoworks Environment version should be the same as the source/lower Infoworks Environment version.
- Infoworks Target Environment should be installed and the environment should be created with the necessary storage and compute interactive cluster.
- The License key should be installed in the Target Infoworks environment with all the required source connector options.
- Ensure that the interactive clusters in both the Source and Target Infoworks Environment are up and running through the migration process.
- The other infoworks users have to be created in the target environment and the roles and access to the domains should be created post-migration.
# Installation
The script will automatically install infoworkssdk required to perform CICD actions when executed.
# Limitations
Will not migrate Infoworks schedules (typically PROD schedules are different from lower environment schedules)
# What are the considerations and steps for CI/CD process integration with Infoworks?
## Migration of Artifacts
### Sources
- Creates source and maps it with environment
- Configure the connection details for the source
- Browse the source for the tables based on filter criteria if any
- Add the browsed tables and metacrawl the tables
- Configure the tables ingestion configurations(Natural keys,watermark column, split by, partition by, advance configurations, etc.)
- Create and configure the table groups
### Pipelines
- Creates the domain for pipeline if doesn’t exist already
- Creates pipeline and attach it to the compute
- Configure the pipeline using the pipeline model from lower environment
- Advance configuration if any
### Workflows
- Creates workflows
- Configures workflow
# Infoworks Developer CICD flow:
- On your local system, make sure you have a local repository cloned from the remote repository. Then, do the following:
- wget –no-check-certificate https://infoworks-releases.s3.amazonaws.com/customer_cicd_poc.tar.gz
- git checkout the repository branch (preprod or prod)
- cd to the repo directory.
- Run the get_config_export.py with the below mentioned parameters to export the required artifacts configurations into individual json files.
# Files/Directory structure
- config.ini: Contains all the parameters and the mappings required for the migration process.
- get_config_export.py: The master script that needs to be executed on your local machine to export the required artfacts into JSON files.
- deployment_plan.py : This script prints the information about the artifacts that will get migration during the current run along with changes provided in config.ini.
- configurations directory: Storage for all the required JSONs of the sources/pipelines/workflows that are exported during the migration process.
#Usage
```sh
python3 get_config_export.py --source_ids <source_ids> --pipeline_ids <pipeline_ids> --pipeline_group_ids <pipeline_group_ids> --workflow_ids <workflow_ids> --refresh_token <your_refresh_token> --protocol http --host <hostname> --port <port>
```
## Parameters for the script:
- source_ids :comma separated source ids to be migrated
- pipeline_ids: comma separated pipeline ids to be migrated
- pipeline_group_ids: comma separated pipeline group ids to be migrated (This will include all the pipelines within pipeline group. Note: Applicable only for Snowflake environment)
- workflow_ids: comma separated workflow ids to be migrated
- refresh_token: your infoworks refresh token from lower environment
- protocol: protocol used to access lower environment(http/https)
- host: host ip of lower environment.
- port: restapi port number of lower environment.(3001 for http and 443 for https)
# Example
```sh
python3 get_config_export.py --source_ids 1d6fae5b9c1d6359d4f0cf1e,dd8b62c3b9455d0b4b016c4d --pipeline_ids 83c15fb2157347a1e4ff030b --workflow_ids 77f68f74d3ec09a4cff076f2 --refresh_token <your_refresh_token> --protocol http --host 10.28.1.163 --port 3001
WARNING: You are using pip version 21.1.1; however, version 22.1.2 is available.
You should consider upgrading via the '/Users/infoworks-user/test_dump/bin/python3 -m pip install --upgrade pip' command.
Dumping file /Users/infoworks-user/configurations/source/source_DEMO_ORACLE.json
Dumping file /Users/infoworks-user/configurations/source/source_DEMO_CSV.json
Dumping file
/Users/infoworks-user/configurations/pipeline/DEMO_DOMAIN#pipeline_DEMO_PIPELINE.json
Dumping file /Users/infoworks-user/configurations/workflow/DEMO_DOMAIN#workflow_DEMO_WORKFLOW.json
(test_dump) IWX-IN-C02WP14TG8WN:~ infoworks-user$
```
### Edit the config.ini as per the mapping needs.
For instance, you would need to map the preprod environment name to prod environment name, you can do so with the config.ini as follows:
```ini
[api_mappings]
ip=10.28.1.95
port=3001
protocol=http
maintain_lineage=false
refresh_token=zThziQ7MoJJPYAha+U/+PBSTZG944F+SHBDs+m/z2qn8+m/ax8Prpzla1MHzQ5EBLzB2Bw8a+Qs9r6En5BEN2DsmUVJ6sKFb2yI2
env_tag=PRD
[environment_mappings]
PRE_PROD_SNOWFLAKE=PROD_SNOWFLAKE
[storage_mappings]
PRE_PROD_DEFAULT_STORAGE=PROD_DEFAULT_STORAGE
[compute_mappings]
PRE_PROD_DEFAULT_PERSISTENT_COMPUTE=PROD_DEFAULT_PERSISTENT_COMPUTE
[table_group_compute_mappings]
PRE_PROD_DEFAULT_PERSISTENT_COMPUTE=PROD_DEFAULT_PERSISTENT_COMPUTE
DEFAULT_DEMO_COMPUTE_CLUSTER=Default_Persistent_Compute_Template
```
In the above file:
[api_mappings]
Contains information about target machine (host,port,infoworks user refresh token etc)
port: rest api port of lower environment.(3001 for http,443 for https)
Note:
If there are any customer specific changes that are supposed to happen like schema name change during the CICD process they can do so by following the below format for section name in config.ini
```ini
[configuration$source_configs$data_lake_schema]
DEMO_CSV_Schema=DEMO_CSV_Schema_PRD
PUBLIC=PUBLIC_PRD
```
You need to specify the path in the json where the particular key appears separated by $.
For cases where you want to give regex pattern instead of actual key name to match criteria for multiple pipelines you can give regex as follows:
```ini
[configuration$pipeline_configs$model$nodes$SNOWFLAKE_TARGET_.*$properties$database_name]
TEST_DATABASE=PRD_DATABASE
```
In the above example, we can match multiple snowflake target table( SNOWFLAKE_TARGET_ABCD,SNOWFLAKE_TARGET_DEFG etc) properties instead of individually specifying section for each keys.
#### Note:
(The above feature is available only starting from Infoworks SDK versions infoworkssdk >= 3.0a3)
In case the json has array of json values, you could use * instead of giving actual index number in section name of config.ini
For example:
```ini
[configuration$pipeline_configs$pipeline_parameters$*$value]
SUPPORT_DB=PRD_DB
```
“*” in the above section indicates the value variable can be in any index of the pipeline_parameters array.
```json
{
"configuration": {
"pipeline_configs": {
"type": "sql",
"query": "Y3JlYXRlIHRhYmxlIHNxbF9waXBlbGluZV8xX3RhYmxlIGFzIHNlbGVjdCAqIGZyb20gY3VzdG9tZXJz", //pragma: allowlist secret
"pipeline_parameters": [
{
"key": "DB_NAME",
"value": "SUPPORT_DB"
}
],
"batch_engine": "SNOWFLAKE",
"query_tag": "dev",
"description": ""}}}
```
### Optional step:
Run deployment_plan.py step to print information about what all changes will occur during this run of config migration
```bash
python3 deployment_plan.py
/usr/local/bin/python3.9 /Users/nitin.bs/PycharmProjects/cicd/customer_cicd_poc/deployment_plan.py
Infoworks source RDBMS_SQLServer will be created/updated.Tables and Table groups under it will be configured based on below changes.
Changed data_lake_schema: from public to PUBLIC_PRD
Changed data_lake_schema: from public_cicd_rdbms_demo to PUBLIC_PRD_RDBMS_DEMO
Changed data_lake_schema: from rdbms_sqlserver_schema to PRD_RDBMS_SQLSERVER_SCHEMA
Changed target_database_name: from csv_automated_att_new to CSV_AUTOMATED_ATT_PRD
Changed target_database_name: from cicd_rdbms_demo to PRD_RDBMS_DEMO
Changed target_database_name: from rdbms_sqlserver to PRD_RDBMS_SQLSERVER
Changed staging_schema_name: from rdbms_sqlserver_schema_stg to PRD_RDBMS_SQLSERVER_SCHEMA_STG
Changed secret_name: from dummy-secret to mongo-pg-pwd
Changed warehouse: from test_wh to DEMO_WH
Infoworks pipeline pipeline1 will be created/updated under sf_domain based on below changes.
Changed database_name: from test_database to PRD_DATABASE
Changed database_name: from testcicdpipeline321 to PRDCICDPIPELINE321
Changed schema_name: from testcicdpipelineschema321 to PRD_CICDPIPELINESCHEMA321
Changed query_tag: from dev to prd
Changed value: from support_db to PRD_DB
```
### Finally commit the changes with the desired commit message and push the code to the preprod/prod branch.
```bash
git commit -m "initial CI/CD commit"
git push origin prod
```
### If running from a local VM, run the below command. This script is responsible for importing the artifact on the target machine whose details are present in config.ini.
```bash
cd $GITHUB_WORKSPACE;
chmod +x main.py;
python3 main.py --config_ini_file <path to config.ini file>
```
# Authors
Nitin BS - nitin.bs@infoworks.io
Abhishek Raviprasad - abhishek.raviprasad@infoworks.io |
import { useState } from "react";
import { StackingClient } from "@stacks/stacking";
import { Form, Formik } from "formik";
import { useNavigate } from "react-router-dom";
import { ErrorAlert } from "@components/error-alert";
import { useNetwork } from "@components/network-provider";
import {
useGetAccountBalance,
useGetPoxInfoQuery,
useGetSecondsUntilNextCycleQuery,
useStackingClient,
} from "@components/stacking-client-provider/stacking-client-provider";
import { STACKING_CONTRACT_CALL_TX_BYTES } from "@constants/app";
import { useCalculateFee } from "@hooks/use-calculate-fee";
import { StartStackingLayout } from "../components/stacking-layout";
import { Amount } from "./components/choose-amount";
import { ConfirmAndSubmit } from "./components/confirm-and-submit";
import { InfoPanel } from "./components/direct-stacking-info-card/direct-stacking-info-card";
import { DirectStackingIntro } from "./components/direct-stacking-intro";
import { Duration } from "./components/duration";
import { PoxAddress } from "./components/pox-address/pox-address";
import { DirectStackingFormValues } from "./types";
import { createHandleSubmit, createValidationSchema } from "./utils";
import { Spinner } from "@stacks/ui";
import { StackingFormInfoPanel } from "../components/stacking-form-info-panel";
import { StackingFormContainer } from "../components/stacking-form-container";
const initialFormValues: DirectStackingFormValues = {
amount: "",
lockPeriod: 12,
poxAddress: "",
};
export function StartDirectStacking() {
const { client } = useStackingClient();
if (!client) {
const msg = "Expected `client` to be defined.";
const id = "32bd8efa-c6cb-4d1c-8f92-f39cd7f3cd74";
console.error(msg);
return <ErrorAlert id={id}>{msg}</ErrorAlert>;
}
return <StartDirectStackingLayout client={client} />;
}
interface StartDirectStackingLayoutProps {
client: StackingClient;
}
function StartDirectStackingLayout({ client }: StartDirectStackingLayoutProps) {
const [isContractCallExtensionPageOpen, setIsContractCallExtensionPageOpen] =
useState(false);
const { networkName } = useNetwork();
const getSecondsUntilNextCycleQuery = useGetSecondsUntilNextCycleQuery();
const getPoxInfoQuery = useGetPoxInfoQuery();
const getAccountBalanceQuery = useGetAccountBalance();
const navigate = useNavigate();
const calcFee = useCalculateFee();
const transactionFeeUStx = calcFee(STACKING_CONTRACT_CALL_TX_BYTES);
if (
getSecondsUntilNextCycleQuery.isLoading ||
getPoxInfoQuery.isLoading ||
getAccountBalanceQuery.isLoading
)
return <Spinner />;
if (
getSecondsUntilNextCycleQuery.isError ||
typeof getSecondsUntilNextCycleQuery.data !== "number" ||
getPoxInfoQuery.isError ||
!getPoxInfoQuery.data ||
getAccountBalanceQuery.isError ||
typeof getAccountBalanceQuery.data !== "bigint"
) {
const msg = "Failed to load necessary data.";
const id = "8c12f6b2-c839-4813-8471-b0fd542b845f";
console.error(id, msg);
return <ErrorAlert id={id}>{msg}</ErrorAlert>;
}
const validationSchema = createValidationSchema({
minimumAmountUStx: BigInt(getPoxInfoQuery.data.min_amount_ustx),
transactionFeeUStx,
availableBalanceUStx: getAccountBalanceQuery.data,
network: networkName,
});
const handleSubmit = createHandleSubmit({
client,
navigate,
setIsContractCallExtensionPageOpen,
});
return (
<Formik
initialValues={initialFormValues}
onSubmit={(values) => {
handleSubmit(values);
}}
validationSchema={validationSchema}
>
<StartStackingLayout
intro={
<DirectStackingIntro
estimatedStackingMinimum={BigInt(
getPoxInfoQuery.data.min_amount_ustx
)}
timeUntilNextCycle={getSecondsUntilNextCycleQuery.data}
/>
}
stackingInfoPanel={
<>
<StackingFormInfoPanel>
<InfoPanel />
</StackingFormInfoPanel>
</>
}
stackingForm={
<Form>
<StackingFormContainer>
<Amount />
<Duration />
<PoxAddress />
<ConfirmAndSubmit isLoading={isContractCallExtensionPageOpen} />
</StackingFormContainer>
</Form>
}
/>
</Formik>
);
} |
<% if user_signed_in? %>
<table class="table table-striped table-bordered table-hover" >
<thead class="table-dark">
<tr>
<th>Name</th>
<th>Phone</th>
<th>Email</th>
<th>Twitter</th>
<%# <th>User Id</th> %>
<%# <th>Show</th> %>
<%# <th>Edit</th> %>
<th></th>
<%# <th>Delete</th> %>
</tr>
</thead>
<tbody>
<% @friends.each do |friend| %>
<%# make friends lists private %>
<% if friend.user == current_user %>
<tr class="align-middle">
<td><%= link_to friend.first_name + ' ' + friend.last_name, friend, style:"text-decoration: none; color: #0e6ecd; font-weight: 600;" %></td>
<td><%= friend.phone %></td>
<td><%= friend.twitter %></td>
<td><%= friend.email %></td>
<%# <td><%= friend.user_id %><%#</td> %>
<%# <td><%= link_to "Show", friend %><%#</td> %>
<%# <td><%= link_to "Edit", edit_friend_path(friend) %><%#</td> %>
<%# deletion confirmation %>
<td><%= button_to "Delete", friend, class:"btn btn-outline-danger btn-sm", method: :delete, onclick:"return confirm('Delete entry?')" %></td>
<%# <td><%= button_to "Delete", friend, method: :delete, class:"btn btn-outline-danger btn-sm" %> <%# </td> %>
</tr>
<% end %>
<%# <%= render "friend" %>
<%# <p>
<%= link_to "Show this friend", friend %>
<%# </p> %>
<% end %>
</tbody>
</table>
<%= link_to "Add Friend", new_friend_path, class:"btn btn-primary" %>
<%# For Signed Out Users, a very basic alternate home page %>
<% else %>
<h1>Friend App</h1>
<p>This is my first rails webpage</p>
<% end %> |
@extends('back.parent.layout')
@section('breadcrumb')
@include('back.parent.partial.breadcrumb', [
'parent' => 'Parametres',
'parent_route' => '#',
'child' => 'Configurations',
])
@endsection
@section('css')
<style>
#holder img {
height: 100%;
width: 100%;
}
</style>
@endsection
@section('main')
<form
method="post"
action="{{ route('configuration.update') }}" enctype="multipart/form-data">
@method('PUT')
@csrf
<div class="row">
<div class="col-md-8">
<x-back.validation-errors :errors="$errors" />
@if(session('ok'))
<x-back.alert
type='success'
title="{!! session('ok') !!}">
</x-back.alert>
@endif
<x-back.card
type='primary'
title='Configuration'>
<x-back.input
name='nom_directeur'
title='Nom de Directeur'
:value="getConfiguration('nom_directeur')"
input='text'
:required="true">
</x-back.input>
<x-back.input
name='mot_directeur'
title='Mot de Directeur'
:value="getConfiguration('mot_directeur')"
input='textarea'
rows=10
:required="false">
</x-back.input>
<button type="submit" class="btn btn-primary">Valider</button>
</x-back.card>
</div>
<div class="col-md-4">
{{-- Upload --}}
<x-back.card
id="photo_upload"
type='primary'
:outline="false"
title='Photo Upload'>
<div class="form-group{{ $errors->has('image_directeur') ? ' is-invalid' : '' }}">
<label for="changeImage">Image</label>
@if(getConfiguration('image_directeur') && !$errors->has('image_directeur'))
<div>
<p>
@if(getConfiguration('image_directeur'))
<img src="{{ getImageSingle(getConfiguration('image_directeur'), true) }}" style="width:100%;">
@else
<img src="{{ asset('/default.png') }}" style="width:100%;">
@endif
</p>
<button type="button" id="changeImage" class="btn btn-warning"
data-update="@if(getConfiguration('image_directeur')) show @endif">
Changer d'image</button>
</div>
@endif
<div id="wrapper" class="@if(getConfiguration('image_directeur')) d-none @endif">
{{--@if(!isset($formation) || $errors->has('photo'))--}}
<div class="custom-file">
<input type="file" id="image_upload" name="image_directeur"
class="{{ $errors->has('image_directeur') ? ' is-invalid ' : '' }} custom-file-input"
value="{{ old('image_directeur', getConfiguration('image_directeur') != null ? getConfiguration('image_directeur') : '') }}">
<label class="custom-file-label" for="image_upload"></label>
<div class="text-center my-1 py-2" style="margin-bottom:15px;">
<label class="label" for="image_upload">
<img id="previewImg" class="m-2" style="width:100%; cursor: pointer;" src=""
{{--src="{{ getImage($formation, true) }}" --}}
alt="">
</label>
</div>
<div class="row justify-content-center">
<button type="button" id="btn-delete-image" class="btn btn-outline-danger d-none">Supprimer</button>
</div>
@if ($errors->has('image_directeur'))
<div class="invalid-feedback">
{{ $errors->first('image_directeur') }}
</div>
@endif
</div>
{{--@endif--}}
</div>
</div>
</x-back.card>
</div>
</div>
</form>
@endsection
@section('js')
<script>
$(document).ready(() => {
console.log($('#image_upload').attr('value'))
if ($('#image_upload').attr('value') != '') {
$('#image_upload').next('.custom-file-label').text($('#image_upload').attr('value'))
console.log('COndition FIle', $('#image_upload').attr('value'))
}
$('form').on('change', '#image_upload', e => {
$(e.currentTarget).next('.custom-file-label').text(e.target.files[0].name);
previewFile(e.currentTarget)
});
$('#changeImage').click(e => {
$(e.currentTarget).parent().hide();
/*console.log($(e.currentTarget), 'changeImage data-update',
$(e.currentTarget).data("update"))*/
let show = $.trim($(e.currentTarget).data("update"))
if ( show === 'show')
{
$('#wrapper').removeClass('d-none')
// $("label[for='image_upload']").click()
$('.label').click()
console.log('changeImage open')
}
});
$('#btn-delete-image').click(e => {
$('#previewImg').attr("src", '#')
$('#photo_upload').css("height", "223px")
$('#previewImg').css("height", "0px")
$(e.currentTarget).addClass('d-none')
$('.custom-file-label').text('')
})
});
function previewFile(input){
let file = $(input).get(0).files[0]
if(file){
let reader = new FileReader()
reader.onload = function(){
$('#previewImg').attr("src", reader.result)
$('#previewImg').css("height", "300px")
$('#photo_upload').css("height", "600px")
$('#btn-delete-image').removeClass('d-none')
// console.log($("#previewImg").attr("src"))
}
reader.readAsDataURL(file)
}
}
</script>
@endsection |
import { MagnifyingGlassIcon } from '@heroicons/react/24/outline';
import { PencilIcon, UserPlusIcon } from '@heroicons/react/24/solid';
import {
Card,
CardHeader,
Input,
Typography,
Button,
CardBody,
Chip,
CardFooter,
Tabs,
TabsHeader,
Tab,
Avatar,
IconButton,
Tooltip,
} from '@material-tailwind/react';
import React, { useState, useEffect } from 'react';
import userApi from '@/api/userApi';
import Pagination from '@/components/pagination/index.jsx';
const TABS = [
{
label: 'All',
value: 'all',
},
{
label: 'Monitored',
value: 'monitored',
},
{
label: 'Unmonitored',
value: 'unmonitored',
},
];
const TABLE_HEAD = ['Member', 'Function', 'Status', 'Employed', ''];
const TABLE_ROWS = [
{
img: 'https://demos.creative-tim.com/test/corporate-ui-dashboard/assets/img/team-3.jpg',
name: 'John Michael',
email: 'john@creative-tim.com',
job: 'Manager',
org: 'Organization',
online: true,
date: '23/04/18',
},
{
img: 'https://demos.creative-tim.com/test/corporate-ui-dashboard/assets/img/team-2.jpg',
name: 'Alexa Liras',
email: 'alexa@creative-tim.com',
job: 'Programator',
org: 'Developer',
online: false,
date: '23/04/18',
},
{
img: 'https://demos.creative-tim.com/test/corporate-ui-dashboard/assets/img/team-1.jpg',
name: 'Laurent Perrier',
email: 'laurent@creative-tim.com',
job: 'Executive',
org: 'Projects',
online: false,
date: '19/09/17',
},
{
img: 'https://demos.creative-tim.com/test/corporate-ui-dashboard/assets/img/team-4.jpg',
name: 'Michael Levi',
email: 'michael@creative-tim.com',
job: 'Programator',
org: 'Developer',
online: true,
date: '24/12/08',
},
{
img: 'https://demos.creative-tim.com/test/corporate-ui-dashboard/assets/img/team-5.jpg',
name: 'Richard Gran',
email: 'richard@creative-tim.com',
job: 'Manager',
org: 'Executive',
online: false,
date: '04/10/21',
},
];
export function CustomerTable() {
const [userList, setUserList] = useState([]);
const [page, setOffset] = useState(0);
const [limit] = useState(5);
const [currentPage, setCurrentPage] = useState(0);
const [pageCount, setPageCount] = useState(0);
const [isloaded, setIsLoaded] = useState(false);
const [searchText, setSearchText] = useState('');
useEffect(() => {
getAllUser();
}, [page, limit]);
const getAllUser = async () => {
setIsLoaded(false);
var dto = { page, limit };
if (searchText) {
dto.search = searchText;
}
console.log('dto', dto);
const response = await userApi.GetAllUser(dto);
setPageCount(Math.ceil(response?.totalRecord / limit));
setUserList(response?.data);
setIsLoaded(true);
};
console.log(userList);
const handlePageClick = (e) => {
setCurrentPage(e.selected);
setOffset(e.selected);
};
return (
<div>
<Card className="mt-10 mb-10 h-full w-full">
<CardHeader floated={false} shadow={false} className="rounded-none">
<div className="mb-2 flex items-center justify-between gap-8">
<div>
<Typography variant="h5" color="blue-gray">
Members list
</Typography>
</div>
<div>
<Input label="Search" icon={<MagnifyingGlassIcon className="h-5 w-5" />} />
</div>
</div>
<div className="flex flex-col items-center justify-between gap-4 md:flex-row">
<div className="w-full md:w-72"></div>
{/* <div className="flex shrink-0 flex-col gap-2 sm:flex-row">
<Button variant="outlined" size="sm">
view all
</Button>
<Button className="flex items-center gap-3" size="sm">
<UserPlusIcon strokeWidth={2} className="h-4 w-4" /> Add member
</Button>
</div> */}
</div>
</CardHeader>
<CardBody className="overflow-scroll px-0">
<table className="mt-4 w-full min-w-max table-auto text-left">
<thead>
<tr className="hover:bg-gray-100 transition-colors">
{TABLE_HEAD.map((head) => (
<th key={head} className="border-y border-blue-gray-100 bg-blue-gray-50/50 p-4">
<Typography
variant="small"
color="blue-gray"
className=" leading-none text-[11px] font-bold uppercase text-blue-gray-400"
>
{head}
</Typography>
</th>
))}
</tr>
</thead>
<tbody>
{userList?.map((item) => (
<tr key={item.userId} className="hover:bg-gray-100 transition-colors">
<td className="p-4 border-b border-blue-gray-50">
<div className="flex items-center gap-3">
<Avatar src={item.avatar} size="sm" />
<div className="flex flex-col">
<Typography variant="small" color="blue-gray" className="font-normal">
{item.name}
</Typography>
<Typography variant="small" color="blue-gray" className="font-normal opacity-70">
{item.email}
</Typography>
</div>
</div>
</td>
<td className="p-4 border-b border-blue-gray-50">
<div className="flex flex-col">
<Typography variant="small" color="blue-gray" className="font-normal">
{'job'}
</Typography>
<Typography variant="small" color="blue-gray" className="font-normal opacity-70">
{'org'}
</Typography>
</div>
</td>
<td className="p-4 border-b border-blue-gray-50">
<div className="w-max">
{/* <Chip
variant="ghost"
size="sm"
value={online ? 'online' : 'offline'}
color={online ? 'green' : 'blue-gray'}
/> */}
</div>
</td>
<td className="p-4 border-b border-blue-gray-50">
<Typography variant="small" color="blue-gray" className="font-normal">
{'date'}
</Typography>
</td>
<td className="p-4 border-b border-blue-gray-50">
<Tooltip content="Edit User">
<IconButton variant="text">
<PencilIcon className="h-4 w-4" />
</IconButton>
</Tooltip>
</td>
</tr>
))}
</tbody>
</table>
</CardBody>
</Card>
<Pagination handlePageClick={handlePageClick} currentPage={currentPage} pageCount={pageCount} />
</div>
);
}
export default CustomerTable; |
from models import db, Commodity, CommodityPrice
from app import app
app.app_context().push()
import requests
import json
import os
from datetime import datetime
from flask_sqlalchemy import SQLAlchemy
base_currency = 'EUR'
endpoint = 'timeseries'
symbols = 'POTATOES'
todaysDate = '2023-03-09'
aYearAgo = '2023-01-09'
access_key_1 = os.environ.get('COMMODITIES_API_KEY_1')
access_key_2 = os.environ.get('COMMODITIES_API_KEY_2')
api_url = 'https://commodities-api.com/api/'+endpoint+'?access_key='+access_key_2+'&start_date='+aYearAgo+'&end_date='+todaysDate+'&base='+base_currency+'&symbols='+symbols
# Get the list of commodities from the API
response = requests.get(api_url)
commodities = json.loads(response.text)
#print(commodities)
#print(json.dumps(commodities, indent=4))
commodity_prices = commodities['data']['rates']
# pretty print the commodities to the console
#print(json.dumps(commodities, indent=4))
# iterate over the commodity prices and add them to the database
"""
the format of the data looks like this:
"rates": {
"2023-02-09": {
"POTATOES": 0.033444816053511635
},
"2023-02-11": {
"POTATOES": 0.03389830508474538
},
}
"""
for date, commodity in commodity_prices.items():
print(date, commodity['POTATOES'])
# get the commodity id from the database by using the commodity symbol
commodity_id = Commodity.query.filter_by(symbol='POTATOES').first().id
# add the latest price to the database
commodity_price = commodity['POTATOES']
# convert the date to a datetime object
date = datetime.strptime(date, '%Y-%m-%d')
# calculate the price
commodity_price = 1/commodity_price
db.session.add(CommodityPrice(commodity_id=commodity_id, price=commodity_price, currency=base_currency, date_created=date))
# Commit the changes to the database
db.session.commit() |
import { useState } from "react";
import Message from "./Message";
import InputEmoji from "react-input-emoji";
import {
selectHMSMessages,
useHMSActions,
useHMSStore,
} from "@100mslive/react-sdk";
import { selectPeers } from "@100mslive/react-sdk";
import { IoMdChatboxes } from "react-icons/io";
import {FaUsers} from 'react-icons/fa'
function ChatNdParticipants() {
const [selectedOption, setSelectedOption] = useState("chat");
const [message, setMessage] = useState("");
const messages = useHMSStore(selectHMSMessages);
const hmsActions = useHMSActions();
const peers = useHMSStore(selectPeers);
const [text, setText] = useState("");
function handleOnEnter(text) {
console.log("enter", text);
}
const handleSubmit = (e) => {
// e.preventDefault();
hmsActions.sendBroadcastMessage(message);
setMessage("");
};
return (
<div className="rightBox">
<div className="rightBox__head">
<span
onClick={() => setSelectedOption("chat")}
className={selectedOption === "chat" ? "selected" : ""}>
Chat <IoMdChatboxes/>
</span>
<span
className={selectedOption === "participants" ? "selected" : ""}
onClick={() => setSelectedOption("participants")}
>
Participants <FaUsers/>
</span>
</div>
<div className="rightBox__optionView">
{selectedOption === "chat" && (
<>
<div className="rightBox__chats">
{/* Messages */}
{messages.map((msg) => (
<Message key={msg.id} message={msg} />
))}
</div>
<div className="inputEmoji">
<InputEmoji
value={message}
onChange={setMessage}
cleanOnEnter
onEnter={handleSubmit}
placeholder="Type a message"
/>
</div>
</>
)}
{selectedOption === "participants" && (
<div className="rightBox__participants">
{/* Participants */}
{peers.map((peer) => (
<>
<span className="rightBox__participant_role">{peer.roleName}</span>
<div className="rightBox__participant">{peer.name}</div>
</>
))}
</div>
)}
</div>
</div>
);
}
export default ChatNdParticipants; |
.. Khungulanga Backend API Documentation
Overview
--------
The Khungulanga backend API serves as the server-side component for the Khungulanga mobile application. It provides the necessary functionality for early diagnosis of skin diseases using the ResNet50v2 architecture. The API allows users to interact with the machine learning models, store diagnostic history, and connect with dermatologists for further analysis.
Getting Started
---------------
To get started with the Khungulanga backend API, follow these steps:
1. Install Dependencies
- Make sure you have Python and Django installed on your system.
- Create a virtual environment and activate it.
2. Clone the Repository
- Clone the Khungulanga backend repository from the Git repository.
```
git clone https://github.com/jahnical/khungulanga.git
```
3. Install Requirements
- Navigate to the project directory and install the required Python packages using pip.
```
cd khungulanga-backend
pip install -r requirements.txt
```
4. Configure the Database
- Open the settings.py file and configure the database settings according to your setup.
5. Migrate Database
- Run the migration command to create the necessary database tables.
```
python manage.py migrate
```
6. Start the Development Server
- Start the development server to run the API locally.
```
python manage.py runserver 8000
```
7. Access the API
- The API will be accessible at `http://localhost:8000`.
API Endpoints
-------------
The following endpoints are available in the Khungulanga backend API:
- `/api/diagnosis/`: Endpoint for diagnosing skin diseases.
- `/api/history/`: Endpoint for managing diagnostic history.
- `/api/users/`: Endpoint for managing user accounts.
- `/api/dermatologists/`: Endpoint for managing dermatologist profiles.
Refer to the API documentation for detailed information on each endpoint.
Indices and Tables
------------------
The following indices and tables provide quick access to different sections of the documentation:
* :ref:`genindex`: General Index
* :ref:`modindex`: Module Index
* :ref:`search`: Search |
<template>
<div>
<div class="mb-4">
<FiltersMenu
:group-by="groupByOptions"
:filter-by="filterOptions"
@searchStringChange="searchString = $event"
@filtersChange="onFiltersChange"
@groupByChange="groupBy = $event"
@reset="onFiltersReset" />
</div>
<div class="mb-4">
<Button
type="save"
@click="showCreationModal = true">
<span>Create new Risk</span>
</Button>
<RiskCreationModal
:show="showCreationModal"
@created="onRiskCreate"
@cancel="showCreationModal = false"/>
</div>
<div>
<LoadingIndicator v-if="loading"/>
<div
v-else
class="relative">
<div v-if="!groupBy">
<ItemsList
v-if="filteredRisks.length"
:items="filteredRisks"
:items-type="ObjectTypes.RISK" />
<div
v-else
class="text-2xl font-semibold italic text-center">
No search result
</div>
</div>
<div v-else>
<div
v-for="(group, idx) in filteredAndGroupedRisks"
:key="idx"
:style="{backgroundColor: group.color ? `${group.color}35` : ''}"
class="p-4 mb-2">
<p
class="text-xl font-semibold mb-3 sticky top-0"
:style="{color: group.color || ''}">
{{ group.title }}
</p>
<ItemsList
v-if="group.items.length"
:items="group.items"
:items-type="ObjectTypes.RISK" />
<div
v-else
class="text-2xl font-semibold italic text-center">
No search result
</div>
</div>
</div>
</div>
</div>
</div>
</template>
<script>
import { mapGetters } from 'vuex';
import { getCurrentPeriod } from '../../../api/risks/periods';
import { getRisks } from '../../../api/risks';
import ItemsList from '../../Molecules/Items/ItemsList.vue';
import LoadingIndicator from '../../Atoms/LoadingIndicator.vue';
import Button from '../../Atoms/Button.vue';
import RiskCreationModal from '../../Molecules/Modals/RiskCreationModal.vue';
import Notification from '../../Atoms/Notification.vue';
import FiltersMenu from '../../Molecules/FiltersMenu.vue';
import { ObjectTypes } from '../../../constants/ObjectTypes';
import { Group } from '../../../constants';
import { filtersMixin } from '../../../mixins/filtersMixin';
export default {
components: {
ItemsList,
LoadingIndicator,
Button,
RiskCreationModal,
Notification,
FiltersMenu
},
mixins: [filtersMixin],
data() {
return {
loading: false,
showCreationModal: false,
risks: [],
currentPeriod: null,
ObjectTypes,
Group
};
},
computed: {
...mapGetters(['allUsers', 'riskUsers']),
filteredAndGroupedRisks() {
if (!this.groupBy) return this.filteredRisks;
let result = [{
id: 'out_of_any_group',
title: 'Out of any group',
color: '#676e7a',
items: []
}];
if (this.groupBy === Group.RESPONSIBLE) {
this.filteredRisks.forEach(risk => {
if (!risk.responsibleIds?.length) {
result[0].items.push(risk);
return;
};
risk.responsibleIds.forEach(responsibleId => {
let responsible = this.allUsers.find(user => user.id === responsibleId);
let groupIdx = result.findIndex(group => group.id === responsibleId);
if (groupIdx !== -1) {
result[groupIdx].items.push(risk);
} else {
result.push({
id: responsibleId,
title: responsible.full_name,
items: [risk]
});
}
});
});
}
if (this.groupBy === Group.ASSESSMENT) {
this.currentPeriod.assessment.forEach(assessmenRow => {
result.push({
...assessmenRow,
items: []
});
});
this.filteredRisks.forEach(risk => {
if (!risk.assessmentGroup || risk.assessmentGroup === -1) {
result[0].items.push(risk);
return;
};
let groupIdx = result.findIndex(group => group.id === risk.assessmentGroup);
result[groupIdx] && result[groupIdx].items.push(risk);
});
}
return result;
},
filteredRisks() {
let result = this.risks;
if (this.searchString) {
result = result.filter(risk => {
return risk.title.toLowerCase().includes(this.searchString.toLowerCase());
});
}
if (this.selectedFilters[Group.RESPONSIBLE]?.length) {
result = result.filter(risk => risk.responsibleIds.some(id => {
return this.selectedFilters[Group.RESPONSIBLE].includes(id);
}));
}
return result;
},
groupByOptions() {
return [{
value: Group.ASSESSMENT,
label: 'Risk assessment'
}, {
value: Group.RESPONSIBLE,
label: 'Risk responsible'
}];
},
filterOptions() {
return [{
groupId: Group.RESPONSIBLE,
groupTitle: 'Responsibles',
items: this.riskUsers.map(user => ({
value: user.id,
label: user.full_name
}))
}];
},
},
beforeMount() {
this.loading = true;
let promises = [
this.getRisks(),
this.getCurrentPeriod()
];
return Promise.all(promises)
.finally(() => {
this.loading = false;
});
},
methods: {
getRisks() {
return getRisks()
.then(({list}) => {
this.risks = list;
});
},
getCurrentPeriod() {
return getCurrentPeriod()
.then(period => {
this.currentPeriod = period;
});
},
onRiskCreate(newRisk) {
this.risks.push(newRisk);
this.showCreationModal = false;
},
},
};
</script> |
# Contribution Guidelines 🙌
This documentation contains a set of guidelines to help you during the contribution process of this project. I'm happy to welcome all the contributions from anyone willing to add new scripts to this repository. Thank you for helping out and remember, No contribution is too small.
## Steps To Follow Before You Contribute 🛠️
Please make sure you follow this guidelines so your code can be merged as quickly as possible
1. On the [GitHub page for this repository,]('https://github.com/blossom-babs/remote-global') click on the Button "Fork".

2. Clone your forked project to your local computer

- for example, run this command inside your terminal:
```bash
git clone https://github.com/<your-github-username>/remote-global.git
```
3. Shift into project folder
```bash
cd path to project folder
```
4. Before you make any changes, keep your fork in sync to avoid merge conflicts:
```bash
git remote add upstream https://github.com/blossom-babs/remote-global.git
git pull upstream main
```
5. After adding the upstream and checking that all files are up to date, create new branch before fixing or editing any files.
```bash
git checkout -b <branch-name>
```
6. Done fixing any issue ? Add the changes with git add, git commit (write a good commit message, if possible):
```bash
git add file or files
git commit -m "descriptive message"
```
7. Push your changes to your repository and make a pull request:
```bash
git push origin <branch-name>
```
8. Create a pull request on the [GitHub page for this repository,]('https://github.com/blossom-babs/remote-global')

## Styles Guidelines 🎨
1. Every page and component should have a corresponding and independent stylesheet in the _`styles`_ folder
2. Files in the component folder should have a corresponding test script writing with jest testing library
3. Files in the pages folder should have a corresponding test script writing with cypress e2e testing |
<template>
<div class="theme-picker">
<button
v-for="(item, index) in options"
:key="index"
:class="item.active ? '-active' : ''"
:aria-pressed="item.active"
@click="setTheme(item.id)"
>{{ item.name }}</button>
</div>
</template>
<script>
export default {
name: 'ThemePicker',
props: {
theme: String
},
computed: {
options() {
return [
{
id: 'light',
name: 'Light',
active: this.theme == 'light'
},
{
id: 'dark',
name: 'Dark',
active: this.theme == 'dark'
}
]
}
},
methods: {
setTheme(value) {
var newValue = value;
if(value == this.theme) {
newValue = this.theme == 'light' ? 'dark' : 'light';
}
this.$emit('setTheme', newValue);
}
}
}
</script>
<style lang="scss" scoped>
@import "../scss/variables.scss";
@import "../scss/mixins.scss";
@import "../scss/animations.scss";
.theme-picker {
border-left: $borderWidth solid rgba(var(--frontRGB), var(--borderOpacity));
button {
appearance: none;
background: transparent;
border-width: 0;
@include r('font-size', 15, 18);
height: 60px;
color: rgba(var(--frontRGB), 0.55);
transition: color 100ms $ease;
&:focus {
outline: none;
}
&:hover {
color: $primary;
}
&.-active {
color: var(--front);
}
}
@include media-query(small) {
flex-grow: 1;
display: flex;
button {
flex-grow: 1;
padding: 0 0 0 5px;
&:last-child {
padding: 0 5px 0 0;
}
}
}
@include media-query(medium-up) {
button {
padding: 0 5px 0 20px;
&:last-child {
padding: 0 20px 0 5px;
}
}
}
}
.--theme-dark {
.theme-picker {
border-color: rgba(var(--frontRGB), var(--borderOpacity));
}
}
</style> |
import { Body, Controller, Delete, Get, HttpCode, Param, Post, Put, UseInterceptors } from '@nestjs/common';
import { plainToInstance } from 'class-transformer';
import { BusinessErrorsInterceptor } from '../shared/interceptors/business-errors/business-errors.interceptor';
import { AlbumService } from './album.service';
import { AlbumDto } from './album.dto/album.dto';
import { AlbumEntity } from './album.entity/album.entity';
@Controller('albums')
@UseInterceptors(BusinessErrorsInterceptor)
export class AlbumController {
constructor(private readonly albumService: AlbumService) {}
@Get(':albumId')
async findOne(@Param('albumId') albumId: string) {
return await this.albumService.findAlbumById(albumId);
}
@Post()
async create(@Body() albumDto: AlbumDto) {
const album: AlbumEntity = plainToInstance(AlbumEntity, albumDto);
return await this.albumService.createAlbum(album);
}
@Delete(':albumId')
@HttpCode(204)
async delete(@Param('albumId') albumId: string) {
return await this.albumService.deleteAlbum(albumId); // Changed 'museumService' to 'aerolineaService'
}
} |
---
title: "Competition_Forecast_RMD"
author: "Nannaphat Sirison, Lynn Wu"
date: "2023-04-03"
output:
pdf_document: default
html_document: default
---
## INTRODUCTION
```{r}
knitr::opts_chunk$set(warning = FALSE, message = FALSE)
#Installing required packages
library(lubridate)
library(ggplot2)
library(forecast)
library(Kendall)
library(tseries)
library(outliers)
library(tidyverse)
library(smooth)
library(kableExtra)
library(readxl)
library(zoo)
library(openxlsx)
library(writexl)
```
This project aims to utilize time series forecasting tools to model daily load demand. As population increases, and as renewable energy penetration increases, it is important to develop models that help forecast load that can help utilities understand load patterns and long term trends in load. This can help utilities plan for how much generation and capacity they can should be procuring to make sure that load is appropriately met.
This project aims to find a suitable model that best forecasts daily load. The methodology/ steps that we implemented is as follows:
> (1) Examine and explore the dataset for any initial trends
(2) Perform initial analysis of the time series using ACF and PACF plots, and decompositions of time series.
(3) Train 4 different models to the time series and examine performance against observed data
(4) Calculate performance metrics for each of the 4 models and chose the best model for a future forecast
(5) Generated a 5 month future forecast using the best chosen model
## ABOUT THE DATA
The dataset we are working in provides hourly data from January 1, 2005 to December 31,2010. We have aggregated hourly data into daily data, by taking the average across 24 hours of each day.
```{r}
#Loading in the data set
df<-read_excel("load.xlsx")
```
```{r}
#DATA WRANGLING
#Taking the average across hours of the day
df$hourly_mean <- rowMeans(df[,3:26])
#Selecting only necessary columns: data and hourly mean
df <- df[, c("date","hourly_mean")]
#Making date column a date format
df$date <- ymd(df$date)
```
```{r}
#Drop NAs
df1 <- df %>% drop_na()
#Converting to time series object (2005.1.1-2010.12.31)
ts <- msts(df1[,2], seasonal.periods = c(7,365.25),start=c(2005,01,01),end=c(2010,12,31))
```
A plot of the dataset we are working with is shown, below with a table of summary statistics.
```{r, echo= TRUE}
#Initial plot of time series
ts_plot<-ggplot(df1,aes(x=date, y=hourly_mean))+
geom_line()+
labs(y="Load", x= "Year", title="Daily Load (averaged across hours)")+
theme_minimal()
plot(ts_plot)
```
```{r, echo = TRUE}
#Summary of time series
ts_summary<-summary(ts)
ts_summary
```
In the plot above, we see that across the time series we there are obvious fluctuations/ oscillations. These fluctuations are not surprising; it is a common for load to vary based on seasons and time of day, for example, higher load is expected during summer time than spring time. We also observe an overall increasing trend, which is expected as energy intensity increases and population increases.
Based on the historical data set we are using, observed minimum load is at 1525, and maximum load is at 7545. Mean load is 3329 and median load is 3182.
## INITIAL TIME SERIES ANALYSIS
Before running a time series forecast model, we prepare and transform the data to fit the needs of time series forecasting. Before selecting models for time series forecasting, we examine ACF and PACF plots of the original, un-transformed time series (shown below).
```{r, echo=TRUE}
#Original Series: ACF and PACF Plots
par(mfrow=c(1,2))
ACF_Plot <- Acf(ts, lag = 40, plot = TRUE,main="ACF of Hourly Mean")
PACF_Plot <- Pacf(ts, lag = 40,plot = TRUE,main="PACF of Hourly Mean")
```
>Plots not only show strong seasonality but also non-stationarity due to the slow decay.
We then examine the decomposition of the original time series to identify seasonality and trend. Decomposition of the time series is displayed below:
```{r, echo=TRUE}
#Original Series: Decomposition
ts %>% mstl() %>%
autoplot()
```
>The trend has a narrow range compared to seasonal components. Both weekly and yearly pattern have strong scales and trend components in daily data.
After performing initial data exploration of aggregated (daily) data, we examine 4 forecasting models. Each model used training data from January 1, 2015 to December 21, 2019, and was compared to test data from January 1st,2020 to December 31st,2020 to check for accuracy.
##FORECASTING DAILY LOAD
```{r, message=FALSE, warning=FALSE}
#create a subset for training purpose (2005-2009)
n_for = 365
ts_train <- subset(ts,end = length(ts)-n_for)
#create a subset for testing purpose (2009-2010)
ts_test <- subset(ts, start = length(ts)-n_for)
autoplot(ts_train)
autoplot(ts_test)
```
#Model 1: STL + ETS
Our first forecasting model applies a non-seasonal exponential smoothing model to all seasonally adjusted data.
```{r, echo=TRUE, message=FALSE, warning=FALSE}
#Fit and forecast STL + ETS model to data
ETS_fit <- stlf(ts_train,h=365)
```
```{r, echo = TRUE}
#Plot model + observed data
autoplot(ts) +
autolayer(ETS_fit, series="STL + ETS",PI=FALSE) +
ylab("Daily Load")+
labs(title= "STL+ETS vs. Observed")
```
We observe that that the STL+ETS model follows the seasonality well (as observed by the coincidental oscillation of the red and black series); however, the magnitude of the forecast does not fit the data we observe well. Forecasted data has a greater magnitude than the observed data when the time series is at its peak but a lower magnitude than observed data when the time series is at its minimum. f.
```{r}
#WRANGLING FOR KAGGLE SUBMISSION
#Generate 2011 output for Kaggle competition
ETS_fit_kaggle <- stlf(ts,h=59)
#Save ETS_fit_kaggle as a dataframe
ETS_fit_kaggle_df <- as.data.frame(ETS_fit_kaggle$mean)
#Read in submission template
submission_template<-read_excel("submission_template.xlsx")
#Merge df
submission_template_ETS <- cbind(submission_template,ETS_fit_kaggle_df)
#Remove extra column
submission_template_ETS <- submission_template_ETS[, c("date","x")]
#Rename column from "x" to "load"
colnames(submission_template_ETS) <- c("date","load")
#Save out dataframe as excel file to submit to Kaggle
write.xlsx(submission_template_ETS, file = "Sirison_Wu_1.xlsx")
```
#Model 2: ARIMA + FOURIER terms
Our second model is called a dynamic harmonic regression model with an ARMA error structure, which adopts a log transformation in the ARIMA model to ensure the forecasts and prediction intervals remain positive. The FOURIER terms determine how quickly the seasonality could change.
```{r ARIMA, echo=TRUE, message=FALSE, warning=FALSE}
ARIMA_Four_fit <- auto.arima(ts_train,
seasonal=FALSE,
lambda=0,
xreg=fourier(ts_train,
K=c(2,48))
)
#Forecast with ARIMA fit
ARIMA_Four_for <- forecast(ARIMA_Four_fit,
xreg=fourier(ts_train,
K=c(2,48),
h=365),
h=365
)
#Plot foresting results
autoplot(ARIMA_Four_for) + ylab("Hourly Load")
#Plot model + observed data
autoplot(ts) +
autolayer(ARIMA_Four_for, series="ARIMA_FOURIER",PI=FALSE) +
ylab("Daily Load")+
labs(title= "ARIMA+Fourier Terms vs. Observed")
```
We tried different K numbers, such as 4, 6, 12, 24, 36, and 60. We found that although 48 performs the best accuracy compared with the original data, the forecasted still has a greater magnitude than observed data when the time series is at its peak maximum, but has a lower magnitude when the time series is at its minimum.
```{r}
#WRANGLING FOR KAGGLE SUBMISSION
#Generate 2011 output for Kaggle competition
ARIMA_FOURIER_fit_kaggle <- forecast(ARIMA_Four_for,h=59)
#Save ETS_fit_kaggle as a dataframe
ARIMA_FOURIER_fit_kaggle_df <- as.data.frame(ARIMA_FOURIER_fit_kaggle$mean)
#Merge df
submission_template_ARIMA <- cbind(submission_template,ARIMA_FOURIER_fit_kaggle_df)
#Remove extra column
submission_template_ARIMA <- submission_template_ARIMA[, c("date","x")]
#Rename column from "x" to "load"
colnames(submission_template_ARIMA) <- c("date","load_Model2")
#Merge model1 and model2
combine_model_final<- merge(submission_template_ETS,submission_template_ARIMA,by="date")
colnames(combine_model_final) <- c("date","load_Model1","load_Model2")
#Save out dataframe as excel file to submit to Kaggle
write.xlsx(combine_model_final, file = "Sirison_Wu_2.xlsx")
```
#Model 3: TBATS
Our third model is the Trigonometric seasonality, Box-Cox transformation (TBATs), which is a model appropriate for handling time series data that has multiple seasonalities. The TBATS approach models seasonal periods using trigonometric based on Fourier series.
```{r, echo=TRUE, message=FALSE, warning=FALSE}
TBATS_fit <- tbats(ts_train)
TBATS_for <- forecast(TBATS_fit, h=365)
```
```{r, echo= TRUE}
#Plot TBATS forecast vs observed data
autoplot(ts) +
autolayer(TBATS_for, series="TBATS",PI=FALSE)+
ylab("Daily Load")+
labs(title= "TBATS vs. Observed")
```
The TBATS model fits the seasonality well; however the magnitude for both when the time series is at its maximum and its minimum is lower than what observed data.
```{r}
#WRANGLING FOR KAGGLE SUBMISSION
#Generate 2011 output for Kaggle competition
TBATS_fit_kaggle <- forecast(TBATS_fit, h=59)
#Save TBATS_fit_kaggle as a dataframe
TBATS_fit_kaggle_df <- as.data.frame(TBATS_fit_kaggle$mean)
#Read in submission template
submission_template<-read_excel("submission_template.xlsx")
#Merge df
submission_template_TBATS <- cbind(submission_template,TBATS_fit_kaggle_df)
#Remove extra column
submission_template_TBATS <- submission_template_TBATS[, c("date","x")]
#Rename column from "x" to "load"
colnames(submission_template_TBATS) <- c("date","load")
#Save out dataframe as excel file to submit to Kaggle
write.xlsx(submission_template_TBATS, file = "Sirison_Wu_3.xlsx")
```
#Model 4. Neural Network Time Series Forecasts
Our fourth model is the Neural Network model. The neural network we used here is a feed forward neural network (FNN), meaning the nodes do not form a cycle or inputs to the FNN produces outputs that do not feed back into the next input.
```{r}
#NN_fit and forecast
NN_fit <- nnetar(ts_train,p=1,P=0,xreg=fourier(ts_train, K=c(2,12)))
NN_for <- forecast(NN_fit, h=365,xreg=fourier(ts_train,
K=c(2,12),h=365))
```
```{r, echo = TRUE}
#Plot NN forecast vs observed data
autoplot(ts) +
autolayer(NN_for, series="Neutral Network",PI=FALSE)+
ylab("Daily Load")+
labs(title= "Neural Network vs. Observed")
```
After trials, we found that NNAR(1,0,12) fits the model best, which means non-seasonal AR is 1, and seasonal AR equals to 0 with 12 hidden nodes.
The neural network model is able to follow both the seasonality and magnitude of the observed data very well.
```{r, message=FALSE}
#WRANGLING FOR KAGGLE SUBMISSION
#Generate 2011 output for Kaggle competition
NN_fit_kaggle <- forecast(NN_for, h=59)
#Save NN_fit_kaggle as a dataframe
NN_fit_kaggle_df <- as.data.frame(NN_fit_kaggle$mean)
#Read in submission template
submission_template<-read_excel("submission_template.xlsx")
#Merge df
submission_template_NN <- cbind(submission_template,NN_fit_kaggle_df)
#Remove extra column
submission_template_NN <- submission_template_NN[, c("date","x")]
#Rename column from "x" to "load"
colnames(submission_template_NN) <- c("date","load")
#Save out dataframe as excel file to submit to Kaggle
write.xlsx(submission_template_NN, file = "Sirison_Wu_4.xlsx")
```
##EXAMINING ACCURACY OF FORECASTS
```{r}
#Model 1: STL + ETS Accuracy
ETS_scores <- accuracy(ETS_fit$mean,ts_test)
#Model 2: Arima + Fourier Accuracy
ARIMA_scores <- accuracy(ARIMA_Four_for$mean,ts_test)
#Model 3: TBATS Accuracy
TBATS_scores <- accuracy(TBATS_for$mean,ts_test)
#Model 4: Neural Network Accuracy
NN_scores <- accuracy(NN_for$mean,ts_test)
```
#Accuracy Comparison
```{r, echo= TRUE}
#Graph of all forecast models
autoplot(ts) +
autolayer(ETS_fit, series="STL + ETS",PI=FALSE) +
autolayer(ARIMA_Four_for, series="ARIMA_FOURIER",PI=FALSE) +
autolayer(TBATS_for, series="TBATS",PI=FALSE)+
autolayer(NN_for, series="NN",PI=FALSE)+
ylab("Daily Load")+
labs(title = "Forecasting Model Comparison")
```
After visually examining how each model performs compares to observed data, it is unclear which model performs the best; therefore, we calculate accuracy metrics for each model.
#Compare performance metrics
```{r}
#create data frame
scores <- as.data.frame(
rbind(ETS_scores, ARIMA_scores, TBATS_scores, NN_scores)
)
row.names(scores) <- c("STL+ETS", "ARIMA+Fourier","TBATS","NN")
#choose model with lowest RMSE
best_model_index <- which.min(scores[,"RMSE"])
cat("The best model by RMSE is:", row.names(scores[best_model_index,]))
#choose model with lowest MAPE
best_model_index <- which.min(scores[,"MAPE"])
cat("The best model by MAPE is:", row.names(scores[best_model_index,]))
```
We examine 2 metrics for model performance: RMSE (Root Mean Square Error) and MAPE (Mean Absolute Percentage Error). RMSE is a metric that averages the difference between actual and predicted values, meaning it takes errors in magnitude into account. MAPE measures the average percentage difference between actual and predicted values.
```{r echo=TRUE, message=FALSE, warning=FALSE}
#Table of accuracy statistics
kbl(scores,
caption = "Forecast Accuracy for Daily Load",
digits = array(5,ncol(scores))) %>%
kable_styling(full_width = FALSE, position = "center", latex_options = "hold_position") %>%
kable_styling(latex_options="striped", stripe_index = which.min(scores[,"RMSE"]))
```
```{r echo=TRUE, message=FALSE, warning=FALSE}
#Table of accuracy statistics
kbl(scores,
caption = "Forecast Accuracy for Daily Load",
digits = array(5,ncol(scores))) %>%
kable_styling(full_width = FALSE, position = "center", latex_options = "hold_position") %>%
kable_styling(latex_options="striped", stripe_index = which.min(scores[,"MAPE"]))
```
The best model by RMSE is the TBATS model, while the best model by MAPE is the Neural Network model. This discrepancy is due to the fact that RMSE and MAPE captures different aspects in terms of accuracy. RMSE focuses more on magnitude of errors, while MAPE focuses more on percentage of errors.
Due to the discrepancy by using just RMSE and MAPE for performance metrics, we also consider other metrics: MAE (mean averaged error) and MPE (mean percentage error). The TBATS model outperforms the Neural Network model in both MAE and MPE.
##FUTURE FORECAST BASED ON CHOSEN BEST ODEL
In conclusion, after training and testing 4 models: STL+ETS, Arima + Fourier Terms, TBATS, and Neural Network, we conclude that the TBATS model is the best performing model for forecasting daily load.
We then regenerated the TBATS model by training it using the entire dataframe, instead of using a subset, as performed previously. The regenerated TBATS model is then used to forecast daily load 5 months (151 days) into the future. The results of the future forecast using a TBATS model is displayed below:
```{r, message = FALSE, echo = TRUE}
#Fit new TBATS model that uses the entire dataframe
TBATS_fit_final <- tbats(ts)
#Forecast of new TBATS model
TBATS_for_final <- forecast(TBATS_fit_final, h=151)
```
```{r, echo = TRUE}
#Plot of future TBATS forecast
autoplot(ts) +
autolayer(TBATS_for_final, series="TBATS",PI=FALSE)+
ylab("Daily Load")+
labs(title= "Observed Data + TBATS Future Forecast")
```
##CONCLUSION
#Discussion and Limitations
We can see that the future forecast 5 months into the future, using the TBATS model looks "smoother" than the rest of the observed data. This is a result of the nature of the model. The TBATS forecast incorporates Box-Cox transformations that reduces variance, and ARMA terms that reduces the impact of random fluctuations.
We also observe a noticeable jump in load; minimum load seems to increase dramatically compared to the series last minima in the observed data. This dramatic increase may partially be due to the "smoothing" effect of the TBATS modeled as discussed above. Even though we do not expect daily load to change dramatically, we do know that under increasing frequency of extreme weather, unexpected load peaks (outliers) are to be expected. Therefore, even though the TBATS performed best when we evaluated models using accuracy metrics, this may mean that given the nature of our time series data (load data) the TBATS model may not be the model choice that is most applicable since it does not perform as well in capturing outliers.
Additionally, the unexpected, observed jump in minimum load may also highlight the limitations of time series forecasting.Even though we trained a forecasting model using more than a decade of data, this does not necessarily mean that the future forecast generated will be 100% accurate. Our model operates under the assumption that the same cycles, patterns and trends that persist in the past will persist into the future.
Overall, this project successfully explored multiple models that are fitted to daily load data. We concluded that the TBATS model outperformed the other 3 models (STL+ETS, Arima + Fourier, and Neural Network) using both a visual comparison and performance metrics (RMSE, MAPE, MSE, and MPE). We were able to generate a future prediction (5 months ahead) for daily load, in which we observed an increase in demand. Nonetheless, we acknowledge the limitations of both the model we chose for future forecasting as well as the limitations of time series forecasting. Regardless, forecasting of future load can still be useful for many stakeholders in the the energy and utility space. Despite the limitations of how accuracy a time series forecast can be, a general idea of what load might look like int he next 10 years can help utilities plan generation and capacity appropriately. |
package com.YK.social_media.controllers;
import com.YK.social_media.models.Message;
import com.YK.social_media.models.User;
import com.YK.social_media.services.FriendService;
import com.YK.social_media.services.MessageService;
import com.YK.social_media.services.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import java.security.Principal;
@Controller
@RequiredArgsConstructor
@Tag(name = "Сообщения")
public class MessageController {
@Autowired
UserService userService;
@Autowired
FriendService friendService;
@Autowired
MessageService messageService;
@Operation(
summary = "Список сообщений пользователя",
description = "Endpoint вывода всех сообщений пользователя. Входящие + список друзей, которым можно отправить сообщения",
responses = {
@ApiResponse(
description = "Выводятся все сообщения пользователя с обратной сортировкой по последним сообщениям",
responseCode = "200"
),
@ApiResponse(
description = "Unauthorized / Invalid Token",
responseCode = "403"
)
}
)
@GetMapping("/my/messages")
public String userMessages(Principal principal, Model model) {
User user = userService.getUserByPrincipal(principal);
model.addAttribute("user", user);
model.addAttribute("friends", friendService.getFriends(user));
model.addAttribute("messages", messageService.receivedMessages(user));
return "my-messages";
}
@Operation(
summary = "Отправка сообщения пользователю",
description = "Endpoint отправки сообщения \"Hello, { Имя пользователя }. How are you?\" пользователю.",
responses = {
@ApiResponse(
description = "Отправленное сообщение добавляется в систему с меткой SENDED",
responseCode = "200"
),
@ApiResponse(
description = "Unauthorized / Invalid Token",
responseCode = "403"
)
}
)
@PostMapping("/user/{user}/send")
public String send(User user, Model model, Principal principal) {
userService.sendMessage(user, principal);
return userMessages(principal, model);
}
@Operation(
summary = "Смена статуса сообщения на \"Прочитано\"",
description = "Endpoint меняеют статус выбранного входящего сообщения на \"Прочитано\"",
responses = {
@ApiResponse(
description = "Статус входящего сообщения меняется на READED",
responseCode = "200"
),
@ApiResponse(
description = "Unauthorized / Invalid Token",
responseCode = "403"
)
}
)
@GetMapping("/message/{message}/read")
public String readMessage(@PathVariable("message") Message message, Model model, Principal principal) {
User receiver = userService.getUserByPrincipal(principal);
messageService.readMessage(message, receiver);
return userMessages(principal, model);
}
@Operation(
summary = "Удаление входящего сообщения",
description = "Endpoint удаления выбранного входящего сообщения",
responses = {
@ApiResponse(
description = "Статус входящего сообщения меняется на DELETED",
responseCode = "200"
),
@ApiResponse(
description = "Unauthorized / Invalid Token / Нельзя удалить сообщение, если пользователь не является адресатом этого сообщения",
responseCode = "403"
)
}
)
@GetMapping("/message/{message}/delete")
public String deleteMessage(@PathVariable("message") Message message, Model model, Principal principal) {
User receiver = userService.getUserByPrincipal(principal);
messageService.deleteMessage(message, receiver);
return userMessages(principal, model);
}
} |
package com.bunny.groovy.ui.fragment.wallet;
import com.bunny.groovy.api.SubscriberCallBack;
import com.bunny.groovy.base.BasePresenter;
import com.bunny.groovy.model.ResultResponse;
import com.bunny.groovy.model.WalletBean;
import com.bunny.groovy.utils.AppCacheData;
import java.util.List;
/**
* Created by bayin on 2018/1/15.
*/
public class WalletListPresetner extends BasePresenter<IWalletListView> {
public WalletListPresetner(IWalletListView view) {
super(view);
}
public void getWalletList() {
addSubscription(apiService.getWalletList(), new SubscriberCallBack<List<WalletBean>>(mView.get()) {
@Override
protected boolean isShowProgress() {
return true;
}
@Override
protected void onSuccess(List<WalletBean> response) {
if (response != null && response.size() > 0) {
mView.setListData(response);
} else mView.noData();
}
@Override
protected void onFailure(ResultResponse response) {
mView.noData();
}
});
}
public void getUserTransactionRecord() {
addSubscription(apiService.getUserTransactionRecord(AppCacheData.getPerformerUserModel().getUserID()), new SubscriberCallBack<List<WalletBean>>(mView.get()) {
@Override
protected boolean isShowProgress() {
return true;
}
@Override
protected void onSuccess(List<WalletBean> response) {
if (response != null && response.size() > 0) {
mView.setListData(response);
} else mView.noData();
}
@Override
protected void onFailure(ResultResponse response) {
mView.noData();
}
});
}
public void getNormalUserTransactionRecord() {
addSubscription(apiService.getNormalUserTransactionRecord(AppCacheData.getPerformerUserModel().getUserID()), new SubscriberCallBack<List<WalletBean>>(mView.get()) {
@Override
protected boolean isShowProgress() {
return true;
}
@Override
protected void onSuccess(List<WalletBean> response) {
if (response != null && response.size() > 0) {
mView.setListData(response);
} else mView.noData();
}
@Override
protected void onFailure(ResultResponse response) {
mView.noData();
}
});
}
} |
package gb.endpoints;
import static gb.testlang.fixtures.CommentsFixtures.ANON_NAME_DIV_TEXT;
import static gb.testlang.fixtures.CommentsFixtures.EXISTING_ID;
import static gb.testlang.fixtures.CommentsFixtures.USERNAME_DIV_TEXT;
import static gb.testlang.fixtures.CommentsFixtures.buildAnonCommentInput;
import static gb.testlang.fixtures.CommentsFixtures.buildCommentEntriesList;
import static gb.testlang.fixtures.UsersFixtures.EXISTING_USERNAME;
import static lombok.AccessLevel.PRIVATE;
import static org.hamcrest.Matchers.containsString;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;
import static org.springframework.http.MediaType.APPLICATION_FORM_URLENCODED;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import java.util.List;
import org.junit.Test;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.security.test.context.support.WithMockUser;
import gb.api.CommentsApi;
import gb.common.it.EndpointITCase;
import gb.controllers.MainController;
import gb.dto.CommentEntry;
import gb.dto.CommentInput;
import lombok.experimental.FieldDefaults;
@FieldDefaults(level=PRIVATE)
@WebMvcTest(MainController.class)
@WithMockUser(username=EXISTING_USERNAME, roles={"USER", "ADMIN", "ACTUATOR"})
public class MainControllerTests extends EndpointITCase {
private static final String ROOT_URL = "/";
private static final String LOGIN_URL = "/login";
private static final String HTML_UTF8 = "text/html;charset=UTF-8";
private static final String LENGTH_ERROR_MESSAGE =
"length must be between";
@MockBean
CommentsApi commentsApi;
@Override
public void setup() {
final List<CommentEntry> commentEntries = buildCommentEntriesList();
when(commentsApi.createComment(any(CommentInput.class)))
.thenReturn(EXISTING_ID);
when(commentsApi.getComments())
.thenReturn(commentEntries);
}
@Test
public void Getting_a_list_of_comments()
throws Exception {
mockMvc.perform(get(ROOT_URL))
.andExpect(status().isOk())
.andExpect(content().contentType(HTML_UTF8))
.andExpect(content().string(containsString(ANON_NAME_DIV_TEXT)))
.andExpect(content().string(containsString(USERNAME_DIV_TEXT)));
}
@Test
public void Creating_a_new_comment() throws Exception {
final String params = payload(buildAnonCommentInput());
mockMvc.perform(post(ROOT_URL)
.content(params)
.contentType(APPLICATION_FORM_URLENCODED))
.andExpect(status().is3xxRedirection())
.andExpect(header().stringValues("Location", ROOT_URL));
}
@Test
public void Invalid_form_should_return_main_page() throws Exception {
final CommentInput invalidInput = CommentInput.builder()
.anonName("").message("").build();
final String params = payload(invalidInput);
mockMvc.perform(post(ROOT_URL)
.content(params)
.contentType(APPLICATION_FORM_URLENCODED))
.andExpect(status().isOk())
.andExpect(content().string(containsString(LENGTH_ERROR_MESSAGE)));
}
@Test
public void A_login_page_should_return_200() throws Exception {
mockMvc.perform(get(LOGIN_URL))
.andExpect(status().isOk())
.andExpect(content().contentType(HTML_UTF8))
.andExpect(content().string(containsString("Login")))
.andExpect(content().string(containsString("Password")));
}
private String payload(final CommentInput input) {
return String.format(
"name=%s&message=%s",
input.getAnonName(),
input.getMessage()
);
}
} |
import { isReadonly, readonly, isProxy } from "../reactive";
describe("readonly test", () => {
it("readonly", () => {
const user = readonly({
name: "bojack",
age: 10,
});
console.warn = jest.fn();
expect(user.age).toBe(10);
user.age = 11;
expect(console.warn).toBeCalled();
expect(user.age).toBe(10);
});
it("isReadonly", () => {
const obj = {
name: "bojack",
age: 10,
};
const user = readonly(obj);
expect(isReadonly(obj)).toBe(false);
expect(isReadonly(user)).toBe(true);
expect(isProxy(user)).toBe(true);
});
it("nested readonly", () => {
const obj = {
name: "bojack",
age: 10,
family: [
{
name: "pear",
age: 20,
},
],
};
const user = readonly(obj);
expect(isReadonly(user)).toBe(true);
expect(isReadonly(user.family)).toBe(true);
expect(isReadonly(user.family[0])).toBe(true);
});
}); |
| **Inicio** | **atrás 6** | **Siguiente 8** |
| --------------------- | ----------------------------------------------------------------- | --------------------------------------------------------------------------------- |
| [🏠](../../README.md) | [⏪](./6.Calculos_de_Tablas_Dashboards_Avanzados_Storytelling.md) | [⏩](./8.Clusters_Territorios_Personalizados_y_Caracteristicas_de_Dise%C3%B1o.md) |
---
## **Índice**
| Temario |
| ------------------------------------------------------------------------------------------------------------- |
| [En qué Formato Deben Estar tus Datos](#en-qué-formato-deben-estar-tus-datos) |
| [Intérprete de Datos](#intérprete-de-datos) |
| [Pivotar](#pivotar) |
| [Dividiendo una Columna en Múltiples Columnas](#dividiendo-una-columna-en-múltiples-columnas) |
| [Grid de Metadatos](#grid-de-metadatos) |
| [Solucionando Errores de Datos Geográficos en Tableau](#solucionando-errores-de-datos-geográficos-en-tableau) |
---
# **Preparación de Datos Avanzada**
---
## **En qué Formato Deben Estar tus Datos**
Tableau puede trabajar con una variedad de formatos de datos, pero existen algunos formatos que son más comunes y recomendados para obtener el mejor rendimiento y funcionalidad en tus análisis. A continuación, te proporcionaré una explicación detallada de los formatos de datos recomendados para Tableau, junto con ejemplos:
1. **Archivos de Excel:**
Tableau puede leer datos de archivos de Excel, como .xlsx y .xls. Puedes utilizar hojas individuales o combinar múltiples hojas en un solo archivo para crear visualizaciones. Por ejemplo, puedes tener un archivo de Excel con diferentes hojas que contengan datos de ventas por región, producto y período de tiempo.
2. **Archivos de texto delimitado:**
Tableau también puede leer datos de archivos de texto delimitado, como .csv (valores separados por comas) y .txt. Estos archivos deben tener una estructura tabular en la que los datos estén separados por un carácter delimitador, como una coma, punto y coma o tabulación. Por ejemplo, puedes tener un archivo CSV con datos de clientes que incluya columnas como ID de cliente, nombre, dirección y edad.
3. **Archivos de bases de datos:**
Tableau es compatible con una amplia gama de bases de datos, incluyendo MySQL, PostgreSQL, Oracle, SQL Server, entre otros. Puedes conectarte directamente a estas bases de datos para extraer datos y crear visualizaciones. Por ejemplo, puedes conectarte a una base de datos de ventas y utilizar consultas SQL para extraer datos específicos para tus análisis.
4. **Archivos de extracto de datos de Tableau (.tde o .hyper):**
Tableau permite crear extractos de datos optimizados para un rendimiento más rápido y eficiente. Estos extractos se almacenan en formato .tde (Tableau Data Extract) o .hyper y contienen datos agregados y optimizados para las consultas en Tableau. Puedes crear extractos a partir de diferentes fuentes de datos y utilizarlos como fuente para tus visualizaciones. Por ejemplo, puedes crear un extracto de datos a partir de un archivo CSV de ventas y utilizarlo para crear visualizaciones que se actualicen rápidamente.
Es importante destacar que, independientemente del formato de tus datos, estos deben estar estructurados de manera adecuada para que Tableau pueda interpretarlos correctamente. Asegúrate de que tus datos tengan una estructura tabular consistente, con columnas y filas bien definidas, y que los valores estén correctamente formateados.
Además, Tableau también te permite conectarte a fuentes de datos en línea, como bases de datos en la nube, servicios web y otras aplicaciones. Puedes utilizar conectores específicos o configurar conexiones personalizadas para acceder a estos datos en Tableau.
En resumen, Tableau es compatible con una variedad de formatos de datos, incluyendo archivos de Excel, archivos de texto delimitado, bases de datos y extractos de datos optimizados. Al elegir el formato adecuado y estructurar tus datos correctamente, podrás aprovechar al máximo las capacidades de análisis de Tableau.
[🔼](#índice)
---
## **Intérprete de Datos**
En Tableau, el Intérprete de Datos es una función que te permite explorar y analizar tus datos de forma rápida y sencilla. Utiliza algoritmos de inteligencia artificial para detectar patrones, columnas, jerarquías y tipos de datos en tu conjunto de datos, lo que facilita el proceso de entender y visualizar la información.
A continuación, te proporcionaré una explicación detallada del Intérprete de Datos en Tableau, junto con ejemplos:
1. **Detección de tipos de datos:**
Cuando cargas un conjunto de datos en Tableau, el Intérprete de Datos analiza los valores de cada columna y asigna automáticamente el tipo de datos correspondiente. Por ejemplo, si una columna contiene fechas, el Intérprete de Datos reconocerá que es un tipo de dato de fecha. Esto es útil porque Tableau aplica automáticamente el formato y las funciones adecuadas a cada tipo de dato, lo que simplifica el proceso de análisis.
**Ejemplo:**
Imagina que tienes un conjunto de datos con una columna llamada "Edad". Al cargar los datos en Tableau y utilizar el Intérprete de Datos, reconocerá que los valores en esa columna son numéricos y asignará automáticamente el tipo de dato "Número".
2. **Detección de jerarquías y agrupaciones:**
El Intérprete de Datos también puede detectar jerarquías y agrupaciones en tus datos. Por ejemplo, si tienes una columna de "Fecha" que incluye valores como "Día", "Mes" y "Año", el Intérprete de Datos identificará esta estructura y creará automáticamente una jerarquía de tiempo para que puedas analizar los datos a diferentes niveles de granularidad.
**Ejemplo:**
Supongamos que tienes una columna de "Fecha" con valores como "01/01/2023". Al utilizar el Intérprete de Datos, reconocerá que los valores son de tipo fecha y creará automáticamente una jerarquía de tiempo con niveles como "Año", "Trimestre", "Mes" y "Día".
3. **Detección de patrones y columnas adicionales:**
El Intérprete de Datos también puede ayudarte a descubrir patrones y columnas adicionales en tus datos. Utiliza algoritmos de análisis para identificar relaciones entre las variables y sugerir visualizaciones relevantes. Por ejemplo, si tienes un conjunto de datos con información demográfica, el Intérprete de Datos puede detectar patrones como la relación entre la edad y el ingreso.
**Ejemplo:**
Supongamos que tienes un conjunto de datos con columnas como "Edad", "Ingresos" y "Ciudad". Al utilizar el Intérprete de Datos, puede detectar que existe una relación entre la edad y los ingresos y sugerir visualizaciones como gráficos de dispersión o gráficos de barras para analizar esta relación.
En resumen, el Intérprete de Datos en Tableau utiliza algoritmos de inteligencia artificial para detectar tipos de datos, jerarquías, patrones y columnas adicionales en tu conjunto de datos. Esto facilita el proceso de exploración y análisis de datos al asignar automáticamente los tipos de datos correctos y sugerir visualizaciones relevantes. Al aprovechar el Intérprete de Datos, puedes ahorrar tiempo y obtener información valiosa de tus datos de manera eficiente.
[🔼](#índice)
---
## **Pivotar**
En Tableau, pivotar se refiere a una técnica que te permite reorganizar la estructura de tus datos para que se ajusten mejor a la forma en que Tableau interpreta y analiza la información. Pivoting o pivotar es útil cuando tienes datos en formato ancho (con muchas columnas) y deseas convertirlos en formato largo (con menos columnas pero más filas) para facilitar el análisis y la visualización.
A continuación, te proporcionaré una explicación detallada de cómo pivotar en Tableau, junto con ejemplos:
1. **Datos en formato ancho:**
En un conjunto de datos en formato ancho, cada columna representa una variable o atributo distinto. Por ejemplo, supongamos que tienes un conjunto de datos con las siguientes columnas: "Producto", "Ventas_2019", "Ventas_2020" y "Ventas_2021". Cada columna representa las ventas anuales de un producto específico en diferentes años.
2. **Pivotar los datos:**
Para pivotar estos datos en Tableau, selecciona las columnas que deseas pivotar (en este caso, las columnas de ventas) y haz clic derecho. Luego, elige la opción "Pivotar" en el menú desplegable. Esto creará una nueva columna llamada "Valor" que contiene los valores de las ventas, y una columna adicional llamada "Nombre de columna" que indica a qué variable corresponde cada valor.
3. **Datos en formato largo:**
Después de pivotar, tus datos se presentarán en formato largo. En este formato, tendrás menos columnas, pero más filas, lo que facilita el análisis y la visualización en Tableau. Ahora, tus datos tendrán columnas como "Producto", "Nombre de columna" y "Valor". La columna "Nombre de columna" indicará el año al que corresponde cada valor de ventas, y la columna "Valor" contendrá los valores de las ventas.
**Ejemplo:**
Antes de pivotar:
| Producto | Ventas_2019 | Ventas_2020 | Ventas_2021 |
| -------- | ----------- | ----------- | ----------- |
| A | 1000 | 1500 | 2000 |
| B | 1200 | 1800 | 2200 |
| C | 900 | 1300 | 1700 |
Después de pivotar:
| Producto | Nombre de columna | Valor |
| -------- | ----------------- | ----- |
| A | Ventas_2019 | 1000 |
| A | Ventas_2020 | 1500 |
| A | Ventas_2021 | 2000 |
| B | Ventas_2019 | 1200 |
| B | Ventas_2020 | 1800 |
| B | Ventas_2021 | 2200 |
| C | Ventas_2019 | 900 |
| C | Ventas_2020 | 1300 |
| C | Ventas_2021 | 1700 |
Ahora, con los datos en formato largo, puedes utilizar Tableau para realizar análisis y visualizaciones más fácilmente. Por ejemplo, puedes crear una visualización que muestre las ventas de cada producto en diferentes años utilizando la columna "Nombre de columna" para representar el eje X y la columna "Valor" para representar el eje Y.
En resumen, pivotar en Tableau implica reorganizar los datos de formato ancho a formato largo, lo que facilita el análisis y la visualización de la información. Al pivotar los datos, puedes trabajar con una estructura más adecuada para Tableau y aprovechar al máximo las funcionalidades de la herramienta.
[🔼](#índice)
---
## **Dividiendo una Columna en Múltiples Columnas**
En Tableau, puedes dividir una columna en múltiples columnas utilizando la función "`Separar`". Esto te permite dividir una columna que contiene datos combinados en diferentes elementos y distribuirlos en columnas separadas para un análisis más detallado.
Aquí tienes una explicación detallada de cómo dividir una columna en múltiples columnas en Tableau, junto con ejemplos:
1. **Identifica la columna que deseas dividir:**
Supongamos que tienes una columna llamada "Nombre completo" que contiene el nombre y apellido de una persona en un solo campo, separados por un espacio.
2. **Utiliza la función "Separar":**
En Tableau, selecciona la columna "Nombre completo" y haz clic derecho. Luego, selecciona la opción "Separar" en el menú desplegable.
3. **Especifica el separador:**
En la ventana emergente de "Separar", se te pedirá que especifiques el separador que se utiliza para dividir los datos en columnas separadas. En este caso, el separador sería el espacio en blanco.
4. **Configura las opciones de separación:**
Puedes elegir si deseas eliminar el campo original o conservarlo. Además, puedes especificar un nombre para las nuevas columnas que se crearán.
Ejemplo:
Antes de dividir:
| Nombre completo |
| --------------- |
| John Smith |
| Jane Doe |
| Mark Johnson |
Después de dividir:
| Nombre | Apellido |
| ------ | -------- |
| John | Smith |
| Jane | Doe |
| Mark | Johnson |
En el ejemplo anterior, la columna "Nombre completo" se dividió en dos columnas separadas: "Nombre" y "Apellido". Los nombres y apellidos individuales se distribuyen en las nuevas columnas, lo que facilita su análisis y visualización en Tableau.
Una vez que has dividido la columna, puedes utilizar las columnas resultantes en tus análisis y visualizaciones. Por ejemplo, puedes crear una visualización que muestre la distribución de los nombres por género o crear filtros basados en los apellidos.
Dividir una columna en múltiples columnas en Tableau te permite trabajar con los datos de manera más granular y realizar análisis más detallados. Es especialmente útil cuando tienes datos combinados en una sola columna y necesitas desglosarlos para un análisis más profundo.
[🔼](#índice)
---
## **Grid de Metadatos**
En Tableau, un grid de metadatos se refiere a una vista en la que puedes explorar y analizar los metadatos de tus fuentes de datos. Los metadatos son información adicional sobre tus datos, como nombres de tablas, nombres de columnas, tipos de datos y relaciones entre tablas. El grid de metadatos en Tableau te brinda una visión general de la estructura y los detalles de tus fuentes de datos.
A continuación, te proporcionaré una explicación detallada de cómo funciona el grid de metadatos en Tableau, junto con ejemplos:
1. **Acceder al grid de metadatos:**
En Tableau, puedes acceder al grid de metadatos en la pestaña "Datos". Allí encontrarás una vista en forma de tabla que muestra información sobre las tablas y columnas de tus fuentes de datos.
2. **Explorar los metadatos:**
En el grid de metadatos, puedes explorar diferentes aspectos de tus datos. Puedes ver los nombres de las tablas y columnas, los tipos de datos, la cantidad de registros y más. También puedes ver las relaciones entre tablas, como las claves primarias y foráneas.
3. **Obtener detalles sobre las columnas:**
Al seleccionar una columna específica en el grid de metadatos, puedes ver detalles adicionales, como el formato, el tamaño máximo y los valores distintos presentes en la columna. Esto te ayuda a comprender mejor los datos y a realizar análisis más precisos.
4. **Realizar acciones sobre los metadatos:**
El grid de metadatos te permite realizar varias acciones sobre tus fuentes de datos. Por ejemplo, puedes renombrar tablas y columnas, cambiar el tipo de datos, agregar descripciones o crear cálculos basados en los metadatos existentes.
**Ejemplo:**
Supongamos que tienes un conjunto de datos que contiene información sobre clientes en una tabla llamada "Clientes". En el grid de metadatos, puedes ver los detalles de esta tabla, como los nombres de las columnas ("Nombre", "Edad", "Género"), los tipos de datos (cadena, entero), la cantidad de registros y más.
Además, si tienes otra tabla llamada "Pedidos" que tiene una relación con la tabla "Clientes", puedes ver esta relación en el grid de metadatos. Puedes identificar la clave primaria en la tabla "Clientes" y la clave foránea en la tabla "Pedidos", lo que te permite comprender mejor cómo se relacionan estas dos tablas en tu conjunto de datos.
El grid de metadatos en Tableau es una herramienta útil para explorar y comprender la estructura y los detalles de tus fuentes de datos. Te brinda una vista completa de los metadatos, lo que facilita la comprensión de tus datos y la toma de decisiones basadas en ellos. Puedes utilizar esta información para realizar análisis más profundos y crear visualizaciones efectivas en Tableau.
[🔼](#índice)
---
## **Solucionando Errores de Datos Geográficos en Tableau**
Cuando trabajas con datos geográficos en Tableau, es posible que te encuentres con errores o inconsistencias en la asignación de ubicaciones geográficas. Estos errores pueden deberse a problemas en los datos, como nombres de lugares mal escritos, coordenadas incorrectas o falta de correspondencia entre los datos y las fuentes geográficas utilizadas por Tableau. A continuación, te proporcionaré una explicación detallada de cómo solucionar errores de datos geográficos en Tableau, junto con ejemplos:
1. **Verificar la calidad de los datos:**
Lo primero que debes hacer es verificar la calidad de tus datos geográficos. Revisa si hay errores tipográficos en los nombres de los lugares o si hay registros con información geográfica faltante. Esto es importante para identificar las áreas problemáticas y determinar qué tipo de errores necesitas abordar.
2. **Utilizar fuentes de datos geográficos confiables:**
Tableau utiliza fuentes de datos geográficos para asignar ubicaciones a tus datos. Asegúrate de utilizar fuentes confiables y actualizadas, como los archivos de formas (shapefiles) o servicios de geocodificación proporcionados por Tableau o proveedores externos. Estas fuentes contienen información precisa sobre las ubicaciones geográficas.
3. **Revisar y corregir las asignaciones geográficas:**
En Tableau, puedes utilizar la función "Verificar asignaciones" para revisar las asignaciones geográficas de tus datos. Esta función te muestra las ubicaciones asignadas y te permite corregir cualquier error o inconsistencia. Puedes hacer clic derecho en un campo geográfico, seleccionar "Verificar asignaciones" y realizar ajustes manualmente en las ubicaciones si es necesario.
4. **Utilizar geocodificación personalizada:**
Si tus datos no se asignan correctamente con las fuentes de datos geográficos estándar, puedes crear una geocodificación personalizada. Esto implica proporcionar a Tableau una tabla adicional que asocie tus datos con las ubicaciones geográficas correspondientes. Por ejemplo, si tienes una columna de nombres de ciudades, puedes crear una tabla de geocodificación que asigne las coordenadas geográficas correctas a cada ciudad.
**Ejemplo:**
Supongamos que tienes una tabla de datos de ventas que contiene una columna de "Ubicación" que representa las ciudades donde se realizaron las ventas. Sin embargo, algunas ciudades tienen nombres mal escritos o no coinciden con las fuentes geográficas utilizadas por Tableau. Para solucionar esto, puedes seguir los pasos anteriores:
1. **Verificar la calidad de los datos:**
Revisa si hay errores tipográficos en los nombres de las ciudades y si hay registros con información faltante o inconsistente.
2. **Utilizar fuentes de datos geográficos confiables:**
Asegúrate de utilizar fuentes de datos geográficos confiables, como archivos de formas (shapefiles) actualizados o servicios de geocodificación proporcionados por Tableau o proveedores externos.
3. **Revisar y corregir las asignaciones geográficas:**
Utiliza la función "Verificar asignaciones" en Tableau para revisar las asignaciones geográficas de las ciudades en tu columna de "Ubicación". Corrige cualquier error o inconsistencia manualmente.
4. **Utilizar geocodificación personalizada:**
Si encuentras que algunas ciudades no se asignan correctamente con las fuentes de datos geográficos estándar, puedes crear una tabla de geocodificación personalizada. Esta tabla contendría los nombres de las ciudades y las correspondientes coordenadas geográficas correctas para cada ciudad. Luego, puedes asociar esta tabla con tu conjunto de datos de ventas en Tableau para obtener asignaciones geográficas precisas.
Solucionar errores de datos geográficos en Tableau es importante para garantizar que tus visualizaciones reflejen correctamente la ubicación de tus datos. Siguiendo los pasos mencionados anteriormente y asegurándote de utilizar fuentes de datos confiables, podrás corregir errores y obtener asignaciones geográficas precisas en tus análisis y visualizaciones en Tableau.
[🔼](#índice)
---
| **Inicio** | **atrás 6** | **Siguiente 8** |
| --------------------- | ----------------------------------------------------------------- | --------------------------------------------------------------------------------- |
| [🏠](../../README.md) | [⏪](./6.Calculos_de_Tablas_Dashboards_Avanzados_Storytelling.md) | [⏩](./8.Clusters_Territorios_Personalizados_y_Caracteristicas_de_Dise%C3%B1o.md) |
--- |
"""server
Serves the following endpoints:
GET /jobs
Return an HTML page containing a table of all jobs, sorted by most
recent first.
POST /jobs
Create a new job. The request body must be a form containing the
following fields:
- "proxy" is the kind of proxy, i.e. either "nginx" or "envoy".
- "proxy_commit" is the SHA1 hash of the git commit of the proxy
project that the job will build and test.
- "tracer_commit" is the SHA1 hash of the git commit of the tracing
library project (i.e. dd-trace-cpp) that the job will use in the
build of the proxy.
Requires the following environment variables:
DATABASE_DIR
Path to the directory containing the sqlite3 database and SQL statement
files.
LOGS_DIR
Path to the directory containing log files.
"""
import database
from flask import Flask, request
import json
import os
from pathlib import Path
import sqlite3
from . import sxml
db_dir = Path(os.environ['DATABASE_DIR'])
logs_dir = Path(os.environ['LOGS_DIR'])
db_path = db_dir / 'database.sqlite'
app = Flask(__name__, static_folder=logs_dir)
print(os.getcwd(), logs_dir)
def link_to_log(file_name):
if file_name is None:
return ''
return ['a', {'href': f'/logs/{file_name}'}, 'output']
def render_runtime(seconds: float):
"""Return a human-readable time duration of the specified number of
`seconds`.
For example:
- 34 -> "34s" for thirty-four seconds.
- 603 -> "10m 3s" for ten minutes and three seconds.
- 7919 -> "2h 11m 59s" for two hours, eleven minutes, and fifty-nine seconds.
"""
seconds = int(seconds)
if seconds < 60:
return f'{seconds}s'
minutes = seconds // 60
seconds = seconds % 60
if minutes < 60:
return f'{minutes}m {seconds}s'
hours = minutes // 60
minutes = minutes % 60
return f'{hours}h {minutes}m {seconds}s'
def render_job_status(start_time, runtime_seconds, return_status):
"""Return a human-readable description of the run status of the job based
on the specified `start_time`, `runtime_seconds`, and `return_status`.
For example:
- "Queued" -> The job has not started.
- "Running" -> The job has started, but has not finished.
- "Completed (36m 10s)" -> The job completed successfully, and took
thirty-six minutes and ten seconds.
- "Failed (5s)" -> The job failed, and took five seconds.
"""
if start_time is None:
return 'Queued'
if runtime_seconds is None:
return 'Running'
runtime = render_runtime(runtime_seconds)
if return_status == 0:
return f'Complete ({runtime})'
return f'Failed ({runtime})'
def jobs_rows(jobs_cursor):
"""Yield HTML table rows from the specified SQL query result set
`jobs_cursor`.
"""
for created, proxy, proxy_commit, proxy_commit_url_pattern, tracer_commit, begin, end, runtime, status, log in jobs_cursor:
yield ['tr',
# Created
['td', created.replace('T', ' ') + ' UTC'],
# Proxy
['td', proxy],
# Proxy Commit
['td',
['a', {'href': proxy_commit_url_pattern.format(commit=proxy_commit)},
proxy_commit[:7]]],
# Tracer Commit
['td',
['a', {'href': f'https://github.com/Datadog/dd-trace-cpp/commit/{tracer_commit}'},
tracer_commit[:7]]],
# Status
['td', render_job_status(begin, runtime, status)],
# Output (log)
['td', link_to_log(log)]] # yapf: disable
def render_jobs_page(jobs_cursor):
"""Return an HTML page containing a table of jobs based off of the specified SQL query result set `jobs_cursor`.
"""
return sxml.html_from_sexpr(
['html',
['head', ['title', 'Proxy Punisher: Jobs']],
['body',
['table', {'border': '1'},
['tr',
['th', 'Created'],
['th', 'Proxy'],
['th', 'Proxy Commit'],
['th', 'Tracer Commit'],
['th', 'Status'],
['th', 'Output']],
*jobs_rows(jobs_cursor)]]]) # yapf: disable
@app.get('/jobs')
def get_jobs():
sql = (db_dir / 'statements' / 'get-jobs.sql').read_text()
with database.connect(f'file:{db_path}?mode=ro', uri=True) as db:
db.execute('pragma foreign_keys = on;')
return render_jobs_page(db.execute(sql))
@app.post('/jobs')
def post_jobs():
proxy = request.form.get('proxy')
if proxy is None:
return f'Missing the "proxy" form field.\n', 400
proxy_commit = request.form.get('proxy_commit')
if proxy_commit is None:
return f'Missing the "proxy_commit" form field.\n', 400
tracer_commit = request.form.get('tracer_commit')
if tracer_commit is None:
return f'Missing the "tracer_commit" form field.\n', 400
sql = (db_dir / 'statements' / 'create-job.sql').read_text()
with database.connect(db_path) as db:
db.execute('pragma foreign_keys = on;')
try:
db.execute(
sql, {
'proxy': proxy,
'proxy_commit': proxy_commit,
'tracer_commit': tracer_commit
})
except sqlite3.IntegrityError as error:
return f'{error}\n', 400
return 'ok\n'
def server():
"""This is the entrypoint for `waitress`, the uWSGI runner."""
return app |
import mongoose, { Schema, Types } from 'mongoose';
// Document interface
export interface UserInterface {
_id: Types.ObjectId;
firstName: string;
lastName: string;
email: string;
password: string;
profilePicture?: string;
bio?: string;
friends?: Types.ObjectId[];
posts?: Types.ObjectId[];
notifications?: Types.ObjectId[];
createdAt: Date;
updatedAt: Date;
accountType: string;
forgotPasswordToken: string;
forgotPasswordTokenExpiry: string;
verifyToken: string;
verifyTokenExpiry: Date;
}
// Schema
const UserSchema = new Schema<UserInterface>({
firstName: { type: String, required: [true, 'Please provide a first name'] },
lastName: { type: String, required: [true, 'Please provide a last name'] },
email: {
type: String,
required: [true, 'Please provide a email'],
unique: true,
},
password: {
type: String,
required: [true, 'Please provide a password'],
// select: false, *it causes error in comparing entered password to hashed
},
profilePicture: { type: String, default: 'default-profile.jpg' },
bio: String,
friends: [{ type: Schema.Types.ObjectId, ref: 'User' }],
posts: [{ type: Schema.Types.ObjectId, ref: 'Post' }],
notifications: [{ type: Schema.Types.ObjectId, ref: 'Notification' }],
createdAt: { type: Date, default: Date.now },
updatedAt: { type: Date, default: Date.now },
accountType: { type: String, required: true, default: 'user' },
forgotPasswordToken: String,
forgotPasswordTokenExpiry: String,
verifyToken: String,
verifyTokenExpiry: Date,
});
const UserModel = mongoose.model('User', UserSchema);
export default UserModel; |
import { Command } from "../command.ts";
import { dim, italic } from "../deps.ts";
import { FishCompletionsGenerator } from "./_fish_completions_generator.ts";
/** Generates fish completions script. */
export class FishCompletionsCommand
extends Command<void, void, { name: string }> {
readonly #cmd?: Command;
public constructor(cmd?: Command) {
super();
this.#cmd = cmd;
return this
.description(() => {
const baseCmd = this.#cmd || this.getMainCommand();
return `Generate shell completions for fish.
To enable fish completions for this program add following line to your ${
dim(italic("~/.config/fish/config.fish"))
}:
${dim(italic(`source (${baseCmd.getPath()} completions fish | psub)`))}`;
})
.noGlobals()
.option("-n, --name <command-name>", "The name of the main command.")
.action(({ name = this.getMainCommand().getName() }) => {
const baseCmd = this.#cmd || this.getMainCommand();
console.log(FishCompletionsGenerator.generate(name, baseCmd));
});
}
} |
import PropTypes from 'prop-types';
import { HiPlusSm } from 'react-icons/hi';
import Container from './styles';
const Card = ({ name, id, logo, handleButton }) => (
<Container type="button" onClick={() => handleButton(id)} existproduct={name}>
{name ? (
<>
<img src={logo} alt="logo" />
<p>{name}</p>
</>
) : (
<>
<HiPlusSm color="#fff" size={40} />
<p>adicionar cliente</p>
</>
)}
</Container>
);
Card.propTypes = {
name: PropTypes.string,
id: PropTypes.number,
logo: PropTypes.string,
handleButton: PropTypes.func.isRequired,
};
Card.defaultProps = {
name: '',
id: -1,
logo: '',
};
export default Card; |
import io.github.bonigarcia.wdm.WebDriverManager;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
public class MultiBrowser {
public static WebDriver driver;
@Parameters ("browser")
@BeforeClass
public void beforeTest(String browser){
if(browser.equalsIgnoreCase("firefox")){
FirefoxOptions options = new FirefoxOptions();
options.setProfile(new FirefoxProfile());
options.addPreference("dom.webnotifications.enabled", false);
options.addPreference("geo.enabled", true);
options.addPreference("geo.prompt.testing",true);
options.addPreference("geo.prompt.testing.allow",true);
WebDriverManager.firefoxdriver().setup();
driver = new FirefoxDriver(options);
}
else if(browser.equalsIgnoreCase("chrome")){
ChromeOptions options = new ChromeOptions();
Map< String, Object > prefs = new HashMap< String, Object>();
Map < String, Object > profile = new HashMap < String, Object>();
Map < String, Integer > contentSettings = new HashMap < String, Integer>();
// 0- Default, 1 - Allow, 2 - Block
contentSettings.put("notifications", 2);
contentSettings.put("geolocation", 2);
profile.put("managed_default_content_settings", contentSettings);
prefs.put("profile", profile);
options.setExperimentalOption("prefs", prefs);
WebDriverManager.chromedriver().setup();
driver = new ChromeDriver(options);
}
}
@Test
public void test(){
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("https://chaldal.com/");
driver.manage().window().maximize();
}
} |
/*
This file is part of solidity.
solidity is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
solidity is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with solidity. If not, see <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
/// Utilities shared by multiple tests for code in solc/.
#include <solc/CommandLineParser.h>
#include <boost/test/unit_test.hpp>
#include <optional>
#include <string>
#include <vector>
BOOST_TEST_DONT_PRINT_LOG_VALUE(solidity::frontend::CommandLineOptions)
BOOST_TEST_DONT_PRINT_LOG_VALUE(solidity::frontend::InputMode)
namespace solidity::frontend::test
{
struct OptionsReaderAndMessages
{
bool success;
CommandLineOptions options;
FileReader reader;
std::optional<std::string> standardJsonInput;
std::string stdoutContent;
std::string stderrContent;
};
std::vector<char const*> makeArgv(std::vector<std::string> const& _commandLine);
/// Runs only command-line parsing, without compilation, assembling or any other input processing.
/// Lets through any @a CommandLineErrors throw by the CLI.
/// Note: This uses the @a CommandLineInterface class and does not actually spawn a new process.
/// @param _commandLine Arguments in the form of strings that would be specified on the command-line.
/// You must specify the program name as the first item.
/// @param _standardInputContent Content that the CLI will be able to read from its standard input.
OptionsReaderAndMessages parseCommandLineAndReadInputFiles(
std::vector<std::string> const& _commandLine,
std::string const& _standardInputContent = ""
);
/// Runs all stages of command-line interface processing, including error handling.
/// Never throws @a CommandLineError - validation errors are included in the returned stderr content.
/// Note: This uses the @a CommandLineInterface class and does not actually spawn a new process.
/// @param _commandLine Arguments in the form of strings that would be specified on the command-line.
/// You must specify the program name as the first item.
/// @param _standardInputContent Content that the CLI will be able to read from its standard input.
OptionsReaderAndMessages runCLI(
std::vector<std::string> const& _commandLine,
std::string const& _standardInputContent = ""
);
std::string stripPreReleaseWarning(std::string const& _stderrContent);
} // namespace solidity::frontend::test |
# Port Access Control in SONiC
# Table of Contents
- **[List of Tables](#list-of-tables)**
- **[Revision](#revision)**
- **[About this Manual](#about-this-manual)**
- **[Definitions and Abbreviations](#definitions-and-abbreviations)**
- **[1 Feature Overview](#1-feature-overview)**
- [1.1 Port Access Control](#11-port-access-control)
- [1.2 Requirements](#12-requirements)
- [1.2.1 Functional Requirements](#121-functional-requirements)
- [1.2.2 Configuration and Management Requirements](#122-configuration-and-management-requirements)
- [1.2.3 Scalability Requirements](#123-scalability-requirements)
- [1.2.4 Warm Boot Requirements](#124-warm-boot-requirements)
- [1.3 Design Overview](#13-design-overview)
- [1.3.1 Container](#131-container)
- [1.3.2 SAI Support](#132-sai-support)
- **[2 Functionality](#2-functionality)**
- [2.1 Target Deployment Use Cases](#21-target-deployment-use-cases)
- [2.2 Functional Description](#22-functional-description)
- [2.2.1 802.1x](#221-802.1x)
- [2.2.2 MAC Authentication Bypass](#222-mac-authentication-bypass)
- [2.2.3 RADIUS](#223-radius)
- [2.2.4 PAC Interface Host Modes](#224-pac-interface-host-modes)
- [2.2.5 VLAN](#225-vlan)
- [2.2.6 MAC move](#226-mac-move)
- [2.2.7 Warmboot](#227-warmboot)
- **[3 Design](#3-design)**
- [3.1 Overview](#31-overview)
- [3.1.1 Configuration flow](#311-configuration-flow)
- [3.1.2 EAPoL Receive flow](#312-eapol-receive-flow)
- [3.1.3 MAB Packet receive flow](#313-mab-packet-receive-flow)
- [3.1.4 RADIUS](#314-radius)
- [3.2 DB Changes](#32-db-changes)
- [3.2.1 Config DB](#321-config-db)
- [3.2.2 App DB](#322-app-db)
- [3.2.3 ASIC DB](#323-asic-db)
- [3.2.4 Counter DB](#324-counter-db)
- [3.2.5 State DB](#325-state-db)
- [3.3 Switch State Service Design](#33-switch-state-service-design)
- [3.3.1 Orchestration Agent](#331-orchestration-agent)
- [3.4 PAC Modules](#34-pac-modules)
- [3.4.1 Authentication Manager](#341-authentication-manager)
- [3.4.2 mabd](#342-mabd)
- [3.4.3 hostapd](#343-hostapd)
- [3.4.4 hostapdmgrd](#344-hostapdmgrd)
- [3.4.5 Interaction between modules](#345-interaction-between-modules)
- [3.5 SyncD](#35-syncd)
- [3.6 SAI](#36-sai)
- [3.6.1 Host Interface Traps](#361-host-interface-traps)
- [3.6.2 Bridge port learning modes](#362-bridge-port-learning-modes)
- [3.6.3 FDB](#363-fdb)
- [3.6.4 VLAN](#363-vlan)
- [3.7 Manageability](#37-manageability)
- [3.7.1 Yang Model](#371-yang-model)
- [3.7.2 Configuration Commands](#372-configuration-commands)
- [3.7.3 Show Commands](#373-show-commands)
- [3.7.4 Clear Commands](#373-clear-commands)
- **[4 Scalability](#4-scalability)**
- **[5 Appendix: Sample configuration](#5-appendix-sample-configuration)**
- **[6 Future Enhancements](#6-future-enhancements)**
# List of Tables
[Table 1 Abbreviations](#table-1-abbreviations)
# Revision
| Rev | Date | Author | Change Description |
| ---- | ---------- | ---------------------------------------- | ------------------ |
| 0.1 | 04/05/2023 | Amitabha Sen, Vijaya Abbaraju, Shirisha Dasari, Anil Kumar Pandey | Initial version
| 0.2 | 04/02/2024 | Vijaya Abbaraju | Updated the CLI config, show and clear commands.
0.3 | 04/10/2024 | Vijaya Abbaraju | Updated the docker used for PAC and code PRs.
|
# About this Manual
This document describes the design details of the Port Access Control (PAC) feature in SONiC.
# Definitions and Abbreviations
| **Term** | **Meaning** |
| ------------- | ---------------------------------------- |
| Authenticator | An entity that enforces authentication on a port before allowing access to services available on that port |
| CoPP | Control Plane Policing |
| 802.1x | IEEE 802.1x standard |
| EAPoL | Extensible Authentication Protocol over LAN |
| MAB | MAC Authentication Bypass |
| PAC | Port Access Control |
| PAE | Port Access Entity |
| RADIUS | Remote Authentication Dial In User service |
| Supplicant | A client that attempts to access services offered by the Authenticator |
| AAA | Authentication, Authorization, Accounting |
# 1 Feature Overview
## 1.1 Port Access Control
Port Access Control (PAC) provides a means of preventing unauthorized access by users to the services offered by a Network.
An entity (Port Access Entity) can adopt one of two distinct roles within an access control interaction:
1. Authenticator: An entity that enforces authentication on a port before allowing access to services available on that port.
2. Supplicant: A client that attempts to access services offered by the Authenticator.
Additionally, there exists a third role:
3. Authentication Server: Performs the authentication function necessary to check the credentials of the Supplicant on behalf of the Authenticator.
Port access control is achieved by enforcing authentication of Supplicants that are attached to an Authenticator's controlled Ports. The result of the authentication process determines whether the Supplicant is authorized to access services on that controlled port.
All three roles are required in order to complete an authentication exchange. A Switch needs to support the Authenticator role, as is supported by PAC. The Authenticator PAE is responsible for communicating with the Supplicant, submitting the information received from the Supplicant to the Authentication Server in order for the credentials to be checked. The Authenticator PAE controls the authorized/unauthorized state of the clients on the controlled port depending on the outcome of the authentication process.
## 1.2 Requirements
### 1.2.1 Functional Requirements
***PAC***
The following are the requirements for Port Access Control feature:
1. PAC should be supported on physical interfaces only.
2. PAC should enforce access control for clients on switch ports using the following authentication mechanisms:
- 802.1x
- MAB (MAC Authentication Bypass).
3. It should be possible to enable both 802.1x and MAB on a port together. Their relative order and priority should be configurable.
4. The following Host modes should be supported
- Multiple Hosts mode: only one client can be authenticated on a port and after that access is granted to all clients connected to the port
- Single-Host mode: one client can be authenticated on a port and is granted access to the port at a given time.
- Multiple Authentication mode: multiple clients can be authenticated on a port and these clients are then granted access. All clients are authorized on the same VLAN.
5. The following PAC port modes should be supported:
- Auto : Authentication is enforced on the port. Traffic is only allowed for authenticated clients
- Force Authorized : All traffic is allowed.
- Force Unauthorized : All traffic is blocked.
6. Reauthentication of clients is supported.
***802.1x***
PAC should support 802.1x Authenticator functionality.
***MAB***
PAC should support MAB for authentication, primarily to support clients that do not support 802.1x.
***RADIUS***
1. PAC should support RADIUS client functionality to be able to authenticate clients using RADIUS.
2. PAC 802.1x should support multiple EAP authentication methods like EAP-MD5, EAP-PEAP, EAP-TLS, etc.
3. PAC MAB should support the EAP authentication methods EAP-MD5, EAP-PAP and EAP-CHAP.
4. The following Authorization attributes from RADIUS should be supported:
- VLAN
- Session-Timeout
- Session-Termination-Action
5. RADIUS authentication should be tested/qualified with the following RADIUS Servers:
- FreeRADIUS
- ClearPass
- Cisco ISE.
### 1.2.2 Configuration and Management Requirements
PAC should support configuration using CLI and JSON based input.
List of configuration shall include the following:
- configuring the port control mode of an interface.
- configuring the host mode of an interface.
- configuring the PAE role of an interface.
- enabling the 802.1x authentication support on the switch.
- enabling MAC Authentication Bypass (MAB) on an interface.
- enabling the authentication method of MAC Authentication Bypass (MAB) on an interface.
- configuring the maximum number of clients supported on an interface when multi-authentication host mode is enabled on the port.
- enabling periodic reauthentication of the supplicant on an interface.
- enabling periodic reauthentication timer configuration of the supplicant on an interface.
- configuring the order of authentication methods used on a port.
- configuring the priority for the authentication methods used on a port.
### 1.2.3 Scalability Requirements
16 authenticated clients per port with a maximum of 128 authenticated clients per switch should be supported.
## 1.3 Design Overview
### 1.3.1 Container
The "pac" docker holds all the port security applications. Code changes are also made to the SWSS docker.
### 1.3.2 SAI Support
No changes to SAI spec for supporting PAC.
# 2 Functionality
## 2.1 Target Deployment Use Cases
The following figure illustrates how clients like PCs and printers are authenticated and authorized for accessing the network.

**Figure 1 : PAC target deployment use cases**
## 2.2 Functional Description
PAC uses authentication methods 802.1x and MAB for client authentication. These methods in turn use RADIUS for client credential verification and receive the authorization attributes like VLANs, for the authenticated clients.
### 2.2.1 802.1x
PAC leverages the IEEE 802.1X-2004 for 802.1x standard as available in the "hostapd" implementation in the sonic-wpa-supplicant folder. It is an IEEE Standard for Port Access Control that provides an authentication mechanism to devices wishing to attach to a LAN. The standard defines Extensible Authentication Protocol over LAN (EAPoL), which is an encapsulation technique to carry EAP packets between the Supplicant and the Authenticator. The standard describes an architectural framework within which authentication and consequent actions take place. It also establishes the requirements for a protocol between the Authenticator and the Supplicant, as well as between the Authenticator and the Authentication server.
### 2.2.2 MAC Authentication Bypass
PAC makes use of MAC Authentication Bypass (MAB) feature to authenticate devices like cameras or printers which do not support 802.1x. MAB makes use of the device MAC address to authenticate the client.
### 2.2.3 RADIUS
***Authentication***
PAC (Authenticator) uses an external RADIUS server for client authentication. It determines the authorization status of the clients based on RADIUS Access-Accept or Access-Reject frames as per the RADIUS RFC 2865.
PAC as a PAE Authenticator for 802.1x is essentially a passthrough for client Authentication exchange messages. Hence different EAP authentication methods like EAP-MD5, EAP-PEAP, EAP-TLS, etc. are supported. These are essentially the 802.1x Supplicant and RADIUS server functionalities.
PAC as a PAE Authenticator for MAB mimics the Supplicant role for MAB clients. Authentication methods EAP-MD5, EAP-PAP and EAP-CHAP are supported.
***Authorization***
Once a client is authenticated, authorization parameters from RADIUS can be sent for the client. The Authenticator switch processes these RADIUS attributes to apply to the client session. Following attributes are supported.
- *VLAN Id*: This is the VLAN ID sent by a RADIUS server for the authenticated client. This VLAN should be a pre-created VLAN on the switch.
- *Session Timeout*: This is the timeout attribute of the authenticated client session.
- *Session Termination Action*: Upon session timeout, the Session Termination Action determines the action on the client session. The following actions are defined:
- *Default*: The client session is torn down and authentication needs to be restarted for the client.
- *RADIUS*: Re-authentication is initiated for the client.
### 2.2.4 PAC Interface Host Modes
PAC works with port learning modes and FDB entries to block or allow traffic for authenticated clients as needed.
- **Multiple Host mode**: A single client can be authenticated on the port. With no client authenticated on the port, the learning mode is set to DROP or CPU_TRAP (if MAB is enabled on the port). Once a client is authenticated on a port, the learning mode is set to HW. All clients connected to the port are allowed access and FDB entries are populated dynamically.
- **Single Host and Multiple Authentication Modes**: All clients on the port need to authenticate. The learning mode of the port is always set to CPU_TRAP. Once a client starts the authentication process, the client is no longer unknown to PAC. PAC installs a static FDB entry to mark the client known so that the incoming traffic does not flood the CPU. The entry is installed with discard bits set to prevent client traffic from being forwarded. In effect, the packets are not flooded to the CPU nor forwarded to other ports during the authentication process. When the client is authenticated, the discard bits of the installed FDB entry are reset to allow client traffic.
### 2.2.5 VLAN
1. PAC associates authenticated clients to a VLAN on the port.
2. If RADIUS assigns a VLAN to a client, the port's configured untagged VLAN membership is reverted and the RADIUS assigned VLAN is used to authorize the client. The RADIUS assigned VLAN is operationally configured as the untagged VLAN of the port. All incoming untagged client traffic is assigned to this VLAN. Any incoming client's tagged traffic will be allowed or dropped based on if it matches the port's configured untagged VLAN or not.
3. If RADIUS does not assign a VLAN to a client, the port's configured untagged VLAN is used to authorize the client. The port's untagged VLAN configuration is retained and all incoming untagged client traffic is assigned to this VLAN. Any incoming client's tagged traffic will be allowed or dropped based on if it matches the port's configured untagged VLAN or not.
4. All clients on a port are always associated with a single VLAN.
5. The RADIUS assigned VLAN configured is reverted to the port's configured untagged VLAN once the last authenticated client on the port logs off.
6. When PAC is disabled on the port, the operationally added untagged VLAN, if present, is removed from the port and the user configured untagged VLAN is assigned back to the port.
7. If clients are authorized on the port's configured untagged VLAN and the VLAN configuration is modified, all the authenticated clients on the port are removed.
8. If clients are authorized on RADIUS assigned VLAN, any updates on the port's configured untagged VLAN does not affect the clients. The configuration is updated in the CONFIG_DB but not propagated to the port.
### 2.2.6 MAC move
If a client that is authorized on one port moves to another port controlled by PAC, the existing client session is torn down and the authentication is attempted again on the new port.
### 2.2.7 Warmboot
After a Warm Boot, the authenticated client sessions are torn down and they need to authenticate again.
# 3 Design
## 3.1 Overview
[Figure 2](#configuration-flow) shows the high level design overview of PAC services in SONiC. The "pac" docker is used for this functionality.
PAC is composed of multiple sub-modules.
1. pacd: PAC daemon is the main module that controls client authentication. It is the central repository of PAC clients. It makes use of hostapd and mabd daemons to authenticate clients via 802.1x and MAB respectively.
2. hostapd: This 802.1x module is an opensource Linux application that is available in the SONiC sonic-wpa-supplicant folder. It uses hostapd.conf as its config file.
3. mabd: This is the MAB authentication module.
4. hostapdmgrd: This is the hostapd manager module. It listens to 802.1x specific configurations from CONFIG_DB and translates them to respective hostapd.conf file config entries and commands to hostapd.
### 3.1.1 Configuration flow

**Figure 2: PAC service daemon and configuration flow**
1. Mgmt interfaces like CLI write the user provided configuration to CONFIG_DB.
2. The pacd, mabd and hostapdmgrd gets notified about their respective configurations.
3. hostapd being a standard Linux application gets its configuration from a hostapd.conf file. hostapdmgrd generates the hostapd.conf file based on the relevant CONFIG_DB tables. hostapdmgrd informs hostapd about the list of ports it needs to run on. This port list is dynamic as it depends of port link/admin state, port configuration etc. hostapdmgrd keeps hostapd updated about these changes.
4. These modules communicate amongst themselves via socket messages.
5. hostapd listens to EAPoL PDUs on the provided interface list. When it receives a PDU, it consults pacd and proceeds to authenticate the client. pacd also listens to "unknown src MAC" and triggers MAB, if configured on the port, to authenticate the client.
### 3.1.2 EAPoL receive flow

**Figure 3: EAPoL receive flow**
1. EAPoL packet is received by hardware on a front panel interface and trapped to the CPU by COPP rules for EAP. The packet gets delivered to the hostapd socket listening on EtherType 0x888E.
2. In a multi-step process, hostapd runs the 802.1x state machine to Authenticate the client via RADIUS.
3. On successful authentication of a client, hostapd sends a "Client Authenticated" message to pacd with all the authorization parameters like VLAN, Session-Timeout, etc.
4. pacd proceeds to authorize the client. RADIUS authorization parameters like client VLAN membership, is communicated to relevant modules (VLAN, FDB) by writing on their tables on STATE_DB. Authenticated clients are updated in PAC_AUTHENTICATED_CLIENT_OPER table in STATE_DB.
5. VLAN, FDB further process these STATE_DB updates from PAC and write into their STATE_DB and APPL_DB tables.
6. Orchagent in SWSS docker gets notified about changes in APPL_DB and responds by translating the APPL_DB changes to respective sairedis calls.
7. Sairedis APIs write into ASIC_DB.
8. Syncd gets notified of changes to ASIC_DB and in turn calls respective SAI calls. The SAI calls translate to respective SDK calls to program hardware.
9. EAP Success message (EAPoL PDU) is sent to the client.
### 3.1.3 MAB packet receive flow

**Figure 4: MAB PDU receive flow**
1. Unknown source MAC packets are received by hardware on a front panel interface and trapped to CPU. The packets gets delivered to a pacd socket.
2. pacd sends a "Client Authenticate" message along with the received packet MAC to mabd.
3. mabd interacts with RADIUS server to authenticate the given client based on the MAC.
4. On successful authentication of a client, mabd sends an "Client Authenticated" message to pacd with all the authorization parameters like VLAN, Session-Timeout, etc.
5. pacd proceeds to authorize the client. RADIUS authorization parameters like client VLAN membership, is communicated to relevant modules (VLAN, FDB) by writing on their tables on STATE_DB. Authenticated clients are updated in PAC_AUTHENTICATED_CLIENT_OPER table in STATE_DB.
6. VLAN, FDB further process these STATE_DB updates from PAC and write into their STATE_DB and APPL_DB tables.
7. Orchagent in SWSS docker gets notified about changes in APPL_DB and responds by translating the APPL_DB changes to respective sairedis calls.
8. Sairedis APIs write into ASIC_DB.
9. Syncd gets notified of changes to ASIC_DB and in turn calls respective SAI calls. The SAI calls translate to respective SDK calls to program hardware.
10. EAP success message (EAPoL PDU) is sent to the client.
### 3.1.4 RADIUS
PAC uses the RADIUS client from hostapd.
PAC supports only 1 RADIUS server. The highest priority server will be picked up for authentication.
## 3.2 DB Changes
### 3.2.1 Config DB
**PAC_PORT_CONFIG**
```
"PAC_PORT_CONFIG": {
"Ethernet1": {
"method_list": [
"dot1x",
"mab"
],
"priority_list": [
"dot1x",
"mab"
],
"port_pae_role": "authenticator",
"port_control_mode": "auto",
"host_control_mode": "multi_auth",
"reauth_period": 60,
"reauth_enable": "true",
"max_users_per_port": 16,
}
}
key = PAC_PORT_CONFIG:port ;Physical port
;field = value
method_list = "dot1x"/"mab" ;List of methods to be used for authentication
priority_list = "dot1x"/"mab" ;Relative priority of methods to be used for authentication
port_pae_role = "none"/"authenticator" ;"none": PAC is disabled on the port
"authenticator": PAC is enabled on the port
port_control_mode = "auto"/"force_authorized"/ ;"auto": authentication enforced on port
"force_unauthorized" ; "force_authorized": authentication not enforced on port
"force_unauthorized": authentication not enforced on port but port is blocked for all traffic
host_control_mode = "multi-host"/ ;"multi-host": One data client can be authenticated on the port. Rest of the
"multi-auth"/"single-auth" clients tailgate once the first client is authenticated.
"multi-auth": Multiple data client and one voice client can be authenticated on the port.
"single-auth": One data client or one voice client can be authenticated on the port.
reauth_period = 1*10DIGIT ;The initial value of the timer that defines the period after which the will
reauthenticate the Supplicant. Range is 1 - 65535 seconds.
reauth_enable = "true"/"false" ;Indicates whether Reauthentication is enabled on the port.
max_users_per_port = 1*2DIGIT ;Maximum number of clients that can be authenticated on the port. This is applicable
only for "multi-auth" host mode. Range is 1 - 16 clients.
```
**HOSTAPD_GLOBAL_CONFIG**
```
"HOSTAPD_GLOBAL_CONFIG": {
"global": {
"dot1x_system_auth_control": "enable"
}
}
;field = value
dot1x_system_auth_control "true"/"false" ; Indicates whether 802.1x is enabled in the system.
```
**MAB_PORT_CONFIG**
```
"PAC_PORT_CONFIG": {
"Ethernet1": {
"mab": "enable",
"mab_auth_type": "eap-md5",
}
}
key = PAC_PORT_CONFIG:port ;Physical port
;field = value
mab = "enable"/"disable" ;Indicates whether MAB is enabled on the port.
mab_auth_type = "eap-md5"/"pap"/"chap' ;MAB authentication type
```
### 3.2.2 App DB
```
"VLAN_MEMBER_TABLE: {
"Vlan10:Ethernet1": {
"dynamic": "yes",
"tagging_mode": "untagged"
}
}
key = VLAN_MEMBER_TABLE:Vlan:Port ;Vlan and Physical port
;field = value
dynamic = "yes"/"no" ;"yes" = configured, "no" = assigned by RADIUS
tagging_mode = "untagged"/"tagged" ;Vlan tagging mode
```
```
"PORT_TABLE: {
"Ethernet1": {
"learn_mode": "drop",
"pvid": "10"
}
},
```
### 3.2.3 ASIC DB
None
### 3.2.4 Counter DB
None
### 3.2.5 State DB
**PAC_PORT_OPER**
```
"PAC_PORT_OPER": {
"Ethernet1": {
"enabled_method_list": [
"dot1x",
"mab"
],
"enabled_priority_list": [
"dot1x",
"mab"
]
}
}
key = PAC_PORT_OPER:port ;Physical port
;field = value
enabled_method_list = "dot1x"/"mab" ;List of methods to be used for authentication
enabled_priority_list = "dot1x"/"mab" ;Relative priority of methods to be used for authentication
```
**PAC_AUTHENTICATED_CLIENT_OPER**
```
"PAC_AUTHENTICATED_CLIENT_OPER": {
"Ethernet1": [
{
"00:00:00:11:02:33": {
"authenticated_method": "dot1x",
"session_timeout": 60,
"user_name": "sonic_user",
"termination_action": 0,
"vlan_id": 194,
"session_time": 511,
}
},
{
"00:00:00:21:00:30": {
"authenticated_method": "dot1x",
"session_timeout": 60,
"user_name": "sonic_user1",
"termination_action": 0,
"vlan_id": 194,
"session_time": 51,
}
}
]
}
key = PAC_AUTHENTICATED_CLIENTS_OPER: mac ; Client MAC address
;field = value ;
authenticated_method = "dot1x"/'mab" ; Method used to authenticate the client
session_timeout = 1*10DIGIT ; Client session timeout
user_name = 1*255VCHARS ; Client user name
termination_action = 1DIGIT ; Client action on session timeout:
;0: Terminate the client
;1: Reauthenticate the client
vlan_id = 1*4DIGIT ; VLAN associated with the authorized client
session_time = 1*10DIGIT ; Client session time.
```
***PAC_GLOBAL_OPER***
```
"PAC_GLOBAL_OPER": {
"global": {
"num_clients_authenticated": 10
}
}
;field = value
num_clients_auth = 1*10DIGIT ;number of clients authenticated
```
***STATE_OPER_PORT***
```
"STATE_OPER_PORT": {
{
"Ethernet0": {
"learn_mode": "cpu_trap",
"acquired": "true",
}
}
}
;field = value
learn_mode = 1*255VCHARS ; learn mode
acquired = 1*255VCHARS ; whether the port is acquired by PAC
```
***STATE_OPER_VLAN***
```
"STATE_OPER_VLAN_MEMBER": {
"Vlan10": [
{
"Ethernet0": {
"tagging_mode": "untagged",
}
}
]
}
;field = value
tagging_mode = 1*255VCHARS ; tagging mode
```
***STATE_OPER_FDB***
```
"STATE_OPER_FDB": {
"Vlan10": [
{
"00:00:00:00:00:01": {
"port": "Ethernet0",
"type": "static",
}
}
]
}
;field = value
port = 1*255VCHARS ; port
type = 1*255VCHARS ; FDB entry type
```
## 3.3 Switch State Service Design
### 3.3.1 Vlan Manager
VLAN Manager processes updates from "pacd" through STATE DB updates and propagates the Port learning mode, Port PVID and VLAN member updates to APP DB for further processing by OA.
### 3.3.2 Orchestration Agent
OA processes updates from APP DB for setting the Port learning mode, VLAN membership and PVID and passes down the same to SAI Redis library for updating the ASIC DB.
## 3.4 PAC Modules
### **3.4.1 Authentication Manager**
Authentication Manager is the central component of the pacd process.
Authentication Manager enables configuring various Port Modes, Authentication Host Modes. These modes determine the number of clients and the type of clients that can be authenticated and authorized on the ports.
Authentication Manager also enables configuring the authentication methods to be used for authenticating clients on a port. By default the configured authentication methods are tried in order for that port. The below authentication methods can be configured for each port.
- 802.1X
- MAB
In the event that a port is configured for 802.1X and MAB in this sequence, the port will first attempt to authenticate the user through 802.1X. If 802.1X authentication times out, the switch will attempt MAB. The automatic sequencing of authentication methods allows the network administrator to apply the same configuration to every access port without having to know in advance what kind of device (employee or guest, printer or PC, IEEE 802.1X capable or not, etc.) will be attached to it.
Authentication Manager allows configuring priority for each authentication method on the port. If the client is already authenticated using MAB and 802.1X happens to have higher priority than MAB, if a 802.1X frame is received, then the existing authenticated client will be authenticated again with 802.1x. However if 802.1X is configured at a lower priority than the authenticated method, then the 802.1X frames will be ignored.
After successful authentication, the authentication method returns the Authorization parameters for the client. Authentication Manager uses these parameters for configuring the switch for allowing traffic for authenticated clients. If Authentication Manager cannot apply any of the authorization attributes for a client, client authentication will fail.
Client reauthentication is also managed by this module.
If RADIUS sends a Session timeout attribute with Termination action RADIUS (reauthenticate) or Default (clear client session), this module manages the client session timers for reauthentication or client cleanup.
### 3.4.2 mabd
mabd provides the MAC Authentication Bypass (MAB) functionality. MAB is intended to provide 802.1x unaware clients controlled access to the network using the devices’ MAC address as an identifier. This requires that the known and allowable MAC address and corresponding access rights be pre-populated in the authentication server.
PAC supported authentication methods for MAB are as given below:
- CHAP
- EAP-MD5
- PAP
### 3.4.3 hostapd
Hostapd is an open source implementation of 802.1x standard and the Linux application is supplied with wpa_suplicant package. The wired driver module of hostapd is adapted to communicate with pacd via socket interface
. hostapd gets its configuration from the hostapd.conf file generated by hostapdmgrd.
### 3.4.4 hostapdmgrd
hostapdmgr reads hostapd specific configuration from SONiC DBs and populates the hostapd.conf. It further notifies the hostapd to re-read the configuration file.
### 3.4.5 Interaction between modules
*hostapd(802.1X)*
hostapd comes to know of an 802.1x client attempting authentication via an EAP exchange. It informs pacd of this client by conveying the client MAC. If the authentication method selected by pacd is 802.1X, pacd sends an event to hostapd for authenticating the user. The client is however authenticated via MAB If the authentication method selected here is MAB.
hostapd informs pacd about the result of the authentication. hostapd also passes all the authorization parameters it receives from the RADIUS Server to the pacd. These are used for configuring the switch to allow authenticated client traffic.
*mabd(MAB)*
When user or client tries to authenticate and the method selected is MAB, the pacd sends an event to mabd for authenticating the user. The client’s MAC address is sent to mabd for the same.
pacd learns client’s MAC address through an hardware rule to Trap-to-CPU the packets from unknown source MAC addresses.
mabd informs pacd about the result of the authentication. mabd also passes all the authorization parameters it receives from the RADIUS Server to the pacd. These are used for configuring the NAS to allow authenticated client traffic.
## 3.5 SyncD
No specific changes are needed in syncd for PAC.
## 3.6 SAI
Existing SAI attributes are used for this implementation and there is no new SAI attribute requirement.
### 3.6.1 Host interface traps
Leveraged **SAI_HOSTIF_TRAP_TYPE_EAPOL** to trap EAP packets (Ethertype - 0x888E) to the CPU.
### 3.6.2 Bridge port learning modes
PAC uses the following bridge port learning modes to drop/trap all unknown source MAC packets.
- SAI_BRIDGE_PORT_FDB_LEARNING_MODE_DROP
- SAI_BRIDGE_PORT_FDB_LEARNING_MODE_HW
- SAI_BRIDGE_PORT_FDB_LEARNING_MODE_CPU_TRAP
### 3.6.3 FDB
PAC uses **SAI_FDB_ENTRY_ATTR_PACKET_ACTION** with **SAI_PACKET_ACTION_DROP** to put the static FDB entry in discard state.
**SAI_PACKET_ACTION_FORWARD** is used to put the static FDB entry into forwarding state post successful client authentication.
## 3.7 Manageability
### 3.7.1 Yang Model
Yang Models are available for managing PAC, hostapd and MAB modules. SONiC YANG is added as part of this contribution.
### 3.7.2 Configuration Commands
The following commands are used to configure PAC.
| CLI Command | Description |
| :--------------------------------------- | :--------------------------------------- |
| config interface authentication port-control <interface\> <auto \| force-authorized \| force-unauthorized \> | This command configures the authentication mode to use on the specified interface. Default is force-authorized. |
| config interface dot1x pae <interface\> <authenticator \| none\> | This command sets the PAC role on the port. Default is none. Role authenticator enables PAC on the port. |
| config interface authentication host-mode <interface\> <multi-auth \| multi-host \| single-host \> | This command configures the host mode on the specified interface. Default is multi-host. |
| config dot1x system-auth-control <enable\|disable\> | This command configures 802.1x globally. Default is disabled. |
| config interface authentication max-users <interface\> <max-users\> | This command configures max users on the specified interface. The count is applicable only in the multiple authentication host mode. Default is 16. |
| config interface mab <interface\> <enable\|disable\> \[ auth-type <pap \| eap-md5 \| chap \>\] | This command configures MAB on the specified interface with the specified MAB authentication type. MAB is disabled by default. Default auth-type is eap-md5. |
| config interface authentication periodic <interface\> <enable\|disable> | This command enables periodic reauthentication of the supplicants on the specified interface. Default is disabled. |
| config interface authentication reauth-period <interface\> <seconds \| server\> | This command configures the reauthentication period of supplicants on the specified interface. The 'server' option is used to fetch this period from the RADIUS server. The 'seconds' option is used to configure the period locally. Default is 'server'. |
| config interface authentication order <interface\> <dot1x \[ mab \] \| mab \[ dot1x \]> | This command is used to set the order of authentication methods used on a port. Default order is 802.1x,mab. |
| config interface authentication priority <interface\> <dot1x \[ mab \] \| mab \[ dot1x \]> | This command is used to set the priority of authentication methods used on a port. Default priority is 802.1x,mab. |
### 3.7.3 Show Commands
**show authentication interface**
This command displays the authentication manager information for the enabled interfaces
root@sonic:/home/admin#
root@sonic:/home/admin# show authentication interface
Interface Port-Control Host-Mode Pae-Role Max-Users Reauth Reauth-Period Reauth-from-Serer config-methods config-priority enabled-methods enabled-priority
----------- -------------- ----------- ------------- ----------- -------- --------------- ------------------- ---------------- ----------------- ----------------- ------------------
Ethernet0 auto multi-auth authenticator 16 disabled 60 False dot1x dot1x,mab dot1x,undefined dot1x,undefined
root@sonic:/home/admin#
**show authentication interface -i Ethernet0**
This command displays the authentication manager information for the specified interface
```
root@sonic:/home/admin# show authentication interface -i Ethernet0
Interface Port-Control Host-Mode Pae-Role Max-Users Reauth Reauth-Period Reauth-from-Serer config-methods config-priority enabled-methods enabled-priority
----------- -------------- ----------- ------------- ----------- -------- --------------- ------------------- ---------------- ----------------- ----------------- ------------------
Ethernet0 auto multi-auth authenticator 16 disabled 60 False dot1x dot1x,mab dot1x,undefined dot1x,undefined
root@sonic:/home/admin#
```
**show authentication interface -i Ethernet0**
This command displays the details authenticated clients.
```
root@sonic:/home/admin# show authentication clients
Authenticated Clients : 1
Interface mac-addr user-name vlan
----------- ----------------- ----------- ------
Ethernet0 00:11:01:00:00:01 usr1 20
root@sonic:/home/admin#
```
**show authentication interface -i Ethernet0**
This command displays the details authenticated clients on specified interface.
```
root@sonic:/home/admin# show authentication clients -i Ethernet0
Authenticated Clients : 1
Interface mac-addr user-name vlan
----------- ----------------- ----------- ------
Ethernet0 00:11:01:00:00:01 usr1 20
root@sonic:/home/admin#
```
**show mab <cr | interface\>**
This command is used to show a summary of the global mab configuration and summary information of the mab configuration for all ports.
```
root@sonic:/home/admin# show mab interface
Interface MAB Enabled auth-type
----------- ------------- -----------
Ethernet1 True pap
root@sonic:/home/admin#
```
**show mab <cr | interface\> -i Ethernet1**
This command also provides the detailed mab configuration for a specified port
root@sonic:/home/admin# show mab interface -i Ethernet1
```
Interface MAB Enabled auth-type
----------- ------------- -----------
Ethernet1 True pap
root@sonic:/home/admin#
```
**show dot1x**
This command is used to show a summary of the global 802.1x configuration.
```
root@sonic:/home/admin# show dot1x
802.1X admin mode : Enabled
root@sonic:/home/admin#
```
### 3.7.4 Clear Commands
**sonic-clear authenticaton sessions**
This command clears information for all Auth Manager sessions. All the authenticated clients are re-initialized and forced to authenticate again.
```
root@sonic:/home/admin# sonic-clear authentication sessions
```
**sonic-clear authenticaton sessions -i \<interface\>**
This command clears information for all Auth Manager sessions on the specified interface.
```
root@sonic:/home/admin# sonic-clear authentication sessions -i Ethernet0
```
**sonic-clear authenticaton sessions -m \<mac-addr\>**
This command clears information for specified client.
```
root@sonic:/home/admin# sonic-clear authentication sessions -m 00:00:00:11:22:33
```
# 4 Scalability
The following scale is supported:
| Configuration / Resource | Scale |
| ---------------------------------------- | ----- |
| Total number of authenticated clients on a port configured in Multiple Authentication host mode | 16 |
| Total number of authenticated clients supported by the switch | 128 |
# 5 Appendix: Sample configuration
```
config interface startup Ethernet0
config vlan add 10
config vlan member add 10 Ethernet0 -u
config radius add 10.10.10.1
config radius passkey mypasskey
config dot1x system-auth-control enable
config interface authentication port-control Ethernet0 auto
config interface authentication host-mode Ethernet0 multi-auth
config interface authentication order Ethernet0 dot1x
config interface authentication priority Ethernet0 dot1x
config interface dot1x pae Ethernet0 authenticator
config interface authentication periodic Ethernet1 enable
config interface authentication reauth-period Ethernet1 120
config interface authentication max-users Ethernet1 6
config interface mab Ethernet1 enable -a pap
```
# 6 Future Enhancements
1. Add configurability support for 802.1x and MAB timers.
2. Add support for fallback VLANs like Guest, Unauth etc. VLAN. These are used to authorize clients if they fail authentication under various circumstances.
3. Add support for RADIUS Authorization attributes like ACLs.
4. Add support for multiple RADIUS servers.
# 7 Code PRs
| Repo | Title | PR |
|--|--| --|
| sonic-wpa-supplicant |sonic-wpasupplicant changes for PAC | https://github.com/sonic-net/sonic-wpa-supplicant/pull/88 |
| sonic-wpa-supplicant |Changes to support PAC and 802.1X interaction | https://github.com/sonic-net/sonic-wpa-supplicant/pull/89 |
| sonic-wpa-supplicant |Changes in HOSTAPD to Support PAC | https://github.com/sonic-net/sonic-wpa-supplicant/pull/90 |
| sonic-wpa-supplicant |HOSTPAD driver changes for PAC | https://github.com/sonic-net/sonic-wpa-supplicant/pull/91 |
| sonic-utilities |CLI support for PAC | https://github.com/sonic-net/sonic-utilities/pull/3265 |
| sonic-buildimage |Docker and Makefile changes for PAC | https://github.com/sonic-net/sonic-buildimage/pull/18616 |
| sonic-buildimage |Changes to handle PAC operational info | https://github.com/sonic-net/sonic-buildimage/pull/18618 |
| sonic-buildimage |Changes to Handle PAC Mgr updates | https://github.com/sonic-net/sonic-buildimage/pull/18619 |
| sonic-buildimage |PAC changes to receive config updates | https://github.com/sonic-net/sonic-buildimage/pull/18620 |
| sonic-buildimage |Hostapd mgr changes for PAC | https://github.com/sonic-net/sonic-buildimage/pull/18621 |
| sonic-buildimage |JSON lib changes to support PAC | https://github.com/sonic-net/sonic-buildimage/pull/18622 |
| sonic-buildimage |MAB mgr changes for PAC | https://github.com/sonic-net/sonic-buildimage/pull/18623 |
| sonic-buildimage |Makefile changes for PAC | https://github.com/sonic-net/sonic-buildimage/pull/18624 |
| sonic-buildimage |MAB makefile and common header files | https://github.com/sonic-net/sonic-buildimage/pull/18625 |
| sonic-buildimage |MAB common header files | https://github.com/sonic-net/sonic-buildimage/pull/18626 |
| sonic-buildimage |MAB generic files | https://github.com/sonic-net/sonic-buildimage/pull/18627 |
| sonic-buildimage |MAB control function changes | https://github.com/sonic-net/sonic-buildimage/pull/18628 |
| sonic-buildimage |MAB protocol related header files | https://github.com/sonic-net/sonic-buildimage/pull/18629 |
| sonic-buildimage |MAB protocol related changes | https://github.com/sonic-net/sonic-buildimage/pull/18630 |
| sonic-buildimage |Auth mgr Makefile and common header files | https://github.com/sonic-net/sonic-buildimage/pull/18631 |
| sonic-buildimage |Auth mgr generic header files | https://github.com/sonic-net/sonic-buildimage/pull/18632 |
| sonic-buildimage |Authmgr event handling and other functionality| https://github.com/sonic-net/sonic-buildimage/pull/18633 |
| sonic-buildimage |Auth mgr API interface functions| https://github.com/sonic-net/sonic-buildimage/pull/18634 |
| sonic-buildimage |Authmgr include files for authentication functionality | https://github.com/sonic-net/sonic-buildimage/pull/18635 |
| sonic-buildimage |Auth mgr functionality changes | https://github.com/sonic-net/sonic-buildimage/pull/18636 |
| sonic-buildimage |PAC infra Makefile changes | https://github.com/sonic-net/sonic-buildimage/pull/18637 |
| sonic-buildimage |PAC infra sonic interface files | https://github.com/sonic-net/sonic-buildimage/pull/18638 |
| sonic-buildimage |PAC infra header files| https://github.com/sonic-net/sonic-buildimage/pull/18639 |
| sonic-buildimage |PAC infra files| https://github.com/sonic-net/sonic-buildimage/pull/18640 |
| sonic-buildimage |PAC infra util changes for logging| https://github.com/sonic-net/sonic-buildimage/pull/18641 |
| sonic-buildimage |PAC infra utils changes for sim| https://github.com/sonic-net/sonic-buildimage/pull/18642 |
| sonic-buildimage |PAC infra utilities| https://github.com/sonic-net/sonic-buildimage/pull/18643 |
| sonic-buildimage |PAC libinfra tool| https://github.com/sonic-net/sonic-buildimage/pull/18644 |
| sonic-buildimage |PAC Infra OS abstraction files| https://github.com/sonic-net/sonic-buildimage/pull/18645 |
| sonic-buildimage |PAC Infra sysapi files| https://github.com/sonic-net/sonic-buildimage/pull/18646 | |
/* Root CSS variables with fallback */
:root {
--main-bg-color: #f4f4f9;
--main-text-color: #2e4a60; /* Fallback color */
--accent-color: color(srgb 0.1 0.2 0.8);
--button-color: #84713E;
}
/* General styling */
body {
font-family: 'Arial', sans-serif;
color: var(--main-text-color, grey);
background-color: var(--main-bg-color);
}
header {
background-color: rgba(0, 118, 255, 0.1);
margin: auto;
padding: 20px;
position: relative;
}
h1, h2, h3 {
color: hsl(210, 50%, 40%);
}
/* Mixing two colors in sRGB color space */
element {
background-color: #7F7F00; /* Equivalent to mixing blue and yellow in equal parts */
/* New color syntax (if supported) */
background-color: color-mix(in srgb, blue 50%, yellow 50%);
}
nav ul {
list-style-type: none;
padding: 0;
}
nav li {
display: inline-block;
margin-right: 10px;
}
/* Example of a class selector */
.main-content {
margin: auto;
width: 90%;
}
/* Example of ID selectors and absolute units */
#agenda, #recordings {
border: 1px solid #ccc;
padding: 20px;
margin-top: 20px;
}
/* Example of pseudo-classes */
a:hover {
color: #B3B3FF; /* Lighter blue, as an approximation of the color-mix result */
color: color-mix(in srgb, blue 70%, white 30%);
}
/* Flexbox layout for navigation */
nav {
display: flex;
justify-content: space-around;
align-items: center;
}
/* Grid layout for team section */
#team {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 20px;
}
/* Media query for responsiveness */
@media (max-width: 768px) {
#team {
grid-template-columns: 1fr;
}
nav ul {
flex-direction: column;
align-items: center;
}
}
/* Text styling */
p {
line-height: 1.5;
text-align: justify;
}
/* Form styling using attribute selectors
input[type="text"],
input[type="date"],
textarea {
width: 100%;
padding: 8px;
margin-top: 5px;
} */
form {
padding: 20px 20px 20px 20px;
/* Padding */
margin: 20px;
/* Margin */
border-radius: 10px;
/* Border radius */
display: block;
/* Display property */
grid-template-columns: 1fr 1fr;
/* Grid template columns */
grid-template-rows: auto;
grid-gap: 80px;
/* Gap between grid items */
}
/* Flexbox within form for better layout */
/* form {
display: flex;
flex-direction: column;
gap: 10px;
} */
/* Display */
main {
display: flex;
/* Display property */
justify-content: space-around;
/* Flexbox attribute */
align-items: center;
/* Flexbox attribute */
flex-wrap: wrap;
/* Flexbox attribute */
}
img, video {
display: block;
margin: auto;
height: auto;
}
audio {
display: block;
margin: auto;
}
/* Position */
footer {
position: static;
/* Position property */
bottom: 0;
/* Position property */
width: 100%;
/* Width */
background-color: hsl(242, 53%, 31%);
/* Background color */
color: white;
/* Text color */
text-align: center;
/* Text alignment */
padding: 1rem 1rem 1rem 1rem;
/* Padding */
}
button {
display: inline;
background-color: #cb912d;
/* New color syntax (if supported) */
background-color: color(srgb 0.79 0.57 0.16);
color: color-mix(in srgb, #191303 90%, white);
/* Text color */
padding: 10px 20px;
/* Padding */
border-style: solid;
border-color: hsl(44, 60%, 13%);
border-width: 2px;
border-radius: 5px;
/* Border radius */
margin: 10px 10px 0px 0px;
cursor: pointer;
/* Cursor */
}
button:hover {
background-color: var(--button-color, #5c50a1);
/* Background color on hover */
}
button:active {
box-shadow: 2px 2px 5px rgb(101, 96, 94);
}
/* Borders and box model
*/
section {
background-color: rgb(201 221 244);
margin-top: 25px;
margin-right: 20px;
margin-bottom: 20px;
margin-left: 50px;
padding-top: 4vh;
padding-right: 8vh;
padding-bottom: 4vh;
padding-left: 6vh;
border: 2px solid #ccc;
border-bottom-style: ridge;
border-radius: 5mm;
width: 20cm;
min-width: 6cm;
}
#introductions {
background-color: hwb(217 82% 4% / 0.7); /* Sets the background color of agenda section to white */
}
/* Using new selectors like :has() */
div:has(> details) {
background-color: hsla(60, 100%, 90%, 0.5);
}
h1,
h2{
margin: 0 0 1rem 0;
font-family: "Jersey 10", sans-serif;
font-weight: 400;
font-style: normal;
}
h1:has(+ h2) {
margin: 0 0 0.25rem 0;
} |
// src/pages/Login.jsx
import { useState, useEffect, useRef } from "react";
import { useNavigate } from "react-router-dom";
import { gsap } from "gsap";
import styles from "../pages/styles/login.module.css";
const Login = () => {
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [error, setError] = useState(null);
const navigate = useNavigate();
const loginBoxRef = useRef();
useEffect(() => {
gsap.fromTo(
loginBoxRef.current,
{ y: -50, opacity: 0 },
{ y: 0, opacity: 1, duration: 1, ease: "power4.out" }
);
}, []);
const handleLogin = async (e) => {
e.preventDefault();
setError(null);
// Perform login logic here, e.g., send login request to backend
try {
// Make API call to login endpoint
// Replace the following with actual login logic
const response = await fetch("http://localhost:8000/api/users/login", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ email, password }),
});
if (response.ok) {
const userData = await response.json();
const userId = userData.userId;
navigate(`/admin/${userId}`);
} else {
setError("Invalid email or password");
}
} catch (error) {
console.error("Error logging in:", error);
setError("An error occurred. Please try again later.");
}
};
return (
<div className={styles.container}>
<div className={styles.loginBox} ref={loginBoxRef}>
<h2 className={styles.title}>Welcome to Project24</h2>
{error && <p className={styles.errorMessage}>{error}</p>}
<form onSubmit={handleLogin} className={styles.form}>
<div className={styles.inputGroup}>
<label htmlFor="email" className={styles.label}>
Email
</label>
<input
type="text"
id="email"
placeholder="Enter Your Email Address"
value={email}
onChange={(e) => setEmail(e.target.value)}
required
className={styles.input}
/>
</div>
<div className={styles.inputGroup}>
<label htmlFor="password" className={styles.label}>
Password
</label>
<input
type="password"
id="password"
placeholder="Enter Your Password"
value={password}
onChange={(e) => setPassword(e.target.value)}
required
className={styles.input}
/>
</div>
<button type="submit" className={styles.loginButton}>
Login
</button>
</form>
</div>
</div>
);
};
export default Login; |
Sistema de ideas Bonindea:
De El Investigador de las Ideas.
(https://investigadorid.wordpress.com/).
Versión 1.4.
Por cuestiones de gusto y comodidad se sigue escribiendo en
un nuevo renglón cada vez que se llega a la columna 60.
Finalidad:
Crear un formato para esquematizar en forma de texto a
ideas posibilitando la modularidad y la modificación.
Metodología:
Ejemplo:
f{descripción[][]...{{}{}{}}{}{{}{}}{{}}{{{}}{}}...}
Donde:
Las llaves encierran un bloque de datos, texto o
información en general: {bloque}.
Los corchetes encierran una definición: [definición].
"f" es el bloque de orden 0 o el bloque fundamental.
En descripción puede estar datos como si el bloque fue
elegido o no entre otros para una lista de opciones de
bloques, la fecha y los votos.
En las definiciones se coloca algún estándar o clase de
datos que ha de seguirse o instanciarse.
También se puede señalar una característica como
transmisible a los bloques de orden mayor que estén dentro
suyo.
Es buena práctica agregar como característica transmisible
al número identificador de bloque (o id) X1.X2.X3... siendo
esos números Xi separados por puntos números enteros igual
o mayores que 0, siendo 0 o "f" el bloque fundamental.
El si se puede modificar un bloque parcial o totalmente o
no es una decisión libre, aunque se recomienda avisar cómo
se hace esto en una definición, o si sólo se puede en un
subbloque titulado "Historial" dentro de su descripción y
con subbloques de éste como las distintas versiones.
Un bloque que es más reciente que otro se posiciona arriba
de ese otro, para un mismo nivel en común y tiene una X de
subnivel mayor.
Se es libre de decidir si se deja uno o varios renglones
entre los bloques.
Se puede reinterpretar una llave como texto simple
poniéndola dentro de una cadena en entre comillas: "{}".
Se aplica lo mismo para los corchetes además de las llaves:
"[]".
Se puede comentar en o incluso proponer una versión
modificada de un bloque por medio de un subbloque dentro
de éste.
Los archivos bonindea pueden son del tipo ".bonindea" y
cada archivo tiene un sistema bonindea dentro.
Estos archivos se pueden agrupar en proyectos bonindea.
Para mencionar bloques (identificados por su id de bloque)
de un sistema o proyecto específico se menciona su id
completo "((ruta terminando en nombre de directorio + \)
(nombre del archivo).bonindea o (nombre del proyecto), o
ambos separados por "; ")..(id's de bloques separados por
comas y ordenados de menor a mayor)".
Ejemplo: ncinid..0.5.1,2.3,2.5,4,8 (para el proyecto
bonindea "ncinid").
Dentro de una definición puede haber otro sistema bonindea.
Se puede importar desde un bloque a otro bloque, sistema
o proyecto bonindea a partir de su id, sin necesidad de ser
completo si se está en un mismo sistema o proyecto.
Copyright:
El texto de "Sistema de ideas Bonindea" de El Investigador
de las Ideas es una obra original del autor.
Licencia de dicho texto: GPLv3
(https://www.gnu.org/licenses/gpl-3.0.en.html).
© El Investigador de las Ideas
(https://investigadorid.wordpress.com/).
Año 2020.
Linking this library statically or dynamically with
other modules is making a combined work based on this
library. Thus, the terms and conditions of the GNU General
Public License cover the whole combination.
As a special exception, the copyright holders of this
library give you permission to link this library with
independent modules to produce an executable, regardless of
the license terms of these independent modules, and to copy
and distribute the resulting executable under terms of your
choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license
of that module. An independent module is a module which is
not derived from or based on this library. If you modify
this library, you may extend this exception to your version
of the library, but you are not obligated to do so. If you
do not wish to do so, delete this exception statement from
your version. |
from contextlib import contextmanager
import pytest
from flask import g, request
from core.common.exceptions import APIError
from takumi.auth import SIGNATURE_HEADERS, _get_signature, task
from takumi.models import ApiTask
class UrlRule:
def __init__(self, endpoint):
self.endpoint = endpoint
def test_task_decorator_raises_exception_if_no_g_task():
with pytest.raises(Exception) as exc:
wrapped = task(lambda: None)
wrapped()
assert "non-task blueprint" in exc.exconly()
@pytest.fixture(autouse=True, scope="module")
def app_context(app):
pass
@contextmanager
def api_task_request(allowed_views, secret=None, **request_attrs):
old_request_attrs = {}
for attr, value in request_attrs.items():
old_request_attrs[attr] = getattr(request, attr)
setattr(request, attr, value)
setattr(g, "task", ApiTask(allowed_views=allowed_views, secret=secret))
wrapped = task(lambda: None)
yield wrapped
delattr(g, "task")
for attr, value in old_request_attrs.items():
setattr(request, attr, value)
def test_task_decorator_raises_exception_if_endpoint_not_in_allowed_views():
with api_task_request([], url_rule=UrlRule("test.something")) as view:
with pytest.raises(APIError) as exc:
view()
assert "Access denied" in exc.exconly()
def test_task_decorator_does_not_raise_exception_if_endpoint_in_allowed_views():
route = "test.something"
with api_task_request([route], url_rule=UrlRule(route)) as view:
view()
def test_task_decorator_raises_exception_if_secret_missing():
route = "test.something"
with api_task_request([route], "test secret", url_rule=UrlRule(route)) as view:
with pytest.raises(APIError) as exc:
view()
assert "Access denied" in exc.exconly()
def test_task_decorator_raises_exception_if_signature_mismatch():
route = "test.something"
headers = {key: "wrong signature" for key in SIGNATURE_HEADERS}
with api_task_request(
[route], secret="test secret", url_rule=UrlRule(route), headers=headers
) as view:
with pytest.raises(APIError) as exc:
view()
assert "Access denied" in exc.exconly()
def test_task_decorator_does_not_raise_exception_if_signature_found_in_any_valid_header():
route = "test.something"
correct_signature = _get_signature("test secret", "test string")
request_attrs = dict(url_rule=UrlRule(route), data="test string")
for header in SIGNATURE_HEADERS:
request_attrs["headers"] = {header: correct_signature}
with api_task_request([route], "test secret", **request_attrs) as view:
try:
view()
except Exception as exception:
assert False, "Failed for header: {} (exception: {})".format(header, exception)
def test_get_signature_handles_unicode():
expected = "d44616514169dc4e793d99ffd02152ef8fd91f0db313eb3fc1844f49f18d083a"
assert _get_signature("test secret", "test string") == expected
assert _get_signature("test secret", "test string") == expected
assert _get_signature("test secret", "test string") == expected
assert _get_signature("test secret", "test string") == expected |
import React, {useState} from 'react';
import {action} from '@storybook/addon-actions';
import {Accordion, AccordionPropsType} from './Accordion';
import {Story} from '@storybook/react';
export default {
title: 'Accordion stories',
component: Accordion
};
const callback = action('accordion mode change event fired');
const callbackProps = {setCollapsed: callback};
const Template: Story<AccordionPropsType> = (args: AccordionPropsType) => <Accordion {...args} items={[
{title: 'Igor', value: 1},
{title: 'Dimych', value: 2},
{title: 'Viktor', value: 3}]} onClick={callback}/>;
export const MenuCollapsedMode = Template.bind(({}));
MenuCollapsedMode.args = {
titleValue: 'Menu',
collapsed: true,
...callbackProps,
};
export const UsersUncollapsedMode = Template.bind(({}));
UsersUncollapsedMode.args = {
titleValue: 'Users',
collapsed: false,
...callbackProps,
items: [{title: 'Igor', value: 1}, {title: 'Dimych', value: 2}, {title: 'Viktor', value: 3}],
onClick: callback
};
export const ModeChanging = () => {
const [value, setValur] = useState<boolean>(true);
return <Accordion titleValue={'Users'} collapsed={value} setCollapsed={() => setValur(!value)}
items={[{title: 'Igor', value: 1}, {title: 'Dimych', value: 2}, {title: 'Viktor', value: 3}]}
onClick={(id)=>{alert(`user with Id ${id} should be happy`)}}/>;
};
// export const Button = ({
// primary = false,
// size = 'medium',
// backgroundColor,
// label,
// ...props
// }: ButtonProps) => {
// const mode = primary ? 'storybook-button--primary' : 'storybook-button--secondary';
// return (
// <button
// type="button"
// className={['storybook-button', `storybook-button--${size}`, mode].join(' ')}
// style={{ backgroundColor }}
// {...props}
// >
// {label}
// </button>
// );
// }; |
import './App.css';
import React from "react";
import { Routes, Route } from "react-router-dom";
import Layout from "./components/Layout";
import AboutMe from "./pages/AboutMe";
import PostPage from "./pages/PostPage";
import LoginPage from "./pages/LoginPage";
import MyBlog from './pages/MyBlog';
import NewPostForm from './components/NewPostForm';
import LogoutPage from './components/LogoutPage';
import UserPosts from './pages/UserPosts';
import SearchResults from './components/SearchResults';
import FullPost from './components/FullPost';
import TagPage from './components/TagPage.js';
import ContactMe from './components/ContactMe';
function App() {
return (
<>
<Routes>
<Route path="/" element={<Layout />}>
<Route index element={<MyBlog />} />
<Route path="about" element={<AboutMe />} />
<Route path="/contact" element={<ContactMe />} />
<Route path="/:id" element={<PostPage />} />
<Route path="/newpost" element={<NewPostForm />} />
<Route path="/login" element={<LoginPage />} />
<Route path="/logout" element={<LogoutPage />} />
<Route path="/myposts" element={<UserPosts />} />
<Route path="search" element={<SearchResults />} />
<Route path="post/:id" element={<FullPost />} />
<Route path="/tag/:tag" element={<TagPage />} />
</Route>
</Routes>
</>
);
}
export default App; |
package org.leondorus.remill.domain.notifgroups
import org.leondorus.remill.domain.model.NotifGroup
import org.leondorus.remill.domain.model.NotifGroupId
import org.leondorus.remill.domain.model.UsePattern
import org.leondorus.remill.domain.platfromnotifications.PlatformNotificationEditUseCase
class NotifGroupEditUseCase(
private val notifGroupEditRepo: NotifGroupEditRepo,
private val platformNotificationEditUseCase: PlatformNotificationEditUseCase,
) {
suspend fun addNotifGroup(name: String, usePattern: UsePattern): NotifGroup {
val notifGroup = notifGroupEditRepo.addNotifGroup(name, usePattern)
val notifTypes = notifGroup.usePattern.notifTypes
for (time in notifGroup.usePattern.schedule.times) {
platformNotificationEditUseCase.addPlatformNotification(time, notifTypes, notifGroup.id)
}
return notifGroup
}
suspend fun updateNotifGroup(newNotifGroup: NotifGroup) {
if (newNotifGroup.drugs.isNotEmpty())
throw DrugListIsNotEmpty("while updating with $newNotifGroup")
notifGroupEditRepo.updateNotifGroup(newNotifGroup)
platformNotificationEditUseCase.deleteAllPlatformNotificationsWithNotifGroup(newNotifGroup.id)
for (time in newNotifGroup.usePattern.schedule.times) {
platformNotificationEditUseCase.addPlatformNotification(
time,
newNotifGroup.usePattern.notifTypes,
newNotifGroup.id
)
}
}
suspend fun deleteNotifGroup(id: NotifGroupId) {
notifGroupEditRepo.deleteNotifGroup(id)
platformNotificationEditUseCase.deleteAllPlatformNotificationsWithNotifGroup(id)
}
} |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.drools.ruleunits.impl;
import java.util.ArrayList;
import java.util.List;
import org.drools.ruleunits.api.DataHandle;
import org.drools.ruleunits.api.DataProcessor;
import org.drools.ruleunits.api.DataSource;
import org.drools.ruleunits.api.SingletonStore;
import org.junit.jupiter.api.Test;
import org.kie.api.runtime.rule.FactHandle;
import static java.util.Arrays.asList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertSame;
public class SingletonDataStoreTest {
@Test
public void testCreate() {
Probe<Integer> probe = new Probe<>();
SingletonStore<Integer> integers = DataSource.createSingleton();
integers.subscribe(probe);
assertNull(probe.handle);
assertNull(probe.value);
}
@Test
public void testAdd() {
Probe<Integer> probe = new Probe<>();
SingletonStore<Integer> integers = DataSource.createSingleton();
integers.subscribe(probe);
integers.set(1);
integers.set(2);
integers.set(3);
assertThat(probe.handle).isNotNull();
assertEquals(3, probe.value);
assertEquals(asList(1, 2, 3), probe.seen);
}
@Test
public void testRemove() {
Probe<Integer> probe = new Probe<>();
SingletonStore<Integer> integers = DataSource.createSingleton();
integers.subscribe(probe);
integers.set(1);
integers.set(2);
integers.set(3);
integers.clear();
assertNull(probe.handle);
assertNull(probe.value);
}
private static class Probe<T> implements DataProcessor<T> {
DataHandle handle;
T value;
List<T> seen = new ArrayList<>();
@Override
public FactHandle insert(DataHandle handle, T object) {
this.handle = handle;
this.value = object;
this.seen.add(object);
return null;
}
@Override
public void update(DataHandle handle, T object) {
assertSame(handle, this.handle);
if (object != this.value) {
this.value = object;
this.seen.add(object);
}
}
@Override
public void delete(DataHandle handle) {
assertSame(handle, this.handle);
this.handle = null;
this.value = null;
}
}
;
} |
// Copyright 2022:
// GobySoft, LLC (2013-)
// Community contributors (see AUTHORS file)
// File authors:
// Toby Schneider <toby@gobysoft.org>
//
//
// This file is part of the Goby Underwater Autonomy Project Libraries
// ("The Goby Libraries").
//
// The Goby Libraries are free software: you can redistribute them and/or modify
// them under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 2.1 of the License, or
// (at your option) any later version.
//
// The Goby Libraries are distributed in the hope that they will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with Goby. If not, see <http://www.gnu.org/licenses/>.
#ifndef GOBY_MIDDLEWARE_IO_COBS_COMMON_H
#define GOBY_MIDDLEWARE_IO_COBS_COMMON_H
#include <memory>
#include <boost/asio/read.hpp> // for async_read
#include <boost/asio/write.hpp> // for async_write
#include "goby/middleware/protobuf/io.pb.h"
#include "goby/util/binary.h"
#include "goby/util/debug_logger.h" // for glog
#include "goby/util/thirdparty/cobs/cobs.h"
namespace goby
{
namespace middleware
{
namespace io
{
template <class Thread>
void cobs_async_write(Thread* this_thread,
std::shared_ptr<const goby::middleware::protobuf::IOData> io_msg)
{
constexpr static char cobs_eol{0};
// COBS worst case is 1 byte for every 254 bytes of input
auto input_size = io_msg->data().size();
auto output_size_max = input_size + (input_size / 254) + 1;
std::string cobs_encoded(output_size_max, '\0');
auto cobs_size = cobs_encode(reinterpret_cast<const uint8_t*>(io_msg->data().data()),
input_size, reinterpret_cast<uint8_t*>(&cobs_encoded[0]));
if (cobs_size)
{
cobs_encoded.resize(cobs_size);
cobs_encoded += cobs_eol;
goby::glog.is_debug2() && goby::glog << group(this_thread->glog_group()) << "COBS ("
<< cobs_encoded.size() << "B) <"
<< " " << goby::util::hex_encode(cobs_encoded)
<< std::endl;
boost::asio::async_write(this_thread->mutable_socket(), boost::asio::buffer(cobs_encoded),
[this_thread, cobs_encoded](const boost::system::error_code& ec,
std::size_t bytes_transferred) {
if (!ec && bytes_transferred > 0)
{
this_thread->handle_write_success(bytes_transferred);
}
else
{
this_thread->handle_write_error(ec);
}
});
}
else
{
goby::glog.is_warn() && goby::glog << group(this_thread->glog_group())
<< "Failed to encode COBS message: "
<< goby::util::hex_encode(io_msg->data()) << std::endl;
this_thread->handle_write_error(boost::system::error_code());
}
}
template <class Thread, class ThreadBase = Thread>
void cobs_async_read(Thread* this_thread,
std::shared_ptr<ThreadBase> self = std::shared_ptr<ThreadBase>())
{
constexpr static char cobs_eol{0};
boost::asio::async_read_until(
this_thread->mutable_socket(), this_thread->buffer_, cobs_eol,
[this_thread, self](const boost::system::error_code& ec, std::size_t bytes_transferred) {
if (!ec && bytes_transferred > 0)
{
std::string bytes(bytes_transferred, '\0');
std::istream is(&this_thread->buffer_);
is.read(&bytes[0], bytes_transferred);
goby::glog.is_debug2() && goby::glog << group(this_thread->glog_group()) << "COBS ("
<< bytes.size() << "B) >"
<< " " << goby::util::hex_encode(bytes)
<< std::endl;
auto io_msg = std::make_shared<goby::middleware::protobuf::IOData>();
auto& cobs_decoded = *io_msg->mutable_data();
cobs_decoded = std::string(bytes_transferred, '\0');
int decoded_size =
cobs_decode(reinterpret_cast<const uint8_t*>(bytes.data()), bytes_transferred,
reinterpret_cast<uint8_t*>(&cobs_decoded[0]));
if (decoded_size)
{
// decoded size includes final 0 so remove last byte?
cobs_decoded.resize(decoded_size - 1);
this_thread->handle_read_success(bytes_transferred, io_msg);
this_thread->async_read();
}
else
{
goby::glog.is_warn() && goby::glog << group(this_thread->glog_group())
<< "Failed to decode COBS message: "
<< goby::util::hex_encode(bytes)
<< std::endl;
this_thread->handle_read_error(ec);
}
}
else
{
this_thread->handle_read_error(ec);
}
});
}
} // namespace io
} // namespace middleware
} // namespace goby
#endif |
<template>
<app-modal name="digital-certificate-modal"
@before-open="beforeOpen"
:title="title"
width="70%"
hide-footer>
<div class="container-fluid">
<div class="row">
<div class="col-sm-12 mb-4 text-right">
<button class="btn btn-primary" @click="create()">{{$t('app.add')}}</button>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<app-table
:filter="false"
:pagination="false"
ref="table"
:api-mode="false"
:data="certificates"
:fields="fields"
>
<div slot="action" slot-scope="props">
<button v-if="!props.rowData.is_active" class="btn btn-outline-success btn-sm pb-0 pt-0 mr-1"
:title="'Active'"
@click="onClickActive(props.rowData)">
{{$t('signature.active')}}
</button>
<button v-if="!props.rowData.is_active" class="btn btn-danger btn-sm pb-0 pt-0 mr-1"
:title="'Delete'"
@click="onClickDelete(props.rowData)">
<i class="fal fa-fw fa-trash" aria-hidden="true"></i>
</button>
<button v-if="props.rowData.is_active" class="btn btn-outline-danger btn-sm pb-0 pt-0"
:title="'Block'"
@click="onClickBlock(props.rowData)">
{{$t('signature.deactivate')}}
</button>
</div>
</app-table>
<digital-certificate-detail-modal @on-ok="onOk"></digital-certificate-detail-modal>
</div>
</div>
</div>
</app-modal>
</template>
<script>
import { mapState } from 'vuex'
import DateTimeUtils from '@/utils/datetime'
import AppModal from '@/components/app-modal/'
import AppTable from '@/components/app-table/'
import CaSignProxy from '@/store/proxies/ca-sign-proxy'
import DigitalCertificateDetailModal from '@/portal-components/signature/digital-certificate-detail-modal'
const fields = context => ([
{
name: 'issuer',
title: context.$t('signature.provider'),
callback: value => (value ? value.split(',')[0].replace('CN=', '') : '')
},
{
name: 'ca_type',
title: context.$t('signature.caType')
},
{
name: 'owner_name',
title: context.$t('signature.ownerName')
},
{
name: 'effective_date',
title: context.$t('signature.effectiveDate'),
callback: value => DateTimeUtils.formatDate(value)
},
{
name: 'expired_at',
title: context.$t('signature.expiredAt'),
callback: value => DateTimeUtils.formatDate(value)
},
{
name: 'is_active',
title: context.$t('signature.status'),
callback: value => (value ? context.$t('signature.active') : context.$t('signature.deactivate'))
},
{
name: '__slot:action',
titleClass: 'text-sm-right',
dataClass: 'text-sm-right',
title: 'app.action'
}
])
export default {
name: 'DigitalCertificateListModal',
components: {
AppModal,
AppTable,
DigitalCertificateDetailModal
},
data () {
return {
certificates: [],
title: null,
fields: []
}
},
computed: {
...mapState('auth', ['currentUser'])
},
methods: {
beforeOpen () {
this.fields = fields(this)
this.title = this.$t('signature.ca')
new CaSignProxy().listAll().then((response) => {
this.certificates = response
})
},
create () {
this.$modal.show('digital-certificate-detail-modal', {
model: {}
})
},
onClickEdit (user) {
this.$modal.show('digital-certificate-detail-modal', {
model: user
})
},
onClickDelete (model) {
const vm = this
this.$modal.show('dialog', {
title: this.$t('app.delete'),
text: this.$t('app.areyousure'),
okText: this.$t('app.delete'),
okClass: 'btn-danger',
onOk: () => {
new CaSignProxy().deleteSignature(model.id).then(() => {
vm.certificates = vm.certificates.filter(u => u.id !== model.id)
})
}
})
},
onClickActive (model) {
this.$modal.show('dialog', {
title: this.$t('signature.activeCA'),
text: this.$t('app.areyousure'),
okText: this.$t('signature.active'),
okClass: 'btn-success',
onOk: () => {
new CaSignProxy().activeSignature(model.id).then(() => {
new CaSignProxy().listAll().then((response) => {
this.certificates = response
})
})
}
})
},
onClickBlock (model) {
this.$modal.show('dialog', {
title: this.$t('signature.deactivateCA'),
text: this.$t('app.areyousure'),
okText: this.$t('signature.deactivate'),
okClass: 'btn-danger',
onOk: () => {
new CaSignProxy().blockSignature(model.id).then(() => {
new CaSignProxy().listAll().then((response) => {
this.certificates = response
})
})
}
})
},
onOk () {
new CaSignProxy().listAll().then((response) => {
this.certificates = response
})
}
}
}
</script> |
@page "/pagewithloading"
@using System.Text.Json.Serialization;
@using BlazorAppRadzenLoading.Models;
@inject DialogService DialogService
<PageTitle>Index</PageTitle>
<!-- LOADING COMPONENT -->
<BlazorAppRadzenLoading.Components.LoadingIndicator DoLoadDataCallback="LoadDataAsync"
Option="options" />
<RadzenContent Container="main">
<RadzenIcon Icon="assessment" />
<RadzenHeading Size="H1" style="display: inline-block" Text="Dashboard" />
<RadzenHeading Size="H2" Text="Stats" />
<div class="row">
<div class="col-md-12 col-xl-3 col-lg-6">
<RadzenCard style="margin-bottom: 16px">
<div class="row">
<div class="col-md-4 col-4">
<RadzenIcon Icon="badge" style="color: #68d5c8; font-size: 48px; height: 64px; width: 100%" />
</div>
<div class="col-md-8 col-8">
<RadzenHeading Size="H4" style="margin-bottom: 0px; text-align: right" />
<RadzenHeading Text="Organization"
Size="H4" style="color: #88989b; font-size: 12px; margin-bottom: 0px; text-align: right" />
<RadzenHeading Text="@organization?.Name"
Size="H4" style="color: #68d5c8; font-size: 16px; margin-bottom: 0px; margin-top: 13px; text-align: right" />
</div>
</div>
</RadzenCard>
</div>
<div class="col-md-12 col-xl-3 col-lg-6">
<RadzenCard style="margin-bottom: 16px">
<div class="row">
<div class="col-md-4 col-4">
<RadzenIcon Icon="functions" style="color: #f9777f; font-size: 48px; height: 64px; width: 100%" />
</div>
<div class="col-md-8 col-8">
<RadzenHeading Size="H4" style="margin-bottom: 0px; text-align: right" />
<RadzenHeading Text="Total Repos"
Size="H4" style="color: #88989b; font-size: 12px; margin-bottom: 0px; text-align: right" />
<RadzenHeading Text="@organization?.TotalPublicRepos.ToString()"
Size="H4" style="color: #f9777f; font-size: 24px; margin-bottom: 0px; margin-top: 13px; text-align: right" />
</div>
</div>
</RadzenCard>
</div>
<div class="col-md-12 col-xl-3 col-lg-6">
<RadzenCard style="margin-bottom: 16px">
<div class="row">
<div class="col-md-4 col-4">
<RadzenIcon Icon="thumb_up" style="color: #ff6d41; font-size: 48px; height: 64px; width: 100%" />
</div>
<div class="col-md-8 col-8">
<RadzenHeading Size="H4" style="margin-bottom: 0px; text-align: right" />
<RadzenHeading Text="Total Followers"
Size="H4" style="color: #88989b; font-size: 12px; margin-bottom: 0px; text-align: right" />
<RadzenHeading Text="@organization?.TotalFollowers.ToString()"
Size="H4" style="color: #ff6d41; font-size: 24px; margin-bottom: 0px; margin-top: 13px; text-align: right" />
</div>
</div>
</RadzenCard>
</div>
<div class="col-md-12 col-xl-3 col-lg-6">
<RadzenCard style="margin-bottom: 16px">
<div class="row">
<div class="col-md-4 col-4">
<RadzenIcon Icon="thumbs_up_down" style="color: #479cc8; font-size: 48px; height: 64px; width: 100%" />
</div>
<div class="col-md-8 col-8">
<RadzenHeading Size="H4" style="margin-bottom: 0px; text-align: right" />
<RadzenHeading Text="Total Followings"
Size="H4" style="color: #88989b; font-size: 12px; margin-bottom: 0px; text-align: right" />
<RadzenHeading Text="@organization?.TotalFollowings.ToString()"
Size="H4" style="color: #479cc8; font-size: 24px; margin-bottom: 0px; margin-top: 13px; text-align: right" />
</div>
</div>
</RadzenCard>
</div>
</div>
<div class="row">
<div class="col-md-12">
<RadzenHeading Size="H2" Text="Repo Stats (aspnetcore)" />
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="row">
<div class="col-md-12 col-lg-6 col-xl-4">
<RadzenCard style="margin-bottom: 16px">
<RadzenChart ColorScheme="ColorScheme.Pastel">
<RadzenColumnSeries Title="Issues by Label"
CategoryProperty="@(nameof(IssueGroupbyLabel.LabelName))"
TItem="IssueGroupbyLabel"
Data="@issueGroupsbyLabel"
ValueProperty="@(nameof(IssueGroupbyLabel.Count))" />
</RadzenChart>
</RadzenCard>
</div>
<div class="col-md-12 col-lg-6 col-xl-4">
<RadzenCard style="margin-bottom: 16px">
<RadzenChart ColorScheme="ColorScheme.Pastel">
@if (issueGroupsbyLabelandCreatedAt is not null)
{
@foreach (var key in issueGroupsbyLabelandCreatedAt.Keys)
{
IEnumerable<IssueGroupbyLabel> list = issueGroupsbyLabelandCreatedAt[key].AsEnumerable();
<RadzenLineSeries Title="@key"
CategoryProperty="@(nameof(IssueGroupbyLabel.CreatedAtString))"
TItem="IssueGroupbyLabel"
Data="@list"
ValueProperty="@(nameof(IssueGroupbyLabel.Count))" />
}
}
</RadzenChart>
</RadzenCard>
</div>
<div class="col-md-12 col-lg-6 col-xl-4">
<RadzenCard style="margin-bottom: 16px">
<RadzenChart ColorScheme="ColorScheme.Pastel">
<RadzenBarSeries Title="Issues by Date"
CategoryProperty="@(nameof(IssueGroup.CreatedAtString))"
TItem="IssueGroup"
Data="@issueGroupsCreatedAt"
ValueProperty="@(nameof(IssueGroup.Count))" />
</RadzenChart>
</RadzenCard>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<RadzenHeading Size="H2" Text="Repositories" />
</div>
</div>
<div class="row">
<div class="col-md-12 col-xl-6">
<RadzenCard>
<RadzenHeading Size="H3" Text="Last Updated Repos" />
<RadzenDataGrid Data="@reposLastUpdated" TItem="Repo"
AllowFiltering="false" AllowColumnResize="true" AllowAlternatingRows="false" AllowSorting="true">
<Columns>
<RadzenDataGridColumn TItem="Repo"
Property="@nameof(Repo.Name)" Title="@nameof(Repo.Name)" />
<RadzenDataGridColumn TItem="Repo"
Property="@nameof(Repo.UpdatedAt)" Title="@nameof(Repo.UpdatedAt)" />
</Columns>
</RadzenDataGrid>
</RadzenCard>
</div>
<div class="col-md-12 col-xl-6">
<RadzenCard>
<RadzenHeading Size="H3" Text="Last Issues (aspnetcore)" />
<RadzenDataGrid Data="@issuesLastUpdated" TItem="Issue"
AllowFiltering="false" AllowColumnResize="true" AllowAlternatingRows="false" AllowSorting="true">
<Columns>
<RadzenDataGridColumn TItem="Issue"
Property="@nameof(Issue.Title)" Title="@nameof(Issue.Title)" />
<RadzenDataGridColumn TItem="Issue"
Property="@nameof(Issue.State)" Title="@nameof(Issue.State)" />
<RadzenDataGridColumn TItem="Issue"
Property="@nameof(Issue.UpdatedAt)" Title="@nameof(Issue.UpdatedAt)" />
</Columns>
</RadzenDataGrid>
</RadzenCard>
</div>
</div>
</RadzenContent>
@code {
BlazorAppRadzenLoading.Components.LoadingIndicatorOptions options =
new(true, false, true, 0, 6);
Organization? organization;
IEnumerable<Repo>? reposLastUpdated;
IEnumerable<IssueGroupbyLabel>? issueGroupsbyLabel;
Dictionary<string, List<IssueGroupbyLabel>>? issueGroupsbyLabelandCreatedAt;
IEnumerable<Issue>? issuesLastUpdated;
IEnumerable<IssueGroup>? issueGroupsCreatedAt;
private async Task LoadDataAsync()
{
//Thread.Sleep(5000); // testing
organization = await GetOrganization();
await InvokeAsync(StateHasChanged); // update this page
options.CurrentStep = 1; // property updates loading component
//Thread.Sleep(5000); // testing
issueGroupsbyLabel = await GetIssueGroupsbyLabel();
await InvokeAsync(StateHasChanged); // update this page
options.CurrentStep = 2; // property updates loading component
//Thread.Sleep(5000); // testing
issueGroupsbyLabelandCreatedAt = await GetIssueGroupsbyLabelandCreatedAt();
await InvokeAsync(StateHasChanged); // update this page
options.CurrentStep = 3; // property updates loading component
//Thread.Sleep(5000); // testing
issueGroupsCreatedAt = await GetIssueGroupsCreatedAt();
await InvokeAsync(StateHasChanged); // update this page
options.CurrentStep = 4; // property updates loading component
//Thread.Sleep(5000); // testing
reposLastUpdated = await GetReposLastUpdated();
await InvokeAsync(StateHasChanged); // update this page
options.CurrentStep = 5; // property updates loading component
//Thread.Sleep(5000); // testing
issuesLastUpdated = await GetIssuesLastUpdated();
await InvokeAsync(StateHasChanged); // update this page
options.CurrentStep = 6; // property updates loading component
}
private async Task<Organization> GetOrganization()
{
using var request = new HttpRequestMessage(HttpMethod.Get,
"https://api.github.com/orgs/dotnet");
using HttpClient client = new HttpClient();
client.DefaultRequestHeaders.UserAgent.ParseAdd("dotnetcoding");
var response = await client.SendAsync(request);
if (response.IsSuccessStatusCode)
{
var result = await response.Content.ReadFromJsonAsync<Organization>();
if (result is not null)
{
return result;
}
}
return new();
}
private async Task<IEnumerable<IssueGroupbyLabel>> GetIssueGroupsbyLabel()
{
List<IssueGroupbyLabel> res = new List<IssueGroupbyLabel>();
using var request = new HttpRequestMessage(HttpMethod.Get,
$"https://api.github.com/repos/dotnet/aspnetcore/issues?per_page=100&sort=created&order=desc");
using HttpClient client = new HttpClient();
client.DefaultRequestHeaders.UserAgent.ParseAdd("dotnetcoding");
using var response = await client.SendAsync(request);
if (response.IsSuccessStatusCode)
{
var result = await response.Content.ReadFromJsonAsync<IEnumerable<Issue>>();
if (result is not null && result.Count() > 0)
{
foreach (var item in result)
{
foreach (var label in item.Labels)
{
var cont = res.FirstOrDefault(x => x.LabelName == label.Name);
if (cont is null)
{
cont = new IssueGroupbyLabel { LabelName = label.Name, Count = 1 };
res.Add(cont);
}
else
{
cont.Count++;
}
}
}
res = res.OrderByDescending(x => x.Count).Take(10).ToList();
}
}
return res;
}
private async Task<Dictionary<string, List<IssueGroupbyLabel>>> GetIssueGroupsbyLabelandCreatedAt()
{
Dictionary<string, List<IssueGroupbyLabel>> dict = new Dictionary<string, List<IssueGroupbyLabel>>();
using var request = new HttpRequestMessage(HttpMethod.Get,
$"https://api.github.com/repos/dotnet/aspnetcore/issues?per_page=100&sort=created&order=desc");
using HttpClient client = new HttpClient();
client.DefaultRequestHeaders.UserAgent.ParseAdd("dotnetcoding");
using var response = await client.SendAsync(request);
if (response.IsSuccessStatusCode)
{
var result = await response.Content.ReadFromJsonAsync<IEnumerable<Issue>>();
if (result is not null && result.Count() > 0)
{
foreach (var item in result)
{
foreach (var label in item.Labels)
{
if (!dict.ContainsKey(label.Name))
dict.Add(label.Name, new List<IssueGroupbyLabel>());
var contain = dict[label.Name].FirstOrDefault(x => x.LabelName == label.Name && x.CreatedAt.Date == item.CreatedAt.Date);
if (contain is not null)
{
contain.Count++;
}
else
{
dict[label.Name].Add(new IssueGroupbyLabel { LabelName = label.Name, CreatedAt = item.CreatedAt.Date, Count = 1 });
}
}
}
dict = dict.OrderByDescending(x => x.Value.Count).Take(5).ToDictionary(x => x.Key, x => x.Value);
}
}
return dict;
}
private async Task<IEnumerable<IssueGroup>> GetIssueGroupsCreatedAt()
{
using var request = new HttpRequestMessage(HttpMethod.Get,
$"https://api.github.com/repos/dotnet/aspnetcore/issues?per_page=100&sort=created&order=desc");
using HttpClient client = new HttpClient();
client.DefaultRequestHeaders.UserAgent.ParseAdd("dotnetcoding");
using var response = await client.SendAsync(request);
if (response.IsSuccessStatusCode)
{
var result = await response.Content.ReadFromJsonAsync<IEnumerable<Issue>>();
if (result is not null && result.Count() > 0)
{
return result.GroupBy(x => new DateTime(x.CreatedAt.Year, x.CreatedAt.Month, x.CreatedAt.Day),
x => x,
(key, g) => new IssueGroup { CreatedAt = key, Count = g.Count() })
.Take(10);
}
}
return new List<IssueGroup>();
}
private async Task<IEnumerable<Repo>> GetReposLastUpdated()
{
using var request = new HttpRequestMessage(HttpMethod.Get,
"https://api.github.com/orgs/dotnet/repos?per_page=10&sort=updated&order=desc");
using HttpClient client = new HttpClient();
client.DefaultRequestHeaders.UserAgent.ParseAdd("dotnetcoding");
var response = await client.SendAsync(request);
if (response.IsSuccessStatusCode)
{
var result = await response.Content.ReadFromJsonAsync<IEnumerable<Repo>>();
if (result is not null)
{
return result;
}
}
return new List<Repo>();
}
private async Task<IEnumerable<Issue>> GetIssuesLastUpdated()
{
using var request = new HttpRequestMessage(HttpMethod.Get,
"https://api.github.com/repos/dotnet/aspnetcore/issues?per_page=10&sort=updated&order=desc");
using HttpClient client = new HttpClient();
client.DefaultRequestHeaders.UserAgent.ParseAdd("dotnetcoding");
var response = await client.SendAsync(request);
if (response.IsSuccessStatusCode)
{
var result = await response.Content.ReadFromJsonAsync<IEnumerable<Issue>>();
if (result is not null)
{
return result;
}
}
return new List<Issue>();
}
} |
import '../community/communityMain.dart';
import 'package:image_picker/image_picker.dart';
import 'communityService.dart';
import 'package:flutter/material.dart';
class CommunityEditAppBar extends StatelessWidget
implements PreferredSizeWidget {
int postId;
String inputTitle;
String inputContent;
List<XFile> images;
List imageUrls;
CommunityEditAppBar({
super.key,
required this.postId,
required this.inputTitle,
required this.inputContent,
required this.images,
required this.imageUrls,
});
@override
Widget build(BuildContext context) {
return AppBar(
leading: IconButton(
onPressed: () {
Navigator.push(context,
MaterialPageRoute(builder: (context) => CommuntiyMain()));
},
icon: const Icon(Icons.arrow_back),
iconSize: 40,
),
title: const Text(
'Edit Article',
style: TextStyle(
fontSize: 22,
fontWeight: FontWeight.w700,
),
),
centerTitle: true,
actions: [
Padding(
padding: const EdgeInsets.symmetric(
horizontal: 15,
),
child: TextButton(
onPressed: () async {
if (inputTitle != '' && inputContent != '') {
CommunitySerrvices.editPost(
postId, inputTitle, inputContent, images, imageUrls);
showDialog(
context: context,
barrierDismissible: false,
builder: (BuildContext context) {
return const AlertDialog(
content: Text('Post edited!'),
);
},
);
await Future.delayed(const Duration(seconds: 1));
Navigator.push(context,
MaterialPageRoute(builder: (context) => CommuntiyMain()));
} else {
showDialog(
context: context,
builder: (context) => AlertDialog(
title: const Text('Can\'t upload article'),
content: const Text(
'Article must include title and content'),
actions: [
TextButton(
onPressed: () {
Navigator.pop(context);
},
child: const Text('OK'),
),
],
));
}
},
child: const Text(
'Edit',
style: TextStyle(
fontSize: 18,
),
),
),
),
],
);
}
@override
Size get preferredSize => const Size.fromHeight(kToolbarHeight);
} |
import {useEffect} from 'react';
import Alert from 'sentry/components/alert';
import Button from 'sentry/components/button';
import {t} from 'sentry/locale';
import {Organization, Project, SeriesApi} from 'sentry/types';
import {defined} from 'sentry/utils';
import trackAdvancedAnalyticsEvent from 'sentry/utils/analytics/trackAdvancedAnalyticsEvent';
import {RecommendedStepsModalProps} from './modals/recommendedStepsModal';
import {getClientSampleRates, SERVER_SIDE_SAMPLING_DOC_LINK} from './utils';
type Props = Pick<RecommendedStepsModalProps, 'onReadDocs'> & {
organization: Organization;
projectId: Project['id'];
projectStats?: SeriesApi;
};
export function SamplingSDKClientRateChangeAlert({
projectStats,
onReadDocs,
organization,
projectId,
}: Props) {
const {diff: clientSamplingDiff} = getClientSampleRates(projectStats);
const recommendChangingClientSdk =
defined(clientSamplingDiff) && clientSamplingDiff >= 50;
useEffect(() => {
if (!recommendChangingClientSdk) {
return;
}
trackAdvancedAnalyticsEvent('sampling.sdk.client.rate.change.alert', {
organization,
project_id: projectId,
});
}, [recommendChangingClientSdk, organization, projectId]);
if (!recommendChangingClientSdk) {
return null;
}
return (
<Alert
type="info"
showIcon
trailingItems={
<Button
href={`${SERVER_SIDE_SAMPLING_DOC_LINK}getting-started/#4-increase-your-sdk-transaction-sample-rate`}
onClick={onReadDocs}
priority="link"
borderless
external
>
{t('Learn More')}
</Button>
}
>
{t(
'To allow more transactions to be processed, we suggest changing your client(SDK) sample rate.'
)}
</Alert>
);
} |
import React, { useState, useEffect } from 'react';
import { allProducts } from './test'; // Импорт данных
import CardInfo from './CardInfo';
import './shopContent.css';
const ShopContent = ({ onProductClick, currentPath }) => {
const itemsPerPage = 9; // Количество товаров на странице
// Закомментировала код для получения данных с сервера
const [products, setProducts] = useState([]);
const [selectedProductInfo, setSelectedProductInfo] = useState(null);
/* const [cart, setCart] = useState([]); */
const [selectedCategory, setSelectedCategory] = useState('Всі');
const [currentPage, setCurrentPage] = useState(1);
const [totalCategoryProducts, setTotalCategoryProducts] = useState([]);
const [isProductInfoVisible, setIsProductInfoVisible] = useState(false);
useEffect(() => {
// Получение данных о товарах с сервера
/* fetch(`http://localhost:8080/api/card_product?page=${currentPage}`)
.then(response => response.json())
.then(data => setProducts(data))
.catch(error => console.error('Error fetching products:', error));
*/
// Адаптированный запрос к серверу (вам нужно адаптировать URL и метод запроса)
fetch(`http://localhost:8080/card`)
.then(response => response.json())
.then(data => {
// Адаптируем полученные данные, если необходимо
const adaptedData = data.map(item => ({
id: item.id,
name: item.name,
price: item.price,
image: item.image,
category: item.category,
}));
setProducts(adaptedData);
})
.catch(error => console.error('Error fetching products:', error));
}, []); // Пустой массив зависимостей означает, что useEffect сработает только при монтировании компонента
const filteredProducts = selectedCategory === 'Всі'
? allProducts
: allProducts.filter(product => product.category === selectedCategory);
setTotalCategoryProducts(filteredProducts);
// Рассчитываем индексы товаров для текущей страницы
const startIndex = (currentPage - 1) * itemsPerPage;
const endIndex = startIndex + itemsPerPage;
// Выбираем только те товары, которые соответствуют текущей странице
const currentProducts = filteredProducts.slice(startIndex, endIndex);
setProducts(currentProducts);
}, [currentPage, selectedCategory])
const getPageNumbers = () => {
const totalPages = Math.ceil(products.length / itemsPerPage);
return Array.from({ length: totalPages }, (_, index) => index + 1);
};
const handlePageChange = (newPage) => {
setCurrentPage(newPage);
setSelectedProductInfo(null); // Сброс информации о товаре при изменении страницы
setIsProductInfoVisible(false);
};
const handleCategoryChange = (category) => {
setSelectedCategory(category);
setCurrentPage(1); // Сброс текущей страницы при изменении категории
setSelectedProductInfo(null); // Сброс информации о товаре при изменении категории
setIsProductInfoVisible(false);
};
const handleCardClick = (product) => {
setSelectedProductInfo(product);
setIsProductInfoVisible(true);
onProductClick(product.name, product.category);
};
/* const handleAddToCart = (product) => {
setCart([...cart, product]);
setSelectedProductInfo(null);
}; */
return (
<div className="shopContent">
<div className="conteiner">
<div className="shop__nav">
<div className={`category-menu ${isProductInfoVisible ? 'hidden' : ''}`}>
{/* Создание кнопок для категорий */}
{['Всі', 'Футболки', 'Купальники', 'Пальто', 'Світшоти'].map(category => (
<button
key={category}
className={`category-btn ${selectedCategory === category ? 'active' : ''}`}
onClick={() => handleCategoryChange(category)}
>
{category}
</button>
))}
</div> </div>
<div className={`product-card__shown-text ${isProductInfoVisible ? 'hidden' : ''}`}>
Показано: {Math.min(itemsPerPage * currentPage, totalCategoryProducts.length)} из {totalCategoryProducts.length} товаров
</div>
<div className={`product-grid-page ${isProductInfoVisible ? 'hidden' : ''}`}>
<div className="product-grid">
{products.map(product => (
<div key={product.id}
className="product-card"
onClick={() => handleCardClick(product)}>
<div className="product-card__img">
<img src={product.image} alt={product.name} />
</div>
<h2 className="product-card__title">{product.name}</h2>
<p className="product-card__price">${product.price}</p>
</div>
))}
</div>
<div className={`product-card__shown-text ${isProductInfoVisible ? 'hidden' : ''}`}>
Показано: {Math.min(itemsPerPage * currentPage, totalCategoryProducts.length)} из {totalCategoryProducts.length} товаров
</div>
<div className="product-card_btn">
{getPageNumbers().map((page, index) => (
<button
className={`product-card__nextbtn ${currentPage === page ? 'active' : ''}`}
key={page}
onClick={() => handlePageChange(page)}
>
{index === 0 ? currentPage : page}
</button>
))}
{currentPage > 1 && (
<button
className="product-card__nextbtn_arrow"
onClick={() => handlePageChange(currentPage - 1)}
>
←
</button>
)}
{/* Если есть еще товары, показываем кнопку для следующей страницы */}
{products.length === itemsPerPage && (
<button
className="product-card__nextbtn_arrow"
onClick={() => handlePageChange(currentPage + 1)}
>
→
</button>
)}
</div>
</div>
{isProductInfoVisible && (
<div className="selected-product-info">
<CardInfo selectedProductInfo={selectedProductInfo} />
</div>
)}
</div>
</div>
);
export default ShopContent; |
/*
* Temple Library for ActionScript 3.0
* Copyright © MediaMonks B.V.
* All rights reserved.
*
* 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.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by MediaMonks B.V.
* 4. Neither the name of MediaMonks B.V. nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY MEDIAMONKS B.V. ''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 MEDIAMONKS B.V. 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.
*
*
* Note: This license does not apply to 3rd party classes inside the Temple
* repository with their own license!
*/
package temple.ui.slider
{
import com.greensock.easing.Ease;
import flash.display.InteractiveObject;
import flash.geom.Rectangle;
/**
* Basic implementation of a StepSlider.
*
* <p>A StepSliderComponent need at least a button and a track which can be set in the Flash IDE or by code. If set
* in the IDE name the object which must act as track 'track' or 'mcTrack'. The button must be called 'button' or
* 'mcButton'.</p>
*
* @author Mark Knol
*/
public class SnapSliderComponent extends StepSliderComponent
{
public function SnapSliderComponent()
{
super();
}
/**
* Duration of the snap animation
*/
public function get duration():Number
{
return SnapSlider(slider).duration;
}
/**
* @private
*/
public function set duration(value:Number):void
{
SnapSlider(slider).duration = value;
}
/**
* Ease of the snap animation
*/
public function get ease():Ease
{
return SnapSlider(slider).ease;
}
/**
* @private
*/
public function set ease(value:Ease):void
{
SnapSlider(slider).ease = value;
}
override protected function createSlider(target:InteractiveObject, bounds:Rectangle):Slider
{
return new SnapSlider(target, bounds);
}
}
} |
const sqlite3 = require('sqlite3').verbose();
class Database {
constructor(dbFilePath) {
this.db = new sqlite3.Database(dbFilePath);
this.initDatabase();
}
initDatabase() {
const createSpecialtyTable = `
CREATE TABLE IF NOT EXISTS Specialty (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL UNIQUE
)
`;
this.db.run(createSpecialtyTable);
}
getUserByName(chatId) {
return new Promise((resolve, reject) => {
this.db.get('SELECT * FROM Users WHERE chat_id = ?', [chatId], (err, row) => {
if (err) {
reject(err);
} else {
resolve(row);
}
});
});
}
createUser(name, chat_id, phone = '') {
if (!chat_id) {
console.error("Chat id is required, skipping creating user");
return;
}
return new Promise((resolve, reject) => {
this.db.run('INSERT INTO Users (name, phone, chat_id) VALUES (?, ?, ?)', [name, phone, chat_id], function (err) {
if (err) {
reject(err);
} else {
console.log("User was created", { chat_id });
resolve(this.lastID);
}
});
});
}
getDoctorSpecialties() {
return new Promise((resolve, reject) => {
this.db.all('SELECT * FROM Specialty', (err, rows) => {
if (err) {
reject(err);
} else {
const specialties = rows.map((row) => row.name);
resolve(specialties);
}
});
});
}
getHospitalsBySpecialty(specialty) {
console.log("Start getting hospitals by specialty", { specialty });
return new Promise((resolve, reject) => {
this.db.all('SELECT * FROM Hospitals WHERE specialties LIKE ?', [`%${specialty}%`], (err, rows) => {
if (err) {
console.log({err})
reject(err);
} else {
resolve(rows);
}
});
});
}
getDoctorsBySpecialityAndHospital(specialty, hospitalId) {
console.log("Start getting doctors by specialty and hospital", { specialty, hospitalId })
return new Promise((resolve, reject) => {
this.db.all('SELECT * FROM Doctors WHERE specialty LIKE ? AND hospital_id = ?', [`%${specialty}%`, hospitalId], (err, rows) => {
if (err) {
console.log({err})
reject(err);
} else {
resolve(rows);
}
});
});
}
getAllDoctors() {
console.log("Start getting doctors ")
return new Promise((resolve, reject) => {
this.db.all('SELECT * FROM Doctors', [], (err, rows) => {
if (err) {
console.log({err})
reject(err);
} else {
resolve(rows);
}
});
});
}
close() {
this.db.close();
}
}
module.exports = {
Database
}; |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TemplateProject2
{
class Program
{
static void Main(string[] args)
{
string intsum = sum<int>(10, 20);
Console.WriteLine(intsum);
string strsum = sum<string>("Hello ", "world");
Console.WriteLine(strsum);
var result1 = DisplayName<Employee>(new Employee());
var result2 = DisplayName<Person>(new Person());
Console.ReadLine();
}
static string sum<T>(T value1, T value2)
{
return value1.ToString() + value2.ToString();
}
static string DisplayName<T>(T p) where T : Person
{
return p.FirstName + p.LastName;
}
}
class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
class Employee : Person
{
public DateTime HoreDate { get; set; }
}
} |
package com.example.duck;
import com.example.behaviour.FlyBehaviour;
import com.example.behaviour.QuackBehaviour;
public abstract class Duck {
FlyBehaviour flyBehaviour;
QuackBehaviour quackBehaviour;
public Duck(FlyBehaviour flyBehaviour,QuackBehaviour quackBehaviour){
this.flyBehaviour = flyBehaviour;
this.quackBehaviour = quackBehaviour;
}
public abstract void display();
public void performFly(){
this.flyBehaviour.fly();
}
public void performQuack(){
this.quackBehaviour.quack();
}
} |
import {tryUntil} from '../../async';
/**
* This is a promise-based version of scrollIntoView().
* Method scrolls the element's parent container such that the element on which
* scrollIntoView() is called is visible to the user. The promise is resolved when
* the element became visible to the user and scrolling stops.
*
* Note: Please, use the native element.scrollIntoView() if you don't need a promise
* to detect the moment when the scroll is finished or you don't use smooth behavior.
* @param element - element to be made visible to the user
* @param options - scrollIntoView options
*/
export function scrollIntoView(element: Element, options?: boolean | ScrollIntoViewOptions | undefined): Promise<boolean> {
let same = 0;
let lastLeft: number;
let lastTop: number;
const check = (): boolean => {
const {top, left} = element.getBoundingClientRect();
if (top !== lastTop || left !== lastLeft) {
same = 0;
lastTop = top;
lastLeft = left;
}
return same++ > 2;
};
element.scrollIntoView(options);
return tryUntil(check, 333, 30); // will check top position every 30ms, but not more than 250 times (10s)
} |
package test;
import queue.Queue;
import task.Task;
/**
Each cpu is composed of a queue. Each cpu can be assigned with some tasks and then perform its own tasks.
*/
public class Cpu {
private Queue queue;
// Must specify a queue to create a cpu.
Cpu(Queue queue) {
this.queue = queue;
}
/**
* Assign or load this cpu with a bunch of tasks.
*
* @tasks
*/
public void assign(Task[] tasks) {
if (this.queue.isFull())
throw new RuntimeException("This cpu is already full.");
for (int i = 0; i < tasks.length; ++i) {
this.queue.enqueue(tasks[i]);
}
}
/**
* Assign or load this cpu with one single task.
*
* @task
* @author haopengwu
*/
public void assign(Task task) {
if (this.queue.isFull())
throw new RuntimeException("This cpu is already full.");
this.queue.enqueue(task);
}
/**
* Execute all the tasks currently loaded with this cpu.
*/
public void perform() {
this.execute();
}
/**
* Perform a bunch of tasks, before which clear the cpu.
*
* @tasks, an array of tasks to be executed
*
*/
public void perform(Task[] tasks) {
this.emptyTasks();
this.assign(tasks);
this.execute();
}
/**
* Perform a bunch of tasks, before which clear the cpu.
*
* @tasks, an array of tasks to be executed
*
*/
public void perform2(Task[] tasks) {
this.emptyTasks();
this.assign(tasks);
this.execute2();
}
/**
* Execute the first task from the load of this cpu.
*/
public void performOnce() {
this.executeOnce();
}
/**
* Execute the first @times tasks from the load of this cpu.
* @return the tasks that have been performed
*/
public Task[] performTimesOf(int times) {
Task[] tasks = new Task[times];
int i = 0;
for (i = 0; i < times; ++i) {
tasks[i] = this.executeOnce();
}
return tasks;
}
/**
* Assign a single task and execute all the tasks in the queue.
*
* @task, an array of tasks to be executed
*
* @deprecated useless and confusing method, to be deleted
*/
private void perform(Task task) {
this.assign(task);
this.execute();
}
/**
* Execute all the tasks inside the queue and this queue becomes empty.
*/
public void execute() {
Task task;
while (!queue.isEmpty()) {
task = queue.dequeue();
task.perform();
}
}
/**
* Execute all the tasks inside the queue, no sleep time.
*/
public void execute2() {
while (!queue.isEmpty()) {
queue.dequeue();
}
}
/**
* Execute all the tasks inside the queue and this queue becomes empty.
*/
public Task executeOnce() {
Task task;
if (!queue.isEmpty()) {
task = queue.dequeue();
task.perform();
return task;
}
return null;
}
/**
* Empty the queue
*/
public void emptyTasks() {
this.queue.empty();
}
} |
<div class="grid">
<div class="col-12">
<div class="card px-6 py-6">
<p-toast></p-toast>
<p-toolbar styleClass="mb-4">
<ng-template pTemplate="left">
<div class="my-2">
<button pButton pRipple label="New" icon="pi pi-plus" class="p-button-success mr-2"
(click)="openNew()"></button>
<button pButton pRipple label="Delete" icon="pi pi-trash" class="p-button-danger"
(click)="deleteSelectedRecipes()" [disabled]="!selectedRecipes || !selectedRecipes.length"></button>
</div>
</ng-template>
<ng-template pTemplate="right">
<p-fileUpload mode="basic" accept="image/*" [maxFileSize]="1000000" label="Import" chooseLabel="Import"
class="mr-2 inline-block"></p-fileUpload>
<button pButton pRipple label="Export" icon="pi pi-upload" class="p-button-help"
(click)="dt.exportCSV()"></button>
</ng-template>
</p-toolbar>
<p-table #dt [value]="recipes" [columns]="cols" responsiveLayout="scroll" [rows]="itemsPerPage"
[(selection)]="selectedRecipes" selectionMode="multiple" [rowHover]="true" dataKey="id" [lazy]="true"
(onLazyLoad)="handleLazyLoad($event)">
<ng-template pTemplate="caption">
<div class="flex flex-column md:flex-row md:justify-content-between md:align-items-center">
<h5 class="m-0">Manage Recipes</h5>
<span class="block mt-2 md:mt-0 p-input-icon-left">
<i class="pi pi-search"></i>
<input pInputText type="text"
(input)="handleSearchInput($event); dt.filterGlobal({ searchInput, page: 0 }, 'contains')"
placeholder="Search..." class="w-full sm:w-auto" />
</span>
</div>
</ng-template>
<ng-template pTemplate="header">
<tr>
<th style="width: 3rem">
<p-tableHeaderCheckbox></p-tableHeaderCheckbox>
</th>
<th pSortableColumn="id">Id <p-sortIcon field="id"></p-sortIcon></th>
<th pSortableColumn="name">Name <p-sortIcon field="name"></p-sortIcon></th>
<th>Image</th>
<th pSortableColumn="rating">Rating <p-sortIcon field="rating"></p-sortIcon></th>
<th pSortableColumn="level.name">Level <p-sortIcon field="level"></p-sortIcon></th>
<th pSortableColumn="category.name">Category <p-sortIcon field="category"></p-sortIcon></th>
<th pSortableColumn="cuisine.name">Cuisine <p-sortIcon field="cuisine"></p-sortIcon></th>
<th></th>
</tr>
</ng-template>
<ng-template pTemplate="body" let-recipe>
<tr>
<td>
<p-tableCheckbox [value]="recipe"></p-tableCheckbox>
</td>
<td style="width:14%; min-width:10rem;"><span class="p-column-title">Id</span>
{{ recipe.id }}
</td>
<td style="width:14%; min-width:10rem;">
<span class="p-column-title">Name</span>
{{ recipe.name }}
</td>
<td style="width:14%; min-width:10rem;"><span class="p-column-title">Image</span>
<img [src]="recipe.media.length > 0 && recipe.media[0].url" [alt]="recipe.name" width="100"
class="shadow-4" />
</td>
<td style="width:12%; min-width:8rem;">
<p-rating [ngModel]="recipe.rating" [readonly]="true" [cancel]="false"></p-rating>
</td>
<td style="width:12%; min-width:8rem;">
<span class="p-column-title">Level</span>
{{ recipe.level.name }}
</td>
<td style="width:12%; min-width:8rem;">
<span class="p-column-title">Category</span>
{{ recipe.category.name }}
</td>
<td style="width:12%; min-width:8rem;">
<span class="p-column-title">Cuisine</span>
{{ recipe.cuisine.name }}
</td>
<td style="width:10%; min-width:10rem;">
<div class="flex">
<button pButton pRipple icon="pi pi-pencil" class="p-button-rounded p-button-secondary mr-2"
tooltipPosition="top" pTooltip="Edit" (click)="editRecipe(recipe)"></button>
<button pButton pRipple icon="pi pi-trash" class="p-button-rounded p-button-danger"
tooltipPosition="top" pTooltip="Delete" (click)="deleteRecipe(recipe)"></button>
</div>
</td>
</tr>
</ng-template>
</p-table>
<p-paginator (onPageChange)="dt.filterGlobal({ searchInput, page: $event.first }, 'contains')"
[first]="currentRecords" [rows]="itemsPerPage" [totalRecords]="totalItems"></p-paginator>
</div>
<p-dialog [(visible)]="recipeDialog" [style]="{width: '1000px'}" header="Recipe Detail" [modal]="true"
class="p-fluid" (onHide)="hideDialog()">
<ng-template pTemplate="content">
<div class="card">
<p-steps [model]="steps" [readonly]="false" [activeIndex]="activeIndexStep"
(activeIndexChange)="handleActiveIndexStepChange($event)"></p-steps>
</div>
<div *ngIf="activeIndexStep === 0" class="card">
<div class="field">
<label for="name">Name</label>
<input type="text" pInputText id="name" [(ngModel)]="recipe.name" required autofocus
[ngClass]="{'ng-invalid ng-dirty' : submitted && !recipe.name}" />
<small class="p-error ng-dirty ng-invalid" *ngIf="submitted && !recipe.name">Name is required.</small>
</div>
<div class="field">
<label for="description">Description</label>
<textarea id="description" pInputTextarea [(ngModel)]="recipe.description" required rows="3"
cols="20"></textarea>
</div>
<div class="field">
<label for="level">Level</label>
<p-dropdown [options]="levels" [(ngModel)]="recipe.level.id" optionLabel="name" optionValue="id"
appendTo="body" [ngClass]="{'ng-invalid ng-dirty' : submitted}" [filter]="true" filterBy="name"
placeholder="Select a Level"></p-dropdown>
<small class="p-error ng-dirty ng-invalid" *ngIf="submitted && recipe.level.id === ''">Level is
required.</small>
</div>
<div class="field">
<label for="category">Category</label>
<p-dropdown [options]="categories" [(ngModel)]="recipe.category.id" optionLabel="name" optionValue="id"
appendTo="body" [ngClass]="{'ng-invalid ng-dirty' : submitted}" [filter]="true" filterBy="name"
placeholder="Select a Category"></p-dropdown>
<small class="p-error ng-dirty ng-invalid" *ngIf="submitted && recipe.category.id === ''">Category is
required.</small>
</div>
<div class="field">
<label for="Cuisine">Cuisine</label>
<p-dropdown [options]="cuisineArray" [(ngModel)]="recipe.cuisine.id" optionLabel="name" optionValue="id"
appendTo="body" [ngClass]="{'ng-invalid ng-dirty' : submitted}" [filter]="true" filterBy="name"
placeholder="Select a Cuisine"></p-dropdown>
<small class="p-error ng-dirty ng-invalid" *ngIf="submitted && recipe.cuisine.id === ''">Cuisine is
required.</small>
</div>
</div>
<div *ngIf="activeIndexStep === 1" class="card">
<ng-template ngFor let-item [ngForOf]="recipe.quantification" let-i="index">
<div class="p-formgrid grid">
<div class="field col md:col-7">
<label for="ingredient-name">Ingredient name</label>
<p-dropdown [options]="ingredients" [(ngModel)]="item.ingredient.id" optionLabel="name" optionValue="id"
appendTo="body" [ngClass]="{'ng-invalid ng-dirty' : submitted}" [filter]="true" filterBy="name"
placeholder="Select an Ingredient" [virtualScroll]="true" [itemSize]="30"></p-dropdown>
<small class="p-error ng-dirty ng-invalid" *ngIf="submitted && item.ingredient.id === ''">Ingredient is
required.</small>
</div>
<div class="field col md:col-2">
<label for="ingredient-value">Value</label>
<p-inputNumber [(ngModel)]="item.value" mode="decimal" inputId="ingredient-value" [useGrouping]="false"
[minFractionDigits]="0" [maxFractionDigits]="2"
[ngClass]="{'ng-invalid ng-dirty' : submitted && item.value <= 0}">
</p-inputNumber>
<small class="p-error ng-dirty ng-invalid" *ngIf="submitted && item.value <= 0">Value is greater than
0</small>
</div>
<div class="field col md:col-2">
<label for="ingredient-unit">Unit</label>
<input type="text" pInputText id="ingredient-unit" [(ngModel)]="item.unit" required autofocus
[ngClass]="{'ng-invalid ng-dirty' : submitted && !item.unit}" />
<small class="p-error ng-dirty ng-invalid" *ngIf="submitted && !item.unit">Unit is required.</small>
</div>
<div *ngIf="i !== 0 || recipe.quantification.length !== 1" class="field col md:col-1">
<button id="ingredient-delete-{{i}}" pButton pRipple icon="pi pi-trash" class="p-button-danger w-9 h-9"
[style]="{ marginTop: '23px' }" (click)="handleRemoveIngredientInRecipe(i)"></button>
</div>
</div>
</ng-template>
<button pButton pRipple label="Add more ingredients" icon="pi pi-plus" class="p-button-outlined"
(click)="handleAddMoreIngredients()"></button>
</div>
<div *ngIf="activeIndexStep === 2" class="card">
<ng-template ngFor let-item [ngForOf]="recipe.recipeStep" let-i="index">
<div class="p-formgrid grid">
<div class="field col md:col-11">
<label for="step-name">Step {{ i + 1 }}</label>
<textarea id="description" pInputTextarea [(ngModel)]="item.content" required rows="2" cols="20"
[ngClass]="{'ng-invalid ng-dirty' : submitted && !item.content}"></textarea>
<small class="p-error ng-dirty ng-invalid" *ngIf="submitted && !item.content">Content is
required.</small>
</div>
<div *ngIf="i !== 0 || recipe.recipeStep.length !== 1" class="field col md:col-1">
<button id="step-delete-{{i}}" pButton pRipple icon="pi pi-trash" class="p-button-danger w-9 h-9"
(click)="handleRemoveStep(i)" [style]="{ marginTop: '23px' }"></button>
</div>
</div>
</ng-template>
<button pButton pRipple label="Add more steps" icon="pi pi-plus" class="p-button-outlined"
(click)="handleAddMoreSteps()"></button>
</div>
</ng-template>
<ng-template pTemplate="footer">
<button pButton pRipple label="Cancel" icon="pi pi-times" class="p-button-text" (click)="hideDialog()"></button>
<button pButton pRipple label="Save" icon="pi pi-check" class="p-button" (click)="saveRecipe()"></button>
</ng-template>
</p-dialog>
<p-dialog [(visible)]="deleteRecipeDialog" header="Confirm" [modal]="true" [style]="{width:'450px'}">
<div class="flex align-items-center justify-content-center">
<i class="pi pi-exclamation-triangle mr-3" style="font-size: 2rem"></i>
<span *ngIf="recipe">Are you sure you want to delete <b>{{recipe.name}}</b>?</span>
</div>
<ng-template pTemplate="footer">
<button pButton pRipple icon="pi pi-times" class="p-button-text" label="No"
(click)="deleteRecipeDialog = false"></button>
<button pButton pRipple icon="pi pi-check" class="p-button-text" label="Yes" (click)="confirmDelete()"></button>
</ng-template>
</p-dialog>
<p-dialog [(visible)]="deleteRecipesDialog" header="Confirm" [modal]="true" [style]="{width:'450px'}">
<div class="flex align-items-center justify-content-center">
<i class="pi pi-exclamation-triangle mr-3" style="font-size: 2rem"></i>
<span>Are you sure you want to delete selected ingredients?</span>
</div>
<ng-template pTemplate="footer">
<button pButton pRipple icon="pi pi-times" class="p-button-text" label="No"
(click)="deleteRecipesDialog = false"></button>
<button pButton pRipple icon="pi pi-check" class="p-button-text" label="Yes"
(click)="confirmDeleteSelected()"></button>
</ng-template>
</p-dialog>
</div>
</div> |
import * as yup from 'yup';
import { RegistrationBody } from '../types';
const registrationBodyValidationSchema: yup.ObjectSchema<RegistrationBody> = yup.object({
email: yup.string()
.required('email is required')
.email('incorect email format'),
password: yup.string()
.required('password is required')
.min(8, 'password must have at least 8 symbols')
.max(32, 'password cannot have more than 32 symbols')
.matches(/[A-Z]{1}/, 'password must have at least one upper case letter')
.matches(/[a-z]{1}/, 'password must have at least one lower case letter')
.matches(/[0-Z9]{1}/, 'password must have at least one number')
.matches(/[#?!.,$%^&*]{1}/, 'password must have at least one special symbol'),
passwordConfirmation: yup.string()
.required('password is required')
.oneOf([yup.ref('password')], 'passwords do not match'),
name: yup.string()
.required('name is required')
.min(2, 'name must have at least 2 letters')
.max(32, 'name can\'t have more than 32 letters'),
surname: yup.string()
.required('surname is required')
.min(2, 'surname must have at least 2 letters')
.max(32, 'surname can\'t have more than 32 letters'),
phone: yup.string()
.required('phone is required')
.min(8, 'phone must have at least 2 numbers')
.max(32, 'phone can\'t have more than 32 numbers'),
})
.strict(true);
export default registrationBodyValidationSchema; |
from django.contrib.auth.decorators import login_required
from django.forms import ModelForm
from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.urls import reverse
from django.utils.text import slugify
from blogdjango.models import Post
from django.views.generic import ListView, DetailView, CreateView
class PostForm(ModelForm):
class Meta:
model = Post
fields = ['title', 'content', 'published']
@login_required
def new_post(request):
if request.method == "POST":
form = PostForm(request.POST)
if form.is_valid(): # valida cfe o model.
new_post = form.save(commit=False)
new_post.slug = slugify(new_post.title)
new_post.save()
return HttpResponseRedirect(reverse("index"))
else:
form = PostForm()
return render(request, "new_post.html", {"form": form})
class PostList(ListView):
#decorations = [login_required] # for class based view
model = Post
template_name = "index.html"
queryset = Post.objects.filter(published=True) #List view para mostrar posts = True.
class PostDetail(DetailView):
model = Post
template_name = "detail.html" |
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:todo_list_provider/app/core/ui/theme_extensions.dart';
import 'package:todo_list_provider/app/models/task_filter_enum.dart';
import 'package:todo_list_provider/app/models/total_tasks_model.dart';
import 'package:todo_list_provider/app/modules/home/home_controller.dart';
class TodoCardFilter extends StatelessWidget {
final String label;
final TaskFilterEnum taskFilter;
final TotalTaskModel? totalTaskModel;
final bool selected;
const TodoCardFilter({
super.key,
required this.label,
required this.taskFilter,
this.totalTaskModel,
required this.selected,
});
double _getPercentFinish() {
final total = totalTaskModel?.totalTak ?? 0.0;
final totalFinish = totalTaskModel?.totalTaskFinish ?? 0.1;
if (total == 0) {
return 0.0;
}
final percent = (totalFinish * 100) / total;
return percent / 100;
}
@override
Widget build(BuildContext context) {
return InkWell(
borderRadius: BorderRadius.circular(30),
onTap: () => context.read<HomeController>().findTasks(
filter: taskFilter,
),
child: Container(
padding: const EdgeInsets.all(20),
constraints: const BoxConstraints(
minHeight: 120,
maxWidth: 150,
),
margin: const EdgeInsets.only(
right: 10,
),
decoration: BoxDecoration(
color: selected ? context.primaryColor : Colors.white,
border: Border.all(width: 1, color: Colors.grey.withOpacity(.8)),
borderRadius: BorderRadius.circular(30),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'${totalTaskModel?.totalTak ?? 0} TASKS',
style: context.titleStyle.copyWith(
fontSize: 10,
color: selected ? Colors.white : Colors.grey,
),
),
Text(
label,
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold,
color: selected ? Colors.white : Colors.black,
),
),
TweenAnimationBuilder<double>(
tween: Tween(
begin: 0.0,
end: _getPercentFinish(),
),
duration: Duration(
seconds: 1,
),
builder: (context, value, child) {
return LinearProgressIndicator(
backgroundColor: selected
? context.primaryColorLight
: Colors.grey.shade300,
valueColor: AlwaysStoppedAnimation<Color>(
selected ? Colors.white : context.primaryColor),
value: value,
);
},
)
],
),
),
);
}
}
//Momento 6:25 |
<?php
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('home');
})->name('home');
Route::get('/character', function () {
return view('character');
})->name('character');
Route::prefix('/comics')->name('comic.')->group(function () {
Route::get('/', function () {
return view('comic.list');
})->name('list');
Route::get('/comic/{index}', function ($index) {
$products = config('comics');
$product = $products[$index];
$prev = $index > 0 ? $index - 1 : count($products) - 1;
$next = $index == count($products) - 1 ? 0 : $index + 1;
$data = compact('product', 'next', 'prev');
return view('comic.detail', $data);
})->name('detail');
});
Route::get('/movies', function () {
return view('movies');
})->name('movies');
Route::get('/tv', function () {
return view('tv');
})->name('tv');
Route::get('/collectibles', function () {
return view('collectibles');
})->name('collectibles');
Route::get('/videos', function () {
return view('videos');
})->name('videos');
Route::get('/fans', function () {
return view('fans');
})->name('fans');
Route::get('/news', function () {
return view('news');
})->name('news');
Route::get('/shop', function () {
return view('shop');
})->name('shop'); |
import fs from "fs/promises";
/**
* Open a file gracefully and return it if possible.
*
* If the file read was unsuccessful, the result will be `undefined`.
*
* @param {string} filename the filename
* @returns {Promise<string | undefined>} the file output
*/
export const openGracefully = async (filename: string): Promise<string | undefined> => {
return fs.access(filename).then(
() => fs.readFile(
filename, {encoding: "utf-8"},
).catch(
() => {
console.error(`Reading file failed: [${filename}].`);
return undefined;
}
),
).catch(
() => {
console.error(`File could not be found: [${filename}].`);
return undefined;
}
);
}; |
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha3/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-KK94CHFLLe+nY2dmCWGMq91rCGa5gtU4mk92HdvYe+M/SXH301p5ILy+dN9+nJOZ" crossorigin="anonymous">
<!-- Custom styles for this template -->
<link rel="stylesheet" type="text/css" href="./assets/css/style.css">
<title>Jill O'Reilly | Web Development Portfolio</title>
<link rel="apple-touch-icon" sizes="180x180" href="./assets/images/apple-touch-icon.png">
<link rel="icon" type="image/png" sizes="32x32" href="./assets/images/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="16x16" href="./assets/images/favicon-16x16.png">
<link rel="manifest" href="./assets/images/site.webmanifest">
</head>
<body>
<!-- Navigation -->
<nav class="navbar navbar-expand-md fixed-top" id="mainNav">
<div class="container">
<h1><a class="navbar-brand" href="#page-top">Jill O'Reilly</a></h1>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarResponsive"
aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse justify-content-end" id="navbarResponsive">
<ul class="navbar-nav ml-auto">
<li class="nav-item">
<a class="nav-link" href="#about">About me</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#work">Work</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#skills">Skills</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#contact">Contact me</a>
</li>
<li class="nav-item">
<a class="nav-link" href="./assets/Jill-OReilly-CV-Sep22.pdf" target="_blank">Resume</a>
</li>
</ul>
</div>
</div>
</nav>
<!-- Header -->
<header class="mb-3">
<p class="subtitle">Front-end web developer</p>
</header>
<!-- Main -->
<main>
<!-- About me -->
<section id="about" class="container">
<h2 class="fw-bold">About me</h2>
<div class="p-3 col-sm-12 col-md-12 col-lg-12 d-flex text-center align-items-center justify-content-center flex-column flex-md-column flex-lg-row">
<img src="./assets/images/jill-avatar-sm.png"
class="m-4 ms-3 float-md-start float-end rounded-top-circle img-fluid"
alt="Avatar image of Jill O'Reilly">
<div>
<p>Hi! I'm <strong>Jill</strong>, a front-end developer based in London but originally from
Australia. I have had a career break after having my 2 daughters and I'm keen to get back
into development. I love HTML, CSS and design and I am excited to learn new technologies like
React,node, git and more!</p>
<p>Outside of web development I love scuba diving and travelling as well as fashion, reading and
fibre art such as cross stitch.</p>
<p>Have a look at the showcase below of some of my work from the web development bootcamp as well as
projects from my work as a developer.</p>
</div>
</div>
</section>
<!-- Work -->
<section id="work" class="mb-3">
<div class="container">
<h2 class="fw-bold pb-3">Work</h2>
<div class="row gap-0 row-gap-lg-4 row-gap-md-3 row-gap-sm-2">
<div class="col-sm-12 col-md-6 col-lg-6">
<div class="card">
<img src="./assets/images/work-horiseon.png" class="card-img-top" alt="Horiseon Code Refactor">
<div class="card-body">
<h5 class="card-title">Horiseon Code Refactor</h5>
<p class="card-text">Skills for Life Front-end Wed Development Bootcamp - Challenge 1 - Code
refactor in HTML and CSS to improve accessibility and SEO</p>
<a href="https://jilloreilly.github.io/code-refactor/" class="btn btn-primary"
target="_blank">View project</a>
</div>
</div>
</div>
<div class="col-sm-12 col-md-6 col-lg-6">
<div class="card">
<img src="./assets/images/work-portfolio.png" class="card-img-top"
alt="Challenge 2 - Portfolio website screenshot">
<div class="card-body">
<h5 class="card-title">Portfolio website</h5>
<p class="card-text">Skills for Life Front-end Wed Development Bootcamp - Challenge 2 -
Portfolio website developed in HTML and CSS</p>
<a href="https://jilloreilly.github.io/jill-oreilly-portfolio/#" class="btn btn-primary"
target="_blank">View project</a>
</div>
</div>
</div>
<div class="col-sm-12 col-md-6 col-lg-6">
<div class="card">
<img src="./assets/images/work-bally.png" class="card-img-top" alt="Bally Luxurywear homepage">
<div class="card-body">
<h5 class="card-title">Bally</h5>
<p class="card-text">Lorem ipsum dolor sit amet consectetur adipisicing elit.</p>
<a href="http://www.bally.com" class="btn btn-primary" target="_blank">View project</a>
</div>
</div>
</div>
<div class="col-sm-12 col-md-6 col-lg-6">
<div class="card">
<img src="./assets/images/work-vm-2.png" class="card-img-top" alt="Virgin Media Homepage">
<div class="card-body">
<h5 class="card-title">Virgin Media</h5>
<p class="card-text">Lorem ipsum dolor sit amet consectetur adipisicing elit.</p>
<a href="http://www.virginmedia.com" class="btn btn-primary" target="_blank">View
project</a>
</div>
</div>
</div>
<div class="col-sm-12 col-md-6 col-lg-6">
<div class="card">
<img src="./assets/images/work-tbc.jpg" class="card-img-top" alt="Project 4 coming soon">
<div class="card-body">
<h5 class="card-title">Coming soon...</h5>
<p class="card-text">Lorem ipsum dolor sit amet consectetur adipisicing elit.</p>
<a href="#" class="btn btn-primary" target="_blank">View project</a>
</div>
</div>
</div>
<div class="col-sm-12 col-md-6 col-lg-6">
<div class="card">
<img src="./assets/images/work-tbc.jpg" class="card-img-top" alt="Project 5 coming soon">
<div class="card-body">
<h5 class="card-title">Coming soon...</h5>
<p class="card-text">Lorem ipsum dolor sit amet consectetur adipisicing elit.</p>
<a href="#" class="btn btn-primary" target="_blank">View project</a>
</div>
</div>
</div>
</div>
</div>
</section>
<!-- Skills -->
<section id="skills" class="container p-3">
<h2 class="fw-bold pb-3">Skills</h2>
<div class="d-flex flex-row flex-wrap justify-content-evenly list-unstyled text-center">
<p class="icon-html">HTML5</p>
<p class="icon-css">CSS3</p>
<p class="icon-bootstrap">Bootstrap</p>
<p class="icon-terminal">Terminal</p>
<p class="icon-git">Git</p>
<p class="icon-github">Github</p>
<p class="icon-javascript">JavaScript</p>
<p class="icon-api">APIs</p>
<p class="icon-node">Node.js</p>
<p class="icon-json">JSON</p>
<p class="icon-react">React.js</p>
</div>
</section>
<!-- Contact details -->
<section id="contact" class="container p-3">
<h2 class="fw-bold pb-3">Contact me</h2>
<div id="contact-info" class="d-flex flex-row justify-content-evenly">
<p><a href="mailto:jill.l.oreilly@gmail.com"><img src="./assets/images/icons/icons8-email-50.png"
alt="Email me"></a></p>
<p><a href="https://github.com/jilloreilly" target="_blank"><img
src="./assets/images/icons/icons8-github-50.png" alt="Github"></a></p>
<p><a href="https://www.linkedin.com/in/jill-o-reilly/" target="_blank"><img
src="./assets/images/icons/icons8-linked-in-50.png" alt="Linked In"></a></p>
<p><a href="./assets/Jill-OReilly-CV-Sep22.pdf" target="_blank"><img
src="./assets/images/icons/icons8-resume-50.png" alt="My Resume"></a></p>
</div>
</section>
</main>
<!-- Footer -->
<footer class="text-center py-3">
<ul class="nav ml-auto justify-content-center">
<li class="nav-item">
<a class="nav-link" href="#about">About me</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#work">Work</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#skills">Skills</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#contact">Contact me</a>
</li>
<li class="nav-item">
<a class="nav-link" href="./assets/Jill-OReilly-CV-Sep22.pdf" target="_blank">Resume</a>
</li>
</ul>
<p>© 2023 Designed and developed by Jill O'Reilly</p>
</footer>
<!-- Optional JavaScript -->
<!-- Popper.js, then Bootstrap JS -->
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.11.7/dist/umd/popper.min.js"
integrity="sha384-zYPOMqeu1DAVkHiLqWBUTcbYfZ8osu1Nd6Z89ify25QV9guujx43ITvfi12/QExE"
crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha3/dist/js/bootstrap.min.js"
integrity="sha384-Y4oOpwW3duJdCWv5ly8SCFYWqFDsfob/3GkgExXKV4idmbt98QcxXYs9UoXAB7BZ"
crossorigin="anonymous"></script>
</body>
</html> |
/**
*
*/
package HowCanIHelp;
import java.util.Calendar;
/**
* @author dweintraub
*
*/
public abstract class Item {
/**
* The Item class is an abstract class that holds general data about goods or
* services that have been inputed into the How Can I Help? database. Classes
* representing specific types of items should inherit from this class.
*/
// Declare variables
protected long userID;
protected static long itemCount = 0;
protected long itemID;
protected String itemDescription;
protected Calendar inputDate;
/**
* Constructor sets the user ID and item description and increments the static
* field itemCount in order to create a unique item ID for each item created. It
* also creates a time stamp to record the date of the item's creation.
* <p>
*
* @param userID
* @param itemDescription
*/
protected Item(long userID, String itemDescription) {
// Increment static field itemCount each time an item object is created, then
// set that as the item ID
itemCount++;
itemID = itemCount;
this.userID = userID;
this.itemDescription = itemDescription;
// Set the date of the offer to the current date
inputDate = Calendar.getInstance();
}
/**
* The getUserID method returns the user ID.
* <p>
*
* @return the user ID
*/
public long getUserID() {
return userID;
}
/**
* The setUserID method allows the user to change the user ID.
* <p>
*
* @param userID the userID to set
*/
public void setUserID(long userID) {
this.userID = userID;
}
/**
* The getItemID method returns the item ID number.
* <p>
*
* @return the itemID
*/
public long getItemID() {
return itemID;
}
/**
* The getItemDescription method returns the item description.
* <p>
*
* @return the itemDescription
*/
public String getItemDescription() {
return itemDescription;
}
/**
* The setItemDescription allows the user to change the item description.
* <p>
*
* @param itemDescription the itemDescription to set
*/
public void setItemDescription(String itemDescription) {
this.itemDescription = itemDescription;
}
/**
* The getRequestDate method returns the date the request was made.
* <p>
*
* @return the requestDate
*/
public Calendar getRequestDate() {
return inputDate;
}
@Override
public String toString() {
return "Item [user ID = " + userID + ", item ID = " + itemID + ", item description = " + itemDescription + "]";
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.