text
stringlengths
184
4.48M
import React, {useEffect, useRef, useState} from 'react' import {Button, Card, message, Modal, Table} from 'antd' import LinkButton from '../../components/LinkButton' import UserForm from './user-form' import {formatDate} from '../../utils/dateUtil' import {PAGE_SIZE} from '../../config/baseConfig' import {reqRoleList, reqUserAdd, reqUserDelete, reqUserList, reqUserUpdate} from '../../api' const User = () => { const userFormRef = useRef(null) const [user, setUser] = useState({}) const [userList, setUserList] = useState([]) const [roleList, setRoleList] = useState([]) const [isShowForm, setIsShowForm] = useState(false) useEffect(() => { queryUserList() queryRoleList() }, []) const queryUserList = () => { reqUserList().then(response => { if (response.success) { setUserList(response.data) } else { message.error(response.message).then() } }) } const queryRoleList = () => { reqRoleList().then(response => { if (response.success) { setRoleList(response.data) } else { message.error(response.message).then() } }) } const userDelete = (user) => { Modal.confirm({ title: `确认删除${user.username}吗?`, onOk: async () => { const response = await reqUserDelete(user.userId) if (response.success) { message.success('删除成功').then() queryUserList() } else { message.error(response.message).then() } }, okText: '确认', cancelText: '取消' }) } const showAdd = () => { setUser({}) setIsShowForm(true) } const showUpdate = (user) => { setUser(user) setIsShowForm(true) } const userAddOrUpdate = async () => { try { const values = await userFormRef.current.validateFields() let response let resultMessage if (user.userId) { resultMessage = '用户修改成功' response = await reqUserUpdate({userId: user.userId, ...values}) } else { resultMessage = '用户添加成功' response = await reqUserAdd(values) } if (response.success) { message.success(resultMessage).then() setIsShowForm(false) userFormRef.current.cleanFormData() queryUserList() } else { message.error(response.message).then() } } catch (err) { console.log(err) } } const columns = [ { title: '用户名', dataIndex: 'username' }, { title: '邮箱', dataIndex: 'email' }, { title: '手机号', dataIndex: 'mobile' }, { title: '所属角色', dataIndex: 'roleName' }, { title: '注册时间', dataIndex: 'createTime', render: formatDate }, { title: '操作', render: (user) => ( <span> <LinkButton onClick={() => showUpdate(user)}>修改</LinkButton> <LinkButton onClick={() => userDelete(user)}>删除</LinkButton> </span> ) } ] const title = ( <Button type="primary" onClick={showAdd}> 创建用户 </Button> ) return ( <Card title={title}> <Table bordered={true} rowKey="userId" pagination={{ showQuickJumper: true, defaultPageSize: PAGE_SIZE }} dataSource={userList} columns={columns}/> <Modal title={user.userId ? '修改用户' : '添加用户'} open={isShowForm} onOk={userAddOrUpdate} onCancel={() => setIsShowForm(false)} okText={user.userId ? '修改' : '添加'} cancelText="取消" > <UserForm ref={userFormRef} roleList={roleList} user={user}/> </Modal> </Card> ) } export default User
-- Copyright Philip Clarke 2021 -- -- --------------------------------------------------------------------- -- This source describes Open Hardware and is licensed under the CERN-OHL-S v2. -- You may redistribute and modify this source and make products using it -- under the terms of the CERN-OHL-S v2 (https://ohwr.org/cern_ohl_s_v2.txt). -- -- This source is distributed WITHOUT ANY EXPRESS OR IMPLIED -- WARRANTY, INCLUDING OF MERCHANTABILITY, SATISFACTORY -- QUALITY AND FITNESS FOR A PARTICULAR PURPOSE. Please see -- the CERN-OHL-S v2 for applicable conditions. -- -- Source location: https://github.com/hdlved/regs_and_lib_hdlmake_experiment -- -- As per CERN-OHL-S v2 section 4, should hardware be produced using this source, -- the product must visibly display the source location in its documentation. -- -- ----------------------------------------------------------------------------- -- -- This code is probably available to purchase from the orgional author under a -- different license if that suits your project better. -- -- ----------------------------------------------------------------------------- -- This is code designed to test hdlmake and FPGA tools for VHDL library support: -- Register_access_functions package... -- This is intended to show how a byte-address -> record based IF can work. -- a file like this can be machine-generated and is very human readable! -- this file is also bus protocol agnostic. -- e.g. the same source file can be used for different bus protocols -- This byte -> record approach also allows for genericisation of -- width -- if byte-enables are used on a per instance basis -- pipelining library ieee; use ieee.std_logic_1164.all; use ieee.numeric_std.all; -- library work; use work.register_types_pkg.all; package register_access_fns_pkg is procedure p_write_byte ( byte_addr : in natural; wr_prot : in std_logic_vector(2 downto 0); wr_byte : in std_logic_vector(7 downto 0); signal regs_out : inout t_regs_out; bad_wr_addr : out boolean; wr_prot_err : out boolean ); procedure p_do_wc ( signal regs_out : inout t_regs_out); procedure p_do_wr_reset ( signal regs_out : inout t_regs_out); procedure p_read_byte ( byte_addr : in natural; rd_prot : in std_logic_vector(2 downto 0); regs_out : in t_regs_out; regs_in : in t_regs_in; bad_rd_addr : out boolean; rd_prot_err : out boolean; rd_byte : out std_logic_vector(7 downto 0) ); -- OK we could have a proc for RC bits end package; package body register_access_fns_pkg is procedure p_write_byte ( byte_addr : in natural; wr_prot : in std_logic_vector(2 downto 0); wr_byte : in std_logic_Vector(7 downto 0); signal regs_out : inout t_regs_out; bad_wr_addr : out boolean; wr_prot_err : out boolean ) is begin bad_wr_addr := false; wr_prot_err := false; case (byte_addr) is when 0 => regs_out.scratchpad( 7 downto 0) <= wr_byte; when 1 => regs_out.scratchpad(15 downto 8) <= wr_byte; when 2 => regs_out.scratchpad(23 downto 16) <= wr_byte; when 3 => regs_out.scratchpad(31 downto 24) <= wr_byte; when 4 => regs_out.b_2_a <= wr_byte(regs_out.b_2_a'range); when 8 => regs_out.wc_examples <= wr_byte(1 downto 0); when 12 => regs_out.leds <= wr_byte(regs_out.leds'range); when 31 => wr_prot_err := true; when others => bad_wr_addr := true; end case; regs_out.last_aw_prot <= wr_prot; end procedure; procedure p_do_wc ( signal regs_out : inout t_regs_out) is begin regs_out.wc_examples <= (others => '0'); regs_out.leds(0) <= '0'; end procedure; procedure p_do_wr_reset ( signal regs_out : inout t_regs_out) is begin regs_out.b_2_a <= (others => '0'); regs_out.wc_examples <= (others => '0'); regs_out.leds <= (others => '1'); end procedure; procedure p_read_byte ( byte_addr : in natural; rd_prot : in std_logic_vector(2 downto 0); regs_out : in t_regs_out; regs_in : in t_regs_in; bad_rd_addr : out boolean; rd_prot_err : out boolean; rd_byte : out std_logic_vector(7 downto 0) ) is begin rd_byte := (others => '0'); bad_rd_addr := false; rd_prot_err := false; case (byte_addr) is when 0 => rd_byte := regs_out.scratchpad( 7 downto 0); when 1 => rd_byte := regs_out.scratchpad(15 downto 8); when 2 => rd_byte := regs_out.scratchpad(23 downto 16); when 3 => rd_byte := regs_out.scratchpad(31 downto 24); when 4 => rd_byte(regs_in.a_2_b'range) := regs_in.a_2_b; when 12 => rd_byte(regs_out.leds'range) := regs_out.leds; when 16 => rd_byte(2 downto 0) := regs_in.switches; when 20 => rd_prot_err := true; when 21 => rd_byte(2 downto 0) := regs_out.last_aw_prot; when others => bad_rd_addr := true; end case; end procedure; end package body register_access_fns_pkg;
from variant_visualizer.core._bio_references import _BioReference from .. import core class ProteinAnnotation(core.BioRegion): def __init__(self, start: int, end: int, reference: _BioReference, annotation_type: str, description: str, source: str, label=str): super().__init__(start, end, reference, label) self.annotation_type = annotation_type self.description = description self.source = source def __key(self): return ('ProteinAnnotation', self.start, self.end, self.reference, self.annotation_type, self.description, self.source) def __hash__(self) -> tuple: return hash(self.__key()) def __repr__(self): return f'ProteinAnnotation {self.start}-{self.end}, reference: {self.reference}, annotation_type: {self.annotation_type}, description: {self.description}, source: {self.source}' def __eq__(self, other: core.BioRegion): """Compares BioRegions. Must be implemented by subclasses.""" if isinstance(other, ProteinAnnotation): return self.__key() == other.__key() elif isinstance(other, core.BioRegion) or other is None: return False else: raise TypeError(f'Testing equality not defined between given objects.')
import _extends from "@babel/runtime/helpers/extends"; import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/objectWithoutPropertiesLoose"; var _excluded = ["onChange", "onFocus", "onBlur", "onPressEnter", "onKeyDown", "type", "disabled", "className", "inputClassName", "defaultValue", "status", "size"]; import React, { useRef, useState, forwardRef, useImperativeHandle, useEffect } from "react"; import classNames from "clsx"; import { resolveOnChange, triggerFocus } from "./utils/commonUtils"; import omit from "../../utils/omit"; import useMergedState from "../../hooks/useMergedState"; import { getPrefixCls } from "../../utils/class"; import { getMergedStatus, getStatusClassNames } from "../../utils/statusUtils"; import DisabledContext from "../../config-provider/DisabledContext"; import SizeContext from "../../config-provider/SizeContext"; import ClearableLabeledBaseInput from "./ClearableLabeledBaseInput"; var Input = /*#__PURE__*/forwardRef(function (props, ref) { var onChange = props.onChange, onFocus = props.onFocus, onBlur = props.onBlur, onPressEnter = props.onPressEnter, onKeyDown = props.onKeyDown, _props$type = props.type, type = _props$type === void 0 ? "text" : _props$type, customDisabled = props.disabled, className = props.className, inputClassName = props.inputClassName, defaultValue = props.defaultValue, customStatus = props.status, customSize = props.size, rest = _objectWithoutPropertiesLoose(props, _excluded); var prefixCls = getPrefixCls("input"); var _useMergedState = useMergedState(defaultValue, { value: props.value }), value = _useMergedState[0], setValue = _useMergedState[1]; var _useState = useState(false), focused = _useState[0], setFocused = _useState[1]; var inputRef = useRef(null); var focus = function focus(option) { if (inputRef.current) { triggerFocus(inputRef.current, option); } var size = React.useContext(SizeContext); var disabled = React.useContext(DisabledContext); var contextStatus = ""; var removePasswordTimeoutRef = useRef([]); var removePasswordTimeout = function removePasswordTimeout() { removePasswordTimeoutRef.current.push(window.setTimeout(function () { var _inputRef$current, _inputRef$current2; if (inputRef.current && ((_inputRef$current = inputRef.current) == null ? void 0 : _inputRef$current.getAttribute("type")) === "password" && (_inputRef$current2 = inputRef.current) != null && _inputRef$current2.hasAttribute("value")) { var _inputRef$current3; (_inputRef$current3 = inputRef.current) == null ? void 0 : _inputRef$current3.removeAttribute("value"); } })); }; useImperativeHandle(ref, function () { return { focus: focus, blur: function blur() { var _inputRef$current4; (_inputRef$current4 = inputRef.current) == null ? void 0 : _inputRef$current4.blur(); }, setSelectionRange: function setSelectionRange(start, end, direction) { var _inputRef$current5; (_inputRef$current5 = inputRef.current) == null ? void 0 : _inputRef$current5.setSelectionRange(start, end, direction); }, select: function select() { var _inputRef$current6; (_inputRef$current6 = inputRef.current) == null ? void 0 : _inputRef$current6.select(); }, input: inputRef.current }; }); useEffect(function () { setFocused(function (prev) { return prev && mergedDisabled ? false : prev; }); }, [mergedDisabled]); useEffect(function () { removePasswordTimeout(); return function () { return removePasswordTimeoutRef.current.forEach(function (item) { return window.clearTimeout(item); }); }; }, []); var handleChange = function handleChange(e) { if (props.value === undefined) { setValue(e.target.value); } if (inputRef.current) { resolveOnChange(inputRef.current, e, onChange); } }; var handleKeyDown = function handleKeyDown(e) { if (onPressEnter && e.key === "Enter") { onPressEnter(e); } onKeyDown == null ? void 0 : onKeyDown(e); }; var handleFocus = function handleFocus(e) { setFocused(true); removePasswordTimeout(); onFocus == null ? void 0 : onFocus(e); }; var handleBlur = function handleBlur(e) { setFocused(false); removePasswordTimeout(); onBlur == null ? void 0 : onBlur(e); }; var handleReset = function handleReset(e) { setValue(""); focus(); if (inputRef.current) { resolveOnChange(inputRef.current, e, onChange); } }; var getInputElement = function getInputElement() { var _classNames; var otherProps = omit(props, ["onPressEnter", "prefix", "suffix", "clearable", "status", "helperText", "errorText", "size", // Input elements must be either controlled or uncontrolled, // specify either the value prop, or the defaultValue prop, but not both. "defaultValue", "affixWrapperClassName", "groupClassName", "inputClassName", "wrapperClassName"]); return /*#__PURE__*/React.createElement("input", _extends({}, otherProps, { onChange: handleChange, onFocus: handleFocus, onBlur: handleBlur, onKeyDown: handleKeyDown, className: classNames(prefixCls, (_classNames = {}, _classNames[prefixCls + "-small"] = mergedSize === "small", _classNames[prefixCls + "-large"] = mergedSize === "large", _classNames[prefixCls + "-disabled"] = mergedDisabled, _classNames), (!!value || mergedStatus === "error") && getStatusClassNames(prefixCls, mergedStatus), inputClassName, className), ref: inputRef, type: type })); }; return /*#__PURE__*/React.createElement(ClearableLabeledBaseInput, _extends({}, rest, { prefixCls: prefixCls, className: className, inputElement: getInputElement(), handleReset: handleReset, value: value, focused: focused, triggerFocus: focus, disabled: mergedDisabled || undefined, status: mergedStatus })); }); export default Input;
/* * client-otr4j, the echonetwork client for otr4j. * SPDX-License-Identifier: GPL-3.0-only */ package nl.dannyvanheumen.echonetwork.client.otr4j; import net.java.otr4j.api.InstanceTag; import net.java.otr4j.api.OtrException; import net.java.otr4j.api.OtrPolicy; import net.java.otr4j.api.Session; import net.java.otr4j.api.SessionID; import net.java.otr4j.session.OtrSessionManager; import nl.dannyvanheumen.echonetwork.protocol.Client; import nl.dannyvanheumen.echonetwork.protocol.EchoProtocol; import nl.dannyvanheumen.echonetwork.utils.Strings; import nl.dannyvanheumen.echonetwork.utils.Threads; import nl.dannyvanheumen.echonetwork.utils.LogManagers; import javax.annotation.Nonnull; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.InetAddress; import java.net.Socket; import java.security.SecureRandom; import java.util.logging.Logger; import static java.util.Objects.requireNonNull; import static java.util.logging.Level.INFO; import static java.util.logging.Level.WARNING; import static nl.dannyvanheumen.echonetwork.protocol.EchoProtocol.DEFAULT_PORT; import static nl.dannyvanheumen.echonetwork.protocol.EchoProtocol.generateLocalID; import static nl.dannyvanheumen.echonetwork.protocol.EchoProtocol.receiveMessage; import static nl.dannyvanheumen.echonetwork.protocol.EchoProtocol.sendMessage; /** * EchoClient. */ public final class StdinClient implements Client { static { LogManagers.readResourceConfig("/logging.properties"); } private static final Logger LOGGER = Logger.getLogger(StdinClient.class.getName()); private StdinClient() { // No need to instantiate. } /** * Main function for starting the client. * * @param args no program parameters defined * @throws IOException In case of failure to establish client connection. * @throws OtrException In case of OTR-based exceptions. */ @SuppressWarnings({"PMD.DoNotUseThreads", "PMD.AssignmentInOperand", "InfiniteLoopStatement"}) public static void main(@Nonnull final String[] args) throws IOException, OtrException { final InstanceTag tag = InstanceTag.random(new SecureRandom()); try (Socket client = new Socket(InetAddress.getLocalHost(), DEFAULT_PORT); OutputStream out = client.getOutputStream(); InputStream in = client.getInputStream()) { final String localID = generateLocalID(client); final Host host = new Host(out, tag, new OtrPolicy(OtrPolicy.OTRL_POLICY_MANUAL)); final OtrSessionManager manager = new OtrSessionManager(host); // Network communications thread. Threads.startDaemon("StdinClient:" + localID, () -> { try { EchoProtocol.Message m; while (true) { m = receiveMessage(in); final SessionID sessionID = new SessionID(localID, m.address, DEFAULT_PROTOCOL_NAME); final Session session = manager.getSession(sessionID); try { final Session.Result message = session.transformReceiving(m.content); LOGGER.log(INFO, "Received ({0}, {1}): {2}", new Object[]{message.tag, message.status, message.content}); } catch (final OtrException e) { LOGGER.log(WARNING, "Failed to process message.", e); } } } catch (final IOException e) { LOGGER.log(WARNING, "Error reading from input: {0}", e.getMessage()); } }, Threads.createLoggingHandler(LOGGER)); // Event loop for processing user input. try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) { while (true) { final Message message = parseLine(reader.readLine()); final SessionID sessionID = new SessionID(localID, message.address, DEFAULT_PROTOCOL_NAME); final Session session = manager.getSession(sessionID); // FIXME how to transform for particular instance tag? (seems missing in API) final String[] parts = session.transformSending(message.content); sendMessage(out, message.address, parts); } } } } @Nonnull private static Message parseLine(@Nonnull final String line) { final String[] parts = Strings.cut(line, ' '); if (parts[1] == null) { throw new IllegalArgumentException("Invalid message line."); } final String[] addr = Strings.cut(parts[0], TAG_SEPARATOR); if (addr[1] == null) { return new Message(parts[0], 0, parts[1]); } else { final int tag = Integer.parseInt(addr[1]); return new Message(addr[0], tag, parts[1]); } } private static class Message { private final String address; private final int tag; private final String content; private Message(@Nonnull final String address, final int tag, @Nonnull final String content) { this.address = requireNonNull(address); this.tag = tag; this.content = requireNonNull(content); } } }
<template> <div class="container"> <pie-chart v-if="showIn" :chartdata="types" :options="options" /> <div class="display-1 text-center my-10" v-else> Não há dados no momento! </div> </div> </template> <script> import { mapState, mapMutations, mapActions } from "vuex"; import PieChart from "../Charts/Pie.vue"; export default { name: "Types", components: { PieChart }, data() { return { showIn: false, types: { labels: [], datasets: [ { data: [], backgroundColor: [], }, ], }, options: { title: { display: true, text: "", fontColor: "#0C2239", position: "top", fontStyle: "bold", fontSize: 18, }, }, }; }, computed: { ...mapState(["animals", "loaded"]), }, methods: { ...mapMutations(["UPDATE_LOAD"]), ...mapActions(["getAnimals"]), getRandomColor() { var letters = "0123456789ABCDEF"; var color = "#"; for (var i = 0; i < 6; i++) { color += letters[Math.floor(Math.random() * 16)]; } return color; }, formatChartAnimals(animals) { let labels = []; let dados = []; animals.forEach((animal) => { labels.push(animal.animal_type); dados.push({ label: animal.animal_type }); }); const formatLabel = new Set(labels); dados = [...formatLabel]; this.types.labels = dados; let qtdOcorrencias = 0; dados.forEach((element) => { animals.filter((el) => { if (el.animal_type === element) { qtdOcorrencias = qtdOcorrencias + 1; } }); this.types.datasets[0].data.push(qtdOcorrencias); this.types.datasets[0].backgroundColor.push( `${this.getRandomColor()}90` ); qtdOcorrencias = 0; }); this.options.title.text = "Tipos de animais mais atendidos"; this.showIn = true; }, }, async created() { await this.getAnimals(); await this.formatChartAnimals(this.animals); }, }; </script>
/* * Copyright 2006-2013 Alessandro Cocco. * * 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 jcodecollector.document; import javax.swing.text.AttributeSet; import javax.swing.text.BadLocationException; import javax.swing.text.PlainDocument; /** * Sotto classe di <code>PlainDocument</code>, permette di specificare il numero * massimo di caratteri accettati dal documento. * * @author Alessandro Cocco [email protected] */ public class LimitedPlainDocument extends PlainDocument { private static final long serialVersionUID = 450773819997253578L; /** Numero massimo di caratteri inseribili nel documento. */ private int maxSize; /** * Crea un <code>LimitedPlainDocument</code> che permette di inserire al * massimo <code>maxSize</code> caratteri. * * @param maxSize Il massimo numero di caratteri che possono essere inseriti * nel documento. */ public LimitedPlainDocument(int maxSize) { this.maxSize = maxSize; } /** * @see javax.swing.text.PlainDocument#insertString(int, String, * AttributeSet) */ @Override public void insertString(int offs, String str, AttributeSet a) throws BadLocationException { if (str == null) { return; } if (getLength() + str.length() > maxSize) { str = str.substring(0, maxSize - getLength()); } super.insertString(offs, str, a); } }
/* Given an integer array nums, return the length of the longest strictly increasing subsequence. A subsequence is a sequence that can be derived from an array by deleting some or no elements without changing the order of the remaining elements. For example, [3,6,2,7] is a subsequence of the array [0,3,1,6,2,2,7]. Example 1: Input: nums = [10,9,2,5,3,7,101,18] Output: 4 Explanation: The longest increasing subsequence is [2,3,7,101], therefore the length is 4. Example 2: Input: nums = [0,1,0,3,2,3] Output: 4 Example 3: Input: nums = [7,7,7,7,7,7,7] Output: 1 */ class Solution { public int lengthOfLIS(int[] nums) { //using dynamic programming approach tc=O(n log n) int[] ans=new int [nums.length]; int len=0; for(int n:nums) { int i=Arrays.binarySearch(ans,0,len,n); if(i<0) i=-(i+1); ans[i]=n; if(i==len) len++; } return len; } }
#include <TC_Memory.h> #include <cstring> #include <algorithm> // for std::for_each, copy and copy_if #include <numeric> // for std::iota #include <list> #include <vector> #include <iterator> namespace techyB { int TC_Memory::ListElem::objCount{0}; void TC_Memory::basicCopyDemo() { const int BUFF_SIZE1 = 40; char dest_buff[BUFF_SIZE1]; char src_buff[BUFF_SIZE1] = "Hello world"; // copies from src_buff to dest until null \0 character is reached std::strcpy(dest_buff, src_buff); std::cout << "copying using strscpy(dst_buff, src_buff)" << std::endl; std::cout << std::endl; std::cout << "Source char array (src_buff) : " << src_buff << std::endl; std::cout << "copied char array (dest_buff): " << dest_buff << std::endl; std::cout << std::endl << std::endl; std::cout << "Reset destination buffer using memset(dst_buff, '\\0, 40)" << std::endl; std::memset(dest_buff, '\0', BUFF_SIZE1); auto printArray = [](const char &ch) { std::cout << ", " << ch; }; std::cout << "dest buffer initial raw content : " << std::endl; std::for_each(dest_buff, dest_buff + BUFF_SIZE1, printArray); std::cout << std::endl << std::endl; std::strcpy(src_buff + strlen(src_buff) + 1, "welcome"); char dest_buff2[BUFF_SIZE1]; std::memcpy(dest_buff, src_buff, BUFF_SIZE1); std::cout << "copying using memscpy(dst_buff, src_buff2, 30)" << std::endl; std::cout << std::endl; std::cout << "dest buffer raw content after memcpy : " << std::endl; std::for_each(dest_buff, dest_buff + BUFF_SIZE1, printArray); std::cout << std::endl << std::endl; std::strcpy(dest_buff2, src_buff); std::cout << "copying using strcpy(dst_buff2, src_buff2)" << std::endl; std::cout << std::endl; std::cout << "dest buffer raw content after strcpy : " << std::endl; std::for_each(dest_buff2, dest_buff2 + BUFF_SIZE1, printArray); std::cout << std::endl << std::endl; } void TC_Memory::advancedMemoryMovement() { // 1) demo iota on linked list std::list<int> myList(10); // initialize list with values starting from 5 incrementing by 1 std::iota(myList.begin(), myList.end(), 5); auto listPrinter = [](const auto &element) { std::cout << "element : " << element << std::endl; }; // 2) demo for_each on list std::cout << "linked list content : " << std::endl; std::for_each(myList.begin(), myList.end(), listPrinter); std::cout << std::endl << std::endl; // 3) demo iota on c style array const int BUFF_SIZE = 10; int intBuffer[BUFF_SIZE]; std::iota(intBuffer, intBuffer + BUFF_SIZE, 4); // 4) demo for_each on basic C style array std::cout << "Array content : " << std::endl; std::for_each(intBuffer, intBuffer + BUFF_SIZE, listPrinter); std::cout << "Object list demonstration : " << std::endl; std::list<ListElem> objList(10); std::iota(objList.begin(), objList.end(), 1); std::cout << "Object list content : " << std::endl; std::for_each(objList.begin(), objList.end(), listPrinter); // 5) demo std::copy std::vector<int> fromVec(10); std::iota(fromVec.begin(), fromVec.end(), 0); std::vector<int> toVec; std::copy(fromVec.begin(), fromVec.end(), std::back_inserter(toVec)); std::cout << "back inserted int vector content : " << std::endl; std::for_each(toVec.begin(), toVec.end(), listPrinter); // 6) copy to ostream std::cout << "std::copy to ostream_iterator, result : " << std::endl; std::copy(toVec.begin(), toVec.end(), std::ostream_iterator<int>(std::cout, " ")); std::cout << std::endl << std::endl; // 7) copy to ostream with predicate std::cout << "std::copy to ostream_iterator with predicate for even numbers, result : " << std::endl; std::copy_if(toVec.begin(), toVec.end(), std::ostream_iterator<int>(std::cout, " "), [](const int x) { return (x % 2) == 0; }); std::cout << std::endl << std::endl; } } // namespace techyB
<?php namespace App\Http\Controllers\Backend; use App\Http\Requests\Country\UpdateCountryRequest; use Illuminate\Contracts\View\View; use App\Contracts\Backend\CountryContract; use App\Http\Requests\Country\StoreCountryRequest; use App\Services\UtilService; use App\Http\Enums\CommonEnum; use Illuminate\Http\RedirectResponse; use App\DataTables\CountryDataTable; class CountryController extends Controller { /** * @var CountryContract */ protected $countryRepository; public function __construct(CountryContract $countryRepository) { $this->countryRepository = $countryRepository; } /** * Display a listing of the resource. */ public function index( UtilService $utilService, CountryDataTable $dataTable ) { try { return $dataTable->render('backend.pages.country.index'); } catch (\Exception $exception) { return $utilService->logErrorAndRedirectToBack('backend.pages.country.index', $exception->getMessage()); } } /** * Show the form for creating a new resource. */ public function create(): View { return view('backend.pages.country.create'); } /** * @param StoreCountryRequest $request * @param UtilService $utilService * @return RedirectResponse */ public function store(StoreCountryRequest $request, UtilService $utilService): RedirectResponse { try { $data = $request->validated(); $this->countryRepository->createCountry($data); return redirect()->route("backend.pages.country.index")->with([ "status" => CommonEnum::SUCCESS_STATUS, "message" => "Country has been added successfully." ]); } catch (\Exception $exception) { return $utilService->logErrorAndRedirectToBack('backend.pages.country.store', $exception->getMessage()); } } public function edit($id, UtilService $utilService) { try { $country = $this->countryRepository->findCountryById($id); return view('backend.pages.country.edit', compact('country')); } catch (\Exception $exception) { return $utilService->logErrorAndRedirectToBack('backend.pages.country.edit', $exception->getMessage()); } } /** * @param $id * @param UpdateCountryRequest $request * @param UtilService $utilService * @return RedirectResponse */ public function update($id, UpdateCountryRequest $request, UtilService $utilService) { try { $data = $request->validated(); $this->countryRepository->updateCountry($id, $data); return redirect()->route("backend.pages.country.index")->with([ "status" => CommonEnum::SUCCESS_STATUS, "message" => "Country has been updated successfully." ]); } catch (\Exception $exception) { return $utilService->logErrorAndRedirectToBack('backend.pages.country.update', $exception->getMessage()); } } /** * Remove the specified resource from storage. */ public function destroy($id, UtilService $utilService) { try { $this->countryRepository->deleteCountry($id); return redirect()->route("backend.pages.country.index")->with([ "status" => CommonEnum::SUCCESS_STATUS, "message" => "Country has been deleted successfully." ]); } catch (\Exception $exception) { return $utilService->logErrorAndRedirectToBack('backend.pages.country.destroy', $exception->getMessage()); } } }
package com.projet_voiture.projet_voiture.controller; import java.util.List; import java.util.Optional; 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.projet_voiture.projet_voiture.modele.Categorie; import com.projet_voiture.projet_voiture.service.CategorieService; @RequestMapping("/categorie") @RestController public class CategorieController { @Autowired private CategorieService service; @GetMapping public List<Categorie> list() { return service.list(); } @GetMapping("/{id}") public Optional<Categorie> findById(@PathVariable("id") int id) { return service.findById(id); } @PostMapping public ResponseEntity<Categorie> insert( @RequestBody Categorie Categorie ) { try { Categorie inserted = service.insert(Categorie); return new ResponseEntity<>(inserted, HttpStatus.CREATED); } catch (Exception e) { return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR); } } @PutMapping("/{id}") public ResponseEntity<Categorie> update( @PathVariable("id") int id, @RequestBody Categorie Categorie ) { Optional<Categorie> to_update = service.findById(id); if (to_update.isPresent()) { Categorie updated = to_update.get(); updated.setNomcategorie( Categorie.getNomcategorie() ); return new ResponseEntity<Categorie>( service.insert(updated), HttpStatus.OK ); } return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR); } @DeleteMapping("/{id}") public ResponseEntity<HttpStatus> deleteById(@PathVariable("id") int id) { try { service.deleteById(id); return new ResponseEntity<>(HttpStatus.OK); } catch (Exception e) { return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); } } }
<!DOCTYPE html> <html lang="en"> <head> {% include "partials/header.html" %} <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/bbbootstrap/libraries@main/choices.min.css"> <script src="https://cdn.jsdelivr.net/gh/bbbootstrap/libraries@main/choices.min.js"></script> </head> <body class="sb-nav-fixed"> <nav class="sb-topnav navbar navbar-expand navbar-dark bg-dark"> {% include "partials/navbar.html" %} </nav> <div id="layoutSidenav"> <div id="layoutSidenav_nav"> <nav class="sb-sidenav accordion sb-sidenav-dark" id="sidenavAccordion"> <div class="sb-sidenav-menu"> {% include "partials/sidebar.html" %} </div> </nav> </div> <div id="layoutSidenav_content"> <main> <div class="container-fluid px-4"> <h1 class="mt-4">Datates</h1> <ol class="breadcrumb mb-4"> <li class="breadcrumb-item active">Datates</li> </ol> <div class="card mb-4"> <div class="card-header"> <i class="fas fa-table me-1"></i> Input </div> <div class="card-body"> <form action="/datates" method="post" class="form-inline"> <div class="form-group"> <input type="text" class="form-control" id="keyword" placeholder="example:astrazeneca sinovac/efek vaksin" name="keyword"> <input type="checkbox" id="astrazeneca" name="astrazeneca" value="astrazeneca"> <label for="astra">astrazeneca</label><br> <input type="checkbox" id="sinovac" name="sinovac" value="sinovac"> <label for="sinovac">sinovac</label><br> <input type="checkbox" id="moderna" name="moderna" value="moderna"> <label for="moderna">moderna</label><br> <input type="checkbox" id="pfizer" name="pfizer" value="pfizer"> <label for="pfizer">pfizer</label><br> <script> let kword = ''; const astra = document.getElementById('astrazeneca') astra.addEventListener('change', (event) => { if (event.currentTarget.checked) { kword+=' astrazeneca' } else { kword = kword.replace('astrazeneca', ''); } kword = kword.trim(); document.getElementById("keyword").value = kword; }); const sinovac = document.getElementById('sinovac') sinovac.addEventListener('change', (event) => { if (event.currentTarget.checked) { kword+=' sinovac' } else { kword = kword.replace('sinovac', ''); } kword = kword.trim(); document.getElementById("keyword").value = kword; }); const moderna = document.getElementById('moderna') moderna.addEventListener('change', (event) => { if (event.currentTarget.checked) { kword+=' moderna' } else { kword = kword.replace('moderna', ''); } kword = kword.trim(); document.getElementById("keyword").value = kword; }); const pfizer = document.getElementById('pfizer') pfizer.addEventListener('change', (event) => { if (event.currentTarget.checked) { kword+=' pfizer' } else { kword = kword.replace('pfizer', ''); } kword = kword.trim(); document.getElementById("keyword").value = kword; }); </script> </div> <br> <div class="form-group"> <button type="submit" class="form-control btn btn-primary" name="query" value="query">Submit</button> </div> </form> </div> </div> <div class="card mb-4"> <div class="card-header"> <i class="fas fa-table me-1"></i> Data Tes </div> <div class="card-body"> {% if data is defined %} <table id="datatablesSimple"> <thead> <tr> <th>No</th> <th>Tanggal</th> <th>Tweet</th> </tr> </thead> <tfoot> <tr> <th>No</th> <th>Tanggal</th> <th>Tweet</th> </tr> </tfoot> <tbody> {% set no = namespace(value=1) %} {% for tweet in data %} <tr> <td>{{ no.value }}</td> <td>{{ tweet[0] }}</td> <td>{{ tweet[1] }}</td> <!-- <td>{{ date }}</td> --> {% set no.value = no.value + 1 %} </tr> {% endfor %} </tbody> </table> <br> <form action="/datates" method="post" class="form-inline"> <div class="form-group"> <button type="submit" class="form-control btn btn-success" name="proses" value="proses">Proses</button> </div> </form> {% endif %} </div> </div> </div> </main> <footer class="py-4 bg-light mt-auto"> {% include "partials/copyright.html" %} </footer> </div> </div> {% include "partials/footer.html" %} </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>DynamicSelector</title> </head> <!-- This is Link for Bootstrap CSS --> <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous"> <!-- This is End for Bootstrap Css --> <link rel="stylesheet" href="./index.css"> <body> <!-- This si Navbar --> <nav class="navbar navbar-expand-lg bg-body-tertiary"> <div class="container-fluid"> <a class="navbar-brand" href="#">Dynamic Selector</a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarNav" style="margin-left: 30px;"> <ul class="navbar-nav"> <li class="nav-item"> <button id="edi" style="font-weight: bold; color: black; font-size: 2rem;margin-top: 6px; background:none; border: none;">EDI</button> </li> <li class="nav-item"> <button class="nav-link" id="sdp" style="font-weight: bold; color: black; font-size: 2rem;margin-left: 20px; background:none; border: none;">SDP</button> </li> <li class="nav-item"> <button class="nav-link" id="cpbut" style="font-weight: bold; color: black; font-size: 2rem;margin-left: 20px; background:none; border: none;">CourseProject</button> </li> </ul> </div> </div> </nav> <!-- This is End of Navbar --> <div class="Container"> <div class="card" style="width: 18rem;" id="homecard"> <img src="./Images/Welcome.png" height="125px" width="100px" class="card-img-top" alt="..."> <div class="card-body"> <h5 class="card-title">WELCOME to Dynamic Selector</h5> <p class="card-text">Welcome to the dynamic hub of knowledge and innovation at VIT! Our website is designed to be your gateway to a world of cutting-edge subjects that empower you for the challenges of today and the opportunities of tomorrow.</p> </div> </div> <div class="card" id="first" style="display: none; width: 25rem;"> <img src="./Images/Projects.png" height="125px" width="100px" class="card-img-top" alt="..."> <div class="card-body"> <h5 class="card-title">EDI</h5> <p class="card-text">Welcome to VIT's Engineering and Innovation Projects (EDI) – where hands-on learning meets groundbreaking solutions. Key Highlights: Project-Based Learning: Immerse yourself in real-world challenges, bridging theory and practice. Interdisciplinary Collaboration: Work with peers from diverse engineering disciplines for a holistic approach to problem-solving.</p> </div> </div> <div class="card" id="second" style="display: none; width: 25rem;"> <img src="./Images/sdp.png" class="card-img-top" alt="..."> <div class="card-body"> <h5 class="card-title">SDP</h5> <p class="card-text">Embark on a journey through the realm of Software Development Project, where theory meets practice to shape the digital landscape. Explore the intricacies of coding, algorithm design, and software architecture. Our SDT program equips you with the skills needed to craft robust, scalable, and innovative solutions in the ever-evolving world of technology.</p> </div> </div> <div class="card" id="third" style="display: none; width: 25rem;"> <img src="./Images/cp.png" class="card-img-top" alt="..."> <div class="card-body"> <h5 class="card-title">Course Project</h5> <p class="card-text">Welcome to VIT's Course Projects (CP), where theory seamlessly transforms into practice through hands-on mini projects aligned with lab sessions. Dive into diverse projects spanning software development to electronic instrumentation, gaining practical exposure and enhancing your problem-solving skills. Collaborate with peers, benefit from faculty mentorship, and celebrate your achievements at the end-of-semester Project Showcase.</p> </div> </div> </div> </body> <script> let FirstDiv = document.querySelector("#first") let SecondDiv = document.querySelector("#second") let ThirdDiv = document.querySelector("#third") let edibut = document.querySelector("#edi"); let sdpbut = document.querySelector("#sdp"); let cpbut = document.querySelector("#cpbut"); let homecard = document.querySelector("#homecard"); edibut.addEventListener("click", (e) => { e.preventDefault(); homecard.style.display = "none"; ThirdDiv.style.display = "none"; SecondDiv.style.display = "none"; FirstDiv.style.display = "block"; }); sdpbut.addEventListener("click", (e) => { e.preventDefault(); FirstDiv.style.display = "none"; homecard.style.display = "none"; ThirdDiv.style.display = "none"; SecondDiv.style.display = "block"; }); cpbut.addEventListener("click", (e) => { e.preventDefault(); FirstDiv.style.display = "none"; homecard.style.display = "none"; ThirdDiv.style.display = "block"; SecondDiv.style.display = "none"; }); </script> <!-- This is Bootstrap Js --> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-C6RzsynM9kWDrMNeT87bh95OGNyZPhcTNXj1NW7RuBCsyN/o0jlpcV8Qyq46cDfL" crossorigin="anonymous"></script> <!-- This is End of BootstrapJS --> </html>
package com.ssafy.kkoma.api.member.controller; import com.ssafy.kkoma.api.member.service.MemberService; import com.ssafy.kkoma.api.offer.service.OfferService; import com.ssafy.kkoma.api.product.dto.OfferedProductInfoResponse; import com.ssafy.kkoma.api.product.dto.ProductInfoResponse; import com.ssafy.kkoma.domain.product.constant.ProductType; import com.ssafy.kkoma.global.resolver.memberinfo.MemberInfo; import com.ssafy.kkoma.global.resolver.memberinfo.MemberInfoDto; import com.ssafy.kkoma.global.util.ApiUtils; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.security.SecurityRequirement; import io.swagger.v3.oas.annotations.tags.Tag; import lombok.RequiredArgsConstructor; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import java.util.ArrayList; import java.util.Comparator; import java.util.List; @RestController @RequestMapping("/api/members") @RequiredArgsConstructor public class MemberController { private final MemberService memberService; private final OfferService offerService; @Tag(name = "Member Activity") @Operation( summary = "유저 관련 상품글 전체 조회", description = "[[노션](https://www.notion.so/todays-jiwoo/5aa3a0c8457942fc87def3e075a8e7a1?pvs=4)]", security = { @SecurityRequirement(name = "bearer-key") } ) @GetMapping("/products") ResponseEntity<ApiUtils.ApiResult<List<?>>> getMyProducts( @MemberInfo MemberInfoDto memberInfoDto, @RequestParam("type") String type ) { Long memberId = memberInfoDto.getMemberId(); List<ProductInfoResponse> productInfoResponses = new ArrayList<>(); if ("sell".equals(type)) { productInfoResponses = memberService.getMySellingProducts(memberId, ProductType.SALE, ProductType.SOLD); } else if ("progress".equals(type)) { List<ProductInfoResponse> buyingProductResponses = offerService.getProgressOfferingProducts(memberId); List<ProductInfoResponse> sellingProductResponses = memberService.getMySellingProducts(memberId, ProductType.PROGRESS); productInfoResponses.addAll(buyingProductResponses); productInfoResponses.addAll(sellingProductResponses); productInfoResponses.sort(Comparator.comparing(ProductInfoResponse::getSelectedTime)); // 거래 수락일 오름차순 정렬 } return ResponseEntity.ok().body(ApiUtils.success(productInfoResponses)); } @Tag(name = "Member Activity") @Operation( security = { @SecurityRequirement(name = "bearer-key") } ) @GetMapping("/products/buy") ResponseEntity<ApiUtils.ApiResult<List<OfferedProductInfoResponse>>> getMyProducts( @MemberInfo MemberInfoDto memberInfoDto ) { Long memberId = memberInfoDto.getMemberId(); List<OfferedProductInfoResponse> offeredProductInfoResponses = offerService.getNotProgressOfferingProducts(memberId); return ResponseEntity.ok().body(ApiUtils.success(offeredProductInfoResponses)); } }
import torch import torchvision import torch.optim as optim import os import json import pandas as pd import numpy as np from sklearn import svm from sklearn.metrics import accuracy_score, precision_score class CPD_SSL(): def __init__(self, backbone, feature_size, device): self.backbone = self.backbone_load(backbone, feature_size, device) self.device = device def backbone_load(self, backbone, feature_size, device): # 1. SqueezeNet if backbone == 'SqeezeNet': squeeze_net = torchvision.models.squeezenet1_1(progress=True).to(device) squeeze_net.classifier = torch.nn.Sequential( torch.nn.AdaptiveAvgPool2d(output_size=(1,1)), torch.nn.Flatten(), torch.nn.Linear(512, feature_size, bias=True)) return squeeze_net # 2. ShuffleNet elif backbone == 'ShuffleNet': shuffle_net = torchvision.models.shufflenet_v2_x2_0().to(device) shuffle_net.fc = torch.nn.Linear(in_features=2048, out_features=feature_size, bias=True) return shuffle_net # 3. RegNet elif backbone == 'RegNet': reg_net = torchvision.models.regnet_y_1_6gf().to(device) reg_net.fc = torch.nn.Linear(in_features=888, out_features=feature_size, bias=True) return reg_net # 4. MobileNet elif backbone == 'MobileNet': mobile_net = torchvision.models.mobilenet_v3_large().to(device) mobile_net.classifier = torch.nn.Sequential( torch.nn.Linear(960, 1280, bias=True), torch.nn.Linear(1280, feature_size, bias=True)) return mobile_net # 5. EfficientNet elif backbone == 'EfficientNet': efficient_net = torchvision.models.efficientnet_b2().to(device) efficient_net.classifier = torch.nn.Sequential( torch.nn.Dropout(p=0.3, inplace=True), torch.nn.Linear(in_features=1408, out_features=feature_size, bias=True)) return efficient_net # 6. MnasNet elif backbone == 'MnasNet': mnas_net = torchvision.models.mnasnet1_3().to(device) mnas_net.classifier = torch.nn.Sequential( torch.nn.Dropout(p=0.2, inplace=True), torch.nn.Linear(in_features=1280, out_features=feature_size, bias=True)) return mnas_net else: print(f'Error : Unspportable Backbone - {backbone}') def train(self, train_loader, epoch, transforms): optimier = optim.Adam(self.backbone.parameters(), lr=0.001) self.experiment_name = self.backbone.__class__.__name__ print(f'backbone : {self.backbone.__class__.__name__}') self.output_path = os.path.join(os.getcwd(), 'outputs_k32_s16' ,self.experiment_name) if os.path.isdir(self.output_path): print(f'Error : path{self.output_path} is already exist') exit() os.makedirs(self.output_path) result ={'Epoch' : [], 'loss_epoch' : [], 'mean_pos' : [], 'mean_neg' : [], } result_df = pd.DataFrame(result) best_loss = 1000000000000000 for i in range(epoch): loss_epoch, mean_pos_epoch, mean_neg_epoch = self.train_one_epoch(data_loader=train_loader, optimizer=optimier, transforms=transforms) print(f'Epoch : {i}/{epoch} | loss_epoch : {loss_epoch} | mean_pos : {mean_pos_epoch} | mean_neg : {mean_neg_epoch}') new_data = { 'Epoch': [int(i)], 'loss_epoch': [loss_epoch], 'mean_pos': [mean_pos_epoch], 'mean_neg' : [mean_neg_epoch] } new_data = pd.DataFrame(new_data) result_df = pd.concat([result_df, new_data]) if i%10 == 0: torch.save(self.backbone.state_dict(), os.path.join(self.output_path, f'Epoch_{i}.pth')) if loss_epoch < best_loss: print(f'Best Loss : {loss_epoch}') torch.save(self.backbone.state_dict(), os.path.join(self.output_path, f'Best_Loss.pth')) best_loss = loss_epoch self.save_dataframe_as_json(result_df) def save_dataframe_as_json(self, dataframe): path = str(self.output_path) + '/result.json' dataframe.to_json(path, orient='records', indent=4) def train_one_epoch(self, data_loader, optimizer, transforms=None): loss_epoch = 0.0 mean_pos_epoch = 0.0 mean_neg_epoch = 0.0 for idx, batch in enumerate(data_loader): data_stft, class_tensor, is_new = batch data_stft.to(self.device) if transforms is not None: data_stft = transforms(data_stft) loss_step, mean_pos, mean_neg = self.train_one_step(data_stft, optimizer) loss_epoch += loss_step mean_pos_epoch += mean_pos mean_neg_epoch += mean_neg loss_epoch /= len(data_loader) mean_pos_epoch /= len(data_loader) mean_neg_epoch /= len(data_loader) return loss_epoch, mean_pos_epoch, mean_neg_epoch def train_one_step(self, batch, optimizer): loss = InfoNCE(negative_mode='paired').to(self.device) batch = batch.to(self.device) batch = self.backbone(batch).to(self.device) query = batch[:-1] positive_pair = batch[1:] negative_pair = [] for i in range(len(batch)-1): neg_i = [] for j in range(len(batch)): if i!=j and j!=i+1: neg_i.append(batch[j]) neg_i = torch.stack(neg_i) negative_pair.append(neg_i) negative_pair = torch.stack(negative_pair).to(self.device) loss_step, mean_pos, mean_neg = loss(query, positive_pair, negative_pair) optimizer.zero_grad() loss_step.backward() optimizer.step() return loss_step.item(), mean_pos.item(), mean_neg.item() def valid_one_epoch(self, data_loader,file_name, threshold = 0.0, transforms=None): best_acc = 0.0 self.backbone.eval() self.experiment_name = self.backbone.__class__.__name__ self.output_path = os.path.join(os.getcwd(), 'outputs_nfft16_h2_b64_k64_s32' ,self.experiment_name) true_correct = 0 false_correct = 0 true_negative = 0 false_negative = 0 total = 0 precision = 0 acc = 0 setting_threshold = threshold anomally = 0.0 with torch.no_grad(): for index, batches in enumerate(data_loader): data_stft, labels, is_new = batches for label in labels: start_l = label[0] for l in label: if start_l == l: continue else: anomally +=1 break data_stft.to(self.device) if transforms is not None: data_stft = transforms(data_stft) batch = self.backbone(data_stft) cos_sim_list = [] for idx in range(len(batch)): # 각 배치별 if idx + 1 >= len(batch): break cos_sim_f = nn.CosineSimilarity(dim=0) cos_sim = cos_sim_f(batch[idx],batch[idx+1]) # 근사한 2쌍 cosine similarity cos_sim_list.append(cos_sim) print(cos_sim) total += len(cos_sim_list) for idx in range(len(cos_sim_list)): if cos_sim_list[idx] < setting_threshold: # 해당 배치가 threshold 이하인지 l1_0 = labels[idx][0] # l0 = len(set(labels[idx].unique().numpy())) tf_flag1 = True for l_ in labels[idx]: # 실제 CP인지 확인 if l1_0 == l_: continue else: tf_flag1 = False true_correct += 1 break tf_flag2 = True if tf_flag1 == True: l2_0 = labels[idx + 1][0] # l0 = len(set(labels[idx].unique().numpy())) for l__ in labels[idx + 1]: # 실제 CP인지 확인 if l2_0 == l__: continue else: true_correct += 1 tf_flag2 = False break if tf_flag1 == True and tf_flag2 == True: false_correct += 1 if cos_sim_list[idx] >= setting_threshold: # 해당 배치가 threshold 이하인지 # l0 = len(set(labels[idx].unique().numpy())) l1_0 = labels[idx][0] tf_flag1 = True for l_ in labels[idx]: # 실제 CP인지 확인 if l1_0 == l_: continue else: tf_flag1 = False false_negative += 1 break # l0 = len(set(labels[idx].unique().numpy())) l2_0 = labels[idx + 1][0] tf_flag2 = True if tf_flag1 == True: for l__ in labels[idx + 1]: # 실제 CP인지 확인 if l2_0 == l__: continue else: tf_flag2 = False false_negative += 1 break if tf_flag1 == True and tf_flag2 == True: true_negative +=1 # correct += (predicted == targets).sum().item() #print(labels) #print(true_correct, anomally) if true_correct + false_correct > 0: precision = true_correct / (true_correct + false_correct) * 100 acc = (true_correct + true_negative) / (true_correct + false_correct + true_negative + false_negative) * 100 print(f'[Test] index: {index + 1} | Acc: {acc} | Precision : {precision:.4f}') if true_correct + false_correct > 0: precision = true_correct / (true_correct + false_correct) * 100 acc = (true_correct + true_negative) / (true_correct + false_correct + true_negative + false_negative) * 100 print(f'[Test] epoch: {1} | Acc: {acc} | Precision : {precision:.4f}') print(f'[Test] epoch: {1} | anomallay: {anomally} | true correct : {true_correct} | false correct : {false_correct} | true negative : {true_negative} | false negative : {false_negative}') print(f'total : {total} | anomallay: {anomally} | sum {true_correct + true_negative + false_correct +false_negative}') directory, epoch = os.path.split(file_name) result = {'model' : [self.experiment_name + epoch], 'threshold' : [threshold], 'Acc' : [acc], 'Precision' : [precision] } epoch = epoch.split('.')[0] result_df = pd.DataFrame(result) path = str(self.output_path) + '/' + self.experiment_name + '_' + epoch + '_' + str(threshold) + '_Acc_Precision.json' print(self.output_path) result_df.to_json(path, orient='records', indent=4) def train_auto(self, train_loader, epoch, transforms, folder_name): optimier = optim.Adam(self.backbone.parameters(), lr=0.001) self.experiment_name = self.backbone.__class__.__name__ print(f'backbone : {self.backbone.__class__.__name__}') self.output_path = os.path.join(os.getcwd(), folder_name ,self.experiment_name) if os.path.isdir(self.output_path): print(f'Error : path{self.output_path} is already exist') exit() os.makedirs(self.output_path) result ={'Epoch' : [], 'loss_epoch' : [], 'mean_pos' : [], 'mean_neg' : [], } result_df = pd.DataFrame(result) best_loss = 1000000000000000 for i in range(epoch): loss_epoch, mean_pos_epoch, mean_neg_epoch = self.train_one_epoch(data_loader=train_loader, optimizer=optimier, transforms=transforms) print(f'Epoch : {i}/{epoch} | loss_epoch : {loss_epoch} | mean_pos : {mean_pos_epoch} | mean_neg : {mean_neg_epoch}') new_data = { 'Epoch': [int(i)], 'loss_epoch': [loss_epoch], 'mean_pos': [mean_pos_epoch], 'mean_neg' : [mean_neg_epoch] } new_data = pd.DataFrame(new_data) result_df = pd.concat([result_df, new_data]) if i%10 == 0: torch.save(self.backbone.state_dict(), os.path.join(self.output_path, f'Epoch_{i}.pth')) if loss_epoch < best_loss: print(f'Best Loss : {loss_epoch}') torch.save(self.backbone.state_dict(), os.path.join(self.output_path, f'Best_Loss.pth')) best_loss = loss_epoch self.save_dataframe_as_json(result_df) def valid_auto(self, data_loader, epoch, folder_name, threshold = 0.0, transforms=None): best_acc = 0.0 self.backbone.eval() self.experiment_name = self.backbone.__class__.__name__ self.output_path = os.path.join(os.getcwd(), folder_name ,self.experiment_name) true_correct = 0 false_correct = 0 true_negative = 0 false_negative = 0 total = 0 precision = 0 acc = 0 setting_threshold = threshold anomally = 0.0 with torch.no_grad(): for index, batches in enumerate(data_loader): data_stft, labels, is_new = batches for label in labels: start_l = label[0] for l in label: if start_l == l: continue else: anomally +=1 break data_stft.to(self.device) if transforms is not None: data_stft = transforms(data_stft) batch = self.backbone(data_stft) cos_sim_list = [] for idx in range(len(batch)): # 각 배치별 if idx + 1 >= len(batch): break cos_sim_f = nn.CosineSimilarity(dim=0) cos_sim = cos_sim_f(batch[idx],batch[idx+1]) # 근사한 2쌍 cosine similarity cos_sim_list.append(cos_sim) print(cos_sim) total += len(cos_sim_list) for idx in range(len(cos_sim_list)): if cos_sim_list[idx] < setting_threshold: # 해당 배치가 threshold 이하인지 l1_0 = labels[idx][0] # l0 = len(set(labels[idx].unique().numpy())) tf_flag1 = True for l_ in labels[idx]: # 실제 CP인지 확인 if l1_0 == l_: continue else: tf_flag1 = False true_correct += 1 break tf_flag2 = True if tf_flag1 == True: l2_0 = labels[idx + 1][0] # l0 = len(set(labels[idx].unique().numpy())) for l__ in labels[idx + 1]: # 실제 CP인지 확인 if l2_0 == l__: continue else: true_correct += 1 tf_flag2 = False break if tf_flag1 == True and tf_flag2 == True: false_correct += 1 if cos_sim_list[idx] >= setting_threshold: # 해당 배치가 threshold 이하인지 # l0 = len(set(labels[idx].unique().numpy())) l1_0 = labels[idx][0] tf_flag1 = True for l_ in labels[idx]: # 실제 CP인지 확인 if l1_0 == l_: continue else: tf_flag1 = False false_negative += 1 break # l0 = len(set(labels[idx].unique().numpy())) l2_0 = labels[idx + 1][0] tf_flag2 = True if tf_flag1 == True: for l__ in labels[idx + 1]: # 실제 CP인지 확인 if l2_0 == l__: continue else: tf_flag2 = False false_negative += 1 break if tf_flag1 == True and tf_flag2 == True: true_negative +=1 # correct += (predicted == targets).sum().item() #print(labels) #print(true_correct, anomally) if true_correct + false_correct > 0: precision = true_correct / (true_correct + false_correct) * 100 acc = (true_correct + true_negative) / (true_correct + false_correct + true_negative + false_negative) * 100 print(f'[Test] index: {index + 1} | Acc: {acc} | Precision : {precision:.4f}') if true_correct + false_correct > 0: precision = true_correct / (true_correct + false_correct) * 100 acc = (true_correct + true_negative) / (true_correct + false_correct + true_negative + false_negative) * 100 print(f'[Test] epoch: {1} | Acc: {acc} | Precision : {precision:.4f}') result = {'model' : [self.experiment_name + '_' + str(epoch)], 'threshold' : [threshold], 'Acc' : [acc], 'Precision' : [precision] } result_df = pd.DataFrame(result) path = str(self.output_path) + '/' + self.experiment_name + '_' + str(epoch) + '_' + str(threshold) + '_Acc_Precision.json' result_df.to_json(path, orient='records', indent=4) def train_set(self, folder_name, train_loader, test_loader, epochs, transforms): self.train_auto(train_loader, epochs, transforms, folder_name) threshold = [0.0, 0.4, 0.6] for thre in threshold: self.valid_auto(test_loader, epochs, folder_name, thre, transforms) def load_model(self, pth_path=None): self.experiment_name = self.backbone.__class__.__name__ print(f'backbone : {self.backbone.__class__.__name__}') self.output_path = os.path.join(os.getcwd(), 'outputs_h2_b64_k128_s64' ,self.experiment_name) if pth_path is None: best_pth = os.path.join(self.output_path, 'Best_Loss.pth') self.backbone.load_state_dict(torch.load(best_pth)) print(best_pth) else: self.backbone.load_state_dict(torch.load(pth_path)) print(pth_path) def train_classifier(self, data_loader,transforms): train_data, train_labels = self.load_classify_dataset(dataloader=data_loader, transforms=transforms) self.clf = svm.SVC(kernel='linear', decision_function_shape='ovr') self.clf.fit(train_data, train_labels) print('Finish_Train') def test_classifier(self, data_loader,transforms): test_data, test_labels = self.load_classify_dataset(dataloader=data_loader, transforms=transforms) predictions = self.clf.predict(test_data) # 정확도 계산 accuracy = accuracy_score(test_labels, predictions) # 정밀도 계산 precision = precision_score(test_labels, predictions, average='weighted') # 결과 출력 print(f'정확도: {accuracy:.2f}') print(f'정밀도: {precision:.2f}') return accuracy, precision def load_classify_dataset(self, dataloader, transforms): dataset_np = [] class_np = [] for batch in dataloader: data, class_tensor, is_new = batch class_info = class_tensor[0][0].item() data = data.to(self.device) if transforms is not None: data = transforms(data) feature = self.backbone(data) feature = feature.squeeze(dim=0).detach().tolist() dataset_np.append(feature) class_np.append(class_info) dataset_np = np.array(dataset_np) class_np = np.array(class_np) return dataset_np, class_np import torch import torch.nn.functional as F from torch import nn __all__ = ['InfoNCE', 'info_nce'] class InfoNCE(nn.Module): """ Calculates the InfoNCE loss for self-supervised learning. This contrastive loss enforces the embeddings of similar (positive) samples to be close and those of different (negative) samples to be distant. A query embedding is compared with one positive key and with one or more negative keys. References: https://arxiv.org/abs/1807.03748v2 https://arxiv.org/abs/2010.05113 Args: temperature: Logits are divided by temperature before calculating the cross entropy. reduction: Reduction method applied to the output. Value must be one of ['none', 'sum', 'mean']. See torch.nn.functional.cross_entropy for more details about each option. negative_mode: Determines how the (optional) negative_keys are handled. Value must be one of ['paired', 'unpaired']. If 'paired', then each query sample is paired with a number of negative keys. Comparable to a triplet loss, but with multiple negatives per sample. If 'unpaired', then the set of negative keys are all unrelated to any positive key. Input shape: query: (N, D) Tensor with query samples (e.g. embeddings of the input). positive_key: (N, D) Tensor with positive samples (e.g. embeddings of augmented input). negative_keys (optional): Tensor with negative samples (e.g. embeddings of other inputs) If negative_mode = 'paired', then negative_keys is a (N, M, D) Tensor. If negative_mode = 'unpaired', then negative_keys is a (M, D) Tensor. If None, then the negative keys for a sample are the positive keys for the other samples. Returns: Value of the InfoNCE Loss. Examples: >>> loss = InfoNCE() >>> batch_size, num_negative, embedding_size = 32, 48, 128 >>> query = torch.randn(batch_size, embedding_size) >>> positive_key = torch.randn(batch_size, embedding_size) >>> negative_keys = torch.randn(num_negative, embedding_size) >>> output = loss(query, positive_key, negative_keys) """ def __init__(self, temperature=0.1, reduction='mean', negative_mode='unpaired'): super().__init__() self.temperature = temperature self.reduction = reduction self.negative_mode = negative_mode def forward(self, query, positive_key, negative_keys=None): return info_nce(query, positive_key, negative_keys, temperature=self.temperature, reduction=self.reduction, negative_mode=self.negative_mode) def info_nce(query, positive_key, negative_keys=None, temperature=0.1, reduction='mean', negative_mode='unpaired'): # Check input dimensionality. if query.dim() != 2: raise ValueError('<query> must have 2 dimensions.') if positive_key.dim() != 2: raise ValueError('<positive_key> must have 2 dimensions.') if negative_keys is not None: if negative_mode == 'unpaired' and negative_keys.dim() != 2: raise ValueError("<negative_keys> must have 2 dimensions if <negative_mode> == 'unpaired'.") if negative_mode == 'paired' and negative_keys.dim() != 3: raise ValueError("<negative_keys> must have 3 dimensions if <negative_mode> == 'paired'.") # Check matching number of samples. if len(query) != len(positive_key): raise ValueError('<query> and <positive_key> must must have the same number of samples.') if negative_keys is not None: if negative_mode == 'paired' and len(query) != len(negative_keys): raise ValueError("If negative_mode == 'paired', then <negative_keys> must have the same number of samples as <query>.") # Embedding vectors should have same number of components. if query.shape[-1] != positive_key.shape[-1]: raise ValueError('Vectors of <query> and <positive_key> should have the same number of components.') if negative_keys is not None: if query.shape[-1] != negative_keys.shape[-1]: raise ValueError('Vectors of <query> and <negative_keys> should have the same number of components.') # Normalize to unit vectors query, positive_key, negative_keys = normalize(query, positive_key, negative_keys) if negative_keys is not None: # Explicit negative keys # Cosine between positive pairs positive_logit = torch.sum(query * positive_key, dim=1, keepdim=True) if negative_mode == 'unpaired': # Cosine between all query-negative combinations negative_logits = query @ transpose(negative_keys) elif negative_mode == 'paired': query = query.unsqueeze(1) negative_logits = query @ transpose(negative_keys) negative_logits = negative_logits.squeeze(1) # First index in last dimension are the positive samples try: logits = torch.cat([positive_logit, negative_logits], dim=1) except: print(negative_logits) exit() labels = torch.zeros(len(logits), dtype=torch.long, device=query.device) else: # Negative keys are implicitly off-diagonal positive keys. # Cosine between all combinations logits = query @ transpose(positive_key) # Positive keys are the entries on the diagonal labels = torch.arange(len(query), device=query.device) return F.cross_entropy(logits / temperature, labels, reduction=reduction), torch.mean(positive_logit), torch.mean(negative_logits) def transpose(x): return x.transpose(-2, -1) def normalize(*xs): return [None if x is None else F.normalize(x, dim=-1) for x in xs]
##### Solutions to the Practice Problems in "AWM-Coding.R" ##### # Disclaimer: these are niether the only ways to solve the given problems, nor can I guarantee they're the most efficient # Use if statements to write a program that tests whether a number if even or odd a = 3 if (a/2 - floor(a/2) == 0){ print("a is even") } else { print("a is odd") } # Use if statements to write a program to tell you whether a student has met the prerequisites for Math 161 # Assume the student has taken both m160 and m124 with a grade of A, B, C, D, or F. # Prerequisites of Math 161: # D or higher in both Math 124 and Math 160 m124 <- "C" m160 <- "B" if (m124 != "F"){ if (m160 != "F"){ print("The student has met the prerequisites for Math 161") } else { print("The student has not met the prerequisites for Math 161") } } else { print("The student has not met the prerequisites for Math 161") } # Use if statements to write a program that will tell you whether the roots of a quadratic polynomial are real or imaginary # I will be sing the form a*x^2 + b*x + c a <- 4 b <- 3 c <- 2 disc <- b^2 - 4*a*c if (disc > 0) { print("The polynomial has 2 real roots") } else if (disc == 0) { print("The polynomial has 1 real, repeated root") } else if (disc < 0) { print("The polynomial has 2 complex roots") } # Use a for loop to find the squares of the integers 0-10 for (x in 0:10){ print(x*x) } # Use for loops and if statements to find which of the integers from 0 to 50 are perfect squares for (x in 0:50){ if (sqrt(x) - floor(sqrt(x)) == 0){ print(x) } } # Use for loops to count number of characters in each of the following fruit names: # "banana", "strawberry", "apple", "pear", "dragonfruit" frootz <- c("banana", "strawberry", "apple", "pear", "dragonfruit") for (fruit in frootz){ print(nchar(fruit)) }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1" /> <link rel="stylesheet" href="./index.css"> <title>BerryCSS Documentation</title> </head> <body> <div class="container pt-24"> <div class="logo px-12"> <div class="logo-image center mb-16"> <img src="./img/main-logo.png" alt="logo"> </div> <div class="logo-content center tac fs-18 fw-500 mb-16"> BerryCss enables you to construct your project more efficiently by merging the structures of Bootstrap and Tailwind. </div> <div class="logo-content center tac fs-16 fw-400 mb-36 row-gap-2"> At the same time, BerryCss includes a global CSS reset feature, enhancing the efficiency of your project construction. </div> </div> <div class="main-title center"> <div class="fs-32 fw-700 lh-110 mb-16 w-max">Documentation</div> </div> <div class="content df fdc gap-12 px-18 mb-24"> <div class="content-title w-max fs-24 fw-500 col-green"> Available breakpoints </div> <div class="content-text pb-8 fs-16 fw-400"> BerryCSS includes six default breakpoints, sometimes referred to as grid tiers, for building responsively. These breakpoints can be customized if you’re using our source Sass files. </div> <div class="code df fdc gap-28 py-28 px-12 bg-white fs-14 rad-4"> <div class="df fdc gap-4 mb-12"> <div class="op-08">// `$xxs` applies to small devices (Landscape phones, more than 374px)</div> <div>$xxs: 374px;</div> <div>@media screen and (min-width: $xxs) {...}</div> </div> <div class="df fdc gap-4 mb-12"> <div class="op-08">// `$mob` applies to general phone devices (phones, more than 576px)</div> <div>$mob: 576px;</div> <div>@media screen and (min-width: $mob) {...}</div> </div> <div class="df fdc gap-4 mb-12"> <div class="op-08">// `$tab` applies to general tablet devices (tablets, more than 767px)</div> <div>$tab: 767px;</div> <div>@media screen and (min-width: $tab) {...}</div> </div> <div class="df fdc gap-4 mb-12"> <div class="op-08">// `$lap` applies to general laptop devices (laptops, more than 1023px)</div> <div>$lap: 1023px;</div> <div>@media screen and (min-width: $lap) {...}</div> </div> <div class="df fdc gap-4 mb-12"> <div class="op-08">// `$lap` applies to general big screen devices (big screens, more than 1440px)</div> <div>$desk: 1440px;</div> <div>@media screen and (min-width: $desk) {...}</div> </div> <div class="df fdc gap-4 mb-12"> <div class="op-08">// `$lap` applies to general large screen devices (large screens, more than 1440px) </div> <div>$big: 1600px;</div> <div>@media screen and (min-width: $big) {...}</div> </div> </div> </div> <div class="content df fdc gap-12 px-18 mb-24"> <div class="content-title w-max fs-24 fw-500 col-green"> Colors </div> <div class="content-text pb-8 fs-16 fw-400"> When you define the colors of your project within the root you see in the visual, you can start using them both within the CSS and automatically inside the classes. </div> <div class="code py-28 px-12 bg-white fs-14 rad-4"> <img src="./img/root-colors.png" alt="root-colors"> </div> </div> <div class="content df fdc gap-12 px-18 mb-24"> <div class="content-title w-max fs-24 fw-500 col-green"> Default Container </div> <div class="content-text pb-8 fs-16 fw-400"> Our default .container class is a responsive, fixed-width container, meaning its max-width changes at each breakpoint. </div> <div class="code py-28 px-12 bg-white fs-14 rad-4"> <img src="./img/container.png" alt="container"> </div> </div> <div class="content df fdc gap-12 px-18 mb-24"> <div class="content-title w-max fs-24 fw-500 col-green"> Grid system </div> <div class="content-text pb-8 fs-16 fw-400"> For grids that are the same from the smallest of devices to the largest, use the .box and .box-* classes. Specify a numbered class when you need a particularly sized column; otherwise, feel free to stick to .box </div> <div class="code py-28 px-12 bg-white fs-14 rad-4"> <img src="./img/row.png" alt="row"> <div class="container px-12 my-12 bg-trans"> <div class="row"> <div class="box-3 box">Box Content</div> <div class="box-3 box">Box Content</div> <div class="box-3 box">Box Content</div> <div class="box-3 box">Box Content</div> </div> </div> <img src="./img/row2.png" alt="row2"> <div class="container px-12 my-12 bg-trans"> <div class="row"> <div class="box-8 box">Box Content</div> <div class="box-4 box">Box Content</div> <div class="box-6 box">Box Content</div> <div class="box-6 box">Box Content</div> <div class="box-4 box">Box Content</div> <div class="box-8 box">Box Content</div> </div> </div> </div> </div> <div class="content df fdc gap-12 px-18 mb-24"> <div class="content-title w-max fs-24 fw-500 col-green"> Stacked To Horizontal </div> <div class="content-text pb-8 fs-16 fw-400"> Using a single set of .box-sm-* classes, you can create a basic grid system that starts out stacked and becomes horizontal at the small breakpoint (sm). </div> <div class="code py-28 px-12 bg-white fs-14 rad-4"> <img src="./img/box-sm.png" alt="box-sm"> <div class="container px-12 my-12 bg-trans"> <div class="row"> <div class="box-sm-3 box">box-sm-3</div> <div class="box-sm-3 box">box-sm-3</div> <div class="box-sm-3 box">box-sm-3</div> <div class="box-sm-3 box">box-sm-3</div> </div> </div> </div> </div> <div class="content df fdc gap-12 px-18 mb-24"> <div class="content-title w-max fs-24 fw-500 col-green"> Mix And Match </div> <div class="content-text pb-8 fs-16 fw-400"> Don’t want your columns to simply stack in some grid tiers? Use a combination of different classes for each tier as needed. See the example below for a better idea of how it all works. </div> <div class="code py-28 px-12 bg-white fs-14 rad-4"> <img src="./img/box-combine.png" alt="box-combine"> <div class="container px-12 my-12 bg-trans"> <div class="row"> <div class="box-sm-3 box-tab-6 box-lap-8 box">box-sm-3 / box-tab-6 / box-lap-8</div> <div class="box-sm-3 box-tab-6 box-lap-4 box">box-sm-3 / box-tab-6 / box-lap-4</div> <div class="box-sm-3 box-tab-6 box-lap-8 box">box-sm-3 / box-tab-6 / box-lap-8</div> <div class="box-sm-3 box-tab-6 box-lap-4 box">box-sm-3 / box-tab-6 / box-lap-4</div> </div> </div> <img src="./img/box-combine2.png" alt="box-combine2"> <div class="container px-12 my-12 bg-trans"> <div class="row"> <div class="box-mob-4 box-big-8 box">box-mob-4 / box-big-8</div> <div class="box-mob-8 box-big-4 box">box-mob-8 / box-big-4</div> <div class="box-mob-4 box-big-8 box">box-mob-4 / box-big-8</div> <div class="box-mob-8 box-big-4 box">box-mob-8 / box-big-4</div> </div> </div> </div> </div> <div class="content df fdc gap-12 px-18 mb-24"> <div class="content-title w-max fs-24 fw-500 col-green"> Responsive Size System </div> <div class="content-text pb-8 fs-16 fw-400"> <div class="mb-8">We've created a responsive 'size system' and applied it to all classes. Without any extra effort, all pixel values will automatically scale down to a ratio of 0.81 below the tablet breakpoint of 767px, achieving a fully responsive appearance automatically.</div> <div>The provided values for font size, margin, padding, gap, radius, etc., will scale down by a factor of 0.81, and there will be no need to write individual media queries.</div> </div> <div class="code py-28 px-12 bg-white fs-14 rad-4"> <img src="./img/size-system.png" alt="size-system"> <div class="fs-24 p-16 m-16 rad-16">"You can check this text 767px for example..."</div> <div class="fs-16 p-8 m-8 rad-8">"You can check this text 767px for example..."</div> <div class="op-08 mt-20">// Additionally, in the CSS file, you can use these values from 1 to 50.</div> <img src="./img/size-system2.png" alt="size-system2"> <div class="op-08 mt-8">// The provided values will scale responsively down.</div> </div> </div> <div class="content df fdc gap-12 px-18 mb-24"> <div class="content-title w-max fs-24 fw-500 col-green"> Flexbox Classes </div> <div class="content-text pb-8 fs-16 fw-400"> <div class="mb-8">There's no need to define CSS values for flexbox properties separately. We've encapsulated them into classes for easy use.</div> <div>For example, when you type 'df', it automatically sets "display:flex;", and similarly, typing 'aic' would set "align-items:center;".You can individually verify the examples below.</div> </div> <div class="code py-28 px-12 bg-white fs-14 rad-4"> <div class="op-08 mb-12">// Align Items Classes</div> <div class="flex-test df ais">ais = align items start</div> <div class="flex-test df aic">aic = align items center</div> <div class="flex-test df aie">aie = align items end</div> <div class="op-08 mt-32 mb-12">// Justify Content Classes</div> <div class="flex-test df jcs">jcs = justify content start</div> <div class="flex-test df jcc">jcc = justify content center</div> <div class="flex-test df jce">jce = justify content end</div> <div class="op-08 mt-32 mb-12">// Align & Justify Classes</div> <div class="flex-test df aic jcc">class="df aic jcc"</div> <div class="flex-test df aie jce">class="df aie jce"</div> <div class="op-08 mt-32 mb-12">// Center Class</div> <div class="flex-test center">class="center"</div> </div> </div> <div class="content df fdc gap-12 px-18 mb-24"> <div class="content-title w-max fs-24 fw-500 col-green"> Padding </div> <div class="content-text pb-8 fs-16 fw-400"> You can easily define padding classes between "from 1px to 50px" </div> <div class="code py-28 px-12 bg-white fs-14 rad-4"> <div class="op-08 mb-8 tac">*** Different Paddings ***</div> <div class="center mb-8"> <div class="p-15 bg-br">p-15</div> <div class="p-25 bg-red">p-25</div> <div class="p-35 bg-green">p-35</div> <div class="p-50 bg-black">p-50</div> </div> <div class="op-08 mb-8 tac">*** class="p-20" ***</div> <div class="p-20 test-box bor-white bg-red mb-20"> <div class="inner center tac bg-green fs-16"> Padding All: 20px </div> </div> <div class="op-08 mb-8 tac">*** class="pt-20" ***</div> <div class="pt-20 test-box bor-white bg-red mb-20"> <div class="inner center tac bg-green fs-16"> Padding Top: 20px </div> </div> <div class="op-08 mb-8 tac">*** class="pl-20" ***</div> <div class="pl-20 test-box bor-white bg-red mb-20"> <div class="inner center tac bg-green fs-16"> Padding Left: 20px </div> </div> <div class="op-08 mb-8 tac">*** class="pr-20" ***</div> <div class="pr-20 test-box bor-white bg-red mb-20"> <div class="inner center tac bg-green fs-16"> Padding Right: 20px </div> </div> <div class="op-08 mb-8 tac">*** class="pb-20" ***</div> <div class="pb-20 test-box bor-white bg-red mb-20"> <div class="inner center tac bg-green fs-16"> Padding Bottom: 20px </div> </div> <div class="op-08 mb-8 tac">*** class="px-20" ***</div> <div class="px-20 test-box bor-white bg-red mb-20"> <div class="inner center tac bg-green fs-16"> Padding-x: 20px </div> </div> <div class="op-08 mb-8 tac">*** class="py-20" ***</div> <div class="py-20 test-box bor-white bg-red mb-20"> <div class="inner center tac bg-green fs-16"> Padding-y: 20px </div> </div> </div> </div> <div class="content df fdc gap-12 px-18 mb-24"> <div class="content-title w-max fs-24 fw-500 col-green"> Margin </div> <div class="content-text pb-8 fs-16 fw-400"> You can easily define margin classes between "from 1px to 50px" </div> <div class="code py-28 px-12 bg-white fs-14 rad-4"> <div class="op-08 mb-8 tac">*** Different Margins ***</div> <div class="center mb-16"> <div class="w-50 h-50 center mt-15 bg-black">mt-25</div> <div class="w-50 h-50 center mr-15 bg-red">mr-15</div> <div class="w-50 h-50 center mb-15 bg-yellow">mb-15</div> <div class="w-50 h-50 center ml-15 bg-green">ml-15</div> </div> <div class="op-08 mb-8 tac mt-20">*** class="m-20" ***</div> <div class="test-box bor-white bg-red"> <div class="inner center tac bg-green fs-16 m-20"> Margin All: 20px </div> </div> <div class="op-08 mb-8 tac mt-20">*** class="mt-20" ***</div> <div class="test-box bor-white bg-red"> <div class="inner center tac bg-green fs-16 mt-20"> Margin Top: 20px </div> </div> <div class="op-08 mb-8 tac mt-20">*** class="ml-20" ***</div> <div class="test-box bor-white bg-red"> <div class="inner center tac bg-green fs-16 ml-20"> Margin Left: 20px </div> </div> <div class="op-08 mb-8 tac mt-20">*** class="mr-20" ***</div> <div class="test-box bor-white bg-red"> <div class="inner center tac bg-green fs-16 mr-20"> Margin Right: 20px </div> </div> <div class="op-08 mb-8 tac mt-20">*** class="mb-20" ***</div> <div class="test-box bor-white bg-red"> <div class="inner center tac bg-green fs-16 mb-20"> Margin Bottom: 20px </div> </div> <div class="op-08 mb-8 tac mt-20">*** class="mx-20" ***</div> <div class="test-box bor-white bg-red"> <div class="inner center tac bg-green fs-16 mx-20"> Margin-x: 20px </div> </div> <div class="op-08 mb-8 tac mt-20">*** class="my-20" ***</div> <div class="test-box bor-white bg-red"> <div class="inner center tac bg-green fs-16 my-20"> Margin-y: 20px </div> </div> </div> </div> </body> </html>
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 { FixtureComponent } from './Component/fixture/fixture.component'; import { SharedModule } from './Shared/shared/shared.module'; import { DynamicDropDownComponent } from './Component/dynamic-drop-down/dynamic-drop-down.component'; import { DateformatPipe } from './dateformat.pipe'; import { HomeComponent } from './Component/home/home.component'; import { FooterComponent } from './Component/footer/footer.component'; import { ToolbarComponent } from './Component/toolbar/toolbar.component'; import { HTTP_INTERCEPTORS } from '@angular/common/http'; import { JwtInterceptor } from './Shared/interceptors/jwt.interceptor'; import { NotificationComponent } from './Component/notification/notification.component'; import { FixtureDetailsComponent } from './Component/fixture-details/fixture-details.component'; import { GroupByPipe } from './Component/Pipe/group-by.pipe'; @NgModule({ declarations: [ AppComponent, FixtureComponent, DynamicDropDownComponent, DateformatPipe, HomeComponent, FooterComponent, ToolbarComponent, NotificationComponent, FixtureDetailsComponent, GroupByPipe, ], imports: [ BrowserModule, AppRoutingModule, SharedModule, BrowserAnimationsModule ], providers: [ {provide: HTTP_INTERCEPTORS, useClass: JwtInterceptor, multi: true} ], bootstrap: [AppComponent] }) export class AppModule { }
<script setup> import { reactive, ref } from "vue"; const drawer = ref(false) const links = reactive([ { icon: 'mdi-home', title: 'Dashboard', route: '/' }, { icon: 'mdi-folder', title: 'My Projects', route: '/projects' }, { icon: 'mdi-account-group', title: 'Team', route: '/team' }, ]) </script> <template> <nav> <v-toolbar flat app> <v-app-bar-nav-icon @click="drawer = !drawer" /> <v-toolbar-title class="text-uppercase text-grey"> <span class="font-weight-light">Todo</span> <span class="font-weight-bold">Ninja</span> </v-toolbar-title> <v-btn flat color="grey"> <span>Sign out</span> <v-icon icon="mdi-exit-to-app" end /> </v-btn> </v-toolbar> <v-navigation-drawer temporary app class="bg-indigo" v-model="drawer"> <v-row justify="center" class="mt-5"> <v-avatar size="100"> <img src="/avatar-1.png" /> </v-avatar> </v-row> <v-list> <v-list-item v-for="link in links" :prepend-icon="`${link.icon}`" :key="link.route" route :to="link.route"> {{ link.title }} </v-list-item> </v-list> </v-navigation-drawer> </nav> </template>
from django.db import models from django.utils import timezone from webpage.models import User class Recipe(models.Model): """ Recipe class model for the Users' recipes. """ # Llave foránea del usuario que escribe la receta user: User = models.ForeignKey( User, on_delete=models.CASCADE, null=True, ) # Nombre de la receta name = models.CharField(max_length=255) # Ingredientes ingredients = models.TextField() # Instrucciones de la preparación instructions = models.TextField() # Path de la imagen linkeada image = models.ImageField( upload_to="" ) # Fecha de la publicación publish_date = models.DateTimeField( default=timezone.localtime, ) def __str__(self): return (f"Recipe(" f"id={self.id}, " f"user={self.user.get_username()}, " f"name={self.name}" f")") class UserLikesRecipe(models.Model): user = models.ForeignKey("webpage.User", on_delete=models.CASCADE) recipe = models.ForeignKey("Recipe", on_delete=models.CASCADE)
# DN 8. Robni problem lastnih vrednosti (Delec v končnem in neskončnem potencialu) Poleg začetnih pogojev lahko enačbe opisujejo tudi robne pogoje. Tokrat se ukvarjamo z robnimi problemi lastnih vrednosti. Pogledali si bomo diferenčno in strelsko metodo in ju aplicirali pri reševanju Schrödingerjeve enačbe za delec v končnem in neskončnem potencialu. ## Navodila Naloga želi, da za končno in neskončno potencialno jamo z prej naštetima metodama določimo nekaj najnižjih lastnih funkcij in lastnih vrednosti energije. ## Napotki ### 1. Zopet normalizacija Če me spomin ne vara, je tudi tu catch, da funkcije na robovih integracijskega intervala zelo rade divje divergirajo in če jih naivno normiraš na maksimum preko celotnega intervala dobiš ravno premico, ki kaže veselo 0. Pri tretji domači nalogi sem v napotkih opisal na grobo, kako si lahko odpraviš tovrsten problem. Gotovo sem nanj naletel spet tudi pri tej nalogi, ker sem ga omenil v komentarju (poleg napačnega predznaka). ### 2. Poglej si zakaj je strelska metoda tako imenovana To je mogoče spet malo za umetnika v sebi, ampak meni se je zdelo zanimivo opazovati, kako strelska metoda deluje. V bistvu gre za nekakšno iskanje ničel. Kar bi bilo res kul, bi bila kakšna animacija. Teh do zdaj nisem omenjal, a sem jih naredil že kar nekaj. Priporočam tudi animacijo grafov tako tu kot pri prejšnjih nalogah. ### 3. Shrani rezultate diagonalizacije Računanje in diagonalizacija matrike je lahko počasna zato se mi zdi koristno omeniti, da se splača rezultate spraviti v datoteko. Strašno enostavno znotraj Pythona. Še sploh če uporabljaš `numpy`. Imaš `numpy.save()` in `numpy.load()`. * [**np.save()**](https://numpy.org/doc/stable/reference/generated/numpy.save.html) * [**np.savez()**](https://numpy.org/doc/stable/reference/generated/numpy.savez.html) * [**np.load()**](https://numpy.org/doc/stable/reference/generated/numpy.load.html) ## Kar sem jaz naredil **Tu je verjetno tisto kar te najbolj zanima**. <details> <summary>Standard Disclaimer</summary> Objavljam tudi kodo. Ta je bila včasih del večjega repozitorija, ampak sem jo sedaj izvzel v svojega, da je bolj pregledna. Koda bi morala biti razmeroma pokomentirana, sploh v kasnejših nalogah. </details> Vseeno pa priporočam, da si najprej sam poskusiš rešiti nalogo. As always za vprašanja sem na voljo. * [**Poročilo DN8**](https://pengu5055.github.io/fmf-pdf/year3/mfp/Marko_Urbanč_08.pdf) * [**Source repozitorij DN8**](https://github.com/pengu5055/mfp08) Priznam, da zna biti source repozitorij nekoliko kaotičen. Over time sem se naučil boljše prakse. Zdi se mi, da je tole glavni `.py` file. * [**main_08.py**](https://github.com/pengu5055/mfp08/blob/main/main_08.py) ## Citiranje *Malo za šalo, malo za res*.. če želiš izpostaviti/omeniti/se sklicati ali pa karkoli že, na moje delo, potem ga lahko preprosto citiraš kot: ```bib @misc{Urbanč_mfpDN8, title={Robni problem lastnih vrednosti}, url={https://pengu5055.github.io/fmf-pages/year3/mfp/dn8.html}, journal={Marko’s Chest}, author={Urbanč, Marko}, year={2023}, month={Oct} } ``` To je veliko boljše kot prepisovanje.
import { createTRPCRouter, protectedProcedure, publicProcedure } from "../trpc"; import { z } from "zod"; import { sendCancelationEmail } from "../utils/sendgrid"; import { startOfToday } from "date-fns"; export const registrationRouter = createTRPCRouter({ byExperience: publicProcedure.input(z.number()).query(({ ctx, input }) => { return ctx.prisma.registration.findMany({ where: { experienceId: input }, }); }), activeRegistrationByExpId: protectedProcedure .input(z.number()) .query(async ({ ctx, input }) => { const activeRegistration = await ctx.prisma.registration.findMany({ where: { experienceId: input, userId: ctx.userId, availability: { startTime: { gte: startOfToday() } } }, include: { availability: true, experience: true }, orderBy: { availability: { startTime: "asc" } } }); return activeRegistration[0]; }), changeRegistrationAvailability: protectedProcedure .input(z.object({ registrationId: z.string(), newAvailabilityId: z.number() })) .mutation(async ({ctx, input}) => { // First check to make sure this user is allowed to change this registration const registration = await ctx.prisma.registration.findUnique({ where: { id: input.registrationId } }); if (!registration) return "registration_does_not_exist"; if (ctx.userId !== registration.userId) return "not_authorized"; // Next check to make sure there is space in the availability being changed to const availability = await ctx.prisma.experienceAvailability.findUnique({ where: { id: input.newAvailabilityId }, include: { experience: true, registrations: true } }); let totalRegistrants = 0; availability?.registrations.forEach(registration => totalRegistrants += registration.partySize); if (totalRegistrants + registration.partySize > (availability?.experience.maxAttendees || 0)) { return "not_enough_space"; } // Finally, update the registration await ctx.prisma.registration.update({ where: { id: input.registrationId }, data: { availabilityId: input.newAvailabilityId } }); return "success"; }), registrantCountByExperience: publicProcedure .input(z.number()) .query(async ({ ctx, input }) => { const registrations = await ctx.prisma.registration.findMany({ where: { experienceId: input }, }); let totalRegistrants = 0; registrations.forEach((registration) => { totalRegistrants += registration.partySize; }); return totalRegistrants; }), removeRegistrant: publicProcedure .input(z.string()) .mutation(async ({ ctx, input }) => { const deletedRegistration = await ctx.prisma.registration.delete({ where: { id: input }, }); const experience = await ctx.prisma.experience.findFirst({ where: { id: deletedRegistration.experienceId }, include: { availability: true, profile: true }, }); const hostProfile = await ctx.prisma.profile.findFirst({ where: { userId: experience?.authorId }, }); if (experience && hostProfile) { await sendCancelationEmail({ recipientEmail: deletedRegistration.email, experience: experience, hostProfile: hostProfile, }); } return deletedRegistration; }), createRegistration: publicProcedure .input( z.object({ userId: z.string(), registrantFirstName: z.string(), registrantLastName: z.string(), partySize: z.number(), email: z.string(), experienceId: z.number(), availabilityId: z.number(), stripeCheckoutSessionId: z.string(), status: z.string(), }) ) .mutation(async ({ ctx, input }) => { const newRegistration = await ctx.prisma.registration.create({ data: { userId: input.userId, registrantFirstName: input.registrantFirstName, registrantLastName: input.registrantLastName, partySize: input.partySize, email: input.email, experienceId: input.experienceId, availabilityId: input.availabilityId, stripeCheckoutSessionId: input.stripeCheckoutSessionId, status: input.status, }, }); return newRegistration; }), });
<!DOCTYPE> <html> <head> <meta charset="utf-8"> <title>IFE JavaScript Task 01</title> <style> div{ padding:5px; width:450px; border:2px solid rgb(233,233,233); box-shadow: 6px 6px 3px #ddd; } .p{ padding:0; margin:7px 0 0 75px; font-family:"黑体"; font-size:110%; display:none; color:rgb(222,222,222); } .text{ border:2px solid rgb(222,222,222); font-family:"黑体"; border-radius:6px; width:300px; font-size:110%; padding:10px; outline:none; margin-top:10px; } .span{ font-family:"黑体"; font-size:120%; margin-right: 20px; } #button{ font-family:"黑体"; width:200px; color:white; font-size:120%; background-color:rgb(47,121,186); border:1px solid rgb(47,121,186); padding:9px 15px; border-radius:6px; margin:10px 0 0 80px; } </style> </head> <body> <div> <span id="span1" class="span">名称</span> <input type="text" id="text1" class="text"/><br/> <p id="p1" class="p">输入4~16位字符的中文、字母、数字或者"_"</p> <span id="span2" class="span">密码</span> <input type="password" id="text2" class="text"/><br/> <p id="p2" class="p">请输入6~16位密码</p> <span id="span3" class="span">确认密码</span> <input type="password" id="text3" class="text"/><br/> <p id="p3" class="p">请再次输入密码</p> <span id="span4" class="span">邮箱</span> <input type="text" id="text4" class="text"/><br/> <p id="p4" class="p">请输入邮箱地址</p> <span id="span5" class="span">手机</span> <input type="text" id="text5" class="text"/><br/> <p id="p5" class="p">请输入您的手机号码</p> <button id="button">验证</button> </div> <script type="text/javascript"> var _text = document.getElementById("text1"); var _text2 = document.getElementById("text2"); var _text3 = document.getElementById("text3"); var _text4 = document.getElementById("text4"); var _text5 = document.getElementById("text5"); var _button = document.getElementById("button"); var _p = document.getElementById("p1"); var _p2 = document.getElementById("p2"); var _p3 = document.getElementById("p3"); var _p4 = document.getElementById("p4"); var _p5 = document.getElementById("p5"); var re = /[^\w\u4e00-\u9fa5]/; var _len; var arr = []; function len(a){ return _len = a.value.replace(/[^\x00-xff]/g,"xx").length; } _text.onfocus = function(){ _p.style.display = "block"; _text.style.borderColor = "rgb(100,174,239)"; } _text.onblur = function(){ if(re.test(_text.value) == true){ _p.innerHTML = '中文、英文字母、数字或者"_"。'; _p.style.color = "rgb(235,118,130)"; _text.style.borderColor = "rgb(235,118,130)"; arr[0] = 0; } else if(_len>16 || _len<4 ||_text.value == ""){ _p.innerHTML = "请输入4~16位字符。"; _p.style.color = "rgb(235,118,130)"; _text.style.borderColor = "rgb(235,118,130)"; arr[0] = 0; } else{ _p.innerHTML = "验证成功"; _p.style.color = "rgb(135,203,116)"; _text.style.borderColor = "rgb(135,203,116)"; arr[0] = 1; } } _text.onkeyup = function (){ len(this); _p.innerHTML = _len + "个字符"; _text.style.borderColor = "rgb(222,222,222)"; _p.style.color = "rgb(222,222,222)"; _p.style.display = "block"; } _text2.onfocus = function(){ _p2.style.display = "block"; _text2.style.borderColor = "rgb(100,174,239)"; } _text2.onblur = function(){ if(this.value.length<6 || this.value.length>16){ _p2.innerHTML = "请输入正确的6~16位密码"; _text2.style.borderColor = "rgb(235,118,130)"; _p2.style.color = "rgb(235,118,130)"; arr[1] = 0; } else{ _p2.innerHTML = "验证成功"; _text2.style.borderColor = "rgb(135,203,116)"; _p2.style.color = "rgb(135,203,116)"; arr[1] = 1; } if(_text3.value != ""&& this.value != _text3.value){ _p3.innerHTML = "与上一次输入不一致"; _p3.style.display = "block"; _text3.style.borderColor = "rgb(235,118,130)"; _p3.style.color = "rgb(235,118,130)"; arr[2] = 0; } } _text3.onfocus = function(){ _p3.style.display = "block"; _text3.style.borderColor = "rgb(100,174,239)"; } _text3.onblur = function(){ if(this.value != _text2.value || this.value.length < 6){ _p3.innerHTML = "与上一次输入不一致"; _text3.style.borderColor = "rgb(235,118,130)"; _p3.style.color = "rgb(235,118,130)"; arr[2] = 0; } else{ _p3.innerHTML = "验证成功"; _text3.style.borderColor = "rgb(135,203,116)"; _p3.style.color = "rgb(135,203,116)"; arr[2] = 1; } } _text4.onfocus = function(){ _p4.style.display = "block"; _text4.style.borderColor = "rgb(100,174,239)"; } _text4.onblur = function(){ if(/^\w+[@]{1}[a-zA-z]{2,10}.com$/.test(this.value) == false){ _p4.innerHTML = "请输入正确的邮箱地址"; _text4.style.borderColor = "rgb(235,118,130)"; _p4.style.color = "rgb(235,118,130)"; arr[3] = 0; } else{ _p4.innerHTML = "验证成功"; _text4.style.borderColor = "rgb(135,203,116)"; _p4.style.color = "rgb(135,203,116)"; arr[3] = 1; } } _text5.onfocus = function(){ _p5.style.display = "block"; _text5.style.borderColor = "rgb(100,174,239)"; } _text5.onblur = function(){ if(/^\d{11}$/.test(this.value) == false){ _p5.innerHTML = "请输入11位数的手机号码"; _text5.style.borderColor = "rgb(235,118,130)"; _p5.style.color = "rgb(235,118,130)"; arr[4] = 0; } else{ _p5.innerHTML = "验证成功"; _text5.style.borderColor = "rgb(135,203,116)"; _p5.style.color = "rgb(135,203,116)"; arr[4] = 1; } } _button.onclick = function(){ var len = 0; for(var i=0;i<arr.length;i++){ len += arr[i]; } if(len == 5){ alert("提交成功") } else{ alert("请输入正确的信息") } } </script> </body> </html>
### [Go to easy](#easy-level-problem) ### [Go to medium](#medium-level) # Easy level problem ### Check_if_Array_Is_Sorted_and_Rotated #### concept: In this solution ,The approach is to compare every current element to it's last element so that every current element is larger than pervious one but at one place the current element is smaller than pervious element where the roation has happened ,and the last element is always less than first element #### python code ```python from typing import List import sys def check( nums: List[int]) -> bool: count = 0 length = len(nums) - 1 for i in range(length): if nums[i] > nums[i + 1]: print(nums[i] , nums[i + 1]) count+=1 print(' count: ', count) print(count) if count > 1 or (count == 1 and nums[0] < nums[length]): return False return True y=check([4,5,6,1,2,3]) print(y) ``` <hr> ### Reverse Integers #### concept: - first step is to check whether element is positive or negative - mathematical concept is used to get last digit of the number which is to get remainder by dividing by 10 and that digit can be stored in list - The loop is used for them element of the list ,which is multiplied by their power of 10 to its position - added all the number to form the number - in last is returned #### python code ```python def reverse(x:int)->int: sys=0 if(x>0): sys=1 else: sys=-1 newX=abs(x) digitList=[] while newX: digitList.append(newX%10) newX=newX//10 reversedNum=0 digitLen=len(digitList) for i in range(digitLen): reversedNum+=digitList[digitLen-1-i]* pow(10,i) res=sys*reversedNum if res > (pow(2, 31) - 1) or res < -(pow(2,31)): # here number is checked that it should not cross the limit return 0 return res ``` <hr> ### find the lcm #### concept: - mathematical concept is used to get lcm (a*b=lcm *hcf) #### python code ```python from d_hcf import find_gcd def lcmAndGcd( A , B): # code here gcd=find_gcd(A,B) lcm=int(A*B/gcd) sol=[lcm,gcd] return sol print(lcmAndGcd(5,6)) ``` <hr> ### check armstrongNumber #### concept: armstrong number are thos number which is when sum of the cube of its digit is equal to the number #### python code ```python def armstrongNumber (ob, n): # code here string_num=str(n) sum=pow(int(string_num[0]),3)+pow(int(string_num[1]),3)+pow(int(string_num[2]),3) if(sum!=n): return "No" return "Yes" ``` <hr> ### find the cubic sum of n number #### concept: - Mathematical formula is used #### python code ```python def sumOfSeries(n): x = (n * (n + 1) / 2) return (int)(x * x) print(sumOfSeries(5)) ``` <hr> ### find nth fibonacci number #### concept: - Recursion is used -Add the fib(num-2)+fib(n-1) #### python code ```python def fib(n: int) -> int: if n ==0 or n==1: return n return fib(n-1)+fib(n-2) ``` <hr> ### left Rotate the number #### concept: - If the arrray is sorted and to rotate left from tth postion - array sice method is used to add before nth and after n th nnum #### python code ```python def leftRotate( arr, k): # Your code goes here return arr[k:] + arr[:k] print('leftRotate([1,2,3,4,5,6],3): ', leftRotate([1,2,3,4,5,6],3)) ``` <hr> ### Given an integer array nums, move all 0's to the end of it while maintaining the relative order of the non-zero elements. #### concept: In this problem there can be multiple solution #### python code ```python def moveZeroes(arr): # sol 1 # return arr.sort(key=bool ,reverse=True) # sol 2 j=0 # to track zero for i in range(len(arr)): if arr[i] != 0: print("Before",arr) arr[i],arr[j]=arr[j],arr[i] print("after",arr) j+=1 # it will not increase until there is non zero number return arr ``` <hr> ### Given an array, rotate the array to the right by k steps, where k is non-negative #### concept: In the first solution ,for loop is used to remove from the last and add to front as the value of K In solution two ,a new array is declared with the length of given list,and a for loop is used to decide the position of the element after k right rotation #### python code ```python # solution 1 def rotate_right(arr:list,k): for i in range(k): x=arr.pop() arr.insert(0,x) return arr # solution 2 def rotate_extraspace(nums:list, k:int) { # intializing the base case if (k==0) return if (nums == null or nums.length == 0) return # creating the new array list res = [None]*nums.length for i in range(len(nums)): newIndex = (i + k) % nums.length res[newIndex] = nums[i] print(res) for i in range(len(nums)): nums[i] = res[i] print(res) ``` <hr> ### find the missing number from the array of range 0 -n in which one is missing #### concept: Mathematical concept is used #### python code ```python def missingNumber(nums:list): n=len(nums) totalSum=(n*(n+1))/2 arrSum=sum(nums) return int(totalSum-arrSum) ``` <hr> ### finding most consecutive 1 in an array of binary #### concept: #### python code ```python def findMaxConsecutiveOnes( nums:list) -> int: count=0 #track the current count of consecutive one max=0 # track the maximum number of 1 has been occured for i in range(len(nums)): if nums[i] == 0: count=0 else: count+=1 if count>max: max+=1 return max ``` <hr> ### Given an array of integers nums and an integer k, return the total number of subarrays whose sum equals to k. #### concept: #### python code ```python def subarraySum( nums: list, k: int) -> int: count=0 # track the number of subarray found totalSum=0 # track the sum to the ith value of array sumobj=defaultdict(lambda : 0) # hashmap to store the sum so far acheived for i in range(len(nums)): totalSum+=nums[i] if totalSum == k: count+=1 if totalSum-k in sumobj: # checking the if total sum - k(required sum ) is there in the object ,if it is then add its value to get the subarray so far occured count+=sumobj[totalSum-k] sumobj[totalSum]+=1 print(sumobj) return count ``` <hr> ### Given a non-empty array of integers nums, every element appears twice except for one. Find that single one.You must implement a solution with a linear runtime complexity and use only constant extra space. #### concept: #### python code ```python def singleNumber(self, nums: List[int]) -> int: return 2*sum(set(nums))-sum(nums) ``` <hr> ### Write an efficient algorithm that searches for a value target in an m x n integer matrix matrix. This matrix has the following properties:Integers in each row are sorted from left to right.The first integer of each row is greater than the last integer of the previous row. #### concept: matrix of size of n(row)*m(column), a[x]=matrix[x/m][x%m]`` #### python code ```python def searchMatrix(matrix:list,target:int)->bool: n=len(matrix) m=len(matrix[0]) left=0 right=n*m-1 while left<right: mid=(left+right)/2 midValue=matrix[int(mid/m)][int(mid%m)] if(midValue== target): return True if(midValue<target): left=mid+1 else: right=mid return False ``` <hr> ### searchInsert #### concept: binary Search is used and condition is changed inside the while loop #### python code ```python def searchInsert(self, nums: list, target: int) -> int: left=0 right=len(nums)-1 # condition to check that left should not be grater than right if it is so # it means the element does not exist while left<=right: # every time resetting mid where we can look that if element exist or not mid=int((left+right)/2) # if element found then return the element if nums[mid]==target: return mid if nums[mid]<target: left=mid+1 else: right=mid-1 return left ``` <hr> ### # Medium Level ### Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.You may assume that each input would have exactly one solution, and you may not use the same element twice.You can return the answer in any order. #### concept In this question ,we can use hashmap concept to store the current value as key and its position as value, then the main logic is to subtract the target to current value and check if that as key in hash then we found the two sum otherwise not #### code ```python def twoSum( nums: list, target: int) -> list: hash=defaultdict(lambda:0) for i in range(len(nums)): sub=target-nums[i] if( sub in hash): return [hash[sub],i] else: hash[nums[i]]=i ``` <hr> ### # Given an array nums with n objects colored red, white, or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white, and blue. We will use the integers 0, 1, and 2 to represent the color red, white, and blue, respectively. You must solve this problem without using the library's sort function. #### concept sol 1 - we can sort the value = 0,1,2 using inbuilt method sol 2 - or use any sorting algorithm #### code ```python ``` <hr> ### #### concept #### code ```python # It can have multiple solution,some of which I have tried # solution 1 Brute force O(n2) def majorityElement(self, nums: List[int]) -> int: majority_count = len(nums)//2 # storing the majority element for num in nums: count = sum(1 for elem in nums if elem == num)# counting the different number occurence of number if count > majority_count:# compareing every time coutn and majority_count and if it is true then return true return num # solution 2 using Hashmap def majorityElement( nums:list) -> int: hashmap=defaultdict(lambda:0) uni=set(nums) # getting unique value for i in uni: # storing number and its no.of occurence in dictionary tnum=nums.count(i) hashmap[i]=tnum for j in hashmap: if hashmap[j]>len(nums)/2: return j # 3 solution def majorityElement(self, nums: List[int]) -> int: nums.sort() return nums[len(nums)//2] # optimal solution def majorityElement(self, nums: List[int]) -> int: curr, count = nums[0], 1 # curr will store the current majority element, count will store the count of the majority for i in nums[1:]: count += (1 if curr == i else -1) # if i is equal to current majority, they're in same team, hence added, else one current majority and i both will be dead if not count: # if count of current majority is zero, then change the majority element, and start its count from 1 curr = i count = 1 return curr ``` <hr> ### Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum. #### concept Kadane’s Algorithm — (Dynamic Programming) #### solution 1 Brute Force Approach One very obvious but not so good solution is to calculate the sum of every possible subarray and the maximum of those would be the solution. We can start from index 0 and calculate the sum of every possible subarray starting with the element A[0], as shown in the figure below. Then, we would calculate the sum of every possible subarray starting with A[1], A[2] and so on up to A[n-1], where n denotes the size of the array (n = 9 in our case). Note that every single element is a subarray itself. #### code ```python #kadane algorithm def maxSubArray(self, nums: List[int]) -> int: lmax=0 gmax=float("-inf") for i in range(len(nums)): lmax=max(nums[i],nums[i]+lmax) if gmax<lmax: gmax=lmax return gmax ``` <hr> ### You are given an array prices where prices[i] is the price of a given stock on the ith day.You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0. #### concept Normal comaprision #### code ```python def maxProfit(prices:list)->int: buy=prices[0] # assumed that buy price is first elemnet profit=0 # profit will be Zero for i in range(prices): if buy>prices[i]: # comparing current price and what was buy price if earlier was larger than we will change our buy price to current ,so that profit can be maximized buy=prices[i] elif prices[i]-buy>profit: # comparing earlier profit ot current profit profit=prices[i]-buy return profit ``` <hr> ### Rearrange the array in alternating positive and negative items #### concept #### code ```python # a kind of brute force approach with non constant space complexity def rearrangeArray(self, nums:list) -> list: positiveNum=[] negativeNum=[] result =[] for i in nums: if i<0: negativeNum.append(i) else: positiveNum.append(i) for i in range(len(nums)): x=i%2 if( x !=0): n=negativeNum.pop(0) result.append(n) else: p=positiveNum.pop(0) result.append(p) return result # _____OPTIMAL SOLUTION def rearrangeArray(self, nums:list) -> list: # POINTER FOR positive value a=0 # pointer for negative Value b=1 # intializing new array where the desired result can be stored arranged=[0]*len(nums) for i in nums: if(i>0):# checking for value is positve # storing value at a position which is always even arranged[a]=i # incrementing the value by 2 for next positvevalue to be stored a+=2 else: # storing value at a position which is always odd arranged[b]=i # incrementing the value by 2 for next negative value to be stored b+=2 return arranged ``` <hr> ### longest consecutive sequence #### concept - sort the number - then loop through the list - and increase only when consecutive nuber are not same - Increase curr streak if it is equal to prev +1 - when it is not then set the value of longest streak - Return the longest Streak #### code ```python def longestConsecutive(self, nums: list ) -> int: # checking if nums list is empty or not if not nums: print(not nums) return 0 # intializing the variable to store the longest and current streak longestStreak=1 currstreak=1 sortnums=sorted(nums) for i in range(len(sortnums)): if sortnums[i] !=sortnums[i-1]: if sortnums[i]==sortnums[i-1]+1: currstreak+=1 else: longestStreak=max(currstreak,longestStreak) currstreak=1 print((currstreak,longestStreak)) # returing the maximum value of current and longest streak return max(currstreak,longestStreak) ``` <hr>
package com.pjyotik.dev.ums.api.dto; import com.pjyotik.dev.ums.api.customAnnotations.countries.ValidateCountry; import com.pjyotik.dev.ums.api.customAnnotations.email.ValidateEmail; import com.pjyotik.dev.ums.api.customAnnotations.gender.ValidateGender; import com.pjyotik.dev.ums.api.customAnnotations.username.ValidateUsername; import jakarta.persistence.Transient; import jakarta.validation.constraints.Email; import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.Pattern; import jakarta.validation.constraints.Size; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import org.springframework.format.annotation.DateTimeFormat; @Data @AllArgsConstructor(staticName = "build") @NoArgsConstructor public class UserRequest { /* @NotBlank: Ensures that the annotated string is not null and has at least one non-whitespace character. */ @NotBlank(message = "First Name is Required") private String firstName; @NotBlank(message = "Last Name is Required") private String lastName; /* Custom Annotation created to validate the gender passed */ @ValidateGender private String gender; @NotBlank(message = "Date of Birth is Required") @DateTimeFormat(pattern = "dd/MM/yyyy") private String dob; @NotBlank(message = "Nationality is required") private String nationality; @NotBlank(message = "Phone number is Required") @Pattern(regexp = "\\d{10}", message = "Phone Number must be 10 digits") private String phoneNumber; /* @Email: Ensures that the annotated string is a valid email address. */ @NotBlank(message = "Email is Required") @Email(message = "Invalid email address") @ValidateEmail private String email; /* The @Transient annotation is used for fields that should not be persisted in the database, such as confirmEmail and confirmPassword. They are used for validation purposes but are not part of the database schema. */ @Transient @NotBlank(message = "Confirm email is Required") private String confirmEmail; @ValidateUsername private String userName; @Size(max = 50, message = "Address Line 1 must not exceed 50 characters") private String addressLine1; @Size(max = 50, message = "Address Line 2 must not exceed 50 characters") private String addressLine2; @Size(max = 7, message = "Post Code must not exceed 7 characters") private String postCode; @ValidateCountry private String country; private String companyName; /* @Size: Specifies the size constraints on a string (e.g., minimum and maximum length). */ @NotBlank(message = "Password is required") @Size(min = 6, message = "Password must be at least 6 characters") private String password; @Transient @NotBlank(message = "Confirm password is required") private String confirmPassword; }
from django import forms from accounts.models import Comment, User, SignedUpUsers from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.password_validation import validate_password from django.contrib.auth import get_user_model from django.contrib.auth.hashers import check_password class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ['content'] widgets = { 'content': forms.Textarea(), } labels = { 'content': '', } class NewUserForm(UserCreationForm): password1 = forms.CharField(label='password',widget=forms.PasswordInput(attrs={'placeholder': 'Пароль'})) password2 = forms.CharField(label='password',widget=forms.PasswordInput(attrs={'placeholder': 'Повторите пароль'})) class Meta: model = User fields = [ 'username', 'first_name', 'last_name', 'password1', 'password2', 'email', 'phone', ] widgets = { 'username' : forms.TextInput(attrs={'placeholder': 'Логин'}), 'first_name' : forms.TextInput(attrs={'placeholder': 'Имя'}), 'last_name' : forms.TextInput(attrs={'placeholder': 'Фамилия'}), 'email': forms.EmailInput(attrs={'placeholder': '[email protected]'}), 'phone': forms.TextInput(attrs={'placeholder': '+996 (XXX)-XXX-XXX', 'type': 'text'}), } class LoginUserForm(forms.Form): username = forms.CharField(label='username') password = forms.CharField(label='password', widget = forms.PasswordInput, validators=[validate_password]) def clean(self): username = self.cleaned_data['username'] password = self.cleaned_data['password'] user = get_user_model().user_set.by_username(username) if not user: raise forms.ValidationError('User not found!') elif not check_password(password, user.password): raise forms.ValidationError('Incorrect password!') else: return self.cleaned_data class SignedUpUsersForm(forms.Form): first_name = forms.CharField(label='Имя') last_name = forms.CharField(label='Фамилия') phone = forms.CharField(label='Телефон') email = forms.EmailField(label='Электронная почта') course = forms.CharField(label='Курс') def save(self): data = self.cleaned_data record = SignedUpUsers(first_name=data['first_name'], last_name=data['last_name'], phone=data['phone'], email=data['email'], course=data['course']) record.save()
package org.hibernate.envers.test.entities.reventity.trackmodifiedentities; import org.hibernate.envers.RevisionEntity; import org.hibernate.envers.RevisionNumber; import org.hibernate.envers.RevisionTimestamp; import javax.persistence.*; import java.util.HashSet; import java.util.Set; /** * Revision entity which {@code modifiedEntityTypes} field is manually populated by {@link CustomTrackingRevisionListener}. * @author Lukasz Antoniak (lukasz dot antoniak at gmail dot com) */ @Entity @RevisionEntity(CustomTrackingRevisionListener.class) public class CustomTrackingRevisionEntity { @Id @GeneratedValue @RevisionNumber private int customId; @RevisionTimestamp private long customTimestamp; @OneToMany(mappedBy="revision", cascade={CascadeType.PERSIST, CascadeType.REMOVE}) private Set<ModifiedEntityTypeEntity> modifiedEntityTypes = new HashSet<ModifiedEntityTypeEntity>(); public int getCustomId() { return customId; } public void setCustomId(int customId) { this.customId = customId; } public long getCustomTimestamp() { return customTimestamp; } public void setCustomTimestamp(long customTimestamp) { this.customTimestamp = customTimestamp; } public Set<ModifiedEntityTypeEntity> getModifiedEntityTypes() { return modifiedEntityTypes; } public void setModifiedEntityTypes(Set<ModifiedEntityTypeEntity> modifiedEntityTypes) { this.modifiedEntityTypes = modifiedEntityTypes; } public void addModifiedEntityType(String entityClassName) { modifiedEntityTypes.add(new ModifiedEntityTypeEntity(this, entityClassName)); } public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof CustomTrackingRevisionEntity)) return false; CustomTrackingRevisionEntity that = (CustomTrackingRevisionEntity) o; if (customId != that.customId) return false; if (customTimestamp != that.customTimestamp) return false; return true; } public int hashCode() { int result = customId; result = 31 * result + (int) (customTimestamp ^ (customTimestamp >>> 32)); return result; } @Override public String toString() { return "CustomTrackingRevisionEntity(customId = " + customId + ", customTimestamp = " + customTimestamp + ")"; } }
import { Controller, Get, Post, Body } from '@nestjs/common'; import { OrdersService } from '../services/orders.service'; import { CreateOrderDto } from '../dto/create-order.dto'; import { ApiTags, ApiOperation, ApiCreatedResponse, ApiBadRequestResponse, ApiOkResponse, } from '@nestjs/swagger'; @Controller('orders') @ApiTags('Orders') export class OrdersController { constructor(private readonly ordersService: OrdersService) {} @ApiOperation({ description: 'This endpoint creates a new order', summary: 'Create a new order', }) @ApiCreatedResponse({ description: 'Order created successfully', }) @ApiBadRequestResponse({ description: 'Invalid body data', }) @Post() async create(@Body() createOrderDto: CreateOrderDto) { // Boxful API requirement console.log(createOrderDto); return await this.ordersService.create(createOrderDto); } @ApiOperation({ description: 'This endpoint retrieves all the orders. Used for test purposes', summary: 'Get all the orders', }) @ApiOkResponse({ description: 'Orders retrieved successfully', }) @Get() async findAll() { return await this.ordersService.findAll(); } }
package com.acme.api.controllers; import com.acme.api.dto.EmployeeRequestBody; import com.acme.api.dto.GetAllProductsDTO; import com.acme.api.entities.Employee; import com.acme.api.entities.Product; import com.acme.api.dto.ProductRequestBody; import com.acme.api.services.ProductService; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.*; import java.util.List; import java.util.Optional; import java.util.stream.Stream; import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE; @RestController @RequestMapping("/api") public class ProductController { // @Autowired if no constructor. final private ProductService productService; public ProductController(ProductService productService) { this.productService = productService; } @GetMapping("/products") public Stream<GetAllProductsDTO> getProducts() { return productService.getAllProducts(); } @GetMapping("/product") public Product getProduct(@RequestParam(name = "id", required=true) long id) { Optional<Product> product = Optional.ofNullable(productService.getProduct(id)); return product.orElse(null); } @ResponseStatus(value = HttpStatus.CREATED) @PostMapping(value = "/product", consumes = APPLICATION_JSON_VALUE) public Product createProduct(@RequestBody ProductRequestBody productRequestBody) { return productService.createProduct(productRequestBody); } @PutMapping(value = "/product", consumes = APPLICATION_JSON_VALUE) public Product updateProduct(@RequestParam(name = "id", required=true) long id, @RequestBody ProductRequestBody productRequestBody) { return productService.updateProduct(id, productRequestBody); } @DeleteMapping("/product") public void deleteProduct(@RequestParam(name = "id", required=true) long id) { productService.deleteProduct(id); } }
System.register(['@angular/core', '@angular/http', '../const/store-helpers', '../const/store-names', 'ng-lightning/ng-lightning'], function(exports_1, context_1) { "use strict"; var __moduleName = context_1 && context_1.id; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; var core_1, http_1, store_helpers_1, store_names_1, ng_lightning_1; var Following; return { setters:[ function (core_1_1) { core_1 = core_1_1; }, function (http_1_1) { http_1 = http_1_1; }, function (store_helpers_1_1) { store_helpers_1 = store_helpers_1_1; }, function (store_names_1_1) { store_names_1 = store_names_1_1; }, function (ng_lightning_1_1) { ng_lightning_1 = ng_lightning_1_1; }], execute: function() { Following = (function () { function Following(http, storeHelpers) { this.http = http; this.storeHelpers = storeHelpers; } Object.defineProperty(Following.prototype, "followingUrl", { set: function (followingUrl) { this._followingUrl = followingUrl; this.GetFollowing(this._followingUrl); }, enumerable: true, configurable: true }); Object.defineProperty(Following.prototype, "followersUrl", { get: function () { return this._followingUrl; }, enumerable: true, configurable: true }); ; Following.prototype.GetFollowing = function (followingUrl) { var _this = this; this.storeHelpers.SetStore([], store_names_1.FOLLOWINGSTORENAME); this.http.get(followingUrl) .subscribe(function (res) { _this.storeHelpers.SetStore(res.json(), store_names_1.FOLLOWINGSTORENAME); }, function (err) { console.log(err.json().message); }); }; Following.prototype.ngOnInit = function () { // create a store for the list of followers for the current user this.following = this.storeHelpers.StoreFactory(store_names_1.FOLLOWINGSTORENAME, []); }; __decorate([ core_1.Input(), __metadata('design:type', String), __metadata('design:paramtypes', [String]) ], Following.prototype, "followingUrl", null); Following = __decorate([ core_1.Component({ directives: [ng_lightning_1.NGL_DIRECTIVES], providers: [], selector: 'gh-following', styleUrls: ['src/following/following-component.css'], templateUrl: 'src/following/following-component.html', }), __metadata('design:paramtypes', [http_1.Http, store_helpers_1.StoreHelpers]) ], Following); return Following; }()); exports_1("Following", Following); } } }); //# sourceMappingURL=following-component.js.map
/* * Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * This component and the accompanying materials are made available * under the terms of "Eclipse Public License v1.0" * which accompanies this distribution, and is available * at the URL "http://www.eclipse.org/legal/epl-v10.html". * * Initial Contributors: * Nokia Corporation - initial contribution. * * Contributors: * * Description: a data class containing browse-related data * */ #ifndef C_CUPNPAVBROWSEREQUEST_H #define C_CUPNPAVBROWSEREQUEST_H #include <e32base.h> #include <s32mem.h> #include "upnpavbrowsingsession.h" // FORWARD DECLARATIONS // CLASS DECLARATION /** * UPnP AV Controller Client/Server communication helper class * * * @lib - * @since Series 60 3.1 */ class CUpnpAVBrowseRequest : public CBase { public: // Constructors and destructor /** * Two-phased constructor. */ static inline CUpnpAVBrowseRequest* NewLC(); /** * Two-phased constructor. */ static inline CUpnpAVBrowseRequest* NewL(); /** * Destructor. */ inline virtual ~CUpnpAVBrowseRequest(); public: /** * Externalizes device information to stream. * Leaves in case of errors. * @since Series 60 3.0 * @param reference to RWriteStream * @return none */ inline void ExternalizeL( RWriteStream& aStream ) const; /** * Internalizes device information from stream. * Leaves in case of errors. * @since Series 60 3.0 * @param reference to RReadStream * @return none */ inline void InternalizeL( RReadStream& aStream ); /** * Externalizes information to stream and returns the object as a heap * desctiptor. */ inline HBufC8* ToDes8L() const; private: // /** * Constructor */ inline CUpnpAVBrowseRequest(); /** * Perform the second phase construction */ inline void ConstructL(); public: // New methods /** * Set Id * @param aId */ inline void SetIdL( const TDesC8& aId ); /** * Get Id * @return id */ inline const TDesC8& Id(); /** * Set search criteria * @param aSearchCriteria */ inline void SetSearchCriteriaL( const TDesC8& aSearchCriteria ); /** * Get search criteria * @return search criteria */ inline const TDesC8& SearchCriteria(); /** * Set filter * @param aFilter */ inline void SetFilterL( const TDesC8& aFilter ); /** * Get filter * @return filter */ inline const TDesC8& Filter(); /** * Set browse flag * @param aBrowseFlag */ inline void SetBrowseFlag( MUPnPAVBrowsingSession::TBrowseFlag aBrowseFlag ); /** * Get browse flag * @return browse flag */ inline MUPnPAVBrowsingSession::TBrowseFlag BrowseFlag(); /** * Set start index * @param aStartIndex */ inline void SetStartIndex( TInt aStartIndex ); /** * Get start index * @return start index */ inline TInt StartIndex(); /** * Set requested count * @param aRequestedCount */ inline void SetRequestedCount( TInt aRequestedCount ); /** * Get requested count * @return requested count */ inline TInt RequestedCount(); /** * Set sort criteria * @param aSortCriteria */ inline void SetSortCriteriaL( const TDesC8& aSortCriteria ); /** * Get sort criteria * @return sort criteria */ inline const TDesC8& SortCriteria(); private: TInt iCriteriaLength; HBufC8* iId; // Owned HBufC8* iSearchCriteria; // Owned HBufC8* iFilter; // Owned MUPnPAVBrowsingSession::TBrowseFlag iBrowseFlag; TInt iStartIndex; TInt iRequestedCount; HBufC8* iSortCriteria; // Owned }; #include "upnpavbrowserequest.inl" #endif // C_CUPNPAVBROWSEREQUEST_H
<?php namespace Drupal\schema_person\Plugin\metatag\Tag; use Drupal\schema_metatag\Plugin\metatag\Tag\SchemaPersonOrgBase; /** * Provides a plugin for the 'schema_person_affiliation' meta tag. * * - 'id' should be a globally unique id. * - 'name' should match the Schema.org element name. * - 'group' should match the id of the group that defines the Schema.org type. * * @MetatagTag( * id = "schema_person_affiliation", * label = @Translation("affiliation"), * description = @Translation("An organization that this person is affiliated with. For example, a school/university, a club, or a team."), * name = "affiliation", * group = "schema_person", * weight = 11, * type = "string", * secure = FALSE, * multiple = FALSE * ) */ class SchemaPersonAffiliation extends SchemaPersonOrgBase { /** * Generate a form element for this meta tag. */ public function form(array $element = []) { $form = parent::form($element); $form['name']['#attributes']['placeholder'] = '[site:name]'; $form['url']['#attributes']['placeholder'] = '[site:url]'; return $form; } }
<template> <BasePage> <template #query> <<%= TableName %>Query @onAdd="onAdd" @onQuery="queryTableData" @onBatchDelete="onBatchDelete" @onReset="onReset" :queryForm.sync="queryForm" ></<%= TableName %>Query> </template> <<%= TableName %>Table @selection-change="onSelectionChange" :pageInfo.sync="pageInfo" :tableData="tableData" :total="total" @onEdit="onEdit" @onDelete="onDelete" ></<%= TableName %>Table> <<%= TableName %>Dialog ref="dialogRef" @refresh="queryTableData"></<%= TableName %>Dialog> </BasePage> </template> <script> import { QueryConditionBuilder } from '@/utils/common/queryConditionBuilder' import <%= TableName %>Dialog from './components/<%= TableName %>Dialog.vue' import <%= TableName %>Table from './components/<%= TableName %>Table.vue' import <%= TableName %>Query from './components/<%= TableName %>Query.vue' export default { data() { return { tableData: [], queryForm: {}, total: 0, pageInfo: { rows: 20, page: 1, }, multipleSelection: [], } }, components: { <%= TableName %>Dialog, <%= TableName %>Table, <%= TableName %>Query, }, watch: { pageInfo: { handler(newValue) { this.queryTableData() }, deep: true, }, }, mounted() { this.queryTableData() }, methods: { // 新增 onAdd() { this.$refs.dialogRef.show({ title: `新增<%= tableCommon %>` }) }, // 删除 async handleDelete(rows) { if (Array.isArray(rows) && !rows.length) { return this.$tools.message(`请勾选要删除的<%= tableCommon %>信息!`, { type: 'warning' }) } const name = rows.map((item) => item.name).join(',') try { await this.$tools.confirm('请确认是否删除【' + name + '】信息?') const { code } = await this.$api.<%= TableName %>Service.delete<%= TableName %>Batch(rows.map((row) => row.documentId)) if (code === 200) this.$tools.message('删除成功') this.queryTableData() } catch (e) { if (e == 'cancel') return this.$tools.message('已取消删除', { type: 'info' }) console.error('删除失败', e) } }, onBatchDelete() { this.handleDelete(this.multipleSelection) }, // 编辑 onEdit(row) { this.$refs.dialogRef.show({ row, title: `编辑<%= tableCommon %>` }) }, // 删除 onDelete(row) { this.handleDelete([row]) }, onSelectionChange(val) { this.multipleSelection = val }, refreshPagination() { this.pageInfo = { rows: 20, page: 1, } }, onReset() { Object.keys(this.queryForm).forEach((key) => { this.queryForm[key] = '' }) this.refreshPagination() }, async queryTableData() { let queryCondition = QueryConditionBuilder.getInstance(this.pageInfo.page, this.pageInfo.rows) Object.keys(this.queryForm).forEach((key) => { if (this.queryForm[key] || this.queryForm[key] == 0) { queryCondition.buildLikeQuery(key, this.queryForm[key]) } }) const { data, count } = await this.$api.<%= TableName %>Service.query<%= TableName %>(queryCondition) this.tableData = data this.total = count }, }, } </script> <style lang="less" scoped></style>
import { Button } from '@mui/material'; import Box from '@mui/material/Box'; import Grid from '@mui/material/Grid'; import Paper from '@mui/material/Paper'; import { styled } from '@mui/material/styles'; import * as React from 'react'; const Item = styled(Paper)(({ theme }) => ({ backgroundColor: theme.palette.mode === 'dark' ? '#1A2027' : '#fff', ...theme.typography.body2, padding: theme.spacing(1), textAlign: 'center', color: theme.palette.text.secondary, })); export default function GridSample() { return ( <Box sx={{ flexGrow: 1 }}> <Grid container spacing={2}> <Grid item xs={8}> <Item> <Button variant="outlined" color="success"> Button Here </Button> <Button variant="text">Text</Button> <Button variant="contained">Contained</Button> <Button variant="outlined">Outlined</Button> </Item> </Grid> <Grid item xs={4}> <Item>xs=4</Item> </Grid> <Grid item xs={4}> <Item>xs=4</Item> </Grid> <Grid item xs={8}> <Item>xs=8</Item> </Grid> </Grid> </Box> ); }
<div id="min-heigth" *ngIf="isNotLoged(); else loginAlert"> <div class="form-container"> <div class="form-wrapper"> <h1>Cadastro de Usuário</h1> <form action="" class="col-12" [formGroup]="userFormGroup" #formDir="ngForm" (ngSubmit)="createUser()" > <div class="mb-2"> <input type="text" name="userName" autocomplete="off" placeholder="Nome de usuário" [(ngModel)]="userToPersit.username" formControlName="username" /> <div class="validation-error" *ngIf="username!.invalid && formDir.submitted" > <p class="error-p" *ngIf="username!.errors?.['required']"> Digite o nome de usuário </p> <p class="error-p" *ngIf="username!.errors?.['maxlength']"> username ultrapassa o limite de carateres </p> </div> </div> <div class="mb-2"> <input type="password" name="senha" autocomplete="off" placeholder="Senha" class="password" [(ngModel)]="userToPersit.password" formControlName="password" /> <div class="validation-error" *ngIf="password!.invalid && formDir.submitted" > <p class="error-p" *ngIf="password!.errors?.['required']"> Digite a senha Senha </p> <p class="error-p" *ngIf="password!.errors?.['maxlength']"> Senha ultrapassa o limite de carateres </p> </div> </div> <div class="mb-2"> <input type="password" name="senha" autocomplete="off" placeholder="Confirme a senha" class="password" [(ngModel)]="confirmPasswordValue" formControlName="confirmPassword" /> <div class="validation-error" *ngIf="confirmPassword!.invalid && formDir.submitted" > <p class="error-p" *ngIf="confirmPassword!.errors?.['required']"> Digite a senha Senha </p> <p class="error-p" *ngIf="confirmPassword!.errors?.['maxlength']"> Senha ultrapassa o limite de carateres </p> </div> </div> <button class="btn btn-primary" [disabled]="formIsSubmitted"> <p class="p-btn" *ngIf="!clicked; else spin">Cadastrar</p> <ng-template #spin> <div class="spinner-border" role="status"> <span class="visually-hidden">Loading...</span> </div> </ng-template> </button> </form> <p>Já tem login? <a (click)="openLoginForm()">Logar</a></p> </div> </div> </div> <ng-template #loginAlert> <div class="container" id="min-heigth"> <mat-card> <mat-card-content style="display: flex; justify-content: space-between;">Você está logado <a routerLink="/">Voltar</a></mat-card-content> </mat-card> </div> </ng-template>
class Node { constructor(value) { this.value = value; this.next = null; } } class LinkedList { constructor() { this.head = null; this.tail = null; this.size = 0; } isEmpty() { return this.size === 0; } getSize() { return this.size; } print() { if (this.isEmpty()) { console.log("List is empty"); } else { let curr = this.head; let listValue = ""; while (curr) { listValue += `${curr.value} `; curr = curr.next; } console.log(listValue); } } // To add value/node at the starting //on(1) prepend(value) { const node = new Node(value); if (this.isEmpty()) { this.head = node; this.tail = node; } else { node.next = this.head; this.head = node; } this.size++; } //To add value/element/node from the end of the list //on(1) append(value) { const node = new Node(value); if (this.isEmpty()) { this.head = node; this.tail = node; } else { this.tail.next = node; this.tail = node; } this.size++; } //To remove value/node from Front //on(1) removeFromFront() { if (this.isEmpty()) { return null; } const value = this.head.value; this.head = this.head.next; this.size--; return value; } //To remove value from End //on(n) removeFromEnd() { if (this.isEmpty()) { return null; } value = this.tail.value; if (this.size === 1) { this.head = null; this.tail = null; } else { let prev = this.head; while (prev.next !== this.tail) { prev = prev.next; } prev.next = null; this.tail = prev; } this.size--; return value; } } module.exports = LinkedList; // const list = new LinkedList(); // console.log(list.isEmpty()); // console.log(list.size); // list.append(1); // list.append(2); // list.append(3); // list.prepend(10); // list.print();
<!DOCTYPE html> <html lang="ko"> <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>자바스크립트 : 반복문</title> <link rel="stylesheet" href="../assets/css/style.css" /> <link rel="stylesheet" href="../assets/css/dracula.css" /> </head> <body> <header id="header"> <h1><a href="../index.html">javascript</a></h1> <nav class="header_nav"> <ul> <li><a href="../javascript01.html">데이터 저장하기</a></li> <li><a href="../javascript02.html">데이터 불러오기</a></li> <li><a href="../javascript03.html">데이터 실행하기</a></li> <li><a href="../javascript04.html">데이터 제어하기</a></li> </ul> <ul> <li><a href="javascript05.html">문자열 객체</a></li> <li><a href="javascript06.html">배열 객체</a></li> <li><a href="javascript07.html">수학 객체</a></li> <li><a href="javascript08.html">숫자 객체</a></li> <li><a href="javascript09.html">브라우저 객체</a></li> <li><a href="javascript10.html">요소 객체</a></li> <li><a href="javascript11.html">이벤트 객체</a></li> </ul> <ul class="effect"> <li><a href="../effect/searchEffect01.html">검색 효과</a></li> <li><a href="../effect/quizEffect01.html">퀴즈 효과</a></li> <li><a href="../effect/textEffect01.html">텍스트 효과</a></li> <li><a href="../effect/mouseEffect01.html">마우스 효과</a></li> <li><a href="../effect/slideEffect01.html">슬라이드 효과</a></li> <li><a href="../effect/parallaxEffect01.html">페럴랙스 효과</a></li> <li><a href="../effect/gameEffect01.html">게임 효과</a></li> </ul> </nav> </header> <!-- //header --> <main id="main"> <div class="document"> <!-- 주 타이틀 --> <h2 class="t_tit">반복문</h2> <p class="t_desc">반복문은 프로그램에서 필요한 결과 값을 도출하기 위해 <i>실행문의 순서를 반복적으로 실행시키는 문법</i>을 말한다. <br> 반복문에는 while문, do while문, for문이 있으며 <i>for문을 가장 많이 사용</i>한다. </p> <hr> <h3 class="t_tit2">while문</h3> <p class="t_desc"> </p> <p class="t_desc2"> 반복해서 문장을 실행할 경우 사용하는 반복문인데, <br> 조건문이 참일 경우에만 실행이 된다. </p> <h23 class="t_tit2">do while문</h3> <p class="t_desc"> </p> <p class="t_desc2"> while문과 비슷하지만 do while문은 <br> 조건 검사를 하지않고 무조건 한번을 실행해준다. </p> <h23 class="t_tit2">for 문</h3> <p class="t_desc"> </p> <p class="t_desc2"> 반복 횟수를 정확히 알고 있을 때 사용하는 반복문 </p> <hr> <!-- 01 --> <h3 class="t_tit2">0 부터 99 까지 출력하기</h3> <div class="t_code"> <pre><code class="language-js"> //0부터 99까지 출력하기 for( let i=0; i&lt;100; i++ ){ document.write(i) } </code></pre> </div> <h3 class="t_tit2">1 부터 100 까지 출력하기</h3> <div class="t_code"> <pre><code class="language-js">// 1부터 100까지 출력 for( let i=1; i=100; i++ ){ document.write(i); } </code></pre> </div> <div class="t_result"> <details> <summary>결과확인</summary> <div class="result09"> 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100 </div> </details> </div> <h3 class="t_tit2">1 부터 100 까지 출력하기 (짝수)</h3> <p class="t_desc">짝수로 출력할 때는 증가값을 2로 해준다.</p> <div class="t_code"> <pre><code class="language-js">// 1부터 100까지 출력 (짝수) for( let i=1; i<=100; i+=2 ){ // i = i + 2 document.write(i); } </code></pre> </div> <div class="t_result"> <details> <summary>결과확인</summary> <div class="result09"> 2468101214161820222426283032343638404244464850525456586062646668707274767880828486889092949698100 </div> </details> </div> <h3 class="t_tit2">1 부터 100 까지 출력하기 (5의 배수)</h3> <p class="t_desc"> for문을 이용해 1부터 100까지 숫자 중 5의 배수만 출력한다. </p> <div class="t_code"> <pre><code class="language-js">{ for(let i=10; i<=100; i++){ if (i%5 == 0) { document.write(i); } } } </code></pre> </div> <div class="t_result"> <details> <summary>결과확인</summary> <div class="result09"> 101520253035404550556065707580859095100 </div> </details> </div> <h3 class="t_tit2">1 부터 100 까지 출력하기 (5의 배수 빨간색, 7의 배수 파란색)</h3> <p class="t_desc"> 1 부터 100 까지 숫자 중 5의 배수는 빨간색, 7의 배수는 파란색으로 출력한다. </p> <div class="t_code"> <pre><code class="language-js">{ for(let i=1; i<=100; i++){ if (i%5 == 0) { document.write("&lt;span style='color: blue'&gt;"+ i +"&lt;/span&gt;"); } if (i%7 == 0) { document.write("&lt;span style='color: red'&gt;"+ i +"&lt;/span&gt;"); } } } </code></pre> </div> <div class="t_result"> <details> <summary>결과확인</summary> <div class="result09"> 101520253035404550556065707580859095100 </div> </details> </div> <h3 class="t_tit2">구구단 출력하기</h3> <p class="t_desc"> for문을 사용하여 맨앞의 값, 중간 값, 답 값을 반복하여 실행해 구구단을 출력한다.</p> <div class="t_code"> <pre><code class="language-js">{ for (let i=2; i<=9; i++){ // 2 ~ 9 까지의 숫자를 출력 for (let j=1; j<=9; j++){ //위 조건이 1번 실행 될 때 9번 실행 ( 1 ~ 9 까지 출력 ) let sum = i * j; // sum은 답을 출력 해주는 저장소 > i 곱하기 j 가 답으로 나타난다. document.write(i + "*" + j + "=" + sum); } } } </code></pre> </div> <div class="t_result"> <details> <summary>결과확인</summary> <div class="result09"> 2*1=2 <br> 2*2=4 <br> 2*3=6 <br> 2*4=8 <br> 2*5=10 <br> 2*6=12 <br> 2*7=14 <br> 2*8=16 <br> 2*9=18 <br> 3*1=3 <br> 3*2=6 <br> 3*3=9 <br> 3*4=12 <br> 3*5=15 <br> 3*6=18 <br> 3*7=21 <br> 3*8=24 <br> 3*9=27 <br> 4*1=4 <br> 4*2=8 <br> 4*3=12 <br> 4*4=16 <br> 4*5=20 <br> 4*6=24 <br> 4*7=28 <br> 4*8=32 <br> 4*9=36 <br> 5*1=5 <br> 5*2=10 <br> 5*3=15 <br> 5*4=20 <br> 5*5=25 <br> 5*6=30 <br> 5*7=35 <br> 5*8=40 <br> 5*9=45 <br> 6*1=6 <br> 6*2=12 <br> 6*3=18 <br> 6*4=24 <br> 6*5=30 <br> 6*6=36 <br> 6*7=42 <br> 6*8=48 <br> 6*9=54 <br> 7*1=7 <br> 7*2=14 <br> 7*3=21 <br> 7*4=28 <br> 7*5=35 <br> 7*6=42 <br> 7*7=49 <br> 7*8=56 <br> 7*9=63 <br> 8*1=8 <br> 8*2=16 <br> 8*3=24 <br> 8*4=32 <br> 8*5=40 <br> 8*6=48 <br> 8*7=56 <br> 8*8=64 <br> 8*9=72 <br> 9*1=9 <br> 9*2=18 <br> 9*3=27 <br> 9*4=36 <br> 9*5=45 <br> 9*6=54 <br> 9*7=63 <br> 9*8=72 <br> 9*9=81 </div> </details> </div> <h3 class="t_tit2">for문을 이용해서 테이블 출력</h3> <p class="t_desc">중첩 for문을 이용해서 테이블을 만들 수 있다.</p> <div class="t_code"> <pre><code class="language-js">//for문을 이용해서 테이블 100칸 출력 let table = "&lt;table&gt;"; for(let i=0; i&lt;10; i++){ table += "&lt;tr&gt;"; for(let j=0; j&lt;10; j++){ table += "&lt;td&gt;😍&lt;/td&gt;"; } table += "&lt;/tr&gt;"; } table +="&lt;/table&gt;"; document.write(table); </code></pre> </div> <div class="t_result"> <details> <summary>결과확인</summary> <div class="result01"> </div> </details> <style> .testTable tr td { border: 1px solid #000; } </style> <script> let table = "<table class='testTable'>"; for(let i=0; i<10; i++){ table += "<tr>"; for(let j=0; j<10; j++){ table += "<td>😍</td>"; } table += "</tr>"; } table +="</table>"; document.querySelector(".result01").innerHTML = table; </script> </div> </div> </main> <!-- //main and --> <footer id="footer"> <a href="mailto:[email protected]">[email protected]</a> </footer> <!-- //footer and --> <script src="../assets/js/highlight.min.js"></script> <script> hljs.highlightAll(); </script> <script> //for문을 이용해서 10~50까지 출력 (5의 배수) { for(let i=10; i<=50; i++){ if (i%5 == 0) { //document.write(i); } } } document.write("<br>"); //for문을 이용해서 1~100까지 출력 (5의 배수, 7의 배수) { for(let i=1; i<=100; i++){ //if (i%5 == 0) { //document.write("<span style='color: blue'>"+i+"</span>"); //} //if (i%7 == 0) { //document.write("<span style='color: red'>"+i+"</span>"); //} } } document.write("<br>"); //for문을 이용해서 1~100까지 출력(짝수는 빨, 홀수는 파) { for(let i=1; i<=100; i++){ if (i%2 == 0) { //document.write("<span style='color: red'>"+i+"<span>"); } else { //document.write("<span style='color: blue'>"+i+"<span>"); } // if (i%2 == 1) { // document.write("<span style='color: blue'>"+i+"<span>"); // } } } document.write("<br>"); //조건부 연산자로 바꿔서 1~100까지 출력(짝수는 빨, 홀수는 파) { for(let i=1; i<=100; i++){ //(i%2 == 0) ? document.write("<span style='color: red'>"+i+"<span>") : document.write("<span style='color: blue'>"+i+"<span>"); } } document.write("<br>"); //구구단 출력 //i * j = sum // 2 * 1 = 2 앞에 숫자 i = 8번 반복 // 2 * 2 = 4 뒤에 숫자 j = 9번 반복 // 2 * 3 = 6 // 2 * 4 = 8 // 2 * 5 = 10 // 2 * 6 = 12 // 2 * 7 = 14 // 2 * 8 = 16 // 2 * 9 = 18 { for (let i=2; i<=9; i++){ for (let j=1; j<=9; j++){ let sum = i * j; //document.write(i + "*" + j + "=" + sum); //document.write("<br>"); } } } //for문을 이요해서 테이블 만들기 { // 데이터 타입 (자료형) // let table1 = 1; //변수 안에 숫자 // let table2 = "1"; //변수 안에 문자 // let table3 = []; //변수 안에 배열 // let table4 = []; //변수 안에 배열 // let table5 = true; //변수 안에 불린 (참, 거짓) // let table6; 변수 안에 특수값 (null, undifined) let table = "<table class='testTable'>"; for(let i=1; i<=10; i++){ table += "<tr>"; for (let j=1; j<=10; j++){ table += "<td>1</td>"; } table += "</tr>"; } table += "</table>"; //document.write(table) } </script> </body> </html>
package ru.practicum.ewm.comment.service; import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import ru.practicum.ewm.comment.dto.CommentDtoRequest; import ru.practicum.ewm.comment.dto.CommentDtoResponse; import ru.practicum.ewm.comment.dto.CommentDtoResponseLong; import ru.practicum.ewm.comment.dto.CommentDtoUpdateRequest; import ru.practicum.ewm.comment.entity.Comment; import ru.practicum.ewm.comment.enums.CommentSort; import ru.practicum.ewm.comment.enums.MessageUpdateInitiator; import ru.practicum.ewm.comment.mapper.CommentMapper; import ru.practicum.ewm.comment.repository.CommentRepository; import ru.practicum.ewm.error.exception.AlreadyExistException; import ru.practicum.ewm.error.exception.NotExistException; import ru.practicum.ewm.event.entity.Event; import ru.practicum.ewm.event.enums.EventState; import ru.practicum.ewm.event.exception.EventNotPublishedException; import ru.practicum.ewm.event.repository.EventRepository; import ru.practicum.ewm.user.entity.User; import ru.practicum.ewm.user.exception.WrongUserException; import ru.practicum.ewm.user.repository.UserRepository; import java.time.LocalDateTime; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; @Service @Transactional @Slf4j @AllArgsConstructor public class CommentServiceImpl implements CommentService { private final CommentRepository commentRepository; private final UserRepository userRepository; private final EventRepository eventRepository; private final CommentMapper commentMapper; @Override public void deleteCommentByAdmin(Long commentId) { Comment comment = getComment(commentId); if (comment.getAnswered() != null) { List<Comment> messages = commentRepository.findAllByReplyToIdId(commentId); for (Comment cmt : messages) { cmt.setReplyToId(null); } commentRepository.saveAll(messages); } commentRepository.deleteById(commentId); log.info("Comment with ID {} was deleted by admin", commentId); } @Override public CommentDtoResponse updateCommentByAdmin(Long commentId, CommentDtoUpdateRequest request) { Comment comment = getComment(commentId); comment.setText(request.getText()); comment.setLastUpdatedOn(LocalDateTime.now()); comment.setUpdateInitiator(MessageUpdateInitiator.ADMIN); Comment result = commentRepository.save(comment); log.info("Comment with ID {} was updated by admin", commentId); return commentMapper.toCommentDtoResponse(result); } @Override public List<CommentDtoResponseLong> searchUserCommentsByAdmin(Long userId, int from, int size) { existsUser(userId); Sort sort = Sort.by(CommentSort.CREATED_ON.getTitle()); Pageable pageable = PageRequest.of(from / size, size, sort); List<Comment> comments = commentRepository.findAllByAuthorId(userId, pageable).toList(); log.info("{} messages was founded", comments.size()); return commentMapper.toCommentDtosResponseLong(comments); } @Override public CommentDtoResponse createCommentByUser(Long userId, Long eventId, CommentDtoRequest request) { Event event = getEvent(eventId); if (event.getState() != EventState.PUBLISHED) { throw new EventNotPublishedException("only for a published event"); } User user = getUser(userId); Comment reply = null; if (request.getReplyToIdLong() != null) { reply = getComment(request.getReplyToIdLong()); if (reply.getAnswered() == null || !reply.getAnswered()) { reply.setAnswered(true); reply = commentRepository.save(reply); } } MessageUpdateInitiator initiator = MessageUpdateInitiator.USER; Comment result = commentMapper.toNewComment(request); result.setEvent(event); result.setAuthor(user); result.setReplyToId(reply); result.setUpdateInitiator(initiator); result.setCreatedOn(LocalDateTime.now()); result = commentRepository.save(result); log.info("Create comment ID {} for event ID {}", result.getId(), result.getEvent().getId()); return commentMapper.toCommentDtoResponse(result); } @Override public CommentDtoResponse updateCommentByUser(Long userId, Long commentId, CommentDtoUpdateRequest request) { Comment comment = getComment(commentId); existsUser(userId); if (!Objects.equals(comment.getAuthor().getId(), userId)) { throw new WrongUserException("User with id=" + userId + " is not the author of the comment"); } if (comment.getAnswered() != null && comment.getAnswered()) { throw new AlreadyExistException("The comment has already been answered."); } comment.setText(request.getText()); comment.setLastUpdatedOn(LocalDateTime.now()); comment.setUpdateInitiator(MessageUpdateInitiator.USER); Comment result = commentRepository.save(comment); log.info("Comment with ID {} was updated by user", commentId); return commentMapper.toCommentDtoResponse(result); } @Override public void deleteCommentByUser(Long userId, Long commentId) { Comment comment = getComment(commentId); existsUser(userId); if (!Objects.equals(comment.getAuthor().getId(), userId)) { throw new WrongUserException("User with id=" + userId + " is not the author of the comment"); } if (comment.getAnswered() != null && comment.getAnswered()) { throw new AlreadyExistException("The comment has already been answered."); } commentRepository.deleteById(commentId); log.info("Comment with ID {} was deleted by user", commentId); } @Override public List<CommentDtoResponse> getEventCommentsByUser(Long userId, Long eventId, int from, int size) { existsUser(userId); Sort sort = Sort.by(CommentSort.CREATED_ON.getTitle()); Pageable pageable = PageRequest.of(from / size, size, sort); List<Comment> comments = commentRepository.findAllByEventId(eventId, pageable).toList(); log.info("{} comments for event ID {} was founded", comments.size(), eventId); return commentMapper.toCommentDtosResponse(comments); } @Override public Map<Long, Integer> getCommentsCountForEvents(List<Event> events) { Map<Long, Integer> result = new HashMap<>(); for (Event event : events) { Integer count = commentRepository.countAllByEventId(event.getId()) == null ? 0 : commentRepository.countAllByEventId(event.getId()); result.put(event.getId(), count); } return result; } private void existsUser(Long userId) { if (!userRepository.existsById(userId)) { throw new NotExistException("User id = " + userId + " not found"); } } private User getUser(Long userId) { return userRepository.findById(userId) .orElseThrow(() -> new NotExistException("User id = " + userId + " not found")); } private Comment getComment(Long commentId) { return commentRepository.findById(commentId) .orElseThrow(() -> new NotExistException("Comment id=" + commentId + " not found")); } private Event getEvent(Long eventId) { return eventRepository.findById(eventId) .orElseThrow(() -> new NotExistException("Event id=" + eventId + " not found")); } }
\PassOptionsToPackage{table}{xcolor} \documentclass[aspectratio=169]{beamer} \usetheme{auriga} \usecolortheme{auriga} \setbeamersize{text margin left=2em,text margin right=2em} \usepackage{fontspec} \usepackage{xcolor} \usepackage{enumitem} \usepackage{makecell} \usepackage{tabularx} % for vertical centering text in X column \renewcommand\tabularxcolumn[1]{m{#1}} \newcolumntype{C}{>{\centering\arraybackslash}X} \setmainfont{PT Astra Serif} \title{ \huge{VXLAN} \\ \vskip0pt plus 1filll \large{Что это, зачем нужен и почему не VLAN?} } \author{Швалов Даниил К33211} \institute{Университет ИТМО} \date{2023} \begin{document} % change itemize default label \def\labelitemi{---} \frame{\titlepage} \begin{frame} \frametitle{Введение} \begin{figure}[H] \centering \includegraphics[width=0.5\textwidth]{images/xkcd.png} \end{figure} Представим, что мы являемся небольшим провайдером виртуальных машин. Пару дней назад крупный клиент захотел, чтобы машины могли общаться между собой по внутренней сети. Причем все это должно быть безопасно. \vspace*{1em} Первое, что приходит в голову --- это \textbf{VLAN}. \end{frame} \begin{frame} \frametitle{Что такое VLAN?} \begin{figure}[H] \centering \includegraphics[width=0.8\textwidth]{images/vlan.png} \end{figure} \vspace*{1em} VLAN (Virtual Local Area Network) --- это технология, которая позволяет создавать группы устройств, имеющих возможность взаимодействовать между собой напрямую на канальном уровне, хотя физически при этом они могут быть подключены к разным коммутаторам. \end{frame} \begin{frame} \frametitle{Зачем нужен VLAN?} \begin{minipage}{0.45\textwidth} VLAN используется для: \vspace*{1em} \begin{itemize} \item гибкого разделения устройств на группы; \item уменьшения количества широковещательного трафика в сети; \item повышения безопасности и управляемости сети. \end{itemize} \end{minipage} \hspace*{1em} \begin{minipage}{0.45\textwidth} \centering \includegraphics[width=0.9\textwidth]{images/vlan-example.png} \end{minipage} \end{frame} \begin{frame} \frametitle{Устройство VLAN} \begin{figure}[H] \centering \includegraphics[width=0.8\textwidth]{images/vlan-access-trunk.png} \end{figure} \footnotesize \begin{itemize}[label=,leftmargin=0pt] \item \textbf{Access порт} --- это порт принадлежащий одному VLAN-у и передающий нетегированный трафик. Access порт может принадлежать только одному VLAN-у, по умолчанию это первый (нетегированный) VLAN. Любой кадр, который проходит через access порт, помечается номером, принадлежащим этому VLAN-у. \item \textbf{Trunk порт} --- это порт передающий тегированный трафик одного или нескольких VLAN-ов. Этот порт, наоборот, не изменяет тег, а лишь пропускает кадры с тегами, которые разрешены на этом порту. \end{itemize} \end{frame} \begin{frame} \frametitle{Формат кадра VLAN} Стандартный Ethernet кадр: \begin{center} \footnotesize \renewcommand*{\arraystretch}{3.0} \begin{tabularx}{\textwidth}{|c|c|c|C|c|} \hline \shortstack{Source MAC \\ 6 байт} & \shortstack{Destination MAC \\ 6 байт} & \shortstack{Type \\ 2 байта} & \shortstack{Payload \\ 1500 байт} & \shortstack{FSC \\ 4 байта} \\ \hline \end{tabularx} \end{center} \vspace*{1em} VLAN Ethernet кадр: \begin{center} \footnotesize \renewcommand*{\arraystretch}{3.0} \begin{tabularx}{\textwidth}{|c|c|c|c|C|c|} \hline \shortstack{Source MAC \\ 6 байт} & \shortstack{Destination MAC \\ 6 байт} & \shortstack{802.1Q Tag \\ 4 байта} & \shortstack{Type \\ 2 байта} & \shortstack{Payload \\ 1500 байт} & \shortstack{FSC \\ 4 байта} \\ \hline \end{tabularx} \end{center} \end{frame} \begin{frame} \frametitle{Формат кадра VLAN} VLAN Ethernet кадр: \begin{center} \footnotesize \renewcommand*{\arraystretch}{3.0} \begin{tabularx}{\textwidth}{|c|c|c|c|C|c|} \hline \shortstack{Source MAC \\ 6 байт} & \shortstack{Destination MAC \\ 6 байт} & \cellcolor{yellow!25}\shortstack{802.1Q Tag \\ 4 байта} & \shortstack{Type \\ 2 байта} & \shortstack{Payload \\ 1500 байт} & \shortstack{FSC \\ 4 байта} \\ \hline \end{tabularx} \end{center} \vspace*{1em} Формат 802.1Q Tag: \begin{center} \footnotesize \renewcommand*{\arraystretch}{3.0} \begin{tabularx}{\textwidth}{|C|C|C|C|} \hline \shortstack{TPID \\ 16 бит} & \shortstack{PCP \\ 3 бита} & \shortstack{DEI \\ 1 бит} & \shortstack{VID \\ 12 бит} \\ \hline \end{tabularx} \end{center} \vspace*{1em} \begin{itemize}[label=,leftmargin=0pt] \item \textbf{Tag Protocol Identifier}: указывает какой протокол используется для тегирования. \item \textbf{Priority code point}: используется для задания приоритета передаваемого трафика. \item \textbf{Drop eligible indicator}: используется для указания кадров, которые могут быть отброшены в случае перегрузки. \item \textbf{VLAN Identifier}: указывает какому VLAN принадлежит кадр. \end{itemize} \end{frame} \begin{frame} \frametitle{Самое время задаться вопросом} \begin{center} \LARGE{Отлично, все работает. \\ Но зачем тогда нужен VXLAN?} \end{center} \end{frame} \begin{frame} \frametitle{Недостатки VLAN} 1. Количество подсетей не может быть больше, чем 4094 (0 или 4095 зарезервированы), поскольку VID всего 12 бит. \begin{center} \footnotesize \renewcommand*{\arraystretch}{3.0} \begin{tabularx}{\textwidth}{|C|C|C|C|} \hline \shortstack{TPID \\ 16 бит} & \shortstack{PCP \\ 3 бита} & \shortstack{DEI \\ 1 бит} & \cellcolor{yellow!25}\shortstack{VID \\ 12 бит} \\ \hline \end{tabularx} \end{center} Этого недостаточно для больших облачных провайдеров. \vspace*{2em} 2. VLAN работает на втором уровне модели OSI. Это вносит свои ограничения, в частности, VLAN не подходит для межсетевого туннелирования. \end{frame} \begin{frame} \frametitle{А это значит, что} \begin{center} \LARGE{VXLAN спешит на помощь!} \end{center} \end{frame} \begin{frame} \frametitle{VXLAN} \begin{figure}[H] \centering \includegraphics[width=\textwidth]{images/vtep.png} \end{figure} VXLAN (Virtual Extensible Local Area Network) --- это технология сетевой виртуализации, которая инкапсулирует пакеты данных, отправленные от виртуальных машин, в пакеты UDP. \vspace*{1em} VTEP (VXLAN tunnel endpoint) --- это конечные точки, которые инкапсулируют и декапсулируют пакеты VXLAN. \end{frame} \begin{frame} \frametitle{VXLAN} \begin{figure}[H] \centering \includegraphics[width=\textwidth]{images/underlay.png} \end{figure} \end{frame} \begin{frame} \frametitle{VXLAN} \begin{figure}[H] \centering \includegraphics[width=\textwidth]{images/overlay.png} \end{figure} \end{frame} \begin{frame} \frametitle{Формат кадра VXLAN} VLAN кадр: \begin{center} \footnotesize \renewcommand*{\arraystretch}{3.0} \begin{tabularx}{\textwidth}{|c|C|c|} \hline \shortstack{Ethernet \\ 18 байт} & \shortstack{Payload \\ 1500 байт} & \shortstack{FSC \\ 4 байта} \\ \hline \end{tabularx} \end{center} \vspace*{1em} VXLAN кадр: \begin{center} \footnotesize \renewcommand*{\arraystretch}{3.0} \begin{tabularx}{\textwidth}{|c|c|c|c|c|C|c|} \hline \shortstack{Outer Ethernet \\ 14 байт} & \shortstack{Outer IP \\ 20 байт} & \shortstack{UDP \\ 8 байт} & \shortstack{VXLAN \\ 8 байт} & \shortstack{Inner Ethernet \\ 14 (18) байт} & \shortstack{Payload \\ 1500 байт} & \shortstack{FSC \\ 4 байта} \\ \hline \end{tabularx} \end{center} \end{frame} \begin{frame} \frametitle{Формат кадра VXLAN} VXLAN кадр: \begin{center} \footnotesize \renewcommand*{\arraystretch}{3.0} \begin{tabularx}{\textwidth}{|c|c|c|c|c|C|c|} \hline \cellcolor{yellow!25}\shortstack{Outer Ethernet \\ 14 байт} & \shortstack{IPv4 \\ 20 байт} & \shortstack{UDP \\ 8 байт} & \shortstack{VXLAN \\ 8 байт} & \shortstack{Inner Ethernet \\ 14 (18) байт} & \shortstack{Payload \\ 1500 байт} & \shortstack{FSC \\ 4 байта} \\ \hline \end{tabularx} \end{center} \vspace*{1em} Формат Ethernet заголовка: \begin{center} \footnotesize \renewcommand*{\arraystretch}{3.0} \begin{tabularx}{\textwidth}{|C|C|C|} \hline \shortstack{Source MAC \\ 6 байт} & \shortstack{Destination MAC \\ 6 байт} & \shortstack{Type \\ 2 байта} \\ \hline \end{tabularx} \end{center} \vspace*{1em} \begin{itemize}[label=,leftmargin=0pt] \item \textbf{Destination MAC}: MAC-адрес VTEP, на который будет отправлен пакет в соответствии с таблицей маршрутизации. \item \textbf{Source MAC}: MAC-адрес VTEP, на который виртуальная машина отправляет пакет. \item Все остальное заполняется также, как для обычного Ethernet. \end{itemize} \end{frame} \begin{frame} \frametitle{Формат кадра VXLAN} VXLAN кадр: \begin{center} \footnotesize \renewcommand*{\arraystretch}{3.0} \begin{tabularx}{\textwidth}{|c|c|c|c|c|C|c|} \hline \shortstack{Outer Ethernet \\ 14 байт} & \cellcolor{yellow!25}\shortstack{IPv4 \\ 20 байт} & \shortstack{UDP \\ 8 байт} & \shortstack{VXLAN \\ 8 байт} & \shortstack{Inner Ethernet \\ 14 (18) байт} & \shortstack{Payload \\ 1500 байт} & \shortstack{FSC \\ 4 байта} \\ \hline \end{tabularx} \end{center} \vspace*{1em} Формат IPv4 заголовка: \begin{center} \footnotesize \renewcommand*{\arraystretch}{3.0} \begin{tabularx}{\textwidth}{|C|C|C|} \hline \shortstack{\ldots \\ 12 байт} & \shortstack{Source IP \\ 4 байта} & \shortstack{Destination IP \\ 4 байта} \\ \hline \end{tabularx} \end{center} \vspace*{1em} \begin{itemize}[label=,leftmargin=0pt] \item \textbf{Source IP}: IP-адрес локального VTEP. \item \textbf{Destination IP}: IP-адрес удаленного VTEP. \item Все остальное заполняется также, как для обычного IPv4. \end{itemize} \end{frame} \begin{frame} \frametitle{Формат кадра VXLAN} VXLAN кадр: \begin{center} \footnotesize \renewcommand*{\arraystretch}{3.0} \begin{tabularx}{\textwidth}{|c|c|c|c|c|C|c|} \hline \shortstack{Outer Ethernet \\ 14 байт} & \shortstack{IPv4 \\ 20 байт} & \cellcolor{yellow!25}\shortstack{UDP \\ 8 байт} & \shortstack{VXLAN \\ 8 байт} & \shortstack{Inner Ethernet \\ 14 (18) байт} & \shortstack{Payload \\ 1500 байт} & \shortstack{FSC \\ 4 байта} \\ \hline \end{tabularx} \end{center} \vspace*{1em} Формат UDP заголовка: \begin{center} \footnotesize \renewcommand*{\arraystretch}{3.0} \begin{tabularx}{\textwidth}{|C|C|C|C|} \hline \shortstack{Source port \\ 2 байта} & \shortstack{Destination port \\ 2 байта} & \shortstack{Length \\ 2 байта} & \shortstack{Checksum \\ 2 байта} \\ \hline \end{tabularx} \end{center} \vspace*{1em} \begin{itemize}[label=,leftmargin=0pt] \item \textbf{Source Port}: вычисляется хешированием заголовков внутреннего кадра Ethernet. \item \textbf{Destination Port}: всегда равен 4789. \item Все остальное заполняется также, как для обычного UDP. \end{itemize} \end{frame} \begin{frame} \frametitle{Формат кадра VXLAN} VXLAN кадр: \begin{center} \footnotesize \renewcommand*{\arraystretch}{3.0} \begin{tabularx}{\textwidth}{|c|c|c|c|c|C|c|} \hline \shortstack{Outer Ethernet \\ 14 байт} & \shortstack{IPv4 \\ 20 байт} & \shortstack{UDP \\ 8 байт} & \cellcolor{yellow!25}\shortstack{VXLAN \\ 8 байт} & \shortstack{Inner Ethernet \\ 14 (18) байт} & \shortstack{Payload \\ 1500 байт} & \shortstack{FSC \\ 4 байта} \\ \hline \end{tabularx} \end{center} \vspace*{1em} Формат заголовка VXLAN: \begin{center} \footnotesize \renewcommand*{\arraystretch}{3.0} \begin{tabularx}{\textwidth}{|C|C|C|C|} \hline \shortstack{VXLAN Flags \\ 1 байт} & \shortstack{Reserved \\ 3 байта} & \shortstack{VNI \\ 3 байта} & \shortstack{Reserved \\ 1 байт} \\ \hline \end{tabularx} \end{center} \vspace*{1em} \begin{itemize}[label=,leftmargin=0pt] \item \textbf{VXLAN Flags}: пятый бит должен быть равен 1. Этот бит сигнализирует о том, что заголовок содержит корректный VNI. Остальные семь бит зарезервированы и равны 0. \item \textbf{VNI}: идентификатор виртуальной сети. \item \textbf{Reversed}: зарезервировано, все биты должны быть равны 0. \end{itemize} \end{frame} \begin{frame} \frametitle{Отличия VXLAN от VLAN} VLAN кадр: \begin{center} \footnotesize \renewcommand*{\arraystretch}{3.0} \begin{tabularx}{\textwidth}{|c|C|c|} \hline \shortstack{Ethernet \\ 18 байт} & \shortstack{Payload \\ 1500 байт} & \shortstack{FSC \\ 4 байта} \\ \hline \end{tabularx} \end{center} \vspace*{1em} VXLAN кадр: \begin{center} \footnotesize \renewcommand*{\arraystretch}{3.0} \begin{tabularx}{\textwidth}{|c|c|c|c|c|C|c|} \hline \shortstack{Outer Ethernet \\ 14 байт} & \shortstack{Outer IP \\ 20 байт} & \shortstack{UDP \\ 8 байт} & \shortstack{VXLAN \\ 8 байт} & \shortstack{Inner Ethernet \\ 14 (18) байт} & \shortstack{Payload \\ 1500 байт} & \shortstack{FSC \\ 4 байта} \\ \hline \end{tabularx} \end{center} \vspace*{1em} \begin{itemize} \item максимальное количество виртуальных сетей, поддерживаемых VXLAN, составляет более 16 миллионов; \item для конфигурации VXLAN реконфигурация физического сетевого оборудования не требуется. \end{itemize} \end{frame} \begin{frame} \frametitle{Итого имеем} \begin{figure}[H] \centering \includegraphics[width=0.7\textwidth]{images/overlay.png} \end{figure} VXLAN --- это технология сетевой виртуализации, которая инкапсулирует пакеты данных, отправленные от виртуальных машин, в пакеты UDP. VXLAN позволяет большому количеству арендаторов предоставлять услуги доступа к виртуальной сети. \end{frame} \begin{frame} \frametitle{Спасибо за внимание} \begin{figure}[H] \centering \includegraphics[width=0.7\textwidth]{images/standards_2x.png} \caption{Мемчик напоследок} \end{figure} \end{frame} \end{document}
<html> <head> <script src="https://d3js.org/d3.v4.min.js"></script> </head> <body> <form> <label> <input type="radio" name="option" value="2011" onclick="radioClicked(this)"> 2011 </label> <label> <input type="radio" name="option" value="2012" onclick="radioClicked(this)"> 2012 </label> <label> <input type="radio" name="option" value="2013" onclick="radioClicked(this)"> 2013 </label> </form> <svg id="chart" width="600" height="500"></svg> <svg id="chart_scatter" width="600" height="500"></svg> <script> var tooltip = d3.select("body") .append("div") .attr("class", "tooltip") .style("position", "absolute") .style("z-index", "10") .style("visibility", "hidden") .text(""); function radioClicked(radioButton) { function addTooltipText(svgElement, name, x, y, r,value_x,value_y) { var tooltipText = svgElement.append("text") .attr("class", "label") .attr("x", x) .attr("y", y - 10) .style("text-anchor", "middle"); // Split the tooltip content into lines using '\n' var lines = ("Name: " + name + "\nX: " + value_x + "\nY: " + value_y + "\nR: " + r).split('\n'); // Add each line of text as a separate tspan element tooltipText.selectAll("tspan") .data(lines) .enter().append("tspan") .attr("x", x) .attr("dy", "1.2em") // Set line spacing .text(function(d) { return d; }); } var svg = d3.select("#chart"), svgscatter = d3.select('#chart_scatter'), margin = { top: 50, right: 50, bottom: 50, left: 50 }, width = svg.attr("width") - margin.left - margin.right, height = svg.attr("height") - margin.top - margin.bottom; svg.selectAll("*").remove(); // Clear the previous content svgscatter.selectAll("*").remove(); var xScale = d3.scaleBand().range([0, width]).padding(0.4), yScale = d3.scaleLinear().range([height, 0]); var xScale_scatter = d3.scaleLinear().range([0, width]), yScale_scatter = d3.scaleLinear().range([height, 0]); var g = svg.append("g") .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); var gScatter = svgscatter.append("g") .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); d3.csv("yearwise.csv", function (error, data) { if (error) { throw error; } var name_list = []; var x_list = []; var y_list = []; var r_list=[]; var x_value = "X" + radioButton.value; var y_value = "Y" + radioButton.value; var r_value="R"+radioButton.value; data.forEach(function (d) { name_list.push(d.Name); x_list.push(+d[x_value]); y_list.push(+d[y_value]); r_list.push(+d[r_value]); }); xScale.domain(name_list); yScale.domain([0, d3.max(y_list)]); xScale_scatter.domain([0,d3.max(x_list)]); yScale_scatter.domain([0, d3.max(y_list)]); console.log("xScale1 domain:", xScale_scatter.domain()); console.log("x_list:", x_list); g.selectAll(".bar") .data(y_list) .enter().append("rect") .attr("class", "bar") .attr("x", function (_, i) { return xScale(name_list[i]); }) .attr("y", function (d) { return yScale(d); }) .attr("width", xScale.bandwidth()) .attr("height", function (d) { return height - yScale(d); }) .on("mouseover", function(_, i) { // Show tooltip on mouseover g.select(".bar:nth-child(" + (i + 1) + ")") .attr("fill", "red"); gScatter.select(".dot:nth-child(" + (i + 1) + ")") .attr("fill", "red"); // Revert to original color addTooltipText(g, name_list[i], xScale(name_list[i]) + xScale.bandwidth() / 2, yScale(y_list[i]), r_list[i],x_list[i],y_list[i]); addTooltipText(gScatter, name_list[i], xScale_scatter(x_list[i]), yScale_scatter(y_list[i]), r_list[i],x_list[i],y_list[i]); }) .on("mouseout", function(_,i) { // Hide tooltip on mouseout tooltip.style("visibility", "hidden"); g.select(".bar:nth-child(" + (i + 1) + ")") .attr("fill", "black"); gScatter.select(".dot:nth-child(" + (i + 1) + ")") .attr("fill", "black"); // Revert to original color g.select(".label").remove(); gScatter.select(".label").remove(); }); // Draw x axis g.append("g") .attr("class", "x axis") .attr("transform", "translate(0," + height + ")") .call(d3.axisBottom(xScale)); // Draw y axis g.append("g") .attr("class", "y axis") .call(d3.axisLeft(yScale)); // Add x axis label svg.append("text") .attr("transform", "translate(" + (width / 2) + " ," + (height + margin.top + 50) + ")") .style("text-anchor", "middle") .text("Names"); // Add y axis label svg.append("text") .attr("transform", "rotate(-90)") .attr("y", margin.left / 2 - 20) .attr("x", 0 - (height / 2)) .attr("dy", "1em") .style("text-anchor", "middle") .text("Values"); gScatter.selectAll(".dot") .data(y_list) .enter().append("circle") .attr("class", "dot") .attr("cx", function (_, i) { console.log(xScale_scatter(+(x_list[i]))); return xScale_scatter(+(x_list[i])); }) .attr("cy", function (_, i) { return yScale_scatter(+y_list[i]); }) .attr("r", function (_, i) { return r_list[i]; }) .on("mouseover", function(_, i) { // Show tooltip on mouseover g.select(".bar:nth-child(" + (i + 1) + ")") .attr("fill", "red"); gScatter.select(".dot:nth-child(" + (i + 1) + ")") .attr("fill", "red"); // Revert to original color addTooltipText(g, name_list[i], xScale(name_list[i]) + xScale.bandwidth() / 2, yScale(y_list[i]), r_list[i],x_list[i],y_list[i]); addTooltipText(gScatter, name_list[i], xScale_scatter(x_list[i]), yScale_scatter(y_list[i]), r_list[i],x_list[i],y_list[i]); }) .on("mouseout", function(_,i) { // Hide tooltip on mouseout g.select(".bar:nth-child(" + (i + 1) + ")") .attr("fill", "black"); gScatter.select(".dot:nth-child(" + (i + 1) + ")") .attr("fill", "black"); // Revert to original color g.select(".label").remove(); gScatter.select(".label").remove(); }); gScatter.append("g") .attr("class", "x axis") .attr("transform", "translate(0," + height + ")") .call(d3.axisBottom(xScale_scatter)); gScatter.append("g") .attr("class", "y axis") .call(d3.axisLeft(yScale_scatter)); svgscatter.append("text") .attr("transform", "translate(" + (width / 2) + " ," + (height + margin.top + 50) + ")") .style("text-anchor", "middle") .text("X-values"); svgscatter.append("text") .attr("transform", "rotate(-90)") .attr("y", margin.left / 2 - 20) .attr("x", 0 - (height / 2)) .attr("dy", "1em") .style("text-anchor", "middle") .text("Y-values"); }); } </script> </body> </html>
// Import Polyfills import 'first-input-delay'; var Performance = /** @class */ (function () { function Performance(config) { this.config = config; } /** * True if the browser supports the Navigation Timing API, * User Timing API and the PerformanceObserver Interface. * In Safari, the User Timing API (performance.mark()) is not available, * so the DevTools timeline will not be annotated with marks. * Support: developer.mozilla.org/en-US/docs/Web/API/Performance/mark * Support: developer.mozilla.org/en-US/docs/Web/API/PerformanceObserver */ Performance.supported = function () { return window.performance && !!performance.now && !!performance.mark; }; /** * For now only Chrome fully support the PerformanceObserver interface * and the entryType "paint". * Firefox 58: https://bugzilla.mozilla.org/show_bug.cgi?id=1403027 */ Performance.supportedPerformanceObserver = function () { return window.chrome && 'PerformanceObserver' in window; }; /** * When performance API available * returns a DOMHighResTimeStamp, measured in milliseconds, accurate to five * thousandths of a millisecond (5 microseconds). */ Performance.prototype.now = function () { return window.performance.now(); }; Performance.prototype.mark = function (metricName, type) { var mark = "mark_" + metricName + "_" + type; window.performance.mark(mark); }; Performance.prototype.measure = function (metricName, metric) { var startMark = "mark_" + metricName + "_start"; var endMark = "mark_" + metricName + "_end"; window.performance.measure(metricName, startMark, endMark); return this.getDurationByMetric(metricName, metric); }; /** * First Paint is essentially the paint after which * the biggest above-the-fold layout change has happened. * PerformanceObserver subscribes to performance events as they happen * and respond to them asynchronously. * entry.name will be either 'first-paint' or 'first-contentful-paint' */ Performance.prototype.firstContentfulPaint = function (cb) { this.perfObserver = new PerformanceObserver(this.performanceObserverCb.bind(this, cb)); this.perfObserver.observe({ entryTypes: ['paint'] }); }; /** * Get the duration of the timing metric or -1 if there a measurement has * not been made by the User Timing API */ Performance.prototype.getDurationByMetric = function (metricName, metric) { var entry = this.getMeasurementForGivenName(metricName); if (entry && entry.entryType === 'measure') { return entry.duration; } return -1; }; /** * Return the last PerformanceEntry objects for the given name. */ Performance.prototype.getMeasurementForGivenName = function (metricName) { var entries = window.performance.getEntriesByName(metricName); return entries[entries.length - 1]; }; Performance.prototype.performanceObserverCb = function (cb, entryList) { var _this = this; var entries = entryList.getEntries(); cb(entries); entries.forEach(function (performancePaintTiming) { if (_this.config.firstContentfulPaint && performancePaintTiming.name === 'first-contentful-paint') { _this.perfObserver.disconnect(); } }); }; return Performance; }()); export default Performance; //# sourceMappingURL=performance.js.map
#!/usr/bin/python3 # -*- coding: utf-8 -*- # --------------------------------------------------------------------> # 风电机组功率曲线分析 # 功能描述:绘制实际功率曲线,与理论功率曲线对比计算发电量偏差等 # # 数据预处理、数据清洗、诊断分析、结果导出 # > 1. 数据预处理 # > 2. 数据清洗 # > 3. 诊断分析 # > 4. 结果导出 # -------------- # # 输入Input: # 输出Output: # # 其它模块、文件关系: # # 备注: # ~~~~~~~~~~~~~~~~~~~~~~ # # <-------------------------------------------------------------------- # -------------------------------------------------------------------- # *** # 加载包 (import package) # *** # -------------------------------------------------------------------- import os # import logging import math import numpy as np import pandas as pd from scipy.optimize import curve_fit # *** ---------- openoa package ---------- from scipy.optimize import differential_evolution # from openoa.utils import power_curve # from openoa.utils.plot import plot_windfarm # # from openoa.utils.filters import range_flag, bin_filter # # from openoa.utils.power_curve.parametric_forms import logistic5param # from openoa.utils.power_curve.parametric_optimize import least_squares, fit_parametric_power_curve from typing import Callable def logistic_5_parametric(windspeed_col: str, power_col: str) -> Callable: return fit_parametric_power_curve( windspeed_col, power_col, curve=logistic5param, optimization_algorithm=differential_evolution, cost_function=least_squares, #! bounds和风机的额定功率有关系 #TODO: logistic方法需要根据风机的具体额定功率进行调整 bounds=((1900, 2100), (-10, -1e-3), (1e-3, 30), (1e-3, 1), (1e-3, 10)), ) # *** ---------- custom package ---------- from models.bin_analysis.quant.cloud.file_dir_tool import get_full_path from models.bin_analysis.quant.cloud.wind_base_tool import cut_speed, plot_save from models.bin_analysis.quant.cloud.wind_base_tool import power_label, wind_speed_label, gen_speed_label from models.bin_analysis.quant.cloud.wind_base_tool import wind_direction_label, nacelle_temp_label, power_pred_label from models.bin_analysis.quant.cloud.wind_base_tool import air_density_label, wind_speed_bin_label, mark_label # -------------------------------------------------------------------- # *** # 日志和参数配置 # *** # -------------------------------------------------------------------- # *** ---------- 日志 ---------- # logger # logger = logging.getLogger() # -------------------------------------------------------------------- # *** # 数据字段名称配置 # data field name [column name] # *** # -------------------------------------------------------------------- actual_power_label = "actual_power" theory_power_label = "theory_power" std_power_label = "std_power" # -------------------------------------------------------------------- # *** # 功率曲线上下边界 # *** #? 1. 基于贝兹理论betz极限的发电功率-上限 #? 2. 根据R. Chedid提出的功率曲线模型(称之为RC模型) 确定功率最低约束-下限 # -------------------------------------------------------------------- def betz_func_closure(rotor_radius, cut_out, rated_speed, rated_power, rated_factor): """根据风速计算贝兹理论betz极限的发电功率-函数闭包 【闭包】 #? 2017_基于INNER-DBSCAN和功率曲线模型的风机异常状态检测 #? 2019_基于线性插值模型的大型风电机组服役性能在线评估方法 Args: wind_speed (float): 风速 rotor_radius (float): 叶轮半径 cut_out (float): 切出风速 rated_speed (float): 额定风速 rated_power (float): 额定容量 rated_factor (float): _description_ air_density (float, optional): 空气密度. Defaults to None. Returns: _type_: 基于贝兹理论betz极限的发电功率-计算函数 """ def betz_func_inner(wind_speed, air_density=None): return betz_func(wind_speed, rotor_radius, cut_out, rated_speed, rated_power, rated_factor, air_density) return betz_func_inner def betz_func(wind_speed, rotor_radius, cut_out, rated_speed, rated_power, rated_factor, air_density=None): """根据风速计算贝兹理论betz极限的发电功率 #? 2017_基于INNER-DBSCAN和功率曲线模型的风机异常状态检测 #? 2019_基于线性插值模型的大型风电机组服役性能在线评估方法 Args: wind_speed (float): 风速 rotor_radius (float): 叶轮半径 cut_out (float): 切出风速 rated_speed (float): 额定风速 rated_power (float): 额定容量 rated_factor (float): _description_ air_density (float, optional): 空气密度. Defaults to None. Returns: _type_: 基于贝兹理论betz极限的发电功率 """ #TODO: 如否考虑切人风速情况: cut_in, # 最大风能利用系数 #? 实际远小于最大风能利用系数,可以进行调整,缩小边界范围 #? power coefficient为"0.40"刚好可以平滑连接到额定风速 # cp = 0.593 # cp = 0.45 cp = 0.40 # 标准空气密度 if air_density is None: # air_density = 1.225 air_density = 1.40 #TODO: 切出风速柔性拓展控制 # , cut_out_ext=None, cut_out_ext_factor if wind_speed <= rated_speed: area_size = math.pi * pow(rotor_radius, 2) / 1000 power_value = 0.5 * air_density * area_size * pow(wind_speed, 3) * cp power_value = min(power_value, rated_power * rated_factor) return round(power_value, 2) elif wind_speed > cut_out: return 0 elif wind_speed >= rated_speed: return rated_power * rated_factor def rc_func_closure(cut_out, rated_speed, cut_in, rated_power, efficiency=0.05): """根据 R. Chedid提出的功率曲线模型(称之为RC模型) 确定功率最低约束-函数闭包 【闭包】 #? 2017_基于INNER-DBSCAN和功率曲线模型的风机异常状态检测 #? 2019_基于线性插值模型的大型风电机组服役性能在线评估方法 Args: wind_speed (float): 风速 rotor_radius (float): 叶轮半径 cut_out (float): 切出风速 rated_speed (float): 额定风速 rated_power (float): 额定容量 rated_factor (float): _description_ air_density (float, optional): 空气密度. Defaults to None. Returns: _type_: 基于RC模型的风机最低发电功率约束-计算函数 """ def rc_func_inner(wind_speed): return rc_func(wind_speed, cut_out, rated_speed, cut_in, rated_power, efficiency) return rc_func_inner def rc_func(wind_speed, cut_out, rated_speed, cut_in, rated_power, efficiency=0.05): """根据 R. Chedid提出的功率曲线模型(称之为RC模型) 确定功率最低约束 #? 2017_基于INNER-DBSCAN和功率曲线模型的风机异常状态检测 #? 2019_基于线性插值模型的大型风电机组服役性能在线评估方法 Args: wind_speed (float): 风速 rotor_radius (float): 叶轮半径 cut_out (float): 切出风速 rated_speed (float): 额定风速 rated_power (float): 额定容量 rated_factor (float): _description_ air_density (float, optional): 空气密度. Defaults to None. Returns: _type_: 基于RC模型的风机最低发电功率约束 """ #? 对应较低的利用效率的额定功率 rated_power = rated_power * efficiency # if wind_speed < cut_in: return 0 elif wind_speed < rated_speed: ''' a = rated_power / (pow(rated_speed, 3) - pow(cut_in, 3)) b = pow(cut_in, 3) / (pow(rated_speed, 3) - pow(cut_in, 3)) return a * pow(wind_speed, 3) - b * rated_power ''' #? 两种不同的计算步骤,结果一致 cut_in_3 = pow(cut_in, 3) power_value = (pow(wind_speed, 3) - cut_in_3) * rated_power / (pow(rated_speed, 3) - cut_in_3) return round(power_value, 2) elif wind_speed <= cut_out: return rated_power else: return 0 # -------------------------------------------------------------------- # *** # 曲线拟合 # *** # -------------------------------------------------------------------- def sigmoid(x, L, x0, k, b): """ sigmoid函数拟合回归 $ \sigma(x) = \frac{1}{1 + e^{-x}} $ :param x: :param L: 曲线左右偏移 :param x0: :param k: :param b: 曲线上下偏移 :return: sigmoid函数公式 """ y = L / (1 + np.exp(-k*(x-x0))) + b return y def curve_fitting(data, wind_speed_list): """ 使用sigmoid函数拟合功率曲线 :param data: 输入数据时序集 :param wind_speed_list: 风速分箱区间 :return: popt - Optimal values for the parameters curve - 拟合的功率曲线数据点集合 """ try: data = data.reset_index(drop=True) except Exception as e: # logger.info("无需执行此步骤!") print("无需执行此步骤!") #? p0:函数参数的初始值,从而减少计算机的计算量 p0 = [data[power_label].max(), data[wind_speed_label].mean(), 1, data[power_label].min()] # 基于sigmoid拟合功率曲线 popt, pcov = curve_fit(sigmoid, data[wind_speed_label], data[power_label], p0, method="dogbox") #! sigmoid拟合可能没有到达额定功率:到达额定风速以后,额定功率数值线偏下 #? sigmoid拟合修正:保证功率曲线到达额定功率数值线 if sigmoid(20, *popt) > data[power_label].max(): k = 1 + np.exp(-popt[2]*(20-popt[1])) popt[0] = (data[power_label].max() - popt[3]) * k # curve = pd.DataFrame(wind_speed_list) curve[power_label] = pd.DataFrame(sigmoid(wind_speed_list, *popt)) curve.columns = [wind_speed_label, actual_power_label] return popt, curve def calc_actual_power_curve(data): """ 计算实际功率曲线数值点【计算每个分箱平均值】 :param data: 输入数据时序集 :return: 功率曲线数据点集合 """ # *** ---------- 1 对风速划分区间 ---------- data, speed_list = cut_speed(data) # *** ---------- 2 根据2个思路绘制实际功率曲线 ---------- speed_bin_dataset = data.groupby(wind_speed_bin_label) actual_power_df = pd.DataFrame() for index, bin_data in speed_bin_dataset: #? 分箱区间点太少,不操作:功率曲线不考虑该部分数值 if len(bin_data) > 0.0001 * len(data): # 2.1 根据IEC按照风速分箱生成实际功率 actual_power = bin_data[power_label].mean() std_power = bin_data[power_label].std() actual_power_curve = pd.DataFrame([index, actual_power, std_power]).T actual_power_curve.columns = [wind_speed_label, actual_power_label, std_power_label] # actual_power_df = actual_power_df._append(actual_power_curve) actual_power_df = pd.concat([actual_power_df, actual_power_curve]) # 2.2 最终的实际功率曲线数据 actual_power_df = actual_power_df[actual_power_df[wind_speed_label] != -1] actual_power_df = actual_power_df.sort_values(wind_speed_label).reset_index(drop=True) return actual_power_df def theory_curve_prep(data, speed_list, avg_air_density = None): """ 理论功率曲线处理 :param data: 标准空气密度下的功率曲线 :param speed_list: 风速分仓列表 :param avg_air_density: 当地实际空气密度【年平均值】 :return: 理论功率曲线数值点 """ # *** ---------- 1 空气密度风速转换 ---------- data1, data2 = data.copy(), data.copy() # 空气密度转换:当地空气密度报标准空气密度的风速转换 if avg_air_density is not None: data1[wind_speed_label] = data1[wind_speed_label].apply(lambda x: x/pow((avg_air_density/1.225), 1/3)) # data1[wind_speed_label] = data1[wind_speed_label] + 0.5 #TODO: 理论功率曲线的两种生成方式 #! 二选一:基于直线拟合和基于sigmoid曲线的两种模式 # *** ---------- 模式一:2 按照原本的风速采样点提取出功率数据 ---------- #! 直接对转换的理论功率曲线进行线性拟合(问题点:曲线不够平滑) # 取理论功率曲线 data2[theory_power_label] = np.nan # all_data = data1._append(data2).sort_values(wind_speed_label) all_data = pd.concat([data1, data2]).sort_values(wind_speed_label) #! 线性拟合:直线拟合 all_data = all_data.interpolate() # 去除空值 all_data = all_data.fillna(method="bfill") # 由于空气密度转换,风速[wind_speed_label]数值变换,需要提取出[3, 3.5, 4......]以0.5为间隔的数据 # "theory_power_temp"为临时标签点,进行指定风速点的功率曲线提取 all_data.columns = [wind_speed_label, "theory_power_temp"] theory_curve = pd.merge(all_data, data, left_on=wind_speed_label, right_on=wind_speed_label, how="inner") theory_curve = theory_curve[[wind_speed_label, "theory_power_temp"]] theory_curve.columns = [wind_speed_label, theory_power_label] # 将功率值转换为整数 theory_curve[theory_power_label] = theory_curve[theory_power_label].astype("int32") # *** ---------- 模式二:3 按照sigmoid曲线拟合功率数据 ---------- ''' #? 适用sigmoid曲线拟合回归 data1 = data1.rename(columns={theory_power_label: power_label}) popt, theory_curve = curve_fitting(data1, speed_list) theory_curve = theory_curve.rename(columns={actual_power_label: theory_power_label}) ''' # *** ---------- 4 功率数据微调,去除异常值 ---------- # 理论功率效果过好,进行部分微调,主要是性能过好,将其调低 # theory_curve[wind_speed_label] = theory_curve[wind_speed_label] + 0.5 # theory_curve[theory_power_label] = theory_curve[theory_power_label] - 8 theory_curve.loc[theory_curve[theory_power_label] < 0, theory_power_label] = 0 theory_curve = theory_curve.reset_index(drop=True) return theory_curve # -------------------------------------------------------------------- # *** # 数据可视化 # *** # -------------------------------------------------------------------- def scatter_two(data): """ 对数据进行可视化 :param data: 输入数据时序集 :return: """ import seaborn as sns import matplotlib.pyplot as plt plt.figure() #? hue="label": 标记异常数据与否 sns.scatterplot(data=data, x=wind_speed_label, y=power_label, hue="label") plt.title("speed_power") plt.show() def plot_power_var(data, power_bin_data, turbine_code, file_path, hue="label"): """ 绘制功率分仓方差 :param data: 输入数据时序集 :param power_bin_data: 功率分仓数据 :param turbine_code: 机组编码 :param file_path: 图像路径 :return: """ import seaborn as sns import matplotlib.pyplot as plt plt.figure() #? hue="label": 标记异常数据与否 #! 参见wind_base_tool文件power_binning函数 sns.scatterplot(data=data, x=wind_speed_label, y=power_label, hue=hue, legend=False, size=5) plt.plot(power_bin_data['speed_mean'], power_bin_data['power_mean'], c="blue", label="power_curve") #? 使用errorbar绘制功率曲线的方差 # fmt:定义数据折线和数据点的样式。 # ecolor:定义误差棒的颜色。 # elinewidth:定义误差棒线的宽度。 # capsize:定义误差棒帽的大小(长度)。 # capthick:定义误差棒帽的宽度。 # alpha:设置透明度(范围:0-1)。 # marker:设置数据点的样式 # markersize(简写ms):定义数据点的大小。 # markeredgecolor(简写mec):定义数据点的边的颜色,可使用官方提供的缩写 # 字母代表的简单颜色,也可以使用RGB颜色和HTML十六进制#aaaaaa格式的颜色(具体可参考matplotlib.colors)。 # markeredgewidth( 简写mew ):定义数据点的边的宽度。 # markerfacecolor(简写 mfc):定义数据点的颜色。 # linestyle:设置折线的样式,设置成none可将折线隐藏。 # label:添加图例。 plt.errorbar(power_bin_data['speed_mean'], power_bin_data['power_mean'], xerr=power_bin_data['speed_std'], fmt='o', ecolor='orangered', color='b', elinewidth=2, capsize=4, markersize=3, mfc='orange', mec='k', mew=0.5) plt.legend() title = "功率分仓偏差分析" + " " + turbine_code plt.title(title) # plt.show() var_file_name = "{}_power_var.png".format(turbine_code) var_full_path = os.path.join(file_path, var_file_name) plt.savefig(var_full_path) plt.close() def scatter_curve(data, curve, title, file_path, hue="label"): """ 绘制散点图和曲线 :param data: 输入数据时序集 :param curve: 理论和实际功率曲线数据 :param title: 图像标题 :param file_path: 图像文件完整路径 :return: """ import seaborn as sns import matplotlib.pyplot as plt plt.figure() #? hue="label": 标记异常数据与否 # palette='vlag' 'deep'【默认】'rainbow' sns.scatterplot(data=data, x=wind_speed_label, y=power_label, hue=hue, palette='deep', legend=False) plt.plot(curve[wind_speed_label], curve[actual_power_label], c="blue", label="actual_curve") plt.plot(curve[wind_speed_label], curve[theory_power_label], c="black", label="theory_curve") #? 使用errorbar绘制功率曲线的方差 # ecolor='r', color='b', crimson deeppink lime #? color与mfc冲突,后者覆盖 plt.errorbar(curve[wind_speed_label], curve[actual_power_label], yerr=curve[std_power_label], fmt='o', ecolor='orangered', color='b', elinewidth=2, capsize=4, markersize=4, mfc='yellow', mec='green', mew=0.5) plt.legend() plt.title(title) # plt.show() plt.savefig(file_path) plt.close() def scatter_curve_x(data, curve, title, file_path, hue="label"): """ 绘制散点图和曲线 :param data: 输入数据时序集 :param curve: 理论和实际功率曲线数据 :param title: 图像标题 :param file_path: 图像文件完整路径 :return: """ import seaborn as sns import matplotlib.pyplot as plt plt.figure() #? hue="label": 标记异常数据与否 #TODO: 与scatter_curve不同的地方 #! "legend=False" 隐藏hue对应的legend显示 sns.scatterplot(data=data, x=wind_speed_label, y=power_label, hue=hue, size=hue, alpha=0.8, legend=False) # markers='^', plt.plot(curve[wind_speed_label], curve[actual_power_label], c="blue", label="actual_curve") plt.plot(curve[wind_speed_label], curve[theory_power_label], c="black", label="theory_curve") #? 使用errorbar绘制功率曲线的方差 plt.errorbar(curve[wind_speed_label], curve[actual_power_label], curve[std_power_label], fmt='o', ecolor='r', color='b', elinewidth=2, capsize=4) plt.legend() plt.title(title) # plt.show() plt.savefig(file_path) plt.close() def wind_speed_power_plot(data, turbine_code, file_path, air_density_tag=None): """ 绘制风速和功率的曲线 :param data: 输入数据时序集 :param turbine_code: 机组编码 :param file_path: 图像文件完整路径 :param air_density_tag: 空气密度标签 :return: """ import seaborn as sns import matplotlib.pyplot as plt xlabel = "风速/(m·s$^{-1}$)" ylabel = "功率/(kW)" title = "风速功率变化分析" + " " + turbine_code file_name = "{}_speed_power.png".format(turbine_code) full_path = os.path.join(file_path, file_name) plt.figure() #? hue="label": 标记异常数据与否 sns.relplot(data=data, x=wind_speed_label, y=power_label, kind="line", ci="sd", #, dashes=False, markers=True style=air_density_tag, hue=air_density_tag, size=air_density_tag) # plt.legend() plt.xlabel(xlabel) plt.ylabel(ylabel) plt.title(title) plt.tight_layout() # plt.show() plt.savefig(full_path) plt.close() def power_curve_pred_plot(wind_speed_list, actual_power_list, pred_power_list, turbine_code, file_path, bin_curve_df=None): """功率实际与预测数据对比展示 Args: wind_speed_list (list): 风速数据 actual_power_list (list): 实际功率数据 pred_power_list (list): 预测功率数据 turbine_code (str): 机组编码 file_path (str): 图像文件完整路径 bin_curve_df (DataFrame): IEC BIN分仓拟合曲线 """ import matplotlib.pyplot as plt plt.figure(figsize = (10, 6)) plt.scatter(wind_speed_list, actual_power_list, color="blue", label="Ground truth", s=0.1) plt.scatter(wind_speed_list, pred_power_list, color="red", label="Prediction", s=0.1) if bin_curve_df is not None: plt.plot(bin_curve_df[wind_speed_label], bin_curve_df[power_label], '-*', label='IEC BIN') plt.title("Power Curve model") plt.xlabel("Wind speed (m/s)") plt.ylabel("Output power") plt.legend() plt.tight_layout() # plt.show() file_name = "{}_dswe.png".format(turbine_code) plot_save(file_path, file_name) def power_curve_3d_series_plot(power_curve_df, turbine_code, file_path): """功率曲线3D展示:实际与预测数据对比展示 【多维度】 【三维功率曲线】 Args: power_curve_df (DataFrame): 功率曲线模型 数据集 turbine_code (str): 机组编码 file_path (str): 图像文件完整路径 """ #? 风速 + 风向 => 功率 三维功率曲线 power_curve_direction_3d_plot(power_curve_df, turbine_code, file_path) #? 风速 + 空气密度 => 功率 三维功率曲线 power_curve_airdensity_3d_plot(power_curve_df, turbine_code, file_path) #? 风速 + 机舱温度 => 功率 三维功率曲线 power_curve_nacelletemp_3d_plot(power_curve_df, turbine_code, file_path) def power_curve_direction_3d_plot(dataset, turbine_code, file_path): """功率曲线3D展示:实际与预测数据对比展示 【风向】 【三维功率曲线】 #? 参考dist_tool.py文件的pcw_direction_3d_plot函数 #? 差异:pcw_direction_3d_plot函数是基于数据的直接展示, #? power_curve_direction_3d_plot函数重点对比实际风机出力 #? 和功率曲线建模的差异对比 Args: dataset (DataFrame): 功率曲线模型 数据集 wind_speed_list (list): 风速数据 wind_direction_list (list): 风向数据 actual_power_list (list): 实际功率数据 pred_power_list (list): 预测功率数据 turbine_code (str): 机组编码 file_path (str): 图像文件完整路径 bin_curve_df (DataFrame): IEC BIN分仓拟合曲线 """ vars_list = [wind_speed_label, wind_direction_label, power_label, power_pred_label] xlabel = "风速/(m·s$^{-1}$)" ylabel = "风向/($°$)" zlabel = "功率/(kW)" title = "风速-风向-功率3D分析" file_name = "pc_direction_3d_{}.png".format(turbine_code) file_path = get_full_path(file_path, file_name) power_curve_vs_pred_3d_plot(dataset, vars_list, file_path, xlabel, ylabel, zlabel, title) def power_curve_airdensity_3d_plot(dataset, turbine_code, file_path): """功率曲线3D展示:实际与预测数据对比展示 【空气密度】 【三维功率曲线】 Args: dataset (DataFrame): 功率曲线模型 数据集 wind_speed_list (list): 风速数据 air_density_list (list): 空气密度数据 actual_power_list (list): 实际功率数据 pred_power_list (list): 预测功率数据 turbine_code (str): 机组编码 file_path (str): 图像文件完整路径 bin_curve_df (DataFrame): IEC BIN分仓拟合曲线 """ vars_list = [wind_speed_label, air_density_label, power_label, power_pred_label] xlabel = "风速/(m·s$^{-1}$)" ylabel = "空气密度/(Kg/m$^3$)" zlabel = "功率/(kW)" title = "风速-空气密度-功率3D分析" file_name = "pc_airsentiy_3d_{}.png".format(turbine_code) file_path = get_full_path(file_path, file_name) power_curve_vs_pred_3d_plot(dataset, vars_list, file_path, xlabel, ylabel, zlabel, title) def power_curve_nacelletemp_3d_plot(dataset, turbine_code, file_path): """功率曲线3D展示:实际与预测数据对比展示 【机舱温度】 【三维功率曲线】 Args: dataset (DataFrame): 功率曲线模型 数据集 wind_speed_list (list): 风速数据 nacelle_temp_list (list): 机舱温度数据 actual_power_list (list): 实际功率数据 pred_power_list (list): 预测功率数据 turbine_code (str): 机组编码 file_path (str): 图像文件完整路径 bin_curve_df (DataFrame): IEC BIN分仓拟合曲线 """ vars_list = [wind_speed_label, nacelle_temp_label, power_label, power_pred_label] xlabel = "风速/(m·s$^{-1}$)" ylabel = "机舱温度/($°$)" zlabel = "功率/(kW)" title = "风速-机舱温度-功率3D分析" file_name = "pc_nacelletemp_3d_{}.png".format(turbine_code) file_path = get_full_path(file_path, file_name) power_curve_vs_pred_3d_plot(dataset, vars_list, file_path, xlabel, ylabel, zlabel, title) def power_curve_vs_pred_3d_plot(dataset, vars_list, file_path, xlabel=None, ylabel=None, zlabel=None, title=None): """ 绘制功率曲线三维展示 图像 【真实功率与预测值对比】 :param dataset: 时序数据集 :param vars_list: x、y、z变量名称列表 :param file_path: 图像文件完整路径 :param xlabel: x坐标名称 :param ylabel: y坐标名称 :param zlabel: z坐标名称 :param title: 图像标题 :return: """ from matplotlib import cm import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D # *** ---------- 3D plot initializing ---------- #? azim是绕z轴旋转的角度 #? elev是绕y轴旋转的角度 #? 默认值:azim=-60, elev=30 figsize=(12, 8) fig = plt.figure(figsize=figsize) #! 存在两种方式绘制3D图形 ax = Axes3D(fig, azim=120, elev=10) # azim=-60 # ax = fig.gca(projection='3d') # ax.view_init(elev=10,azim=120) # *** ---------- 3D Power Curve with power value of ground truth ---------- #? vars_list[0] + vars_list[1] => vars_list[2] ax.scatter(dataset[vars_list[0]], dataset[vars_list[1]], dataset[vars_list[2]], cmap=cm.coolwarm, alpha=0.5, marker='o') # *** ---------- 3D Power Curve with power value of prediction ---------- #? vars_list[0] + vars_list[1] => vars_list[3] ax.scatter(dataset[vars_list[0]], dataset[vars_list[1]], dataset[vars_list[3]], cmap=cm.coolwarm, alpha=0.5, marker='+') # *** ---------- 3D plot setting ---------- ax.set_title(title) ax.set_xlabel(xlabel) ax.set_ylabel(ylabel) ax.set_zlabel(zlabel) # ax.legend() # loc="upper right" fig.add_axes(ax) # fig.legend(loc="upper right") plt.title(title) plt.tight_layout() # plt.show() plt.savefig(file_path) plt.close() # -------------------------------------------------------------------- # *** # Power Curve Modeling # *** # -------------------------------------------------------------------- def power_curve_analysis_openoa(dataset, turbine_code, file_path): """ 基于openoa包功率曲线拟合方法建模分析【Power Curve Modeling】 三种方法建模:IEC、Spline、logistic五参数 :param dataset: 输入数据时序集 :param turbine_code: 机组编码 :param file_path: 图像文件完整路径 :return: """ import matplotlib.pyplot as plt # Fit the power curves #? 返回的是函数 iec_curve = power_curve.IEC(dataset[wind_speed_label], dataset[power_label], bin_width=0.1) l5p_curve = logistic_5_parametric(dataset[wind_speed_label], dataset[power_label]) spline_curve = power_curve.gam(dataset[wind_speed_label], dataset[power_label], n_splines = 20) # Plot the results x = np.linspace(0, 20, 100) plt.figure(figsize = (10, 6)) plt.scatter(dataset[wind_speed_label], dataset[power_label], alpha=0.5, s=1, c='gray') plt.plot(x, iec_curve(x), color="red", label='IEC', linewidth=3) plt.plot(x, spline_curve(x), color="C1", label='Spline', linewidth=3) plt.plot(x, l5p_curve(x), color="C2", label='L5P', linewidth=3) plt.xlabel('Wind speed (m/s)') plt.ylabel('Power (kW)') plt.legend() # 绘图和保存文件 # plt.show() curve_file_name = "{}_openoa.png".format(turbine_code) curve_full_path = os.path.join(file_path, curve_file_name) plt.savefig(curve_full_path) plt.close()
--- title: 'Summary' body_classes: modular published: false columns: 2 --- ### Final Thoughts In many ways, "building" a course is no different than building a house - one does not simply put a bunch of pieces of wood together and call it a house. Designing an effective course that focuses on student learning is no different - one cannot simply "dump" content onto a page and expect students to learn. Much like building a house, course design requires intentional thought and sequential, logical planning. First, one must consider ***who*** we are "building" the course for; next, we can begin planning ***how*** we will go about delivering a positive, intuitive learning experience (the Blueprint). As our planning evolves, we can begin to add details that will engage learners and promote learning - the Blueprint will provide a contextual overview of how each component fits together. Once we have a sense of how all the pieces work together, we can add our assessments with a sense of confidence that they align with the rest of the content in our course. While the course design process is intended to be flexible and fluid, it is also intended to be intentional and purposeful. Laying the groundwork (Blueprint) is a critical component to ensure we have a strong foundation that cultivates an environment of learning.
'use client'; import {Select, SelectProps} from "antd"; import {CampaignStatus} from "@/app/core/model/campaign"; import {sessionMatchAnyRoles} from "@/app/api/auth/[...nextauth]/route"; import {Role} from "@/app/core/role"; import {useSession} from "next-auth/react"; import {forwardRef} from "react"; const translate: any = { [CampaignStatus.INITIAL]: 'Mới tạo', [CampaignStatus.OPENING]: 'Đang quyên góp', [CampaignStatus.COMPLETED]: 'Kết thúc quyên góp', [CampaignStatus.CLOSED]: 'Đóng quyên góp', }; const InnerCampaignStatusSelector = ({placeholder, ...props}: SelectProps, ref: any) => { const {data: session} = useSession(); return ( <Select placeholder={placeholder ?? 'Chọn trạng thái'} ref={ref} options={ Object.entries(CampaignStatus) .filter(([k]) => sessionMatchAnyRoles(session, [Role.ROLE_ADMIN]) === true || k !== CampaignStatus.INITIAL ) .map(([k, v]) => ({ label: translate[k] ?? k, value: v, })) } {...props} /> ) }; const CampaignStatusSelector = forwardRef(InnerCampaignStatusSelector); export default CampaignStatusSelector;
import React, { useMemo, useState } from 'react'; import { createTheme, ThemeProvider } from '@mui/material'; import { ColorModeContext } from '../constant/context'; import Layout from './Layout'; function App() { const [darkMode, setDarkMode] = useState(true); const colorMode = useMemo( () => ({ toggleColorMode: () => { setDarkMode((prevMode) => (!prevMode)); }, }), [], ); const theme = useMemo( () => createTheme({ palette: { mode: darkMode ? 'dark' : 'light', }, }), [darkMode], ); return ( <ColorModeContext.Provider value={colorMode}> <ThemeProvider theme={theme}> <Layout /> </ThemeProvider> </ColorModeContext.Provider> ); } export default App;
import { ChangeDetectionStrategy, ChangeDetectorRef, Component, OnInit } from '@angular/core'; import { PromotionDataService } from '@core/services/promotion-data.service'; import { MessageService } from 'primeng/api'; import { Promotion } from '@core/models/promotions/promotions.model'; import { ConfirmService } from '@core/services/confirm.service'; import { EMPTY, Observable, pluck } from 'rxjs'; import { catchError, filter, map, mergeMap } from 'rxjs/operators'; import { TableItem } from '@core/models/table.interface'; import { UntilDestroy, untilDestroyed } from '@ngneat/until-destroy'; import { LangPipe } from '@shared/pipe/lang.pipe'; import { DatePipe } from '@angular/common'; @UntilDestroy() @Component({ selector: 'app-promotion-list', templateUrl: './promotion-list.component.html', styleUrls: ['./promotion-list.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, providers: [LangPipe, DatePipe] }) export class PromotionListComponent implements OnInit { currentPage = 1; rows = 10; promotions$: Observable<Promotion[]>; cols: TableItem[]; constructor( private _ps: PromotionDataService, private _cs: ConfirmService, private _ms: MessageService, private _cd: ChangeDetectorRef, private _datePipe: DatePipe, private _langPipe: LangPipe ) { } ngOnInit(): void { this.promotions$ = this._queryPromotionList(this.currentPage); this.cols = [ { field: 'index', header: '#', sortable: true, style: { width: '100px' } }, { field: 'image', header: 'Image' }, { field: 'shortName', header: 'Name', sortable: true }, { field: 'shortDescription', header: 'Description', sortable: true }, { field: 'started', header: 'Start Date', sortable: true }, { field: 'ended', header: 'End Date', sortable: true }, { field: 'options', header: 'labels.options', style: { width: '100px' } } ]; } onPageChange(page: number): void { this.currentPage = page + 1; this.promotions$ = this._queryPromotionList(page + 1); } onDelete(item: Promotion): void { this._cs.delete().pipe( filter(result => result), mergeMap(() => this._ps.remove(item.id)), catchError(e => { this._ms.add({ severity: 'error', detail: e.result }); return EMPTY; }), untilDestroyed(this) ) .subscribe(res => { this.promotions$ = this._queryPromotionList(this.currentPage); this._ms.add({ severity: 'success', detail: `Акція "${item.name}" видалена успішно!` }); this._cd.detectChanges(); }); } private _queryPromotionList(page: number): Observable<Promotion[]> { return this._ps.getData({ page, limit: this.rows }).pipe( pluck('result'), map(promotions => promotions.map((promotion, i) => ({ ...promotion, index: i + 1, started: this._datePipe.transform(promotion.startedAt), ended: promotion.endedAt ? this._datePipe.transform(promotion.endedAt) : '-', shortName: this._langPipe.transform(promotion.name), shortDescription: this._langPipe.transform(promotion.description) })))); } }
<template> <div class="list"> <Breadcrumb></Breadcrumb> <!-- 列表展示 --> <div class="header"> <el-form :inline="true" :model="formInline" class="demo-form-inline" strip="true"> <el-form-item label="审批人"> <el-input v-model="formInline.user" placeholder="审批人"></el-input> </el-form-item> <el-form-item label="活动区域"> <el-select v-model="formInline.region" placeholder="活动区域"> <el-option label="区域一" value="shanghai"></el-option> <el-option label="区域二" value="beijing"></el-option> </el-select> </el-form-item> <el-form-item> <el-button type="primary">查询</el-button> </el-form-item> </el-form> </div> <!-- 订单列表按钮 --> <div class="btn"> <el-button type="primary" size="mini" @click="orderCollect">订单汇总</el-button> <download-excel class="export-excel-wrapper" :data="DetailsForm" :fields="json_fields" :header="title" :name="title"> <!-- 上面可以自定义自己的样式,还可以引用其他组件button --> <el-button type="success" size="mini" class="daochu" @click="download">导出</el-button> </download-excel> </div> <!-- 表格 --> <div class="table"> <el-table :data="tableData" style="width: 100%" @selection-change="selectChange"> <el-table-column type="selection" width="55" :selectable="selectFun"> </el-table-column> <el-table-column prop="code" label="订单编号" width="200"> <template slot-scope="scope"> <span @click="goxiangqing(scope.row)" style="color: blue; cursor: pointer;">{{ scope.row.code }}</span> </template> </el-table-column> <el-table-column prop="ordername" label="下单人" width="100"> </el-table-column> <el-table-column prop="company" label="所属单位" width="180"> </el-table-column> <el-table-column prop="phone" label="联系电话" width="180"> </el-table-column> <el-table-column prop="yudingTime" label="预定时间" width="180"> <template slot-scope="scope"> {{ dayjs(scope.row.yudingTime).format('YYYY-MM-DD') }} </template> </el-table-column> <el-table-column prop="price" label="订单价格" width="100"> </el-table-column> <el-table-column label="汇总状态"> <template slot-scope="scope"> <span v-show="scope.row.huizongStatus === 2">已汇总</span> <span v-show="scope.row.huizongStatus === 1">未汇总</span> </template> </el-table-column> </el-table> <!-- 分页 --> <Pagination :pageSize="pageSize" :total="total" @getpagination="getpagination"></Pagination> </div> <!-- 抽屉 显示订单详情 --> <div class="drawer"> <el-drawer title="订单详情" :visible.sync="drawer" :direction="direction" size="87%"> <OrderDes></OrderDes> </el-drawer> </div> </div> </template> <script> import dayjs from 'dayjs'; import Pagination from '@/components/Pagination' import OrderDes from './orderDes.vue' export default { data() { return { formInline: { user: '', region: '' }, //配置表头字段文字 json_fields: { "订单编号": { field: "code", callback: value => { return '&nbsp;' + value } }, "下单人": "ordername", "所属单位": "company", "联系电话": { field: 'phone', callback: value => { return '&nbsp;' + value } }, "预定时间": "yudingTime", "订单价格": "price", "汇总状态": "huizongStatus" }, //需要导出的数据 DetailsForm: [], //导出的表格名称 title: '首客生鲜订单列表', //表数据 tableData: [], //页码 pageSize: 1, //页数 total: 100, //选中的id selectIds: [], //固定汇总后的页码 currentPage: 1, //抽屉的方向 和是否打开 drawer: false, direction: 'rtl', } }, created() { this.getOrderList(1) }, methods: { dayjs, download() { let arr = _.cloneDeep(this.tableData) console.log(arr); console.log(this.tableData); arr.forEach(ele => { ele.yudingTime = dayjs(ele.yudingTime).format('YYYY-MM-DD HH:mm:ss') ele.huizongStatus = ele.huizongStatus == 2 ? '已汇总' : '未汇总' }) this.DetailsForm = arr }, //点击进入订单详情 goxiangqing(val) { this.drawer = !this.drawer }, //禁用已汇总的选项框 selectFun(row, index) { if (row.huizongStatus === 1) { return true } else { return false } }, //选择table selectChange(row) { console.log(row); let arr = [] row.forEach(element => { arr.push(element.id) }); console.log(arr); this.selectIds = arr }, //订单汇总 orderCollect() { this.$confirm('是否需要提交所选内容', '提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }).then(() => { let ids = this.selectIds.join(',') this.changeStatus(ids) // this.$message({ // type: 'success', // message: '提交成功!' // }); }).catch(() => { this.$message({ type: 'info', message: '放弃提交汇总' }); }); }, //订单汇总 async changeStatus(ids) { let res = await this.$api.changeStatus({ ids }) if (res.data.status === 200) { console.log(this.currentPage); this.getOrderList(this.currentPage) this.$message({ type: 'success', message: '提交成功!' }); this.getOrderList(1) } }, //获取订单列表的数据 async getOrderList(page) { let res = await this.$api.orderList({ page }) console.log(res.data); if (res.data.status === 200) { this.tableData = res.data.data this.pageSize = res.data.pageSize this.total = res.data.total } }, //分页 getpagination(page) { this.currentPage = page if (this.searchStatus) { //未点击查询按钮 this.tableline = this.listTotal.slice((page - 1) * 8, page * 8) return; } this.getOrderList(page) }, }, components: { Pagination, OrderDes } }; </script> <style lang='less' scoped> .list { margin: 10px; background-color: #fff; padding: 20px; .header { margin-top: 20px; } .btn { margin-bottom: 10px; border: 1px solid #eee; padding: 10px; border-radius: 5px; display: flex; .daochu { margin-left: 10px; } } } </style>
#include "Harl.hpp" #include <iostream> Harl::Harl() { } void Harl::debug(void) { std::cout << "I love having extra seaweed for my "; std::cout << "7XL-double-tomato-triple-pickle-specialketchup "; std::cout << "burger. I really do!"; std::cout << std::endl; } void Harl::info(void) { std::cout << "I cannot believe adding extra seaweed costs more money. "; std::cout << "You didn’t put enough seaweed in my burger! "; std::cout << "If you did, I wouldn’t be asking for more!"; std::cout << std::endl; } void Harl::warning(void) { std::cout << "I think I deserve to have some extra seaweed for free. "; std::cout << "I’ve been coming for years "; std::cout << "whereas you started working here since last month."; std::cout << std::endl; } void Harl::error(void) { std::cout << "This is unacceptable! "; std::cout << "I want to speak to the manager now."; std::cout << std::endl; } void Harl::complain(std::string level) { t_function complainFunctions[4] = { {"DEBUG", &Harl::debug}, {"INFO", &Harl::info}, {"WARNING", &Harl::warning}, {"ERROR", &Harl::error} }; for (int i = 0; i < 4; i++) { t_function function = complainFunctions[i]; if (function.command == level) return (this->*function.function)(); } std::cout << "\"" << level << "\" is not an option for Harl"; std::cout << std::endl; } Harl::~Harl() { }
import { HiCheckCircle, HiClock, HiQuestionMarkCircle, HiX, } from "react-icons/hi"; import { BiMinus, BiPlus } from "react-icons/bi"; import { Link } from "react-router-dom"; import { useAuthState } from "react-firebase-hooks/auth"; import { getAuth } from "firebase/auth"; import app from "../../firebase/firebase.config"; import { useGetData } from "../../customHooks/useGetData/useGetData"; import { useEffect, useState } from "react"; import Loader from "../../components/loader/Loader"; import { useCurrency } from "../../context/CurrencyContext"; const auth = getAuth(app); const Cart = () => { const [totalPrice, setTotalPrice] = useState(0); const [subtotal, setSubTotal] = useState(0); const { selectedCurrency } = useCurrency(); const [user] = useAuthState(auth); const { data, isLoading, refetch } = useGetData( `/cart/item?email=${user?.email}` ); const cartIncrementCount = (e) => { const uri = `https://test-originale.onrender.com/cart/increase/${e}`; fetch(uri, { method: "PUT" }) .then((res) => res.json()) .then((data) => refetch()); }; const cartDecrementCount = (e) => { const uri = `https://test-originale.onrender.com/cart/decrease/${e}`; fetch(uri, { method: "PUT" }) .then((res) => res.json()) .then((data) => refetch()); }; const calculateTotalPrice = () => { let total = 0; if (data && Array.isArray(data)) { total = data.reduce((accumulator, item) => { const price = parseFloat(item.price); const quantity = parseInt(item.quantity); if (!isNaN(price) && !isNaN(quantity)) { const subtotal = price * quantity; return accumulator + subtotal; } return accumulator; }, 0); } setSubTotal(total); const taxPercentage = 15; // Update tax to 15% const shippingFee = selectedCurrency === "BDT" ? 80 : 10; const taxAmount = (total * taxPercentage) / 100; total += taxAmount + shippingFee; setTotalPrice(total); }; useEffect(() => { calculateTotalPrice(); }, [data]); if (isLoading) { return <Loader />; } const removeProduct = (e) => { const uri = `https://test-originale.onrender.com/cart/delete/${e}`; fetch(uri, { method: "DELETE" }) .then((res) => res.json()) .then((data) => { refetch(); }); }; const countryRoute = selectedCurrency === "BDT" ? "bd" : "uae"; return ( <div> <div className="mx-auto max-w-2xl px-4 pt-16 pb-24 sm:px-6 lg:max-w-7xl lg:px-8"> <h1 className="text-3xl sm:text-4xl text-[#f3f3f3] courierNew text-[1.06rem] font-bold leading-[77.5%] tracking-[0.012rem] uppercase"> Shopping Cart </h1> <div className="mt-12 lg:grid lg:grid-cols-12 lg:items-start lg:gap-x-12 xl:gap-x-16"> <section aria-labelledby="cart-heading" className="lg:col-span-7"> <h2 id="cart-heading" className="sr-only"> Items in your shopping cart </h2> <ul role="list" className="divide-y divide-gray-200 border-t border-b border-gray-200" > {data?.map((product) => ( <li key={product?.id} className="flex py-6 sm:py-10"> <div className="flex-shrink-0"> <img src={product?.img} alt={product?.item?.productName} className="h-24 w-24 rounded-md object-cover object-center sm:h-48 sm:w-48" /> </div> <div className="ml-4 flex flex-1 flex-col justify-start sm:ml-6"> <div className="relative pr-9 sm:grid sm:grid-cols-2 sm:gap-x-6 sm:pr-0"> <div> <div className="flex justify-between"> <Link> <h3 className="text-[#f3f3f3] line-clamp-2 courierNew text-[1.06rem] font-bold leading-[77.5%] tracking-[0.012rem]"> {product?.item?.productName} </h3> </Link> </div> <div className="mt-[0.56rem] flex flex-col gap-[0.34rem]"> <div className="flex items-center gap-2 text-[#f3f3f3] courierNew text-[0.88rem] font-bold leading-[77.5%] tracking-[0.012rem]"> Color : <span style={{ backgroundColor: product.color, width: "20px", height: "20px", borderRadius: "50%", }} ></span> </div> {product.size ? ( <p className="text-[#f3f3f3] courierNew text-[0.88rem] font-bold leading-[77.5%] tracking-[0.012rem]"> Size: {product.size} </p> ) : null} </div> <p className="text-[#f3f3f3] courierNew text-[1.06rem] font-bold leading-[77.5%] tracking-[0.012rem] mt-3"> {product.price} {product.currency} </p> </div> <div className="mt-4 sm:mt-0 sm:pr-9 flex justify-center items-center"> <div className="flex items-center justify-center gap-[1.63rem] border-2 text-white border-[#f3f3f3] h-[2.25rem] py-[1.06rem] px-[0.88rem]"> <button onClick={() => cartDecrementCount(product?._id)} > <BiMinus size={20} /> </button> <span>{product?.quantity}</span> <button onClick={() => cartIncrementCount(product._id)} > <BiPlus size={20} /> </button> </div> <button onClick={() => removeProduct(product._id)} type="button" className="ml-2 inline-flex p-2 text-gray-400 hover:text-gray-500" > <span className="sr-only">Remove</span> <HiX className="h-5 w-5" aria-hidden="true" /> </button> </div> </div> <p className="mt-4 flex items-center space-x-2 text-sm text-gray-700"> {product.inStock ? ( <HiCheckCircle className="h-5 w-5 flex-shrink-0 text-green-500" aria-hidden="true" /> ) : ( <HiClock className="h-5 w-5 flex-shrink-0 text-gray-300" aria-hidden="true" /> )} <span className="text-[0.88rem] font-bold leading-[77.5%] tracking-[0.012rem] courierNew"> {product ? "In stock" : `Ships in `} </span> </p> </div> </li> ))} </ul> </section> {/* Order summary */} <section aria-labelledby="summary-heading" className="mt-16 rounded-lg bg-[#2c332e] px-4 py-6 sm:p-6 lg:col-span-5 lg:mt-0 lg:p-8 shadow-xl" > <h2 id="summary-heading" className="text-[#f3f3f3] euroWide text-[1.06rem] font-bold leading-[122.5%] tracking-[0.0089rem]" > Order summary </h2> <dl className="mt-6 space-y-4"> <div className="flex items-center justify-between"> <dt className="text-[#f3f3f3] courierNew text-[1.06rem] font-bold leading-[77.5%] tracking-[0.012rem]"> Subtotal </dt> <dd className="text-[#f3f3f3] courierNew text-[1.06rem] font-bold leading-[77.5%] tracking-[0.012rem]"> {selectedCurrency === "BDT" ? `BDT ` : `AED `} {subtotal.toFixed(2)} </dd> </div> <div className="flex items-center justify-between border-t border-gray-200 pt-4"> <dt className="flex items-center text-[#f3f3f3] courierNew text-[1.06rem] font-bold leading-[77.5%] tracking-[0.012rem]"> <span>Shipping estimate</span> <a href="#" className="ml-2 flex-shrink-0 text-gray-400 hover:text-gray-500" > <span className="sr-only"> Learn more about how shipping is calculated </span> <HiQuestionMarkCircle className="h-5 w-5" aria-hidden="true" /> </a> </dt> <dd className="text-[#f3f3f3] courierNew text-[1.06rem] font-bold leading-[77.5%] tracking-[0.012rem]"> {selectedCurrency === "BDT" ? `BDT 80` : `AED 10`} </dd> </div> <div className="flex items-center justify-between border-t border-gray-200 pt-4"> <dt className="flex text-[#f3f3f3] courierNew text-[1.06rem] font-bold leading-[77.5%] tracking-[0.012rem]"> <span>Tax estimate</span> <a href="#" className="ml-2 flex-shrink-0 text-gray-400 hover:text-gray-500" > <span className="sr-only"> Learn more about how tax is calculated </span> <HiQuestionMarkCircle className="h-5 w-5" aria-hidden="true" /> </a> </dt> <dd className="text-[#f3f3f3] courierNew text-[1.06rem] font-bold leading-[77.5%] tracking-[0.012rem]"> 15%{" "} </dd> </div> <div className="flex items-center justify-between border-t border-gray-200 pt-4"> <dt className="text-[#f3f3f3] euroWide text-[1.06rem] font-bold leading-[122.5%] tracking-[0.0089rem]"> Order total </dt> <dd className="text-[#f3f3f3] euroWide text-[.88rem] font-bold leading-[122.5%] tracking-[0.0089rem]"> {selectedCurrency === "BDT" ? "BDT " : "AED "} {totalPrice.toFixed(2)} </dd> </div> </dl> <div className="mt-6"> <Link to={`/${countryRoute}/checkout`} className="w-full block text-center rounded-md border border-transparent bg-[#38453e] py-4 px-4 text-base text-white shadow-sm focus:outline-none text-[1.24rem] font-bold leading-[77.5%] tracking-[0.009rem] uppercase courierNew" > Checkout </Link> </div> </section> </div> </div> </div> ); }; export default Cart;
--- title: Execute redimensionamento simples com Aspose.PSD para Java linktitle: Execute o redimensionamento simples second_title: API Java Aspose.PSD description: Aprenda a redimensionar imagens programaticamente com Aspose.PSD para Java. Siga nosso guia passo a passo para manipulação eficiente de imagens. type: docs weight: 11 url: /pt/java/basic-image-operations/simple-resizing/ --- ## Introdução No tutorial de hoje, nos aprofundaremos no processo de redimensionamento simples de imagens usando Aspose.PSD para Java, uma biblioteca poderosa que facilita a manipulação eficiente de imagens. Se você é um desenvolvedor Java que busca uma maneira perfeita de redimensionar imagens programaticamente, você está no lugar certo. ## Pré-requisitos Antes de embarcarmos em nossa jornada de redimensionamento de imagens com Aspose.PSD, certifique-se de ter os seguintes pré-requisitos em vigor: 1. Java Development Kit (JDK): Certifique-se de ter o Java instalado em seu sistema. Você pode baixar a versão mais recente no site[Site Java](https://www.oracle.com/java/). 2. Aspose.PSD para Java: Baixe e instale a biblioteca Aspose.PSD. Você pode encontrar os pacotes necessários no[Página de download do Aspose.PSD para Java](https://releases.aspose.com/psd/java/). Agora que classificamos nossos pré-requisitos, vamos mergulhar no núcleo do nosso tutorial. ## Importar pacotes Comece importando os pacotes necessários para iniciar o processo de redimensionamento de imagens. Inclua as seguintes linhas de código no início do seu arquivo Java: ```java import com.aspose.psd.Image; import com.aspose.psd.imageoptions.JpegOptions; ``` Esses pacotes permitirão que você trabalhe com Aspose.PSD e lide com opções de imagem JPEG. ## Etapa 1: defina seu diretório de documentos Comece definindo o diretório onde seu arquivo PSD está localizado. Substitua “Seu diretório de documentos” pelo caminho real do seu arquivo PSD. ```java String dataDir = "Your Document Directory"; ``` ## Etapa 2: especificar caminhos de origem e destino Agora, defina os caminhos para o seu arquivo PSD de origem e o destino onde a imagem redimensionada será salva. ```java String sourceFile = dataDir + "sample.psd"; String destName = dataDir + "SimpleResizing_out.jpg"; ``` ## Etapa 3: carregar a imagem Carregue a imagem existente em uma instância da classe RasterImage usando o seguinte código: ```java Image image = Image.load(sourceFile); ``` ## Etapa 4: redimensionar a imagem Redimensione a imagem para as dimensões desejadas. Neste exemplo, estamos redimensionando para 300x300 pixels. ```java image.resize(300, 300); ``` ## Etapa 5: salve a imagem redimensionada Salve a imagem redimensionada usando o caminho de destino especificado e JpegOptions. ```java image.save(destName, new JpegOptions()); ``` Parabéns! Você redimensionou uma imagem com sucesso usando Aspose.PSD para Java. Sinta-se à vontade para experimentar diferentes dimensões para atender às suas necessidades. ## Conclusão Neste tutorial, exploramos o processo simples de redimensionamento simples de imagens com Aspose.PSD para Java. Seguindo o guia passo a passo, você pode integrar facilmente essa funcionalidade em seus aplicativos Java. ## Perguntas frequentes ### Q1: Posso redimensionar imagens para dimensões específicas usando Aspose.PSD para Java? A1: Com certeza! O tutorial fornecido demonstra como redimensionar imagens para as dimensões desejadas. ### Q2: O Aspose.PSD para Java é compatível com diferentes formatos de imagem? A2: Sim, Aspose.PSD suporta vários formatos de imagem, proporcionando versatilidade em suas tarefas de manipulação de imagens. ### Q3: Onde posso encontrar documentação adicional para Aspose.PSD para Java? A3: Você pode consultar o[Documentação Aspose.PSD para Java](https://reference.aspose.com/psd/java/) para obter informações detalhadas. ### Q4: Posso experimentar o Aspose.PSD para Java antes de comprar? A4: Certamente! Utilize o[versão de teste gratuita](https://releases.aspose.com/) para explorar os recursos da biblioteca. ### Q5: Como posso obter suporte para Aspose.PSD para Java? A5: Visite o[Fórum Aspose.PSD](https://forum.aspose.com/c/psd/34) para assistência e apoio comunitário.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <link rel="stylesheet" href="style.css"> </head> <body> <h1>CSS Selectors</h1> <h2>Inline style</h2> <strong>HTML:</strong> <pre> style="background-color: cadetblue; width: 200px; height: 75px;" </pre> <strong>CSS:</strong> <pre>Nothing</pre> <strong>Example:</strong> <div style="background-color: cadetblue; width: 200px; height: 75px;"></div> <hr> <h2>ID selector</h2> <strong>HTML:</strong> <pre> id="unique" </pre> <strong>CSS:</strong> <pre> #unique{ background-color:burlywood; width: 300px; height: 100px; } </pre> <strong>Example:</strong> <div id="unique"></div> <hr> <h2>Class selector</h2> <strong>HTML:</strong> <pre> class="classOfElements" </pre> <strong>CSS:</strong> <pre> .classOfElements{ background-color: rgb(172, 172, 74); width: 350px; height: 60px; margin-top: 2px; } </pre> <strong>Example:</strong> <div class="classOfElements"></div> <div class="classOfElements"></div> <div class="classOfElements"></div> <div class="classOfElements"></div> <div class="classOfElements"></div> <hr> <h2>Tag selector</h2> <strong>HTML:</strong> <pre> [tag] </pre> <strong>CSS:</strong> <pre> a{ color: chocolate; text-decoration: none; } </pre> <strong>Example:</strong> <a href="#">Link 1</a> <a href="#">Link 2</a> <a href="#">Link 3</a> <a href="#">Link 4</a> <a href="#">Link 5</a> <hr> <h2>Universal selector</h2> <strong>HTML:</strong> <pre> Nothing </pre> <strong>CSS:</strong> <pre> *{ border: 1px solid red; } </pre> <strong>Example:</strong> </body> </html>
import React, { useState } from 'react'; import { Input, Button, Form, message } from 'antd'; import { useNavigate } from 'react-router-dom'; // Importa useNavigate desde react-router-dom import users from './usuarios.json'; import imagenIcono from './Disneyplus.png'; import Derechos from '../Home/Derechos' import './style.css'; const Login = () => { const [formData, setFormData] = useState({ correo: '', clave: '', }); const [error, setError] = useState(''); const navigate = useNavigate(); // Utiliza useNavigate en lugar de useHistory const handleInputChange = (e) => { const { name, value } = e.target; setFormData({ ...formData, [name]: value, }); }; const handleSubmit = async () => { try { const user = users.find((u) => u.correo === formData.correo && u.clave === formData.clave); if (user) { // Autenticación exitosa message.success('Inicio de sesión exitoso'); setError(''); navigate('/header'); // Utiliza navigate en lugar de history.push } else { setError('Correo o clave incorrectos'); message.error('Correo o clave incorrectos'); } } catch (error) { console.error('Error al obtener datos de usuarios', error); setError('Error al obtener datos de usuarios'); message.error('Error al obtener datos de usuarios'); } }; return ( <div className="login-container"> <div className="login-content"> <div className="card"> <div className="form-container"> <div className="background-image"> <img src={imagenIcono} alt="Disneyplus" /> </div> <h2>Iniciar Sesión</h2> <Form onFinish={handleSubmit}> <div className="form-item-container"> <label className="correo-label">Correo</label> <Form.Item name="correo" rules={[{ required: true, message: 'Este campo es obligatorio' }]}> <Input style={{ width: '200%' }} type="email" name="correo" value={formData.correo} onChange={handleInputChange} className="input-field" /> </Form.Item> </div> <div className="form-item-container"> <label className="clave-label">Contraseña</label> <Form.Item name="clave" rules={[{ required: true, message: 'Este campo es obligatorio' }]}> <Input.Password style={{ width: '182%' }} name="clave" value={formData.clave} onChange={handleInputChange} className="input-field" /> </Form.Item> </div> <Form.Item> <Button type="primary" htmlType="submit" className='botonIngresar'> Ingresar </Button> </Form.Item> </Form> {error && <p className="error-message">{error}</p>} </div> </div> <Derechos /> </div> </div> ); }; export default Login;
import {TextField } from "@mui/material"; import { StyledRegister } from "./styles"; const FormRegister = ({ formik }) => { return ( <StyledRegister> <TextField id="username" type="text" label="Username" fullWidth margin="dense" value={formik.values.username} onBlur={formik.handleBlur} onChange={formik.handleChange} error={!!formik.touched.username && !!formik.errors.username} helperText={formik.touched.username && formik.errors.username} /> <TextField id="email" type="text" label="email" fullWidth margin="dense" value={formik.values.email} onBlur={formik.handleBlur} onChange={formik.handleChange} error={!!formik.touched.email && !!formik.errors.email} helperText={formik.touched.email && formik.errors.email} /> <TextField id="password" type="text" label="password" fullWidth margin="dense" value={formik.values.password} onBlur={formik.handleBlur} onChange={formik.handleChange} error={!!formik.touched.password && !!formik.errors.password} helperText={formik.touched.password && formik.errors.password} /> </StyledRegister> ); } export default FormRegister;
--- layout: post title: RaiseActiveDirectoryFunctionalLevel.ps1 --- - [Description](#description) - [Script](#script) - [Download](#download) - [Report Issues](#report-issues) --- ### Description **_@GitHub Copilot_** - Welcome @BanterBoy, I'm your Copilot and I'm here to help you get things done faster. I can identify issues, explain and even improve code. You can ask generic questions, but what I'm really good at is helping you with your code. For example: Generate unit tests for my code Explain the selected code Propose a fix for the bugs in my code If you want to learn more about my capabilities and limitations, check out the Copilot documentation. I'm powered by AI, so surprises and mistakes are possible. Make sure to verify any generated code or suggestions, and share feedback so that we can learn and improve. **_@BanterBoy:_** - Explain what the script does and why it is useful. **_@GitHub Copilot_** - --- #### Script ```powershell # This script will raise the Active Directory Functional Level. # The functionality level should already be set to Windows 2008 R2 during the DCPromo process. $RaiseTo = "windows2008R2Forest" Import-Module ActiveDirectory $ForestInfo = Get-ADForest $ForestName = $ForestInfo.Name $RaiseFrom = $ForestInfo.ForestMode If ($RaiseFrom -ne $RaiseTo) { Write-Host -ForegroundColor green "Raising the $ForestName forest from $RaiseFrom to $RaiseTo mode..." # Use either one of the following lines: Set-ADForestMode -ForestMode $RaiseTo -confirm:$false #Set-ADForestMode -Identity $ForestName -ForestMode $RaiseTo -confirm:$false } Else { Write-Host -ForegroundColor yellow "The $ForestName forest is already set to $RaiseFrom functionality level." } ``` <span style="font-size:11px;"><a href="#"><i class="fas fa-caret-up" aria-hidden="true" style="color: white; margin-right:5px;"></i>Back to Top</a></span> --- #### Download Please feel free to copy parts of the script or if you would like to download the entire script, simple click the download button. You can download the complete repository in a zip file by clicking the Download link in the menu bar on the left hand side of the page. <button class="btn" type="submit" onclick="window.open('/PowerShell/scripts/activeDirectory/RaiseActiveDirectoryFunctionalLevel.ps1')"> <i class="fa fa-cloud-download-alt"> </i> Download </button> --- #### Report Issues You can report an issue or contribute to this site on <a href="https://github.com/BanterBoy/scripts-blog/issues">GitHub</a>. Simply click the button below and add any relevant notes. I will attempt to respond to all issues as soon as possible. <!-- Place this tag where you want the button to render. --> <a class="github-button" href="https://github.com/BanterBoy/scripts-blog/issues/new?title=RaiseActiveDirectoryFunctionalLevel.ps1&body=There is a problem with this function. Please find details below." data-show-count="true" aria-label="Issue BanterBoy/scripts-blog on GitHub">Issue</a> --- <span style="font-size:11px;"><a href="#"><i class="fas fa-caret-up" aria-hidden="true" style="color: white; margin-right:5px;"></i>Back to Top</a></span> <a href="/menu/_pages/scripts.html"> <button class="btn"> <i class='fas fa-reply'> </i> Back to Scripts </button> </a> [1]: http://ecotrust-canada.github.io/markdown-toc [2]: https://github.com/googlearchive/code-prettify
<template> <div id="app"> <nav id="nav" class="navbar navbar-expand-lg bg-darkness sticky-top transition" :class="{'py-0':isPadding}"> <div class="container"> <router-link to="/" class="navbar-brand text-primary"> <h1 class="h2 text-white d-flex align-items-center mb-0" @click="collapseHide"> <span class="material-icons-outlined material-icons mr-2 h1"> rice_bowl </span> <span>炙燒食堂</span> </h1> </router-link> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation" > <span class="h2 text-white material-icons material-icons-outlined"> menu </span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="custom__nav navbar-nav ml-auto"> <li class="nav-item custom__nav--hover" :class="{'active':navIndex === '0'}" @click="collapseHide('0')"> <router-link to="/products" class="nav-link text-white d-none d-lg-block">我們的餐點</router-link> <router-link to="/products" class="nav-link text-white border-bottom d-lg-none">我們的餐點</router-link> </li> <li class="nav-item custom__nav--hover" :class="{'active':navIndex === '1'}" @click="collapseHide('1')"> <router-link to="/about" class="nav-link text-white d-none d-lg-block">關於我們</router-link> <router-link to="/about" class="nav-link text-white border-bottom d-lg-none">關於我們</router-link> </li> </ul> </div> </div> </nav> <top></top> <router-view/> <footer class="bg-primary py-2"> <div class="container"> <div class="row align-items-center"> <div class="col"> <div class="d-flex flex-column justify-content-center"> <a href="https://maps.google.com/maps?q=桃園市平鎮區民族路239號2樓" target="_blank" class="text-white text-nowrap text-decoration"> 324桃園市平鎮區民族路239號2樓 </a> <p class="mb-0 text-nowrap text-white">週一 ~ 週六 11:00~20:00</p> </div> </div> <div class="col"> <div class="d-flex justify-content-end align-items-center"> <a href="tel:0903017408" class="h2 text-decoration-none text-white mb-0 mr-2"> <i class="fas fa-phone-square-alt"></i> </a> <a href="#" class="h2 text-decoration-none text-white mb-0 mr-2" target="_blank"> <i class="fab fa-facebook-square"></i> </a> <a href="#" target="_blank" class="h2 text-decoration-none text-white mb-0 d-lg-none"> <i class="fab fa-line"></i> </a> <a href="#" target="_blank" class="h2 text-decoration-none text-white mb-0 d-none d-lg-block"> <i class="fab fa-line"></i> </a> </div> </div> <div class="col-12"> <p class="text-center text-secondary mb-0"> <span>炙燒食堂</span> <small class="d-block d-md-inline"> © Copright 2021 僅為作品無任何商業用途.</small> </p> </div> </div> </div> </footer> </div> </template> <script> import $ from 'jquery' import Top from '@/components/Top.vue' export default { components: { Top }, data () { return { navIndex: '', isPadding: false } }, methods: { collapseHide (index) { this.navIndex = index $('#navbarSupportedContent').collapse('hide') }, scrollToNav () { const vm = this const scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop if (scrollTop > 60) { vm.isPadding = true } else { vm.isPadding = false } } }, mounted () { window.addEventListener('scroll', this.scrollToNav) }, unmounted () { window.removeEventListener('scroll', this.scrollToNav) } } </script>
import Vue from 'vue'; import './filter'; import './directive'; import './component'; const App = {}; App.data = () => { return window.__INITIAL_STATE__ || {}; }; App.init = options => { if (EASY_ENV_IS_NODE) { console.log('server render /n'); return App.server(options); } console.log('client render /n'); return App.client(options); }; App.client = options => { Vue.prototype.$http = require('axios'); if (options.store) { options.store.replaceState(Object.assign({}, App.data(), options.store.state)); } else if (window.__INITIAL_STATE__) { options.data = Object.assign(window.__INITIAL_STATE__, options.data && options.data()); } const app = new Vue(options); app.$mount('#app'); }; App.server = options => { if (options.store && options.router) { console.log('处理预取'); return context => { options.router.push(context.state.url); const matchedComponents = options.router.getMatchedComponents(); console.log(matchedComponents, options.router); if (!matchedComponents) { return Promise.reject({ code: '404' }); } return Promise.all( matchedComponents.map(component => { console.log('遍历组件,当前:', component.name); if (component.preFetch) { console.log('存在服务端预取'); return component.preFetch(options.store); } return null; }) ).then(() => { context.state = Object.assign(options.store.state, context.state); return new Vue(options); }).catch((err) => { console.log(err); }); }; } console.log('没有预取'); return context => { const VueApp = Vue.extend(options); const app = new VueApp({ data: context.state }); return new Promise(resolve => { resolve(app); }); }; }; App.use = component => { Vue.use(component); }; App.component = (name, component) => { Vue.component(name, component); }; export default App;
from typing import Optional from sqlalchemy.orm.exc import NoResultFound from sqlalchemy.orm.session import Session from app.domain.user import User, UserRepository from app.usecase.user import UserCommandUseCaseUnitOfWork from .user_dto import userDTO class userRepositoryImpl(UserRepository): """UserRepositoryImpl implements CRUD operations related user entity using SQLAlchemy.""" def __init__(self, session: Session): self.session: Session = session def find_by_id(self, id: str) -> Optional[User]: try: user_dto = self.session.query(userDTO).filter_by(id=id).one() except NoResultFound: return None except: raise return user_dto.to_entity() def create(self, user: User): user_dto = userDTO.from_entity(user) try: self.session.add(user_dto) except: raise class UserCommandUseCaseUnitOfWorkImpl(UserCommandUseCaseUnitOfWork): def __init__( self, session: Session, user_repository: UserRepository, ): self.session: Session = session self.user_repository: UserRepository = user_repository def begin(self): self.session.begin() def commit(self): self.session.commit() def rollback(self): self.session.rollback()
var express = require('express'); var path = require('path'); var favicon = require('serve-favicon'); var logger = require('morgan'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); var request = require('request'); var routes = require('./routes/index'); var users = require('./routes/users'); var keys = require("./keys"); var app = express(); // view engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'jade'); // uncomment after placing your favicon in /public //app.use(favicon(path.join(__dirname, 'public', 'favicon.ico'))); app.use(logger('dev')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.use(cookieParser()); app.use(express.static(path.join(__dirname, 'public'))); app.use('/', routes); app.use('/users', users); app.get('/api', function(req, res) { request.post("https://anilist.co/api/auth/access_token?grant_type=" + keys.grant_type + "&client_id=" + keys.client_id + "&client_secret=" + keys.client_secret, function(err, response, body) { body = JSON.parse(body); // getting authorization credentials request('https://anilist.co/api/anime/20?access_token=' + body.access_token + "&token_type=" + body.token_type, function(error, response, body) { if (!error && response.statusCode == 200) { // var data = JSON.parse(body) // making actual request to api } res.json(body); }); }); }); app.get('/test', function(req, res) { request('http://www.google.com', function(error, response, body) { if(!error && response.statusCode == 200){ console.log(body); } res.send(body); }); }); // catch 404 and forward to error handler app.use(function(req, res, next) { var err = new Error('Not Found'); err.status = 404; next(err); }); // error handlers // development error handler // will print stacktrace if (app.get('env') === 'development') { app.use(function(err, req, res, next) { res.status(err.status || 500); res.render('error', { message: err.message, error: err }); }); } // production error handler // no stacktraces leaked to user app.use(function(err, req, res, next) { res.status(err.status || 500); res.render('error', { message: err.message, error: {} }); }); module.exports = app;
const { response } = require('express'); const Usuario = require('../models/Usuario'); const bcrypt = require('bcryptjs'); const { generarJWT } = require('../helpers/jwt'); const crearUsuario = async(req, res = response) => { const { email, name, password } = req.body; try{ //Verificar el Email const usuario = await Usuario.findOne({ email }); if ( usuario ){ return res.status(400).json({ ok: false, msg: 'El usuario ya existe con ese email' }); } //Crear usuario con el modelo const dbUser = new Usuario( req.body ); //Encriptar la contraseña const salt = bcrypt.genSaltSync(); dbUser.password = bcrypt.hashSync( password, salt ); //Generar el JWT const token = await generarJWT( dbUser.id, name ); //Crear usuario de BD await dbUser.save(); //Generar respuesta exitosa return res.status(201).json({ ok: true, uid: dbUser.id, name, email, token }); }catch (error){ return res.status(500).json({ ok: false, msg: 'Por favor hable con el administrador' }); } } const loginUsuario = async (req, res = response) => { const { email, password } = req.body; try{ const dbUser = await Usuario.findOne({ email }); if ( !dbUser) { return res.status(400).json({ ok: false, msg: 'El correo no existe' }); } //Confirmar si la contraseña hace match const validPassword = bcrypt.compareSync( password, dbUser.password ); if ( !validPassword) { return res.status(400).json({ ok: false, msg: 'El password no es válido' }); } //Generar el JWT const token = await generarJWT( dbUser.id, dbUser.name ); //Respuesta del servicio return res.json({ ok: true, uid: dbUser.id, name: dbUser.name, email: dbUser.email, token }); }catch{ console.log(error); return res.status(500).json({ ok: false, msg: 'Hable con el administrador' }); } } const revalidarToken = async(req, res = response) => { const { uid } = req; //Leer la base de datos const dbUser = await Usuario.findById( uid ); //Generar el JWT const token = await generarJWT( uid, dbUser.name ) return res.json({ ok: true, uid, name: dbUser.name, email: dbUser.email, token }); } module.exports = { crearUsuario, loginUsuario, revalidarToken }
--This chart can provide insights into the distribution of players by nationality, --highlighting the top 10 countries with the highest player representation. --Visualization: Horizontal bar chart select nationality, count(*) as COUNT from fifa22 group by nationality order by count DESC limit 10; --This chart can compare the average overall and potential ratings across different positions, --allowing for a quick comparison of player ratings by their respective positions. --Visualization: Grouped bar chart SELECT Position, AVG(Overall) AS AvgOverall, AVG(Potential) AS AvgPotential FROM Fifa22 GROUP BY Position; --A scatter plot can display the values and wages of players, --providing insights into the relationship between their market value and wage. --Visualization: Scatter plot SELECT name, Value, Wage FROM Fifa22; --This chart can represent the average overall rating split by the preferred foot (left or right), -- indicating any potential differences in player performance based on their dominant foot. SELECT Preferred_Foot, AVG(Overall) AS AvgOverall FROM Fifa22 GROUP BY Preferred_Foot; --This chart can showcase the top 10 clubs with the highest number of players, -- providing insights into the clubs that have a significant presence in the dataset. --Visualization: Vertical bar chart SELECT Club, COUNT(*) AS Count FROM Fifa22 GROUP BY Club ORDER BY Count DESC LIMIT 10; --This chart can illustrate the nationalities with the highest --cumulative market value of their players, providing insights into --countries that have a strong presence in terms of player valuation. --Visualization: Horizontal bar chart SELECT Nationality, SUM(Value) AS TotalValue FROM Fifa22 GROUP BY Nationality ORDER BY TotalValue DESC LIMIT 5; --This chart can display the top 5 nationalities with the highest number of players, -- providing insights into countries that have a larger representation in the dataset. --Visualization: Vertical bar chart SELECT Nationality, COUNT(*) AS Count FROM Fifa22 GROUP BY Nationality ORDER BY Count DESC LIMIT 5;
/* * SPDX-FileCopyrightText: 2023 Zextras <https://www.zextras.com> * * SPDX-License-Identifier: AGPL-3.0-only */ import { act, screen, within } from '@testing-library/react'; import React from 'react'; import OfflineModal from './modals'; import { setup } from '../tests/testUtils'; describe('modals', () => { test('loads modal screen', async () => { const onCloseFn = jest.fn(); const open = true; const { user } = setup(<OfflineModal open={open} onClose={onCloseFn} />); act(() => { jest.runOnlyPendingTimers(); }); expect(screen.getByText('Offline')).toBeVisible(); const okButton = screen.getByRole('button', { name: /ok/i }); expect(okButton).toBeEnabled(); const offline = screen.getByTestId('offlineMsg'); expect(within(offline).getByText(/offline/i)).toBeVisible(); }); });
/** * \file * \brief CryptoAuthLib Basic API methods for Counter command. * * The Counter command reads or increments the binary count value for one of the * two monotonic counters * * \note List of devices that support this command - ATECC508A and ATECC608A. * There are differences in the modes that they support. Refer to device * datasheets for full details. * * \copyright (c) 2015-2018 Microchip Technology Inc. and its subsidiaries. * * \page License * * Subject to your compliance with these terms, you may use Microchip software * and any derivatives exclusively with Microchip products. It is your * responsibility to comply with third party license terms applicable to your * use of third party software (including open source software) that may * accompany Microchip software. * * THIS SOFTWARE IS SUPPLIED BY MICROCHIP "AS IS". NO WARRANTIES, WHETHER * EXPRESS, IMPLIED OR STATUTORY, APPLY TO THIS SOFTWARE, INCLUDING ANY IMPLIED * WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY, AND FITNESS FOR A * PARTICULAR PURPOSE. IN NO EVENT WILL MICROCHIP BE LIABLE FOR ANY INDIRECT, * SPECIAL, PUNITIVE, INCIDENTAL OR CONSEQUENTIAL LOSS, DAMAGE, COST OR EXPENSE * OF ANY KIND WHATSOEVER RELATED TO THE SOFTWARE, HOWEVER CAUSED, EVEN IF * MICROCHIP HAS BEEN ADVISED OF THE POSSIBILITY OR THE DAMAGES ARE * FORESEEABLE. TO THE FULLEST EXTENT ALLOWED BY LAW, MICROCHIP'S TOTAL * LIABILITY ON ALL CLAIMS IN ANY WAY RELATED TO THIS SOFTWARE WILL NOT EXCEED * THE AMOUNT OF FEES, IF ANY, THAT YOU HAVE PAID DIRECTLY TO MICROCHIP FOR * THIS SOFTWARE. */ #include "atca_basic.h" #include "../atca_execution.h" /** \brief Compute the Counter functions * \param[in] mode the mode used for the counter * \param[in] counter_id The counter to be used * \param[out] counter_value pointer to the counter value returned from device * \return ATCA_SUCCESS on success, otherwise an error code. */ ATCA_STATUS atcab_counter(uint8_t mode, uint16_t counter_id, uint32_t *counter_value) { ATCAPacket packet; ATCACommand ca_cmd = _gDevice->mCommands; ATCA_STATUS status = ATCA_GEN_FAIL; do { if (counter_id > 1) { return ATCA_BAD_PARAM; } // build a Counter command packet.param1 = mode; packet.param2 = counter_id; if ((status = atCounter(ca_cmd, &packet)) != ATCA_SUCCESS) { break; } if ((status = atca_execute_command(&packet, _gDevice)) != ATCA_SUCCESS) { break; } if (counter_value != NULL && packet.data[ATCA_COUNT_IDX] >= 7) { *counter_value = ((uint32_t)packet.data[ATCA_RSP_DATA_IDX + 0] << 0) | ((uint32_t)packet.data[ATCA_RSP_DATA_IDX + 1] << 8) | ((uint32_t)packet.data[ATCA_RSP_DATA_IDX + 2] << 16) | ((uint32_t)packet.data[ATCA_RSP_DATA_IDX + 3] << 24); } } while (0); return status; } /** \brief Increments one of the device's monotonic counters * \param[in] counter_id Counter to be incremented * \param[out] counter_value New value of the counter is returned here. Can be * NULL if not needed. * \return ATCA_SUCCESS on success, otherwise an error code. */ ATCA_STATUS atcab_counter_increment(uint16_t counter_id, uint32_t* counter_value) { return atcab_counter(COUNTER_MODE_INCREMENT, counter_id, counter_value); } /** \brief Read one of the device's monotonic counters * \param[in] counter_id Counter to be read * \param[out] counter_value Counter value is returned here. * \return ATCA_SUCCESS on success, otherwise an error code. */ ATCA_STATUS atcab_counter_read(uint16_t counter_id, uint32_t* counter_value) { return atcab_counter(COUNTER_MODE_READ, counter_id, counter_value); }
#ifndef ELDBUS_SIGNATURE_TRAITS_HH_ #define ELDBUS_SIGNATURE_TRAITS_HH_ #include <eina_fold.hh> #include <eina_integer_sequence.hh> namespace efl { namespace eldbus { namespace _detail { template <typename T> struct signature_traits; template <> struct signature_traits<bool> { typedef Eina_Bool raw_type; typedef bool value_type; typedef std::integral_constant<int, 1u> sig_size; static int const sig = 'b'; static raw_type to_raw(value_type v) { return v ? EINA_TRUE : EINA_FALSE; } }; template <> struct signature_traits<char> { typedef char raw_type; typedef raw_type value_type; typedef std::integral_constant<int, 1u> sig_size; static int const sig = 'y'; static raw_type to_raw(value_type v) { return v; } }; template <> struct signature_traits<int16_t> { typedef int16_t raw_type; typedef raw_type value_type; typedef std::integral_constant<int, 1u> sig_size; static char const sig = 'n'; static raw_type to_raw(value_type v) { return v; } }; template <> struct signature_traits<uint16_t> { typedef uint16_t raw_type; typedef raw_type value_type; typedef std::integral_constant<int, 1u> sig_size; static char const sig = 'q'; static raw_type to_raw(value_type i) { return i; } }; template <> struct signature_traits<int32_t> { typedef int32_t raw_type; typedef raw_type value_type; typedef std::integral_constant<int, 1u> sig_size; static char const sig = 'i'; static raw_type to_raw(value_type i) { return i; } }; template <> struct signature_traits<uint32_t> { typedef uint32_t raw_type; typedef raw_type value_type; typedef std::integral_constant<int, 1u> sig_size; static char const sig = 'u'; static raw_type to_raw(value_type i) { return i; } }; template <> struct signature_traits<int64_t> { typedef int64_t raw_type; typedef raw_type value_type; typedef std::integral_constant<int, 1u> sig_size; static char const sig = 'x'; static raw_type to_raw(value_type i) { return i; } }; template <> struct signature_traits<uint64_t> { typedef uint64_t raw_type; typedef raw_type value_type; typedef std::integral_constant<int, 1u> sig_size; static char const sig = 't'; static raw_type to_raw(value_type i) { return i; } }; template <> struct signature_traits<double> { typedef double raw_type; typedef raw_type value_type; typedef std::integral_constant<int, 1u> sig_size; static char const sig = 'd'; static raw_type to_raw(value_type i) { return i; } }; template <> struct signature_traits<std::string> { typedef const char* raw_type; typedef std::string value_type; typedef std::integral_constant<int, 1u> sig_size; static char const sig = 's'; static raw_type to_raw(std::string const& s) { return s.c_str(); } }; template <typename T> struct signature_traits<T const> : signature_traits<T> { }; template <typename T> typename signature_traits<T>::raw_type to_raw(T const& object) { return signature_traits<T>::to_raw(object); } constexpr std::size_t add(std::size_t N) { return N; } constexpr std::size_t add(std::size_t L, std::size_t R) { return L + R; } template <typename... T> constexpr std::size_t add(std::size_t L, std::size_t R, T ... O) { return L + R + add(O...); } template <typename T, typename U> struct signature_size_impl; template <typename T, std::size_t... S> struct signature_size_impl<T, eina::index_sequence<S...> > : std::integral_constant <std::size_t , _detail::add (signature_traits<typename std::tuple_element<S, T>::type>::sig_size::value...)> { }; template <typename T> struct signature_size : signature_size_impl<T, eina::make_index_sequence<std::tuple_size<T>::value> > { }; template <typename ... T> void call_all(T...) {} template <std::size_t I, typename Tuple, std::size_t N , typename = typename std::enable_if<I != N-1>::type> int init_signature(char (&signature)[N]) { signature[I] = signature_traits<typename std::tuple_element<I, Tuple>::type>::sig; return 0; } template <std::size_t I, typename Tuple> int init_signature(char (&signature)[I+1]) { signature[I] = 0; return 0; } template <typename... Args, std::size_t... S, std::size_t N> void init_signature_array(char (&signature)[N], eina::index_sequence<S...>) { call_all(_detail::init_signature<S, std::tuple<Args...> >(signature)...); } } } } #endif
library(rvest) library(xml2) library(jsonlite) library(dplyr) library(RPostgreSQL) library(rtweet) library(gganimate) library(ggplot2) get_data <- function(type = "recentActivities", id=id){ if(type == "recentActivities"){ url <- paste0("https://www.strava.com/athletes/",id) } else { url <- paste0("https://www.strava.com/activities/",id) } out <- read_html(url) %>% html_nodes("[data-react-class]") %>% xml_attr('data-react-props') %>% fromJSON() %>% `[[`(type) return(out) } usr_id <- Sys.getenv("STRAVA_ID") data <- get_data(type = "recentActivities", id = usr_id) data <- data %>% filter(hasGps) %>% select(id, name, type, distance, startDateLocal, elevation, movingTime) data <- as.data.frame(data) data$distance <- as.integer(gsub('.{3}$', '', data$distance)) data$elevation <- gsub('.{2}$', '', data$elevation) data$elevation <- as.integer(gsub(",", "", data$elevation)) data$startDateLocal <- as.Date(data$startDateLocal, "%B %d, %Y") data["startDateLocal"][is.na(data["startDateLocal"])] <- Sys.Date() drv <- dbDriver("PostgreSQL") con <- dbConnect(drv, dbname = Sys.getenv("STRAVA_ELEPHANT_SQL_DBNAME"), host = Sys.getenv("STRAVA_ELEPHANT_SQL_HOST"), port = 5432, user = Sys.getenv("STRAVA_ELEPHANT_SQL_USER"), password = Sys.getenv("STRAVA_ELEPHANT_SQL_PASSWORD")) query <- 'SELECT MAX("id") FROM "public"."activity" ' last_id <- dbGetQuery(con, query) if(is.na(last_id)){ last_id <- 0 } recent_data <- data %>% filter(id > last_id[1,1]) dbWriteTable(conn=con, name='activity', value=recent_data, append = TRUE, row.names = FALSE, overwrite=FALSE) kambing_token <- rtweet::create_token( app = "kambingBot", consumer_key = Sys.getenv("STRAVA_TWITTER_CONSUMER_API_KEY"), consumer_secret = Sys.getenv("STRAVA_TWITTER_CONSUMER_API_SECRET"), access_token = Sys.getenv("STRAVA_TWITTER_ACCESS_TOKEN"), access_secret = Sys.getenv("STRAVA_TWITTER_ACCESS_TOKEN_SECRET") ) l <- length(recent_data$id) if(l > 0){ for(k in 1:l){ id_activity <- recent_data[k,1] recent_act_detail <- get_data(type = "activity", id = recent_data[k,1]) latlng <- recent_act_detail[["streams"]][["latlng"]] distance_stream <- recent_act_detail[["streams"]][["distance"]] altitude <- recent_act_detail[["streams"]][["altitude"]] name <- recent_act_detail[["name"]] distance <- recent_act_detail[["distance"]] elevation <- recent_act_detail[["elevation"]] movingTime <- recent_act_detail[["time"]] if(length(latlng)>0){ df <- as.data.frame(latlng) df$distance <- distance_stream df$altitude <- altitude p <- ggplot(df, aes(x=V2, y=V1)) + geom_path() + geom_point(aes(group = distance)) + transition_reveal(along = distance) + xlab("Longitude") + ylab("Latitude") p <- animate(p,renderer = gifski_renderer()) anim_save("anime.gif", animation = p) status_details <- paste0( "Activity Name: ", name, "\n", "Distance: ", distance, " \n", "Elevation: ", elevation, " \n", "Time: ", movingTime, "\n" ) print(paste("Posting to Twitter", name, sep = ": ")) rtweet::post_tweet( status = status_details, media = "anime.gif", token = kambing_token ) } } } else { print("New activity not found. Nothing posted to Twitter!") }
from cnnClassifier.constants import * from cnnClassifier.utils.common import read_yaml, create_dirs from cnnClassifier.entity.config_entity import (DataIngestionConfig, PrepareBaseModelConfig, PrepareCallbacksConfig, TrainingConfig, EvaluationConfig) import os from pathlib import Path class ConfigurationManager: def __init__(self, config_filepath=CONFING_FILE_PATH, params_filepath=PARAMS_FILE_PATH) -> None: """takes config and params file path creates dirs accordingly... Args: config_filepath (_type_, optional): _description_. Defaults to CONFING_FILE_PATH. params_filepath (_type_, optiona l): _description_. Defaults to PARAMS_FILE_PATH. """ self.config = read_yaml(config_filepath) self.params = read_yaml(params_filepath) create_dirs([self.config.artifacts_root]) def get_data_ingestion_config(self) -> DataIngestionConfig: config = self.config.data_ingestion create_dirs([config.root_dir]) data_ingestion_config = DataIngestionConfig( root_dir=config.root_dir, source_URL=config.source_URL, local_data_file=config.local_data_file, unzip_dir=config.unzip_dir ) return data_ingestion_config def get_prepare_base_model_config(self) -> PrepareBaseModelConfig: config = self.config.prepare_base_model create_dirs([config.root_dir]) prepare_base_model_config = PrepareBaseModelConfig( root_dir=Path(config.root_dir), base_model_path=Path(config.base_model_path), updated_base_model_path=Path(config.updated_base_model_path), params_image_size=self.params.IMAGE_SIZE, params_learning_rate=self.params.LEARNING_RATE, params_classes=self.params.CLASSES, params_include_top=self.params.INCLUDE_TOP, params_weights=self.params.WEIGHTS ) return prepare_base_model_config def get_prepare_callback_config(self) -> PrepareCallbacksConfig: config = self.config.prepare_callbacks model_checkpoint_dir = os.path.dirname( config.checkpoint_model_filepath) create_dirs([ Path(model_checkpoint_dir), Path(config.tensorboard_root_log_dir) ]) prepare_callback_config = PrepareCallbacksConfig( root_dir=Path(config.root_dir), tensorboard_root_log_dir=Path(config.tensorboard_root_log_dir), checkpoint_model_filepath=Path(config.checkpoint_model_filepath) ) return prepare_callback_config def get_training_config(self) -> TrainingConfig: training = self.config.training prepare_base_model = self.config.prepare_base_model params = self.params training_data = os.path.join( self.config.data_ingestion.unzip_dir, "Chicken-fecal-images") create_dirs([Path(training.root_dir)]) training_config = TrainingConfig( root_dir=Path(training.root_dir), trained_model_path=Path(training.trained_model_path), updated_base_model_path=Path( prepare_base_model.updated_base_model_path), training_data=Path(training_data), params_epochs=params.EPOCHS, params_batch_size=params.BATCH_SIZE, params_is_augmentation=params.AUGMENTATION, params_image_size=params.IMAGE_SIZE ) return training_config def get_validation_config(self) -> EvaluationConfig: eval_config = EvaluationConfig( path_of_model=Path("artifacts/training/model.h5"), training_data=Path("artifacts/data_ingestion/Chicken-fecal-images"), all_params=self.params, params_batch_size=self.params.BATCH_SIZE, params_image_size=self.params.IMAGE_SIZE ) return eval_config
import { IconFileExport, IconSettings } from '@tabler/icons-react'; import { useContext, useState } from 'react'; import { useTranslation } from 'next-i18next'; import HomeContext from '@/pages/api/home/home.context'; import { SettingDialog } from '@/components/Settings/SettingDialog'; import { Import } from '../../Settings/Import'; import { Key } from '../../Settings/Key'; import { SidebarButton } from '../../Sidebar/SidebarButton'; import ChatbarContext from '../Chatbar.context'; import { ClearConversations } from './ClearConversations'; export const ChatbarSettings = () => { const { t } = useTranslation('sidebar'); const [isSettingDialogOpen, setIsSettingDialog] = useState<boolean>(false); const { state: { apiKey, lightMode, serverSideApiKeyIsSet, conversations, }, dispatch: homeDispatch, } = useContext(HomeContext); const { handleClearConversations, handleImportConversations, handleExportData, handleApiKeyChange, } = useContext(ChatbarContext); return ( <div className="flex flex-col items-center space-y-1 border-t border-white/20 pt-1 text-sm"> {conversations.length > 0 ? ( <ClearConversations onClearConversations={handleClearConversations} /> ) : null} <Import onImport={handleImportConversations} /> <SidebarButton text={t('Export data')} icon={<IconFileExport size={18} />} onClick={() => handleExportData()} /> <SidebarButton text={t('Settings')} icon={<IconSettings size={18} />} onClick={() => setIsSettingDialog(true)} /> {!serverSideApiKeyIsSet ? ( <Key apiKey={apiKey} onApiKeyChange={handleApiKeyChange} /> ) : null} <SettingDialog open={isSettingDialogOpen} onClose={() => { setIsSettingDialog(false); }} /> </div> ); };
library(tidyverse) FHS_Risk_Score <- function(sex = c('Male', 'Female'), age, total_cholesterol, hdl_cholesterol, systolic_bp, systolic_bp_treated, smoking, diabetes){ #'Calculate the FHS risk score. #' #'@description 10-year CVD event risk score, as published by D'agostino in 2008. #'See General Cardiovascular Risk Profile for Use in Primary Care The Framingham Heart Study, DOI: 10.1161/CIRCULATIONAHA.107.699579 #' #'@param sex The patient sex. #'@param age numeric The patient age. #'@param total_cholesterol numeric The patient total cholesterol #'@param hdl_cholesterol numeric The patient HDL cholesterol #'@param systolic_bp numeric The systolic blood pressure of the patient. #'@param systolic_bp_treated logical Whether the patient is being treated for high blood pressure. #'@param smoking logical Whether the patient smokes. #'@param diabetes logical Whether the patient has diabetes. #' #'@return The patient's 10-year CVD FHS risk score. #There are two different models, one for male, one for female. #t = 10 years. risk <- 0 if(any(is.na(c(sex, age, total_cholesterol, hdl_cholesterol, systolic_bp, systolic_bp_treated, smoking, diabetes)))){ print("Cannot calculate FHS risk score if any of the predictors are NA. Returning NA.") return(NA) } if(sex == 'Male'){ #Adjust blood pressure for treatment beta_bp <- 1.93303 if(systolic_bp_treated) { beta_bp <- 1.99881 } h_0 <- .88936 risk <- 1- h_0 ** exp( log(age) * 3.06117 + log(total_cholesterol) * 1.1237 + log(hdl_cholesterol) * -0.93263 + log(systolic_bp) * beta_bp + as.numeric(smoking) * 0.65451 + as.numeric(diabetes) * 0.57367 - 23.9802 ) } if(sex == 'Female'){ beta_bp <- 2.76157 if(systolic_bp_treated){ beta_bp <- 2.82263 } h_0 <- 0.95012 risk <- 1- h_0 ** exp( log(age) * 2.32888 + log(total_cholesterol) * 1.20904 + log(hdl_cholesterol) * -0.70833 + log(systolic_bp) * beta_bp + as.numeric(smoking) * 0.52873 + as.numeric(diabetes) * 0.69154 - 26.1931 ) } return(risk) } test_fhs_calculator <- function(){ #Compare inputs to known outputs from online calculator: #https://www.framinghamheartstudy.org/fhs-risk-functions/cardiovascular-disease-10-year-risk/ risk_1 = FHS_Risk_Score('Male', 45, 160, 40, 120, F, T, F) print(paste(risk_1, 'was estimated. According to online-tool, should be: 9.5%')) risk_2 = FHS_Risk_Score('Female', 70, 180, 30, 160, T, T, T) print(paste(risk_2, 'was estimated. According to online-tool, should be: 68.5%')) } add_FHS_risk_score <- function(df, assume_binary_NA_means_FALSE = T){ #' Add the Framingham Risk score to a dataframe. See 10-year CVD event risk score, as published by D'agostino in 2008. #' #' @param df data.frame The dataframe to which to add the FHS risk score #' @param assume_binary_NA_means_FALSE logical Whether to assume that if a value is NA for the binary options, that this will be FALSE. #' #' @return The dataframe with the added FHS_Risk_Score_10yr_CVD column get_row_fhs_score <- function(row){ sex <- row[['Sex']] age <- row[['age']] total_cholesterol <- row[['CHOL']] hdl_cholesterol <- row[['HDL']] systolic_bp <- row[['BPsystol']] bp_treated <- row[['receivesBPMeds']] smoking <- row[['CurrentSmoker']] diabetes <- row[['Diabetes']] if(assume_binary_NA_means_FALSE){ if(is.na(bp_treated)){bp_treated <- F} if(is.na(smoking)){smoking <- F} if(is.na(diabetes)){diabetes <- F} } if(any(is.na(c(sex, age, total_cholesterol, hdl_cholesterol, systolic_bp, bp_treated, smoking, diabetes)))){ return(NA) #Cannot calculate risk score if any variable is NA. } fhs_score_row <- FHS_Risk_Score(sex, age, total_cholesterol, hdl_cholesterol, systolic_bp, bp_treated, smoking, diabetes) return(fhs_score_row) } fhs_risk_column <- apply(df, 1, get_row_fhs_score, simplify=T) df$FHS_Risk_Score_10yr_CVD <- fhs_risk_column #See how it compares with Hoffmann cohort: They had only Cohort 1 participants, with mean FHS Risk score of .09 and SD 0.1 hoffmann_cohort <- df %>% filter(CT_number =='1') %>% distinct(ID, IDTYPE, .keep_all = T) print(paste('Cohort corresponding to Hoffmann`s would have FHS Risk Score Mean(SD): ', round(mean(hoffmann_cohort$FHS_Risk_Score_10yr_CVD, na.rm=T), 3), '(', round(sd(hoffmann_cohort$FHS_Risk_Score_10yr_CVD, na.rm=T),3), ')', sep='')) print(paste('Where Hoffmann`s had 0.09 (0.1).')) return(df) }
/** @format */ /** * External dependencies */ import React from 'react'; import PropTypes from 'prop-types'; /** * Internal dependencies */ import FormFieldset from 'components/forms/form-fieldset'; import FormLabel from 'components/forms/form-label'; import FormTextInputWithAffixes from 'components/forms/form-text-input-with-affixes'; import FieldError from '../field-error'; const WeightField = ( { id, title, value, placeholder, updateValue, error, className, weightUnit, } ) => { const handleChangeEvent = event => updateValue( event.target.value ); return ( <FormFieldset className={ className }> <FormLabel htmlFor={ id }>{ title }</FormLabel> <FormTextInputWithAffixes noWrap suffix={ weightUnit } id={ id } name={ id } type="number" placeholder={ placeholder || '0.0' } value={ value } onChange={ handleChangeEvent } isError={ Boolean( error ) } /> { error && typeof error === 'string' && <FieldError text={ error } /> } </FormFieldset> ); }; WeightField.propTypes = { weightUnit: PropTypes.string.isRequired, id: PropTypes.string.isRequired, title: PropTypes.node, value: PropTypes.oneOfType( [ PropTypes.string, PropTypes.number ] ).isRequired, placeholder: PropTypes.string, updateValue: PropTypes.func, error: PropTypes.oneOfType( [ PropTypes.string, PropTypes.bool ] ), className: PropTypes.string, }; export default WeightField;
import gymnasium as gym import numpy as np import matplotlib.pyplot as plt from gymnasium.wrappers import RecordVideo import pickle def run(episodes, epsilon, learning_rate, discount_factor, is_training): env = gym.make("CliffWalking-v0", render_mode=None if is_training else 'rgb_array') if is_training: q = np.zeros((env.observation_space.n, env.action_space.n)) # init cliff walking env array else: env = RecordVideo(env, 'static/uploads') f = open("static/uploads/cliff_walking_sarsa.pkl", "rb") q = pickle.load(f) f.close() # epsilon-greedy policy def policy(state, explore=0.0): action = int(np.argmax(q[state])) if np.random.random() <= explore: action = int(np.random.randint(low=0, high=4, size=1)) return action # PARAMETERS # epsilon_decay_rate = 0.0001 # EPSILON = 0.1 # 1 = argmax, pick optimal action # ALPHA = 0.1 # GAMMA = 1 rewards_per_episode = np.zeros(episodes) for i in range(episodes): state = env.reset()[0] # initial state total_reward_per_eps = 0 terminated = False # True when fall off cliff or reached goal truncated = False # True when actions > 200 action = policy(state, epsilon) while not terminated and not truncated: new_state, reward, terminated, truncated, _ = env.step(action) total_reward_per_eps += reward # print(f"State: {state}, Action: {action}, Q-values: {q[state]}, Reward: {reward}, New State: {new_state}") if is_training: next_action = policy(new_state, epsilon) q[state][action] += learning_rate * ( reward + discount_factor * q[new_state][next_action] - q[state][action]) action = next_action else: action = np.argmax(q[state, :]) state = new_state # epsilon = max(epsilon - epsilon_decay_rate, 0) # if epsilon == 0: # learning_rate = 0.0001 rewards_per_episode[i] = total_reward_per_eps # print("Episode:", i, "Total Reward:", total_reward_per_eps, "Optimal Policy Action:", action) env.close() # print(rewards_per_episode) if is_training: sum_rewards = np.zeros(episodes) window_size = 100 # Adjust the window size as needed for t in range(episodes): sum_rewards[t] = np.sum(rewards_per_episode[max(0, t - window_size + 1):(t + 1)]) # Calculate the moving average moving_avg = sum_rewards / window_size # Plot the moving average plt.plot(moving_avg) # plt.plot(rewards_per_episode, label='Rewards per Episode') plt.xlabel('Episodes') plt.ylabel('Sum of Rewards') plt.title('Training Progress : Cliff Walking - SARSA') plt.savefig('static/uploads/cliff_walking_sarsa.png') plt.show() if is_training: f = open('static/uploads/cliff_walking_sarsa.pkl', "wb") pickle.dump(q, f) f.close() print("Training Complete. Q Table saved.")
package org.ems.employee_management_system.entities; import jakarta.persistence.*; import jakarta.validation.constraints.NotBlank; import lombok.Getter; import lombok.Setter; import org.hibernate.annotations.CreationTimestamp; import java.sql.Timestamp; @Getter @Setter @Entity public class Employee { @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "id") private Long id; @NotBlank(message = "First Name is mandatory") @Column(name = "first_name") private String fname; @NotBlank(message = "Last Name is mandatory") @Column(name = "last_name") private String lname; @NotBlank(message = "Email is mandatory") private String email; @CreationTimestamp @Column(nullable = false, updatable = false) private Timestamp created_at; @Transient private boolean isNew = true; }
#include <stdio.h> #include "main.h" /** * main - Prints all the arguments passed to the program * @argc: Number of arguments passed to the program * @argv: Array of strings containing the arguments passed to the program * * Return: 0 on success */ int main(int argc, char *argv[]) { int i; for (i = 0; i < argc; i++) { printf("%s\n", argv[i]); } return (0); }
### Unit testing on a project structure ### Practice 1: Writing Unit Tests after Writing Source Code 1. Make a project Folder 2. Create a source file and test file 3. Write source code first 4. Write unit tests for the code ### Practice 2: Following Test Driven Development(TDD) 1. Make a project Folder 2. Create a source file and test file 3. Write source code structure(eg. function signatures) 4. Write unit tests for the code 5. Complete source code based on unit test case results ### Practice 3: Better folder structure for source code and test code in a project ### Project Ideas 1. **Project1:** Personal Money Tracker Application(Balance, add_income, add_expense, show_balance, get_records) 2. **Project2:** Library management system (Book Records, add books, borrow books, return books, show current records, etc.)
import { FollowListInfoArgs, SearchUserInfoArgs, RecommendationInfoArgs, FollowListInfoResp, SearchUserInfoResp, RecommendationResp } from "./types"; const endPoint = "https://api.cybertino.io/connect/"; export const followListInfoSchema = ({ address, namespace, network, followingFirst, followingAfter, followerFirst, followerAfter, }: FollowListInfoArgs) => { return { operationName: "followListInfo", query: `query followListInfo($address: String!, $namespace: String, $network: Network, $followingFirst: Int, $followingAfter: String, $followerFirst: Int, $followerAfter: String) { identity(address: $address, network: $network) { followingCount(namespace: $namespace) followerCount(namespace: $namespace) followings(namespace: $namespace, first: $followingFirst, after: $followingAfter) { pageInfo { endCursor hasNextPage } list { address domain avatar } } followers(namespace: $namespace, first: $followerFirst, after: $followerAfter) { pageInfo { endCursor hasNextPage } list { address domain avatar } } } }`, variables: { address, namespace, network, followingFirst, followingAfter, followerFirst, followerAfter, }, }; }; export const searchUserInfoSchema = ({ fromAddr, toAddr, network, }: SearchUserInfoArgs) => { return { operationName: "searchUserInfo", query: `query searchUserInfo($fromAddr: String!, $toAddr: String!, $network: Network) { identity(address: $toAddr, network: $network) { address domain avatar } connections(fromAddr: $fromAddr, toAddrList: [$toAddr], network: $network) { followStatus { isFollowed isFollowing } } }`, variables: { fromAddr, toAddr, network, }, }; }; export const recommendationInfoSchema = ({ address }: RecommendationInfoArgs) => { return { operationName: "recommendation", query: `query QueryRecommendation($address : String!) { recommendations( address: $address filter: SOCIAL network: ETH first: 5 ) { result data { pageInfo { startCursor endCursor hasNextPage hasPreviousPage } list { address domain avatar recommendationReason followerCount } } } }`, variables : { address } } }; export const querySchemas = { followListInfo: followListInfoSchema, searchUserInfo: searchUserInfoSchema, recommendationInfo: recommendationInfoSchema }; export const request = async (url = "", data = {}) => { // Default options are marked with * const response = await fetch(url, { method: "POST", mode: "cors", cache: "no-cache", headers: { "Content-Type": "application/json", }, referrerPolicy: "no-referrer", body: JSON.stringify(data), }); return response.json(); }; export const handleQuery = ( data: { query: string; variables: object; operationName: string; }, url: string ) => { return request(url, data); }; export const followListInfoQuery = async ({ address, namespace, network, followingFirst, followingAfter, followerFirst, followerAfter, }: FollowListInfoArgs) => { const schema = querySchemas["followListInfo"]({ address, namespace, network, followingFirst, followingAfter, followerFirst, followerAfter, }); const resp = await handleQuery(schema, endPoint); return (resp?.data?.identity as FollowListInfoResp) || null; }; export const searchUserInfoQuery = async ({ fromAddr, toAddr, network, }: SearchUserInfoArgs) => { const schema = querySchemas["searchUserInfo"]({ fromAddr, toAddr, network, }); const resp = await handleQuery(schema, endPoint); return (resp?.data as SearchUserInfoResp) || null; }; export const reccomendationQuery = async ({ address } : RecommendationInfoArgs) => { const schema = querySchemas["recommendationInfo"]({ address }); const resp = await handleQuery(schema, endPoint) return (resp?.data as RecommendationResp) || null; };
import heapq '''dynamic programming''' # Time : O(MN) # Space: O(MN) class Solution: def minCut(self, s: str) -> int: # INIT len_s = len(s) cut = [0] * len_s table = [[False] * len_s for _ in range(len_s)] # Bottom-up approach for end in range(len_s): mini = end for start in range(end+1): # check if s[start:end+1] is a palindrome # start + 1 > end -1 인 경우에는 start == end 인 경우 즉, substring이 character인 경우에는 무조건 palindrome이다. 혹은, table[start+1][end-1] if s[start] == s[end] and ( start + 1 > end -1 or table[start+1][end-1]): # table[start+1][end-1] = check if the previous string is palindrome table[start][end] = True mini = 0 if start == 0 else min(mini, cut[start-1] + 1) cut[end] = mini return cut[len_s-1] ''' 아래거는 time limit 초과로 안되는데, 답은 나올 것 같긴 하다. ''' # class Solution: # def minCut(self, s: str) -> int: # paths = [] # path = [] # heap = [] # # global cut # cut = 0 # def partition_helper(index:int, cut:int): # if index == len(s): # # paths.append(path[:]) # # heapq.heappush(heap, (cut, path[:])) # memory limit exceeded # heapq.heappush(heap, cut) # return # for i in range(index, len(s)): # if is_palindrome(s, index, i): # cut += 1 # path.append(s[index:i+1]) # partition_helper(i+1, cut) # path.pop() # cut -= 1 # def is_palindrome(s:str, start:int, end:int) -> bool: # while start <= end and s[start] == s[end]: # start += 1 # end -= 1 # return True if start > end else False # partition_helper(0, cut) # min = heapq.heappop(heap) # return min -1 # return priority value not the key (data itself) if __name__ == '__main__': s = 'aab' x = Solution() print(x.minCut(s)) # 1
import { inject, injectable } from 'tsyringe'; import { IUserDetailRepository } from '../repositories/IUserDetailRepository'; import { IUserDetailDTO } from '../dtos/IUserDetailDTO'; import { AppError } from '../../../shared/errors/AppError'; @injectable() export class FindUserDetailService { constructor( @inject('UserDetailRepository') private userDetailRepository: IUserDetailRepository, ) {} async execute(id: string): Promise<IUserDetailDTO> { const userDetail = await this.userDetailRepository.findById(id); if (!userDetail) { throw new AppError('User not found'); } return userDetail; } }
/* * Copyright 2018 Nico Reißmann <[email protected]> * See COPYING for terms of redistribution. */ #ifndef JLM_LLVM_IR_OPERATORS_GETELEMENTPTR_HPP #define JLM_LLVM_IR_OPERATORS_GETELEMENTPTR_HPP #include <jlm/llvm/ir/tac.hpp> #include <jlm/llvm/ir/types.hpp> #include <jlm/rvsdg/bitstring/type.hpp> #include <jlm/rvsdg/simple-node.hpp> namespace jlm::llvm { /** * This operation is the equivalent of LLVM's getelementptr instruction. * * FIXME: We currently do not support vector of pointers for the baseAddress. * */ class GetElementPtrOperation final : public rvsdg::simple_op { public: ~GetElementPtrOperation() noexcept override; public: GetElementPtrOperation( const std::vector<std::shared_ptr<const rvsdg::bittype>> & offsetTypes, std::shared_ptr<const rvsdg::valuetype> pointeeType) : simple_op(CreateOperandTypes(offsetTypes), { PointerType::Create() }), PointeeType_(std::move(pointeeType)) {} GetElementPtrOperation(const GetElementPtrOperation & other) = default; GetElementPtrOperation(GetElementPtrOperation && other) noexcept = default; bool operator==(const operation & other) const noexcept override; [[nodiscard]] std::string debug_string() const override; [[nodiscard]] std::unique_ptr<rvsdg::operation> copy() const override; [[nodiscard]] const rvsdg::valuetype & GetPointeeType() const noexcept { return *dynamic_cast<const rvsdg::valuetype *>(PointeeType_.get()); } /** * Creates a GetElementPtr three address code. * * FIXME: We should not explicitly hand in the resultType parameter, but rather compute it from * the pointeeType and the offsets. See LLVM's GetElementPtr instruction for reference. * * @param baseAddress The base address for the pointer calculation. * @param offsets The offsets from the base address. * @param pointeeType The type the base address points to. * @param resultType The result type of the operation. * * @return A getElementPtr three address code. */ static std::unique_ptr<llvm::tac> Create( const variable * baseAddress, const std::vector<const variable *> & offsets, const rvsdg::valuetype & pointeeType, const rvsdg::type & resultType) { CheckPointerType(baseAddress->type()); auto offsetTypes = CheckAndExtractOffsetTypes<const variable>(offsets); CheckPointerType(resultType); GetElementPtrOperation operation( offsetTypes, std::static_pointer_cast<const rvsdg::valuetype>(pointeeType.copy())); std::vector<const variable *> operands(1, baseAddress); operands.insert(operands.end(), offsets.begin(), offsets.end()); return tac::create(operation, operands); } /** * Creates a GetElementPtr three address code. * * FIXME: We should not explicitly hand in the resultType parameter, but rather compute it from * the pointeeType and the offsets. See LLVM's GetElementPtr instruction for reference. * * @param baseAddress The base address for the pointer calculation. * @param offsets The offsets from the base address. * @param pointeeType The type the base address points to. * @param resultType The result type of the operation. * * @return A getElementPtr three address code. */ static std::unique_ptr<llvm::tac> Create( const variable * baseAddress, const std::vector<const variable *> & offsets, std::shared_ptr<const rvsdg::valuetype> pointeeType, std::shared_ptr<const rvsdg::type> resultType) { CheckPointerType(baseAddress->type()); auto offsetTypes = CheckAndExtractOffsetTypes<const variable>(offsets); CheckPointerType(*resultType); GetElementPtrOperation operation(offsetTypes, std::move(pointeeType)); std::vector<const variable *> operands(1, baseAddress); operands.insert(operands.end(), offsets.begin(), offsets.end()); return tac::create(operation, operands); } /** * Creates a GetElementPtr RVSDG node. * * FIXME: We should not explicitly hand in the resultType parameter, but rather compute it from * the pointeeType and the offsets. See LLVM's GetElementPtr instruction for reference. * * @param baseAddress The base address for the pointer calculation. * @param offsets The offsets from the base address. * @param pointeeType The type the base address points to. * @param resultType The result type of the operation. * * @return The output of the created GetElementPtr RVSDG node. */ static rvsdg::output * Create( rvsdg::output * baseAddress, const std::vector<rvsdg::output *> & offsets, const rvsdg::valuetype & pointeeType, const rvsdg::type & resultType) { CheckPointerType(baseAddress->type()); auto offsetTypes = CheckAndExtractOffsetTypes<rvsdg::output>(offsets); CheckPointerType(resultType); GetElementPtrOperation operation( offsetTypes, std::static_pointer_cast<const rvsdg::valuetype>(pointeeType.copy())); std::vector<rvsdg::output *> operands(1, baseAddress); operands.insert(operands.end(), offsets.begin(), offsets.end()); return rvsdg::simple_node::create_normalized(baseAddress->region(), operation, operands)[0]; } /** * Creates a GetElementPtr RVSDG node. * * FIXME: We should not explicitly hand in the resultType parameter, but rather compute it from * the pointeeType and the offsets. See LLVM's GetElementPtr instruction for reference. * * @param baseAddress The base address for the pointer calculation. * @param offsets The offsets from the base address. * @param pointeeType The type the base address points to. * @param resultType The result type of the operation. * * @return The output of the created GetElementPtr RVSDG node. */ static rvsdg::output * Create( rvsdg::output * baseAddress, const std::vector<rvsdg::output *> & offsets, std::shared_ptr<const rvsdg::valuetype> pointeeType, std::shared_ptr<const rvsdg::type> resultType) { CheckPointerType(baseAddress->type()); auto offsetTypes = CheckAndExtractOffsetTypes<rvsdg::output>(offsets); CheckPointerType(*resultType); GetElementPtrOperation operation(offsetTypes, std::move(pointeeType)); std::vector<rvsdg::output *> operands(1, baseAddress); operands.insert(operands.end(), offsets.begin(), offsets.end()); return rvsdg::simple_node::create_normalized(baseAddress->region(), operation, operands)[0]; } private: static void CheckPointerType(const rvsdg::type & type) { if (!is<PointerType>(type)) { throw jlm::util::error("Expected pointer type."); } } template<class T> static std::vector<std::shared_ptr<const rvsdg::bittype>> CheckAndExtractOffsetTypes(const std::vector<T *> & offsets) { std::vector<std::shared_ptr<const rvsdg::bittype>> offsetTypes; for (const auto & offset : offsets) { if (auto offsetType = std::dynamic_pointer_cast<const rvsdg::bittype>(offset->Type())) { offsetTypes.emplace_back(std::move(offsetType)); continue; } throw jlm::util::error("Expected bitstring type."); } return offsetTypes; } static std::vector<std::shared_ptr<const rvsdg::type>> CreateOperandTypes(const std::vector<std::shared_ptr<const rvsdg::bittype>> & indexTypes) { std::vector<std::shared_ptr<const rvsdg::type>> types({ PointerType::Create() }); types.insert(types.end(), indexTypes.begin(), indexTypes.end()); return types; } std::shared_ptr<const rvsdg::valuetype> PointeeType_; }; } #endif
package body YAA.Functions is One : constant Real := Real (1.0); Two : constant Real := Real (2.0); Four : constant Real := Real (4.0); -- For any sufficiently continuous function (?) -- f(a0 + a1e1 + a2e2 + a12e12) -- = f(a0) + (a1e1 + a2e2 + a12e12)f'(a0) -- + 0.5*(a1e1 + a2e2 + a12e12)^2f''(a0) -- = f(a0) + (a1e1 + a2e2 + a12e12)f'(a0) -- + 0.5*(a1^2e1^2 + a2^2e2^2 + a12^2e12^2 -- + 2a1a2e1e2 + 2a1a12e1e12 + 2a2a12e2e12)f''(a0) -- = f(a0) + (a1e1 + a2e2 + a12e12)f'(a0) + 0.5*(2a1a2)^2f''(a0) -- = f(a0) + a1f'(a0)e1 + a2f'(a0)e2 + (a12f'(a0) + a1a2f''(a0))e12 function DerivativesToDual (X : Dual; F, FPrime, FSecond : Real) return Dual is begin return ( Re => F, Im1 => X.Im1 * FPrime, Im2 => X.Im2 * FPrime, Im12 => X.Im12 * FPrime + X.Im1 * X.Im2 * FSecond); end DerivativesToDual; -- f(x) = x^q -- f'(x) = qx^(q-1) -- f''(x) = q * (q-1) * x^(q-2) function Power (X : Dual; Q : Real) return Dual is F : constant Real := PowerR (X.Re, Q); FPrime : constant Real := Q * PowerR (X.Re, Q - One); FSecond : constant Real := Q * (Q - One) * PowerR (X.Re, Q - Two); begin return DerivativesToDual (X, F, FPrime, FSecond); end Power; -- f(x) = x^0.5 -- f'(x) = 0.5x^-0.5 = 1 / (2 * f(x)) -- f''(x) = -0.25x^-1.5 = - 1/( 4 * f'(x)^3) function Sqrt (X : Dual) return Dual is F : constant Real := SqrtR (X.Re); FPrime : constant Real := One / (Two * F); FSecond : constant Real := -One / (Four * F * F * F); begin return DerivativesToDual (X, F, FPrime, FSecond); end Sqrt; -- f(x) = log(x) -- f'(x) = x^-1 -- f''(x) = -x^-2 = - f'(x)^2 function Log (X : Dual) return Dual is F : constant Real := LogR (X.Re); FPrime : constant Real := One / (X.Re); FSecond : constant Real := -FPrime * FPrime; begin return DerivativesToDual (X, F, FPrime, FSecond); end Log; -- f(x) = exp(x) -- f'(x) = exp(x) -- f''(x) = exp(x) function Exp (X : Dual) return Dual is F : constant Real := ExpR (X.Re); begin return DerivativesToDual (X, F, F, F); end Exp; -- f(x) = cos(x) -- f'(x) = -sin(x) -- f''(x) = -cos(x) function Cos (X : Dual) return Dual is F : constant Real := CosR (X.Re); FPrime : constant Real := -SinR (X.Re); begin return DerivativesToDual (X, F, FPrime, -F); end Cos; -- f(x) = sin(x) -- f'(x) = cos(x) -- f''(x) = -sinx(x) function Sin (X : Dual) return Dual is F : constant Real := SinR (X.Re); FPrime : constant Real := CosR (X.Re); begin return DerivativesToDual (X, F, FPrime, -F); end Sin; -- f(x) = tan(x) -- f'(x) = 1 + tan^2(x) -- f''(x) = 2 tan(x) (tan(x))' function Tan (X : Dual) return Dual is F : constant Real := TanR (X.Re); FPrime : constant Real := One + F * F; FSecond : constant Real := Two * F * FPrime; begin return DerivativesToDual (X, F, FPrime, FSecond); end Tan; -- f(x) = cot(x) -- f'(x) = -1 - cot^2(x) -- f''(x) = - 2 cot(x) (cot(x))' function Cot (X : Dual) return Dual is F : constant Real := CotR (X.Re); FPrime : constant Real := -One - F * F; FSecond : constant Real := -Two * F * FPrime; begin return DerivativesToDual (X, F, FPrime, FSecond); end Cot; -- f(x) = arccos(x) -- f'(x) = -(1 - x^2)^(-0.5) -- f''(x) = -0.5 * 2x * (1 - x^2)^(-1.5) = -x * f'(x)^3 function Arccos (X : Dual) return Dual is F : constant Real := ArccosR (X.Re); FPrime : constant Real := -One / SqrtR (One - X.Re * X.Re); FSecond : constant Real := -X.Re * FPrime * FPrime * FPrime; begin return DerivativesToDual (X, F, FPrime, FSecond); end Arccos; -- f(x) = arcsin(x) -- f'(x) = (1 - x^2)^(-0.5) -- f''(x) = 0.5 * 2x * (1 - x^2)^(-1.5) = x * f'(x)^3 function Arcsin (X : Dual) return Dual is F : constant Real := ArcsinR (X.Re); FPrime : constant Real := One / SqrtR (One - X.Re * X.Re); FSecond : constant Real := X.Re * FPrime * FPrime * FPrime; begin return DerivativesToDual (X, F, FPrime, FSecond); end Arcsin; -- f(x) = arctan(x) -- f'(x) = (1 + x^2)^(-1) -- f''(x) = - 2x * (1 - x^2)^(-2) = -2x * f'(x)^2 function Arctan (X : Dual) return Dual is F : constant Real := ArctanR (X.Re); FPrime : constant Real := One / (One + X.Re * X.Re); FSecond : constant Real := -Two * X.Re * FPrime * FPrime; begin return DerivativesToDual (X, F, FPrime, FSecond); end Arctan; -- f(x) = arccot(x) -- f'(x) = -(1 + x^2)^(-1) -- f''(x) = 2x * (1 - x^2)^(-2) = 2x * f'(x)^2 function Arccot (X : Dual) return Dual is F : constant Real := ArccotR (X.Re); FPrime : constant Real := -One / (One + X.Re * X.Re); FSecond : constant Real := Two * X.Re * FPrime * FPrime; begin return DerivativesToDual (X, F, FPrime, FSecond); end Arccot; -- f(x) = cosh(x) -- f'(x) = sinh(x) -- f''(x) = cosh(x) function Cosh (X : Dual) return Dual is F : constant Real := CoshR (X.Re); FPrime : constant Real := SinhR (X.Re); begin return DerivativesToDual (X, F, FPrime, F); end Cosh; -- f(x) = sinh(x) -- f'(x) = cosh(x) -- f''(x) = sinh(x) function Sinh (X : Dual) return Dual is F : constant Real := SinhR (X.Re); FPrime : constant Real := CoshR (X.Re); begin return DerivativesToDual (X, F, FPrime, F); end Sinh; -- f(x) = tanh(x) -- f'(x) = 1 - tanh(x)^2 -- f''(x) = -2tanh(x)(tanh(x))' function Tanh (X : Dual) return Dual is F : constant Real := TanhR (X.Re); FPrime : constant Real := One - F * F; FSecond : constant Real := -Two * F * FPrime; begin return DerivativesToDual (X, F, FPrime, FSecond); end Tanh; -- f(x) = coth(x) -- f'(x) = 1 - coth(x)^2 -- f''(x) = -coth(x)(coth(x))' function Coth (X : Dual) return Dual is F : constant Real := CothR (X.Re); FPrime : constant Real := One - F * F; FSecond : constant Real := -Two * F * FPrime; begin return DerivativesToDual (X, F, FPrime, FSecond); end Coth; -- f(x) = arccosh(x) -- f'(x) = (x^2 - 1)^-0.5 -- f''(x) = -0.5 *2x * (x^2 - 1)^-1.5 = -x * f'(x)^3 function Arccosh (X : Dual) return Dual is F : constant Real := ArccoshR (X.Re); FPrime : constant Real := One / SqrtR (X.Re * X.Re - One); FSecond : constant Real := -X.Re * FPrime * FPrime * FPrime; begin return DerivativesToDual (X, F, FPrime, FSecond); end Arccosh; -- f(x) = arcsinh(x) -- f'(x) = (x^2 + 1)^-0.5 -- f''(x) = -0.5 *2x * (x^2 + 1)^-1.5 = -x * f'(x)^3 function Arcsinh (X : Dual) return Dual is F : constant Real := ArcsinhR (X.Re); FPrime : constant Real := One / SqrtR (X.Re * X.Re + One); FSecond : constant Real := -X.Re * FPrime * FPrime * FPrime; begin return DerivativesToDual (X, F, FPrime, FSecond); end Arcsinh; -- f(x) = arctanh(x) -- f'(x) = (1 - x^2)^-1 -- f''(x) = 2x * (1 - x^2)^-2 = 2x * f'(x)^2 function Arctanh (X : Dual) return Dual is F : constant Real := ArctanhR (X.Re); FPrime : constant Real := One / (One - X.Re * X.Re); FSecond : constant Real := Two * X.Re * FPrime * FPrime; begin return DerivativesToDual (X, F, FPrime, FSecond); end Arctanh; -- f(x) = arccoth(x) -- f'(x) = -(1 - x^2)^-1 -- f''(x) = -2x * (1 - x^2)^-2 = -2x * f'(x)^2 function Arccoth (X : Dual) return Dual is F : constant Real := ArctanhR (X.Re); FPrime : constant Real := -One / (One - X.Re * X.Re); FSecond : constant Real := -Two * X.Re * FPrime * FPrime; begin return DerivativesToDual (X, F, FPrime, FSecond); end Arccoth; end YAA.Functions;
import "./App.css"; import { BrowserRouter as Router, Routes, Route } from "react-router-dom"; //import the pages and components import Home from "./pages/Home"; import Projects from "./pages/Projects"; import Learningjourney from "./pages/Learningjourney"; import Navbar from "./components/Navbar"; import Footer from "./components/Footer"; import ProjectDisplay from "./pages/ProjectDisplay"; function App() { return ( <div className="App"> <Router> <Navbar /> <Routes> //define the route to different pages <Route path="/" element={<Home />} /> <Route path="/projects" element={<Projects />} /> <Route path="/project/:id" element={<ProjectDisplay />} /> <Route path="/Learningjourney" element={<Learningjourney/>} /> </Routes> <Footer /> </Router> </div> ); } export default App;
package org.example; import com.fasterxml.jackson.databind.ObjectMapper; import com.github.javaparser.JavaParser; import com.github.javaparser.ast.CompilationUnit; import com.github.javaparser.ast.ImportDeclaration; import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration; import com.github.javaparser.ast.body.MethodDeclaration; import com.github.javaparser.ast.expr.MethodCallExpr; import com.github.javaparser.ast.expr.ObjectCreationExpr; import com.github.javaparser.ast.visitor.VoidVisitorAdapter; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; public class ProjectParser { public static void main(String[] args) { try { // Set the path to your Java project directory String projectDir = "C:\\Users\\admin\\desktop\\bankensApi"; List<File> javaFiles = listJavaFiles(projectDir); List<Map<String, Object>> parsedFiles = new ArrayList<>(); for (File file : javaFiles) { FileInputStream in = new FileInputStream(file); CompilationUnit cu = JavaParser.parse(in); ClassVisitor classVisitor = new ClassVisitor(new String(Files.readAllBytes(file.toPath()))); cu.accept(classVisitor, null); parsedFiles.add(classVisitor.getResult()); } // Convert the result to JSON using Jackson ObjectMapper ObjectMapper mapper = new ObjectMapper(); String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(parsedFiles); System.out.println(json); } catch (IOException e) { e.printStackTrace(); } } // Method to list all Java files in the project directory private static List<File> listJavaFiles(String directoryName) throws IOException { List<File> fileList = new ArrayList<>(); Files.walk(Paths.get(directoryName)) .filter(Files::isRegularFile) .filter(path -> path.toString().endsWith(".java")) .forEach(path -> fileList.add(path.toFile())); return fileList; } // Visitor class to collect information from the Java file private static class ClassVisitor extends VoidVisitorAdapter<Void> { private Map<String, Object> result = new HashMap<>(); private Set<String> methods = new HashSet<>(); private Set<String> methodCalls = new HashSet<>(); private Set<String> objectCreations = new HashSet<>(); private Set<String> imports = new HashSet<>(); private String extendsClass = ""; private Set<String> implementsInterfaces = new HashSet<>(); private String code; public ClassVisitor(String code) { this.code = code; } @Override public void visit(ClassOrInterfaceDeclaration n, Void arg) { super.visit(n, arg); result.put("ClassName", n.getNameAsString()); if (n.getExtendedTypes().isNonEmpty()) { extendsClass = n.getExtendedTypes(0).getNameAsString(); result.put("Extends", extendsClass); } if (n.getImplementedTypes().isNonEmpty()) { n.getImplementedTypes().forEach(implementedType -> implementsInterfaces.add(implementedType.getNameAsString())); result.put("Implements", implementsInterfaces); } } @Override public void visit(MethodDeclaration n, Void arg) { super.visit(n, arg); methods.add(n.getNameAsString()); } @Override public void visit(MethodCallExpr n, Void arg) { super.visit(n, arg); methodCalls.add(n.getNameAsString()); if (n.getScope().isPresent() && n.getScope().get() instanceof com.github.javaparser.ast.expr.NameExpr) { methodCalls.add(n.getScope().get().toString()); } } @Override public void visit(ObjectCreationExpr n, Void arg) { super.visit(n, arg); objectCreations.add(n.getType().getNameAsString()); } @Override public void visit(ImportDeclaration n, Void arg) { super.visit(n, arg); imports.add(n.getNameAsString()); } public Map<String, Object> getResult() { result.put("Methods", methods); result.put("MethodCalls", methodCalls); result.put("ObjectCreations", objectCreations); result.put("Imports", imports); result.put("Code", code); return result; } } }
<template> <section class="character" id="character"> <div class="character__inner"> <Transition name="charSwiper"> <div class="character__swiper" v-if="swiperOn == true"> <ul class="swiper-wrapper"> <li class="swiper-slide" v-for="(a, i) in charInfo" :key="i"> <Transition v-if="slideIndex == i" name="hero"> <div class="character__slide-wrap"> <div :class="`character__bg ${charInfo[i].charName}`"> <video :src=" require(`@/assets/img/character/${charInfo[i].charName}/pc-bg.mp4`) " muted playsinline loop autoplay></video> </div> <div class="character__info"> <div class="character__wrap"> <dl> <dt class="character__name"> <img :src=" require(`@/assets/img/character/${charInfo[i].charName}/name.png`) " :alt="`${charInfo[i].koName}`" /> </dt> <dd class="character__story"> {{ charInfo[i].story }} </dd> </dl> <div class="character__skill"> <span :class="`character__skill-txt ${charInfo[i].charName}`" >캐릭터 스킬</span > <ul class="character__skill-list"> <li> <figure> <img :src=" require(`@/assets/img/character/${charInfo[i].charName}/skill_01.png`) " alt="스킬 1" /> <figcaption> {{ charInfo[i].skil1 }} </figcaption> </figure> </li> <li> <figure> <img :src=" require(`@/assets/img/character/${charInfo[i].charName}/skill_02.png`) " alt="스킬 2" /> <figcaption> {{ charInfo[i].skil2 }} </figcaption> </figure> </li> <li> <figure> <img :src=" require(`@/assets/img/character/${charInfo[i].charName}/skill_03.png`) " alt="스킬 3" /> <figcaption>{{ charInfo[i].skil3 }}</figcaption> </figure> </li> <li> <figure> <img :src=" require(`@/assets/img/character/${charInfo[i].charName}/skill_04.png`) " alt="스킬 4" /> <figcaption> {{ charInfo[i].skil4 }} </figcaption> </figure> </li> </ul> </div> <div class="character__videoBtn"> <a href="https://youtu.be/qG64QXHB12U" target="_blank"> <img src="@/assets/img/character/character-viewBtn.png" alt="캐릭터 영상보기" class="pcBtn" /> <img src="@/assets/img/character/mo/character-viewBtn.png" alt="캐릭터 영상보기" class="mobileBtn" /> </a> </div> </div> </div> </div> </Transition> </li> </ul> <a href="javascript:void(0)" class="character__close" @click="swiperOn = false"> <picture> <source srcset="@/assets/img/character/mo/char-close.png" media="(max-width:1024px)" /> <source srcset="@/assets/img/character/char-close.png" /> <img src="@/assets/img/character/char-close.png" alt="캐릭터 스와이퍼 닫기" /> </picture> </a> <div class="character__swiper-btn"> <a href="javascript:void(0)" class="character__next" @click="nextSlide"> <img src="@/assets/img/character/char-next.png" alt="" /> </a> <a href="javascript:void(0)" class="character__prev" @click="prevSlide"> <img src="@/assets/img/character/char-prev.png" alt="" /> </a> </div> </div> </Transition> <div class="character__tit"> <h2> <picture> <source srcset="@/assets/img/character/mo/char-tit.png" media="(max-width:1024px)" /> <source srcset="@/assets/img/character/char-tit.png" /> <img src="@/assets/img/character/char-tit.png" alt="흔하디 흔한 삼국지는 가라!" /> </picture> </h2> <p> 실존하는 삼국지 게임 중 가장 <br /> 기상천외한 삼국지가 찾아온다! </p> </div> <ul class="character__list" id="charTab"> <li class="swiper-pagination-bullet" v-for="(a, i) in charInfo" :key="i"> <a href="javascript:void(0)"> <div class="character__label" @click=" swiperOn = true; slideIndex = i; "> <i class="char-ico"></i> <span class="char-name">{{ charInfo[i].koName }}</span> </div> </a> <figure> <picture> <source :srcset=" require(`@/assets/img/character/mo/${charInfo[i].charName}.png`) " media="(max-width:1024px)" /> <source :srcset=" require(`@/assets/img/character/${charInfo[i].charName}.png`) " /> <img :src=" require(`@/assets/img/character/${charInfo[i].charName}.png`) " :alt="`${charInfo[i].charName}`" /> </picture> </figure> </li> </ul> </div> </section> </template> <script> import charInfo from '../js/charData'; export default { name: 'CharacterComp', data() { return { charInfo: charInfo, slideIndex: 7, swiperOn: false, }; }, methods: { nextSlide() { if (this.slideIndex < 6) { this.slideIndex++; } }, prevSlide() { if (this.slideIndex > 0) { this.slideIndex--; } }, }, }; </script> <style lang="scss" scoped> .hero-enter-active, .hero-leave-active { transition: opacity 0.5s ease; } .hero-enter-from, .hero.leave-to { opacity: 0; } .charSwiper-enter-active, .charSwiper-leave-active { transition: opacity 0.5s; } .charSwiper-enter, .charSwiper-leave-to { opacity: 0; } .character { background: url('#{$path-image}/character/character-bg.webp') no-repeat center/cover; position: relative; padding-top: remSet(130px); padding-bottom: remSet(100px); aspect-ratio: auto; height: 120vh; @include labtop { aspect-ratio: auto; padding-top: remSet(50px); } @include mobile { padding-top: remSet(130px); padding-bottom: remSet(150px); background-image: url('#{$path-image}/character/mo/character-bg.png'); } @media (max-width: 280px) { //aspect-ratio: 715/1700; padding-top: remSet(90px); } &__inner { width: 100%; height: 100%; display: flex; flex-direction: column; justify-content: space-between; @include mobile { justify-content: flex-start; } } &__tit { display: flex; flex-direction: column; align-items: center; @include mobile { margin-bottom: 0; } @include mobile-mini { margin-bottom: remSet(30px); } h2 { display: inline-block; margin-bottom: remSet(20px); @include mobile { width: 61%; } img { margin: 0 auto; } } p { font-size: remSet(32px); color: #cec0eb; line-height: 1.4; position: relative; padding: remSet(15px) remSet(60px) remSet(30px); text-align: center; @include mobile { /* font-size: remSet(38px); */ font-weight: 800; letter-spacing: 1px; padding: remSet(20px) remSet(70px) remSet(70px); } @media (max-width: 280px) { font-size: remSet(28px); } &::before { content: ''; display: block; width: remSet(80px); height: remSet(130px); background: url('#{$path-image}/character/char-txt-decoL.png') no-repeat center / contain; position: absolute; left: 0; top: 0; @include mobile { background-image: url('#{$path-image}/character/mo/char-txt-decoL.png'); } } &::after { content: ''; display: block; width: remSet(80px); height: remSet(130px); background: url('#{$path-image}/character/char-txt-decoR.png') no-repeat center / contain; position: absolute; right: 0; top: 0; @include mobile { background-image: url('#{$path-image}/character/mo/char-txt-decoR.png'); } } } } &__list { width: 80%; max-width: remSet(1650px); height: calc(100% - remSet(370px)); max-height: remSet(730px); margin: 0 auto; display: flex; justify-content: center; flex-wrap: wrap; @include mobile { margin: auto; width: 95%; } @include mobile-mini { justify-content: space-around; width: 90%; } li { width: 22%; position: relative; z-index: 0; display: flex; justify-content: center; align-items: center; margin: 0 remSet(10px); &.diaochan { img { max-width: remSet(580px); } } &.lvbu { img { max-width: remSet(580px); } } &.zhugeliang { img { max-width: remSet(580px); } } &.liubei { img { max-width: remSet(580px); } } &.zhangfei { img { max-width: remSet(5500px); } } &.guanyu { img { max-width: remSet(580px); } } &.zhaoyun { img { max-width: remSet(620px); } } @include mobile { width: 33%; margin: 0; margin-top: remSet(30px); &.diaochan { order: 0; width: 40%; } &.lvbu { order: 1; width: 40%; } &.zhugeliang { order: 2; } &.liubei { order: 3; } &.zhangfei { order: 4; } &.guanyu { order: 5; width: 40%; } &.zhaoyun { order: 6; width: 40%; } } @include mobile-mini { &.diaochan { img { max-width: remSet(480px); } } &.lvbu { img { max-width: remSet(450px); } } &.zhugeliang { img { max-width: remSet(400px); } } &.liubei { img { max-width: remSet(400px); } } &.zhangfei { img { max-width: remSet(330px); } } &.guanyu { img { max-width: remSet(400px); } } &.zhaoyun { img { max-width: remSet(450px); } } } @media (max-width: 280px) { &.diaochan { img { max-width: remSet(350px); } } &.lvbu { img { max-width: remSet(350px); } } &.zhugeliang { img { max-width: remSet(350px); } } &.liubei { img { max-width: remSet(330px); } } &.zhangfei { img { max-width: remSet(260px); } } &.guanyu { img { max-width: remSet(350px); } } &.zhaoyun { img { max-width: remSet(380px); } } } figure { position: absolute; z-index: -2; left: 50%; top: 50%; transform: translate(-50%, -50%); transition: transform 0.5s; pointer-events: none; @include desktop { transform: translate(-50%, -50%) scale(0.75); } @include mobile { transform: translate(-50%, -50%) scale(1); } img { max-width: fit-content; transform: scale(0.95); @include mobile { transform: scale(1); } } } a { display: block; width: remSet(220px); height: remSet(180px); position: relative; pointer-events: none; } &.hover { z-index: 1; figure { transform: translate(-50%, -50%) scale(1.1, 1.1); @include desktop { transform: translate(-50%, -50%) scale(0.95, 0.95); } @include mobile { transform: translate(-50%, -50%) scale(1.1, 1.1); } img { animation: charfloating infinite 5s ease-in-out; } } } } } &__label { display: flex; align-items: center; position: absolute; left: 0; top: 0; z-index: 1; pointer-events: auto; i { width: remSet(60px); height: remSet(65px); display: block; background: url('#{$path-image}/character/char-ico.png') no-repeat center center; position: relative; z-index: 1; transition: background 0.3s; @include mobile { width: remSet(70px); height: remSet(75px); background-size: contain; } @include mobile-mini { background-image: url('#{$path-image}/character/mo/char-ico-hover.png') !important; } } span { font-size: remSet(18px); color: #d3b97d; background: url('#{$path-image}/character/char-name-bg.png') no-repeat center; background-size: 100% 100%; height: remSet(35px); display: flex; justify-content: center; align-items: center; padding: remSet(3px) remSet(20px) 0; position: relative; z-index: 0; transform: translateX(remSet(-50px)); opacity: 0; transition: transform 0.3s, opacity 0.3s; @include mobile-mini { transform: translateX(remSet(-10px)); opacity: 1; display: none !important; } } &:hover { i { background-image: url('#{$path-image}/character/char-ico-hover.png'); } span { transform: translateX(remSet(-10px)); opacity: 1; } } &.diaochan { top: remSet(-80px); left: remSet(35px); @include mobile-mini { left: remSet(80px); top: remSet(80px); } } &.lvbu { @include mobile-mini { left: remSet(70px); top: remSet(70px); } } &.zhugeliang { top: remSet(100px); @include desktop { top: 0; } @include mobile-mini { left: remSet(100px); top: remSet(100px); } } &.zhaoyun { left: auto; right: remSet(-150px); @include mobile-mini { left: remSet(70px); top: auto; bottom: remSet(-20px); } } &.guanyu { top: auto; bottom: 0; @include mobile-mini { left: remSet(80px); bottom: remSet(-30px); } } &.liubei { top: 40%; left: auto; right: remSet(-150px); @include mobile-mini { top: remSet(140px); right: auto; left: remSet(50px); } } &.zhangfei { left: auto; right: remSet(-200px); @include mobile-mini { top: remSet(100px); left: remSet(50px); right: auto; } } } &__swiper { width: 100%; height: calc(100%); position: fixed; z-index: 9; left: 0; top: 0; opacity: 1; //pointer-events: none; transition: opacity 0.3s; @include mobile { z-index: 11; } /* &.show { opacity: 1; pointer-events: auto; } */ } .swiper-wrapper { width: 100%; height: 100%; position: relative; } .swiper-slide { width: 100%; height: 100%; position: absolute; z-index: 8; left: 0; top: 0; z-index: 1; opacity: 1; } &__slide-wrap { position: relative; width: 100%; height: 100%; z-index: 1; } &__bg { width: 100%; height: 100%; position: absolute; left: 0; top: 0; z-index: -1; background-repeat: no-repeat; background-size: cover; pointer-events: none; video { width: 100%; height: 100%; position: absolute; object-fit: cover; left: 0; top: 0; z-index: -1; pointer-events: none; &.pc-bg { @include mobile { display: none; } } &.mo-bg { display: none; @include mobile { display: block; } } } } &__info { display: flex; flex-direction: column; justify-content: center; align-items: flex-end; width: 100%; height: 100%; max-width: remSet(1280px); margin: 0 auto; text-align: center; @include mobile { justify-content: flex-end; align-items: center; } } &__wrap { @include mobile { height: 55%; padding: 0 remSet(70px); display: flex; flex-direction: column; justify-content: center; align-items: center; } @media (max-width: 280px) { padding: 0 remSet(30px); } } &__name { margin-bottom: remSet(40px); @include mobile { height: remSet(80px); img { height: 100%; } } img { margin: 0 auto; } } &__story { color: #5a4c54; font-size: remSet(24px); line-height: 1.3; letter-spacing: -1px; margin-bottom: remSet(50px); white-space: pre-wrap; @include mobile { font-size: remSet(28px); letter-spacing: 0; line-height: 1.5; //white-space: nowrap; br { display: none; } } } &__skill { background: url('#{$path-image}/character/skill-bg.png') no-repeat center; background-size: 100% 100%; padding: remSet(45px) remSet(45px) remSet(25px); position: relative; max-width: remSet(560px); margin: 0 auto; @include mobile { max-width: 100%; } &-txt { position: absolute; left: 50%; top: remSet(-24px); transform: translateX(-50%); background-size: 100% 100%; background-repeat: no-repeat; background-position: center center; display: block; color: #fff; font-size: remSet(24px); width: remSet(220px); height: remSet(50px); display: flex; justify-content: center; align-items: center; &.diaochan { background-image: url('#{$path-image}/character/diaochan/skill-txt.png'); } &.lvbu { background-image: url('#{$path-image}/character/lvbu/skill-txt.png'); } &.zhugeliang { background-image: url('#{$path-image}/character/zhugeliang/skill-txt.png'); } &.zhaoyun { background-image: url('#{$path-image}/character/zhaoyun/skill-txt.png'); } &.guanyu { background-image: url('#{$path-image}/character/guanyu/skill-txt.png'); } &.liubei { background-image: url('#{$path-image}/character/liubei/skill-txt.png'); } &.zhangfei { background-image: url('#{$path-image}/character/zhangfei/skill-txt.png'); } } &-list { display: flex; li { margin-left: remSet(30px); @include mobile { width: calc((100% / 4) - 10px); } &:first-child { margin-left: 0; } figcaption { margin-top: remSet(15px); font-size: remSet(18px); color: #5a4c54; font-weight: 600; line-height: 1.3; white-space: pre-line; @include mobile { font-size: remSet(22px); font-weight: 400; } @media (max-width: 280px) { white-space: nowrap; } } } } } &__videoBtn { text-align: center; @include mobile { position: absolute; z-index: 1; right: remSet(50px); top: remSet(150px); width: remSet(180px); } @media (max-width: 280px) { right: remSet(20px); width: remSet(150px); } a { margin-top: remSet(30px); display: inline-block; } img.pcBtn { display: block; @include mobile { display: none; } } img.mobileBtn { display: none; @include mobile { display: block; } } } &__close { position: absolute; right: remSet(50px); top: remSet(130px); z-index: 10; @include mobile { width: remSet(48px); height: remSet(48px); top: remSet(50px); } } &__next { position: absolute; right: remSet(100px); top: 50%; z-index: 9; img { height: 100%; } @include mobile { right: remSet(30px); height: remSet(80px); top: 47%; } @media (max-width: 280px) { right: remSet(15px); } } &__prev { position: absolute; left: remSet(100px); top: 50%; z-index: 9; img { height: 100%; } @include mobile { left: remSet(30px); height: remSet(80px); top: 47%; } @media (max-width: 280px) { left: remSet(15px); } } .swiper-button-disabled { opacity: 0.5; } } @keyframes charfloating { 0% { transform: translateY(0px); } 25% { transform: translateY(remSet(-7px)); } 50% { transform: translateY(remSet(7px)); } 75% { transform: translateY(remSet(-7px)); } 100% { transform: translateY(0); } } </style>
import { css } from '@emotion/react' import React, { useRef, useState, useEffect } from 'react' import defaultProfile from '@/assets/image/defaultProfile.jpg'; import { getUserID, getUserProfile } from '@/api/user'; import axios from 'axios'; type ReviewType = { appId: number, userId: number, profileImageURL?: string, name: string, date: string, content: string, helpfulCount?: number, rating: number } type ReviewInputProps = { isRated: boolean, getReviewData: (reviewCount: number, pageNum: number) => void, appID: number, userID: number } function ReviewInput({isRated, getReviewData, appID, userID}: ReviewInputProps) { const [isFocused, setIsFocused] = useState(false); const [isActive, setIsActive] = useState(false); const inputRef = useRef<HTMLInputElement | null>(null); const [profileImage, setProfileImage] = useState(defaultProfile); const env = import.meta.env; const onFocusHandler = () => { setIsFocused(true); } const onClickCancel = () => { setIsFocused(false); setIsActive(false); if (inputRef.current) { inputRef.current.value = ""; } } const onClickConfirm = async () => { if (inputRef.current) { console.log(inputRef.current.value); // API 요청하기... try { const response = await axios.put(env.VITE_API_USER_BASE_URL + "/review", { app_id: appID, user_id: userID, content: inputRef.current.value }) console.log("put 요청 결과:", response); getReviewData(5, 1); } catch { console.log("평가 추가 실패..."); } inputRef.current.value = ""; setIsActive(false); } } const onChangeHandler = (e: React.ChangeEvent<HTMLInputElement>) => { if (e.target.value === "") { setIsActive(false); } else { setIsActive(true); } } const handleInputClick = () => { if (inputRef?.current) { if (inputRef.current.disabled === true) { alert("평가를 먼저 진행해주세요"); } } } useEffect(() => { if (inputRef?.current) { if (isRated) { inputRef.current.disabled = false; inputRef.current.placeholder = "리뷰를 입력해주세요..."; } else { inputRef.current.disabled = true; inputRef.current.placeholder = "평가를 먼저 해주세요"; } } }, [isRated]) useEffect(() => { const id = getUserID(); if (id !== null) { const response = getUserProfile(id); response .then(result => { const user = result?.user; setProfileImage(user?.userProfile.substr(1, user.userProfile.length - 2) ?? defaultProfile); }); } }, []) return ( <div> <div css={inputContainer}> <img src={profileImage} css={profileImageStyle} /> <input onChange={onChangeHandler} css={reviewInputStyle} type="text" ref={inputRef} onFocus={onFocusHandler} onClick={handleInputClick} placeholder="입력해주세요..." /> </div> {isFocused && <div css={buttonsContainer}> <button onClick={onClickCancel} css={cancelButton}>취소</button> <button onClick={onClickConfirm} css={isActive ? addReplyButton : disabledButton}>확인</button> </div> } </div> ) } const inputContainer = css` display: flex; justify-content: space-between; align-items: center; ` const profileImageStyle = css` width: 50px; height: 50px; border-radius: 50%; margin-right: 10px; ` const reviewInputStyle = css` width: 100%; background-color: transparent; padding: 4px 0px 4px 0px; color: white; border: none; border-bottom: 2px solid gray; font-size: 16px; &:focus { outline: none; border-bottom: 2px solid white; } transition-property: border-bottom; transition-duration: 300ms; ` const buttonsContainer = css` display: flex; justify-content: flex-end; ` const cancelButton = css` font-size: 14px; padding: 8px 13px 8px 13px; border: none; border-radius: 20px; margin-left: 10px; color: white; background-color: transparent; cursor: pointer; &:hover { background-color: rgb(117, 98, 146); } ` const addReplyButton = css` font-size: 14px; padding: 8px 13px 8px 13px; border: none; border-radius: 20px; margin-left: 10px; color: white; background-color: rgb(28, 132, 255); cursor: pointer; &:hover { background-color: rgb(52, 145, 255); } ` const disabledButton = css` font-size: 14px; padding: 8px 13px 8px 13px; border: none; border-radius: 20px; margin-left: 10px; color: rgb(255,255,255,0.5); background-color: rgb(91,91,91,0.5); cursor: default; ` export default ReviewInput
//Css import { Todo } from '../../App'; import './card.css'; //Interfaces / Types type CardProps = { todo: Todo; completeTodo: (id: number) => void; deleteTodo: (id: number) => void; }; //Function export default function Card({ todo, completeTodo, deleteTodo }: CardProps) { function handleCompleteTodo() { completeTodo(todo.id); } function handleDeleteTodo() { deleteTodo(todo.id); } return ( //ao passar mais de uma classe em que precisa de if ternário é necessário usar template strings <div className={`container_Card card ${todo.completed ? 'done' : ''}`}> {/* <h2>Fazer café</h2> */} <h1>{todo.title}</h1> <div className='card_buttons'> <button onClick={handleCompleteTodo}> {todo.completed ? 'Retomar' : 'Completar'} </button> <button onClick={handleDeleteTodo}>Deletar</button> </div> </div> ); }
@baseUrl = http://localhost:3333 @auth_token = {{authenticate.response.body.access_token}} #################################################################################################### # O Objetivo desta rota [e realizar o cadastro do usuário na aplicação #################################################################################################### # @name create_account POST {{baseUrl}}/accounts Content-Type: application/json { "name": "Fulano Sousa", "email": "[email protected]", "password": "123456" } #################################################################################################### # O Objetivo desta rota é realizar a autenticação do usuário # OBS: Após a realização da autenticação com sucesso o access_token é preenchido automaticamente #################################################################################################### # @name authenticate POST {{baseUrl}}/sessions Content-Type: application/json { "email": "[email protected]", "password": "123456" } #################################################################################################### # O Objetivo desta rota é realizar o encurtamento da URL #################################################################################################### # @name create_shorten_url POST {{baseUrl}}/shorten Content-Type: application/json Authorization: Bearer {{auth_token}} { "url": "https://teddy360.com.br/material/marco-legal-das-garantias-sancionado-entenda-o-que-muda/" } #################################################################################################### # O Objetivo desta rota é realizar a atualização do endereço de origem da rota # OBS: Primeiro você tem que adquerir o ID da URL, que pode ser na rota de listagem de URLS # ou acessando o banco de dados #################################################################################################### # @name update_url_destiny PUT {{baseUrl}}/shorten Content-Type: application/json Authorization: Bearer {{auth_token}} { "urlId": "0350be3f-5ce3-409e-8299-08d8f8d5f0d9", "newdestinyUrl": "https://github.com/pedrohigordev/challenge-url-shortener" } #################################################################################################### # O Objetivo desta rota é realizar o soft delete da URL cadastrada # OBS: Primeiro você tem que adquerir o ID da URL, que pode ser na rota de listagem de URLS # ou acessando o banco de dados #################################################################################################### # @name delete_url DELETE {{baseUrl}}/shorten?urlId=2f5d76f3-f871-4af7-a7f1-6386b5bba35f Content-Type: application/json Authorization: Bearer {{auth_token}} #################################################################################################### # O Objetivo desta rota é listar todas as URls do usuário autenticado #################################################################################################### # @name list_urls GET {{baseUrl}}/shorten Content-Type: application/json Authorization: Bearer {{auth_token}} #################################################################################################### # O Objetivo desta rota é realizar o acesso e redirecionamento da Url encurtada através do hash # Se possível, copie o código hash e passe como route params #################################################################################################### # @name access_url_shortened GET {{baseUrl}}/tXGvIf Content-Type: application/json Authorization: Bearer {{auth_token}}
--- sidebar_position: 1 --- # Create a satellite Before integrating Juno into your JavaScript app, you need to create a [satellite]. 1. To get started, sign-in to the Juno [console](https://console.juno.build). If you are a new developer on Juno and the Internet Computer, you may be prompted to create your first anonymous [Internet Identity]. 2. Click **Launch a new satellite**. 3. Enter a name for your satellite (note: this is for display purposes only and does not need to be unique). 4. Confirm with **Create a Satellite.**. Juno will automatically generate a unique ID for your new satellite. 5. The platform will then create your satellite smart contract and provision its resources. 6. Once the process is complete, click **Continue** to receive on-screen information about how to develop your dapp or host your website. Alternatively, select "Skip" to access the overview page. [satellite]: ../terminology.md#satellite [Internet Identity]: ../terminology.md#internet-identity
import { useEffect, useState } from "react"; import styles from "./searchInput.module.scss"; import search from "../../img/search.svg"; interface SearchInputProps { keyword: string; setKeyword: (search: string) => void; } export const SearchInput: React.FC<SearchInputProps> = ({ keyword, setKeyword }) => { const [value, setValue] = useState(keyword); useEffect(() => { if (!keyword) { setValue(""); } }, [keyword]); return ( <div className={styles.searchInputWrapper}> <div className={styles.leftSection}> <img src={search} alt="search"></img> </div> <div className={styles.rightSection}> <button onClick={() => setKeyword(value)} data-elem="search-button"> Поиск </button> </div> <input type="search" className={styles.input} value={value} placeholder="Введите название вакансии" autoComplete="off" onChange={(e) => setValue(e.target.value)} data-elem="search-input" ></input> </div> ); };
import style from "./OrderInfo.module.css"; import { useContext, useState } from "react"; import { useEffect } from "react"; import { motion } from "framer-motion"; import { Container, Row, Col, Table, Form, Modal, Button, } from "react-bootstrap"; import { BsPencil, BsTrash } from "react-icons/bs"; import { Tooltip } from "react-tooltip"; import { Link, useNavigate, useParams } from "react-router-dom"; import { ToastContainer, toast } from "react-toastify"; import { ShowContext } from "../../../../context/ShowContext"; import { MedicineContext } from "../../../../context/MedicinesContext"; import useDocumentTitle from "../../../../hooks/useDocumentTitle"; import LinkWithBack from "../../../../components/LinkWithBack/LinkWithBack"; import Icon from "../../../../components/Icon/Icon"; import MenuItem from "../../../../components/MenuItem/MenuItem"; import MediSelected from "../../../../components/MediSelected/MediSelected"; import ButtonSubmit from "../../../../components/ButtonSubmit"; import { createPortal } from "react-dom"; const OrderInfo = () => { const [show, setShow] = useState(false); const handleClose = () => { setShow(false); }; const handleShow = () => { setShow(true); }; const [name, setName] = useState(""); const [medicines, setMedicines] = useState([]); const navigate = useNavigate(); const { spinnerElement, spinner, setSpinner } = useContext(ShowContext); const { loading, error, setError, setLoading, deleteOrder, FetchOrderInfo } = useContext(MedicineContext); const [info, setInfo] = useState([]); const { id } = useParams(); useEffect(() => { setSpinner(true); const setTime = setTimeout(() => { setSpinner(false); }, 300); return () => { clearInterval(setTime); }; }, [setSpinner]); useEffect(() => { const func = async () => { try { setLoading(true); const data = await FetchOrderInfo(id); setMedicines(data.orderMedicines); setName(data.supplier.name); setInfo(data); } catch (error) { setError(error.message); } setLoading(false); }; func(); }, [FetchOrderInfo]); const handleOrderDelete = async (e) => { e.preventDefault(); const response = await deleteOrder(id); if (response.ok) { toast.success("تم حذف الطلبية بنجاح"); setTimeout(() => { navigate(-1); }, 2000); } else { setError(null); setLoading(false); } handleClose(); }; useDocumentTitle("معلومات الطلبية"); return ( <motion.div initial={{ scale: 0 }} animate={{ scale: 1 }} transition={{ type: "spring", stiffness: 260, damping: 20, }} style={{ margin: "auto" }} className={" d-flex flex-column px-sm-5 px-0 pb-4`"} > {spinner && spinnerElement} <Row className="flex-row justify-content-between"> <Col xs="9" md="10"> <LinkWithBack title={"معلومات الطلبية"} /> </Col> <Col className="d-flex gap-1" xs="3" md="2"> <Link to={`/stock/orders/edit/${id}?return=yes`}> <Icon id="edit" icon={<BsPencil fill="white" />} /> </Link> <Icon onClick={handleShow} id="delete" icon={<BsTrash fill="white" />} /> </Col> <Tooltip anchorSelect="#delete" clickable={true} place={"left"} style={{ fontSize: "12px" }} > حذف الطلبية </Tooltip> </Row> <Tooltip anchorSelect="#edit" clickable={true} place={"right"} style={{ fontSize: "12px" }} > تعديل بيانات الطلبية </Tooltip> <Container className="d-flex mt-3 justify-content-center align-items-center m-auto"> <div style={{ width: "90%" }}> {loading && !error && info.length === 0 ? ( <div className="text-center text-black p-0 m-0 mt-5 fw-bold"> جاري التحميل... </div> ) : !loading && !error && info ? ( <> <Row className="justify-content-center mb-1"> <Col sm="6"> <MenuItem title={info.supplyrequest} pt="mt-2 mt-md-0" isLink={false} > طلب الإمداد </MenuItem> </Col> <Col sm="6"> <MenuItem title={info.deliveryrequest} pt="mt-2 mt-md-0" isLink={false} > إذن التسليم </MenuItem> </Col> </Row> <Row className="justify-content-center "> <Col sm="6"> <MenuItem title={info.dateofsupply} pt="mt-2 mt-md-0" isLink={false} > تاريخ التوريد </MenuItem> </Col> <Col sm="6"> <MenuItem title={name} pt="mt-2 mt-md-0" isLink={false}> اسم المورد </MenuItem> </Col> </Row> <Row className="justify-content-center my-2"> <div className={`${style.mediTable} overflow-y-scroll mt-2 px-1`} > <Table striped hover> <thead> <tr> <th className={"showFonts"}>#</th> <th className={"showFonts"}>الدواء</th> <th className={"showFonts"}>الكمية</th> <th className={"showFonts"}>الصلاحية</th> <th className={"showFonts"}>الشركة المصنعة</th> <th className={"showFonts"}>السعر</th> </tr> </thead> <tbody> {!loading && medicines.length > 0 ? medicines.map((medi, index) => ( <MediSelected mode="orderInfo" setId={id} setMode={id} key={medi.medicine.id} name={medi.medicine.name} quantity={medi.amount} price={medi.price} supplier={medi.medicine.manufacturer} expire={medi.expirydate} id={medi.medicine.barcode} idx={index + 1} /> )) : null} </tbody> </Table> </div> </Row> <div className="d-flex flex-row-reverse align-items-end mt-3 mb-4"> <Button className={`btn-main px-3`} onClick={() => window.print()} > طباعة </Button> </div> </> ) : error ? ( <p className="text-center p-0 m-0 mt-5 fw-bold"> عذراً , حدث خطأ ما , يرجى المحاولة مرة أخرى </p> ) : ( <p className="text-center text-white p-0 m-0 mt-5 fw-bold"> عذراً , لا توجد نتائج </p> )} </div> </Container> {createPortal( <Modal show={show} centered={true} onHide={handleClose}> <Modal.Header> <Modal.Title>هل انت متاكد من حذف الطلبية</Modal.Title> </Modal.Header> <Modal.Body> <Form onSubmit={handleOrderDelete}> <div className="btns mt-4 d-flex gap-2 me-auto justify-content-end "> <ButtonSubmit className="btn-danger"> نعم , أريد حذف الطلبية </ButtonSubmit> <Button className="btn-main" onClick={handleClose}> إغلاق </Button> </div> </Form> </Modal.Body> </Modal>, document.getElementById("modal") )} </motion.div> ); }; export default OrderInfo;
<template> <div></div> </template> <script> /** * reduce 对数组中的每个元素执行一个由您提供的reduce函数 * * arr.reduce(function(prev, cur, index, arr) { * ... * }, init) * * prev 必需 上一次调用回调时的返回值 或初始值init * cur 必需 当前正在处理的数组元素 * index 可选 当前正在处理的数组元素的索引值 有init值时,起始索引为0,否则为1 * arr 可选 原始数组 * init 可选 初始值 */ export default { data() { return { arr: [1,2,3,4,5] } }, methods: { testReduce() { const sum = arr.reduce((prev,cur,index,arr) => { return prev + cur }) // 返回结果为 1+2+3+4+5=15 } } } </script>
import { CloudFormationClient, DeleteStackCommand, DeleteStackCommandOutput } from "@aws-sdk/client-cloudformation"; import { DeleteSecretCommand, DeleteSecretCommandInput, DeleteSecretCommandOutput, GetSecretValueCommand, GetSecretValueCommandInput, GetSecretValueCommandOutput, SecretsManagerClient } from "@aws-sdk/client-secrets-manager"; import { SSMClient, GetParameterCommand, GetParameterCommandInput, GetParameterCommandOutput, } from '@aws-sdk/client-ssm'; import { AssumeRoleCommand, STSClient } from '@aws-sdk/client-sts'; import { AppPromoParams, BindResourceParams, GitRepoParams } from "@aws/plugin-aws-apps-common-for-backstage"; import { Logger } from "winston"; export type GitLabDownloadFileResponse = { file_name: string; file_path: string; size: number; encoding: string; content: string; content_sha256: string; ref: string; blob_id: string; commit_id: string; last_commit_id: string; execute_filemode: boolean; } export class AwsAppsPlatformApi { public constructor( private readonly logger: Logger, private readonly awsRegion: string, private readonly awsAccount: string, ) { this.logger.info('Instantiating AWS Apps Platform API with:'); this.logger.info(`awsAccount: ${this.awsAccount}`); this.logger.info(`awsRegion: ${this.awsRegion}`); } /** * Get SecretsManager Secret value. * * @remarks * Get SecretsManager Secret value. * * @param secretArn - The Arn or name of the secret to retrieve * @returns The GetSecretValueCommandOutput object * */ public async getPlatformSecretValue(secretArn: string): Promise<GetSecretValueCommandOutput> { this.logger.info('Calling getPlatformSecretValue'); const client = new SecretsManagerClient({ region: this.awsRegion }); const params: GetSecretValueCommandInput = { SecretId: secretArn, }; const command = new GetSecretValueCommand(params); const resp = client.send(command); return resp; } /** * Get SSM Parameter Store value. * * @remarks * Get SSM Parameter Store value. * * @param ssmKey - The SSM param key to retrieve * @returns The GetParameterCommandOutput object * */ public async getSsmValue(ssmKey: string): Promise<GetParameterCommandOutput> { this.logger.info('Calling getSsmValue'); const client = new SSMClient({ region: this.awsRegion }); const params: GetParameterCommandInput = { Name: ssmKey, WithDecryption: true, }; const command = new GetParameterCommand(params); const resp = client.send(command); return resp; } public async deletePlatformSecret(secretName: string): Promise<DeleteSecretCommandOutput> { this.logger.info('Calling deletePlatformSecret'); const client = new SecretsManagerClient({ region: this.awsRegion }); const params: DeleteSecretCommandInput = { SecretId: secretName, ForceDeleteWithoutRecovery: true, }; const command = new DeleteSecretCommand(params); const resp = client.send(command); return resp; } public async deleteCFStack(stackName: string, accessRole: string): Promise<DeleteStackCommandOutput> { this.logger.info('Calling deleteProvider'); const stsClient = new STSClient({ region: this.awsRegion }); //console.log(`deleting ${stackName}`) const stsResult = await stsClient.send( new AssumeRoleCommand({ RoleArn: accessRole, RoleSessionName: `backstage-session`, DurationSeconds: 3600, // max is 1 hour for chained assumed roles }), ); if (stsResult.Credentials) { //console.log(stsResult.Credentials) const client = new CloudFormationClient({ region: this.awsRegion, credentials: { accessKeyId: stsResult.Credentials.AccessKeyId!, secretAccessKey: stsResult.Credentials.SecretAccessKey!, sessionToken: stsResult.Credentials.SessionToken, }, }); const input = { StackName: stackName, }; const command = new DeleteStackCommand(input); const response = client.send(command); return response } else { throw new Error("can't fetch credentials to remove requested provider") } } public async deleteRepository(gitHost: string, gitProjectGroup: string, gitRepoName: string, gitSecretName: string): Promise<{ status: string, message?: string }> { const gitAdminSecret = await this.getPlatformSecretValue(gitSecretName); const gitAdminSecretObj = JSON.parse(gitAdminSecret.SecretString || ""); const gitToken = gitAdminSecretObj["apiToken"]; // fetch project ID const gitProjects = await fetch(`https://${gitHost}/api/v4/projects?search=${gitRepoName}`, { method: 'GET', headers: { 'PRIVATE-TOKEN': gitToken, 'Content-Type': 'application/json', } }); const gitProjectsJson: { path_with_namespace: string, id: string }[] = await gitProjects.json(); let project = null; if (gitProjectsJson) { project = gitProjectsJson.filter(project => project.path_with_namespace === `${gitProjectGroup}/${gitRepoName}`)[0]; } if (project && project.id) { console.log(`Got GitLab project ID: ${gitProjectsJson[0]?.id}`); // now delete the repo const url = `https://${gitHost}/api/v4/projects/${gitProjectGroup}%2F${gitRepoName}` console.log(url) const deleteRepoResults = await fetch(url, { method: 'DELETE', headers: { 'PRIVATE-TOKEN': gitToken } }); console.log(deleteRepoResults) if (deleteRepoResults.status > 299) { return { status: "FAILURE", message: `Repository failed to delete` }; } else { return { status: "SUCCESS", message: `Repository deleted successfully` }; } } else { console.error(`ERROR: Failed to retrieve project ID for ${gitRepoName}`); return { status: "FAILURE", message: `Failed to retrieve Git project ID for ${gitRepoName}` }; } } private async getGitToken(gitSecretName: string): Promise<string> { const gitAdminSecret = await this.getPlatformSecretValue(gitSecretName); const gitAdminSecretObj = JSON.parse(gitAdminSecret.SecretString || ""); return gitAdminSecretObj["apiToken"]; } private async getGitProjectId(gitHost: string, gitProjectGroup: string, gitRepoName: string, gitToken: string): Promise<string> { const gitProjects = await fetch(`https://${gitHost}/api/v4/projects?search=${gitRepoName}`, { method: 'GET', headers: { 'PRIVATE-TOKEN': gitToken, 'Content-Type': 'application/json', } }); const gitProjectsJson: { path_with_namespace: string, id: string }[] = await gitProjects.json(); let project = null; if (gitProjectsJson) { project = gitProjectsJson.filter(project => project.path_with_namespace === `${gitProjectGroup}/${gitRepoName}`)[0]; } if (project && project.id) { return project.id; } else { throw new Error(`Failed to get git project ID for group '${gitProjectGroup}' and repo '${gitRepoName}'`); } } public async getFileContentsFromGit(repo: GitRepoParams, filePath: string, gitSecretName: string): Promise<GitLabDownloadFileResponse> { const gitToken = await this.getGitToken(gitSecretName); let gitProjectId: string; gitProjectId = await this.getGitProjectId(repo.gitHost, repo.gitProjectGroup, repo.gitRepoName, gitToken); console.log(`Got GitLab project ID: ${gitProjectId}`); const url = `https://${repo.gitHost}/api/v4/projects/${gitProjectId}/repository/files/${filePath}?ref=main`; const result = await fetch(new URL(url), { method: 'GET', headers: { 'PRIVATE-TOKEN': gitToken, 'Content-Type': 'application/json', }, }); const resultBody = await result.json(); if (result.status > 299) { console.error(`ERROR: Failed to retrieve ${filePath} for ${repo.gitRepoName}. Response code: ${result.status} - ${resultBody}`); throw new Error(`Failed to retrieve ${filePath} for ${repo.gitRepoName}. Response code: ${result.status}`); } else { return resultBody; } } public async promoteAppToGit(input: AppPromoParams, gitSecretName: string): Promise<{ status: string, message?: string }> { const gitToken = await this.getGitToken(gitSecretName); // Hardcoded responses for developer testing // return {status: "SUCCESS", message: `Promotion will not be complete until deployment succeeds. Check the CICD pipeline for the most up-to-date information. UI status may take a few minutes to update.`}; // return {status: "FAILURE", message: "Some error description"}; let gitProjectId: string; try { gitProjectId = await this.getGitProjectId(input.gitHost, input.gitProjectGroup, input.gitRepoName, gitToken); console.log(`Got GitLab project ID: ${gitProjectId}`); } catch (err: any) { console.error(`ERROR: ${err.toString()}`); return { status: "FAILURE", message: `Failed to retrieve Git project ID for ${input.gitRepoName}` }; } //Now build a new commit that will trigger the pipeline const actions = await Promise.all(input.providers.map(async (provider) => { const propsFile = `.awsdeployment/providers/${input.envName}-${provider.providerName}.properties`; const prov1EnvRoleArn = (await this.getSsmValue(provider.assumedRoleArn)).Parameter?.Value; let propsContent = `ACCOUNT=${provider.awsAccount}\nREGION=${provider.awsRegion}\nENV_NAME=${provider.environmentName}\nPREFIX=${provider.prefix}\n` + `ENV_PROVIDER_NAME=${provider.providerName}\nENV_ROLE_ARN=${prov1EnvRoleArn}\nAAD_CI_ENVIRONMENT=${provider.environmentName}-${provider.providerName}\n` + `AAD_CI_ENVIRONMENT_MANUAL_APPROVAL=${input.envRequiresManualApproval}\n` + `AAD_CI_REGISTRY_IMAGE=${provider.awsAccount}.dkr.ecr.${provider.awsRegion}.amazonaws.com/${input.appName}-${provider.providerName}\n`; Object.keys(provider.parameters).forEach(key => { propsContent += `${key}=${provider.parameters[key]}\n` }); return { action: "create", file_path: propsFile, content: propsContent }; })); const commit = { branch: "main", commit_message: "generate CICD stages", actions: actions } const url = `https://${input.gitHost}/api/v4/projects/${gitProjectId}/repository/commits`; const result = await fetch(new URL(url), { method: 'POST', body: JSON.stringify(commit), headers: { 'PRIVATE-TOKEN': gitToken, 'Content-Type': 'application/json', }, }); const resultBody = await result.json(); if (result.status > 299) { console.error(`ERROR: Failed to promote ${input.envName}. Response code: ${result.status} - ${resultBody}`); let message = ""; if (resultBody.message?.includes('A file with this name already exists')) { message = `${input.envName} has already been scheduled for promotion. Check the CICD pipeline for the most up-to-date information. UI status may take a few minutes to update.`; } else { message = resultBody.message || ''; } return { status: "FAILURE", message }; } else { return { status: "SUCCESS", message: `Promotion will not be complete until deployment succeeds. Check the CICD pipeline for the most up-to-date information. UI status may take a few minutes to update.` }; } } public async bindResource(input: BindResourceParams, gitSecretName: string): Promise<{ status: string, message?: string }> { const gitAdminSecret = await this.getPlatformSecretValue(gitSecretName); const gitAdminSecretObj = JSON.parse(gitAdminSecret.SecretString || ""); const gitToken = gitAdminSecretObj["apiToken"]; // fetch project ID const gitProjects = await fetch(`https://${input.gitHost}/api/v4/projects?search=${input.gitRepoName}`, { method: 'GET', headers: { 'PRIVATE-TOKEN': gitToken, 'Content-Type': 'application/json', } }); const gitProjectsJson: { path_with_namespace: string, id: string }[] = await gitProjects.json(); let project = null; if (gitProjectsJson) { project = gitProjectsJson.filter(project => project.path_with_namespace === `${input.gitProjectGroup}/${input.gitRepoName}`)[0]; } if (project && project.id) { console.log(`Got GitLab project ID: ${gitProjectsJson[0]?.id}`); const actions = input.policies.map(p => { const policyFile = `.iac/aws_ecs/permissions/${input.envName}/${input.providerName}/${p.policyFileName}.json`; const policyContent = p.policyContent; return { action: "create", file_path: policyFile, content: policyContent }; }) const resourceBindContent = `RESOURCE_ENTITY_REF=${input.resourceEntityRef}\nRESOURCE_ENTITY=${input.resourceName}\nTARGET_ENV_NAME=${input.envName}\nTARGET_ENV_PROVIDER_NAME=${input.providerName}` const resourceBindFile = `.awsdeployment/resource-binding-params-temp.properties`; actions.push({ action: "create", file_path: resourceBindFile, content: resourceBindContent }) const commit = { branch: "main", commit_message: `Bind Resource`, actions: actions } const url = `https://${input.gitHost}/api/v4/projects/${gitProjectsJson[0].id}/repository/commits`; const result = await fetch(new URL(url), { method: 'POST', body: JSON.stringify(commit), headers: { 'PRIVATE-TOKEN': gitToken, 'Content-Type': 'application/json', }, }); const resultBody = await result.json(); if (result.status > 299) { console.error(`ERROR: Failed to bind ${input.envName}. Response code: ${result.status} - ${resultBody}`); let message = ""; if (resultBody.message?.includes('A file with this name already exists')) { message = `${input.envName} has already been scheduled for binding. Check the CICD pipeline for the most up-to-date information. UI status may take a few minutes to update.`; } else { message = resultBody.message || ''; } return { status: "FAILURE", message }; } else { return { status: "SUCCESS", message: `Binding will not be complete until deployment succeeds. Check the CICD pipeline for the most up-to-date information. UI status may take a few minutes to update.` }; } } else { console.error(`ERROR: Failed to retrieve project ID for ${input.gitRepoName}`); return { status: "FAILURE", message: `Failed to retrieve Git project ID for ${input.gitRepoName}` }; } } public async unBindResource(input: BindResourceParams, gitSecretName: string): Promise<{ status: string, message?: string }> { const gitAdminSecret = await this.getPlatformSecretValue(gitSecretName); const gitAdminSecretObj = JSON.parse(gitAdminSecret.SecretString || ""); const gitToken = gitAdminSecretObj["apiToken"]; // fetch project ID const gitProjects = await fetch(`https://${input.gitHost}/api/v4/projects?search=${input.gitRepoName}`, { method: 'GET', headers: { 'PRIVATE-TOKEN': gitToken, 'Content-Type': 'application/json', } }); const gitProjectsJson: { path_with_namespace: string, id: string }[] = await gitProjects.json(); let project = null; if (gitProjectsJson) { project = gitProjectsJson.filter(project => project.path_with_namespace === `${input.gitProjectGroup}/${input.gitRepoName}`)[0]; } if (project && project.id) { console.log(`Got GitLab project ID: ${gitProjectsJson[0]?.id}`); const actions = input.policies.map(p => { const policyFile = `.iac/aws_ecs/permissions/${input.envName}/${input.providerName}/${p.policyFileName}.json`; const policyContent = p.policyContent; return { action: "delete", file_path: policyFile, content: policyContent }; }) const resourceBindContent = `RESOURCE_ENTITY_REF=${input.resourceEntityRef}\nRESOURCE_ENTITY=${input.resourceName}\nTARGET_ENV_NAME=${input.envName}\nTARGET_ENV_PROVIDER_NAME=${input.providerName}` const resourceBindFile = `.awsdeployment/resource-binding-params-temp.properties`; actions.push({ action: "create", file_path: resourceBindFile, content: resourceBindContent }) const commit = { branch: "main", commit_message: `UnBind Resource`, actions: actions } const url = `https://${input.gitHost}/api/v4/projects/${gitProjectsJson[0].id}/repository/commits`; const result = await fetch(new URL(url), { method: 'POST', body: JSON.stringify(commit), headers: { 'PRIVATE-TOKEN': gitToken, 'Content-Type': 'application/json', }, }); const resultBody = await result.json(); if (result.status > 299) { console.error(`ERROR: Failed to unbind ${input.envName}. Response code: ${result.status} - ${resultBody}`); let message = ""; if (resultBody.message?.includes('A file with this name already exists')) { message = `${input.envName} has already been scheduled for unbinding. Check the CICD pipeline for the most up-to-date information. UI status may take a few minutes to update.`; } else { message = resultBody.message || ''; } return { status: "FAILURE", message }; } else { return { status: "SUCCESS", message: `UnBinding will not be complete until deployment succeeds. Check the CICD pipeline for the most up-to-date information. UI status may take a few minutes to update.` }; } } else { console.error(`ERROR: Failed to retrieve project ID for ${input.gitRepoName}`); return { status: "FAILURE", message: `Failed to retrieve Git project ID for ${input.gitRepoName}` }; } } }
import { DefaultTheme, getThemeStyling } from '../../src/themes'; import { ColorCategories, ColorTokens, ThemeColor, ThemeMapper } from '../../src/types'; const mockedMapper: ThemeMapper = { normal: { background: { category: ColorCategories.primary, inverse: false, token: ColorTokens.token_100, }, color: { category: ColorCategories.fonts, inverse: true, token: ColorTokens.token_150, }, }, }; const mockedMapperWithHover: ThemeMapper = { hover: { background: { category: ColorCategories.primary, inverse: false, token: ColorTokens.token_150, }, }, }; const mockedMapperWithMultipleStates: ThemeMapper = { normal: { background: { category: ColorCategories.primary, inverse: false, token: ColorTokens.token_100, }, }, active: { background: { category: ColorCategories.primary, inverse: false, token: ColorTokens.token_50, }, }, hover: { background: { category: ColorCategories.primary, inverse: false, token: ColorTokens.token_150, }, }, }; describe('getThemeStyling', () => { it('Should get correct styling when is not inverse', () => { const style = getThemeStyling(DefaultTheme, ThemeColor.dark, mockedMapper); expect(style).toContain(`background: ${DefaultTheme.dark.primary.token_100}`); }); it('Should get correct styling when is inverse', () => { const style = getThemeStyling(DefaultTheme, ThemeColor.dark, mockedMapper); expect(style).toContain(`color: ${DefaultTheme.light.fonts.token_150}`); }); it('Should get correct styling when is inverse', () => { const style = getThemeStyling(DefaultTheme, ThemeColor.light, mockedMapper); expect(style).toContain(`color: ${DefaultTheme.dark.fonts.token_150}`); }); it('Should get correct styling when using a state different than normal', () => { const style = getThemeStyling(DefaultTheme, ThemeColor.dark, mockedMapperWithHover); expect(style).toContain(`:hover {\nbackground: ${DefaultTheme.dark.primary.token_150};\n}\n`); }); it('Should get correct styling when using multiple states', () => { const style = getThemeStyling(DefaultTheme, ThemeColor.dark, mockedMapperWithMultipleStates); expect(style).toContain(`background: ${DefaultTheme.dark.primary.token_100}`); expect(style).toContain(`:hover {\nbackground: ${DefaultTheme.dark.primary.token_150};\n}\n`); expect(style).toContain(`:active {\nbackground: ${DefaultTheme.dark.primary.token_50};\n}\n`); }); describe('Incorrect mapper', () => { it('Should NOT break if mapper gets incorrect category', () => { const incorrectMapper = { active: { background: { category: 'INCORRECT-CATEGORY', inverse: false, token: ColorTokens.token_100, }, }, }; // eslint-disable-next-line @typescript-eslint/ban-ts-comment //@ts-ignore const style = getThemeStyling(DefaultTheme, ThemeColor.dark, incorrectMapper); expect(style).toContain(`:active {\n}`); }); it('Should NOT break if mapper does NOT include inverse', () => { const incorrectMapper = { active: { background: { category: 'INCORRECT-CATEGORY', token: ColorTokens.token_100, }, }, }; // eslint-disable-next-line @typescript-eslint/ban-ts-comment //@ts-ignore const style = getThemeStyling(DefaultTheme, ThemeColor.dark, incorrectMapper); expect(style).toContain(`:active {\n}`); }); it('Should NOT break if mapper does NOT include token', () => { const incorrectMapper = { active: { background: { category: 'INCORRECT-CATEGORY', }, }, }; // eslint-disable-next-line @typescript-eslint/ban-ts-comment //@ts-ignore const style = getThemeStyling(DefaultTheme, ThemeColor.dark, incorrectMapper); expect(style).toContain(`:active {\n}`); }); it('Should NOT break if mapper does NOT include styling property', () => { const incorrectMapper = { active: { background: {}, }, }; // eslint-disable-next-line @typescript-eslint/ban-ts-comment //@ts-ignore const style = getThemeStyling(DefaultTheme, ThemeColor.dark, incorrectMapper); expect(style).toContain(`:active {\n}`); }); it('Should NOT break if mapper inclues incorrect styling', () => { const incorrectMapper = { normal: { WHATEVERSTYLE: { category: ColorCategories.primary, inverse: false, token: ColorTokens.token_100, }, }, }; // eslint-disable-next-line @typescript-eslint/ban-ts-comment //@ts-ignore const style = getThemeStyling(DefaultTheme, ThemeColor.dark, incorrectMapper); expect(style).toContain(`WHATEVERSTYLE: ${DefaultTheme.dark.primary.token_100};`); }); it('Should NOT break if mapper gets incorrect category', () => { const incorrectMapper = { WHATEVERCATEGORY: { background: { category: ColorCategories.primary, inverse: false, token: ColorTokens.token_100, }, }, }; // eslint-disable-next-line @typescript-eslint/ban-ts-comment //@ts-ignore const style = getThemeStyling(DefaultTheme, ThemeColor.dark, incorrectMapper); expect(style).toContain(`:WHATEVERCATEGORY {\nbackground: ${DefaultTheme.dark.primary.token_100};\n}\n`); }); it('Should NOT break if mapper does NOT includes styles', () => { const incorrectMapper = { normal: null, }; // eslint-disable-next-line @typescript-eslint/ban-ts-comment //@ts-ignore const style = getThemeStyling(DefaultTheme, ThemeColor.dark, incorrectMapper); expect(style).toContain(``); }); }); });
// RecipeCard.jsx import React from 'react'; const RecipeCard = ({ recipe }) => { return ( <div className="bg-white shadow-lg rounded-lg overflow-hidden hover:shadow-xl transition-transform hover:scale-105"> <div className="relative"> <img className="w-full h-48 object-cover object-center rounded-t-lg" src={recipe.image} alt={recipe.label} /> <div className="absolute top-2 left-2 bg-indigo-500 text-white py-1 px-2 rounded"> {recipe.dishType[0]} </div> </div> <div className="p-4"> <h1 className="text-2xl font-semibold text-gray-800 mb-2 capitalize"> {recipe.label} </h1> <div className="text-gray-600 mb-4"> <span className="block mb-1"> <b>Ingredients:</b> </span> {recipe.ingredientLines.map((ingredient, index) => ( <span key={index} className="block pl-4"> {ingredient} </span> ))} </div> <div className="flex items-center justify-between"> <a href={"/"} target="_blank" rel="noopener noreferrer" className="text-indigo-500 font-semibold hover:underline" > View Recipe </a> <div className="flex items-center text-gray-600"> <span className="flex items-center mr-4"> <svg xmlns="http://www.w3.org/2000/svg" className="h-4 w-4 mr-1" fill="none" viewBox="0 0 24 24" stroke="currentColor" > <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M12 5v14m0 0V5m0 0v14m0-14h14m-14 0H5" /> </svg> 1.2K </span> <span className="flex items-center"> <svg xmlns="http://www.w3.org/2000/svg" className="h-4 w-4 mr-1" fill="none" viewBox="0 0 24 24" stroke="currentColor" > <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M6 18L18 6M6 6l12 12" /> </svg> 6 </span> </div> </div> </div> </div> ); }; export default RecipeCard;
<?php namespace App\GraphQL\Mutation; use GraphQL\Type\Definition\Type; use GraphQL\Type\Definition\ResolveInfo; use Folklore\GraphQL\Relay\Support\Mutation as BaseMutation; use GraphQL; use App\Project; class UpdateProjectMutation extends BaseMutation { protected $attributes = [ 'name' => 'UpdateProjectMutation', 'description' => 'A relay mutation' ]; protected function inputType() { return Type::nonNull(GraphQL::type("UpdateProjectInput")); } protected function type() { return GraphQL::type("UpdateProjectPayload"); } protected function rules() { return [ "input.id" => [ "required" ] ]; } public function resolve($root, $args, $context, ResolveInfo $info) { $input = $args['input']; $project = Project::findByNodeId($input['id']); $project->fill($input); $project->save(); } }
import InfoPage from "../components/InfoPage"; import { Pressable, View, Text } from "react-native"; import { Camera, CameraCapturedPicture, CameraType } from "expo-camera"; import { useRef, useState } from "react"; import { useUser } from "@clerk/clerk-expo"; import supabase from "../hooks/initSupabase"; import { manipulateAsync, FlipType, SaveFormat } from "expo-image-manipulator"; import { Image } from "expo-image"; import * as ImagePicker from "expo-image-picker"; import { Ionicons } from "@expo/vector-icons"; import colours from "../styles/colours"; import AsyncStorage from "@react-native-async-storage/async-storage"; import { decode } from "base64-arraybuffer"; import { Snackbar } from "react-native-paper"; import { CacheManager } from "@georstat/react-native-image-cache"; const SetProfilePicture = ({ navigation }) => { const userID = useUser().user.id; let cameraRef = useRef<Camera>(null); const [loading, setLoading] = useState(false); const [content, setContent] = useState(""); const [hasPermission, setHasPermission] = useState(false); const [type, setType] = useState(CameraType.front); const [photo, setPhoto] = useState<CameraCapturedPicture | undefined>( undefined ); return ( <InfoPage header={"Now,"} secondary={"Choose your profile picture."} action={ <View style={{ alignItems: "center", gap: 20, }} > <Pressable style={{ backgroundColor: colours.chordleMyBallsKraz, borderRadius: 25, width: "70%", height: 55, alignItems: "center", justifyContent: "center", }} onPress={async () => { if (!photo && !hasPermission) { const c = await Camera.requestCameraPermissionsAsync(); setHasPermission(c.status === "granted"); } if (!photo && hasPermission) { setPhoto( await cameraRef.current?.takePictureAsync({ base64: true, }) ); } else if (photo) { setContent("Uploading..."); setLoading(true); const path = `${userID}.jpg`; if (type === CameraType.front) { const manipResult = await manipulateAsync( photo.uri, [{ flip: FlipType.Horizontal }], { format: SaveFormat.JPEG, base64: true } ); setPhoto(manipResult); } const { error } = await supabase.storage .from("profile_pictures") .upload(`public/${path}`, decode(photo.base64), { upsert: true, }); // update user profile picture path in the user row if (!error) { await supabase .from("users") .update({ profile_picture: `https://ucjolalmoughwxjvuxkn.supabase.co/storage/v1/object/public/profile_pictures/public/${path}`, }) .eq("uid", userID); await AsyncStorage.setItem( "profile-picture-url", `https://ucjolalmoughwxjvuxkn.supabase.co/storage/v1/object/public/profile_pictures/public/${path}` ); // cache profile picture url CacheManager.clearCache(); // remove old cached profile picture navigation.navigate("Home"); } if (error) { console.log(error); } } }} > <Text style={{ color: "white", fontSize: 16, fontWeight: "600", }} > {!photo ? "Take Picture" : "Submit"} </Text> </Pressable> <Pressable style={{ borderRadius: 25, width: "70%", height: 55, alignItems: "center", justifyContent: "center", borderColor: colours.chordleMyBallsKraz, borderWidth: 3, }} onPress={async () => { setContent("Processing..."); setLoading(true); let result = await ImagePicker.launchImageLibraryAsync({ mediaTypes: ImagePicker.MediaTypeOptions.Images, allowsEditing: true, aspect: [4, 3], quality: 1, base64: true, }); setType(CameraType.back); // set to back camera to prevent flip on image render if (!result.canceled) { setPhoto(result.assets[0]); } }} > <Text style={{ fontSize: 16, fontWeight: "500", }} > Browse photos </Text> </Pressable> <Snackbar visible={loading} onDismiss={() => setLoading(false)} action={{ label: "Dismiss", onPress: () => { setLoading(false); }, }} > {loading && content ? content : "Uploaded!"} </Snackbar> </View> } > <View style={{ flex: 1, alignItems: "center", justifyContent: "center", }} > {hasPermission && !photo ? ( <View style={{ flex: 1, width: "100%", flexDirection: "column", alignItems: "center", justifyContent: "center", }} > <Camera ref={cameraRef} type={type} style={{ width: 269, height: 269, backgroundColor: "#D9D9D9", borderRadius: 10, marginBottom: 20, }} /> <Pressable onPress={() => { setType( type == CameraType.front ? CameraType.back : CameraType.front ); }} > <Ionicons name="ios-camera-reverse" size={24} color="black" /> </Pressable> </View> ) : photo ? ( <> <Image source={{ uri: photo.uri }} style={{ width: 269, height: 269, backgroundColor: "#D9D9D9", borderRadius: 10, marginBottom: 20, }} /> <Pressable onPress={() => { setPhoto(undefined); }} style={{ backgroundColor: "rgba(0,0,0,0.5)", borderRadius: 25, paddingHorizontal: 20, paddingVertical: 10, }} > <Text style={{ color: "white", }} > Retake </Text> </Pressable> </> ) : ( <View style={{ width: 269, height: 269, backgroundColor: "#D9D9D9", borderRadius: 10, marginBottom: 20, }} ></View> )} </View> </InfoPage> ); }; export default SetProfilePicture;
<span class="com">/* The Computer Language Shootout</span> <span class="com"> http://shootout.alioth.debian.org/</span> <span class="com"> contributed by Isaac Gouy</span> <span class="com">*/</span> <span class="kwa">import</span> scala<span class="sym">.</span>concurrent<span class="sym">.</span>_ <span class="kwa">object</span> message <span class="sym">{</span> <span class="kwa">def</span> main<span class="sym">(</span>args<span class="sym">:</span> <span class="kwc">Array</span><span class="sym">[</span><span class="kwc">String</span><span class="sym">]) = {</span> <span class="kwa">val</span> n <span class="sym">=</span> <span class="kwc">Integer</span><span class="sym">.</span>parseInt<span class="sym">(</span>args<span class="sym">(</span><span class="num">0</span><span class="sym">))</span> <span class="kwa">val</span> nActors <span class="sym">=</span> <span class="num">500</span> <span class="kwa">val</span> finalSum <span class="sym">=</span> n <span class="sym">*</span> nActors <span class="kwa">case class</span> Message<span class="sym">(</span>value<span class="sym">:</span> Int<span class="sym">)</span> <span class="kwa">class</span> Incrementor<span class="sym">(</span>next<span class="sym">:</span> Pid<span class="sym">)</span> <span class="kwa">extends</span> Actor <span class="sym">{</span> <span class="kwa">var</span> sum <span class="sym">=</span> <span class="num">0</span> <span class="kwa">override def</span> run<span class="sym">() = {</span> <span class="kwa">while</span> <span class="sym">(</span>true<span class="sym">) {</span> receive <span class="sym">{</span> <span class="kwa">case</span> Message<span class="sym">(</span>value<span class="sym">) =&gt;</span> <span class="kwa">val</span> j <span class="sym">=</span> value <span class="sym">+</span> <span class="num">1</span> <span class="kwa">if</span> <span class="sym">(</span>null <span class="sym">!=</span> next<span class="sym">){</span> next <span class="sym">!</span> Message<span class="sym">(</span>j<span class="sym">)</span> <span class="sym">}</span> <span class="kwa">else</span> <span class="sym">{</span> sum <span class="sym">=</span> sum <span class="sym">+</span> j <span class="kwa">if</span> <span class="sym">(</span>sum <span class="sym">&gt;=</span> finalSum<span class="sym">){</span> Console<span class="sym">.</span>println<span class="sym">(</span>sum<span class="sym">);</span> <span class="kwc">System</span><span class="sym">.</span>exit<span class="sym">(</span><span class="num">0</span><span class="sym">)</span> <span class="slc">// exit without cleaning up</span> <span class="sym">}</span> <span class="sym">}</span> <span class="sym">}</span> <span class="sym">}</span> <span class="sym">}</span> <span class="kwa">def</span> pid<span class="sym">() = {</span> <span class="kwa">this</span><span class="sym">.</span>start<span class="sym">;</span> <span class="kwa">this</span><span class="sym">.</span>self <span class="sym">}</span> <span class="sym">}</span> <span class="kwa">def</span> actorChain<span class="sym">(</span>i<span class="sym">:</span> Int<span class="sym">,</span> a<span class="sym">:</span> Pid<span class="sym">):</span> Pid <span class="sym">=</span> <span class="kwa">if</span> <span class="sym">(</span>i <span class="sym">&gt;</span> <span class="num">0</span><span class="sym">)</span> actorChain<span class="sym">(</span>i<span class="sym">-</span><span class="num">1</span><span class="sym">,</span> <span class="kwa">new</span> Incrementor<span class="sym">(</span>a<span class="sym">).</span>pid <span class="sym">)</span> <span class="kwa">else</span> a <span class="kwa">val</span> firstActor <span class="sym">=</span> actorChain<span class="sym">(</span>nActors<span class="sym">,</span> null<span class="sym">)</span> <span class="kwa">var</span> i <span class="sym">=</span> n<span class="sym">;</span> <span class="kwa">while</span> <span class="sym">(</span>i <span class="sym">&gt;</span> <span class="num">0</span><span class="sym">){</span> firstActor <span class="sym">!</span> Message<span class="sym">(</span><span class="num">0</span><span class="sym">);</span> i <span class="sym">=</span> i<span class="sym">-</span><span class="num">1</span> <span class="sym">}</span> <span class="sym">}</span> <span class="sym">}</span>
<!DOCTYPE HTML> <!-- Solid State by HTML5 UP html5up.net | @ajlkn Free for personal and commercial use under the CCA 3.0 license (html5up.net/license) --> <html> <head> <title>AI-Learning - Objective-C Section 7</title> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no" /> <link rel="stylesheet" href="/assets/css/main.css" /> <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/10.7.2/styles/dracula.min.css"> <noscript> <link rel="stylesheet" href="/assets/css/noscript.css" /> </noscript> </head> <body class="is-preload"> <!-- Page Wrapper --> <div id="page-wrapper"> <!-- Header --> <header id="header" class="alt" style="display: flex; align-items: center;"> <a href="/index.html" style="text-decoration: none; border: none; outline: none;"> <img src="/images/ai-learning-logo.svg" alt="Votre Logo" style="display: block; border: none;"> </a> <nav> <a href="#menu">Menu</a> </nav> </header> <!-- Menu --> <nav id="menu"> <div class="inner"> <h2>Menu</h2> <ul class="links"> <li><a href="/index.html">Accueil</a></li> <li><a href="/courses.html">Formations</a></li> <li><a href="/ai-learning.html">Qu'est ce qu'AI-Learning ?</a></li> <li><a href="/generation.html">Comment sont générées nos formations ?</a></li> <li><a href="/research.html">Travail de recherche</a></li> </ul> <a href="#" class="close">Close</a> </div> </nav> <!-- Wrapper --> <section id="wrapper"> <header> <div class="inner"> <h2>Section 7: Débogage et optimisation</h2> <ul class="actions stacked"> <li><a href="/AI-Learning/objective-c/objective-c.html" class="button"> Revenir à la fiche du cours</a></li> </ul> </div> </header> <!-- Content --> <div class="wrapper"> <div class="inner"> <ul class="actions"> <li><a href="/AI-Learning/objective-c/sections/section6.html" class="button primary"> Section précédente</a></li> <li><a href="/AI-Learning/objective-c/sections/section8.html" class="button primary" id="last"> Section suivante</a></li> </ul> <h2>Les outils de débogage intégrés</h2> <p>Objective-C offre plusieurs outils de débogage intégrés qui peuvent être utilisés pour identifier et résoudre les erreurs dans votre code. Ces outils vous permettent de suivre l'exécution de votre programme, d'inspecter les variables et de mettre en place des points d'arrêt pour arrêter l'exécution à des endroits spécifiques.</p> <p>L'un des outils de débogage les plus couramment utilisés est le débogueur Xcode. Xcode offre une interface conviviale qui vous permet de suivre l'exécution de votre programme ligne par ligne, de visualiser les valeurs des variables et d'inspecter les objets en cours d'exécution. Vous pouvez également mettre en place des points d'arrêt pour arrêter l'exécution à des endroits spécifiques et examiner l'état du programme à ce moment-là.</p> <p>Un autre outil de débogage intégré est l'analyseur statique d'Xcode. Cet outil vous permet de détecter les erreurs potentielles dans votre code avant même de l'exécuter. L'analyseur statique vérifie votre code pour des problèmes tels que les fuites de mémoire, les accès non valides aux tableaux et les variables non initialisées.</p> <h2>Techniques de débogage avancées</h2> <p>En plus des outils de débogage intégrés, il existe plusieurs techniques avancées que vous pouvez utiliser pour résoudre les problèmes plus complexes dans votre code Objective-C.</p> <p>Une technique courante est l'utilisation de journaux de débogage. Les journaux de débogage sont des messages que vous pouvez imprimer à différents endroits de votre code pour suivre l'exécution et vérifier les valeurs des variables. Vous pouvez utiliser la fonction NSLog pour imprimer des messages de débogage dans la console d'exécution.</p> <p>Une autre technique utile est la mise en place de points d'arrêt conditionnels. Les points d'arrêt conditionnels vous permettent de spécifier une condition qui doit être remplie pour que l'exécution s'arrête à un point donné. Cela peut être utile lorsque vous voulez examiner l'état du programme uniquement dans certaines situations.</p> <p>Enfin, l'utilisation de l'analyseur de performances d'Instruments peut vous aider à identifier les goulots d'étranglement et les problèmes de performance dans votre code. L'analyseur de performances vous permet de surveiller l'utilisation de la mémoire, le temps d'exécution et d'autres métriques importantes pour optimiser les performances de votre application.</p> <h2>Profilage et optimisation des performances</h2> <p>Une fois que vous avez identifié les problèmes de performance dans votre code, vous pouvez utiliser des techniques de profilage et d'optimisation pour les résoudre.</p> <p>Le profilage consiste à mesurer les performances de votre application et à identifier les parties du code qui prennent le plus de temps d'exécution. Vous pouvez utiliser l'outil de profilage d'Instruments pour collecter des données de performance et analyser les résultats pour trouver les zones à problèmes.</p> <p>Une fois que vous avez identifié les zones à problèmes, vous pouvez utiliser différentes techniques d'optimisation pour améliorer les performances. Cela peut inclure l'utilisation de structures de données plus efficaces, l'optimisation des boucles et des algorithmes, et la réduction de l'utilisation de la mémoire.</p> <p>Il est important de noter que l'optimisation des performances doit être basée sur des mesures réelles et ne doit être effectuée que lorsque cela est nécessaire. Il est préférable de se concentrer d'abord sur l'écriture d'un code propre et lisible, puis d'optimiser les parties critiques du code si nécessaire.</p> <ul class="actions"> <li><a href="/AI-Learning/objective-c/sections/section6.html" class="button primary"> Section précédente</a></li> <li><a href="/AI-Learning/objective-c/sections/section8.html" class="button primary" id="last"> Section suivante</a></li> </ul> </div> </div> </section> <!-- Footer --> <section id="footer"> <div class="inner"> <ul class="copyright"> <li>&copy; Untitled Inc. All rights reserved.</li> <li>Design: <a href="http://html5up.net">HTML5 UP</a></li> </ul> </div> </section> </div> <!-- Scripts --> <script src="/assets/js/jquery.min.js"></script> <script src="/assets/js/jquery.scrollex.min.js"></script> <script src="/assets/js/browser.min.js"></script> <script src="/assets/js/breakpoints.min.js"></script> <script src="/assets/js/util.js"></script> <script src="/assets/js/main.js"></script> <script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/10.7.2/highlight.min.js"></script> <script>hljs.highlightAll();</script> </body> </html>
//description - given the root of a tree, return the level order traversal of its node's values (from left to right, level by level) //params - {TreeNode} root //return - {number[][]} //solution - initialize an array to hold the result, check if the root is null and if yes return result as is, initialize another array called queue and asign the root inside of the queue, write a while loop that runs as long as the queue is not empty (to represent each level), initialize another array and call it current, create a var called levelSize that will be used to represent the size of each level (either 1 or 2), now write a for loop that runs levelSize times (for the amount of nodes in that level), grab the first node of the queue and place it inside of current, check if that node has a right node then left node and if yes push it to the queue, at the end of the while loop push the current array to the result array (which will contain each level in its own array), return the result class TreeNode { constructor(val) { this.val = val; this.left = null; this.right = null; } } function levelOrderTraversal(root) { // Create an array to store the result const result = []; // Check if the root is null (empty tree) if (!root) { return result; } // Create a queue to perform level-order traversal const queue = [root]; // Continue traversal while the queue is not empty while (queue.length > 0) { const current = []; // Initialize an array to store values of the current level const levelSize = queue.length; // Get the number of nodes at the current level // Process nodes at the current level for (let i = 0; i < levelSize; i++) { const node = queue.shift(); // Remove the first node from the queue current.push(node.val); // Add the value to the current level array // Enqueue the left and right children (if they exist) if (node.left) { queue.push(node.left); } if (node.right) { queue.push(node.right); } } result.push(current); // Add the current level array to the result } // Return the level order traversal result return result; } // Example usage: const root = new TreeNode(3); root.left = new TreeNode(9); root.right = new TreeNode(20); root.right.left = new TreeNode(15); root.right.right = new TreeNode(7); const traversalResult = levelOrderTraversal(root); console.log(traversalResult);
import React, { useEffect, useState } from "react"; import axios from "axios"; import { toast } from "react-toastify"; import { Link, useNavigate } from "react-router-dom"; import { useDispatch, useSelector } from "react-redux"; import { authorizeUser, userSelector } from "../redux/userReducer"; const SignUpForm = () => { const { loggedInUser } = useSelector(userSelector); const dispatch = useDispatch(); const navigate = useNavigate(); const [formData, setFormData] = useState({ identifier: "", password: "", termsAccepted: false, }); const [showPassword, setShowPassword] = useState(false); useEffect(() => { dispatch(authorizeUser()); }, [loggedInUser]); const handleChange = (e) => { const { name, value, checked, type } = e.target; setFormData((prevFormData) => ({ ...prevFormData, [name]: type === "checkbox" ? checked : value, })); }; const handleSubmit = async () => { try { const { data } = await axios.post("/api/v1/user/sign-up", formData); if (data.success) { if (data.firstTime) { toast.success(data.message); return; } toast.success(data.message); localStorage.setItem("loggedInUser", JSON.stringify(data.user)); navigate("/user/posts"); } else { toast.error(data.message); } } catch (error) { toast.error("Something went wrong !"); } }; const togglePasswordVisibility = () => { setShowPassword(!showPassword); }; const isTermsAccepted = () => formData.termsAccepted; return ( <div className="parentContainer bg-gradient-to-tr from-[#212529] to-[#6C757D] w-screen min-h-screen flex flex-col justify-around items-center "> <div className="w-full p-4 md:p-0 md:w-2/3 lg:w-1/3 "> <h2 className="text-3xl font-semibold mb-4">Sign Up or Sign In </h2> <div className="mb-4"> <label htmlFor="identifier" className="block mb-1"> Email or Username </label> <input type="text" id="identifier" name="identifier" value={formData.identifier} onChange={handleChange} placeholder="Enter your email or username" required className="w-full px-4 py-2 border rounded-md" /> </div> <div className="mb-4 relative"> <label htmlFor="password" className="block mb-1"> Password </label> <input type={showPassword ? "text" : "password"} id="password" name="password" value={formData.password} onChange={handleChange} placeholder="Enter your password" required className="w-full px-4 py-2 border rounded-md" /> <button type="button" className="absolute inset-y-0 right-0 px-3 py-8 text-gray-600" onClick={togglePasswordVisibility} > {showPassword ? "Hide" : "Show"} </button> </div> <div className="mb-4"> <label htmlFor="termsAccepted" className="flex items-center"> <input type="checkbox" id="termsAccepted" name="termsAccepted" checked={formData.termsAccepted} onChange={handleChange} className="mr-2 h-6 w-6 rounded border-gray-300 focus:ring-indigo-500 transition-all duration-300 ease-in-out" /> <span className="text-lg transition-all duration-300 ease-in-out"> I accept the terms and conditions </span> </label> </div> <div className="w-full flex justify-center items-center"> <button className={`bg-[#cb4154] transition-all duration-200 ease-in-out text-white px-4 py-2 rounded-md ${ !isTermsAccepted() && "opacity-50 cursor-not-allowed" }`} onClick={handleSubmit} disabled={!isTermsAccepted()} > Sign Up </button> </div> <div> <Link to={"/reset-password"}>Forgotten Password ?</Link> </div> </div> </div> ); }; export default SignUpForm;
// Radix sort is a special sorting algorithm that works on lists of numbers // It exploits the fact that information about the size of a number is encoded in the number of digits. // More digits means a bigger number! // radix helper functions function getDigit(num, i) { return Math.floor(Math.abs(num) / Math.pow(10, i)) % 10; } // console.log("hello", getDigit(1323, 4)); function digitCount(num) { if (num === 0) return 1; return Math.floor(Math.log10(Math.abs(num))) + 1; } // console.log(digitCount(13232)); function mostDigits(nums) { let maxDigits = 0; for (let i = 0; i < nums.length; i++) { maxDigits = Math.max(maxDigits, digitCount(nums[i])); } return maxDigits; } // console.log(mostDigits([13232, 23, 12, 32])); function radixSort(nums) { let maxDigitCount = mostDigits(nums); for (let k = 0; k < maxDigitCount; k++) { let digitBuckets = Array.from({ length: 10 }, () => []); for (let i = 0; i < nums.length; i++) { let digit = getDigit(nums[i], k); digitBuckets[digit].push(nums[i]); } nums = [].concat(...digitBuckets); } return nums; } radixSort([23, 345, 5467, 12, 2345, 9852]);
<ul [class]="NavbarType" [id]="NavbarId"> <li> <div class="user-info"> <div class="row"> <div class="col l4 valign-wrapper"> <img src="assets/images/boy.svg" alt="" class="circle red"> </div> </div> <div class="row"> <div class="col l8"> <ul> <li class="user-name">{{guestName}}</li> <li class="user-room">Habitación {{guestRoom}}</li> </ul> </div> </div> </div> </li> <li> <ul class="collapsible"> <ng-template ngFor let-list [ngForOf]="itemsLists"> <li *ngFor="let mainItem of list"> <ng-container [ngSwitch]="mainItem.type"> <div *ngSwitchCase="'divider'" class="divider"></div> <li *ngSwitchCase="'divider-title'"><a class="subheader">{{mainItem.name}}</a></li> <ng-container *ngSwitchCase="'item'"> <div (click)="onSelect(mainItem.navParams)" class="collapsible-header"> <i class="material-icons">{{mainItem.icon}}</i>{{mainItem.name}} </div> <div class="collapsible-body"> <ul class="collapsible" *ngIf="true"> <li *ngFor="let item of mainItem.items"> <div (click)="onSelect(item.navParams)" class="collapsible-header"> <span>{{item.name}}</span> </div> <div class="collapsible-body"> <ul class="collapsible" *ngIf="true"> <li *ngFor="let subitem of item.subItems"> <div (click)="onSelect(subitem.navParams)" class="collapsible-header"> <span>{{subitem.name}}</span> </div> <div class="collapsible-body"></div> </li> </ul> </div> </li> </ul> </div> </ng-container> </ng-container> </li> </ng-template> </ul> </li> </ul>
import React from "react"; import { Route, Routes } from "react-router-dom"; import axios from "axios"; import { Drawer } from "./components/Drawer"; import { Header } from "./components/Header"; import { Home } from "./pages/Home"; import { Favorites } from "./pages/Favorites"; import { Orders } from "./pages/Orders"; import AppContext from "./context"; export function App() { const [items, setItems] = React.useState([]) const [cartItems, setCartItems] = React.useState([]) const [favorites, setFavorites] = React.useState([]) const [searchValue, setSearchValue] = React.useState('') const [cartOpened, setCartOpened] = React.useState(false); const [isLoading, setIsLoading] = React.useState(true); React.useEffect(() => { // fetch('https://6290ab25665ea71fe13810d5.mockapi.io/items') // .then((res) => { // return res.json(); // }) // .then((json) => { // setItems(json) // }); async function fetchData() { try { const [cartResponse, favoritesResponse, itemsResponse] = await Promise.all([ axios.get('https://6290ab25665ea71fe13810d5.mockapi.io/cart'), axios.get('https://6290ab25665ea71fe13810d5.mockapi.io/favorites'), axios.get('https://6290ab25665ea71fe13810d5.mockapi.io/items') ]) setIsLoading(false) setCartItems(cartResponse.data) setFavorites(favoritesResponse.data) setItems(itemsResponse.data) } catch (error) { alert('Ошибка при запросе данных') console.error(error) } } fetchData() }, []); const onAddToCart = async (obj) => { try { const findItem =cartItems.find((item) => Number(item.parentId) === Number(obj.id)) if (findItem) { setCartItems((prev) => prev.filter((item) => Number(item.parentId) !== Number(obj.id))) await axios.delete(`https://6290ab25665ea71fe13810d5.mockapi.io/cart/${findItem.id}`) } else { setCartItems((prev) => [...prev, obj]) const { data } = await axios.post('https://6290ab25665ea71fe13810d5.mockapi.io/cart', obj) setCartItems((prev) => prev.map(item => { if (item.parentId === data.parentId) { return { ...item, id: data.id } } return item })) } } catch (error) { alert('Ошибка при добавления в корзину') console.error(error) } } const onRemoveItem = (id) => { try { axios.delete(`https://6290ab25665ea71fe13810d5.mockapi.io/cart/${id}`) setCartItems((prev) => prev.filter((item) => Number(item.id) !== Number(id))) } catch (error) { alert('Ошибка при удалении из корзины') console.error(error) } } const onAddToFavorite = async (obj) => { try { if (favorites.find(favObj => Number(favObj.id) === Number(obj.id))) { axios.delete(`https://6290ab25665ea71fe13810d5.mockapi.io/favorites/${obj.id}`) setFavorites((prev) => prev.filter((item) => Number(item.id) !== Number(obj.id))) } else { const { data } =await axios.post(`https://6290ab25665ea71fe13810d5.mockapi.io/favorites`, obj) setFavorites((prev) => [...prev, data]) } } catch (error) { alert('Не удалось добавить в фавриты') console.error(error) } } const onChangeSearchInput = (event) => { setSearchValue(event.target.value) } const isItemAdded = (id) => { return cartItems.some(obj => Number(obj.parentId) === Number(id)) } return ( <AppContext.Provider value={{ items, cartItems, favorites, isItemAdded, onAddToFavorite, onAddToCart, setCartOpened, setCartItems }}> <div className="wrapper clear"> {/* { cartOpened && ( */} <Drawer items={cartItems} onClose={() => setCartOpened(false)} onRemove={onRemoveItem} opened={cartOpened} /> {/* )} */} <Header onClickCart={() => setCartOpened(true)} /> <Routes> <Route exact path='/' element={ <Home items={items} cartItems={cartItems} searchValue={searchValue} setSearchValue={setSearchValue} onChangeSearchInput={onChangeSearchInput} onAddToFavorite={onAddToFavorite} onAddToCart={onAddToCart} isLoading={isLoading} /> } /> <Route exact path='/favorites' element={ <Favorites /> } /> <Route exact path='/orders' element={ <Orders /> } /> </Routes> </div> </AppContext.Provider> ); }
import React from "react"; import { screen, waitFor } from "@testing-library/react"; import userEvent from "@testing-library/user-event"; import renderWithRouterAndRedux from "./renderWithRouterAndRedux"; import App from '../../App'; describe('Teste se a página Login', () => { it('Teste se a página contem inputs', () => { renderWithRouterAndRedux(<App />); const inputName = screen.getByRole('textbox', { name: /nome/i}); const inputEmail = screen.getByRole('textbox', { name: /e\-mail/i}); expect(inputEmail).toBeInTheDocument(); expect(inputName).toBeInTheDocument(); }); it('Test if after clicking the play button, it redirects to the game page', async () => { const { history } = renderWithRouterAndRedux(<App />); const inputName = screen.getByTestId('input-player-name'); const inputEmail = screen.getByTestId('input-gravatar-email'); const buttonPlay = screen.getByRole('button', { name: /play/i}) userEvent.type(inputName, "teste"); userEvent.type(inputEmail, "[email protected]"); userEvent.click(buttonPlay); const count = await screen.findByText('0'); expect(count).toBeInTheDocument(); await waitFor(() => { const { location: { pathname } } = history; expect(pathname).toBe('/game'); }) }); it('Testa se é redirecionado para a página settings', () => { const { history } = renderWithRouterAndRedux(<App />); const settingsBtn = screen.getByRole('button', { name: /settings/i}); userEvent.click(settingsBtn); const { location: { pathname } } = history; expect(pathname).toBe('/configuracoes'); }) });