text
stringlengths
184
4.48M
using System; using System.Diagnostics; using System.Threading.Tasks; using NBomber.Contracts; using NBomber.CSharp; using NUnit.Framework; using RedisBloom.Extensions; namespace RedisBloom.LoadTests { [TestFixture] public class BloomFilterScenarios : BaseTest { private static IStep CheckExistenceStep => Step.Create("check-existence", async context => { var guid = Guid.NewGuid().ToString(); var isExists = await Database.ExistsInBloomFilterAsync(BloomFilterCfg.Name, guid); return isExists ? Response.Fail() : Response.Ok(); }); private static IStep InsertGuidsStep => Step.Create("insert-guids", async context => { var guid = Guid.NewGuid().ToString(); await Database.InsertToBloomFilterAsync(BloomFilterCfg.Name, guid); return Response.Ok(); }); private static Scenario InsertionScenario(int threads, TimeSpan duration) => ScenarioBuilder .CreateScenario("insertion-scenario", InsertGuidsStep) .WithLoadSimulations(LoadSimulation.NewKeepConstant(threads, duration)) .WithoutWarmUp(); private static Scenario CheckExistenceScenario(int threads, TimeSpan duration) => ScenarioBuilder .CreateScenario("check-existence-scenario", CheckExistenceStep) .WithLoadSimulations(LoadSimulation.NewKeepConstant(threads, duration)) .WithoutWarmUp(); [SetUp] public async Task SetUpAsync() { await ReserveBloomFilterAsync(); } [Test] public async Task Insertion_And_CheckExistence_Simultaneously_Scenario() { NBomberRunner .RegisterScenarios ( InsertionScenario(200, TimeSpan.FromSeconds(5)), CheckExistenceScenario(200, TimeSpan.FromSeconds(5)) ) .Run(); await PrintDebugInfoAsync(); } [Test] public async Task Insertion_Then_CheckExistence_Sequentially_Scenario() { NBomberRunner .RegisterScenarios ( InsertionScenario(200, TimeSpan.FromMinutes(10)) ) .Run(); NBomberRunner .RegisterScenarios ( CheckExistenceScenario(200, TimeSpan.FromMinutes(5)) ) .Run(); await PrintDebugInfoAsync(); } [Test] public async Task Insertion_Then_Insertion_And_CheckExistence_Sequentially_Scenario() { NBomberRunner .RegisterScenarios ( InsertionScenario(200, TimeSpan.FromMinutes(15)) ) .Run(); NBomberRunner .RegisterScenarios ( InsertionScenario(5, TimeSpan.FromMinutes(20)), CheckExistenceScenario(300, TimeSpan.FromMinutes(20)) ) .Run(); await PrintDebugInfoAsync(); } private async Task PrintDebugInfoAsync() { var debugInfo = await Database.DebugInfoFromBloomFilterAsync(BloomFilterCfg.Name); Console.WriteLine($"\n\n> BF.DEBUG {BloomFilterCfg.Name} \n{debugInfo}"); } [TearDown] public void TearDown() => base.Dispose(); } }
use defguard::{ auth::failed_login::FailedLoginMap, config::{Command, DefGuardConfig}, db::{init_db, AppEvent, GatewayEvent, Settings, User}, grpc::{run_grpc_server, GatewayMap, WorkerState}, init_dev_env, init_vpn_location, logging, mail::{run_mail_handler, Mail}, run_web_server, wireguard_stats_purge::run_periodic_stats_purge, SERVER_CONFIG, }; use secrecy::ExposeSecret; use std::{ fs::read_to_string, sync::{Arc, Mutex}, }; use tokio::sync::{broadcast, mpsc::unbounded_channel}; #[tokio::main] async fn main() -> Result<(), anyhow::Error> { if dotenvy::from_filename(".env.local").is_err() { dotenvy::dotenv().ok(); } let config = DefGuardConfig::new(); logging::init(&config.log_level, &config.log_file)?; SERVER_CONFIG.set(config.clone())?; let pool = init_db( &config.database_host, config.database_port, &config.database_name, &config.database_user, config.database_password.expose_secret(), ) .await; // handle optional subcommands if let Some(command) = &config.cmd { match command { Command::InitDevEnv => { init_dev_env(&config).await; } Command::InitVpnLocation(args) => { let token = init_vpn_location(&pool, args).await?; println!("{token}"); } }; // return early return Ok(()); } log::debug!("Starting defguard server with config: {config:?}"); if config.openid_signing_key.is_some() { log::info!("Using RSA OpenID signing key"); } else { log::info!("Using HMAC OpenID signing key"); } let (webhook_tx, webhook_rx) = unbounded_channel::<AppEvent>(); let (wireguard_tx, _wireguard_rx) = broadcast::channel::<GatewayEvent>(256); let (mail_tx, mail_rx) = unbounded_channel::<Mail>(); let worker_state = Arc::new(Mutex::new(WorkerState::new(webhook_tx.clone()))); let gateway_state = Arc::new(Mutex::new(GatewayMap::new())); // initialize admin user User::init_admin_user(&pool, config.default_admin_password.expose_secret()).await?; // initialize default settings Settings::init_defaults(&pool).await?; // read grpc TLS cert and key let grpc_cert = config .grpc_cert .as_ref() .and_then(|path| read_to_string(path).ok()); let grpc_key = config .grpc_key .as_ref() .and_then(|path| read_to_string(path).ok()); // initialize failed login attempt tracker let failed_logins = FailedLoginMap::new(); let failed_logins = Arc::new(Mutex::new(failed_logins)); // run services tokio::select! { _ = run_grpc_server(&config, Arc::clone(&worker_state), pool.clone(), Arc::clone(&gateway_state), wireguard_tx.clone(), mail_tx.clone(), grpc_cert, grpc_key, failed_logins.clone()) => (), _ = run_web_server(&config, worker_state, gateway_state, webhook_tx, webhook_rx, wireguard_tx, mail_tx, pool.clone(), failed_logins) => (), _ = run_mail_handler(mail_rx, pool.clone()) => (), _ = run_periodic_stats_purge(pool, config.stats_purge_frequency.into(), config.stats_purge_threshold.into()), if !config.disable_stats_purge => (), }; Ok(()) }
// SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC721/ERC721Burnable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; //nft contract Hero is Ownable, ERC721Burnable { using SafeMath for uint256; uint public maxSupply; uint public maxSpecies; //物种数量 mapping(address => bool) public minters; uint public tokenId; struct Hero { uint id; uint level; //nft 等级 uint kind; // 1 = produce 2= boat 3= double 1= 货物生产英雄 2= 船只加速英雄 3 = 双栖 } mapping(uint => uint[]) public speciesAttributes; mapping(uint => uint[]) public boatAttributes; struct Property { uint id; uint goods_level; uint sail_level; bool is_goods_accelerate; bool is_sail_accelerate; } mapping(address => bool) public operators; mapping(uint => Property) public properties; //根据token id查询对应nft的等级和类型属性 mapping(uint => Hero) public heroes; //1 名字是 MetaLine Hero(MHERO) 注意大小写 constructor() public ERC721("MetaLine Hero", "MHERO") { maxSupply = 1000000; minters[msg.sender] = true; } //mint出新英雄,通过盲盒抽 function safeMint(address _to, uint _level, uint _kind) public onlyMinter { require(tokenId < maxSupply, " > max"); tokenId++; _safeMint(_to, tokenId); heroes[tokenId] = Hero(tokenId, _level, _kind); } function setProperty(uint _id, uint _goods_level, uint _sail_level, bool _is_goods_accelerate, bool _is_sail_accelerate) external onlyMinter { properties[_id] = Property(_id, _goods_level, _sail_level, _is_goods_accelerate, _is_sail_accelerate); } function setBaseUri(string calldata _uri) external onlyOwner { _setBaseURI(_uri); } function setMinter(address _addr, bool _bool) public onlyOwner { minters[_addr] = _bool; } function setMaxSupply(uint _max) external onlyOwner { maxSupply = _max; } function setMaxSpecies(uint _max) external onlyOwner { maxSpecies = _max; } modifier onlyMinter() { require(minters[msg.sender], "!minter"); _; } modifier onlyOperator(){ require(operators[msg.sender], "!o"); _; } function modifyHero(uint256 _tokenId,uint256 _level, uint256 _kind) external onlyOperator{ heroes[_tokenId] = Hero(_tokenId, _level, _kind); } //获取某个地址所有nft属性(等级和类型) function getTotalHeroes(address _account, uint begin, uint end) public view returns (Hero[] memory) { uint _len = end - begin; Hero[] memory _heroes = new Hero[](_len); for (uint256 i = begin; i < end; i++) { _heroes[i - begin].id = tokenOfOwnerByIndex(_account, i); _heroes[i - begin].level = heroes[_heroes[i - begin].id].level; _heroes[i - begin].kind = heroes[_heroes[i - begin].id].kind; } return _heroes; } function getTotalProperties(address _account, uint begin, uint end) public view returns (Property[] memory){ uint _len = end - begin; Property[] memory _properties = new Property[](_len); for (uint256 i = begin; i < end; i++) { _properties[i - begin].id = tokenOfOwnerByIndex(_account, i); _properties[i - begin].goods_level = properties[_properties[i - begin].id].goods_level; _properties[i - begin].sail_level = properties[_properties[i - begin].id].sail_level; _properties[i - begin].is_goods_accelerate = properties[_properties[i - begin].id].is_goods_accelerate; _properties[i - begin].is_sail_accelerate = properties[_properties[i - begin].id].is_sail_accelerate; } return _properties; } function getHeroesPart(uint begin, uint end) public view returns (Hero[] memory) { uint _len = end - begin; Hero[] memory _heroes = new Hero[](_len); for (uint256 i = begin; i < end; i++) { _heroes[i - begin].id = i; _heroes[i - begin].level = heroes[_heroes[i - begin].id].level; _heroes[i - begin].kind = heroes[_heroes[i - begin].id].kind; } return _heroes; } function getPropertiesPart(uint begin, uint end) public view returns (Property[] memory){ uint _len = end - begin; Property[] memory _properties = new Property[](_len); for (uint256 i = begin; i < end; i++) { _properties[i - begin].id = i; _properties[i - begin].goods_level = properties[_properties[i - begin].id].goods_level; _properties[i - begin].sail_level = properties[_properties[i - begin].id].sail_level; _properties[i - begin].is_goods_accelerate = properties[_properties[i - begin].id].is_goods_accelerate; _properties[i - begin].is_sail_accelerate = properties[_properties[i - begin].id].is_sail_accelerate; } return _properties; } }
using System; using System.Collections.Generic; using System.Linq; using UnityEngine; namespace Rilisoft { public class StateMachine<T> : MonoBehaviour { public abstract class State<T> { protected StateMachine<T> Ctx; public T StateId { get; private set; } public State(T stateId, StateMachine<T> context) { StateId = stateId; Ctx = context; } public virtual void In(T fromState) { } public virtual void Out(T toState) { } public virtual void Update() { } protected void To(T state) { Ctx.To(state); } } public abstract class Transition<T> { protected StateMachine<T> Ctx; public T From { get; private set; } public T To { get; private set; } public Transition(T from, T to, StateMachine<T> context) { From = from; To = to; Ctx = context; } public virtual void Action() { } } private bool _enabled; private State<T> _prevState; private Dictionary<T, State<T>> _registeredStates; private List<Transition<T>> _transitions; private int _callStackSize = 10; [SerializeField] [TextArea(5, 10)] private string _callHistory; private List<string> _callStack; public bool Enabled { get { return _enabled; } set { _enabled = value; } } public State<T> CurrentState { get; private set; } public event Action<T, T> OnStateChanged; public StateMachine() { _registeredStates = new Dictionary<T, State<T>>(); _transitions = new List<Transition<T>>(); } protected StateMachine<T> Register(State<T> state) { if (_registeredStates.Keys.Contains(state.StateId)) { Debug.LogErrorFormat("state for '{0}' allready exists", state.StateId); return this; } _registeredStates.Add(state.StateId, state); return this; } protected void Clean() { _registeredStates.Clear(); _transitions.Clear(); CurrentState = null; _prevState = null; } protected StateMachine<T> RegisterTransition(Transition<T> transition) { _transitions.Add(transition); return this; } public void To(T stateId) { if (!_registeredStates.Keys.Contains(stateId)) { Debug.LogErrorFormat("state for '{0}' not found", stateId); return; } if (CurrentState != null) { _prevState = CurrentState; _prevState.Out(stateId); foreach (Transition<T> transition in _transitions) { if (transition.From.Equals(_prevState.StateId) && transition.To.Equals(stateId)) { transition.Action(); } } } CurrentState = _registeredStates[stateId]; CurrentState.In((_prevState == null) ? default(T) : _prevState.StateId); if (this.OnStateChanged != null) { this.OnStateChanged(CurrentState.StateId, (_prevState == null) ? default(T) : _prevState.StateId); } } protected virtual void Tick() { if (Enabled && CurrentState != null) { CurrentState.Update(); } } } }
package br.com.transporte.appGhn.tasks.motorista; import android.os.Handler; import androidx.annotation.NonNull; import java.util.concurrent.Executor; import br.com.transporte.appGhn.database.dao.RoomMotoristaDao; import br.com.transporte.appGhn.model.Motorista; public class AtualizaMotoristaTask { private final Executor executor; private final Handler resultHandler; public AtualizaMotoristaTask(Executor executor, Handler resultHandler) { this.executor = executor; this.resultHandler = resultHandler; } public interface TaskCallback { void finalizaAtualizacao(); } //---------------------------------------------------------------------------------------------- public void solicitaAtualizacao( RoomMotoristaDao dao, Motorista motorista, TaskCallback callBack ) { executor.execute( () -> { realizaAtualizacaoSincrona(dao, motorista); notificaResultado(callBack); }); } private void realizaAtualizacaoSincrona( @NonNull RoomMotoristaDao dao, Motorista motorista ) { dao.substitui(motorista); } private void notificaResultado(@NonNull TaskCallback callBack) { resultHandler.post( callBack::finalizaAtualizacao ); } }
<?php class RequestsTest_IDNAEncoder extends PHPUnit_Framework_TestCase { public static function specExamples() { return array( array( "\xe4\xbb\x96\xe4\xbb\xac\xe4\xb8\xba\xe4\xbb\x80\xe4\xb9\x88\xe4\xb8\x8d\xe8\xaf\xb4\xe4\xb8\xad\xe6\x96\x87", "xn--ihqwcrb4cv8a8dqg056pqjye" ), array( "\x33\xe5\xb9\xb4\x42\xe7\xb5\x84\xe9\x87\x91\xe5\x85\xab\xe5\x85\x88\xe7\x94\x9f", "xn--3B-ww4c5e180e575a65lsy2b", ) ); } /** * @dataProvider specExamples */ public function testEncoding($data, $expected) { $result = Requests_IDNAEncoder::encode($data); $this->assertEquals($expected, $result); } /** * @expectedException Requests_Exception */ public function testASCIITooLong() { $data = str_repeat("abcd", 20); $result = Requests_IDNAEncoder::encode($data); } /** * @expectedException Requests_Exception */ public function testEncodedTooLong() { $data = str_repeat("\xe4\xbb\x96", 60); $result = Requests_IDNAEncoder::encode($data); } /** * @expectedException Requests_Exception */ public function testAlreadyPrefixed() { $result = Requests_IDNAEncoder::encode("xn--\xe4\xbb\x96"); } public function testASCIICharacter() { $result = Requests_IDNAEncoder::encode("a"); $this->assertEquals('a', $result); } public function testTwoByteCharacter() { $result = Requests_IDNAEncoder::encode("\xc2\xb6"); // Pilcrow character $this->assertEquals('xn--tba', $result); } public function testThreeByteCharacter() { $result = Requests_IDNAEncoder::encode("\xe2\x82\xac"); // Euro symbol $this->assertEquals('xn--lzg', $result); } public function testFourByteCharacter() { $result = Requests_IDNAEncoder::encode("\xf0\xa4\xad\xa2"); // Chinese symbol? $this->assertEquals('xn--ww6j', $result); } /** * @expectedException Requests_Exception */ public function testFiveByteCharacter() { $result = Requests_IDNAEncoder::encode("\xfb\xb6\xb6\xb6\xb6"); } /** * @expectedException Requests_Exception */ public function testSixByteCharacter() { $result = Requests_IDNAEncoder::encode("\xfd\xb6\xb6\xb6\xb6\xb6"); } /** * @expectedException Requests_Exception */ public function testInvalidASCIICharacterWithMultibyte() { $result = Requests_IDNAEncoder::encode("\0\xc2\xb6"); } /** * @expectedException Requests_Exception */ public function testUnfinishedMultibyte() { $result = Requests_IDNAEncoder::encode("\xc2"); } /** * @expectedException Requests_Exception */ public function testPartialMultibyte() { $result = Requests_IDNAEncoder::encode("\xc2\xc2\xb6"); } }
import * as React from "react"; import Menu from "@mui/material/Menu"; import MenuItem from "@mui/material/MenuItem"; import { BurgerMenuIconButton } from "./iconbuttons"; import { useAppDispatch } from "store/hooks"; import { ll84QueryActions } from "store/ll84queryslice"; import { buildingInputActions } from "store/buildinginputslice"; import { uiActions } from "store/uislice"; import { InlineStylesType } from "types"; import { sample_ll84_data } from "locallaw/lookups"; import { LL84SelectionToLL97Inputs } from "locallaw/ll84_query_to_ll97_inputs"; const styles: InlineStylesType = { nav: { border: "1px solid black", "& .MuiPaper-root": { paddingLeft: "10px", paddingRight: "10px", border: "gray 1px solid", }, }, }; const NavMenu = () => { const dispatch = useAppDispatch(); const [anchorEl, setAnchorEl] = React.useState<null | HTMLElement>(null); const open = Boolean(anchorEl); const handleClick = (event: React.MouseEvent<HTMLButtonElement>) => { setAnchorEl(event.currentTarget); }; const handleClose = () => { setAnchorEl(null); }; const handleOpenLoadModal = () => { dispatch(uiActions.setCurrentView("load_building_dialogue")); handleClose(); }; const handleOpenInfoModal = () => { dispatch(uiActions.setCurrentView("calc_info_dialogue")); handleClose(); }; const handleOpenBuildingSummaryModal = () => { dispatch(uiActions.setCurrentView("building_summary_dialogue")); handleClose(); }; const handleLoadDemoBuildling = () => { dispatch(ll84QueryActions.setSelectedLL84Property(sample_ll84_data)); let ll97_conversion = LL84SelectionToLL97Inputs(sample_ll84_data); if (ll97_conversion.bldg_type_one_type !== undefined) { dispatch( buildingInputActions.setBuildingInputsFromLL84Results(ll97_conversion) ); } dispatch(uiActions.setCurrentView("chart_view")); }; return ( <div style={{ width: "10px" }}> <BurgerMenuIconButton active={open} clickCallback={handleClick} width={35} height={35} /> <Menu sx={styles.nav} anchorEl={anchorEl} open={open} onClose={handleClose} > <MenuItem onClick={handleOpenLoadModal}>Find Your Building</MenuItem> <MenuItem onClick={handleOpenBuildingSummaryModal}> About Loaded Building </MenuItem> <MenuItem onClick={handleOpenInfoModal}>About This Calculator</MenuItem> <MenuItem onClick={handleLoadDemoBuildling}> Load Sample Building </MenuItem> </Menu> </div> ); }; export default NavMenu;
/** * Copyright (c) 2000-present Liferay, Inc. All rights reserved. * * This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 2.1 of the License, or (at your option) * any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. */ package org.kisti.edison.science.model; import com.liferay.portal.kernel.bean.AutoEscapeBeanHandler; import com.liferay.portal.kernel.exception.SystemException; import com.liferay.portal.kernel.util.ProxyUtil; import com.liferay.portal.kernel.util.StringBundler; import com.liferay.portal.kernel.util.StringPool; import com.liferay.portal.kernel.util.Validator; import com.liferay.portal.model.BaseModel; import com.liferay.portal.model.impl.BaseModelImpl; import com.liferay.portal.util.PortalUtil; import org.kisti.edison.science.service.ClpSerializer; import org.kisti.edison.science.service.ScienceAppRatingsEntryLocalServiceUtil; import org.kisti.edison.science.service.persistence.ScienceAppRatingsEntryPK; import java.io.Serializable; import java.lang.reflect.Method; import java.util.Date; import java.util.HashMap; import java.util.Map; /** * @author EDISON */ public class ScienceAppRatingsEntryClp extends BaseModelImpl<ScienceAppRatingsEntry> implements ScienceAppRatingsEntry { public ScienceAppRatingsEntryClp() { } @Override public Class<?> getModelClass() { return ScienceAppRatingsEntry.class; } @Override public String getModelClassName() { return ScienceAppRatingsEntry.class.getName(); } @Override public ScienceAppRatingsEntryPK getPrimaryKey() { return new ScienceAppRatingsEntryPK(_userId, _scienceAppId); } @Override public void setPrimaryKey(ScienceAppRatingsEntryPK primaryKey) { setUserId(primaryKey.userId); setScienceAppId(primaryKey.scienceAppId); } @Override public Serializable getPrimaryKeyObj() { return new ScienceAppRatingsEntryPK(_userId, _scienceAppId); } @Override public void setPrimaryKeyObj(Serializable primaryKeyObj) { setPrimaryKey((ScienceAppRatingsEntryPK)primaryKeyObj); } @Override public Map<String, Object> getModelAttributes() { Map<String, Object> attributes = new HashMap<String, Object>(); attributes.put("userId", getUserId()); attributes.put("scienceAppId", getScienceAppId()); attributes.put("companyId", getCompanyId()); attributes.put("userName", getUserName()); attributes.put("createDate", getCreateDate()); attributes.put("modifiedDate", getModifiedDate()); attributes.put("classNameId", getClassNameId()); attributes.put("score", getScore()); return attributes; } @Override public void setModelAttributes(Map<String, Object> attributes) { Long userId = (Long)attributes.get("userId"); if (userId != null) { setUserId(userId); } Long scienceAppId = (Long)attributes.get("scienceAppId"); if (scienceAppId != null) { setScienceAppId(scienceAppId); } Long companyId = (Long)attributes.get("companyId"); if (companyId != null) { setCompanyId(companyId); } String userName = (String)attributes.get("userName"); if (userName != null) { setUserName(userName); } Date createDate = (Date)attributes.get("createDate"); if (createDate != null) { setCreateDate(createDate); } Date modifiedDate = (Date)attributes.get("modifiedDate"); if (modifiedDate != null) { setModifiedDate(modifiedDate); } Long classNameId = (Long)attributes.get("classNameId"); if (classNameId != null) { setClassNameId(classNameId); } Long score = (Long)attributes.get("score"); if (score != null) { setScore(score); } } @Override public long getUserId() { return _userId; } @Override public void setUserId(long userId) { _userId = userId; if (_scienceAppRatingsEntryRemoteModel != null) { try { Class<?> clazz = _scienceAppRatingsEntryRemoteModel.getClass(); Method method = clazz.getMethod("setUserId", long.class); method.invoke(_scienceAppRatingsEntryRemoteModel, userId); } catch (Exception e) { throw new UnsupportedOperationException(e); } } } @Override public String getUserUuid() throws SystemException { return PortalUtil.getUserValue(getUserId(), "uuid", _userUuid); } @Override public void setUserUuid(String userUuid) { _userUuid = userUuid; } @Override public long getScienceAppId() { return _scienceAppId; } @Override public void setScienceAppId(long scienceAppId) { _scienceAppId = scienceAppId; if (_scienceAppRatingsEntryRemoteModel != null) { try { Class<?> clazz = _scienceAppRatingsEntryRemoteModel.getClass(); Method method = clazz.getMethod("setScienceAppId", long.class); method.invoke(_scienceAppRatingsEntryRemoteModel, scienceAppId); } catch (Exception e) { throw new UnsupportedOperationException(e); } } } @Override public long getCompanyId() { return _companyId; } @Override public void setCompanyId(long companyId) { _companyId = companyId; if (_scienceAppRatingsEntryRemoteModel != null) { try { Class<?> clazz = _scienceAppRatingsEntryRemoteModel.getClass(); Method method = clazz.getMethod("setCompanyId", long.class); method.invoke(_scienceAppRatingsEntryRemoteModel, companyId); } catch (Exception e) { throw new UnsupportedOperationException(e); } } } @Override public String getUserName() { return _userName; } @Override public void setUserName(String userName) { _userName = userName; if (_scienceAppRatingsEntryRemoteModel != null) { try { Class<?> clazz = _scienceAppRatingsEntryRemoteModel.getClass(); Method method = clazz.getMethod("setUserName", String.class); method.invoke(_scienceAppRatingsEntryRemoteModel, userName); } catch (Exception e) { throw new UnsupportedOperationException(e); } } } @Override public Date getCreateDate() { return _createDate; } @Override public void setCreateDate(Date createDate) { _createDate = createDate; if (_scienceAppRatingsEntryRemoteModel != null) { try { Class<?> clazz = _scienceAppRatingsEntryRemoteModel.getClass(); Method method = clazz.getMethod("setCreateDate", Date.class); method.invoke(_scienceAppRatingsEntryRemoteModel, createDate); } catch (Exception e) { throw new UnsupportedOperationException(e); } } } @Override public Date getModifiedDate() { return _modifiedDate; } @Override public void setModifiedDate(Date modifiedDate) { _modifiedDate = modifiedDate; if (_scienceAppRatingsEntryRemoteModel != null) { try { Class<?> clazz = _scienceAppRatingsEntryRemoteModel.getClass(); Method method = clazz.getMethod("setModifiedDate", Date.class); method.invoke(_scienceAppRatingsEntryRemoteModel, modifiedDate); } catch (Exception e) { throw new UnsupportedOperationException(e); } } } @Override public String getClassName() { if (getClassNameId() <= 0) { return StringPool.BLANK; } return PortalUtil.getClassName(getClassNameId()); } @Override public void setClassName(String className) { long classNameId = 0; if (Validator.isNotNull(className)) { classNameId = PortalUtil.getClassNameId(className); } setClassNameId(classNameId); } @Override public long getClassNameId() { return _classNameId; } @Override public void setClassNameId(long classNameId) { _classNameId = classNameId; if (_scienceAppRatingsEntryRemoteModel != null) { try { Class<?> clazz = _scienceAppRatingsEntryRemoteModel.getClass(); Method method = clazz.getMethod("setClassNameId", long.class); method.invoke(_scienceAppRatingsEntryRemoteModel, classNameId); } catch (Exception e) { throw new UnsupportedOperationException(e); } } } @Override public long getScore() { return _score; } @Override public void setScore(long score) { _score = score; if (_scienceAppRatingsEntryRemoteModel != null) { try { Class<?> clazz = _scienceAppRatingsEntryRemoteModel.getClass(); Method method = clazz.getMethod("setScore", long.class); method.invoke(_scienceAppRatingsEntryRemoteModel, score); } catch (Exception e) { throw new UnsupportedOperationException(e); } } } public BaseModel<?> getScienceAppRatingsEntryRemoteModel() { return _scienceAppRatingsEntryRemoteModel; } public void setScienceAppRatingsEntryRemoteModel( BaseModel<?> scienceAppRatingsEntryRemoteModel) { _scienceAppRatingsEntryRemoteModel = scienceAppRatingsEntryRemoteModel; } public Object invokeOnRemoteModel(String methodName, Class<?>[] parameterTypes, Object[] parameterValues) throws Exception { Object[] remoteParameterValues = new Object[parameterValues.length]; for (int i = 0; i < parameterValues.length; i++) { if (parameterValues[i] != null) { remoteParameterValues[i] = ClpSerializer.translateInput(parameterValues[i]); } } Class<?> remoteModelClass = _scienceAppRatingsEntryRemoteModel.getClass(); ClassLoader remoteModelClassLoader = remoteModelClass.getClassLoader(); Class<?>[] remoteParameterTypes = new Class[parameterTypes.length]; for (int i = 0; i < parameterTypes.length; i++) { if (parameterTypes[i].isPrimitive()) { remoteParameterTypes[i] = parameterTypes[i]; } else { String parameterTypeName = parameterTypes[i].getName(); remoteParameterTypes[i] = remoteModelClassLoader.loadClass(parameterTypeName); } } Method method = remoteModelClass.getMethod(methodName, remoteParameterTypes); Object returnValue = method.invoke(_scienceAppRatingsEntryRemoteModel, remoteParameterValues); if (returnValue != null) { returnValue = ClpSerializer.translateOutput(returnValue); } return returnValue; } @Override public void persist() throws SystemException { if (this.isNew()) { ScienceAppRatingsEntryLocalServiceUtil.addScienceAppRatingsEntry(this); } else { ScienceAppRatingsEntryLocalServiceUtil.updateScienceAppRatingsEntry(this); } } @Override public ScienceAppRatingsEntry toEscapedModel() { return (ScienceAppRatingsEntry)ProxyUtil.newProxyInstance(ScienceAppRatingsEntry.class.getClassLoader(), new Class[] { ScienceAppRatingsEntry.class }, new AutoEscapeBeanHandler(this)); } @Override public Object clone() { ScienceAppRatingsEntryClp clone = new ScienceAppRatingsEntryClp(); clone.setUserId(getUserId()); clone.setScienceAppId(getScienceAppId()); clone.setCompanyId(getCompanyId()); clone.setUserName(getUserName()); clone.setCreateDate(getCreateDate()); clone.setModifiedDate(getModifiedDate()); clone.setClassNameId(getClassNameId()); clone.setScore(getScore()); return clone; } @Override public int compareTo(ScienceAppRatingsEntry scienceAppRatingsEntry) { ScienceAppRatingsEntryPK primaryKey = scienceAppRatingsEntry.getPrimaryKey(); return getPrimaryKey().compareTo(primaryKey); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof ScienceAppRatingsEntryClp)) { return false; } ScienceAppRatingsEntryClp scienceAppRatingsEntry = (ScienceAppRatingsEntryClp)obj; ScienceAppRatingsEntryPK primaryKey = scienceAppRatingsEntry.getPrimaryKey(); if (getPrimaryKey().equals(primaryKey)) { return true; } else { return false; } } public Class<?> getClpSerializerClass() { return _clpSerializerClass; } @Override public int hashCode() { return getPrimaryKey().hashCode(); } @Override public String toString() { StringBundler sb = new StringBundler(17); sb.append("{userId="); sb.append(getUserId()); sb.append(", scienceAppId="); sb.append(getScienceAppId()); sb.append(", companyId="); sb.append(getCompanyId()); sb.append(", userName="); sb.append(getUserName()); sb.append(", createDate="); sb.append(getCreateDate()); sb.append(", modifiedDate="); sb.append(getModifiedDate()); sb.append(", classNameId="); sb.append(getClassNameId()); sb.append(", score="); sb.append(getScore()); sb.append("}"); return sb.toString(); } @Override public String toXmlString() { StringBundler sb = new StringBundler(28); sb.append("<model><model-name>"); sb.append("org.kisti.edison.science.model.ScienceAppRatingsEntry"); sb.append("</model-name>"); sb.append( "<column><column-name>userId</column-name><column-value><![CDATA["); sb.append(getUserId()); sb.append("]]></column-value></column>"); sb.append( "<column><column-name>scienceAppId</column-name><column-value><![CDATA["); sb.append(getScienceAppId()); sb.append("]]></column-value></column>"); sb.append( "<column><column-name>companyId</column-name><column-value><![CDATA["); sb.append(getCompanyId()); sb.append("]]></column-value></column>"); sb.append( "<column><column-name>userName</column-name><column-value><![CDATA["); sb.append(getUserName()); sb.append("]]></column-value></column>"); sb.append( "<column><column-name>createDate</column-name><column-value><![CDATA["); sb.append(getCreateDate()); sb.append("]]></column-value></column>"); sb.append( "<column><column-name>modifiedDate</column-name><column-value><![CDATA["); sb.append(getModifiedDate()); sb.append("]]></column-value></column>"); sb.append( "<column><column-name>classNameId</column-name><column-value><![CDATA["); sb.append(getClassNameId()); sb.append("]]></column-value></column>"); sb.append( "<column><column-name>score</column-name><column-value><![CDATA["); sb.append(getScore()); sb.append("]]></column-value></column>"); sb.append("</model>"); return sb.toString(); } private long _userId; private String _userUuid; private long _scienceAppId; private long _companyId; private String _userName; private Date _createDate; private Date _modifiedDate; private long _classNameId; private long _score; private BaseModel<?> _scienceAppRatingsEntryRemoteModel; private Class<?> _clpSerializerClass = org.kisti.edison.science.service.ClpSerializer.class; }
import asyncio import logging import sys import msgpack from typing import Callable, Any, Dict, List, Optional, Deque from logging import Logger from threading import Thread from collections import deque import nonebot from nonebot import _driver as driver from nonebot.log import default_filter, logger from nonebot.utils import escape_tag, logger_wrapper from nonebot.typing import overrides from nonebot.config import Env, Config from nonebot.drivers import Driver as BaseDriver from nonebot.adapters.onebot.v12 import Bot, Message from nonebot.adapters.onebot.v12 import Adapter as BaseAdapter from nonebot.adapters.onebot.utils import handle_api_result def msg_to_dict(msg: Message) -> List[Dict[str, Any]]: r = [] for seg in msg: r.append({"type": seg.type, "data": seg.data}) return r class WalleDriver(BaseDriver): def __init__(self, env: Env, config: Config): super().__init__(env, config) @overrides(BaseDriver) def type(self) -> str: return "Walle" @overrides(BaseDriver) def logger(self) -> Logger: return logging.getLogger("Walle") @overrides(BaseDriver) def run(self, *args, **kwargs): logger.opt(colors=True).debug( f"<g>Loaded adapters: {escape_tag(', '.join(self._adapters))}</g>" ) @overrides(BaseDriver) def on_startup(self, func: Callable) -> Callable: pass # todo @overrides(BaseDriver) def on_shutdown(self, func: Callable) -> Callable: pass # todo class WalleAdapter(BaseAdapter): @classmethod @overrides(BaseAdapter) def get_name(cls) -> str: return "Walle" @overrides(BaseAdapter) def __init__(self, driver: BaseAdapter, **kwargs: Any): super().__init__(driver, **kwargs) self.actions: Deque[bytes] = deque() @overrides(BaseAdapter) async def _call_api(self, bot: Bot, api: str, **data: Any) -> Any: seq = self._result_store.get_seq() timeout = data.pop("timeout", self.config.api_timeout) if data.get("message"): data["message"] = msg_to_dict(data["message"]) data["self_id"] = bot.self_id self.actions.append( msgpack.packb({"action": api, "params": data, "echo": str(seq)}) ) return handle_api_result( await self._result_store.fetch(bot.self_id, seq, timeout) ) def rs_get_action(self) -> Optional[bytes]: if len(self.actions) <= 0: return None return self.actions.popleft() async def rs_push_event(self, event: bytes): data = msgpack.unpackb(event) self_id = data["self_id"] bot = self.bots.get(self_id) if not bot: bot = Bot(self, self_id) self.bot_connect(bot) log("INFO", f"<y>Bot {escape_tag(self_id)}</y> connected") event = self.json_to_event(data, self_id) asyncio.create_task(bot.handle_event(event)) def rs_push_resp(self, self_id: str, resp: bytes): data = msgpack.unpackb(resp) self._result_store.add_result(self_id, data) try: loop = asyncio.new_event_loop() t = Thread(target=loop.run_forever) t.start() log = logger_wrapper("Walle") env = Env() config = Config(_common_config=env.dict(), _env_file=f".env.{env.environment}") # default_filter.level = config.log_level default_filter.level = "DEBUG" logger.opt(colors=True).info( f"Current <y><b>Env: {escape_tag(env.environment)}</b></y>" ) logger.opt(colors=True).debug( f"Loaded <y><b>Config</b></y>: {escape_tag(str(config.dict()))}" ) driver = WalleDriver(env, config) driver.register_adapter(WalleAdapter) adapter = driver._adapters.get("Walle") nonebot.init() nonebot.load_builtin_plugin("echo") except KeyboardInterrupt: sys.exit(1)
import React, { FC } from "react"; import classNames from "classnames"; import { FancyButtonAsyncTask } from "../../Fancy/Button/FancyButtonAsyncTask"; import { useClipboardWriteText } from "../../../hooks/useClipboardWriteText"; import "./ModalShareCopyButton.css"; export const ModalShareCopyButton: FC<{ text: string | (() => Promise<string>); className?: string; }> = ({ text, className }) => { const writeText = useClipboardWriteText(); return ( <FancyButtonAsyncTask theme="blue" className={classNames("ModalShareCopyButton", className)} labelClassName="ModalShareCopyButton__Label" onTaskBegin={async () => { await writeText(typeof text === "function" ? await text() : text); }} doneText="Copied" icon="copy" > Copy to clipboard </FancyButtonAsyncTask> ); };
import React, { useState } from "react"; import styles from "./css/common.module.css"; import sqlData from "../utils/json/sqlData.json"; import { Light as SyntaxHighlighter } from "react-syntax-highlighter"; import { atomOneDark } from "react-syntax-highlighter/dist/esm/styles/hljs"; import { BackButton } from "../components/BackButton"; import CopyButton from "../components/CopyButton"; import codeBlockStyles from "./const/codeBlockstyle"; function SQL() { return ( <> <div className={styles["container"]}> <div className={styles["index"]}> <BackButton /> <ul> {sqlData.sql_concepts.map((section) => ( <li key={section.id}> <a href={`#${section.id}`}>{section.title}</a> </li> ))} </ul> </div> <div className={styles["content"]}> {sqlData.sql_concepts.map((section) => ( <section key={section.id} id={section.id}> <h2>{section.title}</h2> <p>{section.content}</p> <div> {section.code_example.code && ( <CopyButton code={section.code_example.code} id={section.id} /> )} </div> {section.code_example.code && ( <SyntaxHighlighter language="sql" style={atomOneDark} customStyle={codeBlockStyles} wrapLongLines={true} > {section.code_example.code} </SyntaxHighlighter> )} {section.code_example.output && ( <div> Output <SyntaxHighlighter style={atomOneDark} customStyle={codeBlockStyles} wrapLongLines={true} > {section.code_example.output} </SyntaxHighlighter> </div> )} </section> ))} </div> </div> </> ); } export default SQL;
package com.example.repository.adapter.impl; import com.example.events.ErrorEvent; import com.example.events.MessageEvent; import com.example.model.Student; import com.example.repository.adapter.StudentRepositoryAdapter; import com.example.repository.jpa.StudentRepository; import lombok.RequiredArgsConstructor; import org.springframework.context.ApplicationEventPublisher; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import java.util.List; import java.util.Optional; import static java.lang.Integer.parseInt; import static java.lang.Long.parseLong; import static java.text.MessageFormat.format; import static java.util.stream.Collectors.joining; @Repository @RequiredArgsConstructor public class StudentRepositoryAdapterImpl implements StudentRepositoryAdapter { private final StudentRepository repository; private final ApplicationEventPublisher publisher; @Transactional(readOnly = true) @Override public void findAll() { List<Student> students = repository.findAll(); publisher.publishEvent(students.isEmpty() ? new ErrorEvent("На данный момент нет сохраненных студентов") : new MessageEvent(students.stream() .map(Student::toString) .collect(joining(System.lineSeparator())))); } @Transactional(readOnly = true) @Override public void findById(String id) { try { Optional<Student> opt = repository.findById(parseLong(id)); publisher.publishEvent(opt.isEmpty() ? new ErrorEvent(format("Студент с id:{0} не найден", id)) : new MessageEvent(opt.get().toString())); } catch (NumberFormatException ex) { publisher.publishEvent(new ErrorEvent(format("Неверное значение id: {0}", id))); } } @Transactional @Override public void save(String firstName, String lastName, String age) { if(age.matches("[1-9]\\d?")) { Student saved = repository.save(new Student(firstName, lastName, parseInt(age))); publisher.publishEvent(new MessageEvent(format("Студент с id:{0} сохранен", saved.getId()))); } else { publisher.publishEvent(new ErrorEvent(format("Неверное значение возраста: {0}", age))); } } @Transactional @Override public void deleteById(String id) { try { Long parsedId = parseLong(id); Optional<Student> opt = repository.findById(parsedId); if (opt.isEmpty()) { publisher.publishEvent(new ErrorEvent(format("Студент с id:{0} не найден", id))); } else { repository.deleteById(parsedId); publisher.publishEvent(new MessageEvent(format("Студент с id:{0} успешно удален", id))); } } catch (NumberFormatException ex) { publisher.publishEvent(new ErrorEvent(format("Неверное значение id: {0}", id))); } } @Transactional @Override public void clear() { repository.deleteAll(); publisher.publishEvent(new MessageEvent("Список студентов очищен")); } }
import { DialogContent, DialogFooter, DialogHeader, DialogTitle, } from '@/components/ui/dialog'; import { useCart } from '@/context/cartContext'; import { formatToBRL } from '@/utils/formatToBRL'; import Image from 'next/image'; import { useState } from 'react'; import { CheckoutButton, FooterContent, ImageContainer, InfoText, ProductContainer, ProductInfo, ProductListContainer, } from './styles'; export function CartDialog() { const { cart, removeItemFromCart, handleCheckoutCart } = useCart(); const [isCreatingCheckoutSession, setIsCreatingCheckoutSession] = useState(false); const hasItemsOnCart = cart.length > 0; const formattedProductsToCheckout = cart.reduce<{ products_ids: string[]; total_price: number; }>( (acc, current) => { acc.products_ids.push(current.defaultPriceId); acc.total_price += current.price; return acc; }, { products_ids: [], total_price: 0 }, ); const handleRemoveProductFromCart = (itemId: string) => { removeItemFromCart(itemId); }; const handleCheckout = async () => { setIsCreatingCheckoutSession(true); await handleCheckoutCart(formattedProductsToCheckout.products_ids); }; return ( <DialogContent> <DialogHeader> <DialogTitle>Sacola de compras</DialogTitle> </DialogHeader> <ProductListContainer> {!hasItemsOnCart && <span>Carrinho vazio</span>} {hasItemsOnCart && cart.map((product) => ( <ProductContainer key={product.id}> <ImageContainer> <Image src={product.imageUrl} alt="" width={100} height={100} /> </ImageContainer> <ProductInfo> <h3>{product.name}</h3> <span>{product.price_text}</span> <button type="button" onClick={() => handleRemoveProductFromCart(product.id)} > Remover </button> </ProductInfo> </ProductContainer> ))} </ProductListContainer> {hasItemsOnCart && ( <DialogFooter> <FooterContent> <InfoText>Quantidade</InfoText> <InfoText color="text" align="end" fontSize="lg"> {cart.length} item(s) </InfoText> <InfoText fontSize="lg"> <strong>Valor total</strong> </InfoText> <InfoText align="end" fontSize="xl"> <strong> {formatToBRL(formattedProductsToCheckout.total_price)} </strong> </InfoText> </FooterContent> <CheckoutButton type="button" disabled={isCreatingCheckoutSession} onClick={handleCheckout} > Finalizar compra </CheckoutButton> </DialogFooter> )} </DialogContent> ); }
package main import ( "flag" "fmt" "os" "os/signal" "syscall" "k8s.io/client-go/kubernetes" "k8s.io/client-go/rest" "k8s.io/client-go/tools/cache" ) func main() { // 解析命令行参数,包括kubeconfig路径和Ingress命名空间 kubeconfig := flag.String("kubeconfig", "", "Path to a kubeconfig file") namespace := flag.String("namespace", "default", "Namespace to watch for Ingress resources") flag.Parse() // 创建Kubernetes配置 config, err := rest.InClusterConfig() if err != nil { if *kubeconfig == "" { fmt.Printf("Error creating in-cluster config: %v\n", err) os.Exit(1) } // 如果没有InClusterConfig可用,使用外部kubeconfig文件 config, err = rest.InClusterConfig() if err != nil { fmt.Printf("Error creating out-of-cluster config: %v\n", err) os.Exit(1) } } // 创建Kubernetes客户端 clientset, err := kubernetes.NewForConfig(config) if err != nil { fmt.Printf("Error creating Kubernetes client: %v\n", err) os.Exit(1) } // 创建Informer工厂 factory := cache.NewSharedInformerFactoryWithOptions( clientset, 0, // 0表示不使用Resync cache.ResourceEventHandlerFuncs{ UpdateFunc: func(oldObj, newObj interface{}) { // 处理Ingress资源的更新事件 // 在此处提取Cluster IP信息并进行相应的操作 fmt.Printf("Ingress updated: %v\n", newObj) }, }, ) // 创建Ingress Informer informer := factory.Networking().V1().Ingresses().Informer() stopCh := make(chan struct{}) defer close(stopCh) // 启动Informer go factory.Start(stopCh) // 等待终止信号 signalCh := make(chan os.Signal, 1) signal.Notify(signalCh, syscall.SIGINT, syscall.SIGTERM) <-signalCh }
import { Injectable } from '@angular/core'; import { ApiService } from './api.service'; @Injectable() export class AuthService { constructor( private apiService: ApiService ) { } public static STUDENT = 0; public static RECRUITER = 1; public static PRIMARY_RECRUITER = 2; public static ADMIN = 3; // * LOGIN * // - Authenticates a user // - Expects a LoginModel // - Returns a UserModel login(user) { return this.apiService.post('/user/login', user); } // * LOGOUT * // - Removes all local storage variables for a user logout() { window.localStorage.removeItem('id'); window.localStorage.removeItem('email'); window.localStorage.removeItem('role'); } // * SET LOCAL VARS * // - Sets local storage variables for a user setLocalVars(user) { window.localStorage.setItem('id', user.id); window.localStorage.setItem('email', user.username); } // * GET USER ROLE * // - Gets the first role of the given user getUserRole(user) { let isStudent = false; let isRecruiter = false; let isAdmin = false; let isPrimaryRecruiter = false; let role = 0; user.roles.forEach(role => { if (role.name == "student") { isStudent = true; } else if (role.name == "recruiter") { isRecruiter = true; } else if (role.name == "primaryrecruiter") { isPrimaryRecruiter = true; } else if (role.name == "admin") { isAdmin = true; } }); if (isStudent) { role = AuthService.STUDENT; } else if (isAdmin) { role = AuthService.ADMIN; } else if (isPrimaryRecruiter) { role = AuthService.PRIMARY_RECRUITER; } else if (isRecruiter) { role = AuthService.RECRUITER; } else { role = -1; } return role; } }
import flask import flask_login import os from flask import Flask, flash, render_template, current_app, request, redirect, session from flask_mail import Mail, Message from werkzeug.utils import secure_filename import google_calendar_reader as cal import database_library as db import random app = flask.Flask(__name__) app.secret_key = 'super secret string' # Change this! login_manager = flask_login.LoginManager() login_manager.init_app(app) # Our mock databases. # irl we should use an actual database for this. # We would also obviously not want to store username/login info in plain text like this. users = {'foo@bar.tld': {'pw': 'secret'}} #for user login info # see: https://flask.palletsprojects.com/en/2.2.x/patterns/fileuploads/ # directory where uploaded images will be stored UPLOAD_FOLDER = 'static/image_uploads' ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif'} app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER # set up the mail instance keyFile = open("EMAIL_KEY", "r") emailKey = keyFile.read() keyFile.close() addressFile = open("EMAIL_ADDRESS", "r") emailAddress = addressFile.read() addressFile.close() app.config.update( MAIL_SERVER='smtp.gmail.com', MAIL_PORT=465, MAIL_USE_SSL=True, MAIL_USERNAME = emailAddress, MAIL_PASSWORD = emailKey ) mail = Mail(app) #Passcode for OTP global_final_otp = '' class User(flask_login.UserMixin): pass @login_manager.user_loader def user_loader(email): if email not in users: return user = User() user.id = email return user @login_manager.request_loader def request_loader(request): email = request.form.get('email') if email not in users: return user = User() user.id = email # DO NOT ever store passwords in plaintext and always compare password # hashes using constant-time comparison! user.is_authenticated = request.form['pw'] == users[email]['pw'] return user @login_manager.unauthorized_handler def unauthorized_handler(): return 'Unauthorized' #@app.route('/') #def index(): # if flask_login.current_user.is_anonymous: # return 'Hello anonymous user' # else: # return f'Hello {flask_login.current_user.id}' # #return 'Hello user' @app.route("/") def welcome(): newEvents = cal.get_next_five_events() return render_template("welcome.html",next_events=newEvents) @app.route("/donate") def donate(): return render_template("donate.html") @app.route("/members") def members(): return render_template("members.html", member=db.get_team_members()) @app.route("/alumni") def alumni(): print(db.get_alumni()) return render_template("alumni.html", alumni=db.get_alumni()) @app.route("/calendar") def calendar(): oldEvents = cal.get_last_five_events() newEvents = cal.get_next_five_events() return render_template("calendar.html",past_events = oldEvents,next_events = newEvents) @app.route("/instagram") def instagram(): return render_template("instagram.html",social=db.get_page("social"), contact=db.get_page("contact")) @app.route("/about") def about(): return render_template("about_us.html", officers=db.get_about(), content=db.get_page("aboutus")) #recruitment page @app.route("/join") def join(): test = db.get_testimonial() return render_template("join.html",test=test) @app.route("/contact") def contact(): return render_template("contactus.html",social=db.get_page("social"),logo=db.get_page("contact_logo")) @app.route("/contact",methods=['POST']) def contact_post(): msg = Message(subject=request.form['subject'], body="Hello, \n\n My name is "+request.form['name']+". My email is " + request.form['email']+ "\n\nHere is my message: "+request.form['message']+"\n\nYou can contact me at: "+request.form['phone'] + "\n\n(Note: There is a message from Contact Page - Sac State Rowing Website)", sender=request.form['email'], recipients=[emailAddress.rstrip()]) mail.send(msg) return render_template("contactus.html") @app.route("/recruitment") def recruitment(): return render_template("recruitment.html") @app.route('/login') def login(): return render_template("login.html") @app.route('/login', methods=['POST']) def login_form(): email = flask.request.form['email'] if flask.request.form['pw'] == users[email]['pw']: user = User() user.id = email flask_login.login_user(user) return flask.redirect(flask.url_for('protected')) return 'Bad login' #return render_template("login.html") ##TO-DO: # - find way to make sure code becomes invalid after a set amount of time # - check email to make sure it is a valid email addr and that it matches set email # -make sure email storage is done with hash value and to validate with hash match # - email message needs to be secure, email text should be hidden from traffic sniffing @app.route('/verify', methods = ["POST"]) def verify(): #Creates OTP final_otp = '' for i in range(6): final_otp = final_otp + str(random.randint(0,9)) #Sends message to email put in form msg = Message(subject="Rowing Club Sign-in Passcode", body="Passcode for log-in verification: " + str(final_otp), sender="noreply@rowingclub.com", #curr ver shows sender same as recipient in actal email, see if there is a fix for this recipients=[request.form['email_otp']]) mail.send(msg) #Sets a session var to be referenced for validate page. #Might be removed after flask session is ended but not sure how this works with hosted website session['final_otp'] = final_otp #session['user_email'] = request.form['email_otp'] return render_template('login_otp.html') @app.route('/validate',methods=["POST"]) def validate(): # OTP Entered by the User user_otp = request.form['otp'] if int(session['final_otp']) == int(user_otp): #User var setting done manually so session cookies can be generated to access page #Will need to alter to change to authorized rowing club email when published user = User() user.id = 'foo@bar.tld' flask_login.login_user(user) return flask.redirect(flask.url_for('protected')) else: flash('Incorrect Passcode Entered, Try again') return render_template('login_otp.html') @app.route('/protected', methods=['POST']) @flask_login.login_required def protected_post(): print(request.form) if "deleteplayer" in request.form: text = request.form['deleteplayer'] db.delete_player(text) if "player-name" in request.form: nametext = request.form['player-name'] desc = request.form['player-desc'] # check if the post request has the file part if 'player-file' not in request.files: print('No file part') return redirect(request.url) file = request.files['player-file'] # If the user does not select a file, the browser submits an # empty file without a filename. if file.filename == '': print('No file name') return redirect(request.url) if file and allowed_file(file.filename): print('Success') filename = secure_filename(file.filename) print(os.path.join(app.config['UPLOAD_FOLDER'], filename)) file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) else: print('File name not allowed') return redirect(request.url) db.insert_player(nametext,desc,filename) ####################################################### # Alumni form -> needs to be changed to edit text. Alumni memebers not a part of page ####################################################### if "deletealumni" in request.form: text = request.form['deletealumni'] db.delete_alumni(text) if "alumni-name" in request.form: nametext = request.form['alumni-name'] desc = request.form['alumni-desc'] # check if the post request has the file part if 'alumni-file' not in request.files: print('No file part') return redirect(request.url) file = request.files['alumni-file'] # If the user does not select a file, the browser submits an # empty file without a filename. if file.filename == '': print('No file name') return redirect(request.url) if file and allowed_file(file.filename): print('Success alumni') filename = secure_filename(file.filename) print(os.path.join(app.config['UPLOAD_FOLDER'], filename)) file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) else: print('File name not allowed') return redirect(request.url) db.insert_alumni(nametext,desc,filename) ####################################################### # team members form ####################################################### if "deleteteam" in request.form: text = request.form['deleteteam'] db.delete_team_members(text) if "team-name" in request.form: nametext = request.form['team-name'] desc = request.form['team-player-desc'] role = request.form['team-role-desc'] # check if the post request has the file part if 'team-file' not in request.files: print('No file part') return redirect(request.url) file = request.files['team-file'] # If the user does not select a file, the browser submits an # empty file without a filename. if file.filename == '': print('No file name') return redirect(request.url) if file and allowed_file(file.filename): print('Success team member') filename = secure_filename(file.filename) print(os.path.join(app.config['UPLOAD_FOLDER'], filename)) file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) else: print('File name not allowed') return redirect(request.url) db.insert_team_members(nametext,desc,filename,role) ####################################################### # Officer form ####################################################### if "deleteofficers" in request.form: text = request.form['deleteofficers'] db.delete_about(text) #if "officers-add-form" in request.form: if "officers-name" in request.form: print('Officers add form') nametext = request.form['officers-name'] desc = request.form['officers-desc'] # check if the post request has the file part if 'officers-file' not in request.files: print('No file part') return redirect(request.url) file = request.files['officers-file'] # If the user does not select a file, the browser submits an # empty file without a filename. if file.filename == '': print('No file name') return redirect(request.url) if file and allowed_file(file.filename): print('Success officer') filename = secure_filename(file.filename) print(os.path.join(app.config['UPLOAD_FOLDER'], filename)) file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) else: print('File name not allowed') return redirect(request.url) db.insert_about(nametext,desc,filename) ####################################################### # Testimonials form ####################################################### if "deletetestimonial" in request.form: text = request.form['deletetestimonial'] db.delete_testimonial(text) if "testimonial-name" in request.form: nametext = request.form['testimonial-name'] text1 = request.form['testimonial-text1'] text2 = request.form['testimonial-text2'] # check if the post request has the file part if 'testimonial-file' not in request.files: print('No file part') return redirect(request.url) file = request.files['testimonial-file'] # If the user does not select a file, the browser submits an # empty file without a filename. if file.filename == '': print('No file name') return redirect(request.url) if file and allowed_file(file.filename): print('Success testimonial') filename = secure_filename(file.filename) print(os.path.join(app.config['UPLOAD_FOLDER'], filename)) file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) else: print('File name not allowed') return redirect(request.url) db.insert_testimonial(nametext,text1,filename,text2) players = db.get_players() #print(players) alumni = db.get_alumni() #print(alumni) team_members = db.get_team_members() #print(team_members) officers = db.get_about() #print(officers) testimonial=db.get_testimonial() #print(testimonial) return render_template("admin.html", players=players, alumni=alumni, team_members=team_members, officers=officers, testimonial=testimonial, blocks=db.get_pages()) @app.route('/protected') @flask_login.login_required def protected(): players = db.get_players() #print(players) alumni = db.get_alumni() #print(alumni) team_members = db.get_team_members() #print(team_members) officers = db.get_about() #print(officers) testimonial=db.get_testimonial() #print(testimonial) return render_template("admin.html", players=players, alumni=alumni, team_members=team_members, officers=officers, testimonial=testimonial, blocks=db.get_pages()) @app.route('/logout') def logout(): flask_login.logout_user() return redirect('/') @app.route('/sql_debug') def sql_debug(): return render_template("sql_debug.html", players=db.get_players()) # checks if file with filename is allowed to be uploaded def allowed_file(filename): return '.' in filename and \ filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS @app.route('/updatecontent', methods=['POST']) @flask_login.login_required def cmsPages(): if flask.request.method == 'POST': json_data = flask.request.get_json() db.update_page(json_data["slug"],json_data["content"]) return { 'data' : db.get_page(json_data["slug"]), 'message': "Updated!" } return render_template('admin.html') @app.route('/editpage', methods=['POST']) @flask_login.login_required def updatePage(): if flask.request.method == 'POST': json_data = flask.request.get_json() return { 'data' : db.get_page(json_data["slug"]) } return render_template('admin.html') @app.route('/uploadimage', methods=['POST']) @flask_login.login_required def uploadImage(): if flask.request.method == 'POST': if request.files.get("file"): if allowed_file(request.files.get("file").filename): file = secure_filename(request.files.get("file").filename) request.files.get("file").save(os.path.join(app.config['UPLOAD_FOLDER'], file)) return { 'location' : os.path.join(app.config['UPLOAD_FOLDER'], file) }
package crypto import ( "fmt" "testing" "github.com/stretchr/testify/assert" ) func TestGeneratePrivateKey(t *testing.T) { privKey := GeneratePrivateKey() assert.Equal(t, len(privKey.Bytes()), privKeyLen) pubKey := privKey.Public() assert.Equal(t, len(pubKey.Bytes()), pubKeyLen) } func TestPrivateKeySign(t *testing.T) { privKey := GeneratePrivateKey() msg := []byte("foo bar baz") sig := privKey.Sign(msg) pubKey := privKey.Public() assert.True(t, sig.Verify(pubKey, msg)) // test with invalid message assert.False(t, sig.Verify(pubKey, []byte("foo baz baz"))) //test with invaid pubKey invalidPrivKey := GeneratePrivateKey() assert.False(t, sig.Verify(invalidPrivKey.Public(), msg)) } func TestPublicKeyToAddress(t *testing.T) { privKey := GeneratePrivateKey() pubKey := privKey.Public() address := pubKey.Address() assert.Equal(t, addressLen, len(address.Bytes())) fmt.Println(address) } func TestNewPrivateKeyFromString(t *testing.T) { var ( seed = "69cab4a7ae8d62b697ee10e1c81387cce63c20328fb5846b61655763b46c9c31" privKey = NewPrivateKeyFromString(seed) addressStr = "3970f73ae883185753fdfdca96622b7c6d16de46" ) assert.Equal(t, privKeyLen, len(privKey.Bytes())) address := privKey.Public().Address() assert.Equal(t, addressStr, address.String()) }
// Copyright 2022, University of Freiburg, // Chair of Algorithms and Data Structures. // Author: // 2022 - Johannes Kalmbach <kalmbach@cs.uni-freiburg.de> #ifndef QLEVER_TRANSPARENTFUNCTORS_H #define QLEVER_TRANSPARENTFUNCTORS_H #include <util/Forward.h> #include <util/TypeTraits.h> #include <utility> /// Contains several function object types with templated operator() that wrap /// overloaded functions from the standard library. This enables passing them as /// function parameters. /// Note that in theory all of them could be implemented shorter as captureless /// lambda expressions. We have chosen not to do this because the STL also does /// not choose this approach (see e.g. `std::less`, `std::plus`, etc.) and /// because global inline lambdas in header files might in theory cause ODR (one /// definition rule) problems, especially when using different compilers. namespace ad_utility { namespace detail { // Implementation of `first` (see below). struct FirstImpl { template <typename T> constexpr decltype(auto) operator()(T&& pair) const noexcept { return std::get<0>(AD_FWD(pair)); } }; // Implementation of `second` (see below). struct SecondImpl { template <typename T> constexpr decltype(auto) operator()(T&& pair) const noexcept { return std::get<1>(AD_FWD(pair)); } }; // Implementation of `holdsAlternative` (see below). template <typename T> struct HoldsAlternativeImpl { constexpr decltype(auto) operator()(auto&& variant) const { return std::holds_alternative<T>(AD_FWD(variant)); } }; // Implementation of `get` (see below). template <typename T> struct GetImpl { constexpr decltype(auto) operator()(auto&& variant) const { return std::get<T>(AD_FWD(variant)); } }; // Implementation of `getIf` (see below). template <typename T> struct GetIfImpl { template <typename Ptr> requires std::is_pointer_v<std::remove_cvref_t<Ptr>> constexpr decltype(auto) operator()(Ptr& variantPtr) const { return std::get_if<T>(variantPtr); } template <typename Ptr> requires(!std::is_pointer_v<std::remove_cvref_t<Ptr>>) constexpr decltype(auto) operator()(Ptr& variant) const { return std::get_if<T>(&variant); } }; // Implementation of `toBool` (see below). struct ToBoolImpl { constexpr decltype(auto) operator()(const auto& x) const { return static_cast<bool>(x); } }; } // namespace detail /// Return the first element via perfect forwarding of any type for which /// `std::get<0>(x)` is valid. This holds e.g. for `std::pair`, `std::tuple`, /// and `std::array`. static constexpr detail::FirstImpl first; /// Return the second element via perfect forwarding of any type for which /// `std::get<1>(x)` is valid. This holds e.g. for `std::pair`, `std::tuple`, /// and `std::array`. static constexpr detail::SecondImpl second; /// Transparent functor for `std::holds_alternative` template <typename T> static constexpr detail::HoldsAlternativeImpl<T> holdsAlternative; /// Transparent functor for `std::get`. Currently only works for `std::variant` /// and not for `std::array` or `std::tuple`. template <typename T> static constexpr detail::GetImpl<T> get; /// Transparent functor for `std::get_if`. As an extension to `std::get_if`, /// `ad_utility::getIf` may also be called with a `variant` object or reference, /// not only with a pointer. template <typename T> static constexpr detail::GetIfImpl<T> getIf; static constexpr detail::ToBoolImpl toBool; /// A functor that takes an arbitrary number of arguments by reference and does /// nothing. struct Noop { void operator()(const auto&...) const { // This function deliberately does nothing (static analysis expects a // comment here). } }; [[maybe_unused]] static constexpr Noop noop{}; } // namespace ad_utility #endif // QLEVER_TRANSPARENTFUNCTORS_H
<?php if (!file_exists("events/index.json")) { return; } // Read json file with events $str = file_get_contents("events/index.json"); // Convert json into array $events = json_decode($str, true); // Sort events DESC uasort($events, function ($event1, $event2) { return strtotime($event1["date"]) - strtotime($event2["date"]); }); $future_events = []; $past_events = []; ?> <?php $today = time(); ?> <?php foreach ($events as $i => $event) : ?> <?php $event_dt = strtotime($event["date"]); // Get event date date object $date_event = date_create(date('d-m-Y', $event_dt)); // Get today date object $date_today = date_create(date('d-m-Y', time())); // Get date difference object $diff = date_diff($date_today, $date_event); // Difference in days $diff_days = $diff->days; // If the date is from the past, multiply by -1 so it is negative if ($diff->invert) { $diff_days = $diff_days * -1; } if ($diff_days >= 0) { array_push($future_events, $event); // echo 'Future ' . $event["date"] . "Today : " . $today . "<br>"; } else { array_push($past_events, $event); // echo 'Past ' . $event["date"] . "Today : " . $today . "<br>"; } ?> <?php endforeach; // Take only 3 latest events $latest_events = array_slice($future_events, 0, 4); // var_dump($future_events) ; // echo "<br>". "laetst" ; // var_dump($latest_events); ?> <?php include_once("workshop.php");?> <?php if (count($latest_events) > 0) : ?> <section id="events" class="home-section" style="background-color: var(--bg-darker);"> <div class="container" style="justify-content:center;"> <div class="row"> <div class="col text-center mb-5"> <h2>Happening Soon</h2> </div> </div> <div class="row mb-5" style="justify-content: center;"> <?php foreach ($latest_events as $i => $event) : ?> <!-- <div class="col-sm-12 col-md-6 col-lg-3"> --> <div class="col-12 col-lg-3 col-md-6"> <div class="card <?php echo $event["type"] ?>"> <!-- IF THE PATH IS BLANK, DON'T INCLUDE HYPERLINK --> <?php if ($event["path"] == "") : { ?> <a><img src="<?php echo $event["img"] ?>" class="card-img-top" alt="<?php echo $event["title"] ?>"></a> <div class="card-body"> <h4><a><?php echo $event["title"] ?></a></h4> <h6><?php echo date_format(date_create($event['date']), "d M Y") ?></h6> </div> <?php } else : { ?> <?php if ($event["link"] == "") : { ?> <a href="<?php echo $event["path"] ?>"><img src="<?php echo $event["img"] ?>" class="card-img-top" alt="<?php echo $event["title"] ?>"></a> <?php } else : { ?> <a href="<?php echo $event["link"] ?>" target="_blank"><img src="<?php echo $event["img"] ?>" class="card-img-top" alt="<?php echo $event["title"] ?>"></a> <?php } endif; ?> <div class="card-body"> <?php if ($event["link"] == "") : { ?> <h4><a href="<?php echo $event["path"] ?>"><?php echo $event["title"] ?></a></h4> <?php } else : { ?> <h4><a href="<?php echo $event["link"] ?>" target="_blank"><?php echo $event["title"] ?></a></h4> <?php } endif; ?> <h6><?php echo date_format(date_create($event['date']), "d M Y") ?></h6> <p class="card-text"><a href="<?php echo $event["path"] ?>"><?php echo $event["description"] ?></a></p> </div> <?php } endif; ?> </div> </div> <?php endforeach; ?> </div> <div class="row"> <div class="col text-center"> <a href="/events" class="btn btn-lg btn-primary">See All Events</a> <!-- <a href="/events#past-events" class="btn btn-lg btn-outline-secondary">Past Events</a> --> <a href="events-past.php" class="btn btn-lg btn-outline-secondary">Recent / Past Events</a> </div> </div> </div> </section> <?php endif; ?>
import { theme } from '@/constants/themes' import Author from '@/models/Author' import { Ionicons } from '@expo/vector-icons' import { BottomSheetBackgroundProps, BottomSheetModal, BottomSheetView, } from '@gorhom/bottom-sheet' import { Text, View, useSx } from 'dripsy' import { useCallback, useMemo, useRef } from 'react' import Animated from 'react-native-reanimated' import truncateEnd from '../helpers/truncateEnd' import AnimatedPressable from './AnimatedPressable' import BookModal from './BookModal' import Button from './Button' import PageCounter from './PageCounter' import ThumbnailImage from './ThumbnailImage' export interface BookProps { title: string authors: Author[] | string[] description: string thumbnail: string pageCount: number onPress?: () => void buttonTitle?: string buttonIcon?: React.ComponentProps<typeof Ionicons>['name'] buttonOnPress?: () => void } export default function BookCard({ title, authors, thumbnail, pageCount, description, buttonTitle, buttonIcon, buttonOnPress = () => {}, }: BookProps) { const sx = useSx() const container = sx({ paddingHorizontal: 10, flexDirection: 'row', marginBottom: 10, justifyContent: 'space-between', }) const contentStyles = sx({ height: 'auto', width: '65%', flexDirection: 'row', }) const buttonContainer = sx({ flex: 1, alignItems: 'flex-end', justifyContent: 'center', }) const textContainer = sx({ flexDirection: 'column', alignItems: 'start', rowGap: 5, }) const shadowStyle = sx({ backgroundColor: 'black', borderRadius: 32, shadowColor: 'white', shadowOffset: { width: 0, height: 16, }, shadowOpacity: 0.5, shadowRadius: 24.0, elevation: 16, }) const bottomSheetModalRef = useRef<BottomSheetModal>(null) const handlePresentModalPress = useCallback(() => { bottomSheetModalRef.current?.present() }, []) const renderContent = () => ( <BookModal title={title} description={description} authors={authors} thumbnail={thumbnail} pageCount={pageCount} buttonOnPress={buttonOnPress} /> ) const snapPoints = useMemo(() => ['95%'], []) function CustomBackground({ style }: BottomSheetBackgroundProps) { const containerAnimatedStyle = sx({ backgroundColor: '$background' }) const containerStyle = useMemo( () => [style, containerAnimatedStyle], [style, containerAnimatedStyle] ) return <Animated.View pointerEvents="none" style={containerStyle} /> } const truncatedTitle = truncateEnd(title, 50) const truncatedAuthors = authors && authors.length > 0 && truncateEnd(authors.join(', '), 35) return ( <View sx={container}> <AnimatedPressable style={contentStyles} onPress={handlePresentModalPress} > {thumbnail && ( <ThumbnailImage src={thumbnail} style={{ marginRight: 10, }} /> )} <View sx={textContainer}> <Text variant="bookTitle">{truncatedTitle}</Text> {truncatedAuthors ? ( <Text>By {truncatedAuthors}</Text> ) : ( <Text>No authors data</Text> )} <PageCounter count={pageCount} /> </View> </AnimatedPressable> <View sx={buttonContainer}> <Button type="secondary" round title={buttonTitle} onPress={buttonOnPress} iconName={buttonIcon} /> </View> <BottomSheetModal ref={bottomSheetModalRef} index={0} snapPoints={snapPoints} style={shadowStyle} backgroundComponent={CustomBackground} handleIndicatorStyle={{ backgroundColor: theme.colors.$text, }} > <BottomSheetView style={{ flex: 1, }} > {renderContent()} </BottomSheetView> </BottomSheetModal> </View> ) }
<?php namespace App\Models; use Illuminate\Contracts\Auth\MustVerifyEmail; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Foundation\Auth\User as Authenticatable; use Illuminate\Notifications\Notifiable; use App\Models\Role; class User extends Authenticatable { use HasFactory, Notifiable; /** * The attributes that are mass assignable. * * @var array */ protected $guarded = ['id', 'created_at','updated_at','email_verified_at','remember_token']; /** * The attributes that should be hidden for arrays. * * @var array */ protected $hidden = [ 'password', 'remember_token', ]; /** * The attributes that should be cast to native types. * * @var array */ protected $casts = [ 'email_verified_at' => 'datetime', ]; public function hasRole($role) { if ($this->roles()->where('role', $role)->first()) { return true; } return false; } public function roles() { return $this->belongsToMany(Role::class); } public function addresses() { return $this->hasMany(Address::class); } public function carts() { return $this->hasMany(Cart::class); } }
import 'package:flutter/material.dart'; class GradientContainer extends StatelessWidget { final Widget child; final List<Color> colors; GradientContainer({required this.child, required this.colors}); @override Widget build(BuildContext context) { return Container( decoration: BoxDecoration( gradient: LinearGradient( colors: colors, begin: Alignment.topCenter, end: Alignment.bottomCenter, stops: [0.5, 1.0], ), ), child: child, ); } }
/* eslint-disable react-hooks/exhaustive-deps */ import React, { useEffect, useState } from "react"; import { fetchData, optionsExercise } from "../api/FetchData"; import { Box, Pagination, Stack, Typography } from "@mui/material"; import { ExerciseCard } from "./ExerciseCard"; export function Exercises({ setExercises, exercises, bodyPart }) { const [currentPage, setCurrentPage] = useState(1); const [exercisesPerPage] = useState(6); useEffect(()=>{ console.log(exercises) },[exercises]) useEffect(() => { const exerciseFilter = async () => { if (bodyPart === "all") { const exerciseData = await fetchData( "https://exercisedb.p.rapidapi.com/exercises?limit=400", optionsExercise ); setExercises(exerciseData); } else { const exerciseData = await fetchData( `https://exercisedb.p.rapidapi.com/exercises/bodyPart/${bodyPart}`, optionsExercise ); console.log("bodyPart", exerciseData) setExercises(exerciseData); } }; exerciseFilter(); }, [bodyPart]); // pagination const indexOfLastExercise = currentPage * exercisesPerPage; const indexOfFirstExercise = indexOfLastExercise - exercisesPerPage; const currentExercises = exercises.slice( indexOfFirstExercise, indexOfLastExercise ); const paginate = (event, value) => { setCurrentPage(value); window.scrollTo({ top: 1800, behavior: "smooth" }); }; return ( <Box id="exercises" sx={{ mt: { lg: "109px" } }} mt="50px" p="20px"> <Typography variant="h4" fontWeight="bold" sx={{ fontSize: { lg: "44px", xs: "30px" } }} mb="46px" > Showing Results </Typography> <Stack direction="row" sx={{ gap: { lg: "107px", xs: "50px" } }} flexWrap="wrap" justifyContent="center" > {currentExercises.map((exercise, idx) => ( <ExerciseCard key={idx} exercise={exercise} /> ))} </Stack> <Stack sx={{ mt: { lg: "114px", xs: "70px" } }} alignItems="center"> {exercises.length > 9 && ( <Pagination color="standard" shape="rounded" defaultPage={1} count={Math.ceil(exercises.length / exercisesPerPage)} page={currentPage} onChange={paginate} size="large" /> )} </Stack> </Box> ); }
<?php use App\Events\MessagePosted; /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | contains the "web" middleware group. Now create something great! | */ Route::get('/', function () { return view('welcome'); }); // ->middleware('auth') sorgt dafuer, dass /chat nur fuer registrierte nutzer zugaenglich ist Route::get('/chat', function (){ return view('chat'); })->middleware('auth'); Route::get('/messages', function () { return App\Message::with('user')->get(); })->middleware('auth'); Route::post('/messages', function () { //store new message $user = Auth::user(); $message = $user->messages()->create([ 'message' => request()->get('message') ]); //Announce that a new msg has been posted broadcast(new MessagePosted($message,$user))->toOthers(); return ['status' => 'OK']; })->middleware('auth'); Auth::routes(); Route::get('/home', 'HomeController@index')->name('home');
# Mодуль InstanceCounter, содержащий методы класса и инстанс-методы, которые подключаются автоматически при вызове include module InstanceCounter def self.included(base) base.extend ClassMethods base.include InstanceMethods end attr_reader :instances module ClassMethods # Метод класса, который возвращает кол-во экземпляров данного класса def instances_count @instances ||= 0 @instances += 1 end def instances @instances end end module InstanceMethods # Метод, который увеличивает счетчик кол-ва экземпляров класса и который можно вызвать из конструктора. При этом данный метод не должен быть публичным. protected def register_instance self.class.instances_count end end end
import torch from torch import nn from torchvision import transforms as T from PIL import Image import numpy as np from pathlib import Path import random, datetime, os import gym from gym.spaces import Box from gym.wrappers import FrameStack from nes_py.wrappers import JoypadSpace import gym_super_mario_bros from tensordict import TensorDict from torchrl.data import TensorDictReplayBuffer, LazyMemmapStorage class SkipFrame(gym.Wrapper): def __init__(self, env, skip): """Return only every `skip`-th frame""" super().__init__(env) self._skip = skip def step(self, action): """Repeat action, and sum reward""" total_reward = 0.0 for i in range(self._skip): # Accumulate reward and repeat the same action obs, reward, done, trunk, info = self.env.step(action) total_reward += reward if done: break return obs, total_reward, done, trunk, info class GrayScaleObservation(gym.ObservationWrapper): def __init__(self, env): super().__init__(env) obs_shape = self.observation_space.shape[:2] self.observation_space = Box(low=0, high=255, shape=obs_shape, dtype=np.uint8) def permute_orientation(self, observation): observation = np.transpose(observation, (2, 0, 1)) observation = torch.tensor(observation.copy(), dtype=torch.float) return observation def observation(self, observation): observation = self.permute_orientation(observation) transform = T.Grayscale() observation = transform(observation) return observation class ResizeObservation(gym.ObservationWrapper): def __init__(self, env, shape): super().__init__(env) if isinstance(shape, int): self.shape = (shape, shape) else: self.shape = tuple(shape) obs_shape = self.shape + self.observation_space.shape[2:] self.observation_space = Box(low=0, high=255, shape=obs_shape, dtype=np.uint8) def observation(self, observation): transforms = T.Compose( [T.Resize(self.shape, antialias=True), T.Normalize(0, 255)] ) observation = transforms(observation).squeeze(0) return observation
import { reactive, toRefs } from "vue" import { upload, fileList } from './interface/upload' import { uploadFile } from '@/apis/common' import { $$t } from '@/plugins/language/setupI18n'; import { UploadProps, UploadChangeParam, message, UploadFile } from 'ant-design-vue' export const useUpload = ({ uploadRule, setEmit, fileSize, total, fileAction, handUpload, beforeLoad, }: upload.hookProps) => { const state = reactive<upload.stateProps>({ fileListData: [], //显示的文件 notFileList: [], //待上传文件 action: '', //上传地址 visible: false, //预览 currentFile: null }) // 设置请求前缀 const { VITE_API_URL } = import.meta.env state.action = `${VITE_API_URL}${fileAction}` // 处理默认fileList const setFileList = (fileList: UploadProps['fileList']) => { beforeLoad ? beforeLoad(fileList, state) : state.fileListData = fileList || [] } const uploadSize = (file: UploadFile): boolean => { const isMax = file.size / 1024 / 1024 < fileSize; if (!isMax) message.warn(`${$$t('messages.fileSizeMax', { num: fileSize })}`) return isMax } const beforeUpload = (file: UploadFile, fileList: UploadProps['fileList']) => { if (state.fileListData.length >= total) { message.warn(`${$$t('messages.uploadMaxNum', { num: total })}`) return false } if (!uploadSize(file) || !uploadRule(file)) { //判断文件类型,大小 setTimeout(() => state.fileListData.pop(), 100) return false } if (handUpload) { //自定义上传 state.notFileList.push(file) return false } return true } // 变化事件 const upChange = (info: UploadChangeParam<UploadFile<uploadFile>>) => { let { status, response } = info.file if (status === 'done') { let { code, data, message: msg } = response state.fileListData.pop() if (code === 200) { state.fileListData.push({ url: data.url, status: 'done', uid: String(data.id), name: data.name }) setEmit('change', state) } else { message.warn(msg ?? $$t('messages.uploadFailed')) } } else if (status === 'removed') { state.notFileList = state.notFileList.filter(x => x.uid !== info.file.uid) setEmit('change', state) } } // 手动上传 const handUploadFn = () => { setEmit('handUpload', state) } const handlePreview = (flie: fileList) => { state.visible = true state.currentFile = flie } return { ...toRefs(state), beforeUpload, upChange, setFileList, handUploadFn, handlePreview } }
import React from "react"; import DiagnosisListItem from "./DiagnosisListItem"; interface DiagnosisListProps { diagnosisCodes: string[] | undefined, } const DiagnosisList = ({ diagnosisCodes }: DiagnosisListProps): JSX.Element => { let diagnoses = <div style={{fontStyle: "italic", color: "gray"}}>No diagnoses.</div>; if (Array.isArray(diagnosisCodes)) { diagnoses = ( <div style={{marginTop: "0.3em"}}> <div>Diagnoses:</div> <ul className="diagnoseList" style={{paddingLeft: "1.5em", margin: "0.3em 0 0 0"}}> {diagnosisCodes.map(c => <li key={c}><DiagnosisListItem code={c} /></li>)} </ul> </div> ); } return diagnoses; }; export default DiagnosisList;
import { lazy, Suspense } from 'solid-js' import { Router, Routes, Route } from 'solid-app-router' import AppHeader from './AppHeader' import AppFooter from './AppFooter' import '@/styles/app.css' const Airports = lazy(() => import('@/modules/airports/components/Airports')) const Bookings = lazy(() => import('@/modules/bookings/components/Bookings')) const Crews = lazy(() => import('@/modules/crews/components/Crews')) const Country = lazy(() => import('@/modules/crews/components/Country')) const CountryDetails = lazy(() => import('@/modules/crews/components/CountryDetails')) const Airport = lazy(() => import('@/modules/crews/components/Airport')) const AirportDetails = lazy(() => import('@/modules/crews/components/AirportDetails')) const Crew = lazy(() => import('@/modules/crews/components/Crew')) const CrewDetails = lazy(() => import('@/modules/crews/components/CrewDetails')) const CrewSettings = lazy(() => import('@/modules/crews/components/CrewSettings')) // const UnknownCountry = lazy(() => import('./UnknownCountry')) // const UnknownAirport = lazy(() => import('./UnknownAirport')) // const UnknownCrew = lazy(() => import('./UnknownCrew')) const UnknownModule = lazy(() => import('@/modules/UnknownModule')) const App = () => { return ( <Router> <AppHeader /> <Suspense fallback={() => 'Loading...'}> <Routes> <Route path="/airports" element={<Airports />} /> <Route path="/bookings" element={<Bookings />} /> <Route path="/crews" element={<Crews />}> <Route path="/:country" element={<Country />}> <Route path="/" element={<CountryDetails />} /> <Route path="/:airport" element={<Airport />}> <Route path="/" element={<AirportDetails />} /> <Route path="/:crew" element={<Crew />}> <Route path="/" element={<CrewDetails />} /> <Route path="/settings" element={<CrewSettings />} /> </Route> </Route> </Route> <Route path="/" element={<div class="crews-home">Crews Home will be here.</div>}/> </Route> <Route path="/" element={<Airports />} /> <Route path="/*all" element={<UnknownModule />} /> </Routes> </Suspense> <AppFooter /> </Router> ) } export default App
import { Handler, HandlerResponse } from "@netlify/functions" import { ApiAuthenticatedHandler, AuthenticatedHandlerContext, } from "@heist/common/contracts" const makeResponse = (statusCode: number, body: unknown): HandlerResponse => { const result: HandlerResponse = { statusCode, } if (body) result.body = JSON.stringify(body) return result } export const makeHandler = (handler: Handler): Handler => { return async (event, context) => { try { const result = await handler(event, context) return makeResponse(200, result) } catch (e) { return makeResponse(400, e) } } } export const makeAuthenticatedHandler = < // eslint-disable-next-line @typescript-eslint/no-explicit-any THandler extends ApiAuthenticatedHandler<any, any> >( handler: THandler ): Handler => { return async (event, context) => { if (!context.clientContext) { return makeResponse( 400, "No clientContext provided for authenticated route" ) } try { const request = ( event.body ? JSON.parse(event.body) : {} ) as Parameters<THandler>[0] const result = await handler( request, event, context as AuthenticatedHandlerContext ) return makeResponse(200, result) } catch (e) { console.log("Error", e) return makeResponse(400, e) } } } export const getUserInfo = ( context: AuthenticatedHandlerContext ): { userId: string; full_name?: string } => { const user = context.clientContext.user if (!user.user_metadata.userId) throw new Error("No userId") return { userId: user.user_metadata.userId, full_name: user.user_metadata.full_name, } }
import numpy as np from sklearn.model_selection import train_test_split import matplotlib.pyplot as plt from sklearn.metrics import accuracy_score # ÖNEMLİ # Debug modu: True ise işlemler çıktı ekranına yazdırılır, False ise yazdırılmaz *** DEBUG_MODE = True # Sigmoid aktivasyon fonksiyonu def sigmoid(x): return 1 / (1 + np.exp(-x)) # Sigmoid fonksiyonunun türevi def sigmoid_turevi(x): return x * (1 - x) # Model parametrelerinin başlatılması def parametreleri_baslat(giris_boyutu, gizli_boyut, cikis_boyutu): W1 = np.random.randn(giris_boyutu, gizli_boyut) # Gizli katman ağırlıklar b1 = np.zeros((1, gizli_boyut)) # Gizli katman bias değerleri W2 = np.random.randn(gizli_boyut, cikis_boyutu) # Gizli katman ağırlık b2 = np.zeros((1, cikis_boyutu)) # Çıkış bias return W1, b1, W2, b2 # İleri yayılım işlemi def ileri_yayilim(X, W1, b1, W2, b2): Z1 = np.dot(X, W1) + b1 # Giriş verisini gizli katmana aktarma A1 = sigmoid(Z1) # Gizli katman çıkışlarını sigmoid fonksiyonundan geçirme Z2 = np.dot(A1, W2) + b2 # Gizli katman çıkışlarını çıkış katmanına aktarma A2 = sigmoid(Z2) # Çıkış katman çıkışlarını sigmoid fonksiyonundan geçirme return Z1, A1, Z2, A2 # Hata hesaplama def hata_hesapla(A2, Y): m = Y.shape[0] # Veri noktalarının sayısını alma hata = -np.sum(np.multiply(np.log(A2), Y) + np.multiply(np.log(1 - A2), (1 - Y))) / m return hata # Geri yayılım işlemi def geri_yayilim(X, Y, Z1, A1, Z2, A2, W1, W2, b1, b2, ogrenme_orani): m = X.shape[0] # Veri noktalarının sayısını alma dZ2 = A2 - Y # çıkışta hata hesaplama # Çıkış katmanındaki ağırlıkların güncellenmesi dW2 = (1 / m) * np.dot(A1.T, dZ2) db2 = (1 / m) * np.sum(dZ2, axis=0, keepdims=True) # Gizli katmandaki hata hesaplama dZ1 = np.dot(dZ2, W2.T) * sigmoid_turevi(A1) # Gizli katmandaki ağırlıkların güncellenmesi dW1 = (1 / m) * np.dot(X.T, dZ1) db1 = (1 / m) * np.sum(dZ1, axis=0, keepdims=True) # Ağırlıkların güncellenmesi W1 -= ogrenme_orani * dW1 b1 -= ogrenme_orani * db1 W2 -= ogrenme_orani * dW2 b2 -= ogrenme_orani * db2 if DEBUG_MODE: # geri yayılım hesaplamalarını çıktı oalrak yazdırma print("Geri Yayılım Hesaplamaları:") print("dW1:", dW1) print("db1:", db1) print("dW2:", dW2) print("db2:", db2) return W1, b1, W2, b2 # Sinir ağı modelinin eğitimi def sinir_agi_egitimi(X_train, y_train, X_test, y_test, giris_boyutu, gizli_boyut, cikis_boyutu, ogrenme_orani, iterasyon_sayisi): # Parametreleri başlatma W1, b1, W2, b2 = parametreleri_baslat(giris_boyutu, gizli_boyut, cikis_boyutu) y_train = y_train.astype(int) # y_train'i tamsayıya dönüştür y_test = y_test.astype(int) # y_test'i tamsayıya dönüştür # Eğitim ve test verisi için maliyet ve doğruluk metriklerinin listeleri egitim_maliyetleri = [] test_maliyetleri = [] egitim_dogruluklari = [] test_dogruluklari = [] # Eğitim döngüsü for iterasyon in range(iterasyon_sayisi): # İleri ve geri yayılım Z1, A1, Z2, A2 = ileri_yayilim(X_train, W1, b1, W2, b2) W1, b1, W2, b2 = geri_yayilim(X_train, y_train.reshape(-1, 1), Z1, A1, Z2, A2, W1, W2, b1, b2, ogrenme_orani) # Eğitim verisi üzerinde maliyeti hesapla ve kaydet egitim_maliyeti = hata_hesapla(A2, y_train.reshape(-1, 1)) egitim_maliyetleri.append(egitim_maliyeti) # Eğitim verisi üzerinde doğruluk hesapla ve kaydet egitim_tahminleri = tahmin_et(X_train, W1, b1, W2, b2) egitim_tahminleri = (egitim_tahminleri > 0.5).astype(int) egitim_dogrulugu = accuracy_score(y_train, egitim_tahminleri) egitim_dogruluklari.append(egitim_dogrulugu) # Test verisi üzerinde maliyeti hesapla ve kaydet Z1_test, A1_test, Z2_test, A2_test = ileri_yayilim(X_test, W1, b1, W2, b2) test_maliyeti = hata_hesapla(A2_test, y_test.reshape(-1, 1)) test_maliyetleri.append(test_maliyeti) # Test verisi üzerinde doğruluk hesapla ve kaydet test_tahminleri = tahmin_et(X_test, W1, b1, W2, b2) test_dogrulugu = accuracy_score(y_test, test_tahminleri) test_dogruluklari.append(test_dogrulugu) # Her 100 iterasyonda bir eğitim ve test verisi için maliyeti ve doğruluğu yazdır if iterasyon % 100 == 0: if DEBUG_MODE: print(f"Iterasyon {iterasyon}:") print(f" Eğitim Maliyeti: {egitim_maliyeti}, Eğitim Doğruluğu: {egitim_dogrulugu}") print(f" Test Maliyeti: {test_maliyeti}, Test Doğruluğu: {test_dogrulugu}") return W1, b1, W2, b2, egitim_maliyetleri, test_maliyetleri, egitim_dogruluklari, test_dogruluklari # Modelin test verisi üzerinde tahmin yapması def tahmin_et(X_test, W1, b1, W2, b2): _, _, _, tahminler = ileri_yayilim(X_test, W1, b1, W2, b2) tahminler = (tahminler > 0.5).astype(int) return tahminler # Veriyi yükleme ve eğitim/test kümelerine ayırma veri_yolu = "C:\\Users\\FIRAT\\Desktop\\myProject\\veri-madenciligi\\Backpropagation-Projesi\\data.txt" # Veri yolu belirtilmeli veri = np.loadtxt(veri_yolu) X = veri[:, :-1] y = veri[:, -1] X_egitim, X_test, y_egitim, y_test = train_test_split(X, y, test_size=0.2, random_state=42) # Hiperparametreler giris_boyutu = X_egitim.shape[1] gizli_boyut = 10 # Değiştirilebilir cikis_boyutu = 1 # İkili sınıflandırma varsayımı ogrenme_orani = 0.01 iterasyon_sayisi = 1000 # Modeli eğitme W1, b1, W2, b2, egitim_maliyetleri, test_maliyetleri, egitim_dogruluklari, test_dogruluklari = sinir_agi_egitimi(X_egitim, y_egitim, X_test, y_test, giris_boyutu, gizli_boyut, cikis_boyutu, ogrenme_orani, iterasyon_sayisi) # Sonuçları görselleştirme plt.figure(figsize=(12, 5)) # Eğitim ve test maliyetlerini çizdirme plt.subplot(1, 2, 1) plt.plot(range(iterasyon_sayisi), egitim_maliyetleri, label='Eğitim') plt.plot(range(iterasyon_sayisi), test_maliyetleri, label='Test') plt.xlabel('Iterasyon') plt.ylabel('Maliyet') plt.title('Eğitim ve Doğrulama Kaybı') plt.legend() # Eğitim ve test doğruluklarını çizdirme plt.subplot(1, 2, 2) plt.plot(range(iterasyon_sayisi), egitim_dogruluklari, label='Eğitim') plt.plot(range(iterasyon_sayisi), test_dogruluklari, label='Test') plt.xlabel('Iterasyon') plt.ylabel('Doğruluk') plt.title('Eğitim ve Doğrulama Doğruluğu') plt.legend() plt.tight_layout() plt.show()
const express = require('express'); const router = express.Router(); const multer = require("multer"); const upload = multer({ storage: multer.memoryStorage(), // or use multer.diskStorage() for disk storage limits: { fileSize: 5 * 1024 * 1024, // Adjust the file size limit as needed }, }); const cloudinary = require("cloudinary").v2; const streamifier = require("streamifier"); const Video = require('../models/Video'); const User = require('../models/User'); const Ebook = require('../models/Ebook') const Follow=require('../models/Follow') const auth = require('../middleware/auth') require('dotenv').config(); cloudinary.config({ cloud_name: process.env.CLOUD_NAME, api_key: process.env.API_KEY, api_secret: process.env.API_SECRET, secure: true, }); let streamUpload = (req) => { return new Promise((resolve, reject) => { let stream = cloudinary.uploader.upload_stream((error, result) => { if (result) { resolve(result); } else { reject(error); } }); streamifier.createReadStream(req.file.buffer).pipe(stream); }); }; async function uploadFile(req) { let result = await streamUpload(req); return result; } router.get('/videos', async (req, res) => { const { page = 1, limit = 10, sortBy, sortOrder, filterByViews, filterByAuthor, type } = req.query; const options = { page: parseInt(page), limit: parseInt(limit), sort: sortBy ? { [sortBy]: sortOrder === 'desc' ? -1 : 1 } : null, }; try { let query = {}; query.disabled = false; if (filterByViews) { query.views = filterByViews; } if (filterByAuthor) { query.author = filterByAuthor; } if (type) { query.author = type; } const videos = await Video.paginate(query, options); console.log(videos); const authorIds = videos.docs.map(video => video.author); const authors = await User.find({ _id: { $in: authorIds } }, 'username'); const videosWithAuthorNames = videos.docs.map(video => { const author = authors.find(author => author._id.equals(video.author)); return { ...video.toObject(), author: author ? author.username : null, authorId: author ? author._id : null }; }); const modifiedPaginatedResult = { ...videos, docs: videosWithAuthorNames }; res.json(modifiedPaginatedResult); } catch (err) { console.error(err.message); res.status(500).send('Server Error'); } }); // router.get('/videos/mine', auth, async (req, res) => { // try { // const authorId = req.user.id; // console.log(authorId); // const posts = await BlogPost.find({ author: authorId }); // res.json(posts); // } catch (err) { // console.error(err.message); // res.status(500).send('Server Error'); // } // }); router.get('/videos/mine', auth, async (req, res) => { const { type } = req.query; try { console.log(type); const videos = await Video.find({ author: req.user.id }) .populate('author', 'username fullName profilePic'); // Populate the author field let filteredVideos = []; if (type == "live"){ filteredVideos = videos.filter(video => video.type === "Live"); }else{ filteredVideos = videos.filter(video => video.type != "Live"); } const videosWithAuthorNames = filteredVideos.map(video => { return { ...video.toObject(), author: video.author ? video.author.username : null, authorId: video.author ? video.author._id : null, authorName: video.author ? video.author.fullName : null, authorProfilePic: video.author ? video.author.profilePic : null, }; }); res.json(videosWithAuthorNames); } catch (err) { console.error(err.message); res.status(500).send('Server Error'); } }); router.get('/author/:id/videos', async (req, res) => { const { type } = req.query; try { const videos = await Video.find({ author: req.params.id }) .populate('author', 'username fullName profilePic'); // Populate the author field let filteredVideos = []; if (type == "live"){ filteredVideos = videos.filter(video => video.type === "Live"); }else{ filteredVideos = videos.filter(video => video.type != "Live"); } const videosWithAuthorNames = filteredVideos.map(video => { return { ...video.toObject(), author: video.author ? video.author.username : null, authorId: video.author ? video.author._id : null, authorName: video.author ? video.author.fullName : null, authorProfilePic: video.author ? video.author.profilePic : null, }; }); res.json(videosWithAuthorNames); } catch (err) { console.error(err.message); res.status(500).send('Server Error'); } }); router.get('/ebooks/mine', auth, async (req, res) => { const { type } = req.query; try { console.log(type); const ebooks = await Ebook.find({ author: req.user.id }) .populate('author', 'username fullName profilePic'); // Populate the author field let filteredEbooks = []; if (type){ if (type == "free"){ filteredEbooks = ebooks.filter(ebook => ebook.type === "Free"); }else{ filteredEbooks = ebooks.filter(ebook => ebook.type != "Free"); } }else{ filteredEbooks = ebooks; } const ebooksWithAuthorNames = filteredEbooks.map(ebook => { return { ...ebook.toObject(), author: ebook.author ? ebook.author.username : null, authorId: ebook.author ? ebook.author._id : null, authorName: ebook.author ? ebook.author.fullName : null, authorProfilePic: ebook.author ? ebook.author.profilePic : null, }; }); res.json(ebooksWithAuthorNames); } catch (err) { console.error(err.message); res.status(500).send('Server Error'); } }); // router.post('/upload/video', upload.single("file"), async (req, res)=>{ // if (req.file){ // const uploadedVideoFile = await uploadFile(req); // res.json({url: uploadedVideoFile.url}); // console.log(uploadedVideoFile.url); // }else{ // res.status(404).json({msg: "Attach the File"}); // } // }) router.post('/ebooks', auth, async (req, res) => { console.log("Ebooks"); let { title, introduction, category, coverImage, contents, price, bookType } = req.body; console.log("Ebooks"); console.log(req.body); console.log("Ebooks"); const newEbook = new Ebook({ title: title, author: req.user.id, coverImage: coverImage, type: bookType == 'free' ? 'Free' : 'Paid', introduction: introduction, price: price, category: category, contents: contents, }); const ebook = await newEbook.save(); res.json(ebook); }); router.post('/videos', auth, upload.single('coverImage'), async (req, res) => { if (req.file) { try { const uploadedImage = await uploadFile(req); let { title, description, publishTime, videoUrl } = req.body; publishTime==="Now"? publishTime = "Published" : "Upcoming"; const newVideo = new Video({ title, description, author: req.user.id, coverImage: uploadedImage.url, type: publishTime, videoFile: videoUrl, }); const video = await newVideo.save(); res.json(video); } catch (err) { console.error(err.message); res.status(500).send('Server Error'); } } else { res.status(400).send('Attach coverImage'); } }); router.post('/videos/live', auth, async (req, res) => { try { let { serverUrl, streamKey, title, coverImage, introduction } = req.body; const newVideo = new Video({ title: title, description: introduction, author: req.user.id, coverImage: coverImage, type: "Live", streamKey: streamKey, serverUrl: serverUrl }); const video = await newVideo.save(); res.json(video); } catch (err) { console.error(err.message); res.status(500).send('Server Error'); } }); // Handle video file upload router.post('/upload/video', upload.single('file'), async (req, res) => { try { if (!req.file) { return res.status(400).json({ error: 'No file provided' }); } const result = await cloudinary.uploader.upload_stream({ resource_type: 'video' }, (error, result) => { if (result) { res.json({ url: result.secure_url }); } else { console.error(error); res.status(500).json({ error: 'Error uploading video' }); } }).end(req.file.buffer); } catch (error) { console.error(error); res.status(500).json({ error: 'Server error' }); } }); // Handle video file upload router.post('/upload/image', upload.single('file'), async (req, res) => { try { if (!req.file) { return res.status(400).json({ error: 'No file provided' }); } const result = await uploadFile(req); console.log(result); res.json({url: result.url}); } catch (error) { console.error(error); res.status(500).json({ error: 'Server error' }); } }); router.delete('/videos/:id', auth, async (req, res) => { try { console.log(req.params.id); const video = await Video.findById(req.params.id); if (!video) { return res.status(404).json({ msg: 'Video not found' }); } if (video.author.toString() !== req.user.id) { return res.status(403).json({ msg: 'Access denied. Not the video author' }); } await video.deleteOne(); res.json({ msg: 'Video deleted successfully' }); } catch (err) { console.error(err.message); res.status(500).send('Server Error'); } }) router.delete('/ebooks/:id', auth, async (req, res) => { try { const ebook = await Ebook.findById(req.params.id); if (!ebook) { return res.status(404).json({ msg: 'Ebook not found' }); } if (ebook.author.toString() !== req.user.id) { return res.status(403).json({ msg: 'Access denied. Not the ebook author' }); } await ebook.deleteOne(); res.json({ msg: 'Ebook deleted successfully' }); } catch (err) { console.error(err.message); res.status(500).send('Server Error'); } }); router.get('/MustWatchLive', async (req, res) => { try { const videos = await Video.find({ type: 'Live' }).populate('author', 'fullName profilePic'); const fetchedData = videos.map(video => ({ name: video.author.fullName, title: video.title, source: video.coverImage, views: video.views, type: video.type, imageSrc: video.author.profilePic })); console.log(fetchedData); res.status(200).json(fetchedData); } catch (error) { res.status(500).json({ message: error.message }); } }); router.get('/TopStreamers', async (req, res) => { try { const users = await User.find({}, '_id fullName userInfo'); const userCounts = await Promise.all( users.map(async user => { const followerCount = await Follow.countDocuments({ following: user._id }); return { _id: user._id, fullName: user.fullName, userInfo: user.userInfo, followersCount: followerCount }; }) ); console.log(userCounts) res.status(200).json(userCounts); } catch (error) { res.status(500).json({ message: error.message }); } }); router.get('/TrendingVideo', async (req, res) => { try { const videos = await Video.find({ type: 'Published' }).populate('author', 'fullName profileImage'); const fetchedData = videos.map(video => ({ name: video.author.fullName, title: video.title, source: video.coverImage, views: video.views, type: video.type, imageSrc: video.author.profileImage })); res.status(200).json(fetchedData); } catch (error) { res.status(500).json({ message: error.message }); } }); router.get('HotVideos', async (req, res) => { try { const videos = await Video.find({ type: 'Upcoming' }).populate('author', 'fullName profileImage'); const fetchedData = videos.map(video => ({ name: video.author.fullName, title: video.title, source: video.coverImage, views: video.views, type: video.type, imageSrc: video.author.profileImage })); res.status(200).json(fetchedData); } catch (error) { res.status(500).json({ message: error.message }); } }); router.get('/popularbooks', async (req, res) => { try { const books = await Ebook.find({ category: "Published" }).populate('author', 'fullName profilePic'); const fetchedData = books.map(book => ({ name: book.author.fullName, title: book.title, source: book.coverImage, views: book.views, type: book.type, imageSrc: book.author.profilePic })); res.status(200).json(fetchedData); } catch (error) { res.status(500).json({ message: error.message }); } }); router.get('/TopLecturer',async(req,res)=>{ try { const users = await User.find({}, '_id fullName userInfo profilePic'); const userCounts = await Promise.all( users.map(async user => { const followerCount = await Follow.countDocuments({ following: user._id }); return { _id: user._id, fullName: user.fullName, userInfo: user.userInfo, ProfileImage:user.profilePic, followersCount: followerCount }; }) ); res.status(200).json(userCounts); } catch (error) { res.status(500).json({ message: error.message }); } }); router.get('/Books/Novels', async (req, res) => { try { const books = await Ebook.find({ category: "Novel" }).populate('author', 'fullName profilePic'); const fetchedData = books.map(book => ({ name: book.author.fullName, title: book.title, source: book.coverImage, views: book.views, type: book.type, imageSrc: book.author.profilePic })); console.log(fetchedData); res.status(200).json(fetchedData); } catch (error) { res.status(500).json({ message: error.message }); } }); router.get('/Books/Education', async (req, res) => { try { const books = await Ebook.find({ category: "Education" }).populate('author', 'fullName profilePic'); const fetchedData = books.map(book => ({ name: book.author.fullName, title: book.title, source: book.coverImage, views: book.views, type: book.type, imageSrc: book.author.profilePic })); console.log(fetchedData); res.status(200).json(fetchedData); } catch (error) { res.status(500).json({ message: error.message }); } }); router.get('/Books/ScienceFiction', async (req, res) => { try { const books = await Ebook.find({ category: "Science Fiction" }).populate('author', 'fullName profilePic'); const fetchedData = books.map(book => ({ name: book.author.fullName, title: book.title, source: book.coverImage, views: book.views, type: book.type, imageSrc: book.author.profilePic })); console.log(fetchedData); res.status(200).json(fetchedData); } catch (error) { res.status(500).json({ message: error.message }); } }); router.get('/AllLecturer', async (req, res) => { try { const totalUsersCount = await User.countDocuments(); const users = await User.find({}, '_id fullName userInfo profilePic rating works hashtag'); const userCounts = await Promise.all( users.map(async user => { const followerCount = await Follow.countDocuments({ following: user._id }); return { _id: user._id, fullName: user.fullName, userInfo: user.userInfo, profilePic: user.profilePic, // Corrected the property name to profilePic rating: user.rating, works: user.works, tags: user.hashtag, avgrating: user.rating / totalUsersCount, // Use totalUsersCount obtained earlier followersCount: followerCount }; }) ); res.status(200).json(userCounts); } catch (error) { res.status(500).json({ message: error.message }); } }); router.get('/VerifiedLecturer',async(req,res)=>{ try { const totalUsersCount = await User.countDocuments(); const users = await User.find({category:"Verified"}, '_id fullName userInfo profilePic rating works hashtag'); const userCounts = await Promise.all( users.map(async user => { const followerCount = await Follow.countDocuments({ following: user._id }); return { _id: user._id, fullName: user.fullName, userInfo: user.userInfo, profilePic: user.profilePic, // Corrected the property name to profilePic rating: user.rating, works: user.works, tags: user.hashtag, avgrating: user.rating / totalUsersCount, // Use totalUsersCount obtained earlier followersCount: followerCount }; }) ); console.log(userCounts); res.status(200).json(userCounts); } catch (error) { res.status(500).json({ message: error.message }); } }); router.get('/NotVerifiedLecturer',async(req,res)=>{ try { const totalUsersCount = await User.countDocuments(); const users = await User.find({category:"NotVerified"}, '_id fullName userInfo profilePic rating works hashtag'); const userCounts = await Promise.all( users.map(async user => { const followerCount = await Follow.countDocuments({ following: user._id }); return { _id: user._id, fullName: user.fullName, userInfo: user.userInfo, profilePic: user.profilePic, // Corrected the property name to profilePic rating: user.rating, works: user.works, tags: user.hashtag, avgrating: user.rating / totalUsersCount, // Use totalUsersCount obtained earlier followersCount: followerCount }; }) ); console.log(userCounts); res.status(200).json(userCounts); } catch (error) { res.status(500).json({ message: error.message }); } }); module.exports = router;
import { h, createApp } from 'vue' import singleSpaVue from 'single-spa-vue' import App from './App.vue' import router from './router' const vueLifeCycles = singleSpaVue({ createApp, appOptions: { el: '#vue-app-root', render(props: Record<PropertyKey, any> = {}) { return h(App, { ...props, // single-spa props are available on the "this" object. Forward them to your component as needed. // https://single-spa.js.org/docs/building-applications#lifecycle-props // if you uncomment these, remember to add matching prop definitions for them in your App.vue file. /* name: this.name, mountParcel: this.mountParcel, singleSpa: this.singleSpa, */ }) }, }, handleInstance(app) { app.use(router) }, }) export const bootstrap = vueLifeCycles.bootstrap export const mount = vueLifeCycles.mount export const unmount = vueLifeCycles.unmount
var PLAY = 1; var END = 0; var gameState = PLAY; var trex, trex_running, trex_collided; var ground, invisibleGround, groundImage; var cloudsGroup, cloudImage; var obstaclesGroup, obstacle1, obstacle2, obstacle3, obstacle4, obstacle5, obstacle6; var score=0; var gameOver, restart; localStorage["HighestScore"] = 0; function preload(){ trex_running = loadAnimation("trex1.png","trex3.png","trex4.png"); trex_collided = loadAnimation("trex_collided.png"); groundImage = loadImage("ground2.png"); cloudImage = loadImage("cloud.png"); obstacle1 = loadImage("obstacle1.png"); obstacle2 = loadImage("obstacle2.png"); obstacle3 = loadImage("obstacle3.png"); obstacle4 = loadImage("obstacle4.png"); obstacle5 = loadImage("obstacle5.png"); obstacle6 = loadImage("obstacle6.png"); gameOverImg = loadImage("gameOver.png"); restartImg = loadImage("restart.png"); } function setup() { createCanvas(600, 200); trex = createSprite(50,180,20,50); trex.addAnimation("running", trex_running); trex.addAnimation("collided", trex_collided); trex.scale = 0.5; ground = createSprite(200,180,400,20); ground.addImage("ground",groundImage); ground.x = ground.width /2; ground.velocityX = -(6 + 3*score/100); gameOver = createSprite(300,100); gameOver.addImage(gameOverImg); restart = createSprite(300,140); restart.addImage(restartImg); gameOver.scale = 0.5; restart.scale = 0.5; gameOver.visible = false; restart.visible = false; invisibleGround = createSprite(200,190,400,10); invisibleGround.visible = false; cloudsGroup = new Group(); obstaclesGroup = new Group(); score = 0; } function draw() { //trex.debug = true; background(180); text("Score: "+ score, 500,50); if (gameState===PLAY){ score = score + Math.round(getFrameRate()/60); ground.velocityX = -(6 + 3*score/100); if(keyDown("space") && trex.y >= 159) { trex.velocityY = -12; } trex.velocityY = trex.velocityY + 0.8 if (ground.x < 0){ ground.x = ground.width/2; } trex.collide(invisibleGround); spawnClouds(); spawnObstacles(); if(obstaclesGroup.isTouching(trex)){ gameState = END; } } else if (gameState === END) { gameOver.visible = true; restart.visible = true; //set velcity of each game object to 0 ground.velocityX = 0; trex.velocityY = 0; obstaclesGroup.setVelocityXEach(0); cloudsGroup.setVelocityXEach(0); //change the trex animation trex.changeAnimation("collided",trex_collided); //set lifetime of the game objects so that they are never destroyed obstaclesGroup.setLifetimeEach(-1); cloudsGroup.setLifetimeEach(-1); if(mousePressedOver(restart)) { reset(); } } drawSprites(); } function spawnClouds() { //write code here to spawn the clouds if (frameCount % 60 === 0) { var cloud = createSprite(600,120,40,10); cloud.y = Math.round(random(80,120)); cloud.addImage(cloudImage); cloud.scale = 0.5; cloud.velocityX = -3; //assign lifetime to the variable cloud.lifetime = 200; //adjust the depth cloud.depth = trex.depth; trex.depth = trex.depth + 1; //add each cloud to the group cloudsGroup.add(cloud); } } function spawnObstacles() { if(frameCount % 60 === 0) { var obstacle = createSprite(600,165,10,40); //obstacle.debug = true; obstacle.velocityX = -(6 + 3*score/100); //generate random obstacles var rand = Math.round(random(1,6)); switch(rand) { case 1: obstacle.addImage(obstacle1); break; case 2: obstacle.addImage(obstacle2); break; case 3: obstacle.addImage(obstacle3); break; case 4: obstacle.addImage(obstacle4); break; case 5: obstacle.addImage(obstacle5); break; case 6: obstacle.addImage(obstacle6); break; default: break; } //assign scale and lifetime to the obstacle obstacle.scale = 0.5; obstacle.lifetime = 300; //add each obstacle to the group obstaclesGroup.add(obstacle); } } function reset(){ gameState = PLAY; gameOver.visible = false; restart.visible = false; obstaclesGroup.destroyEach(); cloudsGroup.destroyEach(); trex.changeAnimation("running",trex_running); if(localStorage["HighestScore"]<score){ localStorage["HighestScore"] = score; } console.log(localStorage["HighestScore"]); score = 0; }
package baananou.taskmanager.restController; import baananou.taskmanager.models.Task; import baananou.taskmanager.services.ICategoryService; import baananou.taskmanager.services.ITaskService; import jakarta.validation.Valid; import lombok.AllArgsConstructor; import org.springframework.web.bind.annotation.*; import java.time.LocalDateTime; import java.util.List; @RestController @AllArgsConstructor @RequestMapping("/api/v1/tasks") public class TaskRestController { private ITaskService taskService; private ICategoryService categoryService; //Get all tasks Working @GetMapping("/") public List<Task> getAllTasks() { return taskService.getAllTasks(); } //Get task by id Working @GetMapping("/{id}") public Task getTaskById(@PathVariable Long id) { return taskService.getTaskById(id); } //Create New Task Working @PostMapping("/add") public void addTask(@Valid @RequestBody Task task) { // Ensure createdAt and updatedAt are set before saving task.setCreatedAt(LocalDateTime.now()); task.setUpdatedAt(LocalDateTime.now()); taskService.createTask(task); } //Delete Task Working @DeleteMapping("/delete/{id}") public void deleteTask(@PathVariable(name = "id") long id) { taskService.deleteTask(id); } //Update Task Not Working @PutMapping("/update/{id}") public void updateTask(@PathVariable(name = "id") long id, @Valid @RequestBody Task updatedTask) { // Set updatedAt field before updating the task updatedTask.setUpdatedAt(LocalDateTime.now()); // Set the ID for the updated task updatedTask.setId(id); updatedTask.setCreatedAt(updatedTask.getCreatedAt()); updatedTask.setUpdatedAt(LocalDateTime.now()); taskService.updateTask(id,updatedTask); } }
import { HttpStatus } from "@nestjs/common"; import { CE_ErrorCode } from "@/common/error-code"; import { AppHttpException } from "@/common/exception"; export class NoSuchProblemException extends AppHttpException { constructor(msg?: string) { super(HttpStatus.NOT_FOUND, CE_ErrorCode.Problem_NoSuchProblem, msg ?? "No such problem."); } } export class InvalidFileUploadTokenException extends AppHttpException { constructor(msg?: string) { super(HttpStatus.BAD_REQUEST, CE_ErrorCode.Problem_InvalidFileUploadToken, msg ?? "Invalid file upload token."); } } export class TooManyFileUploadRequestException extends AppHttpException { constructor(msg?: string) { super( HttpStatus.TOO_MANY_REQUESTS, CE_ErrorCode.Problem_TooManyFileUploadRequest, msg ?? "Too many file upload request.", ); } } export class TooLargeUploadFileException extends AppHttpException { constructor(msg?: string) { super(HttpStatus.BAD_REQUEST, CE_ErrorCode.Problem_TooLargeUploadFile, msg ?? "Too large upload file."); } } export class FileLimitExceededException extends AppHttpException { constructor(msg?: string) { super(HttpStatus.FORBIDDEN, CE_ErrorCode.Problem_FileLimitExceeded, msg ?? "File limit exceeded."); } }
import type { ComponentType, PropsWithChildren, ComponentProps } from 'react' import type { CmsComponent, ContentLinkWithLocale, ComponentFactory, ContentQueryProps, ContentType } from '@remkoj/optimizely-dxp-react' import { print } from 'graphql' import { createClient, Utils } from '@remkoj/optimizely-dxp-react' import { getFactory } from './factory' import * as Queries from './queries' import type * as GraphQL from './gql/graphql' import { gql } from 'graphql-request' const DEBUG = process.env.DXP_DEBUG == '1' const DEV = process.env.NODE_ENV == 'development' type CmsComponentProps = ComponentProps<CmsComponent> & { [key: string]: any } type EnhancedCmsComponent = ComponentType<CmsComponentProps> export type CmsContentProps = PropsWithChildren<{ /** * The content type to render */ contentType?: string[] /** * The content link to render */ contentLink: ContentLinkWithLocale /** * The initial, pre-loaded data. If set this will be used instead of having the * component fetching its' own data. So be sure that this leverages the fragment * specified by the component. * * It will filter out the fiels from the IContentData fragment, to determine if * data has been provided. */ fragmentData?: { [fieldname: string]: any } /** * The native key to use when the element is part of an array */ key?: string /** * If enabled, it will flag all rendering to be inclusive of the Optimizely Edit mode * attributes for On Page Editing */ inEditMode?: boolean /** * The Optimizely Graph client to use, it will use a new instance if none is provided, * the new instance will always use the SingleKey i.e. thus not load edit mode content */ client?: ReturnType<typeof createClient> /** * The component factory to use, it will use the default instance if not provided */ factory?: ComponentFactory /** * If enabled any warnings intended for an editor will be shown, even if "inEditMode" * is false. */ outputEditorWarning?: boolean /** * The prefix to apply to the content type, to allow loading of different templates based * upon location of usage. If set and the content type already starts with this prefix, * it will not be applied. */ contentTypePrefix?: string }> /** * React Server Side component for the CmsContent * * @param param0 * @returns */ export const CmsContent = async ({contentType, contentTypePrefix, contentLink, children, inEditMode, client, fragmentData, outputEditorWarning} : CmsContentProps) : Promise<JSX.Element> => { if ((DEBUG || DEV) && !client) console.warn(`[CmsContent] No Content Graph client provided with ${ JSON.stringify(contentLink) }, this will cause problems with edit mode!`) // Parse & prepare props const factory = getFactory() client = client ?? createClient() const isInlineBlock = Utils.isInlineContentLink(contentLink) // DEBUG Tracing if (DEBUG) console.log("[CmsContent] Rendering CMS Content for:", JSON.stringify(contentType), isInlineBlock ? "Inline content" : JSON.stringify({ id: contentLink.id, workId: contentLink.workId, guidValue: contentLink.guidValue, locale: contentLink.locale }), inEditMode ? "edit-mode" : "published") // Ensure we have a content type to work with if (!isInlineBlock && !contentType) { if (DEBUG || DEV) console.warn(`[CmsContent] No content type provided for content ${ JSON.stringify({ id: contentLink.id, workId: contentLink.workId, guidValue: contentLink.guidValue, locale: contentLink.locale }) }, this causes an additional GraphQL query to resolve the ContentType`) contentType = await getContentType(contentLink, client) } // Apply the content-type prefix if needed if (Array.isArray(contentType) && Utils.isNonEmptyString(contentTypePrefix) && contentType.length > 0 && contentType[0] != contentTypePrefix) { if (DEBUG) console.info(`[CmsContent] Component type [${ contentType.join('/')}] doesn't have the configured prefix, adding ${ contentTypePrefix } as prefix`) contentType.unshift(contentTypePrefix) } // Resolve component const Component = factory.resolve(contentType ?? "") as EnhancedCmsComponent | undefined if (!Component) { if (DEBUG || DEV) { console.warn(`[CmsContent] Component of type "${ contentType?.join('/') ?? "" }" not resolved by factory`) } if (DEBUG || inEditMode || outputEditorWarning) { const errorMsg = <div className='opti-error'>Component of type "{ contentType?.join('/') ?? "" }" not resolved by factory</div> return children ? <>{ errorMsg }{children}</> : errorMsg } return <>{children ? children : undefined }</> } if (DEBUG) console.log("[CmsContent] Rendering item using component:", Component?.displayName ?? Component) // Render with previously loaded data const fragmentProps = fragmentData ? Object.getOwnPropertyNames(fragmentData).filter(x => !Queries.CmsContentFragments.IContentDataProps.includes(x)) : [] if (fragmentProps.length > 0) { if (DEBUG) console.log("[CmsContent] Rendering CMS Component using fragment information", fragmentProps) if (Utils.validatesFragment(Component) && !Component.validateFragment(fragmentData)) { console.error("[CmsContent] Invalid fragment data received for ", Component.displayName ?? contentType?.join("/") ?? "[Undetermined component]") return <></> } return <Component inEditMode={ inEditMode } contentLink={ contentLink } data={ fragmentData || {} } client={ client } /> } // If we don't have previously loaded data we cannot load content for inline blocks if (isInlineBlock) return (DEBUG || inEditMode || outputEditorWarning) ? <div className='opti-error'>Inline blocks cannot be loaded individually</div> : <></> // Render using included query if (Utils.isCmsComponentWithDataQuery(Component)) { const gqlQuery = Component.getDataQuery() const gqlVariables : ContentQueryProps = Utils.contentLinkToRequestVariables(contentLink) as Omit<ContentLinkWithLocale, 'guidValue'> & { guidValue: string } if (DEBUG) console.log("[CmsContent] Component data fetching variables:", gqlVariables) const gqlResponse = await client.query<{}>(gqlQuery, gqlVariables) if (DEBUG) console.log("[CmsContent] Component request the following data:", gqlResponse) return <Component inEditMode={ inEditMode } contentLink={ contentLink } data={ gqlResponse } client={ client } /> } // Render using included fragment if (Utils.isCmsComponentWithFragment(Component)) { type FragmentQueryVariables = ContentQueryProps & { isCommonDraft?: boolean | null, guidValue: string } type FragmentQueryResponse = { contentById: { total: number, items: { contentType: string[], id: { id: number, workId: number, guidValue: string }, locale: { name: string }, [propertyName: string]: any }[] }} const [name, fragment] = Component.getDataFragment() const fragmentQuery = `query getContentFragmentById($id: Int!, $workId: Int, $guidValue: String, $locale: [Locales]!, $isCommonDraft: Boolean ) { contentById: Content( where: { ContentLink: { Id: { eq: $id }, WorkId: { eq: $workId }, GuidValue: { eq: $guidValue } },IsCommonDraft: {eq: $isCommonDraft} }, orderBy: { Status: ASC }, locale: $locale, limit: 1 ) { total items { contentType: ContentType id: ContentLink { id: Id, workId: WorkId, guidValue: GuidValue } locale: Language { name: Name } ...${ name } } } } ${ print(fragment) }` const fragmentVariables : FragmentQueryVariables = Utils.contentLinkToRequestVariables(contentLink) as FragmentQueryVariables if (!fragmentVariables?.workId && inEditMode) fragmentVariables.isCommonDraft = true if (DEBUG) console.log(`[CmsContent] Component data fetching using fragment ${ name }, with variables: ${ JSON.stringify(fragmentVariables) }`) const fragmentResponse = await client.request<FragmentQueryResponse, FragmentQueryVariables>(fragmentQuery, fragmentVariables) const totalItems = fragmentResponse.contentById.total || 0 if (totalItems < 1) throw new Error(`CmsContent expected to load exactly one content item, received ${ totalItems } from Optimizely Graph.`) if (totalItems > 1 && DEBUG) console.warn(`[CmsContent] Resolved ${ totalItems } content items, expected only 1. Picked the first one`) return <Component inEditMode={ inEditMode } contentLink={ contentLink } data={ fragmentResponse.contentById.items[0] } client={ client } /> } // Assume there's no server side prepared data needed for the component if (DEBUG) console.log(`[CmsContent] Component of type "${ contentType?.join('/') ?? Component.displayName ?? '?'}" did not request pre-loading of data`) return <Component inEditMode={ inEditMode } contentLink={ contentLink } data={ fragmentData || {} } client={ client } /> } export default CmsContent export async function getContentType(link: ContentLinkWithLocale, gqlClient: ReturnType<typeof createClient>) : Promise<ContentType | undefined> { if ((!link.id || link.id < 1) && (!link.guidValue || link.guidValue == "")) throw new Error("Cannot dynamically determine the content type of an inline block") const gqlQueryVars = Utils.contentLinkToRequestVariables(link) const gqlResponse = await gqlClient.request(Queries.getContentTypeQuery, gqlQueryVars as GraphQL.GetContentTypeQueryVariables) if (gqlResponse.Content?.total != 1) { if (DEBUG) console.error(`getContentType: Expected exactly one type, received ${ gqlResponse.Content?.total ?? 0 } types for`, gqlQueryVars) return undefined } const items = gqlResponse.Content?.items if (!items || items.length == 0) throw new Error("The content item could not be found!") const contentType = Utils.normalizeContentType(items[0]?.ContentType) if (!contentType) throw new Error("The item did not contain type information") return contentType }
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateCategoriesTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('categories', function (Blueprint $table) { $table->id(); $table->string('title_ar')->nullable(); $table->string('title_en')->nullable(); $table->enum('type',['main','sub'])->default('main'); $table->unsignedBigInteger('from_id')->nullable(); $table->string('image')->nullable(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('categories'); } }
import 'package:meta/meta.dart'; import '../extensions/data_class_extensions.dart'; import '../tdapi.dart'; /// A document message (general file) @immutable class MessageDocument extends MessageContent { const MessageDocument({ required this.document, required this.caption, }); /// [document] The document description final Document document; /// [caption] Document caption final FormattedText caption; static const String constructor = 'messageDocument'; static MessageDocument? fromJson(Map<String, dynamic>? json) { if (json == null) { return null; } return MessageDocument( document: Document.fromJson(json['document'] as Map<String, dynamic>?)!, caption: FormattedText.fromJson(json['caption'] as Map<String, dynamic>?)!, ); } @override String getConstructor() => constructor; @override Map<String, dynamic> toJson() => <String, dynamic>{ 'document': document.toJson(), 'caption': caption.toJson(), '@type': constructor, }; @override bool operator ==(Object other) => overriddenEquality(other); @override int get hashCode => overriddenHashCode; }
import styled from 'styled-components'; import { Navigate, Route, Routes } from 'react-router-dom'; import { ChatMain } from './features/chat/ChatMain'; import { CssBaseline } from '@mui/material'; import { ChatDetailsMain } from './features/chat/ChatDetailsMain'; import { AuthGuard } from './shared/AuthGuard'; import { SignIn } from './features/auth/SignIn'; import { useAppDispatch, useAppSelector } from './hooks'; import { User } from '@shared/models/user.model'; import { setUser } from './features/auth/auth.slice'; import { SignUp } from './features/auth/SignUp'; const StyledApp = styled.div` // Your style here `; function getSavedUser(): User | null { let user: User | null = null; try { user = JSON.parse(localStorage.getItem('user') || ''); } catch (e) { user = null; } return user; } export function App() { const dispatch = useAppDispatch(); const user = getSavedUser(); if (user) { dispatch(setUser({ user })); } return ( <StyledApp> <CssBaseline /> <Routes> <Route path="/chats" element={ <AuthGuard> <ChatMain /> </AuthGuard> } > <Route path=":chatId" element={<ChatDetailsMain />} /> <Route path="all" element={<ChatDetailsMain />} /> </Route> <Route path="/signin" element={<SignIn />} /> <Route path="/signup" element={<SignUp />} /> <Route path="/" element={<Navigate to="/chats/all" />} /> </Routes> </StyledApp> ); } export default App;
import React from "react"; import { FaRegAddressCard } from "react-icons/fa"; import { Link } from "react-router-dom"; import { SlPicture } from "react-icons/sl"; import { AiOutlineHome } from "react-icons/ai"; import { useGlobalContext } from "../context"; import axios from "axios"; import { useState, useEffect } from "react"; import { useNavigate } from "react-router-dom"; import Layout from "./Layout"; function Edit({ newFollower, setNewFollower }) { const { user, image, baseURL, setUser } = useGlobalContext(); const [emailUpdated, setEmailUpdated] = useState(); const [Error, setError] = useState(""); const [loading, setLoading] = useState(false); const [usernameUpdated, setUsernameUpdated] = useState(); const [file, setFile] = useState(); const [otherUser, setOtherUser] = useState(); const [fileUrl, setFileUrl] = useState(""); const navigate = useNavigate(); useEffect(() => { if (localStorage.getItem("token") && localStorage.getItem("id")) { setLoading(true); axios .get(`${baseURL}api/users/${localStorage.getItem("id")}`) .then((res) => { setOtherUser(res.data); setUser(res.data); setLoading(false); }); } }, []); const handleProfileUpdate = (e) => { setError(""); e.preventDefault(); if (emailUpdated || usernameUpdated || file) { setLoading(true); setError(false); const formData = new FormData(); formData.append("usernameUpdated", usernameUpdated || user.username); formData.append("emailUpdated", emailUpdated || user.email); formData.append("id", user.id); formData.append("photo", file); axios .put(`${baseURL}api/users/edit`, formData, { headers: { "Content-Type": "multipart/form-data" }, }) .then((res) => { setLoading(false); setUser({ email: res.data.email, username: res.data.username, token: user.token, picture: res.data.picture, id: user.id, }); navigate("/"); }) .catch((error) => { setLoading(false); setError(error.response.data.error); }); } else { setError("Fill in all fields!"); } }; const handleFileChange = (e) => { setFile(e.target.files[0]); const reader = new FileReader(); const file = e.target.files[0]; reader.readAsDataURL(file); reader.onload = (e) => { setFileUrl(e.target.result); }; }; return ( <> <Layout setNewFollower={setNewFollower} newFollower={newFollower} /> <section style={{ display: "flex", justifyContent: "center", alignItems: "center", height: "100%", }} > <form onSubmit={(e) => handleProfileUpdate(e)} className="profilepage-container" style={{ position: "relative", }} > <div className={Error ? "error-cont on" : "error-cont"}>{Error}</div> <Link to="/"> <AiOutlineHome className="go-back-icon" /> </Link> <Link to="/profile"> <FaRegAddressCard className="edit-icon" /> </Link> <div className="edit-image-cont"> <img src={ fileUrl || `${baseURL}images/${otherUser?.picture?.split("\\")[1]}` } className="profile-pfp" /> <div htmlFor="update-image" className="edit-image-overlay"> <label htmlFor="update-image"> <SlPicture className="update-image-icon" /> Upload </label> <input onChange={(e) => handleFileChange(e)} id="update-image" style={{ display: "none" }} name="profilePicture" type="file" accept="image/jpeg, image/png, image/jpg" /> </div> </div> <div className="edit-input-cont"> <input value={usernameUpdated} onChange={(e) => setUsernameUpdated(e.target.value)} type="text" placeholder={otherUser?.username} /> <input value={emailUpdated} onChange={(e) => setEmailUpdated(e.target.value)} type="text" placeholder={otherUser?.email} /> </div> {loading ? ( <div className="loader"></div> ) : ( <button type={"submit"} className="save-edits"> Save </button> )} </form> </section> </> ); } export default Edit;
import NextAuth, { NextAuthOptions } from 'next-auth'; import { PrismaAdapter } from '@auth/prisma-adapter'; import { type Adapter } from 'next-auth/adapters'; import CredentialsProvider from 'next-auth/providers/credentials'; import GithubProvider from 'next-auth/providers/github'; import prisma from '@/lib/prisma'; import { authActions } from '@/actions'; export const authOptions: NextAuthOptions = { adapter: PrismaAdapter(prisma) as Adapter, providers: [ GithubProvider({ clientId: process.env.GITHUB_ID || '', clientSecret: process.env.GITHUB_SECRET || '', }), CredentialsProvider({ name: 'Credentials', credentials: { email: { label: 'Email', type: 'email', placeholder: 'user@google.com' }, password: { label: 'Password', type: 'password', placeholder: '******' }, }, async authorize(credentials) { const user = await authActions.signInEmailPassword(credentials!.email, credentials!.password); return user ?? null; }, }), ], session: { strategy: 'jwt', }, callbacks: { async signIn({ user }) { // console.log({user}); return true; }, async jwt({ token, user, account, profile }) { // console.log({ token }); const dbUser = await prisma.user.findUnique({ where: { email: token.email ?? 'no-email' } }); token.id = dbUser?.id ?? 'no-uuid'; return token; }, async session({ session, token, user }) { if (session && session.user) { session.user.id = token.id; } return session; }, }, }; const handler = NextAuth(authOptions); export { handler as GET, handler as POST };
Massachusetts Institute of Technology 6.042J/18.062J, Fall ’05: Mathematics for Computer Science Prof. Albert R. Meyer and Prof. Ronitt Rubinfeld December 2 revised December 2, 2005, 1086 minutes Problem Set 10 Due: December 9 Reading: Lecture notes for weeks 13 and 14. Problem 1. MIT students sometimes delay laundry for a few days. Assume all random values described below are mutually independent. (a) A busy student must complete 3 problem sets before doing laundry. Each problem set requires 1 day with probability 2/3 and 2 days with probability 1/3. Let B be the number of days a busy student delays laundry. What is E [B ]? Example: If the first problem set requires 1 day and the second and third problem sets each require 2 days, then the student delays for B = 5 days. (b) A relaxed student rolls a fair, 6­sided die in the morning. If he rolls a 1, then he does his laundry immediately (with zero days of delay). Otherwise, he delays for one day and repeats the experiment the following morning. Let R be the number of days a relaxed student delays laundry. What is E [R]? Example: If the student rolls a 2 the first morning, a 5 the second morning, and a 1 the third morning, then he delays for R = 2 days. (c) Before doing laundry, an unlucky student must recover from illness for a number of days equal to the product of the numbers rolled on two fair, 6­sided dice. Let U be the expected number of days an unlucky student delays laundry. What is E [U ]? Example: If the rolls are 5 and 3, then the student delays for U = 15 days. (d) A student is busy with probability 1/2, relaxed with probability 1/3, and unlucky with probability 1/6. Let D be the number of days the student delays laundry. What is E [D]? Copyright © 2005, Prof. Albert R. Meyer and Prof. Ronitt Rubinfeld. Problem Set 10 2 Problem 2. There are about 250,000,000 people in the United States who might use a phone. Assume that each person is on the phone during each minute mutually indepen­ dently with probability p = 0.01. (To keep the problem simple, we are putting aside the fact that people are on the phone more often at certain times of day and on certain days of the year.) (a) What is the expected number of people on the phone at a given moment? (b) Suppose that we construct a phone network whose capacity is a mere one percent above the expectation. Upper bound the probability that the network is overloaded in a given minute. (Use the approximation formula given in the notes. You may need to evaluate this expression in a clever way because of the size of numbers involved. For example, you could first evaluate the logarithm of the given expression.) (c) What is the expected number of minutes (approximately) until the system is over­ loaded for the first time? Problem 3. We are given a set of n distinct positive integers. We then determine the maximum of these numbers by the following procedure: Randomly arrange the numbers in a sequence. Let the “current maximum” initially be the first number in the sequence and the “current element” be the second element of the sequence. If the current element is greater than the current maximum, perform an “update”: that is, change the current maximum to be the current element. Either way, change the current element to be the next element of the sequence. Repeat this process until there is no next element. Prove that the expected number of updates is ∼ ln n. Hint: Let Mi be the indicator variable for the event that the ith element of the sequence is bigger than all the previous elements in the sequence. Problem 4. In a certain card game, each card has a point value. • Numbered cards in the range 2 to 9 are worth five points each. • The card numbered 10 and the face cards (jack, queen, king) are worth ten points each. • Aces are worth fifteen points each. Problem Set 10 3 (a) Suppose that you thoroughly shuffle a 52­card deck. What is the expected total point value of the three cards on the top of the deck after the shuffle? (b) Suppose that you throw out all the red cards and shuffle the remaining 26­card, all­ black deck. Now what is the expected total point value of the top three cards? (Note that drawing three aces, for example, is now impossible!) Problem 5. A true story from World War II: The army needs to identify soldiers with a disease called “klep”. There is a way to test blood to determine whether it came from someone with klep. The straightforward ap­ proach is to test each soldier individually. This requires n tests, where n is the number of soldiers. A better approach is the following: group the soldiers into groups of k . Blend the blood samples of each group and apply the test once to each blended sample. If the group­blend doesn’t have klep, we are done with that group after one test. If the group­ blend fails the test, then someone in the group has klep, and we individually test all the soldiers in the group. Assume each soldier has klep with probability, p, independently of all the other soldiers. (a) What is the expected number of tests as a function of n, p, and k? (Assume for sim­ plicity that n is divisible by k .) (b) How should k be chosen to minimize the expected number of test performed, and what is the resulting expectation? (c) What fraction of the work does the grouping method expect to save over the straight­ forward approach in a million­strong army where 1% have klep? Problem 6. The hat­check staff has had a long day, and at the end of the party they decide to return people’s hats at random. Suppose that n people have their hats returned at random. We previously showed that the expected number of people who get their own hat back is 1, irrespective of the total number of people. In this problem we will calculate � the variance in the number of people who get their hat back. Let Xi = 1 if the ith person gets his or her own hat back and 0 otherwise. Let Sn ::= n Xi , so Sn is the total number of people who get their own hat back. Show that i=1 (a) E [Xi 2 ] = 1/n. (b) E [XiXj ] = 1/n(n − 1) for i = j . � Problem Set 10 (c) E [S 2 ] = 2. Hint: Use (a) and (b). n (d) Var [Sn ] = 1. 4 (e) Explain why you cannot use the variance of sums formula to calculate Var [Sn ]. (f) Using Chebyshev’s Inequality, show that Pr {Sn ≥ 11} ≤ .01 for any n ≥ 11. Problem 7. Let R1 and R2 be independent random variables, and f1 and f2 be any func­ tions such that domain (fi ) = codomain (Ri ) for i = 1, 2. Prove that f1 (R1 ) and f2 (R2 ) are independent random variables. Problem 8. Let A, B , C be events, and let IA , IB , IC be the corresponding indicator vari­ ables. Prove that A, B , C are mutually independent iff the random variables IA , IB , IC are mutually independent. Massachusetts Institute of Technology 6.042J/18.062J, Fall ’05: Mathematics for Computer Science Prof. Albert R. Meyer and Prof. Ronitt Rubinfeld Solutions cover sheet December 2 Student’s Solutions to Problem Set 10 Your name: Due date: December 9 Submission date: Circle your TA: David Jelani Sayan Hanson Collaboration statement: Circle one of the two choices and provide all pertinent info. 1. I worked alone and only with course materials. 2. I collaborated on this assignment with: got help from:1 and referred to:2 DO NOT WRITE BELOW THIS LINE Problem Score 1 2 3 4 5 6 7 8 Total Copyright © 2005, Prof. Albert R. Meyer and Prof. Ronitt Rubinfeld. 1People other than course staff. 2Give citations to texts and material other than the Fall ’02 course materials.
import datetime import evaluate import json from datasets import Dataset, DatasetDict from transformers import GPT2Tokenizer, GPT2LMHeadModel, TrainingArguments, Trainer """ This script uses the Hugging Face Trainer API to train the DialoGPT model on the combined CareerBud dataset. """ # Load the JSON dataset with open('../Fine-tuning Datasets/careerbud_dataset.json', 'r') as file: data = json.load(file) # Convert each item to the specified string format and collect them formatted_questions = [{'questions': f"{item['input']} {item['response']}"} for item in data] # Convert the list of strings into a Hugging Face Dataset dataset = Dataset.from_dict({'questions': [item['questions'] for item in formatted_questions]}) # Split data into 90% training and 10% testing train_test_split = dataset.train_test_split(test_size=0.1) dataset = DatasetDict({ 'train': train_test_split['train'], 'test': train_test_split['test'] }) # Load the tokenizer and model model_name = 'microsoft/DialoGPT-medium' tokenizer = GPT2Tokenizer.from_pretrained(model_name) tokenizer.pad_token = tokenizer.eos_token model = GPT2LMHeadModel.from_pretrained(model_name) # Encode the dataset def encode(examples): encoded = tokenizer(examples['questions'], truncation=True, padding='max_length', max_length=128) encoded['labels'] = encoded['input_ids'][:] return encoded encoded_dataset = dataset.map(encode, batched=True) # Define the Training Arguments training_args = TrainingArguments( num_train_epochs=5, per_device_train_batch_size=16, per_device_eval_batch_size=16, learning_rate=0.00005, output_dir="../DialoGPT-CareerBud-Checkpoints", evaluation_strategy="epoch", # Evaluate after each epoch load_best_model_at_end=True, # Load the best model at the end of training save_strategy="epoch", # Save model checkpoint after each epoch metric_for_best_model="eval_bleu", # Use BLEU to identify the best model greater_is_better=True, logging_strategy="epoch" ) # Define evaluate function for tracking BLEU score def compute_metrics(eval_pred): predictions, labels = eval_pred # Decode the predictions decoded_predictions = [tokenizer.decode(g, skip_special_tokens=True, clean_up_tokenization_spaces=True) for g in predictions.argmax(-1)] # Decode the labels (references) decoded_labels = [[tokenizer.decode(g, skip_special_tokens=True, clean_up_tokenization_spaces=True)] for g in labels] # Initialise the BLEU metric bleu_metric = evaluate.load('bleu') # Compute BLEU score results = bleu_metric.compute(predictions=decoded_predictions, references=decoded_labels) return {"bleu": results["bleu"]} # Initialise the Trainer trainer = Trainer( model=model, args=training_args, train_dataset=encoded_dataset["train"], eval_dataset=encoded_dataset["test"], compute_metrics=compute_metrics, ) print(f'Trainer initialised and now starting. Timestamp: {datetime.datetime.now()}') # Train the model trainer.train() print(f'Training done! Timestamp: {datetime.datetime.now()}') # Save the model trainer.save_model("DialoGPT-CareerBud")
# example 2.1 of section 2.2.1 # (example 2.1 of section 2.2.1) : Starting with R and data : Working with data from files : Working with well-structured data from files or URLs # Title: Reading the UCI car data uciCar <- read.table( # Note: 1 'car.data.csv', # Note: 2 sep = ',', # Note: 3 header = TRUE, # Note: 4 stringsAsFactor = TRUE # Note: 5 ) View(uciCar) # Note: 6 # Note 1: # Command to read from a file or URL and store the result in a new data frame object # called # uciCar. # Note 2: # Filename or URL to get the data from. # Note 3: # Specify the column or field separator as a # comma. # Note 4: # Tell R to expect a header line that defines # the data column names. # Note 5: # Tell R to convert string values to factors. This is the default behavior, so we are just using this argument to document intent. # Note 6: # Examine the data with R’s built-in # table viewer.
create table products ( id serial primary key, name varchar(50), producer varchar(50), count integer default 0, price integer ); create table history_of_price ( id serial primary key, name varchar(50), price integer, date timestamp ); create or replace function nalog_after() returns trigger as $$ BEGIN update products set price = price + 1 where id = (select id from inserted); return new; END; $$ LANGUAGE 'plpgsql'; create or replace function nalog_before() returns trigger as $$ BEGIN new.price = new.price + 1; return new; END; $$ LANGUAGE 'plpgsql'; create trigger nalog_after_trigger after insert on products referencing new table as inserted for each statement execute procedure nalog_after(); create trigger nalog_before_trigger before insert on products for each row execute procedure nalog_before(); create or replace function history() returns trigger as $$ BEGIN insert into history_of_price(name,price,date) values(new.name,new.price,current_date); return new; END; $$ LANGUAGE 'plpgsql'; create trigger history_of_price_trigger after insert on products for each row execute procedure history();
% splits section with PJVS signal into particular segments. Removes data before % MRs and after MRe. Calculates mean and std for segments, removes PRs and PRe function [s_y, s_mean, s_std, s_uA] = pjvs_split_segments(y, Spjvs, MRs, MRe, PRs, PRe, dbg) % Remove points masked by MRs and MRe y = y(MRs + 1 : end - MRe); % Change Spjvs indexes to match removed points: Spjvs = Spjvs - MRs; Spjvs(Spjvs > numel(y) + 1) = []; % ensure start and ends of record as PJVS segments Spjvs(Spjvs < 1) = []; Spjvs(Spjvs > numel(y) + 1) = []; if Spjvs(1) ~= 1 Spjvs = [1 Spjvs]; end if Spjvs(end) ~= numel(y) + 1 % because Spjvs marks start of step, next % step is after the last data sample Spjvs(end+1) = numel(y) + 1; end % Loop to cut into segments. Segments can be of different length. Also % calculates means and std for case of removed PRs and PRe to save % processing time. % initliaze variables: maxsegmentlen = max(diff(Spjvs)); s_y = nan.*zeros(maxsegmentlen, numel(Spjvs) - 1); % Because basic Matlab does not contain nanmean and nanstd, two methods % available. Second method is 10x slower. if exist('nanmean') % faster version for j = 1:numel(Spjvs) - 1 % get one segment actlen = Spjvs(j+1) - Spjvs(j); tmp = y(Spjvs(j) : Spjvs(j+1) - 1); if numel(tmp) > PRs + PRe tmp = tmp(1 + PRs : end-PRe); s_y(1:numel(tmp), j) = tmp; else if j == 1 % it is first segment, lets neglect it disp(sprintf('Not enough samples in segment after start and end removal, section %d-%d, segment %d, PRs: %d, PRe: %d. It is first segment, neglecting.', dbg.section(1), dbg.section(2), j, PRs, PRe)); elseif j == numel(Spjvs) - 1 % it is last segment, lets neglect it disp(sprintf('Not enough samples in segment after start and end removal, section %d-%d, segment %d, PRs: %d, PRe: %d. It is last segment, neglecting.', dbg.section(1), dbg.section(2), j, PRs, PRe)); else error(sprintf('Not enough samples in segment after start and end removal, section %d-%d, segment %d. This usually happens if the MX switching freuency is not right, and the disturbance caused by MX switch interfere with PJVS phase detection algorithm (pjvs_ident_segments).', dbg.section(1), dbg.section(2), j)); end end end % remove neglected: if all(isnan(s_y(:,1))) % first segment was neglected, remove it from matrices: s_y(:,1) = []; end if all(isnan(s_y(:,end))) % last segment was neglected, remove it from matrices: s_y(:,end) = []; end s_mean = nanmean(s_y, 1); s_std = nanstd(s_y, 0, 1); s_uA = s_std./sqrt(sum(~isnan(s_y),1)); else % slow version for basic Matlab without nanmean s_mean = nan.*zeros(1, numel(Spjvs) - 1); s_std = nan.*zeros(1, numel(Spjvs) - 1); for j = 1:length(Spjvs) - 1 % get one segment actlen = Spjvs(j+1) - Spjvs(j); tmp = y(Spjvs(j) : Spjvs(j+1) - 1); if numel(tmp) > PRs + PRe tmp = tmp(1 + PRs : end-PRe); s_y(1:numel(tmp), j) = tmp; else if j == 1 % it is first segment, lets neglect it disp(sprintf('Not enough samples in segment after start and end removal, section %d-%d, segment %d, PRs: %d, PRe: %d. It is first segment, neglecting.', dbg.section(1), dbg.section(2), j, PRs, PRe)); elseif j == numel(Spjvs) - 1 % it is last segment, lets neglect it disp(sprintf('Not enough samples in segment after start and end removal, section %d-%d, segment %d, PRs: %d, PRe: %d. It is last segment, neglecting.', dbg.section(1), dbg.section(2), j, PRs, PRe)); else error(sprintf('Not enough samples in segment after start and end removal, section %d-%d, segment %d. This usually happens if the MX switching freuency is not right, and the disturbance caused by MX switch interfere with PJVS phase detection algorithm (pjvs_ident_segments).', dbg.section(1), dbg.section(2), j)); end end % remove neglected: if all(isnan(s_y(:,1))) % first segment was neglected, remove it from matrices: s_y(1,:) = []; end if all(isnan(s_y(:,end))) % last segment was neglected, remove it from matrices: s_y(:,end) = []; end s_mean(j) = mean(tmp); s_std(j) = std(tmp); s_uA(j) = s_std(j)./sqrt(numel(tmp)); end % for j = 1:length(Spjvs) - 1 end % if exist('nanmean') end % function
// This program shows that an array is not a pointers // But it decays to a pointer to the first element of the // array by the compiler #include <stdio.h> int main (void) { int array[4] = {0}; // Loop through the array and print out the address of // each of the elements of the array int i = 0; while (i < 4) { printf("The memory address of array[%d] is %p\n", i, &array[i]); i++; } // Now print out the ADDRESS of the array by referencing // with the name of the array only. What do you notice? printf("The memory address of the array is %p\n", array); return 0; }
import React, { useState, useEffect, useContext, useReducer, useCallback } from 'react'; import ThemeContext from './ThemeContext'; const counterReducer = (state, action) => { switch (action.type) { case 'INCREMENT': return { count: state.count + 1 }; case 'DECREMENT': return { count: state.count - 1 }; default: return state; } }; export default function Counter() { const [count, setCount] = useState(0); const [data, setData] = useState(null); const [state, dispatch] = useReducer(counterReducer, { count: 0 }); const theme = useContext(ThemeContext); // Define a callback function for handling API data const handleApiData = useCallback((result) => { const apiData = result.entries || result.data || []; setData(apiData); }, []); useEffect(() => { // Fetch data from an API fetch('https://api.publicapis.org/entries') .then(response => response.json()) .then(handleApiData) // Use the callback function .catch(error => console.error('Error fetching data:', error)); }, [handleApiData]); // Include the callback function in the dependency array console.log('Theme:', theme); return ( <> <div> <p>Count: {state.count}</p> <button onClick={() => dispatch({ type: 'INCREMENT' })}>Increment</button> <button onClick={() => dispatch({ type: 'DECREMENT' })}>Decrement</button> </div> <div> {data && ( <div> <h2>API Data</h2> <ul> {data.map(api => ( <li key={api.API}> <strong>Name:</strong> {api.API}, <strong>Category:</strong> {api.Category}<br /> </li> ))} </ul> </div> )} </div> <p style={{ color: theme }}>Themed text</p> </> ); }
import axios from "axios"; import React, { useState } from "react"; import { Button, Col, Form, Row } from "react-bootstrap"; import validation from "./actions/validation"; const DeliveryForm = ({ products }) => { const [nameValidation, setNameValidation] = useState({ valid: false, text: null, }); const [lastNameValidation, setLastNameValidation] = useState({ valid: false, text: null, }); const [emailValidation, setEmailValidation] = useState({ valid: false, text: null, }); const [name, setName] = useState(""); const [lastName, setLastName] = useState(""); const [email, setEmail] = useState(""); const productsId = []; products.forEach((item) => productsId.push(item.idpizza)); const productsNames = []; products.forEach((item) => productsNames.push(item.nombre)); const productsCantidad = []; products.forEach((item) => { if (item.cantidad) productsCantidad.push(item.cantidad); else productsCantidad.push(1); }); let total = 0; products.forEach((item) => (total += Number(item.precioTotal))); const validate = (e) => { switch (e.target.name) { case "name": setNameValidation(validation(e.target.name, e.target.value)); setName(e.target.value); break; case "lastName": setLastNameValidation(validation(e.target.name, e.target.value)); setLastName(e.target.value); break; case "email": setEmailValidation(validation(e.target.name, e.target.value)); setEmail(e.target.value); break; default: return null; } }; const onSubmit = (e) => { e.preventDefault(); axios.post("api/pedido/create", { name: name, lastName: lastName, email: email, canal: "retiro en local", productos: { ids: productsId, nombres: productsNames, cantidades: productsCantidad, }, total: total, }); }; return ( <Form className="mt-5 w-75 bg-dark text-center" onSubmit={onSubmit}> <Row className="fila"> <Col className="col-md-4"> <Form.Label className="text-primary" htmlFor="name"> Nombre </Form.Label>{" "} {nameValidation.text} </Col> <Col> <Form.Control type="text" name="name" onChange={validate} /> </Col> </Row> <Row className="fila"> <Col className="col-md-4"> <Form.Label className="text-primary" htmlFor="lastName"> Apellido </Form.Label>{" "} {lastNameValidation.text} </Col> <Col> <Form.Control type="text" name="lastName" onChange={validate} /> </Col> </Row> <Row className="fila"> <Col className="col-md-4"> <Form.Label className="text-primary" htmlFor="phone"> Numero de contacto </Form.Label> </Col> <Col> <Form.Control type="text" name="phone" onChange={validate} /> </Col> </Row> <Row className="fila"> <Col className="col-md-4"> <Form.Label className="text-primary" htmlFor="email"> Email </Form.Label>{" "} {emailValidation.text} </Col> <Col> <Form.Control type="email" name="email" onChange={validate} /> </Col> </Row> <Row className="fila"> <Button variant="outline-primary row-2" type="submit" onSubmit={onSubmit} > Solicitar pedido </Button> </Row> </Form> ); }; export default DeliveryForm;
import React from 'react'; import { View } from 'react-native'; import { categories } from '../../utils/categories'; import { Container, Title, Amount, Footer, Category, CategoryName, Date, Icon } from './styles'; interface Category { name: string; icon: string; } export interface TransactionCardProps { type: 'positive' | 'negative'; name: string; amount: string; category: string; date: string; } interface Props { data: TransactionCardProps } export const TransactionCard: React.FC<Props> = ({ data }) => { const [ category ] = categories.filter( item => item.key === data.category ); return ( <Container> <Title> {data.name} </Title> <Amount type={data.type}> { data.type === 'negative' && '- ' } { data.amount } </Amount> <Footer> <Category> <Icon name={category.icon} /> <CategoryName> {category.name} </CategoryName> </Category> <Date> {data.date} </Date> </Footer> </Container> ); }
import React, { useCallback, useContext, createContext, useReducer, useMemo, } from 'react'; import auth, { FirebaseAuthTypes } from '@react-native-firebase/auth'; import firestore from '@react-native-firebase/firestore'; import { GoogleSignin, statusCodes, User as GoogleUserInfo, } from '@react-native-google-signin/google-signin'; import * as AppleAuthentication from 'expo-apple-authentication'; import * as Crypto from 'expo-crypto'; import * as SecureStore from 'expo-secure-store'; import { Alert } from 'react-native'; import AnalyticsEvents from '../constants/AnalyticsEvents'; import Analytics from './analytics.service'; import { ACTION, initialState, appReducer, AppState } from './mainAppReducer'; import refreshUserData from './refreshUserData'; import Notification from './notification.service'; import { useUserDataStore } from '../utilities/userDataStore'; export type AuthContextValue = { state: AppState; dispatch: React.Dispatch<ACTION>; signIn: () => Promise<void>; signInWithApple: () => Promise<void>; signOut: () => Promise<void>; finishOnboarding: () => void; }; const initialAuth: AuthContextValue = { state: initialState, dispatch: () => {}, signIn: () => new Promise<void>(() => {}), signInWithApple: () => new Promise<void>(() => {}), signOut: () => new Promise<void>(() => {}), finishOnboarding: () => {}, }; export default class Auth { static Context = createContext<AuthContextValue>(initialAuth); static useAuthService(): AuthContextValue { const [state, dispatch] = useReducer(appReducer, initialState); const processFbLogin = useCallback( async ( result: FirebaseAuthTypes.UserCredential, displayName?: string, ): Promise<void> => { // Store credentials in SecureStore if ('user' in result) { const profileData = result?.additionalUserInfo?.profile ? { ...result.additionalUserInfo.profile, name: result.additionalUserInfo.profile.name || displayName, } : {}; await Promise.all([ SecureStore.setItemAsync('providerId', result.user.providerId), SecureStore.setItemAsync('userId', result.user.uid), SecureStore.setItemAsync( 'profileData', JSON.stringify(profileData), ), ]); // Check if that user's document exists, in order to direct them to or past onboarding const onboardingComplete = await firestore() .collection('users') .doc(result.user.uid) .get() .then((docSnapshot) => { // Check if the user document exists and if onboarding is marked complete. // If user doc doesn't exist, create it if (!docSnapshot.exists) { firestore() .collection('users') .doc(result.user.uid) .set({ userInfo: { displayName: result.user.displayName || displayName, email: result.user.email, uid: result.user.uid, photoURL: result.user.photoURL ?? '', signUpDate: firestore.FieldValue.serverTimestamp(), }, onboardingComplete: false, lastChat: { message: '', sender: '', sentByUser: true, time: firestore.Timestamp.now(), }, }) .catch((error) => { console.error('Error creating user document: ', error); }); return false; // Report onboarding as incomplete } else { const onboardingMarkedComplete = docSnapshot?.data()?.onboardingComplete; // might be undefined return onboardingMarkedComplete ?? false; } }); // Update app state accordingly thru context hook function dispatch({ type: 'SIGN_IN', token: result.user.uid, onboardingComplete: onboardingComplete, profileData, userData: { displayName: result.user.displayName || displayName, email: result.user.email, uid: result.user.uid, }, }); Analytics.logEvent(AnalyticsEvents.logIn); } else { Alert.alert( 'Signin failed', 'Unexpected error occurred! Please try again later.', ); console.log('Error signing in (maybe cancelled)'); } // Update user's data from Firestore db refreshUserData(dispatch); }, [dispatch], ); const signIn = useCallback(async (): Promise<void> => { let googleUserInfo: GoogleUserInfo | undefined; GoogleSignin.configure({ scopes: [ 'https://www.googleapis.com/auth/userinfo.profile', 'https://www.googleapis.com/auth/userinfo.email', ], webClientId: '713165282203-jjc54if1n7krahda9gvkio0siqltq57t.apps.googleusercontent.com', offlineAccess: false, forceCodeForRefreshToken: false, }); dispatch({ type: 'SET_SIGNINGIN', isSigningIn: true }); try { await GoogleSignin.hasPlayServices({ showPlayServicesUpdateDialog: true, }); googleUserInfo = await GoogleSignin.signIn(); } catch (error: any) { dispatch({ type: 'SET_SIGNINGIN', isSigningIn: false }); error.message = error.code === statusCodes.SIGN_IN_CANCELLED || error.code === '8' // 8: INTERNAL_ERROR - An internal error occurred. Retrying should resolve the problem. ? '' : error.code === statusCodes.IN_PROGRESS ? 'Sign in is in progress already.' : error.code === statusCodes.PLAY_SERVICES_NOT_AVAILABLE ? 'Google play services are not available or outdated.' : 'Unknown error happened! Please try again later.'; if (error.message) { Alert.alert('Google Signin Error', error.message); } return; } dispatch({ type: 'SET_LOADING', isLoading: true }); // Pipe the result of Google login into Firebase auth try { const { idToken } = googleUserInfo; const credential = auth.GoogleAuthProvider.credential(idToken); const fbSigninResult = await auth().signInWithCredential(credential); await processFbLogin(fbSigninResult); } catch (error) { if (__DEV__) { console.log('error in signIn: ', error); } } finally { dispatch({ type: 'SET_LOADING', isLoading: false }); dispatch({ type: 'SET_SIGNINGIN', isSigningIn: false }); } }, [dispatch, processFbLogin]); const signOut = useCallback(async () => { const userId = auth().currentUser?.uid; if (userId) { try { await Notification.updateExpoPushToken( 'No push token provided', userId, ); } catch {} } SecureStore.deleteItemAsync('userId'); dispatch({ type: 'SIGN_OUT' }); await auth().signOut(); await GoogleSignin.revokeAccess(); await GoogleSignin.signOut(); Analytics.logEvent(AnalyticsEvents.logOut); Analytics.setUserId(null); }, [dispatch]); const signInWithApple = useCallback(async (): Promise<void> => { let credential: AppleAuthentication.AppleAuthenticationCredential; let rawNonce: string | undefined; dispatch({ type: 'SET_SIGNINGIN', isSigningIn: true }); try { rawNonce = Math.random().toString(36).substring(2, 10); const hashedNonce = await Crypto.digestStringAsync( Crypto.CryptoDigestAlgorithm.SHA256, rawNonce, ); credential = await AppleAuthentication.signInAsync({ requestedScopes: [ AppleAuthentication.AppleAuthenticationScope.FULL_NAME, AppleAuthentication.AppleAuthenticationScope.EMAIL, ], nonce: hashedNonce, }); if (credential.fullName?.givenName) { SecureStore.setItemAsync( 'appleId.givenName', credential.fullName.givenName, ); } else { const givenName = await SecureStore.getItemAsync('appleId.givenName'); credential = { ...credential, fullName: { ...credential.fullName, givenName, } as AppleAuthentication.AppleAuthenticationFullName, }; } if (credential.fullName?.familyName) { SecureStore.setItemAsync( 'appleId.familyName', credential.fullName.familyName, ); } else { const familyName = await SecureStore.getItemAsync( 'appleId.familyName', ); credential = { ...credential, fullName: { ...credential.fullName, familyName, } as AppleAuthentication.AppleAuthenticationFullName, }; } } catch (error: any) { dispatch({ type: 'SET_SIGNINGIN', isSigningIn: false }); if (error.code !== 'ERR_CANCELED') { Alert.alert('Signin failed', error.message); } return; } dispatch({ type: 'SET_LOADING', isLoading: true }); // Pipe the result of Sign in with Apple into Firebase auth try { const { identityToken, fullName } = credential; const appleAuthCredential = auth.AppleAuthProvider.credential( identityToken!, rawNonce, ); const fbSigninResult = await auth().signInWithCredential( appleAuthCredential, ); await processFbLogin( fbSigninResult, `${fullName?.givenName} ${fullName?.familyName}`, ); } catch (error) { if (__DEV__) { console.log('error in signInWithApple: ', error); } } finally { dispatch({ type: 'SET_LOADING', isLoading: false }); dispatch({ type: 'SET_SIGNINGIN', isSigningIn: false }); } }, [dispatch, processFbLogin]); const finishOnboarding = useCallback(async () => { useUserDataStore((userDataState) => userDataState.setOnboardingComplete(), ); }, [dispatch]); const value = useMemo( () => ({ state, dispatch, signIn, signOut, signInWithApple, finishOnboarding, }), [state, dispatch, signIn, signOut, signInWithApple, finishOnboarding], ); return value; } static useAuth(): AuthContextValue { return useContext(Auth.Context); } }
#ifndef ACTOR_H_ #define ACTOR_H_ #include "GraphObject.h" #include "StudentWorld.h" // Abstract Actor class class Actor: public GraphObject { public: // Constructor Actor(StudentWorld* game, int imageID, int startX, int startY, Direction dir, int depth = 0) : GraphObject(imageID, startX, startY, dir, depth) {} // Destructor virtual ~Actor() {} // Public Interface virtual void doSomething() = 0; virtual bool isAnimate() = 0; virtual bool canDie() = 0; virtual bool isColonized() {return false;} }; #ifndef INANIMATEACTOR_H_ #define INANIMATEACTOR_H_ class InanimateActor: public Actor{ public: // Constructor InanimateActor(StudentWorld* game, int imageID, int startX, int startY, int depth = 2) : Actor(game, imageID, startX, startY, right, depth) {} // Destructor virtual ~InanimateActor() {} // Public Interface virtual void doSomething() = 0; // Getting inanimate actor status virtual bool canDie() {return canDecay();} virtual bool isAnimate() {return false;} // main distinguishing characteristic virtual bool canDecay() {return false;} // by default they do not decay virtual bool isBlocker() {return false;}; // by default is not a blocker private: }; #endif // INANIMATEACTOR_H_ #ifndef PEBBLE_H_ #define PEBBLE_H_ class Pebble: public InanimateActor{ public: // Constructor Pebble(StudentWorld* game, int startX, int startY) : InanimateActor(game, IID_ROCK, startX, startY, 1) {} // Destructor virtual ~Pebble() {} // Public Interface virtual bool isBlocker() {return true;} // only blocker inanimate actpr private: virtual void doSomething() {return;} // Pebble should do nothing during tick }; #endif // PEBBLE_H_ #ifndef WATER_H_ #define WATER_H_ class Water: public InanimateActor{ public: // Constructor Water(StudentWorld* game, int startX, int startY) : InanimateActor(game, IID_WATER_POOL, startX, startY) {m_game = game;} // Destructor virtual ~Water() {} private: StudentWorld* m_game; virtual void doSomething() {m_game->hurtInsects(getX(), getY(), 's');} // stun insects at x, y }; #endif // WATER_H_ #ifndef POISON_H_ #define POSION class Poison: public InanimateActor{ public: // Constructor Poison(StudentWorld* game, int startX, int startY) : InanimateActor(game, IID_POISON, startX, startY) {m_game = game;} // Destructor virtual ~Poison() {} private: StudentWorld* m_game; virtual void doSomething() {m_game->hurtInsects(getX(), getY(),'p');} // poison insects at x, y }; #endif // PEBBLE_H_ #ifndef DECAYABLEACTOR_H_ #define DECAYABLEACTOR_H_ class DecayableActor: public InanimateActor{ public: // Constructor DecayableActor(StudentWorld* game, int imageID, int startX, int startY, int energy) : InanimateActor(game, imageID, startX, startY) {m_game = game; m_energy = energy;} // Destructor virtual ~DecayableActor() {} // Public Interface virtual void doSomething() {setEnergy(getEnergy() - 1);}; // getters and setters - status virtual bool canDecay() {return true;} // main characteristic of this subclass virtual bool isEdible() {return false;} // by default decayable actors are not edible virtual int getEnergy() {return m_energy;} // change from points to energy to differentiate it from alive actors virtual void setEnergy(int modifiedEnergy) {m_energy = modifiedEnergy;} virtual bool isGone() {return getEnergy() == 0;} private: int m_energy; StudentWorld* m_game; }; #endif // DECAYABLEACTOR_H_ #ifndef FOOD_H_ #define FOOD_H_ class Food: public DecayableActor{ public: // Constructor Food(StudentWorld* game, int startX, int startY, int foodPts = 6000) : DecayableActor(game, IID_FOOD, startX, startY, foodPts) {} // Destructor virtual ~Food() {} // do nothing // Public Interface virtual bool isEdible() {return true;} private: virtual void doSomething() {return;} // do nothing }; #endif // FOOD_H_ #ifndef PHEROMONE_H_ #define PHEROMONE_H_ class Pheromone: public DecayableActor{ public: // Constructor Pheromone(StudentWorld* game, int imageID, int startX, int startY, int colony) : DecayableActor(game, imageID, startX, startY, 256) {m_game = game; m_colony = colony; moveTo(startX, startY);} // Destructor virtual ~Pheromone() {} // Public Interface int getColony() {return m_colony;} private: StudentWorld* m_game; int m_colony; }; #endif // PHEROMONE_H_ #ifndef ANTHILL_H_ #define ANTHILL_H_ class Anthill: public DecayableActor { public: // Constructor Anthill(StudentWorld* game, int startX, int startY, int colony, Compiler* c) : DecayableActor(game, IID_ANT_HILL, startX, startY, 8999) { m_game = game; m_colony = colony; m_c = c;} // Destructor virtual ~Anthill() {} // Public Interface void virtual doFunction(); int getColony() {return m_colony;} private: StudentWorld* m_game; Compiler* m_c; int m_colony; virtual void doSomething(); }; #endif // ANT_H_ #ifndef ANIMATEACTOR_H_ #define ANIMATEACTOR_H_ class AnimateActor : public Actor{ public: // Constructor AnimateActor(StudentWorld* game, int imageID, int startX, int startY, Direction dir, int healthPts, int depth = 0) :Actor(game, imageID, startX, startY, dir, depth) {m_game = game; m_points = healthPts; stunned = false; poisoned = false;} // Destructor virtual ~AnimateActor() {} // Public Interface virtual void doSomething(); // Direction GraphObject::Direction randDir(); // dealing with points int getPoints() {return m_points;} // return number of points void setPoints(int modifiedPoints) { m_points = modifiedPoints;} // set points to new value // status virtual bool canDie() {return true;} virtual bool isAnimate() {return true;} virtual bool isDead() {return m_points <= 0;} virtual bool isSleeping() = 0; // blocking bool isBlocked(int x, int y) {return m_game->isBlocked(x, y);} // stunning virtual void stun() {stunned = true;} virtual bool checkStunStatus() {return stunned;} void unstun() {stunned = false;} // eating bool eat(int maxFood); // poisoning virtual void poison(); // moving virtual bool moveStep(Direction dir, int oldX, int oldY); virtual int getDistanceToMove() {return distanceToMove;} virtual void setDistanceToMove(int modifiedDistance) {distanceToMove = modifiedDistance;} private: int distanceToMove = randInt(2, 10); bool poisoned = false; bool stunned; StudentWorld* m_game; int m_points; }; #endif // ANIMATEACTOR_H_ #ifndef GRASSHOPPER_H_ #define GRASSHOPPER_H_ class Grasshopper: public AnimateActor { public: // Constructor Grasshopper(StudentWorld* game, int ImageID, int startX, int startY, int points) :AnimateActor(game, ImageID, startX, startY, right, points) {m_game = game; setDistanceToMove(randInt(2, 10)); setDirection(randDir());} // Destructor virtual ~Grasshopper() {} // Public Interface virtual void doSomething(); // stunning virtual bool isSleeping(); virtual bool doFunction() = 0; private: int ticksToSleep = 0; bool recoveringFromStun = false; StudentWorld* m_game; }; #endif // GRASSHOPPER_H_ #ifndef BABYGRASSHOPPER_H_ #define BABYGRASSHOPPER_H_ class BabyGrasshopper: public Grasshopper { public: // Constructor BabyGrasshopper(StudentWorld* game, int startX, int startY) : Grasshopper(game, IID_BABY_GRASSHOPPER, startX, startY, 500) { m_game = game;} // Destructor virtual ~BabyGrasshopper() {} virtual bool doFunction(); private: StudentWorld* m_game; }; #endif // BABYGRASSHOPPER_H_ #ifndef ADULTGRASSHOPPER_H_ #define ADULTGRASSHOPPER_H_ class AdultGrasshopper: public Grasshopper { public: // Constructor AdultGrasshopper(StudentWorld* game, int startX, int startY) : Grasshopper(game, IID_ADULT_GRASSHOPPER, startX, startY, 1600) { m_game = game;} // Destructor virtual ~AdultGrasshopper() {} // Public Interface virtual void poison() {return;} // never gets poisoned virtual bool checkStunStatus() {return false;} // never gets stunned virtual bool doFunction(); // deciding to jump or bite private: StudentWorld* m_game; // jumping bool jump(); void jumpTo(int x, int y); bool isInBounds(int x, int y); // to check if in bounds // storing coordinates struct Coord{ int x; int y; }; vector<Coord> jumpOptions; }; #endif // ADULTGRASSHOPPER_H_ #ifndef ANT_H_ #define ANT_H_ class Ant: public AnimateActor { public: // Constructor Ant(StudentWorld* game, int ImageID, int startX, int startY, int colony, Compiler* compiler) : AnimateActor(game, ImageID, startX, startY, right, 1500, 1) { m_game = game; unstun(); m_colony = colony; m_compiler = compiler; setDirection(randDir());} // Destructor virtual ~Ant() {} // Public Interface virtual bool isSleeping(); virtual int getColony() {return m_colony;} virtual bool isColonized() {return true;} void storeFood(int amount); // change bitten status void gotBitten() {bitten = true;} private: virtual void doSomething(); virtual void doFunction(); Compiler* m_compiler; StudentWorld* m_game; // direction change void rotateClockwise(); void rotateCounterClockwise(); bool bitten = false; int ic = 0; // instruction counter int m_colony; int storedFood = 0; int ticksToSleep = 0; }; #endif // ANT_H_ #endif // ACTOR_H_
// // ElementsSizeFilter.swift // Mindbox // // Created by vailence on 07.09.2023. // Copyright © 2023 Mindbox. All rights reserved. // import Foundation import MindboxLogger protocol ElementsSizeFilterProtocol { func filter(_ size: ContentElementSizeDTO?) throws -> ContentElementSize } final class ElementSizeFilterService: ElementsSizeFilterProtocol { enum Constants { static let defaultSize = ContentElementSize(kind: .dp, width: 24, height: 24) } func filter(_ size: ContentElementSizeDTO?) throws -> ContentElementSize { guard let size = size else { Logger.common(message: "Size is invalid or missing. Default value set: [\(Constants.defaultSize)].", level: .debug, category: .inAppMessages) return Constants.defaultSize } switch size.kind { case .dp: if let height = size.height, let width = size.width, height >= 0, width >= 0 { return ContentElementSize(kind: size.kind, width: width, height: height) } case .unknown: Logger.common(message: "Unknown type of ContentElementSize. Default value set: [\(Constants.defaultSize)].", level: .debug, category: .inAppMessages) return Constants.defaultSize } throw CustomDecodingError.unknownType("ElementSizeFilterService validation not passed. In-app will be ignored.") } }
const uuid = require('uuid') const fs = require('fs') const path = require('path') class Course { constructor(title, price, image) { this.title = title this.price = price this.image = image this.id = uuid.v4() } toJSON() { return { title: this.title, price: this.price, image: this.image, id: this.id } } async save() { const courses = await Course.getAll() courses.push(this.toJSON()) return new Promise((resolve, reject) => { fs.writeFile( path.join(__dirname, '..', 'data', 'courses.json'), JSON.stringify(courses), (err) => { if (err) reject(err) else resolve() } ) }) } static getAll() { return new Promise((resolve, reject) => { fs.readFile( path.join(__dirname, '..', 'data', 'courses.json'), 'utf-8', (err, content) => { if (err) reject(err) else resolve(JSON.parse(content)) } ) }) } static async getByID(id) { const coursesData = await Course.getAll() return coursesData.find(course => course.id === id) } static async update(course) { const courses = await Course.getAll() const index = courses.findIndex(c => c.id === course.id) courses[index] = course return new Promise((resolve, reject) => { fs.writeFile( path.join(__dirname, '..', 'data', 'courses.json'), JSON.stringify(courses), (err) => { if (err) reject(err) else resolve() } ) }) } static async deleteCourse(course) { const courses = await Course.getAll() const index = courses.findIndex(c => c.id === course.id) courses.splice(index, 1) return new Promise((resolve, reject) => { fs.writeFile( path.join(__dirname, '..', 'data', 'courses.json'), JSON.stringify(courses), (err) => { if (err) reject(err) else resolve() } ) }) } } module.exports = Course
package com.example.demo.utils.aspect.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Base annotation for logging with AOP * This annotation should be used only when ALL the information wants to be logged * * If you want to log only some create another annotation with level field, * as a best practice the child annotation should be annotated with the corresponding * @Logged configuration kinda like a child class (inheritance is not possible with annotations) */ @Target({ ElementType.METHOD, ElementType.TYPE, ElementType.CONSTRUCTOR }) @Retention(RetentionPolicy.RUNTIME) public @interface Logged { int level() default 400; // info boolean executionTime() default true; boolean inputArgs() default true; boolean outputArgs() default true; boolean exception() default true; boolean begin() default true; boolean end() default true; }
## ChromeDriverBase Class ChromeDriverBase is a base class that provides a convenient way to create a Chrome web driver instance using the Selenium library. This class can be used as a parent class for implementing custom web driver classes that perform specific tasks on web pages. The class uses the Chrome browser to open URLs and can perform actions on web elements by executing JavaScript code. ### Example usage ``` from base_class.chrome_driver_base import ChromeDriverBase class MyDriver(ChromeDriverBase): pass ``` ``` skill_share_login_url = "https://www.skillshare.com/en/login" driver = ExampleDriver() driver.openUrl(skill_share_login_url) ``` In the above example, a custom web driver class named MyDriver is defined that inherits from ChromeDriverBase. Then, an instance of this class is created, and the openUrl() method is used to open a web page in the Chrome browser. ## HandleEventHelper Class HandleEventHelper is a helper class that provides methods for interacting with web elements on a page using the Selenium library. This class can be used to perform various actions on web elements, such as clicking on buttons, entering text in input fields, etc. The class also provides methods for waiting for web elements to become present on the page before performing any actions. ### Example usage ``` from selenium.webdriver.common.by import By skill_share_login_url = "https://www.skillshare.com/en/login" driver = ExampleDriver() driver.openUrl(skill_share_login_url) ``` ``` def sample_with_attribute(): driver.handle_event_helper.execute_element_by_attribute("name", "email", "sample@gmail.com") driver.handle_event_helper.execute_element_by_attribute("type", "button") ``` ``` def sample_with_class_name(): driver.handle_event_helper.execute_element_by_tag(By.CLASS_NAME, "login-inputs-fields", "sample@gmail.com") driver.handle_event_helper.execute_element_by_tag(By.CLASS_NAME, "submit-btn") ``` ``` def sample_with_x_path(): driver.handle_event_helper.execute_element_by_tag(By.XPATH, '//*[@id="page-wrapper"]/div[2]/div/div/form/div[2]/input', "sample@gmail.com") driver.handle_event_helper.execute_element_by_tag(By.XPATH, '//*[@id="page-wrapper"]/div[2]/div/div/form/button[4]') ``` ``` def sample_with_pure_text(): time.sleep(5) #Have to set a fixed wait time. And the input field have no text content at all driver.handle_event_helper.execute_element_have_text("input", 'Email address', "sample@gmail.com") driver.handle_event_helper.execute_element_have_text("button", 'Sign In') ``` ``` def sample_step_by_step(): element = driver.handle_event_helper.wait_for_presence(By.CLASS_NAME, "submit-btn") driver.handle_event_helper.move_cursor_and_click(element) ``` In the above example, an instance of the Chrome web driver is created, and an instance of HandleEventHelper is initialized with this driver instance. Then, various methods of HandleEventHelper are used to interact with web elements on the page, such as clicking on a button and entering text in an input field. The wait_for_presence() method is also used to wait for an element to become present on the page before performing any action on it. ## Captcha Solver This section contains the implementation of a captcha solver using computer vision and Selenium WebDriver. The `CaptchaSolver` class has methods to bypass login captchas and solve them using image recognition. The `waiting_for_loading_login_captcha` method waits for the captcha to load before solving it. The `solve_captcha` method downloads the captcha images and uses OpenCV to get the drag position to solve the captcha. The `is_page_source_contains_text` method checks if a given text is present in the page source. ### Example usage ``` while self.captcha_solver.is_waiting_for_sign_up_loading_captcha(): //do something if can not load captcah after TIME_OUT seconds pass self.captcha_solver.bypass_sign_up_captcha() ``` This code snippet runs a loop to continuously check if the sign-up captcha is still loading. If the loading takes too long, the program will proceed to the next line of code after a specified timeout. Once the captcha is loaded, the `bypass_sign_up_captcha()` method is called to solve the captcha and allow the program to proceed with sign-up. ## Remote API helper The RemoteAPIHelper class provides a convenient method for fetching JSON data from an API endpoint using Selenium. The class takes in a webdriver object during initialization and also initializes an instance of the HandleEnventHelper class which it uses to interact with the web page. ### Example usage ``` def sample_fetch_api(): api_url = "https://api.usercentrics.eu/translations/translations-en.json" json_result = driver.remote_api_helper.loadJsonFromURL(api_url) print(json_result) ``` In the above example, a sample_fetch_api() function has been defined to demonstrate how to use the RemoteAPIHelper class to fetch JSON data from an API endpoint in a Selenium script. This function can be used as a starting point for developers who want to integrate API requests into their Selenium scripts. ## Command Executor This module provides helper functions to execute commands in Python. - `execute_command(command)`: This function executes the given command. - `execute_command_with_root(command, root_password)`: This function executes the given command as root, using the specified root_password. ### Example usage ``` from command_execution_helper import execute_command, execute_command_with_root # Execute a simple command execute_command('ls') # Execute a command as root execute_command_with_root('apt-get update', 'mypassword') ``` ## File IO Helper This module provides various helper functions to work with file Input/Output (IO) operations. The functions provided are: - `remove_data_from_file(removedData, file_name)`: This function removes the lines containing the given removedData from the file with the specified file_name. It reads the file into a list, filters out the lines containing the specified removedData, and overwrites the file with the filtered list of lines. - `get_first_data_from_file(file_name)`: This function returns the first line of the file with the specified file_name. It reads the file, returns the first line as a string, and removes the newline character. - `get_random_data_from_file(file_name)`: This function returns a random line from the file with the specified file_name. It reads the file, generates a random index within the range of the number of lines, returns the line at that index as a string, and removes the newline character. - `get_all_data_as_list_from_file(file_name)`: This function returns all lines from the file with the specified file_name as a list of strings. It reads the file, returns all lines as a list of strings, and removes the newline character from each line. - `save_new_data(data, file_name)`: This function appends the given data as a new line to the file with the specified file_name. - `keep_log_data(data, additional_data = "", file_name = "data")`: This function appends the given data along with any additional data (if provided) to the log file with the specified file_name. If no file_name is provided, it will use the default value of "data". - `get_machine_name()`: This function returns the hostname of the machine on which the code is running. - `create_csv_directory()`: This function creates a directory named csv_file if it does not already exist and returns the path to the directory. ### Example usage ``` import file_io_helper # create csv directory csv_directory = file_io_helper.create_csv_directory() # save new data to file data = "new data" file_io_helper.save_new_data(data, "data") # get first line from file first_line = file_io_helper.get_first_data_from_file("data") print(first_line) # get random line from file random_line = file_io_helper.get_random_data_from_file("data") print(random_line) # get all lines from file as list all_lines = file_io_helper.get_all_data_as_list_from_file("data") print(all_lines) # remove data from file data_to_remove = "data to remove" file_io_helper.remove_data_from_file(data_to_remove, "data") # keep log data log_data = "log data" file_io_helper.keep_log_data(log_data, additional_data="some additional data") ``` ## DateTimeHelper A class for handling datetime manipulation in Python. - `get_time_remain_to(destinated_date_time_str)`: returns the timedelta between the current date and time and the given destination date and time string. - `get_current_date_time_in_date_time_format()`: returns the current date and time in the format specified in date_time_format. - `conver_str_date_time_to_hour_time_format(date_time_str)`: converts a datetime string to the hour format specified in hour_time_format. - `conver_str_date_time_to_date_time_format(date_time_str)`: converts a datetime string to the datetime format specified in date_time_format. - `conver_str_time_to_another_format(date_time_str, another_date_time_format)`: converts a datetime string to a specified datetime format.
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"/> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <title>Document</title> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous"> <link rel="stylesheet" href="style.css"> </head> <body> <nav class="navbar navbar-expand-lg navbar-dark bg-dark"> <span class="navbar-brand mb-0 h1">Movie PRO</span> <div class="input-group-append d-none d-md-flex mr-auto"> <select class="custom-select form-control rounded-left border-right-0" id="movie-search-select-md"> <option selected>Type</option> <option value="rating">Rating</option> <option value="title">Title</option> <option value="genre">Genre</option> </select> <input type="text" class="form-control rounded-0 search-item" id="search-item-md"> <button class="btn btn-outline-secondary form-control movie-search" type="button"><i class="fa fa-search"></i></button> <button class="btn btn-outline-secondary form-control rounded-right movie-search" type="button" data-toggle="modal" data-target="#advancedSearchModal">Advanced</button> </div> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarNavDropdown"> <ul class="navbar-nav"> <li class="nav-item"> <button type="button" class="btn btn-dark" data-toggle="modal" data-target="#addMovieModal">Add Movie</button> </li> <li class="nav-item dropdown"> <button id="btnSortDropdown" type="button" class="btn btn-dark dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Sort by </button> <div class="dropdown-menu" aria-labelledby="btnSortDropdown"> <a class="dropdown-item" id="rating" href="#">Rating</a> <a class="dropdown-item" id="title" href="#">Title</a> <a class="dropdown-item" id="genre" href="#">Genre</a> </div> </li> </ul> </div> </nav> <main class="container mt-4"> <div class="d-md-none d-flex flex-column align-items-center"> <div class="d-flex mb-5"> <img src="../images/popcorn.png" alt="popcorn-image"> <h3 class="ml-4 mb-0">WHAT IS MOVIE PRO</h3> </div> <h4 class="text-center mb-3">Search a movie</h4> <p class="ml-5 mr-5 mb-5">You can search movies by titles, ratings or generes. We'll find the movies for you! (Note: when searching by genre, only one word is needed or you can use advanced search)</p> <div class="input-group-append mb-4"> <select class="custom-select form-control rounded-left border-right-0" id="movie-search-select-sm"> <option selected>Type</option> <option value="rating">Rating</option> <option value="title">Title</option> <option value="genre">Genre</option> </select> <input type="text" class="form-control rounded-right" id="search-item-sm"> </div> <button class="btn btn-success mb-2 movie-search" type="button">Search</button> <input class="font-italic mb-5 button" type="button" data-toggle="modal" data-target="#advancedSearchModal" value="Advanced Search"> </div> <form class="modal fade input-group" id="addMovieModal" tabindex="-1" aria-labelledby="addMovieModal" style="display: none;" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title">Movie Info</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true" id="close">×</span> </button> </div> <div class="modal-body d-flex flex-column"> <label for="Movie-Input-Title" class="form-label">Enter Movie</label> <input type="text" class="form-control" id="Movie-Input-Title" aria-describedby="MovieHelp" placeholder="Enter Movie here"> </div> <div class="modal-footer"> <button type="submit" class="btn btn-secondary" id="submit-movie-name">Submit</button> </div> </div> </div> </form> <form class="modal fade input-group" id="advancedSearchModal" tabindex="-1" aria-labelledby="advancedSearchModal" style="display: none;" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title">Advanced Search</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true" id="closePage">×</span> </button> </div> <div class="modal-body d-flex flex-column"> <label for="movieGenre" class="form-label">Genre</label> <input type="checkbox" class="form-control" id="movieGenre" aria-describedby="movieGenre"> </div> <div class="modal-footer"> <button type="submit" class="btn btn-secondary" id="submit">Submit</button> </div> </div> </div> </form> <div class="se-pre-con"></div> <div class="card-deck row"></div> <div class="modal fade input-group" id="movieModal" tabindex="-1" aria-labelledby="movieModal" style="display: none;" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title">Movie Info</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true" id="x">×</span> </button> </div> <div class="modal-body d-flex flex-column"> <label><em>TITLE:</em> <input type="text" class="form-control movieModalTitle"> </label> <label><em>PLOT:</em> <textarea class="form-control movieModalPlot"></textarea> </label> <label><em>YEAR:</em> <input type="text" class="form-control movieModalYear"> </label> <label><em>GENRE:</em> <input type="text" class="form-control movieModalGenre"> </label> <label><em>DIRECTOR:</em> <input type="text" class="form-control movieModalDirector"> </label> <label><em>ACTORS:</em> <input type="text" class="form-control movieModalActors"> </label> <label><em>RATING:</em> <input type="text" class="form-control movieModalRating"> </label> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" id="finish-editing">Finish Editing</button> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> </div> </div> </div> </div> </main> <footer class="text-center"> <div>&#169; 2021 All rights reserved</div> <div> <a href="#"><i class="fa fa-facebook"></i></a> <a href="#"><i class="fa fa-twitter"></i></a> <a href="#"><i class="fa fa-rss"></i></a> <a href="#"><i class="fa fa-google"></i></a> <a href="#"><i class="fa fa-flickr"></i></a> <a href="#"><i class="fa fa-linkedin"></i></a> <a href="#"><i class="fa fa-pinterest"></i></a> </div> </footer> <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ho+j7jyWK8fNQe+A12Hb8AhRq26LrZ/JpcUGGOn+Y7RsweNrtN/tE3MoK7ZeZDyx" crossorigin="anonymous"></script> <script src="../script.js"></script> </body> </html>
From 05960109c00f8f7e62ef9120d0abf97083a63595 Mon Sep 17 00:00:00 2001 From: Jianing Ren <jianing.ren@rock-chips.com> Date: Fri, 5 Jun 2020 15:08:28 +0800 Subject: [PATCH] phy: phy-rockchip-naneng-usb2: add vup_gpio for swing calibration The USB2.0 OTG PHY of RV1126/1109 which is designed for lower power consumption provides only 8.8mA current source on DM. Multiplied by 45 Ohm host termination resistance, voltage is about 400mV. If the threshold voltage of host is greater than 400mV, the high speed handshake will fail and SoC communicate at full speed. So swing calibration is necessary. We use gpio to control the 220 Ohm pull-up resistor to provide additional current. Experiments show that the voltage of chirpK can be increases to about 600mV. Change-Id: I8b41054af4732569dbc8185bc3d3d4a2ba83cd6a Signed-off-by: Jianing Ren <jianing.ren@rock-chips.com> --- .../phy/rockchip/phy-rockchip-naneng-usb2.c | 127 ++++++++++++++++-- 1 file changed, 118 insertions(+), 9 deletions(-) diff --git a/drivers/phy/rockchip/phy-rockchip-naneng-usb2.c b/drivers/phy/rockchip/phy-rockchip-naneng-usb2.c index 04cb59b6274e..446570227cca 100644 --- a/drivers/phy/rockchip/phy-rockchip-naneng-usb2.c +++ b/drivers/phy/rockchip/phy-rockchip-naneng-usb2.c @@ -41,6 +41,12 @@ enum rockchip_usb2phy_port_id { USB2PHY_NUM_PORTS, }; +enum calibrate_state { + SWING_CALIBRATION, + CURRENT_COMPENSATION, + CALIBRATION_DONE, +}; + static const unsigned int rockchip_usb2phy_extcon_cable[] = { EXTCON_USB, EXTCON_USB_HOST, @@ -204,7 +210,7 @@ struct rockchip_usb2phy_port { /** * struct rockchip_usb2phy: usb2.0 phy driver data. - * @dev: pointer to our struct device + * @dev: pointer to our struct device. * @grf: General Register Files regmap. * @base: the base address of APB interface. * @reset: power reset signal for phy. @@ -214,7 +220,10 @@ struct rockchip_usb2phy_port { * @clk480m_hw: clock struct of phy output clk management. * @chg_type: USB charger types. * @edev_self: represent the source of extcon. - * @edev: extcon device for notification registration + * @edev: extcon device for notification registration. + * @vup_gpio: gpio switch for pull-up register on DM. + * @wait_timer: hrtimer for phy calibration delay. + * @cal_state: state of phy calibration. * @phy_cfg: phy register configuration, assigned by driver data. * @ports: phy port instance. */ @@ -230,6 +239,9 @@ struct rockchip_usb2phy { enum power_supply_type chg_type; bool edev_self; struct extcon_dev *edev; + struct gpio_desc *vup_gpio; + struct hrtimer wait_timer; + enum calibrate_state cal_state; const struct rockchip_usb2phy_cfg *phy_cfg; struct rockchip_usb2phy_port ports[USB2PHY_NUM_PORTS]; }; @@ -677,13 +689,87 @@ static int rockchip_usb2phy_set_mode(struct phy *phy, enum phy_mode mode) return ret; } -static const struct phy_ops rockchip_usb2phy_ops = { - .init = rockchip_usb2phy_init, - .exit = rockchip_usb2phy_exit, - .power_on = rockchip_usb2phy_power_on, - .power_off = rockchip_usb2phy_power_off, - .set_mode = rockchip_usb2phy_set_mode, - .owner = THIS_MODULE, +static enum hrtimer_restart rv1126_wait_timer_fn(struct hrtimer *t) +{ + enum hrtimer_restart ret; + ktime_t delay; + static u32 reg; + struct rockchip_usb2phy *rphy = container_of(t, struct rockchip_usb2phy, + wait_timer); + + switch (rphy->cal_state) { + case SWING_CALIBRATION: + /* disable tx swing calibrate */ + writel(0x5d, rphy->base + 0x20); + /* read the value of rsistance calibration */ + reg = readl(rphy->base + 0x10); + + /* open the pull-up resistor */ + gpiod_set_value(rphy->vup_gpio, 1); + /* set cfg_hs_strg 0 to increase chirpk amplitude */ + writel(0x08, rphy->base + 0x00); + /* + * set internal 45 Ohm resistance minimal to + * increase chirpk amplitude + */ + writel(0x7c, rphy->base + 0x10); + + delay = ktime_set(0, 1200000); + hrtimer_forward_now(&rphy->wait_timer, delay); + rphy->cal_state = CURRENT_COMPENSATION; + ret = HRTIMER_RESTART; + break; + case CURRENT_COMPENSATION: + /* close the pull-up resistor */ + gpiod_set_value(rphy->vup_gpio, 0); + /* + * set cfg_sel_strength and cfg_sel_pw 1 to + * correct the effect of pull-up resistor + */ + writel(0xe8, rphy->base + 0x00); + /* write the value of rsistance calibration */ + writel(reg, rphy->base + 0x10); + + delay = ktime_set(0, 1000000); + hrtimer_forward_now(&rphy->wait_timer, delay); + rphy->cal_state = CALIBRATION_DONE; + ret = HRTIMER_RESTART; + break; + case CALIBRATION_DONE: + /* enable tx swing calibrate */ + writel(0x4d, rphy->base + 0x20); + /* fall through */ + default: + ret = HRTIMER_NORESTART; + break; + } + + return ret; +} + +static int rv1126_usb2phy_calibrate(struct phy *phy) +{ + struct rockchip_usb2phy_port *rport = phy_get_drvdata(phy); + struct rockchip_usb2phy *rphy = dev_get_drvdata(phy->dev.parent); + ktime_t delay; + + if (rport->port_id != USB2PHY_PORT_OTG) + return 0; + + delay = ktime_set(0, 500000); + rphy->cal_state = SWING_CALIBRATION; + hrtimer_start(&rphy->wait_timer, delay, HRTIMER_MODE_REL); + + return 0; +} + +static struct phy_ops rockchip_usb2phy_ops = { + .init = rockchip_usb2phy_init, + .exit = rockchip_usb2phy_exit, + .power_on = rockchip_usb2phy_power_on, + .power_off = rockchip_usb2phy_power_off, + .set_mode = rockchip_usb2phy_set_mode, + .owner = THIS_MODULE, }; static const char *chg_to_string(enum power_supply_type chg_type) @@ -1222,6 +1308,13 @@ static int rockchip_usb2phy_probe(struct platform_device *pdev) if (IS_ERR(rphy->reset)) return PTR_ERR(rphy->reset); + rphy->vup_gpio = devm_gpiod_get_optional(dev, "vup", GPIOD_OUT_LOW); + if (IS_ERR(rphy->vup_gpio)) { + ret = PTR_ERR(rphy->vup_gpio); + dev_err(dev, "failed to get vup gpio (%d)\n", ret); + return ret; + } + reset_control_assert(rphy->reset); udelay(1); reset_control_deassert(rphy->reset); @@ -1293,6 +1386,15 @@ static int rockchip_usb2phy_probe(struct platform_device *pdev) of_node_cmp(child_np->name, "otg-port")) goto next_child; + if (rphy->vup_gpio && + of_device_is_compatible(np, "rockchip,rv1126-usb2phy")) { + rockchip_usb2phy_ops.calibrate = + rv1126_usb2phy_calibrate; + hrtimer_init(&rphy->wait_timer, CLOCK_MONOTONIC, + HRTIMER_MODE_REL); + rphy->wait_timer.function = &rv1126_wait_timer_fn; + } + phy = devm_phy_create(dev, child_np, &rockchip_usb2phy_ops); if (IS_ERR(phy)) { dev_err(dev, "failed to create phy\n"); @@ -1349,6 +1451,13 @@ static int rockchip_usb2phy_probe(struct platform_device *pdev) static int rockchip_usb2phy_remove(struct platform_device *pdev) { + struct device_node *np = pdev->dev.of_node; + struct rockchip_usb2phy *rphy = platform_get_drvdata(pdev); + + if (rphy->vup_gpio && + of_device_is_compatible(np, "rockchip,rv1126-usb2phy")) + hrtimer_cancel(&rphy->wait_timer); + return 0; } -- 2.35.3
/* eslint-disable no-console */ 'use strict' const https = require('https') const fs = require('fs') const crypto_ = require('crypto') const jsdom = require('jsdom') const sharp = require('sharp') const request = require('request') const { JSDOM } = jsdom const shasum = crypto_.createHash('sha1') const url = process.argv[2] const req = https.request(url, (res: any) => { let html = '' res.on('data', (chunk: any) => { html += chunk }) res.on('end', async () => { const ogpObj: any = {} const dom = new JSDOM(html) const headEls = dom.window.document.head.children for (let i = 0; i < headEls.length; i++) { const prop = headEls[i].getAttribute('property') if (!prop) continue ogpObj[prop.split(':')[1]] = headEls[i].getAttribute('content') } let fileName = '' if (ogpObj.image) { fileName = await downloadImage(ogpObj.image) } console.log(ogpObj) console.log('↓----------------') console.log( `<link-card title="${ogpObj.title}" text="${ ogpObj.description }" link-url="${ ogpObj.url }" img-src="${`/link_img/${fileName}.png`}"></link-card>` ) }) }) req.end() async function downloadImage(fileUrl: string) { console.log(fileUrl) return await new Promise<string>((resolve) => { request({ method: 'GET', url: fileUrl, encoding: null }, async function ( error: any, response: any, body: any ) { if (!error && response.statusCode === 200) { fs.writeFileSync('tmp.png', body, 'binary') shasum.update(fileUrl) const hash = shasum.digest('hex') console.log(hash) await resizeImage('tmp.png', hash) resolve(hash) } }) }) } async function resizeImage(filePath: string, outputName: string) { await new Promise<void>((resolve) => { sharp(filePath) .resize(null, 100) .resize(100, 100) .toFile( `client/static/link_img/${outputName}.png`, (err: any, info: any) => { if (err) { throw err } console.log(info) resolve() } ) }) }
import { useState } from 'react'; import { useDispatch, useSelector } from 'react-redux'; import { Formik, Form, ErrorMessage } from 'formik'; import { useTranslation } from 'react-i18next'; import { toast } from 'react-toastify'; import { apiUpdateUserSettings } from '../../redux/authorization/authReducer'; import { closeModal } from '../../redux/modal/modalSlice'; import { selectUserData, selectIsLoading } from '../../redux/selectors'; import { userSettingsSchema } from 'schemas/schemas'; import { SaveModalButton } from 'components'; import { UploadPhoto } from 'components/Icons/UploadPhoto'; import { Eye } from '../../components/Icons/Eye'; import { EyeSlash } from '../../components/Icons/EyeSlash'; import { FormInfo, PersonalInfo, AvatarSettingsTitle, AvatarInput, Avatar, AvatarLabel, UploadPhotoText, OptionTitle, FieldContainer, FieldContainerNoMargin, GenderContainer, RadiosContainer, RadioElement, InputRadio, Label, InputText, PasswordsContainer, PasswordTitle, InputWrapper, IconButton, InputPassword, SaveButtonContainer, Error, } from './FormUserSettings.styled'; export const FormUserSettings = () => { const dispatch = useDispatch(); const { t } = useTranslation(); const isLoading = useSelector(selectIsLoading); const data = useSelector(selectUserData); const [showOldPassword, setShowOldPassword] = useState(false); const [showNewPassword, setShowNewPassword] = useState(false); const [showRepeatPassword, setShowRepeatPassword] = useState(false); const [localAvatarUrl, setlocalAvatarUrl] = useState(null); const [avatarFile, setavatarFile] = useState(null); const swapOldPassword = () => { setShowOldPassword(!showOldPassword); }; const swapNewPassword = () => { setShowNewPassword(!showNewPassword); }; const swapRepeatPassword = () => { setShowRepeatPassword(!showRepeatPassword); }; const handleChange = e => { setlocalAvatarUrl(URL.createObjectURL(e.currentTarget.files[0])); setavatarFile(e.currentTarget.files[0]); }; const handleSubmit = (values, actions) => { const formData = new FormData(); Object.entries(values).forEach(([key, value]) => { if ( value !== '' && value !== undefined && value !== null && key !== 'repeatPassword' ) { formData.append(key, value); } }); avatarFile && formData.append('avatarURL', avatarFile); dispatch(apiUpdateUserSettings(formData)) .unwrap() .then(res => { toast.success('Settings updated successfully'); dispatch(closeModal()); }) .catch(e => { toast.error(e.response.data.message); }); }; const initialValues = { avatarURL: '', gender: data?.gender ? data.gender : null, userName: data?.userName ? data.userName : '', email: data?.email ? data.email : '', oldPassword: '', newPassword: '', }; return ( <Formik initialValues={initialValues} validationSchema={userSettingsSchema} onSubmit={handleSubmit} > {({ errors }) => ( <Form autoComplete="off"> <FormInfo> <PersonalInfo> <FieldContainer> <AvatarSettingsTitle> {t('UserSettings.UserSettingsPhotoTitle')} </AvatarSettingsTitle> <AvatarLabel> <Avatar src={ (localAvatarUrl && localAvatarUrl) || (data?.avatarURL && data.avatarURL) } alt="avatar" /> <UploadPhoto /> <UploadPhotoText> {t('UserSettings.UserSettingsPhotoUpload')} </UploadPhotoText> <AvatarInput id="avatarURL" name="avatarURL" type="file" accept="image" onChange={handleChange} /> </AvatarLabel> <ErrorMessage name="avatarURL" component={Error} /> </FieldContainer> <GenderContainer> <OptionTitle> {t('UserSettings.UserSettingsGenderTitle')} </OptionTitle> <RadiosContainer> <RadioElement> <InputRadio type="radio" name="gender" id="Woman" value="Woman" /> <ErrorMessage name="gender" component={Error} /> <Label htmlFor="Woman"> {t('UserSettings.UserSettingsGenderWoman')} </Label> </RadioElement> <RadioElement> <InputRadio type="radio" name="gender" id="Man" value="Man" /> <Label htmlFor="Man"> {t('UserSettings.UserSettingsGenderMan')} </Label> </RadioElement> </RadiosContainer> </GenderContainer> <FieldContainer> <OptionTitle htmlFor="userName"> {t('UserSettings.UserSettingsNameLabel')} </OptionTitle> <InputText name="userName" type="text" id="userName" placeholder={t('UserSettings.UserSettingsNamePlaceholder')} $error={errors.userName} /> <ErrorMessage name="userName" component={Error} /> </FieldContainer> <FieldContainerNoMargin> <OptionTitle htmlFor="email"> {t('UserSettings.UserSettingsEmailLabel')} </OptionTitle> <InputText type="email" name="email" id="email" placeholder={t('UserSettings.UserSettingsEmailPlaceholder')} $error={errors.email} /> <ErrorMessage name="email" component={Error} /> </FieldContainerNoMargin> </PersonalInfo> <PasswordsContainer> <PasswordTitle> {t('UserSettings.UserSettingsPasswordTitle')} </PasswordTitle> <FieldContainer> <Label htmlFor="oldPassword"> {t('UserSettings.UserSettingsOldPassLabel')} </Label> <InputWrapper> <InputPassword type={showOldPassword ? 'text' : 'password'} name="oldPassword" id="oldPassword" placeholder={t( 'UserSettings.UserSettingsPasswordPlaceholder' )} $error={errors.oldPassword} /> <IconButton type="button" onClick={swapOldPassword}> {showOldPassword ? <Eye /> : <EyeSlash />} </IconButton> </InputWrapper> <ErrorMessage name="newPassword" component={Error} /> </FieldContainer> <FieldContainer> <Label htmlFor="newPassword"> {t('UserSettings.UserSettingsNewPassLabel')} </Label> <InputWrapper> <InputPassword type={showNewPassword ? 'text' : 'password'} name="newPassword" id="newPassword" placeholder={t( 'UserSettings.UserSettingsPasswordPlaceholder' )} $error={errors.newPassword} /> <IconButton type="button" onClick={swapNewPassword}> {showNewPassword ? <Eye /> : <EyeSlash />} </IconButton> </InputWrapper> <ErrorMessage name="newPassword" component={Error} /> </FieldContainer> <FieldContainerNoMargin> <Label htmlFor="repeatPassword"> {t('UserSettings.UserSettingsRepeatPassLabel')} </Label> <InputWrapper> <InputPassword type={showRepeatPassword ? 'text' : 'password'} name="repeatPassword" id="repeatPassword" placeholder={t( 'UserSettings.UserSettingsPasswordPlaceholder' )} $error={errors.repeatPassword} /> <IconButton type="button" onClick={swapRepeatPassword}> {showRepeatPassword ? <Eye /> : <EyeSlash />} </IconButton> </InputWrapper> <ErrorMessage name="repeatPassword" component={Error} /> </FieldContainerNoMargin> </PasswordsContainer> </FormInfo> <SaveButtonContainer> <SaveModalButton isLoading={isLoading} /> </SaveButtonContainer> </Form> )} </Formik> ); };
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_strmapi.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: joseanto <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2023/10/27 09:10:10 by joseanto #+# #+# */ /* Updated: 2023/10/27 09:10:11 by joseanto ### ########.fr */ /* */ /* ************************************************************************** */ #include "libft.h" char *ft_strmapi(char const *s, char (*f)(unsigned int, char)) { int i; char *str; if (!s || !f) { return (NULL); } i = 0; while (s[i]) { i++; } str = malloc((i + 1) * sizeof(char)); if (str) { str[i] = '\0'; while (i) { i--; str[i] = f(i, s[i]); } } return (str); } // #include <stdio.h> // static char upper(unsigned int i, char c) // { // if (c >= 'a' && c <= 'z') // { // return (c - 32); // } // return c; // } // int main(void) // { // printf("%s", ft_strmapi("teste", upper)); // return (0); // }
package org.colos.roboticsLabs.robots.utils.trajectories; /** * @author Almudena Ruiz */ public class Spline2Trajectory extends Trajectory { protected double[] mQInt1, mQInt2; protected double mtInt1, mtInt2; private double[][] mVqi, mCoef1, mCoef2, mCoef3; public Spline2Trajectory(double[] qi, double[] qInt1, double[] qInt2, double[] qf, double tInt1, double tInt2, double duration) { super(qi, qf, duration); mtInt1 = tInt1; mtInt2 = tInt2; mQInt1 = new double[mDOF]; System.arraycopy(qInt1, 0, mQInt1, 0, mDOF); mQInt2 = new double[mDOF]; System.arraycopy(qInt2, 0, mQInt2, 0, mDOF); mVqi = new double[mDOF][4]; mCoef1 = new double[mDOF][4]; mCoef2 = new double[mDOF][4]; mCoef3 = new double[mDOF][4]; for (int i = 0; i < mDOF; i++) { mVqi[i] = velqi(mQi[i], mQInt1[i], mQInt2[i], mQf[i], mtInt1, mtInt2, mDuration); mCoef1[i] = coefPolSpline(mQi[i], mQInt1[i], mVqi[i][0], mVqi[i][1], 0, mtInt1); mCoef2[i] = coefPolSpline(mQInt1[i], mQInt2[i], mVqi[i][1], mVqi[i][2], mtInt1, mtInt2); mCoef3[i] = coefPolSpline(mQInt2[i], mQf[i], mVqi[i][2], mVqi[i][3], mtInt2, mDuration); } } /** * Gets the first intermediate position of the trajectory * @return the first intermediate position */ final public double[] getQInt1() {return mQInt1;} /** * Gets the first intermediate time of the trajectory * @return the first intermediate time */ final public double getIntermediateTime1() {return mtInt1;} /** * Gets the second intermediate position of the trajectory * @return the second intermediate position */ final public double[] getQInt2() {return mQInt2;} /** * Gets the second intermediate time of the trajectory * @return the second intermediate time */ final public double getIntermediateTime2() {return mtInt2;} /** * Calculates the velocity of the trajectory * @param qi the initial point * @param q1 the first intermediate point * @param q2 the second intermediate point * @param qf the final point * @param t1 the first intermediate time * @param t2 the second intermediate time * @param tf the final time * @return the velocity in these points */ private double[] velqi(double qi, double q1, double q2, double qf,double t1, double t2, double tf) { double[] vqi = new double[4]; vqi[0] = vqi[3] = 0; // vqi = vqf = 0; double K = (3 * (t1 * t1 * (q2 - q1) + t2 * t2 * (q1 - qi))) / (t1 * t2); double L = (3 * (t2 * t2 * (qf - q2) + tf * tf * (q2 - q1))) / (t2 * tf); vqi[2] = (2 * (t1 + t2) * L - K * tf) / (4 * (t1 + t2) * (t2 + tf) - t1 * tf); vqi[1] = (K - t1 * vqi[2]) / (2 * (t1 + t2)); return vqi; } /** * Calculates the coefficient of the Spline polynomial * @param qi the initial point * @param qf the final point * @param vqi the initial point velocity * @param vqf the final point velocity * @param ti the initial time * @param tf the final time * @return the Spline polynomial coefficients */ private double[] coefPolSpline(double qi, double qf, double vqi, double vqf, double ti, double tf) { double[] coef = new double[4]; // coef a, b, c, d, double T = tf - ti; // coef T coef[0] = qi; // coef a coef[1] = vqi; // coef b coef[2] = ((3 * (qf - qi)) / (T * T)) - (2 * vqi + vqf) / (T * T); // coef c coef[3] = ((-2 * (qf - qi)) / (T * T * T)) + ((vqf + vqi) / (T * T)); // coef d return coef; } /** * Calculates the value of a given coefficient * @param coef the coefficient * @param ti the initial time * @param t the time * @return the coefficient value at given times */ private double evalPol(double[] coef, double ti, double t) { return coef[0] + coef[1] * (t - ti) + coef[2] * (t - ti) * (t - ti) + coef[3] * (t - ti) * (t - ti) * (t - ti); } public double[] getPoint(double t) { double[] q = new double[mDOF]; if (t <= 0) q = mQi; else { if (t <= mtInt1) { // Polinomio en (qi, qInt1] for (int i = 0; i < mDOF; i++) { q[i] = evalPol(mCoef1[i], 0, t); } } else if (t <= mtInt2) { // Polinomio en (qInt1, qInt2] for (int i = 0; i < mDOF; i++) { q[i] = evalPol(mCoef2[i], mtInt1, t); } } else if (t < mDuration) { // Polinomio en (qInt2, qf) for (int i = 0; i < mDOF; i++) { q[i] = evalPol(mCoef3[i], mtInt2, t); } } else q = mQf; } return q; } public double[][] getPoints(double[] t) { double[][] points = new double[t.length][mDOF]; for (int i = 0; i < t.length; i++) { points[i] = getPoint(t[i]); } return points; } public double[][] getPoints(int nPoints) { double[] t = new double[nPoints]; double deltaT = mDuration / (nPoints - 1); double l1 = mtInt1; int n1 = (int) Math.round(1 + l1 / deltaT); double deltaT1 = l1 / (n1 - 1); double l2 = mtInt2 - mtInt1; int n2 = (int) Math.round(l2 / deltaT); double deltaT2 = l2 / n2; double l3 = mDuration - mtInt2; int n3 = nPoints - (n1 + n2); // int n3 = (int) Math.round(l3 / deltaT); double deltaT3 = l3 / n3; for (int i = 0; i < n1; i++) { t[i] = i * deltaT1; System.out.println("t" + (i + 1) + " = " + t[i]); } for (int i = 0; i < n2; i++) { t[n1 + i] = mtInt1 + (i + 1) * (deltaT2); System.out.println("t" + (n1 + i + 1) + " = " + t[n1 + i]); } for (int i = 0; i < n3; i++) { t[n1 + n2 + i] = mtInt2 + (i + 1) * (deltaT3); System.out .println("t" + (n1 + n2 + i + 1) + " = " + t[n1 + n2 + i]); } return getPoints(t); } }
import { Hero } from '../hero'; import { FormsModule } from '@angular/forms'; import { HeroService } from '../hero.service'; import { ActivatedRoute } from '@angular/router'; import { CommonModule, Location } from '@angular/common'; import { Component, Input, inject } from '@angular/core'; @Component({ selector: 'app-hero-detail', standalone: true, imports: [CommonModule, FormsModule], templateUrl: './hero-detail.component.html', styleUrl: './hero-detail.component.css', }) export class HeroDetailComponent { @Input() hero?: Hero; location: Location; route: ActivatedRoute = inject(ActivatedRoute); constructor(private heroService: HeroService, location: Location) { this.location = location; } ngOnInit() { this.getHero(); } getHero() { const id = Number(this.route.snapshot.params['id']); this.heroService.getHero(id).subscribe((hero) => (this.hero = hero)); } save(): void { if (this.hero) { this.heroService.updateHero(this.hero).subscribe(() => this.goBack()); } } goBack(): void { this.location.back(); } }
package com.rustedbrain.diploma.travelvisualizer.task.place; import android.os.AsyncTask; import android.util.Log; import com.rustedbrain.diploma.travelvisualizer.LoginActivity; import com.rustedbrain.diploma.travelvisualizer.MainActivity; import com.rustedbrain.diploma.travelvisualizer.TravelAppUtils; import com.rustedbrain.diploma.travelvisualizer.model.dto.security.AuthUserDTO; import com.rustedbrain.diploma.travelvisualizer.model.dto.travel.LatLngDTO; import com.rustedbrain.diploma.travelvisualizer.model.dto.travel.PlaceDescriptionDTO; import com.rustedbrain.diploma.travelvisualizer.model.dto.travel.request.NamingPlaceRequest; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.http.converter.json.MappingJacksonHttpMessageConverter; import org.springframework.web.client.HttpClientErrorException; import org.springframework.web.client.ResourceAccessException; import org.springframework.web.client.RestTemplate; import java.net.URI; import java.net.URISyntaxException; import java.util.Collections; import java.util.List; public class GetPlaceDescriptionTask extends AsyncTask<Void, Void, ResponseEntity<PlaceDescriptionDTO>> { private final List<Listener> taskListeners; private final AuthUserDTO userDTO; private final double placeLatitude; private final double placeLongitude; public GetPlaceDescriptionTask(double placeLatitude, double placeLongitude, AuthUserDTO userDTO, Listener listener) { this.placeLatitude = placeLatitude; this.placeLongitude = placeLongitude; this.userDTO = userDTO; this.taskListeners = Collections.singletonList(listener); } @Override protected ResponseEntity<PlaceDescriptionDTO> doInBackground(Void... params) { try { RestTemplate restTemplate = new RestTemplate(); restTemplate.getMessageConverters().add(new MappingJacksonHttpMessageConverter()); NamingPlaceRequest request = new NamingPlaceRequest(userDTO.getUsername(), new LatLngDTO(placeLatitude, placeLongitude)); HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.add(MainActivity.AUTH_TOKEN_HEADER_NAME, userDTO.getToken()); return restTemplate.postForEntity(new URI(TravelAppUtils.getAbsoluteUrl(TravelAppUtils.PLACE_GET_MAP_DESCRIPTION_URL)), new HttpEntity<>(request, httpHeaders), PlaceDescriptionDTO.class); } catch (ResourceAccessException | HttpClientErrorException | URISyntaxException ex) { Log.d(LoginActivity.class.getName(), ex.getMessage()); return null; } } @Override protected void onPostExecute(final ResponseEntity<PlaceDescriptionDTO> responseEntity) { for (Listener listener : taskListeners) { listener.setGetPlaceDescriptionTask(null); listener.showProgress(false); } if (responseEntity == null) { for (Listener listener : taskListeners) { listener.showGetPlaceDescriptionDTOTaskError(); } } else if (HttpStatus.OK.equals(responseEntity.getStatusCode())) { for (Listener listener : taskListeners) { listener.showPlaceDescriptionDTO(responseEntity.getBody()); } } else { for (Listener listener : taskListeners) { listener.showGetPlaceDescriptionDTOTaskError(); } } } @Override protected void onCancelled() { for (Listener listener : taskListeners) { listener.setGetPlaceDescriptionTask(null); listener.showProgress(false); } } public interface Listener { void setGetPlaceDescriptionTask(GetPlaceDescriptionTask getPlaceDescriptionTask); void showProgress(boolean show); void showGetPlaceDescriptionDTOTaskError(); void showPlaceDescriptionDTO(PlaceDescriptionDTO placeDescriptionDTO); } }
import type TelegramBot from "node-telegram-bot-api"; import type { ChatId } from "node-telegram-bot-api"; import type { Products } from "../Products"; import type { IUserState } from "../interfaces/IUserState"; import { States } from "../States"; import { setUserState } from "../features/setUserState"; import { Texts, greeting, newOrder } from "../texts"; import { askKeyboard, contactsKeyboard, menuKeyboard, orderKeyboard, portfolioKeyboard } from "../keyboards"; import { ADMIN_CHAT_ID } from "../consts"; import { Commands } from "../Commands"; export const start = async (chatId: ChatId, name: string, userStates: IUserState[], bot: TelegramBot) => { setUserState(chatId, States.Menu, userStates, name); const returnText = greeting(name); return await bot.sendMessage(chatId, returnText, menuKeyboard); }; export const menu = async (chatId: ChatId, userName: string, userStates: IUserState[], bot: TelegramBot) => { setUserState(chatId, States.Menu, userStates, userName); return await bot.sendMessage(chatId, "Меню", menuKeyboard); }; export const order = async (chatId: ChatId, userName: string, userStates: IUserState[], bot: TelegramBot) => { setUserState(chatId, States.Order, userStates, userName); return await bot.sendMessage( chatId, "Какой продукт вы хотите заказать?", orderKeyboard, ); }; export const sendOrder = async (userName: string, chatId: ChatId, product: Products, userStates: IUserState[], bot: TelegramBot) => { const result = newOrder(userName, chatId, product) setUserState(chatId, States.Menu, userStates, userName); await bot.sendMessage(ADMIN_CHAT_ID, result, { parse_mode: "HTML" }); return await bot.sendMessage( chatId, Texts.OrderHasBeenSend, menuKeyboard, ); }; export const contacts = async (chatId: ChatId, userName: string, userStates: IUserState[], bot: TelegramBot) => { setUserState(chatId, States.Contacts, userStates, userName); return await bot.sendMessage( chatId, "Мои контакты. Жду сообщения", contactsKeyboard, ); }; export const portfolio = async (chatId: ChatId, userName: string, userStates: IUserState[], bot: TelegramBot) => { setUserState(chatId, States.Portfolio, userStates, userName); return await bot.sendMessage(chatId, "Портфолио", portfolioKeyboard); }; export const ask = async (chatId: number, userName: string, userStates: IUserState[], bot: TelegramBot) => { setUserState(chatId, States.Ask, userStates, userName); return await bot.sendMessage( chatId, Texts.AskAnyQuestion, askKeyboard, ); }; export const askSend = async (chatId: ChatId, userName: string, userMessage: string, userStates: IUserState[], bot: TelegramBot) => { setUserState(chatId, States.Menu, userStates, userName); if(userMessage === Commands.Ask || userMessage === Commands.Contacts || userMessage === Commands.Menu || userMessage === Commands.Order || userMessage === Commands.Portfolio){ return await bot.sendMessage(chatId, Texts.WriteCorrectAnswer, menuKeyboard); } const message = `Пользователь @${userName} задал вопрос:\n\n"${userMessage}"`; await bot.sendMessage(ADMIN_CHAT_ID, message); return await bot.sendMessage( chatId, Texts.MessageHasBeenSend, menuKeyboard, ); };
/** * Object Node Class * * This Class implements a JSON Object node which contains named Json nodes * in a non-order-dependent manner. This is equivalent to a map-type * representation. * * Author: Jeffrey R. Naujok * Created: 4/15/2019 * Log: * $LOG$ * * Copyright (C) 2019, The Irene Adler Software Group, all rights reserved. * [A division of BlackStar Enterprises, LLC.] */ #ifndef IASLIB_OBJECTNODE_H__ #define IASLIB_OBJECTNODE_H__ #ifdef IASLIB_JSON_SUPPORT__ #include "JsonNode.h" #include "../Collections/Hash.h" namespace IASLib { class CObjectNode : public CJsonNode { private: CHash objectNodes; public: /** * Calling "asText" on an ObjectNode will return the JSON representation of the entire * object node -- in short, the JSON text. */ virtual CString asText(); /** * Method that can be called to get a node that is guaranteed not to allow changing of * this node through mutators on this node or any of its children. */ virtual CJsonNode *clone(); /** * Method for accessing all value nodes of this Node, iff this node is a JSON Array or Object node. */ virtual CIterator *elements(); // Equality for node objects is defined as full (deep) value equality. virtual bool equals(CJsonNode *o); virtual CIterator *fieldNames(); virtual CIterator *fields(); // Method for finding a JSON Object that contains specified field, within this node or its descendants. virtual CJsonNode *findParent(CString fieldName); // Method for finding a JSON Object that contains specified field, within this node or its descendants. virtual CArray *FindParents(CString fieldName); virtual CArray *FindParents(CString fieldName, CArray *foundSoFar); //Method similar to findValue(java.lang.String), but that will return a "missing node" instead of null if no field is found. virtual CJsonNode *findPath(CString fieldName); // Method for finding a JSON Object field with specified name in this node or its child nodes, and returning value it has. virtual CJsonNode *findValue(CString fieldName); // Method for finding JSON Object fields with specified name, and returning found ones as a List. virtual CArray *FindValues(CString fieldName); virtual CArray *FindValues(CString fieldName, CArray *foundSoFar); // Similar to findValues(java.lang.String), but will additionally convert values into Strings, calling asText(). virtual CArray *FindValuesAsText(CString fieldName); virtual CArray *FindValuesAsText(CString fieldName, CArray *foundSoFar); // Method for accessing value of the specified element of an array node. virtual CJsonNode *get(int index); // Method for accessing value of the specified field of an object node. virtual CJsonNode *get(CString fieldName); // Return the type of this node virtual JsonNodeType getNodeType() { return JsonNodeType::OBJECT; } // Method that allows checking whether this node is JSON Array node and contains a value for specified index If this is the case (including case of specified indexing having null as value), returns true; otherwise returns false. virtual bool has(int index); // Method that allows checking whether this node is JSON Object node and contains value for specified property. virtual bool has(CString fieldName); // Method that is similar to has(int), but that will return false for explicitly added nulls. virtual bool hasNonNull(int index); // Method that is similar to has(String), but that will return false for explicitly added nulls. virtual bool hasNonNull(CString fieldName); virtual bool isContainerNode(); virtual bool isNull(); virtual bool isObject() { return true; } virtual bool isPojo(); virtual CIterator *iterator(); // This method is similar to get(int), except that instead of returning null if no such element exists (due to index being out of range, or this node not being an array), a "missing node" (node that returns true for isMissingNode()) will be returned. virtual CJsonNode *path(int index); // This method is similar to get(String), except that instead of returning null if no such value exists (due to this node not being an object, or object not having value for the specified field), a "missing node" (node that returns true for isMissingNode()) will be returned. virtual CJsonNode *path(CString fieldName); virtual int size(); // Note: marked as abstract to ensure all implementation classes define it properly. virtual CString toString(); // Method that can be called on Object nodes, to access a property that has Object value; or if no such property exists, to create, add and return such Object node. virtual CJsonNode *with(CString propertyName); // Method that can be called on Object nodes, to access a property that has Array value; or if no such property exists, to create, add and return such Array node. virtual CJsonNode *withArray(CString propertyName); }; } #endif // IASLIB_JSON_SUPPORT__ #endif // IASLIB_OBJECTNODE_H__
/* C++ program to compare swap function of two numbers by comparing pass by pointer vs pass by reference vs pass by value */ #include <iostream> using namespace std; // Function to swap two numbers using // pass by pointer. void swapp(int* x, int* y) { int z = *x; *x = *y; *y = z; } // Function to swap two numbers using // pass by reference. void swapr(int& x, int& y) { int z = x; x = y; y = z; } void swapv(int x, int y) { int z = x; x = y; y = z; } int main() { int a = 45, b = 35; cout << "Before Swap\n"; cout << "a = " << a << " b = " << b << "\n"; swapp(&a, &b); cout << "After Swap with pass by pointer\n"; cout << "a = " << a << " b = " << b << "\n"; a = 45, b = 35; cout << "Before Swap\n"; cout << "a = " << a << " b = " << b << "\n"; swapr(a, b); cout << "After Swap with pass by reference\n"; cout << "a = " << a << " b = " << b << "\n"; a = 45, b = 35; cout << "Before Swap\n"; cout << "a = " << a << " b = " << b << "\n"; swapv(a, b); cout << "After Swap with pass by reference\n"; cout << "a = " << a << " b = " << b << "\n"; return 0; }
/* * astyle --force-indent=tab=4 --brackets=linux --indent-switches * --pad=oper --one-line=keep-blocks --unpad=paren * * Miranda NG: the free IM client for Microsoft* Windows* * * Copyright (c) 2000-09 Miranda ICQ/IM project, * all portions of this codebase are copyrighted to the people * listed in contributors.txt. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * you should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * part of tabSRMM messaging plugin for Miranda. * * (C) 2005-2009 by silvercircle _at_ gmail _dot_ com and contributors * * the contact cache * */ #ifndef __CONTACTCACHE_H #define __CONTACTCACHE_H #define C_INVALID_PROTO "<proto error>" #define C_INVALID_ACCOUNT _T("<account error>") #define C_INVALID_PROTO_T _T("<proto error>") #define HISTORY_INITIAL_ALLOCSIZE 300 struct TInputHistory { TCHAR* szText; size_t lLen; }; struct TSessionStats { enum { BYTES_RECEIVED = 1, BYTES_SENT = 2, FAILURE = 3, UPDATE_WITH_LAST_RCV = 4, SET_LAST_RCV = 5, INIT_TIMER = 6, }; time_t started; unsigned iSent, iReceived, iSentBytes, iReceivedBytes; unsigned messageCount; unsigned iFailures; unsigned lastReceivedChars; BOOL bWritten; }; struct CContactCache : public MZeroedObject { CContactCache() {} CContactCache(const HANDLE hContact); ~CContactCache() { releaseAlloced(); } const bool isValid() const { return(m_Valid); } const WORD getStatus() const { return(m_wStatus); } const WORD getMetaStatus() const { return(m_wMetaStatus); } const WORD getActiveStatus() const { return(m_isMeta ? m_wMetaStatus : m_wStatus); } const WORD getOldStatus() const { return(m_wOldStatus); } const TCHAR* getNick() const { return(m_szNick); } const HANDLE getContact() const { return(m_hContact); } const HANDLE getActiveContact() const { return(m_isMeta ? (m_hSubContact ? m_hSubContact : m_hContact) : m_hContact); } const DWORD getIdleTS() const { return(m_idleTS); } const char* getProto() const { return(m_szProto); } const TCHAR* getProtoT() const { return(m_tszProto); } const char* getMetaProto() const { return(m_szMetaProto ? m_szMetaProto : C_INVALID_PROTO); } const TCHAR* getMetaProtoT() const { return(m_szMetaProto ? m_tszMetaProto : C_INVALID_PROTO_T); } const char* getActiveProto() const { return(m_isMeta ? (m_szMetaProto ? m_szMetaProto : m_szProto) : m_szProto); } const TCHAR* getActiveProtoT() const { return(m_isMeta ? (m_szMetaProto ? m_tszMetaProto : m_tszProto) : m_tszProto); } bool isMeta() const { return(m_isMeta); } bool isSubContact() const { return(m_isSubcontact); } bool isFavorite() const { return(m_isFavorite); } bool isRecent() const { return(m_isRecent); } const TCHAR* getRealAccount() const { return(m_szAccount ? m_szAccount : C_INVALID_ACCOUNT); } const TCHAR* getUIN() const { return(m_szUIN); } const TCHAR* getStatusMsg() const { return(m_szStatusMsg); } const TCHAR* getXStatusMsg() const { return(m_xStatusMsg); } const TCHAR* getListeningInfo() const { return(m_ListeningInfo); } BYTE getXStatusId() const { return(m_xStatus); } const HWND getWindowData(TWindowData*& dat) const { dat = m_dat; return(m_hwnd); } const HWND getHwnd() const { return(m_hwnd); } int getMaxMessageLength(); TWindowData* getDat() const { return(m_dat); } void updateStats(int iType, size_t value = 0); const DWORD getSessionStart() const { return(m_stats->started); } const int getSessionMsgCount() const { return((int)m_stats->messageCount) ; } void updateState(); bool updateStatus(); bool updateNick(); void updateMeta(bool fForce = false); bool updateUIN(); void updateStatusMsg(const char *szKey = 0); void setWindowData(const HWND hwnd = 0, TWindowData *dat = 0); void resetMeta(); void closeWindow(); void deletedHandler(); void updateFavorite(); TCHAR* getNormalizedStatusMsg(const TCHAR *src, bool fStripAll = false); HICON getIcon(int& iSize) const; /* * input history */ void saveHistory(WPARAM wParam, LPARAM lParam); void inputHistoryEvent(WPARAM wParam); static CContactCache* getContactCache(HANDLE hContact); static void cacheUpdateMetaChanged(); private: void allocStats(); void initPhaseTwo(); void allocHistory(); void releaseAlloced(); HANDLE m_hContact; HANDLE m_hSubContact; WORD m_wStatus, m_wMetaStatus; WORD m_wOldStatus; char* m_szProto, *m_szMetaProto; TCHAR* m_tszProto, m_tszMetaProto[40]; TCHAR* m_szAccount; TCHAR m_szNick[80], m_szUIN[80]; TCHAR* m_szStatusMsg, *m_xStatusMsg, *m_ListeningInfo; BYTE m_xStatus; DWORD m_idleTS; bool m_isMeta, m_isSubcontact; bool m_Valid; bool m_isFavorite; bool m_isRecent; HWND m_hwnd; int m_nMax; int m_iHistoryCurrent, m_iHistoryTop, m_iHistorySize; TWindowData *m_dat; TSessionStats *m_stats; TInputHistory *m_history; }; #endif /* __CONTACTCACHE_H */
const { ActivityType, Events } = require('discord.js'); const CLIENT_ACTIVITY = ActivityType.Playing; module.exports = { name: Events.ClientReady, once: true, nickname: 'Client Presence', /** * @param {Client} client */ async execute(client) { // Start function const repeatingFunction = async () => { // Variables const textArray = [ `with ${client.guilds.cache.size.toLocaleString()} guilds`, `with ${client.channels.cache.size.toLocaleString()} channels`, `with ${client.guilds.cache .reduce((a, g) => a + g.memberCount, 0) .toLocaleString()} users`, `with ${client.guilds.cache .reduce((a, g) => a + g.channels.cache.size, 0) .toLocaleString()} channels`, `with ${client.guilds.cache .reduce((a, g) => a + g.roles.cache.size, 0) .toLocaleString()} roles`, `with ${client.guilds.cache .reduce((a, g) => a + g.emojis.cache.size, 0) .toLocaleString()} emojis`, `with ${client.guilds.cache .reduce((a, g) => a + g.voiceStates.cache.size, 0) .toLocaleString()} voice states`, `with ${client.guilds.cache .reduce( (a, g) => a + g.members.cache.filter((m) => m.user.bot).size, 0 ) .toLocaleString()} bots`, ]; const randomNumberOfArray = Math.floor(Math.random() * textArray.length); const clientActivityText = textArray[randomNumberOfArray]; // Set client presence client.user.setPresence({ activities: [ { name: `${clientActivityText}`, type: CLIENT_ACTIVITY, }, ], status: 'dnd', }); // Repeat function every 10 seconds setTimeout(repeatingFunction, 10000); }; // Start function repeatingFunction(); }, };
#include <coretypes/json_deserializer_impl.h> #include <coretypes/coretypes.h> #include <coretypes/json_serialized_object.h> #include <coretypes/json_serialized_list.h> #include <coretypes/updatable.h> #include <coretypes/ctutils.h> #include <rapidjson/document.h> #include <memory> BEGIN_NAMESPACE_OPENDAQ // static ErrCode JsonDeserializerImpl::DeserializeTagged(JsonValue& document, IBaseObject* context, IBaseObject** object) { using namespace rapidjson; auto jsonObject = document.GetObject(); if (jsonObject.HasMember("__type")) { if (jsonObject["__type"].IsString()) { std::string typeId = jsonObject["__type"].GetString(); daqDeserializerFactory factory; ErrCode errCode = daqGetSerializerFactory(typeId.data(), &factory); if (OPENDAQ_FAILED(errCode)) { return errCode; } SerializedObjectPtr jsonSerObj; errCode = createObject<ISerializedObject, JsonSerializedObject>(&jsonSerObj, jsonObject); if (OPENDAQ_FAILED(errCode)) { return errCode; } errCode = factory(jsonSerObj, context, object); if (OPENDAQ_FAILED(errCode)) { return errCode; } return OPENDAQ_SUCCESS; } return OPENDAQ_ERR_DESERIALIZE_UNKNOWN_TYPE; } return OPENDAQ_ERR_DESERIALIZE_NO_TYPE; } ErrCode JsonDeserializerImpl::DeserializeList(const JsonList& array, IBaseObject* context, IBaseObject** object) { IList* list; ErrCode errCode = createList(&list); if (OPENDAQ_FAILED(errCode)) { return errCode; } for (auto& element : array) { IBaseObject* elementObj; errCode = Deserialize(element, context, &elementObj); if (OPENDAQ_FAILED(errCode)) { return errCode; } errCode = list->moveBack(elementObj); if (OPENDAQ_FAILED(errCode)) { return errCode; } } *object = list; return OPENDAQ_SUCCESS; } // static ErrCode JsonDeserializerImpl::Deserialize(JsonValue& document, IBaseObject* context, IBaseObject** object) { ErrCode errCode = OPENDAQ_SUCCESS; switch (document.GetType()) { case rapidjson::kNullType: object = nullptr; break; case rapidjson::kObjectType: errCode = DeserializeTagged(document, context, object); break; case rapidjson::kStringType: { IString* list; errCode = createString(&list, document.GetString()); *object = list; break; } case rapidjson::kNumberType: if (document.IsInt()) { IInteger* integer; errCode = createInteger(&integer, document.GetInt()); *object = integer; } else if (document.IsInt64()) { IInteger* integer; errCode = createInteger(&integer, document.GetInt64()); *object = integer; } else { IFloat* floating; errCode = createFloat(&floating, document.GetDouble()); *object = floating; } break; case rapidjson::kArrayType: errCode = DeserializeList(document.GetArray(), context, object); break; case rapidjson::kFalseType: { IBoolean* boolean; errCode = createBoolean(&boolean, false); *object = boolean; break; } case rapidjson::kTrueType: { IBoolean* boolean; errCode = createBoolean(&boolean, true); *object = boolean; break; } default: *object = nullptr; return OPENDAQ_ERR_DESERIALIZE_UNKNOWN_TYPE; } return errCode; } ErrCode JsonDeserializerImpl::deserialize(IString* serialized, IBaseObject* context, IBaseObject** object) { if (serialized == nullptr) { return OPENDAQ_ERR_ARGUMENT_NULL; } SizeT length; serialized->getLength(&length); ConstCharPtr ptr; serialized->getCharPtr(&ptr); #if defined(_WIN32) constexpr size_t dataPaddingSize = 0; #else //heap-buffer-overflow in _mm_load_si128 https://github.com/Tencent/rapidjson/issues/1723 constexpr size_t dataPaddingSize = 16; #endif char* buffer = new(std::nothrow) char[length + 1 + dataPaddingSize * 2]; if (!buffer) { return OPENDAQ_ERR_NOMEMORY; } JsonDocument document; strcpy(&buffer[dataPaddingSize], ptr); if (document.ParseInsitu(&buffer[dataPaddingSize]).HasParseError()) { delete[] buffer; return OPENDAQ_ERR_DESERIALIZE_PARSE_ERROR; } ErrCode errCode = Deserialize(document, context, object); delete[] buffer; return errCode; } ErrCode JsonDeserializerImpl::update(IUpdatable* updatable, IString* serialized) { if (serialized == nullptr || updatable == nullptr) { return OPENDAQ_ERR_ARGUMENT_NULL; } SizeT length; ErrCode err = serialized->getLength(&length); if (!OPENDAQ_SUCCEEDED(err)) { return err; } ConstCharPtr ptr; err = serialized->getCharPtr(&ptr); if (!OPENDAQ_SUCCEEDED(err)) { return err; } std::unique_ptr<char[]> buffer(new(std::nothrow) char[length + 1]); if (!buffer) { return OPENDAQ_ERR_NOMEMORY; } JsonDocument document; strcpy(buffer.get(), ptr); if (document.ParseInsitu(buffer.get()).HasParseError()) { return OPENDAQ_ERR_DESERIALIZE_PARSE_ERROR; } if (document.GetType() != rapidjson::kObjectType) { return OPENDAQ_ERR_INVALIDTYPE; } SerializedObjectPtr jsonSerObj; ErrCode errCode = createObject<ISerializedObject, JsonSerializedObject>(&jsonSerObj, document.GetObject()); if (OPENDAQ_FAILED(errCode)) { return errCode; } return updatable->update(jsonSerObj); } ErrCode JsonDeserializerImpl::toString(CharPtr* str) { if (str == nullptr) { return OPENDAQ_ERR_ARGUMENT_NULL; } return daqDuplicateCharPtr("JsonDeserializer", str); } CoreType JsonDeserializerImpl::GetCoreType(const JsonValue& value) noexcept { switch (value.GetType()) { case rapidjson::kNullType: return ctObject; case rapidjson::kFalseType: case rapidjson::kTrueType: return ctBool; case rapidjson::kObjectType: return ctObject; case rapidjson::kArrayType: return ctList; case rapidjson::kStringType: return ctString; case rapidjson::kNumberType: if (value.IsInt() || value.IsInt64()) { return ctInt; } return ctFloat; default: return ctUndefined; } } // createJsonDeserializer extern "C" ErrCode PUBLIC_EXPORT createJsonDeserializer(IDeserializer** jsonDeserializer) { if (!jsonDeserializer) return OPENDAQ_ERR_ARGUMENT_NULL; IDeserializer* object = new(std::nothrow) JsonDeserializerImpl(); if (!object) return OPENDAQ_ERR_NOMEMORY; object->addRef(); *jsonDeserializer = object; return OPENDAQ_SUCCESS; } END_NAMESPACE_OPENDAQ
--- title: "Introduction to R" author: "Julien Brun" date: "June, 2016" output: html_document --- *Attribution*: this tutorial is an adaptation of the material prepared by Karthik Ram for NCEAS [summer school 2013] # Condition ## if .. else statement ```{r if else, eval = FALSE} # Structure if (cond1=true) { cmd1 } else { cmd2 } # Example x <- 5 if (x > 0) { print("positive") } else { print("negative") } # More conditions!! x <- 0 if (x > 0) { print("positive") } else if (x < 0) { print("negative") } else { print("zero") } ``` ![tips](images/tip.png) Nesting several conditions can quickly make your code hard to read and debug. Try to avoid complex and multiple nested conditions. # Loops - Repeating the same operation # For ```{r for loops, eval = FALSE} # Structure for (variable in sequence) { statements } for (x in 1:10) { print(x) } ``` Note: The `break` function is used to break out of loops, and `next` halts the processing of the current iteration and advances the looping index. ![](images/challengeproblemred_scribble.png) **Challenge**: write a script that sequentially print to the screen the squared value of the following sequence, but exit the loop if the value is larger than 140. Here is the code to generate the sequence: ```{r for loops challenge, eval = FALSE} set.seed(123) s <- rnorm(1:100, mean = 100, sd = 20) ``` # While ```{r while loops, eval = FALSE} # Structure while (condition) { statements } i <- 0 while (i < 10) { print(i) i = i + 1 # Do not forget to update your condidion } ``` ![](images/challengeproblemred_scribble.png) **Challenge**: redo the challenge using a while loop! # Learning the apply family of functions As we discuss previously R is built to work with vectors. The family of `apply` functions has been build to leverage vectorized operations that lower the explicit need of `for` loops. Note that apply functions are in fact C for loops (faster). These include: ```{r, eval = FALSE} apply lapply tapply sapply ``` ## apply `apply` applies a function to each row or column of a matrix. ```{r, eval = TRUE} m <- matrix(c(1:10, 11:20), nrow = 10, ncol = 2) m # 1 is the row index # 2 is the column index apply(m, 1, sum) apply(m, 2, sum) apply(m, 1, mean) apply(m, 2, mean) ``` ## tapply `tapply` applies a function to subsets of a vector. ```{r, eval = TRUE} df <- data.frame(names = sample(c("A","B","C"), 10, rep = T), length = rnorm(10)) df tapply(df$length, df$names, mean) ``` Now with a more familiar dataset. ```{r, eval = TRUE} tapply(iris$Petal.Length, iris$Species, mean) ``` ## lapply (and llply) What it does: Returns a list of same length as the input. Each element of the output is a result of applying a function to the corresponding element. ```{r, eval = TRUE} my_list <- list(a = 1:10, b = 2:20) my_list l <- lapply(my_list, mean) l class(l) ``` ## sapply `sapply` is a more user friendly version of `lapply` and will return a list of matrix where appropriate. Let's work with the same list we just created. ```{r, eval = TRUE} my_list x <- sapply(my_list, mean) x class(x) ``` ## replicate An extremely useful function to generate datasets for simulation purposes. ```{r, eval = TRUE} replicate(10, rnorm(10)) replicate(10, rnorm(10), simplify = TRUE) ``` The final arguments turns the result into a vector or matrix if possible. ## mapply Its more or less a multivariate version of `sapply`. It applies a function to all corresponding elements of each argument. Example: ```{r, eval = TRUE} list_1 <- list(a = c(1:10), b = c(11:20)) list_1 list_2 <- list(c = c(21:30), d = c(31:40)) list_2 mapply(sum, list_1$a, list_1$b, list_2$c, list_2$d) ```
#ifndef SENSOR_MODULE_H_ #define SENSOR_MODULE_H_ #include <Arduino.h> #include <Wire.h> #define BOARD_MODULE_DEBUG class SensorModule; // forward declaration for the update function /** * Update function that is triggered when a sensor state has changed. */ typedef void (*SensorUpdatedFunction)(); /** * Represents a physical board module. The module is split into sectors, fields and sensors. The following image shows the sector and field view. * * ┌─────────┬─────────┬─────────┬─────────┐ * │ │ │ │ │ * │ S2F2 │ S2F3 │ S3F2 │ S3F3 │ * │ │ │ │ │ * ├─────────┼─────────┼─────────┼─────────┤ * │ │ │ │ │ * │ S2F0 │ S2F1 │ S3F0 │ S3F1 │ * │ │ │ │ │ * ├─────────┼─────────┼─────────┼─────────┤ * │ │ │ │ │ * │ S0F2 │ S0F3 │ S1F2 │ S1F3 │ * │ │ │ │ │ * ├─────────┼─────────┼─────────┼─────────┤ * │ │ │ │ │ * │ S0F0 │ F0F1 │ S1F0 │ S1F1 │ * │ │ │ │ │ * └─────────┴─────────┴─────────┴─────────┘ * * Each field has 5 sensors to detect magnetic fields, one for each edge of the field and one in the upper left corner. The four * sensors at the edge have the name of cardinal directions, the last one is labeled as BOARD one. * ┌─────────────────────┐ * │ B NORTH │ * │ ███ │ * │ W E │ * │ E █ S0F0 █ A │ * │ S █ █ S │ * │ T T │ * │ ███ │ * │ SOUTH │ * └─────────────────────┘ * * Finally every field has a button assigned that can be pressed by the player to interact with the module in a mechanical way. This * sensor is labeld as button. * * Based on these information every sensor on the field can be identified by the coordinates and the sensor type, e.g. * * S0F0_NORTH * S1F3_BUTTON * ect. */ class SensorModule { public: /** * @brief the type of sensor used */ enum SensorType { BUTTON, BOARD, EDGE }; /** * Creates a new instance. * * @param i2cBus I2C bus used to control the PCA9555 instances. Since the bus maybe shared with other instances it has to be provided from outside. * @param irq the interrupt used for the complete gameboard. Used to update the internal multiplexer pin state array when a change is detected. * @param updateFunction function that is called when an sensor update was detected in the loop() function call * @param mxAddress the I2C address of the multiplexer to which this module is connected * @param mxChannel the I2C multiplexer channel to which this module is connected. */ SensorModule(TwoWire *i2cBus, uint8_t irq, uint8_t mxAddress, uint8_t mxChannel); /** * Has to be executed before the use of this class. The i2cBus.begin(...) method has to be called BEFORE this method is called, otherwise the values will * not be resolved correctly */ bool begin(); void checkIRQ(); /** * Performs an update of the internal registers of the module and triggers call backs if a change was detected. */ void update(); /** * Checks if the passed PIN is active (set to 0) for the passed multiplexer address. The readMXPins() method has to be executed before a call to this method * to have values that represent the actual state. This is usually performed when the interrupt is triggered. * * @param address the address of the multiplexer to query a pin. * @param pin the pin from 0 - 15 to query */ bool sensorActive(uint8_t address, uint8_t pin); /** * Enables or disables the sensors of the physical board modules. If a sensor is disabled no events of the corresponding type will be sent by the board * anymore. This can be used to avoid error handling for irrelevant cases. If you wait for a button event and the player shouldn't add / remove / move * something on the game board, disabling the BOARD and EDGE sensors can avoid false positives during the interaction. In addition, disabled sensors reduce * the overall processing time of the physical board module and my increase the responsiveness of the hardware. <p> The method will always set the state of * all sensors, i.e. the full expected value set (all three boolean values) have to be provided, there is no delta calculation. * * @param button if the button sensor type is enabled or not * @param board if the board sensor type is enabled or not * @param edge if the edge sensor type is enabled or not */ void enableSensors(bool button, bool board, bool edge) { _edgeEnabled = edge; _buttonEnabled = button; _boardEnabled = board; }; /** * @brief Sets the callback function for a sensor change. The callback is only triggered if the sensors are activated (default is active). * @param callback the callback to execute */ void setCallback(SensorType type, SensorUpdatedFunction callback); /** @brief Writes the sensor state of the passed type as bit encoded bytes to the destination parameter. The size depends on the type, i.e. for board and button we need 2 bytes, every module of the board has 16 sensors so that 16 bits are needed, for edge sensors 4 bytes are set (every module has 16 fields with 4 sensors) */ void writeSensorState(SensorType type, uint8_t *dest); /** * Writes the physical PIN states of the passed multiplexer address to the serial output for debugging reasons. Used when BOARD_MODULE_DEBUG is defined * @param address the address of the I2C multiplexer to write the pins */ void dumpPinStatesToSerial(uint8_t address); void dumpPinStatesToSerial(); private: /** * Holds the state of the digital multiplexer ICs. This array is initialized during initalization when the initMultiplexer() method is called and updated * whenever the readMXPins(address) method for a given adress is called. That means that without an update the ICs may have different states than the ones * represented here. * * The board has 7 multiplexers with the following addresses * * I2C_BUTTONS 0x20 * I2C_SECTOR_0 0x21 * I2C_SECTOR_1 0x22 * I2C_SECTOR_2 0x23 * I2C_SECTOR_3 0x24 * I2C_BOARD 0x25 * I2C_IRQ 0x26 * * which are stored in this array in increasing order (_mxPinStates[1] == I2C_SECTOR_0) * */ uint16_t _mxPinStates[7]; /** * The previous version of the pin states to calculate the delta between the current one and the previous one */ uint16_t _mxPinStatesPrev[7]; /** * I2C bus used to control the PCA9555 instances. Since the bus maybe shared with other instances it has to be provided from outside. */ TwoWire *_i2cBus; /** * Interrupt for the complete board module */ uint8_t _irq; /** * Address of the TCA9548 multiplexer to which the module is connected. */ uint8_t _mxAddress; /** * Channel of the TCA9548 multiplexer to which the module is connected. */ uint8_t _mxChannel; /** * if the edge sensors of the fields are enabled. */ bool _edgeEnabled = true; /** * If the button sensors of the fields are enabled. */ bool _buttonEnabled = true; /** * if the board sensors of the fields are enabled. */ bool _boardEnabled = true; /** * Function that is called when an sensor update was detected in the loop() function call for the edge sensors. If no callback function is set, the sensor * changes of these sensors are ignored. */ SensorUpdatedFunction _edgeCallback; /** * Function that is called when an sensor update was detected in the loop() function call for the board sensors. */ SensorUpdatedFunction _boardCallback; /** * Function that is called when an sensor update was detected in the loop() function call for the button sensors. */ SensorUpdatedFunction _buttonCallback; // business logic to update the internal state of the board module instance // --------------------------------------------------------------------------------------------------------------------------------- /** * Reads the state of the pins for the multiplexer with the passed address. The result is stored in the _mxPinStates array for the passed address. * * @param address the I2C address of the queried PCA9555 * * @return the current state */ uint16_t readMXPins(uint8_t address); // low level interactions with the digital multiplexer // --------------------------------------------------------------------------------------------------------------------------------- /** * Performs the initialization of the multiplexer with the given address. During the initialization the I2C connection is tested and the configuration * register of the multiplexer is set to INPUT only. This method is called for all used multiplexers of the board. * * @param address the multiplexer address */ bool initMultiplexer(uint8_t address); /** * Write the value given to the register set to selected chip. * * @param address Address of I2C chip * @param reg register to write to * @param value value to write to register * */ bool writeRegister(uint8_t address, uint8_t reg, uint8_t value); /** * Reads the data from addressed chip at selected register. * If the value is above 255, an error is set. * error codes : 256 = either 0 or more than one byte is received from the chip * * @param address Address of I2C chip * @param reg Register to read from * @return data in register */ uint16_t readRegister(uint8_t address, uint8_t reg); /** * Configures the TCA9548 to connect to the I2C bus of this module */ void enableMXChannel(); }; #endif
package com.podProject.model; import jakarta.persistence.*; import lombok.Data; import lombok.NoArgsConstructor; import org.springframework.stereotype.Component; @Entity @Data @Component @NoArgsConstructor public class ComputerCase { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long caseId; @Column(unique = true) private String name; private String type; private String colour; private String powerSupply; private String sidePanel; private String externalVolume; private int internal35Bays; private double price; public ComputerCase(String name, String type, String colour, String powerSupply, String sidePanel, String externalVolume, int internal35Bays, double price) { this.name = name; this.type = type; this.colour = colour; this.powerSupply = powerSupply; this.sidePanel = sidePanel; this.externalVolume = externalVolume; this.internal35Bays = internal35Bays; this.price = price; } public long getCaseId() { return caseId; } public void setCaseId(long caseId) { this.caseId = caseId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getColour() { return colour; } public void setColour(String colour) { this.colour = colour; } public String getPowerSupply() { return powerSupply; } public void setPowerSupply(String powerSupply) { this.powerSupply = powerSupply; } public String getSidePanel() { return sidePanel; } public void setSidePanel(String sidePanel) { this.sidePanel = sidePanel; } public String getExternalVolume() { return externalVolume; } public void setExternalVolume(String externalVolume) { this.externalVolume = externalVolume; } public int getInternal35Bays() { return internal35Bays; } public void setInternal35Bays(int internal35Bays) { this.internal35Bays = internal35Bays; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } @Override public String toString() { return "ComputerCase{" + "caseId=" + caseId + ", name='" + name + '\'' + ", type='" + type + '\'' + ", colour='" + colour + '\'' + ", powerSupply='" + powerSupply + '\'' + ", sidePanel='" + sidePanel + '\'' + ", externalVolume='" + externalVolume + '\'' + ", internal35Bays=" + internal35Bays + ", price=" + price + '}'; } }
<%@page import="java.util.ArrayList"%> <%@page import="entity.Item"%> <%@page import="entity.Cart"%> <%@page contentType="text/html" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>L-BEAUTY!</title> <link rel="stylesheet" href="css/home-style.css"> <%@include file="part/icon.html" %> <link href="https://fonts.googleapis.com/css?family=Alegreya+SC|Amatic+SC|Bahianita|Bubblegum+Sans|Fredericka+the+Great|Handlee|Love+Ya+Like+A+Sister|Luckiest+Guy|Nothing+You+Could+Do|Open+Sans+Condensed:300|Permanent+Marker|Shadows+Into+Light|Zilla+Slab&display=swap" rel="stylesheet"> <link href="https://fonts.googleapis.com/css?family=Dosis&display=swap" rel="stylesheet"> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.0/css/all.css" integrity="sha384-lZN37f5QGtY3VHgisS14W3ExzMWZxybE1SJSEsQp9S+oqd12jhcu+A56Ebc1zFSJ" crossorigin="anonymous"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha256-pasqAKBDmFT4eHoN2ndd6lN370kFiGUFyTiUHWhU7k8=" crossorigin="anonymous"></script> <script> $(function () { $(".toggle").on("click", function () { if ($(".item").hasClass("active")) { $(".item").removeClass("active"); } else { $(".item").addClass("active"); } }); }); </script> </head> <body> <header> <nav> <ul class="menu"> <li class="logo"><a href="index.jsp"><img src="img/logo.png" alt=""></a></li> <li class="item"><a href="index.jsp">Home</a></li> <li class="item"><a href="discovery.jsp">Discovery</a></li> <li class="item"><a href="findus.jsp">Find us</a></li> <li class="item"><a href="getMerch">Shop</a></li> <% if (session.getAttribute("visitor") == null) { %> <li class="item button"><a href="login.jsp">Log In</a></li> <li class="item button secondary"><a href="signup.jsp">Sign Up</a></li> <li class="item cart"><a href="" onclick="noticeLogin()"><i class="fas fa-shopping-cart"></i></a></li> <% } else { Object obj = session.getAttribute("cart"); int noOfItems = 0; if (obj != null) { Cart cart = (Cart) obj; ArrayList<Item> list = (ArrayList<Item>) cart.getItems(); noOfItems = list.size(); } %> <li class="item" id="user"><a href=""><i class="fas fa-user"></i> ${sessionScope.visitor.username}</a></li> <li class="item button secondary"><a href="logout">Log Out</a></li> <li class="item cart"><a href="cart.jsp"><i class="fas fa-shopping-cart"></i>(<%=noOfItems%>)</a></li> <% } %> <li class="toggle"><span class="bars"></span></li> </ul> </nav> </header> <!-- HEADER --> <div class="wrapper"> <div id="quote"> <p>" Since love grows within you, so beauty grows. For love is the beauty of the soul. "</p> <p>Saint Augustine</p> </div> <header class="text-center text-white d-flex"> <div class="container my-auto"> <div class="row"> <div class="col-lg-12 my-auto"> <h1 class="text-uppercase faded" id="tek"> <strong> <p id="wt">WELCOME TO</p> <p id="highlight">L-BEAUTY</p> </strong> </h1> <hr> </div> <div class="col-lg-12 my-auto" id="sns"> <a href="https://www.facebook.com/ngoclann22/" target="blank"><i class="fab fa-facebook"></i></a> <a href="https://www.instagram.com/meow_bubble/" target="blank"><i class="fab fa-instagram"></i></a> <a href="https://twitter.com/TriLy9" target="blank"><i class="fab fa-twitter" ></i></a> <a href="https://www.youtube.com/channel/UC6gp1ymmcB2MVZGLuXy_VEQ" target="blank"><i class="fab fa-youtube"></i></a> </div> </div> </div> </header> </div> <%@include file="part/footer.html" %> <script> function noticeLogin() { alert("You need to login first!"); } </script> </body> </html>
import { ServerError } from '@/application/errors' import { adaptMulter } from '@/main/adapters' import { NextFunction, Request, RequestHandler, Response } from 'express' import { getMockReq, getMockRes } from '@jest-mock/express' import multer from 'multer' jest.mock('multer') describe('adaptMulter', () => { let req: Request let res: Response let next: NextFunction let fakeMulter: jest.Mocked<typeof multer> let multerSpy: jest.Mock let singleSpy: jest.Mock let uploadSpy: jest.Mock let sut: RequestHandler beforeAll(() => { req = getMockReq() res = getMockRes().res next = getMockRes().next fakeMulter = multer as jest.Mocked<typeof multer> uploadSpy = jest.fn().mockImplementation((req, res, next) => { req.file = { buffer: Buffer.from('any_buffer'), mimetype: 'any_type', originalname: 'any_name' } next() }) singleSpy = jest.fn().mockImplementation(() => uploadSpy) multerSpy = jest.fn().mockImplementation(() => ({ single: singleSpy })) jest.mocked(fakeMulter).mockImplementation(multerSpy) }) beforeEach(() => { req = getMockReq({ locals: { anyLocals: 'any_locals' } }) sut = adaptMulter }) it('should call single upload with correct input', async () => { sut(req, res, next) expect(multerSpy).toHaveBeenCalledTimes(1) expect(multerSpy).toHaveBeenCalledWith() expect(singleSpy).toHaveBeenCalledTimes(1) expect(singleSpy).toHaveBeenCalledWith('file') expect(uploadSpy).toHaveBeenCalledTimes(1) expect(uploadSpy).toHaveBeenCalledWith(req, res, expect.any(Function)) }) it('should return 500 if upload fails', async () => { const error = new Error('multer_error') uploadSpy.mockImplementationOnce((req, res, next) => { next(error) }) sut(req, res, next) expect(res.status).toHaveBeenCalledTimes(1) expect(res.status).toHaveBeenCalledWith(500) expect(res.json).toHaveBeenCalledTimes(1) expect(res.json).toHaveBeenCalledWith({ error: new ServerError(error).message }) }) it('should not add file to req.locals', async () => { uploadSpy.mockImplementationOnce((req, res, next) => { next() }) sut(req, res, next) expect(req.locals).toEqual({ anyLocals: 'any_locals' }) }) it('should add file to req.locals', async () => { sut(req, res, next) expect(req.locals).toEqual({ anyLocals: 'any_locals', file: { buffer: Buffer.from('any_buffer'), mimeType: req.file?.mimetype, fileName: req.file?.originalname } }) }) it('should call next on success', async () => { sut(req, res, next) expect(next).toHaveBeenCalledTimes(1) expect(next).toHaveBeenCalledWith() }) })
package com.IvanChikanov.BloxCons.Controllers; import com.IvanChikanov.BloxCons.Other.JsType; import com.IvanChikanov.BloxCons.Services.ModuleService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import java.io.IOException; import java.util.List; @Controller @RequestMapping("/js") public class ModuleController { @Autowired private ModuleService moduleService; @GetMapping("/get/{module_id}") public ResponseEntity<byte[]> getJS(@PathVariable Long module_id) throws IOException { byte[] created = moduleService.createFile(JsType.FULL, module_id); return ResponseEntity.ok().headers(getJsHeaders(created.length)).body(created); } @GetMapping("/list") @ResponseBody public List<String[]> get() { List<String[]> m = moduleService.getModuleList(); return m; } @GetMapping("/delete/{id}") public ResponseEntity<String> deleteModule(@PathVariable Long id) { moduleService.DeleteModule(id); return ResponseEntity.ok().build(); } @GetMapping("/get_other_script/{id}") public ResponseEntity<byte[]> loadResourceJsOther(@PathVariable Long id) throws IOException { byte[] other = moduleService.createOtherFile(id); return ResponseEntity.ok().headers(getJsHeaders(other.length)).body(other); } @PostMapping("/update_other_dependencies") public ResponseEntity<String> updateOthers(@RequestParam("otherIds") Long[] ids, @RequestParam("moduleId") Long moduleId) { try { moduleService.UpdateOtherModulesSet(ids, moduleId); return ResponseEntity.ok("ok"); } catch (Exception ex) { return ResponseEntity.ok(ex.getMessage()); } } private HttpHeaders getJsHeaders(int length) { HttpHeaders headers = new HttpHeaders(); headers.setContentLength(length); headers.setContentType(MediaType.parseMediaType("application/javascript")); return headers; } }
// // DoorClass.swift // StealthProject // // Created by Antonio Romano on 13/05/22. // import Foundation import SpriteKit class Door: SKSpriteNode{ private var isOpen: Bool = false private var closedTexture: SKTexture = SKTexture() private var openTexture: SKTexture = SKTexture() private var openNormalTexture: SKTexture = SKTexture() private var doorPlacement: DoorPlacement = .UP required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } init(_ placement: DoorPlacement, isOpen: Bool, floor: FloorType){ if isOpen == false{ super.init(texture: closedTexture, color: .clear, size: CGSize(width: blocco, height: blocco)) self.doorPlacement = placement setTexture(placement, floor: floor) self.isOpen = false self.run(.setTexture(closedTexture)) }else{ super.init(texture: openTexture, color: .clear, size: CGSize(width: blocco, height: blocco)) self.doorPlacement = placement setTexture(placement, floor: floor) self.isOpen = true self.run(.setTexture(openTexture)) } self.name = "door" self.physicsBody?.categoryBitMask = ColliderType.DOOR.rawValue self.physicsBody?.collisionBitMask = ColliderType.PLAYER.rawValue self.physicsBody?.contactTestBitMask = ColliderType.PLAYER.rawValue } private func setTexture(_ placement: DoorPlacement, floor: FloorType){ if floor == .SECOND_FLOOE || floor == .LAST_FLOOR{ switch placement { case .UP, .DOWN: closedTexture = SKTexture(imageNamed: "doorClosed") openTexture = SKTexture(imageNamed: "doorOpen") case .LEFT: closedTexture = SKTexture(imageNamed: "doorLeft") openTexture = SKTexture(imageNamed: "doorOpenLeft") case .RIGHT: closedTexture = SKTexture(imageNamed: "doorRight") openTexture = SKTexture(imageNamed: "doorOpenRight") } }else{ switch placement { case .UP, .DOWN: closedTexture = SKTexture(imageNamed: "portaEsternaChiusa") openTexture = SKTexture(imageNamed: "portaEsternaAperta") self.normalTexture = SKTexture(imageNamed: "portaEsternaChiusaNormalMap") openNormalTexture = SKTexture(imageNamed: "portaEsternaApertaNormalMap") case .LEFT: closedTexture = SKTexture(imageNamed: "portaEsternaLateraleChiusaSx") openTexture = SKTexture(imageNamed: "portaEsternaLateraleApertaSx") case .RIGHT: closedTexture = SKTexture(imageNamed: "portaEsternaLateraleChiusaDx") openTexture = SKTexture(imageNamed: "portaEsternaLateraleApertaDx") } } } func getOpenStaus()->Bool{ return self.isOpen } func open(){ self.isOpen = true self.run(.setTexture(openTexture)) self.normalTexture = openNormalTexture self.physicsBody = SKPhysicsBody() self.physicsBody?.affectedByGravity = false self.physicsBody?.isDynamic = false self.physicsBody?.allowsRotation = false } }
use reqwest::Url; use serde::Deserialize; use crate::engines::{EngineResponse, EngineSearchResult, RequestResponse, CLIENT}; pub fn request(query: &str) -> RequestResponse { CLIENT .get( Url::parse_with_params( "https://api.yep.com/fs/2/search", &[ ("client", "web"), ("gl", "all"), ("no_correct", "true"), ("q", query), ("safeSearch", "off"), ("type", "web"), ], ) .unwrap(), ) .into() } #[derive(Deserialize, Debug)] struct YepApiResponse { pub results: Vec<YepApiResponseResult>, } #[derive(Deserialize, Debug)] struct YepApiResponseResult { pub url: String, pub title: String, pub snippet: String, } pub fn parse_response(body: &str) -> eyre::Result<EngineResponse> { let (code, response): (String, YepApiResponse) = serde_json::from_str(body)?; if &code != "Ok" { return Ok(EngineResponse::new()); } let search_results = response .results .into_iter() .map(|result| { let description_html = scraper::Html::parse_document(&result.snippet); let description = description_html.root_element().text().collect(); EngineSearchResult { url: result.url, title: result.title, description, } }) .collect(); Ok(EngineResponse { search_results, featured_snippet: None, answer_html: None, infobox_html: None, }) }
<style lang="scss"> .tree-select { position: relative; display: inline-block; .el-input { cursor: pointer; } .el-autocomplete-suggestion { position: absolute; z-index: 2003; background-color: #fff; } &__wrap { max-height: 260px; overflow: auto; padding: 6px 0; box-sizing: border-box; background-color: #fff; .el-tree { border: none; } } &__btns { background-color: #fbfdff; border-top: 1px solid #e4e4e4; margin-top: 0; padding: 0 10px; height: 38px; line-height: 36px; } &__btns .el-color-dropdown__btn { background-color: #fff; } } .el-color-dropdown__link-btn, .el-color-dropdown__link-btn:focus { outline: none; } </style> <script> import Popper from 'element-ui/src/utils/vue-popper' import Clickoutside from 'element-ui/src/utils/clickoutside' import Emitter from 'element-ui/src/mixins/emitter' import TreeSelectBtns from './tree-select-btns.vue' export default { name: 'TreeSelect', componentName: 'TreeSelect', mixins: [Popper, Emitter], components: { TreeSelectBtns }, directives: { Clickoutside }, props: { tree: { // 树组件参数 type: Object, default() { return {} } }, input: { // 输入框组件参数 type: Object, default() { return {} } }, value: [Array, String, Number], // 默认选中树的key,需要配合tree设置 node-key formatter: { // 输入框显示文字格式函数 type: Function, default(nodes) { return nodes.map(node => { return node.text }).join(', ') } }, multiple: { // 是否允许多选 type: Boolean, default: true } }, data() { return { isShowPopper: false, inputValue: '', checked: [], dropdownWidth: '', count: 0, checkedCount: 0, tips: '已选 0 条数据' } }, methods: { updateCount() { // 更新合计 let count = 0 if(this.$refs.tree) { const id = this.tree['node-key'] || 'id', nodes = this.$refs.tree.getCheckedNodes() count = nodes.map(n => { return n[id] }).length } this.checkedCount = count this.tips = `已选 ${count} 条数据` }, handleInputFocus() { this.isShowPopper = true }, close() { this.isShowPopper = false }, handleChange(isSilent) { if(this.$refs.tree) { const id = (this.tree.props && this.tree.props['node-key']) || this.tree['node-key'] || 'id', nodes = this.$refs.tree.getCheckedNodes() if(!isSilent) { if(this.multiple) { const keys = nodes.map(n => { return n[id] }) this.$emit('input', keys) this.$emit('change', nodes) } else { this.$emit('input', nodes[0] ? nodes[0][id] : '') this.$emit('change', nodes[0] || null) } } else { this.$refs.tree.setCheckedKeys(this.value, true) } this.inputValue = this.formatter(nodes) this.checked = nodes this.updateCount() } }, handleCurrentChange(data, isCheck) { if(!this.multiple) { if(isCheck) { this.clearChecked() this.$refs.tree.setCheckedKeys([data[this.tree['node-key'] || 'id']]) } } this.handleConfirm() }, handleConfirm() { this.handleChange() // this.close() }, clearChecked() { if(this.$refs.tree) { this.$refs.tree.setCheckedKeys([]) } } }, updated() { this.dropdownWidth = this.$refs.input.$refs.input.offsetWidth this.handleChange(true) }, render(h) { return h('div', { 'class': 'tree-select', directives: [{ name: 'clickoutside', value: this.close }] }, [ h('el-input', { props: { icon: 'caret-bottom', ...this.input, value: this.tips, readonly: true, 'on-icon-click': this.handleInputFocus }, ref: 'input', on: { focus: this.handleInputFocus } }), h('transition', { props: { name: 'el-zoom-in-top' } }, [ h('div', { 'class': 'el-autocomplete-suggestion', directives: [{ name: 'show', value: this.isShowPopper }], style: { width: this.dropdownWidth + 'px' } }, [ h('el-scrollbar', { props: { tag: 'div', 'wrap-class': 'tree-select__wrap' } }, [ h('el-tree', { props: { 'check-strictly': !this.multiple, ...this.tree, 'default-checked-keys': Array.isArray(this.value) ? this.value : [this.value] }, on: { 'check-change': this.handleCurrentChange }, ref: 'tree' }) ]), h('tree-select-btns') ]) ]) ]) }, created() { // this.$on('confirm', this.handleConfirm) this.$on('clear', this.clearChecked) } } </script>
package uvg.edu.gt; import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Represents a graph using an adjacency matrix. */ public class Graph { private static final int NO_EDGE = 0; private final int[][] adjacencyMatrix; private final int numVertices; private FloydAlgorithm floyd; private Map<String, Integer> cityToVertexId; private Map<Integer, String> vertexIdToCity; /** * Initializes the graph with a specified number of vertices. * * @param numVertices the number of vertices in the graph */ public Graph(int numVertices) { this.numVertices = numVertices; this.cityToVertexId = new HashMap<>(); this.vertexIdToCity = new HashMap<>(); adjacencyMatrix = new int[numVertices][numVertices]; for (int i = 0; i < numVertices; i++) { for (int j = 0; j < numVertices; j++) { adjacencyMatrix[i][j] = NO_EDGE; } } floyd = new FloydAlgorithm(numVertices); } /** * Adds an edge to the graph with a specified weight. * * @param source the source vertex * @param destination the destination vertex * @param weight the weight of the edge */ public void addEdge(int source, int destination, int weight) { validateVertex(source); validateVertex(destination); adjacencyMatrix[source][destination] = weight; floyd.addEdge(source, destination, weight); floyd.floydWarshall(); } /** * Adds an edge to the graph with a specified weight by city names. * * @param city1 the source city * @param city2 the destination city * @param weight the weight of the edge */ public void addEdge(String city1, String city2, int weight) { int source = cityToVertexId.get(city1); int destination = cityToVertexId.get(city2); addEdge(source, destination, weight); } /** * Removes an edge from the graph. * * @param source the source vertex * @param destination the destination vertex */ public void removeEdge(int source, int destination) { validateVertex(source); validateVertex(destination); adjacencyMatrix[source][destination] = NO_EDGE; floyd.addEdge(source, destination, Integer.MAX_VALUE); // Effectively removing the edge floyd.floydWarshall(); } /** * Removes an edge from the graph by city names. * * @param city1 the source city * @param city2 the destination city */ public void removeEdge(String city1, String city2) { int source = cityToVertexId.get(city1); int destination = cityToVertexId.get(city2); removeEdge(source, destination); } /** * Prints the adjacency matrix of the graph. */ public void printGraph() { for (int i = 0; i < numVertices; i++) { for (int j = 0; j < numVertices; j++) { System.out.print(adjacencyMatrix[i][j] + " "); } System.out.println(); } } /** * Returns the adjacency matrix of the graph. * * @return the adjacency matrix */ public int[][] getAdjacencyMatrix() { return adjacencyMatrix; } /** * Returns the number of vertices in the graph. * * @return the number of vertices */ public int getNumVertices() { return numVertices; } private void validateVertex(int v) { if (v < 0 || v >= numVertices) { throw new IllegalArgumentException("Vertex index out of bounds: " + v); } } public void initializeGraphFromFile(String filePath) throws IOException { FileParser fileParser = new FileParser(filePath); List<FileParser.Route> routes = fileParser.parse(); int vertexCount = 0; for (FileParser.Route route : routes) { if (!cityToVertexId.containsKey(route.getCity1())) { cityToVertexId.put(route.getCity1(), vertexCount); vertexIdToCity.put(vertexCount, route.getCity1()); vertexCount++; } if (!cityToVertexId.containsKey(route.getCity2())) { cityToVertexId.put(route.getCity2(), vertexCount); vertexIdToCity.put(vertexCount, route.getCity2()); vertexCount++; } } for (FileParser.Route route : routes) { int from = cityToVertexId.get(route.getCity1()); int to = cityToVertexId.get(route.getCity2()); addEdge(from, to, route.getDistance()); } } public double getShortestPathDistance(String from, String to) { int fromId = cityToVertexId.get(from); int toId = cityToVertexId.get(to); return floyd.getDistance(fromId, toId); } public List<Integer> getShortestPath(String from, String to) { int fromId = cityToVertexId.get(from); int toId = cityToVertexId.get(to); return floyd.getPath(fromId, toId); } public String getGraphCenter() { int centerId = GraphCenter.findGraphCenter(floyd); return vertexIdToCity.get(centerId); } public Map<Integer, String> getVertexIdToCity() { return vertexIdToCity; } }
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xml:lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <meta http-equiv="description" content="README for cllib"/> <meta http-equiv="keywords" content="free software, open-source software, Common Lisp, http, ftp"/> <base href="http://clocc.hg.sourceforge.net/hgweb/clocc/clocc/raw-file/tip/"/> <link rev="made" href="mailto:sds@gnu.org"/> <title>README</title> </head> <body> <h1>README for CLLIB</h1> <p>This is a library of various tools, written in <a href="http://www.lisp.org">Common Lisp</a>.</p> <p>You can download this package from the following HTTP mirrors:</p> <ul> <li><a href="http://clocc.sf.net/dist/cllib.zip">sourceforge</a></li> <li><a href="http://sds.podval.org/data/cllib.zip">podval.org</a></li> </ul> <p>To use this package, you will need an <a href="http://www.lisp.org/HyperSpec/FrontMatter/">ANSI</a> <a href="http://www.lisp.org/table/systems.htm">Common Lisp</a> as well as my cross-implementation portability package <a href="port.html"><code>PORT</code></a>.</p> <h2><a href="http://clocc.sourceforge.net">CLOCC</a></h2> <p><code>CLLIB</code> is now a part of <code>CLOCC</code> (in <a href="src/cllib/"><code>src/cllib</code></a>), and, as such, is accessible via anonymous CVS and FTP, as explained on the <code>CLOCC</code> homepage. <code>CLLIB</code> can be compiled using <a href="src/defsystem-3.x/defsystem.lisp"><code>mk:defsystem</code></a>, which is a part of <code>CLOCC</code>, and it relies on <a href="src/port/"><code>src/port</code></a>, (<a href="http://clocc.sf.net/dist/port.zip">download</a>) which was actually a part of <code>CLLIB</code> before.</p> <h2>Files</h2> <p>This Common Lisp sources include the following files (in the alphabetical order):</p> <table border="2" cellpadding="2"> <tr><th>file</th><th>description</th></tr> <tr><th align="left"><a href="src/cllib/animals.lisp"><code>animals.lisp</code></a></th> <td align="left">"guess the animal" game; simple neural net</td></tr> <tr><th align="left"><a href="src/cllib/autoload.lisp"><code>autoload.lisp</code></a></th> <td align="left"><code>autoload</code> function and snarfing autoloads from other files</td></tr> <tr><th align="left"><a href="src/cllib/base.lisp"><code>base.lisp</code></a></th> <td align="left">basic definitions: package and path</td></tr> <tr><th align="left"><a href="src/cllib/base64.lisp"><code>base64.lisp</code></a></th> <td align="left">base64 encoding and decoding</td></tr> <tr><th align="left"><a href="src/cllib/card.lisp"><code>card.lisp</code></a></th> <td align="left">Rolodex: <a href="http://bbdb.sourceforge.net">BBDB</a>/<a href="http://www.cis.ohio-state.edu/htbin/rfc/rfc2426.html">vCard</a> handling</td></tr> <tr><th align="left"><a href="src/cllib/check.lisp"><code>check.lisp</code></a></th> <td align="left">check values and types of the elements of a list</td></tr> <tr><th align="left"><a href="src/cllib/clhs.lisp"><code>clhs.lisp</code></a></th> <td align="left"><a href="http://www.lisp.org/HyperSpec/FrontMatter/" >Common Lisp HyperSpec</a> access</td></tr> <tr><th align="left"><a href="src/cllib/closio.lisp"><code>closio.lisp</code></a></th> <td align="left">read/write CLOS objects</td></tr> <tr><th align="left"><a href="src/cllib/csv.lisp"><code>csv.lisp</code></a></th> <td align="left">read/write comma-separated values</td></tr> <tr><th align="left"><a href="src/cllib/cvs.lisp"><code>cvs.lisp</code></a></th> <td align="left">CVS diff and log parsing</td></tr> <tr><th align="left"><a href="src/cllib/data.lisp"><code>data.lisp</code></a></th> <td align="left">data analysis and visualization</td></tr> <tr><th align="left"><a href="src/cllib/date.lisp"><code>date.lisp</code></a></th> <td align="left">date/time</td></tr> <tr><th align="left"><a href="src/cllib/datedl.lisp"><code>datedl.lisp</code></a></th> <td align="left">dated lists</td></tr> <tr><th align="left"><a href="src/cllib/doall.lisp"><code>doall.lisp</code></a></th> <td align="left">answer questions automatically; requires <a href="src/tools/metering/metering.lisp"><code>metering.lisp</code></a></td></tr> <tr><th align="left"><a href="src/cllib/elisp.lisp"><code>elisp.lisp</code></a></th> <td align="left">Load <a href="http://www.cs.indiana.edu/elisp/elisp-intro.html">Emacs-Lisp</a> code into Common Lisp</td></tr> <tr><th align="left"><a href="src/cllib/fileio.lisp"><code>fileio.lisp</code></a></th> <td align="left">read/write lists etc</td></tr> <tr><th align="left"><a href="src/cllib/fin.lisp"><code>fin.lisp</code></a></th> <td align="left">Financial functions: mortgage calculations, Luhn algorithm, Black-Scholes, Solow</td></tr> <tr><th align="left"><a href="src/cllib/geo.lisp"><code>geo.lisp</code></a></th> <td align="left">geography, weather, etc</td></tr> <tr><th align="left"><a href="src/cllib/getopt.lisp"><code>getopt.lisp</code></a></th> <td align="left">command line option processing - for Lisp scripting</td></tr> <tr><th align="left"><a href="src/cllib/gnuplot.lisp"><code>gnuplot.lisp</code></a></th> <td align="left"><a href="http://www.gnuplot.info/">Gnuplot</a> interface</td></tr> <tr><th align="left"><a href="src/cllib/gq.lisp"><code>gq.lisp</code></a></th> <td align="left">GetQuote - stock quotes over the Internet.</td></tr> <tr><th align="left"><a href="src/cllib/grepfin.lisp"><code>grepfin.lisp</code></a></th> <td align="left">query the financial data from <a href="http://www.mffais.com/">MFFAIS</a> and <a href="http://finviz.com/">FINVIZ</a>; this requires that <code>MOP</code> supports <code>DEFSTRUCT</code> thus will not work in, e.g., <code>sbcl</code></td></tr> <tr><th align="left"><a href="src/cllib/h2lisp.lisp"><code>h2lisp.lisp</code></a></th> <td align="left">parsing C headers</td></tr> <tr><th align="left"><a href="src/cllib/html.lisp"><code>html.lisp</code></a></th> <td align="left">HTML parsing via <code>text-stream</code></td></tr> <tr><th align="left"><a href="src/cllib/htmlgen.lisp"><code>htmlgen.lisp</code></a></th> <td align="left">HTML generation</td></tr> <tr><th align="left"><a href="src/cllib/inspect.lisp"><code>inspect.lisp</code></a></th> <td align="left">portable inspector (2 frontends: TTY and an HTML broser)</td></tr> <tr><th align="left"><a href="src/cllib/iter.lisp"><code>iter.lisp</code></a></th> <td align="left">iterate across multidimensional arrays</td></tr> <tr><th align="left"><a href="src/cllib/laser.lisp"><code>laser.lisp</code></a></th> <td align="left">print a hardcopy</td></tr> <tr><th align="left"><a href="src/cllib/lift.lisp"><code>lift.lisp</code></a></th> <td align="left">lift (ROC) curve analysis</td></tr> <tr><th align="left"><a href="src/cllib/list.lisp"><code>list.lisp</code></a></th> <td align="left">list utilities</td></tr> <tr><th align="left"><a href="src/cllib/log.lisp"><code>log.lisp</code></a></th> <td align="left">time elapsed, messages etc</td></tr> <tr><th align="left"><a href="src/cllib/math.lisp"><code>math.lisp</code></a></th> <td align="left">arithmetics, permutations, statistics, geometry and more</td></tr> <tr><th align="left"><a href="src/cllib/matrix.lisp"><code>matrix.lisp</code></a></th> <td align="left">matrix operations (solving linear equations, inversion)</td></tr> <tr><th align="left"><a href="src/cllib/miscprint.lisp"><code>miscprint.lisp</code></a></th> <td align="left">print hash tables, packages, characters etc</td></tr> <tr><th align="left"><a href="src/cllib/munkres.lisp"><code>munkres.lisp</code></a></th> <td align="left">Munkres' Assignment Algorithm (AKA "Hungarian Algorithm")</td></tr> <tr><th align="left"><a href="src/cllib/bayes.lisp"><code>bayes.lisp</code></a></th> <td align="left">Naive Bayesian classifier</td></tr> <tr><th align="left"><a href="src/cllib/ocaml.lisp"><code>ocaml.lisp</code></a></th> <td align="left">Read <a href="https://github.com/janestreet/sexplib">ocaml sexp</a> files</td></tr> <tr><th align="left"><a href="src/cllib/octave.lisp"><code>octave.lisp</code></a></th> <td align="left">interact with <a href="http://www.octave.org/">octave</a> - the GNU MatLab</td></tr> <tr><th align="left"><a href="src/cllib/prompt.lisp"><code>prompt.lisp</code></a></th> <td align="left">fontify the prompt in an xterm</td></tr> <tr><th align="left"><a href="src/cllib/rng.lisp"><code>rng.lisp</code></a></th> <td align="left">Random Number Generator (by <a href="http://www.mindspring.com/~rtoy">Raymond Toy</a>) for various non-trivial distributions</td></tr> <tr><th align="left"><a href="src/cllib/rpm.lisp"><code>rpm.lisp</code></a></th> <td align="left">RPM handling (download etc) - a better <a href="http://www.tuxedo.org/~esr/software.html">rpmwatcher</a></td></tr> <tr><th align="left"><a href="src/cllib/server.lisp"><code>server.lisp</code></a></th> <td align="left">REPL over a socket</td></tr> <tr><th align="left"><a href="src/cllib/simple.lisp"><code>simple.lisp</code></a></th> <td align="left"><code>with-collect</code> and some simple stuff</td></tr> <tr><th align="left"><a href="src/cllib/sorted.lisp"><code>sorted.lisp</code></a></th> <td align="left">operate on sorted lists (map, reduce etc)</td></tr> <tr><th align="left"><a href="src/cllib/stat.lisp"><code>stat.lisp</code></a></th> <td align="left">multidimensional statistics - requires</td></tr> <tr><th align="left"><a href="src/cllib/string.lisp"><code>string.lisp</code></a></th> <td align="left">string splitting</td></tr> <tr><th align="left"><a href="src/cllib/symb.lisp"><code>symb.lisp</code></a></th> <td align="left">symbol concatenation</td></tr> <tr><th align="left"><a href="src/cllib/tests.lisp"><code>tests.lisp</code></a></th> <td align="left">regression testing (internal)</td></tr> <tr><th align="left"><a href="src/cllib/tilsla.lisp"><code>tilsla.lisp</code></a></th> <td align="left"><code>comma</code> and friends for <code>format ~//</code></td></tr> <tr><th align="left"><a href="src/cllib/url.lisp"><code>url.lisp</code></a></th> <td align="left">HTTP/FTP/URL etc</td></tr> <tr><th align="left"><a href="src/cllib/withtype.lisp"><code>withtype.lisp</code></a></th> <td align="left">various utilities not fitting anywhere else</td></tr> <tr><th align="left"><a href="src/cllib/xml.lisp"><code>xml.lisp</code></a></th> <td align="left"><a href="http://www.w3.org/XML/">XML</a> parsing</td></tr> </table> <h2>License</h2> <p>This package is distributed under the <a href="http://www.gnu.org/copyleft/gpl.html">GNU GPL</a>.</p> <p>If you must use the code in a proprietary environment (i.e., you would like to distribute without sources something based on this library), please <a href="mailto:sds@gnu.org?subject=CLLIB/GPL">contact me</a> and I am sure we will be able to find some agreeable terms.</p> <h2>Compiling</h2> <p>To use the library, type <code>"make system"</code>, which should compile all the files. Alternatively, you can issue the <code>(mk:compile-system "cllib")</code> command yourself. This will create and compile the <code>"auto.lisp"</code> file with all the autoloads. Then you can dump your images.</p> <p>See also the general <a href="http://clocc.sourceforge.net">CLOCC</a> <a href="INSTALL"><code>INSTALL</code></a> instructions.</p> <p>This library depends on <a href="src/port/"><code>port</code></a> and <a href="src/tools/metering/metering.lisp"><code>metering</code></a>. These packages will be compiled by <code>"make system"</code>.</p> <p>Please note that this package exports symbols with names which might be already present as an extension in your Common Lisp implementation. I recommend issuing the following command before using this package:</p> <pre> #+clisp (shadowing-import '(cllib::read-from-file cllib::browse-url cllib::*browsers* cllib::*browser* cllib::with-collect cllib::! cllib::erf cllib::with-html-output cllib::with-http-output cllib::*inspect-frontend* cllib::*inspect-browser* cllib::*inspect-print-lines* cllib::*inspect-print-level* cllib::*inspect-print-length* cllib::*inspect-length*)) </pre> <h2>Comments</h2> <p><a href="mailto:clocc-list@lists.sourceforge.net">Comments</a> and <a href="https://sourceforge.net/bugs/?func=addbug&amp;group_id=1802">bug reports</a> are welcome.</p> <p><br/><br/></p><hr/> <table width="100%"><tr><td align="left"> <a href="http://sds.podval.org/">Sam Steingold</a><address> <a href="mailto:sds@gnu.org?subject=CLLIB">&lt;sds@gnu.org&gt;</a></address> </td><td align="right"><a href="http://validator.w3.org/check/referer"><img src="http://www.w3.org/Icons/valid-xhtml10" alt="Valid XHTML 1.0!" height="31" width="88"/></a></td></tr></table> </body> </html>
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Restaurant website</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous"> <link rel="stylesheet" href="components/style.css"> </head> <body> <!-- navbar --> <nav class="navbar navbar-expand-lg bg-white shadow py-3 sticky-top" > <div class="container"> <a class="navbar-brand" href="#Home"> <img src="/components/images/mallareddy3.jpg" alt="" width="150px" height="150px"> </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"> <ul class="navbar-nav mx-auto"> <li class="nav-item"> <a class="nav-link" href="#Home">Home</a> </li> <li class="nav-item"> <a class="nav-link" href="#About Us" >About Us</a> </li> <li class="nav-item"> <a class="nav-link" href="#Menu" >Menu</a> </li> <li class="nav-item"> <a class="nav-link" href="#Reservation" >Reservation</a> </li> </ul> <a href="#" class="btn btn-brand">Online Order</a> </div> </div> </nav> <!-- slider --> <div id="carouselExample" class="carousel slide"> <div class="carousel-inner"> <div class="carousel-item text-center vh-100 active slide-1 "> <!--<div class="container h-100 d-flex align-item-center jusitify-content-center">--> <div> <div class="row jusitify-content-center"> <!--<div class="col-lg-8">--> <div> <h4 class="text-white " style="text-align: center;">WELCOME TO MALLAREDDY KITCHEN</h4> <h1 class="display-1 text-white" style="margin-top:300px;"> Experience Authentic flavours</h1> <a href="#" class="btn btn-brand">Try now</a> </div> </div> </div> </div> <div class="carousel-item text-center vh-100 slide-2"> <!-- <div class="container h-100 d-flex align-item-center jusitify-content-center">--> <div> <div class="row jusitify-content-center"> <div> <h4 class="text-white">WELCOME TO MALLAREDDY KITCHEN</h4> <h1 class="display-1 text-white" style="margin-top:300px;">Good food is the foundation of genuine happiness</h1> <a href="#" class="btn btn-brand">book table</a> </div> </div> </div> </div> </div> <button class="carousel-control-prev" type="button" data-bs-target="#carouselExample" data-bs-slide="prev"> <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="visually-hidden">Previous</span> </button> <button class="carousel-control-next" type="button" data-bs-target="#carouselExample" data-bs-slide="next"> <span class="carousel-control-next-icon" aria-hidden="true"></span> <span class="visually-hidden">Next</span> </button> </div> <!-- about us --> <section id="About Us"> <div class="container"> <div class="row align-items-center"> <div class="col-lg-5"> <img src="/components/images/res.webp" alt="" height="300px" width="530px"> </div> <div class="col-lg-5"> <h1>About Us</h1> <div class="divider my-4"></div> <p >The Mallareddy kitchen that ultimately came to be known as the restaurant originated in hyderabad, and the hyderabadi people have continued to make major contributions to the restaurant's development. The first restaurant proprietor is believed to have been one A+.</p> <a href="#Menu" class="btn btn-brand"> Explore our menu</a> </div> </div> </div> </section> <!-- menu --> <section id="Menu" class="bg-light"> <div class="container"> <div class="row"> <div class="col-12 intro-text"> <h1>Explore Our Menu</h1> <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Blanditiis soluta perspiciatis recusandae velit quis vel debitis necessitatibus officia fugiat ad minima dolorum, vitae dolor temporibus mollitia, placeat natus quo. Nostrum!</p> </div> </div> </div> <div class="container"> <ul class="nav nav-pills mb-3 justify-content-center" id="pills-tab" role="tablist" > <li class="nav-item" role="presentation"> <button class="nav-link active" id="pills-all-tab" data-bs-toggle="pill" data-bs-target="#pills-all" type="button" role="tab" aria-controls="pills-all" aria-selected="true">All</button> </li> <li class="nav-item" role="presentation"> <button class="nav-link " id="pills-lunch-tab" data-bs-toggle="pill" data-bs-target="#pills-lunch" type="button" role="tab" aria-controls="pills-lunch" aria-selected="true">Lunch</button> </li> <li class="nav-item" role="presentation"> <button class="nav-link " id="pills-dinner-tab" data-bs-toggle="pill" data-bs-target="#pills-dinner" type="button" role="tab" aria-controls="pills-dinner" aria-selected="true">Dinner</button> </li> </ul> <div class="tab-content" id="pills-tabContent"> <div class="tab-pane fade show active" id="pills-all" role="tabpanel" aria-labelledby="pills-all-tab" tabindex="0"> <div class="row gy-4"> <div class="col-lg-3 col-sm-6"> <div class="Menu-item bg-white shadow-on-hover"> <img src="/components/images/Tmenu1.webp" alt="" width="306px" height="200px" > <div class="Menu-item-content p-4"> <h5 class="mt-1 mb-2"><a href="#">Gluten pancake</a></h5> <p class="small">Gluten is composed of two types of proteins, called gliadin and glutenin</p> </div> </div> </div> <div class="col-lg-3 col-sm-6"> <div class="Menu-item bg-white shadow-on-hover"> <img src="/components/images/menu2.jpg" alt="" width="306px" height="200px" > <div class="Menu-item-content p-4"> <h5 class="mt-1 mb-2"><a href="#">Italian pizza</a></h5> <p class="small">Pizza became as popular as it did in part because of the sheer number of Italian immigrants</p> </div> </div> </div> <div class="col-lg-3 col-sm-6"> <div class="Menu-item bg-white shadow-on-hover"> <img src="/components/images/menu3.webp" alt="" width="306px" height="200px" > <div class="Menu-item-content p-4"> <h5 class="mt-1 mb-2"><a href="#">Burrito</a></h5> <p class="small">Authentic Mexican burritos consist of two thin flour tortillas filled with a variety of ingredients</p> </div> </div> </div> <div class="col-lg-3 col-sm-6"> <div class="Menu-item bg-white shadow-on-hover"> <img src="/components/images/menu4.jpeg" alt="" width="306px" height="200px" > <div class="Menu-item-content p-4"> <h5 class="mt-1 mb-2"><a href="#">Burger</a></h5> <p class="small">so they swapped in cooked ground mixed with coffee and brown sugar to add flavor, and served it as a sandwich</p> </div> </div> </div> <div class="col-lg-3 col-sm-6"> <div class="Menu-item bg-white shadow-on-hover"> <img src="/components/images/menu 5.jpeg" alt="" width="306px" height="200px" > <div class="Menu-item-content p-4"> <h5 class="mt-1 mb-2"><a href="#">Chicken biryani</a></h5> <p class="small">Biryani is a mixed rice dish, mainly popular in South Asia. It is made with rice, some type of meat and spices. </p> </div> </div> </div> <div class="col-lg-3 col-sm-6"> <div class="Menu-item bg-white shadow-on-hover"> <img src="/components/images/menu6.jpeg" alt="" width="306px" height="200px" > <div class="Menu-item-content p-4"> <h5 class="mt-1 mb-2"><a href="#">Mutton biryani</a></h5> <p class="small">Hyderabadi Biryani is the most popular biryani in India because of its meticulous blend of spices, nestled with the tenderness of meat and veggies.</p> </div> </div> </div> <div class="col-lg-3 col-sm-6"> <div class="Menu-item bg-white shadow-on-hover"> <img src="/components/images/menu8.jpeg" alt="" width="306px" height="200px" > <div class="Menu-item-content p-4"> <h5 class="mt-1 mb-2"><a href="#">Mojito</a></h5> <p class="small">A mojito is a classic highball drink that originated in Cuba. Not surprisingly, this cocktail uses ingredients indigenous</p> </div> </div> </div> <div class="col-lg-3 col-sm-6"> <div class="Menu-item bg-white shadow-on-hover"> <img src="/components/images/menu8.jpeg" alt="" width="306px" height="200px" > <div class="Menu-item-content p-4"> <h5 class="mt-1 mb-2"><a href="#">Thick shake</a></h5> <p class="small"> Thick shakes is the amount of ice cream that goes into their making. So, if it's a thick shake you've ordered, expect four generous scoops of ice cream and just a splash of milk.</p> </div> </div> </div> </div> </div> <div class="tab-pane fade show " id="pills-lunch" role="tabpanel" aria-labelledby="pills-lunch-tab" tabindex="0"> <div class="row gy-4"> <div class="col-lg-3 col-sm-6"> <div class="Menu-item bg-white shadow-on-hover"> <img src="/components/images/Tmenu1.webp" alt="" width="306px" height="200px" > <div class="Menu-item-content p-4"> <h5 class="mt-1 mb-2"><a href="#">Gluten pancake</a></h5> <p class="small">Gluten is composed of two types of proteins, called gliadin and glutenin</p> </div> </div> </div> <div class="col-lg-3 col-sm-6"> <div class="Menu-item bg-white shadow-on-hover"> <img src="/components/images/menu2.jpg" alt="" width="306px" height="200px" > <div class="Menu-item-content p-4"> <h5 class="mt-1 mb-2"><a href="#">Italian pizza</a></h5> <p class="small">Pizza became as popular as it did in part because of the sheer number of Italian immigrants</p> </div> </div> </div> <div class="col-lg-3 col-sm-6"> <div class="Menu-item bg-white shadow-on-hover"> <img src="/components/images/menu3.webp" alt="" width="306px" height="200px" > <div class="Menu-item-content p-4"> <h5 class="mt-1 mb-2"><a href="#">Burrito</a></h5> <p class="small">Authentic Mexican burritos consist of two thin flour tortillas filled with a variety of ingredients</p> </div> </div> </div> <div class="col-lg-3 col-sm-6"> <div class="Menu-item bg-white shadow-on-hover"> <img src="/components/images/menu4.jpeg" alt="" width="306px" height="200px" > <div class="Menu-item-content p-4"> <h5 class="mt-1 mb-2"><a href="#">Burger</a></h5> <p class="small">so they swapped in cooked ground mixed with coffee and brown sugar to add flavor, and served it as a sandwich</p> </div> </div> </div> </div> </div> <div class="tab-pane fade show " id="pills-dinner" role="tabpanel" aria-labelledby="pills-dinner-tab" tabindex="0"> <div class="row gy-4"> <div class="col-lg-3 col-sm-6"> <div class="Menu-item bg-white shadow-on-hover"> <img src="/components/images/menu 5.jpeg" alt="" width="306px" height="200px" > <div class="Menu-item-content p-4"> <h5 class="mt-1 mb-2"><a href="#">Chicken biryani</a></h5> <p class="small">Biryani is a mixed rice dish, mainly popular in South Asia. It is made with rice, some type of meat and spices. </p> </div> </div> </div> <div class="col-lg-3 col-sm-6"> <div class="Menu-item bg-white shadow-on-hover"> <img src="/components/images/menu6.jpeg" alt="" width="306px" height="200px" > <div class="Menu-item-content p-4"> <h5 class="mt-1 mb-2"><a href="#">Mutton biryani</a></h5> <p class="small">Hyderabadi Biryani is the most popular biryani in India because of its meticulous blend of spices, nestled with the tenderness of meat and veggies.</p> </div> </div> </div> <div class="col-lg-3 col-sm-6"> <div class="Menu-item bg-white shadow-on-hover"> <img src="/components/images/menu7.jpeg" alt="" width="306px" height="200px" > <div class="Menu-item-content p-4"> <h5 class="mt-1 mb-2"><a href="#">Mojito</a></h5> <p class="small">A mojito is a classic highball drink that originated in Cuba. Not surprisingly, this cocktail uses ingredients indigenous</p> </div> </div> </div> <div class="col-lg-3 col-sm-6"> <div class="Menu-item bg-white shadow-on-hover"> <img src="/components/images/menu8.jpeg" alt="" width="306px" height="200px" > <div class="Menu-item-content p-4"> <h5 class="mt-1 mb-2"><a href="#">Thick shake</a></h5> <p class="small"> Thick shakes is the amount of ice cream that goes into their making. So, if it's a thick shake you've ordered, expect four generous scoops of ice cream and just a splash of milk.</p> </div> </div> </div> </div> </div> </div> </div> </section> <!-- reservation --> <section id="Reservation"> <div class="container"> <div class="row"> <div class="col-12 intro text"> <h1>Book Your Table</h1> <P>Lorem ipsum dolor, sit amet consectetur adipisicing elit. Iure, facilis eos alias di</P> </div> </div> </div> <form action="#" class="row justify-content-center"> <div class="col-lg-8"> <div class="row g-3"> <div class="form-group col-md-6"> <input type="text" class="form-control" placeholder="Full name"> </div> <div class="form-group col-md-6"> <input type="email" class="form-control" placeholder="Email Address"> </div> <div class="form-group col-md-6"> <input type="text" class="form-control" placeholder=" date"> </div> <div class="form-group col-md-6"> <input type="text" class="form-control" placeholder="Enter time"> </div> <div class="form-group col-md-6"> <input type="number" class="form-control" placeholder="Total persons"> </div> <div class="form-group col-md-6"> <input type="text" class="form-control" placeholder="Enter Coupon "> </div> <div class="form-group col-md-12"> <a href="#" class="btn btn-brand"> Submit</a> </div> </form> </section> <!-- footer --> <footer class="form-top"> <div class="container"> <div class="row"> <div class="col-lg-4"> <img src="/components/images/mallareddy3.jpg" alt="" width="150px" height="100px"> <p>The Mallareddy kitchen that ultimately came to be known as the restaurant originated in hyderabad, and the hyderabadi people have continued to make major contributions to the restaurant's development. The first restaurant proprietor is believed to have been one NAAC A+.</p> </div> <div class="col-lg-3 ms-auto"> <h6 class="text-white mb-4"> CONTACT</h6> <p>Phone numer:987654321</p> <p>Email:malla@gmail.com</p> <p>address: Kphb Near Metro </p> </div> <div class="col-lg-3"> <h6 class="text-white md-4"> OPENING HOURS</h6> <p >Monday-Friday:12pm -10pm</p> <p>Saturday&Sunday:12pm-11pm</p> </div> </div> </div> <div class="footer-bottom"> <div class="container"> <div class="row justify-content-center "> <div class="col-auto"> <p class="rohit" > Copyrights all reserved by @Mallareddy</p> </div> </div> </div> </div> </footer> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-YvpcrYf0tY3lHB60NNkmXc5s9fDVZLESaAA55NDzOxhy9GkcIdslK1eN7N6jIeHz" crossorigin="anonymous"></script> </body> </html>
package app.beautyminder.controller.cosmetic; import app.beautyminder.domain.Cosmetic; import app.beautyminder.service.ReviewService; import app.beautyminder.service.cosmetic.CosmeticRankService; import app.beautyminder.service.cosmetic.CosmeticService; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.media.Content; import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.responses.ApiResponse; import jakarta.validation.Valid; import lombok.RequiredArgsConstructor; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.util.List; @RequiredArgsConstructor @RestController @RequestMapping("/cosmetic") public class CosmeticController { private final CosmeticService cosmeticService; private final CosmeticRankService cosmeticRankService; @Operation(summary = "Get All Cosmetics", description = "모든 화장품을 가져옵니다.", tags = {"Cosmetic Operations"}, responses = {@ApiResponse(responseCode = "200", description = "성공", content = @Content(schema = @Schema(implementation = Cosmetic.class, type = "array"))), @ApiResponse(responseCode = "404", description = "화장품을 찾을 수 없음", content = @Content(schema = @Schema(implementation = String.class)))}) @GetMapping public ResponseEntity<List<Cosmetic>> getAllCosmetics() { List<Cosmetic> cosmetics = cosmeticService.getAllCosmetics(); return ResponseEntity.ok(cosmetics); } @Operation(summary = "Get Cosmetic by ID", description = "ID로 화장품을 가져옵니다.", tags = {"Cosmetic Operations"}, parameters = {@Parameter(name = "id", description = "화장품의 ID")}, responses = {@ApiResponse(responseCode = "200", description = "성공", content = @Content(schema = @Schema(implementation = Cosmetic.class))), @ApiResponse(responseCode = "404", description = "화장품을 찾을 수 없음", content = @Content(schema = @Schema(implementation = String.class)))}) @GetMapping("/{id}") public ResponseEntity<Cosmetic> getCosmeticById(@PathVariable String id) { Cosmetic cosmetic = cosmeticService.getCosmeticById(id); if (cosmetic == null) { return ResponseEntity.notFound().build(); } return ResponseEntity.ok(cosmetic); } // Add a new cosmetic @Operation(summary = "Create a cosmetic data", description = "화장품을 생성합니다.", tags = {"Cosmetic Operations"}, requestBody = @io.swagger.v3.oas.annotations.parameters.RequestBody(description = "화장품"), responses = {@ApiResponse(responseCode = "200", description = "화장품 추가 성공", content = @Content(schema = @Schema(implementation = Cosmetic.class))),}) @PostMapping public ResponseEntity<Cosmetic> createCosmetic(@Valid @RequestBody Cosmetic cosmetic) { Cosmetic newCosmetic = cosmeticService.saveCosmetic(cosmetic); return ResponseEntity.ok(newCosmetic); } // Update an existing cosmetic @Operation(summary = "Update cosmetic entirely", description = "Cosmetic을 업데이트 합니다. (통째로)", tags = {"Cosmetic Operations"}, parameters = {@Parameter(name = "id", description = "화장품의 ID"),}, requestBody = @io.swagger.v3.oas.annotations.parameters.RequestBody(description = "Cosmetic 모델"), responses = {@ApiResponse(responseCode = "200", description = "성공", content = @Content(schema = @Schema(implementation = Cosmetic.class))), @ApiResponse(responseCode = "404", description = "화장품을 찾을 수 없음", content = @Content(schema = @Schema(implementation = String.class)))}) @PutMapping("/{id}") public ResponseEntity<Cosmetic> updateCosmetic(@PathVariable String id, @RequestBody Cosmetic cosmeticDetails) { Cosmetic updatedCosmetic = cosmeticService.updateCosmetic(id, cosmeticDetails); if (updatedCosmetic == null) { return ResponseEntity.notFound().build(); } return ResponseEntity.ok(updatedCosmetic); } // Delete a cosmetic @Operation(summary = "Delete a cosmetic entirely", description = "Cosmetic을 삭제 합니다.", tags = {"Cosmetic Operations"}, parameters = {@Parameter(name = "id", description = "화장품의 ID"),}, responses = {@ApiResponse(responseCode = "200", description = "성공", content = @Content(schema = @Schema())), @ApiResponse(responseCode = "404", description = "화장품을 찾을 수 없음", content = @Content(schema = @Schema()))}) @DeleteMapping("/{id}") public ResponseEntity<Void> deleteCosmetic(@PathVariable String id) { boolean deleted = cosmeticService.deleteCosmetic(id); if (!deleted) { return ResponseEntity.notFound().build(); } return ResponseEntity.ok().build(); } @Operation(summary = "Cosmetic Redis click++", description = "Cosmetic click++", tags = {"Redis Operations"}, parameters = {@Parameter(name = "cosmeticId", description = "화장품의 ID"),}, responses = {@ApiResponse(responseCode = "200", description = "성공", content = @Content(schema = @Schema()))}) @PostMapping("/click/{cosmeticId}") public ResponseEntity<Void> incrementClickCount(@PathVariable String cosmeticId) { cosmeticRankService.collectClickEvent(cosmeticId); return ResponseEntity.ok().build(); } @Operation(summary = "Cosmetic Redis search hit++", description = "Cosmetic searchHit++", tags = {"Redis Operations"}, parameters = {@Parameter(name = "cosmeticId", description = "화장품의 ID"),}, responses = {@ApiResponse(responseCode = "200", description = "성공", content = @Content(schema = @Schema()))}) @PostMapping("/hit/{cosmeticId}") public ResponseEntity<Void> incrementHitCount(@PathVariable String cosmeticId) { cosmeticRankService.collectHitEvent(cosmeticId); return ResponseEntity.ok().build(); } }
--- title: "\"Mastering FB Sharing YouTube Videos Directly for 2024\"" date: 2024-05-31T12:40:34.694Z updated: 2024-06-01T12:40:34.694Z tags: - ai video - ai youtube categories: - ai - youtube description: "\"This Article Describes Mastering FB: Sharing YouTube Videos Directly for 2024\"" excerpt: "\"This Article Describes Mastering FB: Sharing YouTube Videos Directly for 2024\"" keywords: "Share YouTube on Facebook,FB Video Posting,Direct FB Video Upload,YouTube to FB Links,FB Video Broadcast,Social Media Sharing,Integrate YouTube FB" thumbnail: https://www.lifewire.com/thmb/DwsDy9imoz85_yJbP3D7n-APAnE=/540x405/filters:no_upscale():max_bytes(150000):strip_icc()/unnamed2-60f231b72c19491683c2166c9285b34d.jpg --- ## Mastering FB: Sharing YouTube Videos Directly ##### Create High-Quality Video - Wondershare Filmora An easy and powerful YouTube video editor Numerous video and audio effects to choose from Detailed tutorials provided by the official channel [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) YouTube reports that Facebook is the most utilized platform fans use to watch online content. More so, up to 40% of those who watch the content do share links with their friends online – this then makes it quick to promote YouTube content on Facebook. Simply by making your new YouTube content visible on your Facebook page, and you’ll be certain that thousands of viewers will have a glimpse of it. You must already be scratching your head for ways on how to post a YouTube video on a Facebook page. Well, we bring you several ways to go through that and make your YouTube content accessible on Facebook. ![how to share youtube video on facebook](https://images.wondershare.com/filmora/article-images/2021/share-youtube-video-on-facebook-1.png) #### In this article 01 [How to Post YouTube video on Facebook?](#part1) 02 [Extra Tip: Facebook Video Tips for more Views and Shares](#part2) 03 [Frequently Asked Question about Facebook video](#part3) ## How to Post YouTube video on Facebook? Since Facebook is easily accessible, many users have more access to it than other social media platforms. More so, the page allows you to communicate with your audience via photos, videos, graphics, text, among many other multimedia contents. You don’t even need any programming skills to operate it. Here are ways to post YouTube content to Facebook. #### How to share a YouTube video on Facebook using a computer If you have a stationary point of work, i.e., a computer, it is possible to share your YouTube video through it. Step 1\. First, visit the YouTube site at <https://www.youtube.com>. It can launch from any web browser. Step 2\. Choose from among your videos on YouTube the one you wish to share on Facebook. Step 3\. Then find the “Share” icon located directly under the video you want to share. Click on the video and hit the “Share” button below the video. Step 4\. Choose “Facebook” from the sharing options that pop up. ![share youtube video on facebook using computer](https://images.wondershare.com/filmora/article-images/2021/share-youtube-video-on-facebook-2.png) Step 5\. Next, sign in to “Facebook” on your desktop. Then select the destination point you want your video to land in by using the drop-down menu at the top of your desktop screen. Select the “Share to News Feed” or perhaps the share to “Story.” Step 6\. Finally, click the “Post to Facebook” tab to share your YouTube content with Facebook. #### How to share a YouTube video on Facebook using a mobile device Are you on the go and want your Facebook fans to know what content you have on your YouTube channel? Here are the simple steps on how to post a YouTube video on Facebook right from the palm of your hands – a mobile device. Step 1\. Use any browser on your mobile device to launch the YouTube app from the official website. Step 2\. Peruse through your YouTube videos and choose the one you wish to share on Facebook. Step 3\. Check below the video and click on the “Share” icon. Step 4\. Search through the app’s options and choose Facebook. Also, ensure that the “Facebook” app is installed on your mobile device to make your videos sharable. Step 5\. Click on the “Next” option in the upper right-hand corner of your mobile screen. It will enable video sharing. ![share youtube video on facebook using mobile](https://images.wondershare.com/filmora/article-images/2021/share-youtube-video-on-facebook-3.png) Step 6\. Then choose the YouTube video’s post destination to your Facebook. It could be shared on your timeline, story, or a Facebook group’s page. Step 7\. Finally, click on the “Share” tab to make your video viewable on Facebook. ![how to share youtube video on facebook using mobile](https://images.wondershare.com/filmora/article-images/2021/share-youtube-video-on-facebook-4.png) #### How to post a YouTube video on Facebook Easily post your YouTube video on Facebook and let viewers access them directly from your Facebook feed. By this, your fans don’t have to click on other tabs but will access the videos directly. Step 1\. Copy the YouTube video’s link First, go to your YouTube channel and copy the video link that you want to post to Facebook. You can as well copy the embed code. Step 2\. Embed the video link you copied This link should be embedded into a Facebook post. Do this by first logging into your Facebook account. Then go to the top of your “Facebook News Feed” and click the “What’s on your mind” box. Step 3\. Paste your link Right-click on the “What’s on your mind” box, then select the “Paste” option. Step 4\. Preview video Facebook will let you preview the video you just posted. Check whether you have pasted the right video before you post it. Step 5\. Post your video Now, scroll down and click on the “Post” tab. You can also add a message to your post. Just place a cursor after the video URL and hit the “Enter” key on your keyboard. Finally, scroll down and hit the “Post” tab to make your video public on Facebook. ## Extra Tip: Facebook Video Tips for more Views and Shares You have to play your cards well when it comes to posting and sharing your videos on Facebook. These tips are all you need. #### \- Catch viewer’s attention within the shortest time possible Here, your main aim is to convince your viewers. So, don’t let them spend so much time before you catch their attention. You can bring up a point about some latest news or adventures that let your viewers connect immediately. #### \- Add captions to the video It is not necessarily possible that viewers will watch your videos with the sound on. Some like it when it’s silent and might disable the sound auto-play. Add some captions so that viewers will understand your video, even on silent mode. #### \- Emphasize on one key-point Focus on one key point so that your viewers are not swayed away. Your video is highly sharable if it is easy to understand. #### \- Add a Call To Action Including a call-to-action will encourage your viewers to subscribe to your channel. Ensure you include it at the end of your video to tell viewers what to do next. You could also include a link to your blog post to let your viewers read and find more content from your other channels. #### \- Facebook ads can make a great difference Facebook is a great place for running ads that reach a wider audience. Adverts are great ways to target a specific audience. They explain your products and services more straightforwardly. #### \- Embed your videos on blog posts Numerous people get to access guest posts and blog posts. You can embed your Facebook videos on such posts to reach more people. Just get the embed code from your video, then copy and paste it to a guest or blog post. ## Frequently Asked Question about Facebook video Both viewers and content creators have a few concerns about YouTube and Facebook videos. Here are some frequently asked questions that will be of benefit to you. #### 1) Is it legal to share YouTube videos? YouTube is just one platform where content creators showcase their productions. Yes, it is legal to share your content on other forums like Facebook, Twitter, Instagram, etc. #### 2) What is the best time to post to your Facebook page? The best time to post on a Facebook page depends on your time zone. Generally, viewers access Facebook late in the evening and early in the night. Perhaps they are off work and now want to relax by checking the day’s updates. #### 3) What are Facebook business accounts and personal accounts? Facebook business accounts are designed for users who want to use Facebook to administer their pages and advert campaigns. This account cannot be found in searching or receiving friend request apps. Nonetheless, personal accounts are used at basic and casual levels. You can search for friends and send requests. Personal accounts are also easy to manage. #### 4) Can I mobilize people to share my posted content on Facebook? Yes, it is possible to let others share what you have posted. Just ensure they know your intention by constant reminders. Some popular ways that are proven to be effective include the use of “Call to Action,” using an image or video with your Facebook status update and offering some incentive to your fans for sharing. #### 5) Does the quality of my YouTube content drop when I share it with Facebook? Of course not! What you pull from your YouTube channel is the kind of video that will be watched from Facebook. The quality cannot deteriorate. However, it is good to ensure you compose quality videos on YouTube before sharing them. Several video editing apps like Filmora can help you compose quality videos with high resolution. ## Conclusion ● Facebook is a great platform that is accessed by a wide audience. More so, you can share your content from other platforms easily. The article has covered how to share YouTube videos on Facebook and hook your audience. You can use your computer or share directly from your mobile device in simple steps. It is also better to play some tricks on your effort to reach a wider audience. These include a CTA, embedding your Facebook videos to blogs posts, among other options. [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) YouTube reports that Facebook is the most utilized platform fans use to watch online content. More so, up to 40% of those who watch the content do share links with their friends online – this then makes it quick to promote YouTube content on Facebook. Simply by making your new YouTube content visible on your Facebook page, and you’ll be certain that thousands of viewers will have a glimpse of it. You must already be scratching your head for ways on how to post a YouTube video on a Facebook page. Well, we bring you several ways to go through that and make your YouTube content accessible on Facebook. ![how to share youtube video on facebook](https://images.wondershare.com/filmora/article-images/2021/share-youtube-video-on-facebook-1.png) #### In this article 01 [How to Post YouTube video on Facebook?](#part1) 02 [Extra Tip: Facebook Video Tips for more Views and Shares](#part2) 03 [Frequently Asked Question about Facebook video](#part3) ## How to Post YouTube video on Facebook? Since Facebook is easily accessible, many users have more access to it than other social media platforms. More so, the page allows you to communicate with your audience via photos, videos, graphics, text, among many other multimedia contents. You don’t even need any programming skills to operate it. Here are ways to post YouTube content to Facebook. #### How to share a YouTube video on Facebook using a computer If you have a stationary point of work, i.e., a computer, it is possible to share your YouTube video through it. Step 1\. First, visit the YouTube site at <https://www.youtube.com>. It can launch from any web browser. Step 2\. Choose from among your videos on YouTube the one you wish to share on Facebook. Step 3\. Then find the “Share” icon located directly under the video you want to share. Click on the video and hit the “Share” button below the video. Step 4\. Choose “Facebook” from the sharing options that pop up. ![share youtube video on facebook using computer](https://images.wondershare.com/filmora/article-images/2021/share-youtube-video-on-facebook-2.png) Step 5\. Next, sign in to “Facebook” on your desktop. Then select the destination point you want your video to land in by using the drop-down menu at the top of your desktop screen. Select the “Share to News Feed” or perhaps the share to “Story.” Step 6\. Finally, click the “Post to Facebook” tab to share your YouTube content with Facebook. #### How to share a YouTube video on Facebook using a mobile device Are you on the go and want your Facebook fans to know what content you have on your YouTube channel? Here are the simple steps on how to post a YouTube video on Facebook right from the palm of your hands – a mobile device. Step 1\. Use any browser on your mobile device to launch the YouTube app from the official website. Step 2\. Peruse through your YouTube videos and choose the one you wish to share on Facebook. Step 3\. Check below the video and click on the “Share” icon. Step 4\. Search through the app’s options and choose Facebook. Also, ensure that the “Facebook” app is installed on your mobile device to make your videos sharable. Step 5\. Click on the “Next” option in the upper right-hand corner of your mobile screen. It will enable video sharing. ![share youtube video on facebook using mobile](https://images.wondershare.com/filmora/article-images/2021/share-youtube-video-on-facebook-3.png) Step 6\. Then choose the YouTube video’s post destination to your Facebook. It could be shared on your timeline, story, or a Facebook group’s page. Step 7\. Finally, click on the “Share” tab to make your video viewable on Facebook. ![how to share youtube video on facebook using mobile](https://images.wondershare.com/filmora/article-images/2021/share-youtube-video-on-facebook-4.png) #### How to post a YouTube video on Facebook Easily post your YouTube video on Facebook and let viewers access them directly from your Facebook feed. By this, your fans don’t have to click on other tabs but will access the videos directly. Step 1\. Copy the YouTube video’s link First, go to your YouTube channel and copy the video link that you want to post to Facebook. You can as well copy the embed code. Step 2\. Embed the video link you copied This link should be embedded into a Facebook post. Do this by first logging into your Facebook account. Then go to the top of your “Facebook News Feed” and click the “What’s on your mind” box. Step 3\. Paste your link Right-click on the “What’s on your mind” box, then select the “Paste” option. Step 4\. Preview video Facebook will let you preview the video you just posted. Check whether you have pasted the right video before you post it. Step 5\. Post your video Now, scroll down and click on the “Post” tab. You can also add a message to your post. Just place a cursor after the video URL and hit the “Enter” key on your keyboard. Finally, scroll down and hit the “Post” tab to make your video public on Facebook. ## Extra Tip: Facebook Video Tips for more Views and Shares You have to play your cards well when it comes to posting and sharing your videos on Facebook. These tips are all you need. #### \- Catch viewer’s attention within the shortest time possible Here, your main aim is to convince your viewers. So, don’t let them spend so much time before you catch their attention. You can bring up a point about some latest news or adventures that let your viewers connect immediately. #### \- Add captions to the video It is not necessarily possible that viewers will watch your videos with the sound on. Some like it when it’s silent and might disable the sound auto-play. Add some captions so that viewers will understand your video, even on silent mode. #### \- Emphasize on one key-point Focus on one key point so that your viewers are not swayed away. Your video is highly sharable if it is easy to understand. #### \- Add a Call To Action Including a call-to-action will encourage your viewers to subscribe to your channel. Ensure you include it at the end of your video to tell viewers what to do next. You could also include a link to your blog post to let your viewers read and find more content from your other channels. #### \- Facebook ads can make a great difference Facebook is a great place for running ads that reach a wider audience. Adverts are great ways to target a specific audience. They explain your products and services more straightforwardly. #### \- Embed your videos on blog posts Numerous people get to access guest posts and blog posts. You can embed your Facebook videos on such posts to reach more people. Just get the embed code from your video, then copy and paste it to a guest or blog post. ## Frequently Asked Question about Facebook video Both viewers and content creators have a few concerns about YouTube and Facebook videos. Here are some frequently asked questions that will be of benefit to you. #### 1) Is it legal to share YouTube videos? YouTube is just one platform where content creators showcase their productions. Yes, it is legal to share your content on other forums like Facebook, Twitter, Instagram, etc. #### 2) What is the best time to post to your Facebook page? The best time to post on a Facebook page depends on your time zone. Generally, viewers access Facebook late in the evening and early in the night. Perhaps they are off work and now want to relax by checking the day’s updates. #### 3) What are Facebook business accounts and personal accounts? Facebook business accounts are designed for users who want to use Facebook to administer their pages and advert campaigns. This account cannot be found in searching or receiving friend request apps. Nonetheless, personal accounts are used at basic and casual levels. You can search for friends and send requests. Personal accounts are also easy to manage. #### 4) Can I mobilize people to share my posted content on Facebook? Yes, it is possible to let others share what you have posted. Just ensure they know your intention by constant reminders. Some popular ways that are proven to be effective include the use of “Call to Action,” using an image or video with your Facebook status update and offering some incentive to your fans for sharing. #### 5) Does the quality of my YouTube content drop when I share it with Facebook? Of course not! What you pull from your YouTube channel is the kind of video that will be watched from Facebook. The quality cannot deteriorate. However, it is good to ensure you compose quality videos on YouTube before sharing them. Several video editing apps like Filmora can help you compose quality videos with high resolution. ## Conclusion ● Facebook is a great platform that is accessed by a wide audience. More so, you can share your content from other platforms easily. The article has covered how to share YouTube videos on Facebook and hook your audience. You can use your computer or share directly from your mobile device in simple steps. It is also better to play some tricks on your effort to reach a wider audience. These include a CTA, embedding your Facebook videos to blogs posts, among other options. [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) YouTube reports that Facebook is the most utilized platform fans use to watch online content. More so, up to 40% of those who watch the content do share links with their friends online – this then makes it quick to promote YouTube content on Facebook. Simply by making your new YouTube content visible on your Facebook page, and you’ll be certain that thousands of viewers will have a glimpse of it. You must already be scratching your head for ways on how to post a YouTube video on a Facebook page. Well, we bring you several ways to go through that and make your YouTube content accessible on Facebook. ![how to share youtube video on facebook](https://images.wondershare.com/filmora/article-images/2021/share-youtube-video-on-facebook-1.png) #### In this article 01 [How to Post YouTube video on Facebook?](#part1) 02 [Extra Tip: Facebook Video Tips for more Views and Shares](#part2) 03 [Frequently Asked Question about Facebook video](#part3) ## How to Post YouTube video on Facebook? Since Facebook is easily accessible, many users have more access to it than other social media platforms. More so, the page allows you to communicate with your audience via photos, videos, graphics, text, among many other multimedia contents. You don’t even need any programming skills to operate it. Here are ways to post YouTube content to Facebook. #### How to share a YouTube video on Facebook using a computer If you have a stationary point of work, i.e., a computer, it is possible to share your YouTube video through it. Step 1\. First, visit the YouTube site at <https://www.youtube.com>. It can launch from any web browser. Step 2\. Choose from among your videos on YouTube the one you wish to share on Facebook. Step 3\. Then find the “Share” icon located directly under the video you want to share. Click on the video and hit the “Share” button below the video. Step 4\. Choose “Facebook” from the sharing options that pop up. ![share youtube video on facebook using computer](https://images.wondershare.com/filmora/article-images/2021/share-youtube-video-on-facebook-2.png) Step 5\. Next, sign in to “Facebook” on your desktop. Then select the destination point you want your video to land in by using the drop-down menu at the top of your desktop screen. Select the “Share to News Feed” or perhaps the share to “Story.” Step 6\. Finally, click the “Post to Facebook” tab to share your YouTube content with Facebook. #### How to share a YouTube video on Facebook using a mobile device Are you on the go and want your Facebook fans to know what content you have on your YouTube channel? Here are the simple steps on how to post a YouTube video on Facebook right from the palm of your hands – a mobile device. Step 1\. Use any browser on your mobile device to launch the YouTube app from the official website. Step 2\. Peruse through your YouTube videos and choose the one you wish to share on Facebook. Step 3\. Check below the video and click on the “Share” icon. Step 4\. Search through the app’s options and choose Facebook. Also, ensure that the “Facebook” app is installed on your mobile device to make your videos sharable. Step 5\. Click on the “Next” option in the upper right-hand corner of your mobile screen. It will enable video sharing. ![share youtube video on facebook using mobile](https://images.wondershare.com/filmora/article-images/2021/share-youtube-video-on-facebook-3.png) Step 6\. Then choose the YouTube video’s post destination to your Facebook. It could be shared on your timeline, story, or a Facebook group’s page. Step 7\. Finally, click on the “Share” tab to make your video viewable on Facebook. ![how to share youtube video on facebook using mobile](https://images.wondershare.com/filmora/article-images/2021/share-youtube-video-on-facebook-4.png) #### How to post a YouTube video on Facebook Easily post your YouTube video on Facebook and let viewers access them directly from your Facebook feed. By this, your fans don’t have to click on other tabs but will access the videos directly. Step 1\. Copy the YouTube video’s link First, go to your YouTube channel and copy the video link that you want to post to Facebook. You can as well copy the embed code. Step 2\. Embed the video link you copied This link should be embedded into a Facebook post. Do this by first logging into your Facebook account. Then go to the top of your “Facebook News Feed” and click the “What’s on your mind” box. Step 3\. Paste your link Right-click on the “What’s on your mind” box, then select the “Paste” option. Step 4\. Preview video Facebook will let you preview the video you just posted. Check whether you have pasted the right video before you post it. Step 5\. Post your video Now, scroll down and click on the “Post” tab. You can also add a message to your post. Just place a cursor after the video URL and hit the “Enter” key on your keyboard. Finally, scroll down and hit the “Post” tab to make your video public on Facebook. ## Extra Tip: Facebook Video Tips for more Views and Shares You have to play your cards well when it comes to posting and sharing your videos on Facebook. These tips are all you need. #### \- Catch viewer’s attention within the shortest time possible Here, your main aim is to convince your viewers. So, don’t let them spend so much time before you catch their attention. You can bring up a point about some latest news or adventures that let your viewers connect immediately. #### \- Add captions to the video It is not necessarily possible that viewers will watch your videos with the sound on. Some like it when it’s silent and might disable the sound auto-play. Add some captions so that viewers will understand your video, even on silent mode. #### \- Emphasize on one key-point Focus on one key point so that your viewers are not swayed away. Your video is highly sharable if it is easy to understand. #### \- Add a Call To Action Including a call-to-action will encourage your viewers to subscribe to your channel. Ensure you include it at the end of your video to tell viewers what to do next. You could also include a link to your blog post to let your viewers read and find more content from your other channels. #### \- Facebook ads can make a great difference Facebook is a great place for running ads that reach a wider audience. Adverts are great ways to target a specific audience. They explain your products and services more straightforwardly. #### \- Embed your videos on blog posts Numerous people get to access guest posts and blog posts. You can embed your Facebook videos on such posts to reach more people. Just get the embed code from your video, then copy and paste it to a guest or blog post. ## Frequently Asked Question about Facebook video Both viewers and content creators have a few concerns about YouTube and Facebook videos. Here are some frequently asked questions that will be of benefit to you. #### 1) Is it legal to share YouTube videos? YouTube is just one platform where content creators showcase their productions. Yes, it is legal to share your content on other forums like Facebook, Twitter, Instagram, etc. #### 2) What is the best time to post to your Facebook page? The best time to post on a Facebook page depends on your time zone. Generally, viewers access Facebook late in the evening and early in the night. Perhaps they are off work and now want to relax by checking the day’s updates. #### 3) What are Facebook business accounts and personal accounts? Facebook business accounts are designed for users who want to use Facebook to administer their pages and advert campaigns. This account cannot be found in searching or receiving friend request apps. Nonetheless, personal accounts are used at basic and casual levels. You can search for friends and send requests. Personal accounts are also easy to manage. #### 4) Can I mobilize people to share my posted content on Facebook? Yes, it is possible to let others share what you have posted. Just ensure they know your intention by constant reminders. Some popular ways that are proven to be effective include the use of “Call to Action,” using an image or video with your Facebook status update and offering some incentive to your fans for sharing. #### 5) Does the quality of my YouTube content drop when I share it with Facebook? Of course not! What you pull from your YouTube channel is the kind of video that will be watched from Facebook. The quality cannot deteriorate. However, it is good to ensure you compose quality videos on YouTube before sharing them. Several video editing apps like Filmora can help you compose quality videos with high resolution. ## Conclusion ● Facebook is a great platform that is accessed by a wide audience. More so, you can share your content from other platforms easily. The article has covered how to share YouTube videos on Facebook and hook your audience. You can use your computer or share directly from your mobile device in simple steps. It is also better to play some tricks on your effort to reach a wider audience. These include a CTA, embedding your Facebook videos to blogs posts, among other options. [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) YouTube reports that Facebook is the most utilized platform fans use to watch online content. More so, up to 40% of those who watch the content do share links with their friends online – this then makes it quick to promote YouTube content on Facebook. Simply by making your new YouTube content visible on your Facebook page, and you’ll be certain that thousands of viewers will have a glimpse of it. You must already be scratching your head for ways on how to post a YouTube video on a Facebook page. Well, we bring you several ways to go through that and make your YouTube content accessible on Facebook. ![how to share youtube video on facebook](https://images.wondershare.com/filmora/article-images/2021/share-youtube-video-on-facebook-1.png) #### In this article 01 [How to Post YouTube video on Facebook?](#part1) 02 [Extra Tip: Facebook Video Tips for more Views and Shares](#part2) 03 [Frequently Asked Question about Facebook video](#part3) ## How to Post YouTube video on Facebook? Since Facebook is easily accessible, many users have more access to it than other social media platforms. More so, the page allows you to communicate with your audience via photos, videos, graphics, text, among many other multimedia contents. You don’t even need any programming skills to operate it. Here are ways to post YouTube content to Facebook. #### How to share a YouTube video on Facebook using a computer If you have a stationary point of work, i.e., a computer, it is possible to share your YouTube video through it. Step 1\. First, visit the YouTube site at <https://www.youtube.com>. It can launch from any web browser. Step 2\. Choose from among your videos on YouTube the one you wish to share on Facebook. Step 3\. Then find the “Share” icon located directly under the video you want to share. Click on the video and hit the “Share” button below the video. Step 4\. Choose “Facebook” from the sharing options that pop up. ![share youtube video on facebook using computer](https://images.wondershare.com/filmora/article-images/2021/share-youtube-video-on-facebook-2.png) Step 5\. Next, sign in to “Facebook” on your desktop. Then select the destination point you want your video to land in by using the drop-down menu at the top of your desktop screen. Select the “Share to News Feed” or perhaps the share to “Story.” Step 6\. Finally, click the “Post to Facebook” tab to share your YouTube content with Facebook. #### How to share a YouTube video on Facebook using a mobile device Are you on the go and want your Facebook fans to know what content you have on your YouTube channel? Here are the simple steps on how to post a YouTube video on Facebook right from the palm of your hands – a mobile device. Step 1\. Use any browser on your mobile device to launch the YouTube app from the official website. Step 2\. Peruse through your YouTube videos and choose the one you wish to share on Facebook. Step 3\. Check below the video and click on the “Share” icon. Step 4\. Search through the app’s options and choose Facebook. Also, ensure that the “Facebook” app is installed on your mobile device to make your videos sharable. Step 5\. Click on the “Next” option in the upper right-hand corner of your mobile screen. It will enable video sharing. ![share youtube video on facebook using mobile](https://images.wondershare.com/filmora/article-images/2021/share-youtube-video-on-facebook-3.png) Step 6\. Then choose the YouTube video’s post destination to your Facebook. It could be shared on your timeline, story, or a Facebook group’s page. Step 7\. Finally, click on the “Share” tab to make your video viewable on Facebook. ![how to share youtube video on facebook using mobile](https://images.wondershare.com/filmora/article-images/2021/share-youtube-video-on-facebook-4.png) #### How to post a YouTube video on Facebook Easily post your YouTube video on Facebook and let viewers access them directly from your Facebook feed. By this, your fans don’t have to click on other tabs but will access the videos directly. Step 1\. Copy the YouTube video’s link First, go to your YouTube channel and copy the video link that you want to post to Facebook. You can as well copy the embed code. Step 2\. Embed the video link you copied This link should be embedded into a Facebook post. Do this by first logging into your Facebook account. Then go to the top of your “Facebook News Feed” and click the “What’s on your mind” box. Step 3\. Paste your link Right-click on the “What’s on your mind” box, then select the “Paste” option. Step 4\. Preview video Facebook will let you preview the video you just posted. Check whether you have pasted the right video before you post it. Step 5\. Post your video Now, scroll down and click on the “Post” tab. You can also add a message to your post. Just place a cursor after the video URL and hit the “Enter” key on your keyboard. Finally, scroll down and hit the “Post” tab to make your video public on Facebook. ## Extra Tip: Facebook Video Tips for more Views and Shares You have to play your cards well when it comes to posting and sharing your videos on Facebook. These tips are all you need. #### \- Catch viewer’s attention within the shortest time possible Here, your main aim is to convince your viewers. So, don’t let them spend so much time before you catch their attention. You can bring up a point about some latest news or adventures that let your viewers connect immediately. #### \- Add captions to the video It is not necessarily possible that viewers will watch your videos with the sound on. Some like it when it’s silent and might disable the sound auto-play. Add some captions so that viewers will understand your video, even on silent mode. #### \- Emphasize on one key-point Focus on one key point so that your viewers are not swayed away. Your video is highly sharable if it is easy to understand. #### \- Add a Call To Action Including a call-to-action will encourage your viewers to subscribe to your channel. Ensure you include it at the end of your video to tell viewers what to do next. You could also include a link to your blog post to let your viewers read and find more content from your other channels. #### \- Facebook ads can make a great difference Facebook is a great place for running ads that reach a wider audience. Adverts are great ways to target a specific audience. They explain your products and services more straightforwardly. #### \- Embed your videos on blog posts Numerous people get to access guest posts and blog posts. You can embed your Facebook videos on such posts to reach more people. Just get the embed code from your video, then copy and paste it to a guest or blog post. ## Frequently Asked Question about Facebook video Both viewers and content creators have a few concerns about YouTube and Facebook videos. Here are some frequently asked questions that will be of benefit to you. #### 1) Is it legal to share YouTube videos? YouTube is just one platform where content creators showcase their productions. Yes, it is legal to share your content on other forums like Facebook, Twitter, Instagram, etc. #### 2) What is the best time to post to your Facebook page? The best time to post on a Facebook page depends on your time zone. Generally, viewers access Facebook late in the evening and early in the night. Perhaps they are off work and now want to relax by checking the day’s updates. #### 3) What are Facebook business accounts and personal accounts? Facebook business accounts are designed for users who want to use Facebook to administer their pages and advert campaigns. This account cannot be found in searching or receiving friend request apps. Nonetheless, personal accounts are used at basic and casual levels. You can search for friends and send requests. Personal accounts are also easy to manage. #### 4) Can I mobilize people to share my posted content on Facebook? Yes, it is possible to let others share what you have posted. Just ensure they know your intention by constant reminders. Some popular ways that are proven to be effective include the use of “Call to Action,” using an image or video with your Facebook status update and offering some incentive to your fans for sharing. #### 5) Does the quality of my YouTube content drop when I share it with Facebook? Of course not! What you pull from your YouTube channel is the kind of video that will be watched from Facebook. The quality cannot deteriorate. However, it is good to ensure you compose quality videos on YouTube before sharing them. Several video editing apps like Filmora can help you compose quality videos with high resolution. ## Conclusion ● Facebook is a great platform that is accessed by a wide audience. More so, you can share your content from other platforms easily. The article has covered how to share YouTube videos on Facebook and hook your audience. You can use your computer or share directly from your mobile device in simple steps. It is also better to play some tricks on your effort to reach a wider audience. These include a CTA, embedding your Facebook videos to blogs posts, among other options. <ins class="adsbygoogle" style="display:block" data-ad-format="autorelaxed" data-ad-client="ca-pub-7571918770474297" data-ad-slot="1223367746"></ins> <ins class="adsbygoogle" style="display:block" data-ad-format="autorelaxed" data-ad-client="ca-pub-7571918770474297" data-ad-slot="1223367746"></ins> ## Wander in Wealthy Web Words Worlds # Best Free YouTube Comment Finder You Should Try ![author avatar](https://images.wondershare.com/filmora/article-images/richard-bennett.jpg) ##### Richard Bennett Mar 27, 2024• Proven solutions Are you trying to make more people notice your YouTube video? According to surveys, YouTube is the second most popular search engine after Google, with more than 100 hours of video uploaded every minute. _For a YouTube influencer, comments play a crucial role, and so is comment modification._ Now, YouTube has not yet come up with a complete comment modification kit. With the existing tools and free comment finder applications combined, it has become easier to remove improper, unprofessional or offensive comments and engage with genuine followers on YouTube. This thread is a guide for selecting the best YouTube comment finder and a tutorial to use existing YouTube tools to control comments. ## Part 1: Best Free YouTube Comments Finder YouTube Comment Finder is an SEO feature that allows you to look at the best catchphrases for any mainstream YouTube video. Here are some of the best apps that offer the feature. 1. ### YTComment Finder YT Comment Finder is one of the most user-friendly and straightforward comment finder tools available on the internet. It is free to use and produces incredible results. Let us see how it works. * To visit the website, click on the link below <https://ytcomment.kmcat.uk/> * A search bar will be visible on the homepage. You can enter the title of the video you wish to search comments for, or the URL of the YouTube channel or a video URL, and then click the Search ![YTComment Finder interface](https://images.wondershare.com/filmora/article-images/ytcomment-youtube-comment-finder.jpg) * In the next step, you will find a complete list of videos with the same title. Choose your video and click on Search This Video**.** * A new search bar will appear for any comments you choose to look up. ![YTComment Finder search feature](https://images.wondershare.com/filmora/article-images/ytcomment-comment-search.jpg) With YTComment, you can see the basic information about the YouTube video or channel, and to find a comment, all you have to do is type in a word you want to search, and you'll get a list of all the comments relevant to that term or its synonyms as well. ### 2\. YouTube First Comment Finder Although YouTube has settings to know about the first comment in a video, that is only accessible to the creator and is a big burden process. With YouTube First Comment Finder, you're just a click away. * Open the website through this link <https://first-comment.com/> * Paste the URL of your YouTube video in the search box. Click on the FIND There you go! The name of the first commenter of the video will come right in front of you, and you can even see what the comment is and the date of commenting. * **Unique Feature:** This website comes with a tutorial and you can find out the first comment of the YouTube quickly with it. However, the feature of this tool is limited. ### 3\. Hadzy It is one of the most user-friendly and ad-free random comment pickers available for YouTube. Hadzy is quick and can handle more comments than other sites. Hadzy YouTube comment picker is popular among most of the Tubers. * To open Hadzy, click on the link <https://hadzy.com/> * Simply copy and paste the YouTube video's URL into the homepage's search bar. * A pop-up will appear with all the details about the video. You just need to click on Load Data. ![Hadzy YouTube comment search feature](https://images.wondershare.com/filmora/article-images/hadzy-youtube-comment-finder.jpg) * In the next step, you will be redirected to another pop-up with two buttons- 'View Comments' and 'View Statistics.' Click on View Comments to check the first, second and all the other comments in ascending order. * **Unique feature 1:** By clicking the View Statistics button, you can get a track of the popular words used in the comment section and the top questions asked by your followers. * **Unique feature 2:** Along with the comment, details of the user, time of commenting, and many more things can be extracted from Hadzy. ## **Part 2:** **How to Find the First Comments You Have Posted on YouTube?** There are times when you regret what you've commented on in the past or wish to go back and look up your first message on YouTube. However, it is not always possible to recall the channel or video where you left the comment. So, is there a way or a tool that can make it just a doodle? Certainly yes. Did you know that you can check for any previous comments you've made on YouTube regardless of how old it is? Everything you have to do now follows the steps below. For the following methods, it is preferable to use a browser rather than the YouTube App. * Go to the homepage of YouTube. At the top left corner, Click on the three-lined icon. Click on History next. You will be redirected to your account's history section. * At the right corner, choose History type as 'community.' Below that, click on the 'Comments' option. Finally, a new tab would open with all your YouTube comment history. ![ YouTube comment history search ](https://images.wondershare.com/filmora/article-images/youtube-history-comments-menu.jpg) By these basic steps, enjoy editing or deleting your comments and replies directly on YouTube! However, you will have to scroll down a long way before you hit the end to see your first comment posted on YouTube. ## Part 3: How to Find the Latest Comments you have received on YouTube? You do not get notifications about comments left on your YouTube videos at times. Mostly, it's due to your notification preferences. When you enable comment notifications, you'll be informed of all the latest comments on your videos. And this, in turn, allows you to keep track of your followers and engage with them more easily. YouTube is a vast platform, and there are quite a few modifications hidden everywhere. To know everything is not always possible. Now that you are here let's see how to locate the most recent comment you've got on YouTube. **Step 1: Enable Comment Notifications** * Open the homepage of YouTube, scroll down to 'Settings' and click on it. You will be redirected to the Setting page. * From the bar in the left corner, select **Notifications** and scroll down and enable 'Activity on my Channel.' These steps are convenient both for pc as well as a mobile app. Just follow three steps, Setting-Notifications-Activity on your Channel. **Step 2: Check the Notification Bar** * Click on the bell icon at the top right corner and there you would receive notifications regarding all the comment activities. Click on the particular notification to go to that comment. ## Bonus: How to Change the Comments View Order? Did you know you can also customize your comment section as per your need? On the watch page for your video, you can rearrange the order of the comments. You may sort the comments by top comments or by date added. It's just simple steps ahead. * First of all, you need to sign in to YouTube Studio: <http://studio.youtube.com>, * From the left bar, select Content, click a video's thumbnail, and click on Show More in video details page. ![ YouTube comment and rating settings ](https://images.wondershare.com/filmora/article-images/set-up-comment-ratings.jpg) * Under 'Comments and ratings,' select Sort by, and then choose between "Top" and "Newest." * Save the changes, and you are done! **Conclusion** YouTube comments play a predominant role in handling your business as a YouTuber. It's reasonable to believe that the search algorithm considers comments on your videos to be a significant indicator of their efficiency, and therefore gives them higher rankings for specific searches. The higher your video content's exposure on the internet, the more you'll be included in YouTube or Google searches. YouTube Comments Finder helps you keep track of the good and bad comments in your videos and definitely helps improve the SEO of your Channel. Thanks to YouTube's advanced tools and websites like Hadzy, YouTube comment Finder, YT Comment Finder and YouTube First Comment Finder, managing third-party interaction is a lot simpler today. ![author avatar](https://images.wondershare.com/filmora/article-images/richard-bennett.jpg) Richard Bennett Richard Bennett is a writer and a lover of all things video. Follow @Richard Bennett ##### Richard Bennett Mar 27, 2024• Proven solutions Are you trying to make more people notice your YouTube video? According to surveys, YouTube is the second most popular search engine after Google, with more than 100 hours of video uploaded every minute. _For a YouTube influencer, comments play a crucial role, and so is comment modification._ Now, YouTube has not yet come up with a complete comment modification kit. With the existing tools and free comment finder applications combined, it has become easier to remove improper, unprofessional or offensive comments and engage with genuine followers on YouTube. This thread is a guide for selecting the best YouTube comment finder and a tutorial to use existing YouTube tools to control comments. ## Part 1: Best Free YouTube Comments Finder YouTube Comment Finder is an SEO feature that allows you to look at the best catchphrases for any mainstream YouTube video. Here are some of the best apps that offer the feature. 1. ### YTComment Finder YT Comment Finder is one of the most user-friendly and straightforward comment finder tools available on the internet. It is free to use and produces incredible results. Let us see how it works. * To visit the website, click on the link below <https://ytcomment.kmcat.uk/> * A search bar will be visible on the homepage. You can enter the title of the video you wish to search comments for, or the URL of the YouTube channel or a video URL, and then click the Search ![YTComment Finder interface](https://images.wondershare.com/filmora/article-images/ytcomment-youtube-comment-finder.jpg) * In the next step, you will find a complete list of videos with the same title. Choose your video and click on Search This Video**.** * A new search bar will appear for any comments you choose to look up. ![YTComment Finder search feature](https://images.wondershare.com/filmora/article-images/ytcomment-comment-search.jpg) With YTComment, you can see the basic information about the YouTube video or channel, and to find a comment, all you have to do is type in a word you want to search, and you'll get a list of all the comments relevant to that term or its synonyms as well. ### 2\. YouTube First Comment Finder Although YouTube has settings to know about the first comment in a video, that is only accessible to the creator and is a big burden process. With YouTube First Comment Finder, you're just a click away. * Open the website through this link <https://first-comment.com/> * Paste the URL of your YouTube video in the search box. Click on the FIND There you go! The name of the first commenter of the video will come right in front of you, and you can even see what the comment is and the date of commenting. * **Unique Feature:** This website comes with a tutorial and you can find out the first comment of the YouTube quickly with it. However, the feature of this tool is limited. ### 3\. Hadzy It is one of the most user-friendly and ad-free random comment pickers available for YouTube. Hadzy is quick and can handle more comments than other sites. Hadzy YouTube comment picker is popular among most of the Tubers. * To open Hadzy, click on the link <https://hadzy.com/> * Simply copy and paste the YouTube video's URL into the homepage's search bar. * A pop-up will appear with all the details about the video. You just need to click on Load Data. ![Hadzy YouTube comment search feature](https://images.wondershare.com/filmora/article-images/hadzy-youtube-comment-finder.jpg) * In the next step, you will be redirected to another pop-up with two buttons- 'View Comments' and 'View Statistics.' Click on View Comments to check the first, second and all the other comments in ascending order. * **Unique feature 1:** By clicking the View Statistics button, you can get a track of the popular words used in the comment section and the top questions asked by your followers. * **Unique feature 2:** Along with the comment, details of the user, time of commenting, and many more things can be extracted from Hadzy. ## **Part 2:** **How to Find the First Comments You Have Posted on YouTube?** There are times when you regret what you've commented on in the past or wish to go back and look up your first message on YouTube. However, it is not always possible to recall the channel or video where you left the comment. So, is there a way or a tool that can make it just a doodle? Certainly yes. Did you know that you can check for any previous comments you've made on YouTube regardless of how old it is? Everything you have to do now follows the steps below. For the following methods, it is preferable to use a browser rather than the YouTube App. * Go to the homepage of YouTube. At the top left corner, Click on the three-lined icon. Click on History next. You will be redirected to your account's history section. * At the right corner, choose History type as 'community.' Below that, click on the 'Comments' option. Finally, a new tab would open with all your YouTube comment history. ![ YouTube comment history search ](https://images.wondershare.com/filmora/article-images/youtube-history-comments-menu.jpg) By these basic steps, enjoy editing or deleting your comments and replies directly on YouTube! However, you will have to scroll down a long way before you hit the end to see your first comment posted on YouTube. ## Part 3: How to Find the Latest Comments you have received on YouTube? You do not get notifications about comments left on your YouTube videos at times. Mostly, it's due to your notification preferences. When you enable comment notifications, you'll be informed of all the latest comments on your videos. And this, in turn, allows you to keep track of your followers and engage with them more easily. YouTube is a vast platform, and there are quite a few modifications hidden everywhere. To know everything is not always possible. Now that you are here let's see how to locate the most recent comment you've got on YouTube. **Step 1: Enable Comment Notifications** * Open the homepage of YouTube, scroll down to 'Settings' and click on it. You will be redirected to the Setting page. * From the bar in the left corner, select **Notifications** and scroll down and enable 'Activity on my Channel.' These steps are convenient both for pc as well as a mobile app. Just follow three steps, Setting-Notifications-Activity on your Channel. **Step 2: Check the Notification Bar** * Click on the bell icon at the top right corner and there you would receive notifications regarding all the comment activities. Click on the particular notification to go to that comment. ## Bonus: How to Change the Comments View Order? Did you know you can also customize your comment section as per your need? On the watch page for your video, you can rearrange the order of the comments. You may sort the comments by top comments or by date added. It's just simple steps ahead. * First of all, you need to sign in to YouTube Studio: <http://studio.youtube.com>, * From the left bar, select Content, click a video's thumbnail, and click on Show More in video details page. ![ YouTube comment and rating settings ](https://images.wondershare.com/filmora/article-images/set-up-comment-ratings.jpg) * Under 'Comments and ratings,' select Sort by, and then choose between "Top" and "Newest." * Save the changes, and you are done! **Conclusion** YouTube comments play a predominant role in handling your business as a YouTuber. It's reasonable to believe that the search algorithm considers comments on your videos to be a significant indicator of their efficiency, and therefore gives them higher rankings for specific searches. The higher your video content's exposure on the internet, the more you'll be included in YouTube or Google searches. YouTube Comments Finder helps you keep track of the good and bad comments in your videos and definitely helps improve the SEO of your Channel. Thanks to YouTube's advanced tools and websites like Hadzy, YouTube comment Finder, YT Comment Finder and YouTube First Comment Finder, managing third-party interaction is a lot simpler today. ![author avatar](https://images.wondershare.com/filmora/article-images/richard-bennett.jpg) Richard Bennett Richard Bennett is a writer and a lover of all things video. Follow @Richard Bennett ##### Richard Bennett Mar 27, 2024• Proven solutions Are you trying to make more people notice your YouTube video? According to surveys, YouTube is the second most popular search engine after Google, with more than 100 hours of video uploaded every minute. _For a YouTube influencer, comments play a crucial role, and so is comment modification._ Now, YouTube has not yet come up with a complete comment modification kit. With the existing tools and free comment finder applications combined, it has become easier to remove improper, unprofessional or offensive comments and engage with genuine followers on YouTube. This thread is a guide for selecting the best YouTube comment finder and a tutorial to use existing YouTube tools to control comments. ## Part 1: Best Free YouTube Comments Finder YouTube Comment Finder is an SEO feature that allows you to look at the best catchphrases for any mainstream YouTube video. Here are some of the best apps that offer the feature. 1. ### YTComment Finder YT Comment Finder is one of the most user-friendly and straightforward comment finder tools available on the internet. It is free to use and produces incredible results. Let us see how it works. * To visit the website, click on the link below <https://ytcomment.kmcat.uk/> * A search bar will be visible on the homepage. You can enter the title of the video you wish to search comments for, or the URL of the YouTube channel or a video URL, and then click the Search ![YTComment Finder interface](https://images.wondershare.com/filmora/article-images/ytcomment-youtube-comment-finder.jpg) * In the next step, you will find a complete list of videos with the same title. Choose your video and click on Search This Video**.** * A new search bar will appear for any comments you choose to look up. ![YTComment Finder search feature](https://images.wondershare.com/filmora/article-images/ytcomment-comment-search.jpg) With YTComment, you can see the basic information about the YouTube video or channel, and to find a comment, all you have to do is type in a word you want to search, and you'll get a list of all the comments relevant to that term or its synonyms as well. ### 2\. YouTube First Comment Finder Although YouTube has settings to know about the first comment in a video, that is only accessible to the creator and is a big burden process. With YouTube First Comment Finder, you're just a click away. * Open the website through this link <https://first-comment.com/> * Paste the URL of your YouTube video in the search box. Click on the FIND There you go! The name of the first commenter of the video will come right in front of you, and you can even see what the comment is and the date of commenting. * **Unique Feature:** This website comes with a tutorial and you can find out the first comment of the YouTube quickly with it. However, the feature of this tool is limited. ### 3\. Hadzy It is one of the most user-friendly and ad-free random comment pickers available for YouTube. Hadzy is quick and can handle more comments than other sites. Hadzy YouTube comment picker is popular among most of the Tubers. * To open Hadzy, click on the link <https://hadzy.com/> * Simply copy and paste the YouTube video's URL into the homepage's search bar. * A pop-up will appear with all the details about the video. You just need to click on Load Data. ![Hadzy YouTube comment search feature](https://images.wondershare.com/filmora/article-images/hadzy-youtube-comment-finder.jpg) * In the next step, you will be redirected to another pop-up with two buttons- 'View Comments' and 'View Statistics.' Click on View Comments to check the first, second and all the other comments in ascending order. * **Unique feature 1:** By clicking the View Statistics button, you can get a track of the popular words used in the comment section and the top questions asked by your followers. * **Unique feature 2:** Along with the comment, details of the user, time of commenting, and many more things can be extracted from Hadzy. ## **Part 2:** **How to Find the First Comments You Have Posted on YouTube?** There are times when you regret what you've commented on in the past or wish to go back and look up your first message on YouTube. However, it is not always possible to recall the channel or video where you left the comment. So, is there a way or a tool that can make it just a doodle? Certainly yes. Did you know that you can check for any previous comments you've made on YouTube regardless of how old it is? Everything you have to do now follows the steps below. For the following methods, it is preferable to use a browser rather than the YouTube App. * Go to the homepage of YouTube. At the top left corner, Click on the three-lined icon. Click on History next. You will be redirected to your account's history section. * At the right corner, choose History type as 'community.' Below that, click on the 'Comments' option. Finally, a new tab would open with all your YouTube comment history. ![ YouTube comment history search ](https://images.wondershare.com/filmora/article-images/youtube-history-comments-menu.jpg) By these basic steps, enjoy editing or deleting your comments and replies directly on YouTube! However, you will have to scroll down a long way before you hit the end to see your first comment posted on YouTube. ## Part 3: How to Find the Latest Comments you have received on YouTube? You do not get notifications about comments left on your YouTube videos at times. Mostly, it's due to your notification preferences. When you enable comment notifications, you'll be informed of all the latest comments on your videos. And this, in turn, allows you to keep track of your followers and engage with them more easily. YouTube is a vast platform, and there are quite a few modifications hidden everywhere. To know everything is not always possible. Now that you are here let's see how to locate the most recent comment you've got on YouTube. **Step 1: Enable Comment Notifications** * Open the homepage of YouTube, scroll down to 'Settings' and click on it. You will be redirected to the Setting page. * From the bar in the left corner, select **Notifications** and scroll down and enable 'Activity on my Channel.' These steps are convenient both for pc as well as a mobile app. Just follow three steps, Setting-Notifications-Activity on your Channel. **Step 2: Check the Notification Bar** * Click on the bell icon at the top right corner and there you would receive notifications regarding all the comment activities. Click on the particular notification to go to that comment. ## Bonus: How to Change the Comments View Order? Did you know you can also customize your comment section as per your need? On the watch page for your video, you can rearrange the order of the comments. You may sort the comments by top comments or by date added. It's just simple steps ahead. * First of all, you need to sign in to YouTube Studio: <http://studio.youtube.com>, * From the left bar, select Content, click a video's thumbnail, and click on Show More in video details page. ![ YouTube comment and rating settings ](https://images.wondershare.com/filmora/article-images/set-up-comment-ratings.jpg) * Under 'Comments and ratings,' select Sort by, and then choose between "Top" and "Newest." * Save the changes, and you are done! **Conclusion** YouTube comments play a predominant role in handling your business as a YouTuber. It's reasonable to believe that the search algorithm considers comments on your videos to be a significant indicator of their efficiency, and therefore gives them higher rankings for specific searches. The higher your video content's exposure on the internet, the more you'll be included in YouTube or Google searches. YouTube Comments Finder helps you keep track of the good and bad comments in your videos and definitely helps improve the SEO of your Channel. Thanks to YouTube's advanced tools and websites like Hadzy, YouTube comment Finder, YT Comment Finder and YouTube First Comment Finder, managing third-party interaction is a lot simpler today. ![author avatar](https://images.wondershare.com/filmora/article-images/richard-bennett.jpg) Richard Bennett Richard Bennett is a writer and a lover of all things video. Follow @Richard Bennett ##### Richard Bennett Mar 27, 2024• Proven solutions Are you trying to make more people notice your YouTube video? According to surveys, YouTube is the second most popular search engine after Google, with more than 100 hours of video uploaded every minute. _For a YouTube influencer, comments play a crucial role, and so is comment modification._ Now, YouTube has not yet come up with a complete comment modification kit. With the existing tools and free comment finder applications combined, it has become easier to remove improper, unprofessional or offensive comments and engage with genuine followers on YouTube. This thread is a guide for selecting the best YouTube comment finder and a tutorial to use existing YouTube tools to control comments. ## Part 1: Best Free YouTube Comments Finder YouTube Comment Finder is an SEO feature that allows you to look at the best catchphrases for any mainstream YouTube video. Here are some of the best apps that offer the feature. 1. ### YTComment Finder YT Comment Finder is one of the most user-friendly and straightforward comment finder tools available on the internet. It is free to use and produces incredible results. Let us see how it works. * To visit the website, click on the link below <https://ytcomment.kmcat.uk/> * A search bar will be visible on the homepage. You can enter the title of the video you wish to search comments for, or the URL of the YouTube channel or a video URL, and then click the Search ![YTComment Finder interface](https://images.wondershare.com/filmora/article-images/ytcomment-youtube-comment-finder.jpg) * In the next step, you will find a complete list of videos with the same title. Choose your video and click on Search This Video**.** * A new search bar will appear for any comments you choose to look up. ![YTComment Finder search feature](https://images.wondershare.com/filmora/article-images/ytcomment-comment-search.jpg) With YTComment, you can see the basic information about the YouTube video or channel, and to find a comment, all you have to do is type in a word you want to search, and you'll get a list of all the comments relevant to that term or its synonyms as well. ### 2\. YouTube First Comment Finder Although YouTube has settings to know about the first comment in a video, that is only accessible to the creator and is a big burden process. With YouTube First Comment Finder, you're just a click away. * Open the website through this link <https://first-comment.com/> * Paste the URL of your YouTube video in the search box. Click on the FIND There you go! The name of the first commenter of the video will come right in front of you, and you can even see what the comment is and the date of commenting. * **Unique Feature:** This website comes with a tutorial and you can find out the first comment of the YouTube quickly with it. However, the feature of this tool is limited. ### 3\. Hadzy It is one of the most user-friendly and ad-free random comment pickers available for YouTube. Hadzy is quick and can handle more comments than other sites. Hadzy YouTube comment picker is popular among most of the Tubers. * To open Hadzy, click on the link <https://hadzy.com/> * Simply copy and paste the YouTube video's URL into the homepage's search bar. * A pop-up will appear with all the details about the video. You just need to click on Load Data. ![Hadzy YouTube comment search feature](https://images.wondershare.com/filmora/article-images/hadzy-youtube-comment-finder.jpg) * In the next step, you will be redirected to another pop-up with two buttons- 'View Comments' and 'View Statistics.' Click on View Comments to check the first, second and all the other comments in ascending order. * **Unique feature 1:** By clicking the View Statistics button, you can get a track of the popular words used in the comment section and the top questions asked by your followers. * **Unique feature 2:** Along with the comment, details of the user, time of commenting, and many more things can be extracted from Hadzy. ## **Part 2:** **How to Find the First Comments You Have Posted on YouTube?** There are times when you regret what you've commented on in the past or wish to go back and look up your first message on YouTube. However, it is not always possible to recall the channel or video where you left the comment. So, is there a way or a tool that can make it just a doodle? Certainly yes. Did you know that you can check for any previous comments you've made on YouTube regardless of how old it is? Everything you have to do now follows the steps below. For the following methods, it is preferable to use a browser rather than the YouTube App. * Go to the homepage of YouTube. At the top left corner, Click on the three-lined icon. Click on History next. You will be redirected to your account's history section. * At the right corner, choose History type as 'community.' Below that, click on the 'Comments' option. Finally, a new tab would open with all your YouTube comment history. ![ YouTube comment history search ](https://images.wondershare.com/filmora/article-images/youtube-history-comments-menu.jpg) By these basic steps, enjoy editing or deleting your comments and replies directly on YouTube! However, you will have to scroll down a long way before you hit the end to see your first comment posted on YouTube. ## Part 3: How to Find the Latest Comments you have received on YouTube? You do not get notifications about comments left on your YouTube videos at times. Mostly, it's due to your notification preferences. When you enable comment notifications, you'll be informed of all the latest comments on your videos. And this, in turn, allows you to keep track of your followers and engage with them more easily. YouTube is a vast platform, and there are quite a few modifications hidden everywhere. To know everything is not always possible. Now that you are here let's see how to locate the most recent comment you've got on YouTube. **Step 1: Enable Comment Notifications** * Open the homepage of YouTube, scroll down to 'Settings' and click on it. You will be redirected to the Setting page. * From the bar in the left corner, select **Notifications** and scroll down and enable 'Activity on my Channel.' These steps are convenient both for pc as well as a mobile app. Just follow three steps, Setting-Notifications-Activity on your Channel. **Step 2: Check the Notification Bar** * Click on the bell icon at the top right corner and there you would receive notifications regarding all the comment activities. Click on the particular notification to go to that comment. ## Bonus: How to Change the Comments View Order? Did you know you can also customize your comment section as per your need? On the watch page for your video, you can rearrange the order of the comments. You may sort the comments by top comments or by date added. It's just simple steps ahead. * First of all, you need to sign in to YouTube Studio: <http://studio.youtube.com>, * From the left bar, select Content, click a video's thumbnail, and click on Show More in video details page. ![ YouTube comment and rating settings ](https://images.wondershare.com/filmora/article-images/set-up-comment-ratings.jpg) * Under 'Comments and ratings,' select Sort by, and then choose between "Top" and "Newest." * Save the changes, and you are done! **Conclusion** YouTube comments play a predominant role in handling your business as a YouTuber. It's reasonable to believe that the search algorithm considers comments on your videos to be a significant indicator of their efficiency, and therefore gives them higher rankings for specific searches. The higher your video content's exposure on the internet, the more you'll be included in YouTube or Google searches. YouTube Comments Finder helps you keep track of the good and bad comments in your videos and definitely helps improve the SEO of your Channel. Thanks to YouTube's advanced tools and websites like Hadzy, YouTube comment Finder, YT Comment Finder and YouTube First Comment Finder, managing third-party interaction is a lot simpler today. ![author avatar](https://images.wondershare.com/filmora/article-images/richard-bennett.jpg) Richard Bennett Richard Bennett is a writer and a lover of all things video. Follow @Richard Bennett <ins class="adsbygoogle" style="display:block" data-ad-format="autorelaxed" data-ad-client="ca-pub-7571918770474297" data-ad-slot="1223367746"></ins> <ins class="adsbygoogle" style="display:block" data-ad-client="ca-pub-7571918770474297" data-ad-slot="8358498916" data-ad-format="auto" data-full-width-responsive="true"></ins>
import React, { useState, useEffect } from "react"; import Input from "../../components/input/Input"; import Button from "../../components/button/Button"; import "./login.css"; import { Link } from "react-router-dom"; import { getAuth, signInWithEmailAndPassword } from "firebase/auth"; import { logIn } from "../../redux/user/userActions"; import { connect } from "react-redux"; import { useNavigate } from "react-router-dom"; function Login({ Login }) { const [state, setState] = useState({ password: "", email: "", error: "", submitting: false, success: "", }); const { password, email, error, submitting, success } = state; const navigate = useNavigate(); const setInputs = (e) => { setState({ ...state, [e.target.name]: e.target.value }); }; const handleLogin = async (e) => { e.preventDefault(); if (email == "" || password == "") { setState({ ...state, error: "Please make sure all the fields are filled", success: "", }); } else { try { setState({ ...state, error: "", submitting: true, }); const auth = getAuth(); const user = await signInWithEmailAndPassword(auth, email, password); setState({ ...state, password: "", email: "", error: "", submitting: false, success: "Logged In Successfully. Redirecting you to chat...", }); Login(user.user.uid); setTimeout(() => { navigate("/"); }, 2000); } catch (error) { if (error.code === "auth/invalid-login-credentials") { setState({ ...state, error: "Invalid Login Credentials", success: "", }); } else if (error.code === "auth/weak-password") { setState({ ...state, error: "Password should be at least 6 characters.", success: "", }); } else if (error.code === "auth/too-many-requests") { setState({ ...state, error: "Access to this account has been temporarily disabled due to many failed login attempts. You can immediately restore it by resetting your password or you can try again later. ", success: "", }); } else { setState({ ...state, error: error.message, success: "" }); } } } }; return ( <> <div className="container"> <div className="row"> <div className="col-md-5 mx-auto "> <div className="form shadow"> <form onSubmit={handleLogin} action="" method="POST"> <div className="row"> <div className="col-12"> <div className="form-heading">Login</div> </div> </div> <div className="row"> <div className="col-12"> {error.length > 0 ? ( <div className="alert alert-danger ">{error}</div> ) : ( <div></div> )} {success.length > 0 ? ( <div className="alert alert-success">{success}</div> ) : ( <div></div> )} </div> </div> <div className="row"> <div className="col-12"> <Input label="Email" type="email" onChange={setInputs} value={email} name="email" /> </div> </div> <div className="row"> <div className="col-12"> <Input label="Password" type="password" onChange={setInputs} value={password} name="password" /> </div> </div> <div className="row pe-0"> <div className="col-12 pe-0"> {submitting ? ( <Button type="submit" value="Logging in, Please wait ..." disabled="disabled" className="disabled" /> ) : ( <Button type="submit" value="Login" /> )} </div> </div> <div className="row"> <div className="col-12 text-end"> <p> New to chat? <Link to="/register">Register</Link> </p> </div> </div> </form> </div> </div> </div> </div> </> ); } const mapDispatchToProps = (dispatch) => { return { Login: (data) => { dispatch(logIn(data)); }, }; }; export default connect(null, mapDispatchToProps)(Login);
import { useContext, createContext, useState, useEffect} from "react"; const ThemeContext = createContext(); export default function ThemeContextProvider({ children }) { const [theme, setTheme] = useState( localStorage.getItem("theme") !=="dark" ? "light" : "dark"); useEffect(() => { const root = window.document.documentElement; const removeOldTheme = theme === "dark" ? "light" : "dark"; root.classList.remove(removeOldTheme); root.classList.add(theme); localStorage.setItem("theme", theme); }, [theme]); return ( <ThemeContext.Provider value={{ theme, setTheme }}> {children} </ThemeContext.Provider> ) } export function useTheme() { return useContext(ThemeContext); }
package com.ea.ai.rag.dms.presentation.api; import com.ea.ai.rag.dms.application.service.AiServiceClient; import com.ea.ai.rag.dms.domain.dto.Document; import com.ea.ai.rag.dms.domain.vo.ai.Answer; import com.ea.ai.rag.dms.domain.vo.ai.Question; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.media.Content; import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.tags.Tag; import jakarta.validation.Valid; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; @Tag(name = "AiServiceClient", description = "API gateway for the AI Service Client") @RestController public class AiServiceClientRestController { public static final Logger logger = LoggerFactory.getLogger(AiServiceClientRestController.class); AiServiceClient aiServiceClient; public AiServiceClientRestController(AiServiceClient aiServiceClient) { this.aiServiceClient = aiServiceClient; } @Operation( summary = "Ask a relevant question", description = "Ask a relevant question", responses = { @ApiResponse(responseCode = "200", description = "ok", content = @Content( schema = @Schema(implementation = Answer.class) )) } ) @PostMapping(value = "/v1/document/ask", produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<Answer> askQuestion(@RequestBody @Valid Question question) { return new ResponseEntity<>(aiServiceClient.askQuestion(question), HttpStatus.OK); } @Operation( summary = "Add document to vector store", description = "Add document to vector store", responses = { @ApiResponse(responseCode = "200", description = "ok") } ) @PostMapping(value = "/v1/document", consumes = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<Void> addDocumentToVectorStore(@RequestBody @Valid Document document) { aiServiceClient.addDocumentToVectorStore(document); return new ResponseEntity<>(HttpStatus.OK); } }
# Required library library(sparklyr) library(mongolite) library(tm) library(ggplot2) library(dplyr) # call the spark Sys.setenv(SPARK_HOME ='/home/hduser/Desktop/spark-2.4.5') sc <- spark_connect(master = "local") # retrive the collection from the mongo ukdb <- mongo(collection = "uktweets", db = "ukdata", url = "mongodb://localhost") usadb <- mongo(collection = "usatweets", db = "usadata", url = "mongodb://localhost") canadadb <- mongo(collection = "canadatweets", db = "canadadata", url = "mongodb://localhost") #load data into spark memory datacollect<-sdf_copy_to(sc,as.data.frame(ukdb$find(limit = 10000)%>%select(text)),overwrite = T) datacollect2<-sdf_copy_to(sc,as.data.frame(usadb$find(limit = 10000)%>%select(text)),overwrite = T) datacollect3<-sdf_copy_to(sc,as.data.frame(canadadb$find(limit = 10000)%>%select(text)),overwrite = T) pdata<-datacollect pdata2<-datacollect2 pdata3<-datacollect3 # data extracting and cleaning New <- pdata%>%collect() New$text=gsub("http\\w+", "", New$text) New$text=gsub("&amp", "", New$text) New$text = gsub("(RT|via)((?:\\b\\W*@\\w+)+)", "", New$text) New$text = gsub("@\\w+", "", New$text) New$text = gsub("[[:punct:]]", "", New$text) New$text = gsub("[[:digit:]]", "", New$text) New$text = gsub("[ \t]{2,}", "", New$text) New$text = gsub("^\\s+|\\s+$", "", New$text) New$text <- iconv(New$text, "UTF-8", "ASCII", sub="") New$text<- removeWords(New$text, stopwords("en")) New2 <- pdata2%>%collect() New2$text=gsub("http\\w+", "", New2$text) New2$text=gsub("&amp", "", New2$text) New2$text = gsub("(RT|via)((?:\\b\\W*@\\w+)+)", "", New2$text) New2$text = gsub("@\\w+", "", New2$text) New2$text = gsub("[[:punct:]]", "", New2$text) New2$text = gsub("[[:digit:]]", "", New2$text) New2$text = gsub("[ \t]{2,}", "", New2$text) New2$text = gsub("^\\s+|\\s+$", "", New2$text) New2$text <- iconv(New2$text, "UTF-8", "ASCII", sub="") New2$text<- removeWords(New2$text, stopwords("en")) New3 <- pdata3%>%collect() New3$text=gsub("http\\w+", "", New3$text) New3$text=gsub("&amp", "", New3$text) New3$text = gsub("(RT|via)((?:\\b\\W*@\\w+)+)", "", New3$text) New3$text = gsub("@\\w+", "", New3$text) New3$text = gsub("[[:punct:]]", "", New3$text) New3$text = gsub("[[:digit:]]", "", New3$text) New3$text = gsub("[ \t]{2,}", "", New3$text) New3$text = gsub("^\\s+|\\s+$", "", New3$text) New3$text <- iconv(New3$text, "UTF-8", "ASCII", sub="") New3$text<- removeWords(New3$text, stopwords("en")) # lexicon algorithm for sentiment analysis library(syuzhet) # sentiment for UK emotions <- get_nrc_sentiment(New$text) Sentimentscores_new<-data.frame(colSums(emotions[,])) names(Sentimentscores_new)<-"Score" Sentimentscores_new<-cbind("sentiment"=rownames(Sentimentscores_new),Sentimentscores_new) rownames(Sentimentscores_new)<-NULL # sentiment for USA emotions2 <- get_nrc_sentiment(New2$text) Sentimentscores_new2<-data.frame(colSums(emotions2[,])) names(Sentimentscores_new2)<-"Score" Sentimentscores_new2<-cbind("sentiment"=rownames(Sentimentscores_new2),Sentimentscores_new2) rownames(Sentimentscores_new2)<-NULL # sentiment for CANADA emotions3 <- get_nrc_sentiment(New3$text) Sentimentscores_new3<-data.frame(colSums(emotions3[,])) names(Sentimentscores_new3)<-"Score" Sentimentscores_new3<-cbind("sentiment"=rownames(Sentimentscores_new3),Sentimentscores_new3) rownames(Sentimentscores_new3)<-NULL # data can show as a table view View(Sentimentscores_new) View(Sentimentscores_new2) View(Sentimentscores_new3) # sentimenal point insert into new mongo db collection ukdbplot <- mongo(collection = "ukplot", db = "ukdata", url = "mongodb://localhost") usadbplot <- mongo(collection = "usaplot", db = "usadata", url = "mongodb://localhost") canadadbplot <- mongo(collection = "canadaplot", db = "canadadata", url = "mongodb://localhost") # data inserted into the mongodb ukdbplot$insert(Sentimentscores_new) usadbplot$insert(Sentimentscores_new2) canadadbplot$insert(Sentimentscores_new3) # diconnect spark spark_disconnect(sc) source("dtvisualize.R")
<refentry id="dump"> <refnamediv> <refname>DUMP</refname> <refpurpose>Formatted File Data Dump in Hexadecimal and ASCII</refpurpose> </refnamediv> <refsynopsisdiv> <cmdsynopsis> <command>dump</command> <arg choice="opt"> <replaceable>-h -m -x</replaceable> </arg> <arg choice="opt"> <replaceable>path</replaceable> </arg> </cmdsynopsis> </refsynopsisdiv> <refsect1><title>Description</title> <para> This command produces a formatted display of the physical data contents of the path specified which may be a mass storage file or any other I/O device. If a pathlist is omitted, the standard input path is used. The output is written to standard output. This command is commonly used to examine the contents of non-text files. </para> <para> The data is displayed 16 bytes per line in both hexadecimal and ASCII character format. Data bytes that have non-displayable values are represented by periods in the character area. </para> <para> The addresses displayed on the dump are relative to the beginning of the file. Because memory modules are position-independent and stored on files exactly as they exist in memory, the addresses shown on the dump correspond to the relative load addresses of memory-module files. </para> <informaltable frame="none"> <tgroup cols="2"> <colspec colwidth="1in"/> <colspec colwidth="4in"/> <tbody> <row> <entry>-h</entry> <entry>prevent dump from printing its header every 256 bytes</entry> </row> <row> <entry>-m</entry> <entry>names on the command line are modules in memory</entry> </row> <row> <entry>-x</entry> <entry>names on the command line are files relative to the execution directory</entry> </row> </tbody> </tgroup> </informaltable> </refsect1> <refsect1><title>Examples</title> <screen> dump (display keyboard input in hex) dump myfile &gt;/p (dump myfile to printer) dump -m kernel (dump the kernel module in memory) </screen> </refsect1> <refsect1><title>Sample Output</title> <screen> Address 0 1 2 3 4 5 6 7 8 9 A B C D E F 0 2 4 6 8 A C E -------- ---- ---- ---- ---- ---- ---- ---- ---- ---------------- 00000000 87CD 0038 002A P181 2800 2E00 3103 FFE0 .M.8.*q.(...1..' 00000010 0418 0000 0100 0101 0001 1808 180D 1B04 ................ 00000020 0117 0311 0807 1500 002A 5445 S2CD 5343 .........*TERMSC 00000030 C641 4349 C10E 529E FACIA.R. ^ ^ ^ starting data bytes in hexadecimal data bytes in address format ASCII format </screen> </refsect1> </refentry>
import os import pytest from flask_jwt_extended import create_access_token from app import create_app from app.models.patient import db @pytest.fixture(autouse=True) def env_setup(): os.environ['FLASK_ENV'] = 'testing' yield os.environ['FLASK_ENV'] = 'development' @pytest.fixture def app(): app = create_app() with app.app_context(): db.create_all() yield app with app.app_context(): db.session.remove() db.drop_all() @pytest.fixture def client(app): return app.test_client() @pytest.fixture def runner(app): return app.test_cli_runner() @pytest.fixture def headers(app): with app.app_context(): access_token = create_access_token(identity=1) return {'Authorization': 'Bearer ' + access_token}
// ignore_for_file: file_names import 'package:dio/dio.dart'; import 'package:flutter/material.dart'; import 'package:get/get.dart'; import '../model/series.dart'; import 'api.dart'; class CountriesSeriesController extends GetxController { final Dio _dio = Dio(BaseOptions(baseUrl: ApiConstants.baseUrl)); final ScrollController scrollController = ScrollController(); final countriesSeries = <Series>[].obs; // final countriesSeries = <Series>[].obs; var currentCountry = ''.obs; int currentPage = 1; final isLoading = false.obs; CountriesSeriesController(String year) { currentCountry.value = year; scrollController.addListener(_scrollListener); // Tambahkan listener scroll fetchSeriesCountries( currentPage, year); // Pindahkan fetchSeriesCountries ke sini } Future<void> fetchSeriesCountries(int page, String title) async { try { isLoading(true); // Ganti "United States" menjadi "USA" jika title sama dengan "United States" if (title.contains(" ")) { title = title.replaceAll(" ", "-"); } final response = await _dio .get('${ApiConstants.seriesCountriesEndpoint}/$title/$page'); final List<dynamic> data = response.data; final List<Series> newSeries = data.map((item) => Series.fromJson(item)).toList(); if (page == 1) { countriesSeries.assignAll(newSeries); } else { countriesSeries.addAll(newSeries); } } catch (error) { throw Exception('Error fetching latest movies: $error'); } finally { isLoading(false); } } void loadNextPage() { currentPage++; fetchSeriesCountries(currentPage, currentCountry.value); // fetchSeriesGenres(currentPage, currentGenre.value); } void _scrollListener() { if (scrollController.position.pixels == scrollController.position.maxScrollExtent) { // Scroll mencapai akhir halaman, panggil halaman berikutnya loadNextPage(); } } }
import { Component } from "@angular/core"; interface Game { title: string; price: number; img: string; } @Component({ selector: 'su-game', // template: '<h2>This is game component</h2>', templateUrl: './game.component.html', styleUrls: ['./game.component.css'] }) export class GameComponent { shouldPriceBeColorized: boolean = false; games: Game[] = [ { title: 'Minecraft', price: 10, img: 'https://www.minecraft.net/content/dam/games/minecraft/key-art/CC-Update-Part-II_600x360.jpg' }, { title: 'CS:GO', price: 25, img: 'https://estnn.com/wp-content/uploads/2022/05/CS-GO-wallpaper-HD-art_hue3ed7aeab8fceb3ccf3a35de14fc82fb_1114369_1920x1080_resize_q75_lanczos.jpg' }, { title: 'League of Legends', price: 0, img: 'https://cdn.vox-cdn.com/thumbor/UehyoNzYoIR5ZJDrvHjDAZhmkaI=/0x0:1920x1080/1400x933/filters:focal(1030x331:1336x637):no_upscale()/cdn.vox-cdn.com/uploads/chorus_image/image/65632309/jbareham_191158_ply0958_decade_lolengends.0.jpg' }, ] handleExpandContentClick(): void { this.shouldPriceBeColorized = !this.shouldPriceBeColorized; } }
# 弹出选择 Popselect 如果你想选择一些数据,还不想看到那个框子,可以使用 Popselect。 ## 演示 ```demo basic.vue size.vue scrollable.vue multiple.vue slot.vue ``` ## API ### Popselect Props | 名称 | 类型 | 默认值 | 说明 | 版本 | | --- | --- | --- | --- | --- | | multiple | `boolean` | `false` | 是否为多选 | | | node-props | `(option: SelectOption \| SelectGroupOption) => object` | `undefined` | 选项的 DOM 属性生成函数 | 2.30.4 | | options | `Array<SelectOption \| SelectGroupOption>` | `[]` | 配置选项内容,详情参考 [Select](select#SelectOption-Properties) | | | scrollable | `boolean` | `false` | 选择菜单是否可滚动 | | | render-label | `(option: SelectOption \| SelectGroupOption) => VNodeChild` | `undefined` | 控制全部选项的渲染 | | | size | `'small' \| 'medium' \| 'large'` | `'medium'` | 组件尺寸 | | | value | `string \| number \| Array<string \| number> \| null` | `null` | 受控模式下的值 | | | virtual-scroll | `boolean` | `false` | 是否启用虚拟滚动 | 2.30.4 | | on-update:value | `(value: string \| number \| Array<string \| number> \| null, option: SelectBaseOption \| null \| Array<SelectBaseOption>) => void` | `undefined` | 值更新的回调 | | 对于 SelectOption & SelectGroupOption,参考 [Select](select#SelectOption-Properties) 对于其他 props,参考 [Popover](popover#Popover-Props) ### Popselect Slots | 名称 | 参数 | 说明 | 版本 | | ------ | ---- | ------------------- | ------ | | action | `()` | 菜单操作区域的 slot | 2.22.0 | | empty | `()` | 菜单无数据时的 slot | 2.22.0 |
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using webapi.event_.tarde.Domains; using webapi.event_.tarde.Interfaces; using webapi.event_.tarde.Repositories; namespace webapi.event_.tarde.Controllers { [Route("api/[controller]")] [ApiController] [Produces("application/json")] public class TipoEventoController : ControllerBase { private ITipoEventoRepository _tipoEventoRepository { get; set; } public TipoEventoController() { _tipoEventoRepository = new TipoEventoRepository(); } /// <summary> /// Cadastra um TipoEveto na tabela no banco /// </summary> /// <param name="tipoEvento"></param> /// <returns></returns> [HttpPost] public IActionResult Post(TipoEvento tipoEvento) { try { _tipoEventoRepository.Cadastrar(tipoEvento); return Ok("Tipo de evento cadastrado com sucesso!"); } catch (Exception erro) { return BadRequest(erro.Message); } } /// <summary> /// Deleta um Tipo de evento por id /// </summary> /// <param name="id">Id do TipoEvento</param> /// <returns>StatusCode</returns> [HttpDelete] public IActionResult Delete(Guid id) { try { _tipoEventoRepository.Deletar(id); return Ok("O Tipo de evento foi deletado com sucesso!"); } catch (Exception erro) { return BadRequest(erro.Message); } } /// <summary> /// Atualiza um Tipo de evento por id /// </summary> /// <param name="id">Id do Tipo de evento</param> /// <param name="tipoEvento">Objeto do tipo TipoEvento</param> /// <returns></returns> [HttpPut] public IActionResult Put(Guid id, TipoEvento tipoEvento) { try { _tipoEventoRepository.Atualizar(id, tipoEvento); return Ok("Tipo de evento atualizado com sucesso!"); } catch (Exception erro) { return BadRequest(erro.Message); } } /// <summary> /// Busca todos os TipoEvento salvos /// </summary> /// <returns>Lista de TipoEvento ou StatusCode</returns> [HttpGet] public IActionResult GetAll() { try { List<TipoEvento> tiposEvento = _tipoEventoRepository.BuscarTodos(); if (tiposEvento != null) return Ok(tiposEvento); return NotFound("Nenhum tipo de evento encontrado!"); } catch (Exception erro) { return BadRequest(erro.Message); } } /// <summary> /// Busca um TipoEvento por id /// </summary> /// <param name="id">Id do TipoEvento</param> /// <returns>TipoEvento ou StatusCode</returns> [HttpGet("{id}")] public IActionResult GetById(Guid id) { try { TipoEvento tipoEvento = _tipoEventoRepository.BuscarPorId(id); if (tipoEvento != null) return Ok(tipoEvento); return NotFound("Tipo de evento não encontrado!"); } catch (Exception erro) { return BadRequest(erro.Message); } } } }
// ------------------------- PEDRA PAPEL TESOURA --------------------------------------------------- const elementsPlayer = document.querySelectorAll('.player-options div > img') //Pegando todos os elementos de dentro da div let playerOpt = '' // Instanciando primeiramente a opção do player como vazio const elementsEnemy = document.querySelectorAll('.enemy-options div > img') //Pegando todos os elementos de dentro da div let enemyOpt = '' // Instanciando primeiramente a opção do player como vazio function resetOpt(elements) { // Função para definir o resto qual não foi a escolha do player para opacity 0.3 for (var i = 0; i < elements.length; i++) { // Um loop para percorrer todos os elementos elements[i].style.opacity = 0.3 // Definindo a opacidade do elemento } } function enemyPlayer() { let rand = Math.floor(Math.random() * 3) for (let i = 0; i < elementsEnemy.length; i++) { if (i == rand) { elementsEnemy[i].style.opacity = 1 enemyOpt = elementsEnemy[i].getAttribute('opt') } } } function defineWinner() { // Função que realiza o algorítimo para definir o vencedor de acordo com as regras do jogo, também // retorna ao usuário quem foi o ganhador, perdedor ou se houve empate. let winnerMessage = document.querySelector('.result') const win = () => { winnerMessage.innerHTML = 'PARABÉNS VOCÊ FOI O VENCEDOR!' winnerMessage.classList.add('result-show') } const lose = () => { winnerMessage.innerHTML = 'INFELIZMENTE VOCÊ PERDEU, DESEJO-LHE MAIS SORTE DA PRÓXIMA VEZ!' winnerMessage.classList.add('result-show') } const draw = () => { winnerMessage.innerHTML = 'EMPATOU! TENTE NOVAMENTE!' winnerMessage.classList.add('result-show') } if (playerOpt === 'rock') { if (enemyOpt === 'rock') { draw() } else if (enemyOpt === 'scissor') { win() } else if (enemyOpt === 'paper') { lose() } } else if (playerOpt === 'paper') { if (enemyOpt === 'paper') { draw() } else if (enemyOpt === 'rock') { win() } else if (enemyOpt === 'scissor') { lose() } } else if (playerOpt === 'scissor') { if (enemyOpt === 'scissor') { draw() } else if (enemyOpt === 'paper') { win() } else if (enemyOpt === 'rock') { lose() } } } for (var i = 0; i < elementsPlayer.length; i++) { // um loop percorrendo todos os elementos do player elementsPlayer[i].addEventListener('click', (t) => { // Uma função para dispara em efeito de click do user resetOpt(elementsPlayer) // Usando a função de resetOpt para deixar a opacity padrão de 0.3 as não escolhas do player resetOpt(elementsEnemy) t.target.style.opacity = 1 // Definindo a escolha e deixando em evidência com o opacity 1 playerOpt = t.target.getAttribute('opt') // Pegando o valor escolhido pelo player enemyPlayer() // Função que define a jogada gerada de modo aleatória do adversário defineWinner() // Função que realiza as validações para definir o vencedor de acordo com as regras do jogo }) } // HTML DA PÁGINA PARA INSERIR NO INDEX.HTML PARA QUE ESTE APP FUNCIONE CORRETAMENTE { /* <body> <style> *{ margin: 0; padding: 0; box-sizing: border-box; } body { background: linear-gradient(180deg, #ededed, #adadad); display: flex; flex-direction: column; align-items: center; gap: 20px; padding: 20px; color: #363636; } h1 { width: 50%; padding: 8px; border-radius: 8px; display: flex; justify-content: center; background-color: #c8c8c8; box-shadow: 0px 5px 15px 0px #363636 ; } .result-show { padding: 8px; border-radius: 8px; border: solid 1px #363636; display: flex; justify-content: center; background-color: transparent; box-shadow: 0px 5px 15px 0px #7b7b7b ; } .player-options img, .enemy-options img { max-width: 200px; opacity: 0.3; } .player-options { cursor: pointer; } .player-options img:hover { scale: 1.1; transition: 250ms } .align { width: 100%; display: flex; justify-content: space-around; } </style> <h1>Pedra, papel ou tesoura!</h1> <h3 class="result"></h3> <div class="align"> <div class="player-options"> <div><img title="rock" opt="rock" src="./apps/pedrapapeltesoura/rock.png" /></div> <div><img title="paper" opt="paper" src="./apps/pedrapapeltesoura/paper.png" /></div> <div><img title="scissor" opt="scissor" src="./apps/pedrapapeltesoura/scissor.png" /></div> </div> <div class="enemy-options"> <div><img title="rock" opt="rock" src="./apps/pedrapapeltesoura/rock.png" /></div> <div><img title="paper" opt="paper" src="./apps/pedrapapeltesoura/paper.png" /></div> <div><img title="scissor" opt="scissor" src="./apps/pedrapapeltesoura/scissor.png" /></div> </div> </div> <script></script> </body> */ }
#ifndef SLIST_H #define SLIST_H #include "listex2.gh" // sorted lists without duplicates // TODO: remove other lemma's fixpoint bool sorted(list<int> vs) { switch(vs) { case nil: return true; case cons(h1, t1): return switch(t1) { case nil: return true; case cons(h2, t2): return h1 < h2 && sorted(t1); }; } } fixpoint list<int> sorted_insert(int v, list<int> vs) { switch(vs) { case nil: return cons(v, nil); case cons(h, t): return (h < v ? cons(h, sorted_insert(v, t)) : (h == v ? vs : cons(v, vs))); } } fixpoint t last<t>(list<t> l) { switch(l) { case nil:return default_value<t>; case cons(h, t): return (t == nil ? h : last(t)); } } //assuming el is member of l fixpoint list<t> insertAfter<t>(list<t> l, t el, t el2) { switch(l) { case nil: return nil; case cons(h, t): return (h == el? cons(h, cons(el2, t)) : cons(h, insertAfter(t, el, el2))); } } fixpoint list<t> replace<t>(list<t> l, t el, list<t> l2) { switch(l) { case nil: return nil; case cons(h, t): return (h == el? append(l2,t) : cons(h, replace(t, el, l2))); } } lemma void sorted_mem_cons(int v, int x, list<int> l); requires sorted(cons(x, l)) == true &*& v < x; ensures !mem(v, cons(x, l)); lemma void sorted_mem_cons2(int v, int x, int y, list<int> l); requires sorted(cons(x, cons(y, l))) == true &*& x < v &*& v <= y; ensures mem(v, cons(x, cons(y, l))) == (v == y); lemma void sorted_cons(int x, list<int> l); requires sorted(cons(x, l)) == true; ensures sorted(l) == true; lemma void sorted_append(int x, list<int> l1, int y, list<int> l2); requires sorted(append(cons(x, l1), cons(y, l2))) == true; ensures x < y; lemma void sorted_mem_append(int v, list<int> l1, int x, list<int> l2); requires sorted(append(l1, cons(x, l2))) == true &*& x < v; ensures mem(v, append(l1, cons(x, l2))) == mem(v, l2); lemma void sorted_append_split(list<int> l1, list<int> l2); requires sorted(append(l1, l2)) == true; ensures sorted(l2) == true; lemma void sorted_append_split2(list<int> l1, list<int> l2); requires sorted(append(l1, l2)) == true; ensures sorted(l1) == true; lemma void sorted_snoc(list<int> l, int v); requires sorted(snoc(l, v)) == true; ensures sorted(l) == true; lemma void sorted_insert_mem(int v, list<int> vs); requires true; ensures mem(v, sorted_insert(v, vs)) == true; lemma void append_snoc<t>(list<t> l1, t val, list<t> l2); requires true; ensures append(snoc(l1, val), l2) == append(l1, cons(val, l2)); lemma void sorted_insert_sorted(int v, list<int> vs); requires sorted(vs) == true; ensures sorted(sorted_insert(v, vs)) == true; lemma void si_append(int v, list<int> l1, int l2h, list<int>l2t); requires sorted(append(l1, cons(l2h, l2t))) == true &*& v < l2h; ensures sorted_insert(v, append(l1, cons(l2h, l2t))) == append(sorted_insert(v, l1), cons(l2h, l2t)); lemma void si1(int v, list<int> l); requires sorted(cons(INT_MIN, snoc(l, INT_MAX))) == true &*& v > INT_MIN &*& v < INT_MAX; ensures sorted_insert(v, cons(INT_MIN, snoc(l, INT_MAX))) == cons(INT_MIN, snoc(sorted_insert(v, l), INT_MAX)); lemma void si2(int v, list<int> l1, int pv, int cv, list<int> l2); requires sorted(append(l1, cons(pv, cons(cv, l2)))) == true &*& pv < v &*& v < cv; ensures sorted_insert(v, append(l1, cons(pv, cons(cv, l2)))) == append(l1, cons(pv, cons(v, cons(cv, l2)))); lemma void si3(int v, list<int> l1, int pv, int cv, list<int> l2); requires sorted(append(l1, cons(pv, cons(cv, l2)))) == true &*& v == cv; ensures sorted_insert(v, append(l1, cons(pv, cons(cv, l2)))) == append(l1, cons(pv, cons(cv, l2))); lemma void append_nonnil<t>(list<t> l1, list<t> l2); requires l2 != nil; ensures append(l1, l2) != nil; lemma void last_append<t>(list<t> l1, list<t> l2); requires l2 != nil; ensures last(append(l1, l2)) == last(l2); lemma void last_snoc<t>(list<t> l, t v); requires true; ensures last(snoc(l, v)) == v; lemma void last_eq(list<int> vs, list<int> vs1, int pv, int cv); requires cons(INT_MIN, snoc(vs, INT_MAX)) == append(vs1, cons(pv, cons(cv, nil))); ensures cv == INT_MAX; lemma void remove_sorted(int v, list<int> vs); requires sorted(vs) == true; ensures sorted(remove(v, vs)) == true; lemma void remove_nomem<t>(t v, list<t> l); requires !mem(v, l); ensures remove(v, l) == l; lemma void remove_append<t>(t v, list<t> l1, list<t> l2); requires !mem(v, l2); ensures remove(v, append(l1, l2)) == append(remove(v, l1), l2); lemma void remove_helper1(int v, list<int> l); requires sorted(cons(INT_MIN, snoc(l, INT_MAX))) == true &*& v > INT_MIN &*& v < INT_MAX; ensures remove(v, cons(INT_MIN, snoc(l, INT_MAX))) == cons(INT_MIN, snoc(remove(v, l), INT_MAX)); lemma void remove_sorted_nomem(int v, int h, list<int> t); requires sorted(cons(h, t)) == true &*& v<h; ensures remove(v, cons(h,t)) == cons(h,t); lemma void remove_helper2(int v, list<int> l1, int pv, int cv, list<int> l2); requires sorted(append(l1, cons(pv, cons(cv, l2)))) == true &*& pv < v &*& v < cv; ensures remove(v, append(l1, cons(pv, cons(cv, l2)))) == append(l1, cons(pv, cons(cv, l2))); lemma void remove_helper3(int v, list<int> l1, int pv, int cv, list<int> l2); requires sorted(append(l1, cons(pv, cons(cv, l2)))) == true &*& v == cv; ensures remove(v, append(l1, cons(pv, cons(cv, l2)))) == append(l1, cons(pv, l2)); lemma void sorted_remove_all2_h(int v, int h, list<int> t); requires sorted(cons(h, t)) == true && h > v; ensures remove_all2(v, cons(h, t)) == cons(h, t); lemma void sorted_remove_all2(int v, list<int> l); requires sorted(l) == true; ensures remove(v, l) == remove_all2(v, l); lemma void remove_all2_spec<t>(t v, t v2, list<t> l); requires true; ensures mem(v2, remove_all2(v, l)) == (mem(v2, l) && v2 != v); lemma void replace_append<t>(list<t> la, list<t> lb, t el, list<t> l2); requires !mem(el, la); ensures replace(append(la, lb), el, l2) == append(la, replace(lb, el, l2)); lemma void sorted_insert_mem_increasing(list<int> l, int v, int v2); requires v != v2 &*& sorted(l) == true; ensures mem(v2, sorted_insert(v, l)) == mem(v2, l); #endif
// 209625946 Tomer Berenstein package animation.screenanimation; import listeners.lhelpers.Counter; /** * The WinScreen class is a win screen animation that extends ScreenAnimation * and displays a message when the player wins the game. * * @author Tomer Berenstein tomerbrotem@gmail.com * @version 19.0.2 * @since 2023-01-17 */ public class WinScreen extends ScreenAnimation { private Counter scoreCounter; /** * Creates a new WinScreen with the given score counter. * * @param scoreCounter The counter for the player's score. */ public WinScreen(Counter scoreCounter) { this.scoreCounter = scoreCounter; } @Override public String textOutput() { return "You Win! Your score is: " + this.scoreCounter.getValue(); } }
import 'package:flutter/material.dart'; import 'package:psxmpc/config/ps_colors.dart'; import '../../../../../core/vendor/constant/ps_dimens.dart'; import '../../../../../core/vendor/utils/utils.dart'; import '../../../../../core/vendor/viewobject/item_currency.dart'; class ItemCurrencyListViewItem extends StatelessWidget { const ItemCurrencyListViewItem( {Key? key, required this.itemCurrency, this.onTap, this.animationController, this.animation, required this.isSelected}) : super(key: key); final ItemCurrency itemCurrency; final Function? onTap; final AnimationController? animationController; final Animation<double>? animation; final bool isSelected; @override Widget build(BuildContext context) { animationController!.forward(); return AnimatedBuilder( animation: animationController!, child: InkWell( onTap: onTap as void Function()?, child: Container( height: PsDimens.space52, margin: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 12.0), child: Material( color: Utils.isLightMode(context) ? PsColors.achromatic200 : PsColors.achromatic900, child: Padding( padding: const EdgeInsets.all(PsDimens.space16), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: <Widget>[ Text( itemCurrency.currencySymbol!, textAlign: TextAlign.start, style: Theme.of(context).textTheme.titleSmall!.copyWith( fontSize: 14, fontWeight: FontWeight.w400, color: Utils.isLightMode(context) ? PsColors.text800 : PsColors.achromatic50, ), ), if (isSelected) const Icon(Icons.check_circle,) ], ), ), ), ), ), builder: (BuildContext contenxt, Widget? child) { return FadeTransition( opacity: animation!, child: Transform( transform: Matrix4.translationValues( 0.0, 100 * (1.0 - animation!.value), 0.0), child: child), ); }, ); } }
// Get the calculate button const calculateButton = document.getElementById('calculate'); // Add click event listener to the calculate button calculateButton.addEventListener('click', function() { // Get the input values const investmentAmount = parseFloat(document.getElementById('investment-amount').value.replace(',', '.')); const investmentTerm = parseInt(document.getElementById('investment-term').value); const periodType = document.getElementById('period-type').value; const diRate = parseFloat(document.getElementById('di-rate').value); const selicRate = parseFloat(document.getElementById('selic-rate').value); const cdbRate = parseFloat(document.getElementById('cdb-rate').value); const lciRate = parseFloat(document.getElementById('lci-rate').value); // Calculate the results for each investment type const savingsResults = calculateSavings(investmentAmount, investmentTerm, periodType, diRate); const cdbResults = calculateCdb(investmentAmount, investmentTerm, periodType, diRate, selicRate); const lciResults = calculateLci(investmentAmount, investmentTerm, periodType, selicRate); // Display the results displayResults(savingsResults, 'savings-result'); displayResults(cdbResults, 'cdb-result'); displayResults(lciResults, 'lci-result'); }); // Function to calculate savings investment function calculateSavings(investmentAmount, investmentTerm, periodType, diRate) { const months = periodType === 'days' ? investmentTerm / 30 : periodType === 'months' ? investmentTerm : investmentTerm * 12; const interest = (investmentAmount * diRate * months) / 100; const total = investmentAmount + interest; return { investmentType: 'Poupança', investmentAmount: investmentAmount.toFixed(2), interest: interest.toFixed(2), total: total.toFixed(2) }; } // Function to calculate CDB/RDB/LC investment function calculateCdb(investmentAmount, investmentTerm, periodType, diRate, selicRate) { const months = periodType === 'days' ? investmentTerm / 30 : periodType === 'months' ? investmentTerm : investmentTerm * 12; const diInterest = (investmentAmount * diRate * months) / 100; const selicInterest = (investmentAmount * selicRate * months) / 100; const totalDiInterest = diInterest * (cdbRate / 100); const totalInterest = totalDiInterest + selicInterest; const total = investmentAmount + totalInterest; const ir = totalInterest * 0.15; const netTotal = total - ir; return { investmentType: 'CDB/RDB', investmentAmount: investmentAmount.toFixed(2), diInterest: diInterest.toFixed(2), selicInterest: selicInterest.toFixed(2), totalDiInterest: totalDiInterest.toFixed(2), totalInterest: totalInterest.toFixed(2), total: total.toFixed(2), ir: ir.toFixed(2), netTotal: netTotal.toFixed(2) }; } // Function to calculate LCI/LCA investment function calculateLci(investmentAmount, investmentTerm, periodType, selicRate) { const months = periodType === 'days' ? investmentTerm / 30 : periodType === 'months' ? investmentTerm : investmentTerm * 12; const selicInterest = (investmentAmount * selicRate * months) / 100; const total = investmentAmount + selicInterest; return { investmentType: 'LCI/LCA', investmentAmount: investmentAmount.toFixed(2), selicInterest: selicInterest.toFixed(2), total: total.toFixed(2) }; } // Function to display the results function displayResults(results, resultId) { const resultElement = document.getElementById(resultId); resultElement.innerHTML = ` <h2>${results.investmentType}</h2> <p>Valor Investido: R$ ${results.investmentAmount}</p> <p>Rendimento Bruto: R$ ${results.interest}</p> ${results.ir > 0 ? `<p>Imposto de Renda: R$ ${results.ir} (15%)</p>` : ''} <p>Valor Total Líquido: R$ ${results.netTotal || results.total}</p> `; }