text
stringlengths
184
4.48M
import { useEffect, useRef } from 'react'; export default ( eventName: string, handler: (e: Event | CustomEvent | UIEvent | any) => void, options?: boolean | EventListenerOptions, ) => { const savedHandler = useRef<any>(null); useEffect(() => { savedHandler.current = handler; }, [handler]); useEffect(() => { const isSupported = window && window.addEventListener; if (!isSupported) return; const eventListener = (event: any) => savedHandler.current(event); window.addEventListener(eventName, eventListener, options); return () => { window.removeEventListener(eventName, eventListener); }; }, [eventName, window]); };
@extends('layouts.auth') @section('content') <div class="register-box"> <div class="register-logo"> <a href="../../index2.html"><b>Admin</b>LTE</a> </div> <div class="card"> <div class="card-body register-card-body"> <p class="login-box-msg">Register a new membership</p> <form method="POST" action="{{ route('register') }}"> @csrf <div class="input-group mb-3"> <input id="name" type="text" placeholder="Enter your name" class="form-control @error('name') is-invalid @enderror" name="name" value="{{ old('name') }}" required autocomplete="name" autofocus> @error('name') <span class="invalid-feedback" role="alert"> <strong>{{ $message }}</strong> </span> @enderror <div class="input-group-append"> <div class="input-group-text"> <span class="fas fa-user"></span> </div> </div> </div> <div class="input-group mb-3"> <input id="email" type="email" placeholder="Enter your email" class="form-control @error('email') is-invalid @enderror" name="email" value="{{ old('email') }}" required autocomplete="email"> @error('email') <span class="invalid-feedback" role="alert"> <strong>{{ $message }}</strong> </span> @enderror <div class="input-group-append"> <div class="input-group-text"> <span class="fas fa-envelope"></span> </div> </div> </div> <div class="input-group mb-3"> <input id="password" type="password" placeholder="Enter your password" class="form-control @error('password') is-invalid @enderror" name="password" required autocomplete="new-password"> @error('password') <span class="invalid-feedback" role="alert"> <strong>{{ $message }}</strong> </span> @enderror <div class="input-group-append"> <div class="input-group-text"> <span class="fas fa-lock"></span> </div> </div> </div> <div class="input-group mb-3"> <input id="password-confirm" type="password" placeholder="Enter confirm password" class="form-control" name="password_confirmation" required autocomplete="new-password"> <div class="input-group-append"> <div class="input-group-text"> <span class="fas fa-lock"></span> </div> </div> </div> <div class="row"> <div class="col-8"> <div class="icheck-primary"> <input type="checkbox" id="agreeTerms" name="terms" value="agree"> <label for="agreeTerms"> I agree to the <a href="#">terms</a> </label> </div> </div> <!-- /.col --> <div class="col-4"> <button type="submit" class="btn btn-primary btn-block">Register</button> </div> <!-- /.col --> </div> </form> <a href="{{ route('login') }}" class="text-center">I already have a membership</a> </div> <!-- /.form-box --> </div><!-- /.card --> </div> <!-- /.register-box --> @endsection
import { Injectable } from '@nestjs/common'; import { Country } from './entities/country.entity'; import { InjectRepository } from '@nestjs/typeorm'; import { Repository } from 'typeorm'; import { Province } from './entities/province.entity'; import { District } from './entities/district.entity'; import { SubDistrict } from './entities/sub-district.entity'; import { SearchProvinceDto } from './dto/search-province.dto'; import { SearchDistrictDto } from './dto/search-district.dto'; import { SearchSubDistrictDto } from './dto/search-sub-district.dto'; import { getRespones } from 'src/shared/functions/respone-function'; import { BasicsearchDto } from 'src/shared/basics/basic-search.dto'; import { VerifyOptDto } from './dto/verify-otp.dto'; import { Twilio } from "twilio"; import { VerifyMobileDto } from 'src/users/dto/verify-mobile.dto'; import { VerifyPhoneNumberDto } from './dto/verify-phone-number.dto'; import { CreateAddressDto } from '../users/dto/create-address.dto'; const accountSid = "AC39157a1fcdda4fcf1771d06a63839549"; const authToken = '1de7bd1c0034f520a6e027daa8581443'; const verifySid = "VA1e0a217f2a87b99089a13d06c3dfe7bc"; // const client = require("twilio")(accountSid, '1de7bd1c0034f520a6e027daa8581443'); @Injectable() export class AddressService { constructor( @InjectRepository(Country) private readonly countryRepository: Repository<Country>, @InjectRepository(Province) private readonly provinceRepository: Repository<Province>, @InjectRepository(District) private readonly districtRepository: Repository<District>, @InjectRepository(SubDistrict) private readonly subDistrictRepository: Repository<SubDistrict>, ) { } async getCountry(){ const data = await this.countryRepository.find({select:{ code:true, name:true, }}); return getRespones(data,new BasicsearchDto()) } async getProvince(dto:SearchProvinceDto){ const data = await this.provinceRepository.find({where:{countryCode:dto.countryCode}}) return getRespones(data,new BasicsearchDto()) } async getDistrict(dto:SearchDistrictDto){ const data = await this.districtRepository.find({where:{provinceCode:dto.provinceCode}}) return getRespones(data,new BasicsearchDto()) } async getSubDistrict(dto:SearchSubDistrictDto){ const data = await this.subDistrictRepository.find({where:{districtCode:dto.districtCode}}) return getRespones(data,new BasicsearchDto()) } async verifyPhoneNumber(dto:VerifyPhoneNumberDto){ const client = new Twilio(accountSid, authToken); const result = await client.verify.v2.services(verifySid).verifications.create({ to:dto.phoneNumber, channel:"sms", }) return result } async verifyOtpCode(dto:VerifyOptDto){ const client = new Twilio(accountSid, authToken); const result = await client.verify.v2.services(verifySid).verificationChecks .create({ to:dto.phoneNumber, code:dto.otpCode }) return result } }
<?php /** * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ declare(strict_types=1); namespace Magento\Setup\Declaration; use Magento\Framework\App\ResourceConnection; use Magento\Framework\App\Utility\Files; use Magento\Framework\Component\ComponentRegistrar; use Magento\Framework\Component\ComponentRegistrarInterface; use Magento\Framework\ObjectManagerInterface; use Magento\Framework\Setup\Declaration\Schema\Dto\Constraint; use Magento\Framework\Setup\Declaration\Schema\Dto\Index; use Magento\Framework\Setup\Declaration\Schema\SchemaConfigInterface; use Magento\TestFramework\Helper\Bootstrap; use Magento\TestFramework\ObjectManager; /** * Class WhitelistDeclarationTest */ class WhitelistDeclarationTest extends \PHPUnit\Framework\TestCase { /** * @var ComponentRegistrarInterface */ private $componentRegistrar; /** * @var SchemaConfigInterface */ private $schemaConfig; public function setUp() { /** @var ObjectManagerInterface|ObjectManager $objectManager */ $objectManager = Bootstrap::getObjectManager(); $resourceConnection = $objectManager->create(ResourceConnection::class); $objectManager->removeSharedInstance(ResourceConnection::class); $objectManager->addSharedInstance($resourceConnection, ResourceConnection::class); $this->componentRegistrar = $objectManager->get(ComponentRegistrarInterface::class); $this->schemaConfig = $objectManager->create(SchemaConfigInterface::class); } /** * Checks that all declared table elements also declared into whitelist declaration. * * @magentoAppIsolation enabled * @throws \Exception */ public function testConstraintsAndIndexesAreWhitelisted() { $undeclaredElements = []; $resultMessage = "New table elements that do not exist in the whitelist declaration:\n"; $whitelistTables = $this->getWhiteListTables(); $declarativeSchema = $this->schemaConfig->getDeclarationConfig(); foreach ($declarativeSchema->getTables() as $schemaTable) { $tableNameWithoutPrefix = $schemaTable->getNameWithoutPrefix(); foreach ($schemaTable->getConstraints() as $constraint) { $constraintNameWithoutPrefix = $constraint->getNameWithoutPrefix(); if (isset($whitelistTables[$tableNameWithoutPrefix][Constraint::TYPE][$constraintNameWithoutPrefix])) { continue; } $undeclaredElements[$tableNameWithoutPrefix][Constraint::TYPE][] = $constraintNameWithoutPrefix; } foreach ($schemaTable->getIndexes() as $index) { $indexNameWithoutPrefix = $index->getNameWithoutPrefix(); if (isset($whitelistTables[$tableNameWithoutPrefix][Index::TYPE][$indexNameWithoutPrefix])) { continue; } $undeclaredElements[$tableNameWithoutPrefix][Index::TYPE][] = $indexNameWithoutPrefix; } } $undeclaredElements = $this->filterUndeclaredElements($undeclaredElements); if (!empty($undeclaredElements)) { $resultMessage .= json_encode($undeclaredElements, JSON_PRETTY_PRINT); } $this->assertEmpty($undeclaredElements, $resultMessage); } /** * Excludes ignored elements from the list of undeclared table elements. * * @param array $undeclaredElements * @return array */ private function filterUndeclaredElements(array $undeclaredElements): array { $files = Files::getFiles([__DIR__ . '/_files/ignore_whitelisting'], '*.json'); $ignoredElements = []; foreach ($files as $filePath) { $ignoredElements = array_merge_recursive( $ignoredElements, json_decode(file_get_contents($filePath), true) ); } return $this->arrayRecursiveDiff($undeclaredElements, $ignoredElements); } /** * Performs a recursive comparison of two arrays. * * @param array $array1 * @param array $array2 * @return array */ private function arrayRecursiveDiff(array $array1, array $array2): array { $diffResult = []; foreach ($array1 as $key => $value) { if (array_key_exists($key, $array2)) { if (is_array($value)) { $recursiveDiffResult = $this->arrayRecursiveDiff($value, $array2[$key]); if (count($recursiveDiffResult)) { $diffResult[$key] = $recursiveDiffResult; } } else { if (!in_array($value, $array2)) { $diffResult[] = $value; } } } else { $diffResult[$key] = $value; } } return $diffResult; } /** * @return array */ private function getWhiteListTables(): array { $whiteListTables = []; foreach ($this->componentRegistrar->getPaths(ComponentRegistrar::MODULE) as $path) { $whiteListPath = $path . DIRECTORY_SEPARATOR . 'etc' . DIRECTORY_SEPARATOR . 'db_schema_whitelist.json'; if (file_exists($whiteListPath)) { $whiteListTables = array_replace_recursive( $whiteListTables, json_decode(file_get_contents($whiteListPath), true) ); } } return $whiteListTables; } }
<!DOCTYPE html> <html lang="es"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <link rel="preconnect" href="https://fonts.googleapis.com" /> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin /> <link href="https://fonts.googleapis.com/css2?family=Raleway:ital,wght@0,700;1,700&family=Roboto:ital,wght@0,400;0,500;0,700;0,900;1,500;1,700;1,900&display=swap" rel="stylesheet" /> <link rel="stylesheet" href="./css/style.css" /> <title>WebStudio</title> </head> <body> <header class="page-header"> <div class="container header-container"> <a class="logo" href="./index.html">Webstudio</a> <nav> <ul class="nav-menu"> <li> <a class="headers" href="./index.html">Estudio</a> </li> <li> <a class="headers current" href="./portfolio.html">Portafolio</a> </li> <li> <a class="headers" href="./index.html">Contacto</a> </li> </ul> </nav> <ul class="contact-menu"> <li> <a class="nav-contact" href="#"> <svg class="icon" width="20" height="20"> <use href="./images/sprites.svg#sobre"></use> </svg> [email protected] </a> </li> <li> <a class="nav-contact" href="#"> <svg class="icon" width="20" height="20"> <use href="./images/sprites.svg#telefono"></use> </svg> +52 55 5529 60 00 </a> </li> </ul> </div> </header> <main> <section class="portafolio section"> <div class="container"> <h2 hidden>Portafolio</h2> <ul class="portafolio-list"> <li><button class="button current" type="button">Todo</button></li> <li><button class="button" type="button">Sitios-Web</button></li> <li><button class="button" type="button">Aplicaciones</button></li> <li><button class="button" type="button">Diseño</button></li> <li><button class="button" type="button">Marketing</button></li> </ul> <ul class="portafolio-cards"> <li class="portafolio-items"> <img src="./images/Portafolio_01.jpg" width="340" alt="computador"/> <div class="proyect"> <h3 class="portafolio-title">Tecnoduck</h3> <p class="portafolio-description">Sitio-web</p> </div> </li> <li class="portafolio-items"> <img src="./images/Portafolio_02.jpg" width="340" alt=""/> <div class="proyect"> <h3 class="portafolio-title">Póster de Nueva Orleans vs Estrella Dorada</h3> <p class="portafolio-description">Diseño</p> </div> </li> <li class="portafolio-items"> <img src="./images/Portafolio_03.jpg" width="340" alt=""/> <div class="proyect"> <h3 class="portafolio-title">Restaurante Seafood</h3> <p class="portafolio-description">Aplicaciones</p> </div> </li> <li class="portafolio-items"> <img src="./images/Portafolio_04.jpg" width="340" alt="" /> <div class="proyect"> <h3 class="portafolio-title">Proyecto Prime</h3> <p class="portafolio-description">Marketing</p> </div> </li> <li class="portafolio-items"> <img src="./images/Portafolio_05.jpg" width="340" alt="" /> <div class="proyect"> <h3 class="portafolio-title">Proyecto Cajas</h3> <p class="portafolio-description">Aplicaciones</p> </div> </li> <li class="portafolio-items"> <img src="./images/Portafolio_06.jpg" width="340" alt="" /> <div class="proyect"> <h3 class="portafolio-title">La inspiración no tiene límites</h3> <p class="portafolio-description">Sitio-web</p> </div> </li> <li class="portafolio-items"> <img src="./images/Portafolio_07.jpg" width="340" alt="" /> <div class="proyect"> <h3 class="portafolio-title">Edición Limitada</h3> <p class="portafolio-description">Diseño</p> </div> </li> <li class="portafolio-items"> <img src="./images/Portafolio_08.jpg" width="340" alt="" /> <div class="proyect"> <h3 class="portafolio-title">Proyecto LAB</h3> <p class="portafolio-description">Marketing</p> </div> </li> <li class="portafolio-items"> <img src="./images/Portafolio_09.jpg" width="340" alt="" /> <div class="proyect"> <h3 class="portafolio-title">Negocio en Crecimiento</h3> <p class="portafolio-description">Aplicaciones</p> </div> </li> </ul> </div> </section> </main> <footer class="footer"> <div class="container footer-flex"> <div> <a class="logo-footer" href="index.html">Webstudio</a> <address> <a class="address" href="#">Calz. Ticomán 500, Ciudad de México, CDMX, México</a> </address> <ul> <li><a class="contact" href="#">[email protected]</a></li> <li><a class="contact" href="#"> +52 55 5529 6000</a></li> </ul> </div> <div> <h2 class="aside-title">encuentrenos en</h2> <ul class="aside-list"> <li> <a href="" class="aside"> <svg width="20" height="20"> <use href="./images/sprites.svg#instagram"></use> </svg> </a> </li> <li> <a href="" class="aside"> <svg width="20" height="20"> <use href=" ./images/sprites.svg#twitter"></use> </svg> </a> </li> <li> <a href="" class="aside"> <svg width="20" height="20"> <use href="./images/sprites.svg#facebook"></use> </svg> </a> </li> <li> <a href="" class="aside"> <svg width="20" height="20"> <use href="./images/sprites.svg#linkedin"></use> </svg> </a> </li> </ul> </div> <div> </footer> </body> </html>
package Model.Database.Interaction; import Model.Database.Support.Assurance; import Model.Database.Support.SqlConnectionOneTimeReestablisher; import Model.Database.Tables.T_CentralUnit; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Dictionary; import java.util.Hashtable; import java.util.List; public class I_CentralUnit extends InteractionWithDatabase { /**** * Attempt to insert the parsed argument T_CentralUnit into the real database * @param conn * @param ps * @param tcu * @return * @throws SQLException */ public static int insert(Connection conn, PreparedStatement ps, T_CentralUnit tcu) throws SQLException { if (tcu.IsTableOkForDatabaseEnter() == false) throw new SQLException("Given attribute T_CentralUnit is not ok for database enter"); // Fill SQL db table names String tableNames = String.join(", ", T_CentralUnit.DBNAME_UID, T_CentralUnit.DBNAME_DIPADDRESS, T_CentralUnit.DBNAME_FRIENDLYNAME, T_CentralUnit.DBNAME_SIMNO, T_CentralUnit.DBNAME_IMEI, T_CentralUnit.DBNAME_ZWAVE, T_CentralUnit.DBNAME_BUILDING_ID ); // SQL Definition ps = conn.prepareStatement( "INSERT INTO " + T_CentralUnit.DBTABLE_NAME + "(" + tableNames + ") " + "VALUES (" + "?, ?, ?, ?, ?, ?, ?" + ") " ); int col = 0; ps.setInt(++col, tcu.getA_Uid()); ps.setString(++col, tcu.getA_DipAddress()); ps.setString(++col, tcu.getA_FriendlyName()); ps.setString(++col, tcu.getA_SimNO()); ps.setString(++col, tcu.getA_Imei()); ps.setString(++col, tcu.getA_Zwave()); ps.setInt(++col, tcu.getA_BuildingID()); // SQL Execution SqlConnectionOneTimeReestablisher scotr = new SqlConnectionOneTimeReestablisher(); int affectedRows = scotr.TryUpdateFirstTime(conn, ps); if (affectedRows == 0) throw new SQLException("Something happened. Insertion of CentralUnit into db failed."); return affectedRows; } public static List<T_CentralUnit> retrieveByBuildingId(Connection conn, PreparedStatement ps, ResultSet rs, int buildingId) throws SQLException { Assurance.idCheck(buildingId); // SQL Definition ps = conn.prepareStatement( "SELECT " + "* " + "FROM " + T_CentralUnit.DBTABLE_NAME + " " + "WHERE " + T_CentralUnit.DBNAME_BUILDING_ID + "=?" ); int col = 0; ps.setInt(++col, buildingId); // SQL Execution SqlConnectionOneTimeReestablisher scotr = new SqlConnectionOneTimeReestablisher(); rs = scotr.TryQueryFirstTime(conn, ps, rs); List<T_CentralUnit> arr = new ArrayList<>(); if (!rs.isBeforeFirst()) { /* nothing was returned */ } else { while (rs.next()) { arr.add(I_CentralUnit.FillEntity(rs)); } } return arr; } public static T_CentralUnit retrieveByDip(Connection conn, PreparedStatement ps, ResultSet rs, String dip) throws SQLException { Assurance.varcharCheck(dip); // SQL Definition ps = conn.prepareStatement( "SELECT " + "* " + "FROM " + T_CentralUnit.DBTABLE_NAME + " " + "WHERE " + T_CentralUnit.DBNAME_DIPADDRESS +"=?" ); int col = 0; ps.setString(++col, dip); // SQL Execution SqlConnectionOneTimeReestablisher scotr = new SqlConnectionOneTimeReestablisher(); rs = scotr.TryQueryFirstTime(conn, ps, rs); T_CentralUnit tc = null; if (!rs.isBeforeFirst()) { /* nothing was returned */ } else { rs.next(); tc = I_CentralUnit.FillEntity(rs); } return tc; } // Privates public static T_CentralUnit FillEntity(ResultSet rs) throws SQLException { Dictionary dict = new Hashtable(); dict.put(T_CentralUnit.DBNAME_UID, rs.getInt(T_CentralUnit.DBNAME_UID)); dict.put(T_CentralUnit.DBNAME_DIPADDRESS, rs.getString(T_CentralUnit.DBNAME_DIPADDRESS)); dict.put(T_CentralUnit.DBNAME_FRIENDLYNAME, rs.getString(T_CentralUnit.DBNAME_FRIENDLYNAME)); dict.put(T_CentralUnit.DBNAME_SIMNO, rs.getString(T_CentralUnit.DBNAME_SIMNO)); dict.put(T_CentralUnit.DBNAME_IMEI, rs.getString(T_CentralUnit.DBNAME_IMEI)); dict.put(T_CentralUnit.DBNAME_ZWAVE, rs.getString(T_CentralUnit.DBNAME_ZWAVE)); dict.put(T_CentralUnit.DBNAME_BUILDING_ID, rs.getInt(T_CentralUnit.DBNAME_BUILDING_ID)); return T_CentralUnit.CreateFromRetrieved(rs.getInt(T_CentralUnit.DBNAME_ID), dict); } public static boolean checkIfExists(Connection conn, PreparedStatement ps, ResultSet rs, int uid, String dip, int buildingId) throws SQLException{ // SQL Definition ps = conn.prepareStatement( "SELECT " + "* " + "FROM " + T_CentralUnit.DBTABLE_NAME + " " + "WHERE Uid=? OR (BuildingID=? AND DipAddress=?) " ); int col = 0; ps.setInt(++col, uid); ps.setInt(++col, buildingId); ps.setString(++col, dip); // SQL Execution SqlConnectionOneTimeReestablisher scotr = new SqlConnectionOneTimeReestablisher(); rs = scotr.TryQueryFirstTime(conn, ps, rs); return rs.isBeforeFirst(); } public static boolean checkIfDipOccupiedAlready(Connection conn, PreparedStatement ps, ResultSet rs, String dip) throws SQLException{ Assurance.varcharCheck(dip); // SQL Definition ps = conn.prepareStatement( "SELECT " + "* " + "FROM " + T_CentralUnit.DBTABLE_NAME + " " + "WHERE DipAddress=?" ); int col = 0; ps.setString(++col, dip); // SQL Execution SqlConnectionOneTimeReestablisher scotr = new SqlConnectionOneTimeReestablisher(); rs = scotr.TryQueryFirstTime(conn, ps, rs); return rs.isBeforeFirst(); } }
import { Link, useFetcher } from "@remix-run/react"; import { Icon } from "@iconify/react"; type NavigationPropsType = { isAuthenticated: boolean; name: string; }; const Navigation = ({ isAuthenticated, name }: NavigationPropsType) => { const fetcher = useFetcher(); return ( <div className="flex size-full flex-col justify-between bg-white px-4 pb-4 pt-2"> <div className="flex h-full flex-col justify-between"> <div> <p className="mb-2 p-2 text-sm text-neutral-600 antialiased">Main Menu</p> <nav className="space-y-2"> <Link to="/" className="flex cursor-pointer items-center rounded-md p-2 hover:bg-neutral-100" > <Icon icon="ic:round-home" className="text-2xl text-neutral-600" /> <p className="ml-3 mt-1 text-sm font-medium text-neutral-600 antialiased">Home</p> </Link> <Link to="/dashboard" className="flex cursor-pointer items-center rounded-md p-2 hover:bg-neutral-100" > <Icon icon="ic:round-dashboard" className="text-2xl text-neutral-600" /> <p className="ml-3 mt-1 text-sm font-medium text-neutral-600 antialiased"> Dashboard </p> </Link> <Link to="/reporting" className="flex cursor-pointer items-center rounded-md p-2 hover:bg-neutral-100" > <Icon icon="oui:app-reporting" className="text-2xl text-neutral-600" /> <p className="ml-3 mt-1 text-sm font-medium text-neutral-600 antialiased"> Reporting </p> </Link> {isAuthenticated && ( <Link to="/settings" className="flex cursor-pointer items-center rounded-md p-2 hover:bg-neutral-100" > <Icon icon="ic:round-settings" className="text-2xl text-neutral-600" /> <p className="ml-3 mt-1 text-sm font-medium text-neutral-600 antialiased"> Settings </p> </Link> )} </nav> </div> <div className="mb-4"> <Link to="/support" className="flex cursor-pointer items-center rounded-md p-2 hover:bg-neutral-100" > <Icon icon="mdi:customer-service" className="text-2xl text-neutral-600" /> <p className="ml-3 mt-1 text-sm font-medium text-neutral-600 antialiased">Support</p> </Link> {isAuthenticated && ( <button onClick={() => fetcher.submit( { _action: "logout", }, { method: "POST", encType: "application/json" } ) } className="block w-full cursor-pointer items-center rounded-md p-2 hover:bg-neutral-100" > <div className="flex items-center"> <Icon icon="solar:logout-outline" className="text-2xl text-red-600" /> <p className="ml-3 text-sm font-medium text-red-600 antialiased">Logout</p> </div> </button> )} </div> </div> <div className="border-t-[1px] pt-4"> {isAuthenticated ? ( <div className="flex w-full items-center gap-4"> <Icon icon="ph:user" className="text-sm text-neutral-600" /> <p className="text-sm font-medium text-neutral-600 antialiased">{name}</p> </div> ) : ( <nav className="space-y-2"> <Link to="/login" className="flex cursor-pointer items-center rounded-md p-2 hover:bg-neutral-100" > <Icon icon="ri:login-circle-fill" className="text-2xl text-neutral-600" /> <p className="ml-3 mt-1 text-sm font-medium text-neutral-600 antialiased"> Login / Create Account </p> </Link> </nav> )} </div> </div> ); }; export default Navigation;
// El método concat() se usa para unir dos o más arrays. Este método no cambia los arrays existentes, // sino que devuelve un nuevo array. // Ejercicio: Combinar dos arrays en uno nuevo // Descripción: // Escribe una función llamada combinarArrays que tome dos arrays como parámetros y utilice el método concat() // para combinarlos en un nuevo array. La función debe devolver el nuevo array resultante de la combinación. // Instrucciones: // 1. Declara una función llamada combinarArrays que acepte dos parámetros: array1 y array2. // 2. Dentro de la función, utiliza el método concat() para combinar array1 y array2 en un nuevo array. // Asigna el resultado a una variable llamada resultado. // 3. Devuelve el nuevo array resultado utilizando la declaración return. // 4. Prueba tu función llamándola con diferentes arrays y verifica que el resultado sea el array combinado correctamente. let letras1 = ['a', 'b', 'c', 'd']; let letras2 = ['e', 'f', 'g', 'h']; let num1 = [1, 2, 3]; let num2 = [4, 5, 6]; const combinarArrays = (array1, array2) =>{ const resultado = array1.concat(array2) return resultado } console.log(combinarArrays(letras1,letras2)); console.log(combinarArrays(num1,num2));
Router npm install react-router-dom 1- tüm route larımızı BrowserRouter kapsayacak şekilde Routes larımızın içine koyuyoruz. 2- yapımız en basit haliyle aşağıdaki gibidir. <BrowserRouter> <Navbar/> <Routes> <Route path="/" element = {<Home/>}> <Route path="/about" element = {<About/>}> about sayfasına gider <Route path="*" element = {<Error/>}> url yanlış girilirse </Routes> </BrowserRouter> 3-Router hooks = useNavigate , useParams, useLocation 4-link ve a tagi arasındaki fark a tagi ile sayfa render olur ama link ile sayfa tekrardan render yapmaz. 5- link ve Navlink arasında ise , Navlink ( anchor tag ) stil verebiliriz ama link i component olarak react-router dan çektiğimiz için stil yapamıyoruz. 6-link to="/" şeklindedir. 7- fetch ile fakeapi den ürünlerimizi çekiyoruz.useEffect kullandım. 8-consola yazdıramadığımız şeyleri network içinde attığımız istekleri görebiliriz. 9- to={`/details`} şeklinde olursa url miz localhost:3000/details e gider ama to={`details`} bu şeklinde olursa localhost:3000/.../details şeklinde olur. yani devamına ekler . 10-<Route path="products/details/Id" element={<Details />} /> bu şekilde url de localhost:3000/products/details/id gelirse Details sayfasına git demek ama ben öyle istemiyorum Id yerine ne gelirse gelsin Details sayfasına göndermek istiyorum bu yüzden :ID şeklinde yapmalıyım.Dinamik şekilde oluşturmuş oldum. 11- navigate(-1) dersem önceki sayfaya yönlendirmiş olur. 12-useNavigate : Belirli URL'ye, ileri veya geri sayfalara gitmeye yardımcı olur. import { useNavigate } from 'react-router-dom'; export function GoHome() { let navigate = useNavigate(); const handleClick = e => { e.preventDefault(); navigate('/home'); } return <button onClick={handleClick}>Go to Home</button> } 13-useParams: URL parametrelerinin anahtar/değer çiftlerinden oluşan bir nesne döndürür. yani Url de kullandığımız tüm parametreleri bana getirir. path="products/details/:Id burada : dan sonrasındakini parametre olarak algılar. import { BrowserRouter as Router, Switch, Route, useParams } from "react-router-dom"; function BlogPost() { let { slug } = useParams(); return <div>Now showing post {slug}</div>; } ReactDOM.render( <Router> <Switch> <Route exact path="/"> <HomePage /> </Route> <Route path="/blog/:slug"> <BlogPost /> </Route> </Switch> </Router>, node ); 14-useLocation : sayfalar arası bilgi gönderme yapar. import { useHistory } from "react-router-dom"; function HomeButton() { let history = useHistory(); function handleClick() { history.push("/home"); } return ( <Button type="button" onClick={handleClick}> Go home </Button> ); }
#include <stdio.h> #include <stdarg.h> int my_printf(const char *fmt, ...) { va_list args; va_start(args, fmt); int chars_written = 0; int i = 0; while(fmt[i] != '\0'){ if(fmt[i] == '%'){//ne chetem "%" za specifikatora i++; switch(fmt[i]){ case 'd':{ int num = va_arg(args, int); chars_written += printf("%d", num); break; } case 'f':{ double num = va_arg(args, double); chars_written += printf("%f", num); break; } case 'c':{ int c = va_arg(args, int); putc(c, stdout); chars_written++; break; } default: putc(fmt[i], stdout); chars_written++; break; } } else{ putc(fmt[i], stdout); chars_written++; } i++; } va_end(args); return chars_written; } int main(){ int d = 13; double f = 8.14; char c = 'E'; int result = my_printf("Integer: %d, Float: %f, Character: %c\n", d, f, c); printf("Total characters written: %d\n", result); return 0; }
import { ref, get, push, update, remove, serverTimestamp } from "@firebase/database"; import { useFirebase } from "../firebase/FirebaseContext"; const useFirebaseDB = () => { const { firebaseState } = useFirebase(); const { db } = firebaseState; const getAll = async (path: string) => { if (db) { const dataRef = ref(db, path); try { const dataSnapshot = await get(dataRef); const data: any[] = []; if (dataSnapshot.exists()) { dataSnapshot.forEach((snapshot) => { data.push({ key: snapshot.key, id: snapshot.key, ...snapshot.val() }); }); } return data; } catch (error) { console.error(`Failed to read ${path}:${error}`); return []; } } } const getById = async (path: string) => { if (db) { const dataRef = ref(db, path); try { const dataSnapshot = await get(dataRef); if (dataSnapshot.exists()) { return dataSnapshot.val(); } return {}; } catch (error) { console.error(`Failed to read ${path}`); } } } const create = async (path: string, data: any) => { if (db) { try { const dataRef = ref(db, path); const newKey = push(dataRef).key; if (!newKey) { throw new Error('Failed to create key'); } update(dataRef, { [newKey]: { ...data, createdAt: serverTimestamp() }, }); return newKey; } catch (error) { console.error(`Failed to create data in ${path}:${error}`); } } } const modify = async (path: string, data: any) => { if (db) { try { const dataRef = ref(db, path); update(dataRef, { ...data, updatedAt: serverTimestamp() }); } catch (error) { console.error(`Failed to update data in ${path}:${error}`); } } } const rem = async (path: string) => { if (db) { try { const dataRef = ref(db, path); remove(dataRef); } catch (error) { console.error(`Failed to remove data in ${path}:${error}`); } } } return { getAll, getById, create, modify, rem } } export default useFirebaseDB;
const cors = require("cors"); const express = require("express"); const mongoose = require("mongoose"); const { Server } = require("socket.io"); const { createServer } = require("http"); const cookieParser = require("cookie-parser"); const requestLogger = require("./middlewares/logger"); const errorHandler = require("./middlewares/errorHandler"); const { verifyAccessToken } = require("./middlewares/token"); const monitorTaskDeadline = require("./utils/monitorTaskDeadline"); const unknownRouteHandler = require("./middlewares/unknownRouteHandler"); const app = express(); const httpServer = createServer(app); const io = new Server(httpServer, { cors: { origin: process.env.CLIENT_URL, credentials: true, }, }); const connectedUsers = {}; io.on("connection", (socket) => { console.log(`A new client ${socket.id} is now connected to this server`); socket.on("loggedIn", (userId) => (connectedUsers[userId] = socket.id)); socket.on("disconnect", () => { const userId = Object.keys(connectedUsers).find( (key) => connectedUsers[key] === socket.id ); if (userId) delete connectedUsers[userId]; console.log(`The client ${socket.id} has disconnected from the server`); }); }); module.exports = { io, connectedUsers }; // Custom routes const authRoutes = require("./routes/authRoute"); const userRoutes = require("./routes/userRoute"); const publicRoutes = require("./routes/publicRoute"); const projectRoutes = require("./routes/projectRoute"); // Set the view engine to ejs app.set("view engine", "ejs"); // Body parser middlewares app.use(express.json()); app.use(express.urlencoded({ extended: true })); // Cookie parser middleware app.use(cookieParser()); // CORS middleware app.use(cors({ credentials: true, origin: process.env.CLIENT_URL })); // Logging middleware app.use(requestLogger); // Public Routes app.use("/api", publicRoutes); // Authentication Routes app.use("/api/auth", authRoutes); // Private Routes app.use("/api/user/:userId", verifyAccessToken, [userRoutes, projectRoutes]); // Unknown routes handling middleware app.use("*", unknownRouteHandler); // Error handling middleware app.use(errorHandler); const startApp = async () => { try { await mongoose.connect( process.env.MONGODB_URI + "?retryWrites=true&w=majority" ); console.log("Database connected successfully"); httpServer.listen(process.env.PORT, () => { console.log("Server is running on port:", process.env.PORT); }); await monitorTaskDeadline(io); } catch (error) { console.error("Database connection error:", { name: error.name, message: error.message, stack: error.stack, }); process.exit(1); } }; startApp();
import React from "react"; import Link from "next/link"; const Form = ({ type, post, setPost, submit, handleSubmit }) => { return ( <section className="w-full max-w-full flex-start flex-col"> <h1 className="head_text text-left"> <span className="blue_gradient">{type} Post</span> </h1> <p className="desc text-left max-w-md"> {type} and share amazing prompts with the world, and let your imagination run wild with all AI-powered platform. </p> <form className="mt-20 w-full max-w-2xl flex flex-col gap-7 glassmorphism" onSubmit={handleSubmit} > <label> <span className="font-satoshi font-semibold text-gray-700"> Your AI prompt </span> <textarea value={post.prompt} onChange={(e) => { setPost({ ...post, prompt: e.target.value }); }} required placeholder="Write your prompt here..." className="form_textarea" /> </label> <label> <span className="font-satoshi font-semibold text-gray-700"> Tag{` `} <span className="font-normal"> (#idea, #product, #webdevelopement) </span> </span> <input value={post.tag} onChange={(e) => { setPost({ ...post, tag: e.target.value }); }} required placeholder="#tag" className="form_input" /> </label> <div className="flex-end mb-5 gap-4 mx-3"> <Link href="/" className="text-sm text-gray-500"> cancel </Link> <button type="submit" disabled={submit} className="text-white text-sm bg-primary-orange rounded-full px-5 py-1.5" > {submit ? `${type}...` : type} </button> </div> </form> </section> ); }; export default Form;
package de.fu_berlin.inf.dpp.net.internal; import java.io.IOException; import java.io.InterruptedIOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import org.apache.log4j.Logger; import org.jivesoftware.smack.Connection; import org.jivesoftware.smackx.bytestreams.socks5.Socks5Proxy; import org.picocontainer.annotations.Nullable; import de.fu_berlin.inf.dpp.SarosContext.Bindings.IBBTransport; import de.fu_berlin.inf.dpp.SarosContext.Bindings.Socks5Transport; import de.fu_berlin.inf.dpp.annotations.Component; import de.fu_berlin.inf.dpp.net.ConnectionState; import de.fu_berlin.inf.dpp.net.IConnectionListener; import de.fu_berlin.inf.dpp.net.IPacketInterceptor; import de.fu_berlin.inf.dpp.net.IReceiver; import de.fu_berlin.inf.dpp.net.IncomingTransferObject; import de.fu_berlin.inf.dpp.net.JID; import de.fu_berlin.inf.dpp.net.NetTransferMode; import de.fu_berlin.inf.dpp.net.SarosNet; import de.fu_berlin.inf.dpp.net.upnp.IUPnPService; import de.fu_berlin.inf.dpp.preferences.PreferenceUtils; import de.fu_berlin.inf.dpp.util.Utils; /** * This class is responsible for handling all transfers of binary data. It * maintains a map of established connections and tries to reuse them. * * @author srossbach * @author coezbek * @author jurke */ @Component(module = "net") public class DataTransferManager implements IConnectionListener { private static final Logger log = Logger .getLogger(DataTransferManager.class); private static final String DEFAULT_CONNECTION_ID = "default"; private final TransferModeDispatch transferModeDispatch = new TransferModeDispatch(); private CopyOnWriteArrayList<IPacketInterceptor> packetInterceptors = new CopyOnWriteArrayList<IPacketInterceptor>(); private volatile JID currentLocalJID; private Connection connection; private final IReceiver receiver; private final IUPnPService upnpService; private final ITransport mainTransport; private final ITransport fallbackTransport; private final PreferenceUtils preferenceUtils; private final Map<String, ConnectionHolder> connections = Collections .synchronizedMap(new HashMap<String, ConnectionHolder>()); private final Lock connectLock = new ReentrantLock(); private final Set<String> currentOutgoingConnectionEstablishments = new HashSet<String>(); private final List<ITransport> availableTransports = new CopyOnWriteArrayList<ITransport>(); private final IByteStreamConnectionListener byteStreamConnectionListener = new IByteStreamConnectionListener() { /** * Adds an incoming transfer. * * @param transferObject * An IncomingTransferObject that has the TransferDescription * as content to provide information of the incoming transfer * to upper layers. */ @Override public void addIncomingTransferObject( final IncomingTransferObject transferObject) { final TransferDescription description = transferObject .getTransferDescription(); boolean dispatchPacket = true; for (IPacketInterceptor packetInterceptor : packetInterceptors) dispatchPacket &= packetInterceptor .receivedPacket(transferObject); if (!dispatchPacket) return; log.trace("[" + transferObject.getTransferMode() + "] received incoming transfer object: " + description + ", throughput: " + Utils.throughput(transferObject.getCompressedSize(), transferObject.getTransferDuration())); if (transferObject.getTransferDescription().compressContent()) { byte[] payload = transferObject.getPayload(); long compressedPayloadLenght = payload.length; try { payload = Utils.inflate(payload, null); } catch (IOException e) { log.error("could not decompress transfer object payload", e); return; } // FIXME change method signature ((BinaryChannelTransferObject) transferObject).setPayload( compressedPayloadLenght, payload); } transferModeDispatch.transferFinished(description.getSender(), transferObject.getTransferMode(), true, transferObject.getCompressedSize(), transferObject.getUncompressedSize(), transferObject.getTransferDuration()); receiver.processTransferObject(transferObject); } @Override public void connectionChanged(String connectionID, JID peer, IByteStreamConnection connection, boolean incomingRequest) { synchronized (connections) { log.debug("bytestream connection changed " + connection.getMode() + " [to: " + peer + "|inc: " + incomingRequest + "|id: " + connectionID + "]"); ConnectionHolder holder = connections.get(toConnectionIDToken( connectionID, peer)); if (holder == null) { holder = new ConnectionHolder(); connections.put(toConnectionIDToken(connectionID, peer), holder); } if (!incomingRequest) { IByteStreamConnection old = holder.out; assert (old == null || !old.isConnected()); holder.out = connection; } else { IByteStreamConnection old = holder.in; assert (old == null || !old.isConnected()); holder.in = connection; } connection.initialize(); } transferModeDispatch.connectionChanged(peer, connection); if (connection.getMode() == NetTransferMode.IBB && incomingRequest && upnpService != null) upnpService.checkAndInformAboutUPnP(); } @Override public void connectionClosed(String connectionID, JID peer, IByteStreamConnection connection) { closeConnection(connectionID, peer); transferModeDispatch.connectionChanged(peer, null); } }; private static class ConnectionHolder { private IByteStreamConnection out; private IByteStreamConnection in; } public DataTransferManager(SarosNet sarosNet, IReceiver receiver, @Nullable @Socks5Transport ITransport mainTransport, @Nullable @IBBTransport ITransport fallbackTransport, @Nullable IUPnPService upnpService, @Nullable PreferenceUtils preferenceUtils) { this.receiver = receiver; this.fallbackTransport = fallbackTransport; this.mainTransport = mainTransport; this.upnpService = upnpService; this.preferenceUtils = preferenceUtils; this.initTransports(); sarosNet.addListener(this); } public void sendData(String connectionID, TransferDescription transferDescription, byte[] payload) throws IOException { JID connectionJID = currentLocalJID; if (connectionJID == null) throw new IOException("not connected to a XMPP server"); IByteStreamConnection connection = getCurrentConnection(connectionID, transferDescription.getRecipient()); if (connection == null) throw new IOException("not connected to " + transferDescription.getRecipient() + " [connection identifier=" + connectionID + "]"); if (log.isTraceEnabled()) log.trace("sending data ... from " + connectionJID + " to " + transferDescription.getRecipient() + "[connection identifier=" + connectionID + "]"); transferDescription.setSender(connectionJID); sendInternal(connection, transferDescription, payload); } /** * @deprecated establishes connections on demand * @param transferDescription * @param payload * @throws IOException */ @Deprecated public void sendData(TransferDescription transferDescription, byte[] payload) throws IOException { JID connectionJID = currentLocalJID; if (connectionJID == null) throw new IOException("not connected to a XMPP server"); if (log.isTraceEnabled()) log.trace("sending data ... from " + connectionJID + " to " + transferDescription.getRecipient()); JID recipient = transferDescription.getRecipient(); transferDescription.setSender(connectionJID); sendInternal(connectInternal(DEFAULT_CONNECTION_ID, recipient), transferDescription, payload); } private void sendInternal(IByteStreamConnection connection, TransferDescription transferData, byte[] payload) throws IOException { try { boolean sendPacket = true; for (IPacketInterceptor packetInterceptor : packetInterceptors) sendPacket &= packetInterceptor.sendPacket(transferData, payload); if (!sendPacket) return; long sizeUncompressed = payload.length; if (transferData.compressContent()) payload = Utils.deflate(payload, null); long transferStartTime = System.currentTimeMillis(); connection.send(transferData, payload); transferModeDispatch.transferFinished(transferData.getRecipient(), connection.getMode(), false, payload.length, sizeUncompressed, System.currentTimeMillis() - transferStartTime); } catch (IOException e) { log.error( Utils.prefix(transferData.getRecipient()) + "failed to send " + transferData + " with " + connection.getMode() + ":" + e.getMessage(), e); throw e; } } /** * @deprecated */ @Deprecated public void connect(JID peer) throws IOException { connect(DEFAULT_CONNECTION_ID, peer); } public void connect(String connectionID, JID peer) throws IOException { if (connectionID == null) throw new NullPointerException("connectionID is null"); if (peer == null) throw new NullPointerException("peer is null"); connectInternal(connectionID, peer); } public TransferModeDispatch getTransferModeDispatch() { return transferModeDispatch; } /** * @deprecated Disconnects {@link IByteStreamConnection} with the specified * peer * * @param peer * {@link JID} of the peer to disconnect the * {@link IByteStreamConnection} */ @Deprecated public boolean closeConnection(JID peer) { return closeConnection(DEFAULT_CONNECTION_ID, peer); } public boolean closeConnection(String connectionIdentifier, JID peer) { ConnectionHolder holder = connections.remove(toConnectionIDToken( connectionIdentifier, peer)); if (holder == null) return false; if (holder.out != null) holder.out.close(); if (holder.in != null) holder.in.close(); return holder.out != null || holder.in != null; } /** * @deprecated */ @Deprecated public NetTransferMode getTransferMode(JID jid) { return getTransferMode(null, jid); } public NetTransferMode getTransferMode(String connectionID, JID jid) { IByteStreamConnection connection = getCurrentConnection(connectionID, jid); return connection == null ? NetTransferMode.NONE : connection.getMode(); } private IByteStreamConnection connectInternal(String connectionID, JID peer) throws IOException { IByteStreamConnection connection = null; String connectionIDToken = toConnectionIDToken(connectionID, peer); synchronized (currentOutgoingConnectionEstablishments) { if (!currentOutgoingConnectionEstablishments .contains(connectionIDToken)) { connection = getCurrentConnection(connectionID, peer); if (connection == null) currentOutgoingConnectionEstablishments .add(connectionIDToken); } if (connection != null) { log.trace("Reuse bytestream connection " + connection.getMode()); return connection; } } connectLock.lock(); try { connection = getCurrentConnection(connectionID, peer); if (connection != null) return connection; JID connectionJID = currentLocalJID; if (connectionJID == null) throw new IOException("not connected to a XMPP server"); ArrayList<ITransport> transportModesToUse = new ArrayList<ITransport>( availableTransports); log.debug("currently used IP addresses for Socks5Proxy: " + Arrays.toString(Socks5Proxy.getSocks5Proxy() .getLocalAddresses().toArray())); for (ITransport transport : transportModesToUse) { log.info("establishing connection to " + peer.getBase() + " from " + connectionJID + " using " + transport.getNetTransferMode()); try { connection = transport.connect(connectionID, peer); break; } catch (IOException e) { log.error(Utils.prefix(peer) + " failed to connect using " + transport.toString() + ": " + e.getMessage(), e); } catch (InterruptedException e) { IOException io = new InterruptedIOException( "connecting cancelled: " + e.getMessage()); io.initCause(e); throw io; } catch (Exception e) { log.error(Utils.prefix(peer) + " failed to connect using " + transport.toString() + " because of an unknown error: " + e.getMessage(), e); } } if (connection != null) { byteStreamConnectionListener.connectionChanged(connectionID, peer, connection, false); return connection; } throw new IOException("could not connect to: " + Utils.prefix(peer)); } finally { synchronized (currentOutgoingConnectionEstablishments) { currentOutgoingConnectionEstablishments .remove(connectionIDToken); } connectLock.unlock(); } } private void initTransports() { boolean forceIBBOnly = false; if (preferenceUtils != null) forceIBBOnly = preferenceUtils.forceFileTranserByChat(); availableTransports.clear(); if (!forceIBBOnly && mainTransport != null) availableTransports.add(0, mainTransport); if (fallbackTransport != null) availableTransports.add(fallbackTransport); log.debug("used transport order for the current XMPP connection: " + Arrays.toString(availableTransports.toArray())); } /** * Sets up the transports for the given XMPPConnection */ private void prepareConnection(final Connection connection) { assert (this.connection == null); initTransports(); this.connection = connection; this.currentLocalJID = new JID(connection.getUser()); for (ITransport transport : availableTransports) { transport.initialize(connection, byteStreamConnectionListener); } } private void disposeConnection() { currentLocalJID = null; boolean acquired = false; try { acquired = connectLock.tryLock(5000, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { acquired = false; } try { for (ITransport transport : availableTransports) transport.uninitialize(); } finally { if (acquired) connectLock.unlock(); } List<ConnectionHolder> currentConnections; synchronized (connections) { currentConnections = new ArrayList<ConnectionHolder>(); for (ConnectionHolder holder : connections.values()) { ConnectionHolder current = new ConnectionHolder(); current.out = holder.out; current.in = holder.in; currentConnections.add(current); } } /* * Just close one side as this will trigger closeConnection via the * listener which will close the other side too */ for (ConnectionHolder holder : currentConnections) { IByteStreamConnection connection; if (holder.out != null) connection = holder.out; else connection = holder.in; assert (connection != null); log.trace("closing " + connection.getMode() + " connection"); try { connection.close(); } catch (Exception e) { log.error("error closing " + connection.getMode() + " connection ", e); } } if (connections.size() > 0) log.warn("new connections were established during connection shutdown: " + connections.toString()); connections.clear(); transferModeDispatch.clear(); connection = null; } @Override public void connectionStateChanged(Connection connection, ConnectionState newState) { if (newState == ConnectionState.CONNECTED) prepareConnection(connection); else if (this.connection != null) disposeConnection(); } // TODO: move to ITransmitter public void addPacketInterceptor(IPacketInterceptor interceptor) { packetInterceptors.addIfAbsent(interceptor); } // TODO: move to IReceiver public void removePacketInterceptor(IPacketInterceptor interceptor) { packetInterceptors.remove(interceptor); } /** * Left over and <b>MUST</b> only used by the STF * * @deprecated * @param incomingTransferObject */ @Deprecated public void addIncomingTransferObject( IncomingTransferObject incomingTransferObject) { byteStreamConnectionListener .addIncomingTransferObject(incomingTransferObject); } /** * Returns the current connection for the remote side. If the local side is * connected to the remote side as well as the remote side is connected to * the local side the local to remote connection will be returned. * * @param connectionID * identifier for the connection to retrieve or <code>null</code> * to retrieve the default one * @param jid * JID of the remote side * @return the connection to the remote side or <code>null</code> if no * connection exists */ private IByteStreamConnection getCurrentConnection(String connectionID, JID jid) { synchronized (connections) { ConnectionHolder holder = connections.get(toConnectionIDToken( connectionID, jid)); if (holder == null) return null; if (holder.out != null) return holder.out; return holder.in; } } private static String toConnectionIDToken(String connectionIdentifier, JID jid) { if (connectionIdentifier == null) connectionIdentifier = DEFAULT_CONNECTION_ID; return connectionIdentifier.concat(":").concat(jid.toString()); } }
const express = require("express"); const exphbs = require("express-handlebars"); const app = express(); const PORT = 8080; const productsRouter = require("./routes/products.router"); const cartsRouter = require("./routes/carts.router"); const helper = require("./helpers/helper.js"); const session = require("express-session"); const userRouter = require("./routes/user.router.js"); const sessionRouter = require("./routes/sessions.router.js"); const authRouter = require("./routes/auth.router.js"); const initializePassport = require("./config/passport.config.js"); const passport = require("passport"); const sessionConfig = require("./utils/session_config.js"); // initiate db require("./dababase.js"); // initiate passport initializePassport(); // Middlewares app.use(express.urlencoded({ extended: true })); app.use(express.json()); app.use(session(sessionConfig)); app.use(passport.initialize()); app.use(passport.session()); // Handlebars config app.engine( "handlebars", exphbs.engine({ helpers: helper, }) ); app.set("view engine", "handlebars"); app.set("views", "src/views"); // Routes app.use("/api/products", productsRouter); app.use("/api/cart", cartsRouter); app.use("/api/users", userRouter); app.use("/api/sessions", sessionRouter); app.use("/auth", authRouter); // Server init app.listen(PORT, () => { console.log(`Listening to port ${PORT}`); });
import math from typing import List import numpy as np from numpy.lib.function_base import average from numpy.random import SeedSequence, default_rng from flock_settings import FlockSettings, Setting from simulation.message import Message from util.vector_helpers import get_distance, vector_to_bearing from .drone_wrapper import DroneWrapper from .mothership_wrapper import MothershipWrapper from .objectives import MothershipObjective, DroneObjective # this implementation adapts implementations found on both # https://alan-turing-institute.github.io/rsd-engineeringcourse/ch01data/084Boids.html # and # https://medium.com/better-programming/boids-simulating-birds-flock-behavior-in-python-9fff99375118 class Flock: """Flock implementation keeping track of all drones""" # pylint: disable=too-many-instance-attributes # pylint: disable=too-many-arguments drones: List[DroneWrapper] = None mother_id = 0 def __init__(self, settings: FlockSettings, positions, velocities): # set attributes using arguments passed to constructor self.flock_size = settings.get(Setting.FLOCK_SIZE) self.message = None self.packet_loss = settings.get(Setting.PACKET_LOSS) self.separation_distance = settings.get(Setting.SEPARATION_DISTANCE) self.bandwidth = settings.get(Setting.BANDWIDTH) self.message_size = settings.get(Setting.MESSAGE_SIZE) self.com_range = settings.get(Setting.MAX_RANGE) self.collision_distance = settings.get( Setting.SEPARATION_DISTANCE) / 10 self.seed = settings.get(Setting.SEED) self.rng = default_rng(self.seed) self.master_seed = SeedSequence(self.seed) child_seeds = self.master_seed.spawn(self.flock_size) self.__collision_count = 0 self.__last_collisions = [] self.__messages_sent_last_step = [] self.mothership_objective = settings.get(Setting.MOTHERSHIP_OBJECTIVE) self.drone_objective = settings.get(Setting.DRONE_OBJECTIVE) self.target_pos = np.array( [settings.get(Setting.TARGET_X), settings.get(Setting.TARGET_Y)]).reshape(2, 1) self.target_radius = settings.get(Setting.TARGET_RADIUS) self.target_heading = settings.get(Setting.TARGET_HEADING) is_mothership_mission = (self.mothership_objective != MothershipObjective.NONE or self.drone_objective == DroneObjective.TARGET_MOTHERSHIP) self.drones = [] for i in range(self.flock_size): if(is_mothership_mission and i == 0): mothership = MothershipWrapper(self, settings, position=positions[:, 0].reshape( (2, 1)), velocity=velocities[:, 0].reshape((2, 1)), seed=child_seeds[0]) self.drones.append(mothership) else: drone = DroneWrapper(self, settings, positions[:, i].reshape( (2, 1)), velocities[:, i].reshape((2, 1)), seed=child_seeds[i], my_id=i) self.drones.append(drone) def get_size(self): return self.flock_size def get_positions(self): """This function returns the positions of all the drones in the flock as a 2xcount array.""" return np.asarray([d.get_exact_position() for d in self.drones]).T.reshape((2, self.flock_size)) def get_approx_positions(self): """This function returns the approximate positions of all the drones in the flock as a 2xcount array.""" return np.asarray([d.get_approximated_position() for d in self.drones]).T.reshape((2, self.flock_size)) def get_speeds(self): """This function returns the sppeds of all the drones in the flock as a list""" return [np.linalg.norm(d.velocity) for d in self.drones] def get_velocities(self): """This function returns the velocities of all the drones in the flock as a 2xcount array""" return np.asarray([d.velocity for d in self.drones]).T.reshape((2, self.flock_size)) def get_headings(self): """This function returns the headings of all the drones in the flock as an list of size flock_size""" return [d.heading for d in self.drones] def update(self, step): messages = self.get_messages_for_step(step) for message in messages: sender_id = message.get_drone_id() for drone in self.drones: receiver_id = drone.my_id if(sender_id != receiver_id and self.drones_in_range(sender_id, receiver_id)): if(self.rng.random() * 100 >= self.packet_loss): drone.handle_message(message) self.__messages_sent_last_step = messages for drone in self.drones: drone.update(1) self.check_for_collisions() def get_messages_for_step(self, step) -> list[Message]: messages = [] total_messages_sent = self.get_total_messages_sent_by_step(step) messages_already_sent = self.get_total_messages_sent_by_step(step - 1) for message_index in range(messages_already_sent, total_messages_sent): sender_index = message_index % self.flock_size message = self.get_drone(sender_index).generate_message() messages.append(message) return messages def get_total_messages_sent_by_step(self, step): return max(0, int(math.floor(step * self.bandwidth / self.message_size))) def get_messages_sent_last_step(self) -> list[Message]: return self.__messages_sent_last_step def print_drones_data(self): for drone in self.drones: drone.print_data() def calculate_cohesion(self): """Calculate cohesion metric for the swarm, returns the desired separation distance over the average distance between the drones and the swarm center measured in km^-1""" if len(self.drones) < 2: return 1 mean = [sum(x)/len(x) for x in zip(*[d.get_exact_position() for d in self.drones])] total = 0 for d in self.drones: total += get_distance(mean, d.get_exact_position()) average_dist = total / len(self.drones) return np.sqrt(len(self.drones)) * self.separation_distance / average_dist / 4 def get_min_separation(self): if len(self.drones) < 2: return 0 nearest_dist = np.Infinity for drone_a in self.drones: for drone_b in self.drones: if drone_a != drone_b: dist = get_distance( drone_a.get_exact_position(), drone_b.get_exact_position()) if(dist < nearest_dist): nearest_dist = dist return nearest_dist / self.separation_distance def get_average_separation(self): if len(self.drones) < 2: return 0 sum = 0 count = 0 for drone_a in self.drones: nearest_dist = np.Infinity for drone_b in self.drones: if drone_a != drone_b: dist = get_distance( drone_a.get_exact_position(), drone_b.get_exact_position()) if dist < nearest_dist: nearest_dist = dist sum += nearest_dist count += 1 return (sum / count) / self.separation_distance def get_max_separation(self): if len(self.drones) < 2: return 0 max = 0 for drone_a in self.drones: nearest_dist = np.Infinity for drone_b in self.drones: dist = get_distance( drone_a.get_exact_position(), drone_b.get_exact_position()) if dist != 0 and dist < nearest_dist: nearest_dist = dist if(nearest_dist > max): max = nearest_dist return max / self.separation_distance def get_velocity_variation(self): if len(self.drones) < 2: return 0 mean_velocity = [sum(x)/len(x) for x in zip(*[d.velocity for d in self.drones])] sum_of_differences_from_mean = 0 speeds = [np.linalg.norm(d.velocity) for d in self.drones] mean_speed = sum(speeds)/len(speeds) for d in self.drones: sum_of_differences_from_mean += get_distance( mean_velocity, d.velocity) return (sum_of_differences_from_mean / len(self.drones)) / mean_speed def get_drone(self, drone_id): return self.drones[drone_id] def drones_in_range(self, drone_a_id, drone_b_id): drone_a = self.drones[drone_a_id] drone_b = self.drones[drone_b_id] dist = get_distance(drone_a.get_exact_position(), drone_b.get_exact_position()) return dist <= self.com_range def get_average_position_error(self): return average([d.get_position_error() for d in self.drones]) def get_average_neighbour_error(self): return average([d.get_neighour_error() for d in self.drones]) def calculate_flock_groups(self): tagged_drones = [False] * self.flock_size to_expand = [] groups = 0 while(not all(tagged_drones)): if(len(to_expand) > 0): selection = to_expand.pop() else: selection = next(index for index, tagged in enumerate( tagged_drones) if not tagged) tagged_drones[selection] = True groups += 1 for i in range(0, self.flock_size): if(not tagged_drones[i] and self.drones_in_range(selection, i)): tagged_drones[i] = True to_expand.append(i) return groups def check_for_collisions(self): collisions = [] for a_index, drone_a in enumerate(self.drones): for b_index, drone_b in enumerate(self.drones): # prevent self and duplicates if(a_index < b_index): dist = get_distance( drone_a.get_exact_position(), drone_b.get_exact_position()) if(dist < self.collision_distance): collision = (a_index, b_index) collisions.append(collision) if(not collision in self.__last_collisions): self.__collision_count += 1 self.__last_collisions = collisions def get_num_collisions(self): return self.__collision_count def get_average_distance_from_mother(self): mother = self.drones[0] return average([get_distance(mother.get_exact_position(), d.get_exact_position()) for d in self.drones[1:]]) def get_average_distance_from_origin(self): return np.linalg.norm(self.get_flock_center()) def get_heading_error(self): pos = self.get_flock_center() heading = vector_to_bearing(pos) error = abs(heading - self.target_heading) if(error > 180): error = 360 - error return error def get_flock_center(self): return np.average([d.get_exact_position() for d in self.drones], axis=0) def get_distance_from_target(self): return get_distance(self.get_flock_center(), self.target_pos) def get_distance_from_circle(self): return abs(self.target_radius - self.get_distance_from_target()) def get_circle_bearing(self): vec = self.get_flock_center() - self.target_pos return vector_to_bearing(vec)
import {z} from "zod"; export const JobDoneDTOSchema = z.object({ /** * Job's UUID */ uuid: z.string(), /** * What was done */ description: z.string(), /** * Number of time units in minutes */ time: z.number(), /** * JobDone's tags */ tags: z.array(z.string()), }).strict(); /** * Job done DTO model */ export type JobDoneDTO = z.infer<typeof JobDoneDTOSchema>;
<?php namespace App\Models; use App\State\Order\StateOrderExitCanceled; use App\State\Order\StateOrderExitConcluded; use App\State\Order\StateOrderExitConference; use App\State\Order\StateOrderExitNew; use App\State\Order\StateOrderExitSeparation; use App\State\Order\StateOrderExitTransfer; use App\State\Order\StateOrderExitTransit; use App\State\Order\StateOrderExitTransport; class OrderExits extends Orders { /** * STATUS DO PEDIDO */ public const STATUSES = [ 'Novo' => StateOrderExitNew::class, 'Cancelado' => StateOrderExitCanceled::class, 'Aguardando Transferência' => StateOrderExitTransfer::class, 'Aguardando Separação' => StateOrderExitSeparation::class, 'Aguardando Conferência' => StateOrderExitConference::class, 'Aguardando Transporte' => StateOrderExitTransport::class, 'Em Transito' => StateOrderExitTransit::class, 'Concluído' => StateOrderExitConcluded::class ]; /** * RETORNA O STATUS DO PEDIDO * @param string $state * @return string|null */ public static function status(string $state):? string { return (array_search($state,self::STATUSES)??null); } /** * RETORNA SE ALGUM ITEM ESTA COM UM STATUS EM ESPECIFICO * @param string $status * @return bool */ public function hasStatusItems(string $status): bool { if(OrderItemExits::where('order_id',$this->id)->where('status',$status)->first()){ return true; } return false; } /** * RETORNA OS ITEMS DO PEDIDO * @return \Illuminate\Database\Eloquent\Relations\HasMany */ public function items() { return $this->hasMany(OrderItemExits::class,'order_id','id'); } /** * RETORNA OS PACOTES DO PEDIDO * @return \Illuminate\Database\Eloquent\Relations\HasMany */ public function packages() { return $this->hasMany(OrderPackages::class,'order_id','id'); } /** * RETORNA OS SERVIÇOS DO PEDIDO * @return \Illuminate\Database\Eloquent\Relations\HasMany */ public function services() { return $this->hasMany(OrderServices::class,'order_id','id'); } /** * MANIPULA AS AÇÕES. * @param string $action * @param ...$arguments * @return mixed */ public function handle(string $action,...$arguments) { $class = self::STATUSES[$this->status]; return (new $class($this))->$action(...$arguments); } }
import fs from "fs"; type Race = { time: number; recordDistance: number }; export function createRacesFromInput(path: string) { const races: Race[] = []; const times: number[] = []; const distances: number[] = []; fs.readFileSync(path) .toString() .split(/\r?\n/) .map((row, index) => { const currentRow = row .split(":")[1] .split(" ") .filter(Number) .map((el) => parseInt(el)); if (index === 0) { times.push(...currentRow); } if (index === 1) { distances.push(...currentRow); } }); if (times.length !== distances.length) { throw new Error("bad input"); } times.forEach((time, index) => { races.push({ time, recordDistance: distances[index], }); }); return races; } type RaceOutcome = { chargeTime: number; distanceTraveled: number }; export function getRacePossibilitiesCount({ race }: { race: Race }) { const possibleOutcomes: RaceOutcome[] = []; for (let i = 0; i <= race.time; i++) { const chargeTime = i; const travelTime = race.time - chargeTime; const speed = i; const distanceTraveled = travelTime * speed; if (i === 0) { possibleOutcomes.push({ chargeTime: 0, distanceTraveled: 0, }); } else { possibleOutcomes.push({ chargeTime, distanceTraveled, }); } } return possibleOutcomes.filter( (possibility) => possibility.distanceTraveled > race.recordDistance ).length; } function getRacePossibilitiesProduct({ races }: { races: Race[] }) { const counts: number[] = []; races.forEach((race) => { const count = getRacePossibilitiesCount({ race }); counts.push(count); }); return counts.reduce((acc, curr) => acc * curr); } // answer: 449820 console.log( getRacePossibilitiesProduct({ races: createRacesFromInput("./input.txt") }) );
#![doc = include_str!("../README.md")] #![allow(unused_variables)] #[macro_use] extern crate pbc_contract_codegen; extern crate contract_version_base; extern crate pbc_contract_common; use contract_version_base::state::ContractVersionBase; use pbc_contract_common::address::Address; use pbc_contract_common::avl_tree_map::AvlTreeMap; use pbc_contract_common::context::ContractContext; use pbc_contract_common::sorted_vec_map::SortedVecSet; const CONTRACT_NAME: &str = env!("CARGO_PKG_NAME"); const CONTRACT_VERSION: &str = env!("CARGO_PKG_VERSION"); /// The state of the vote, which is persisted on-chain. #[state] pub struct VoteState { /// Owner of the voting contract. pub owner: Address, /// Identification of the proposal being voted for. pub proposal_id: u64, /// The list of eligible voters. pub voters: SortedVecSet<Address>, /// The deadline of the vote in UTC millis /// (milliseconds after 1970-01-01 00:00:00 UTC) pub deadline_utc_millis: i64, /// The votes cast by the voters. /// true is for the proposal, false is against. pub votes: AvlTreeMap<Address, bool>, /// The result of the vote. /// None until the votes has been counted, /// Some(true) if the proposal passed, /// Some(false) if the proposal failed. pub result: Option<bool>, pub version: ContractVersionBase, } /// Initialize a new vote for a proposal /// /// # Arguments /// /// * `_ctx` - the contract context containing information about the sender and the blockchain. /// * `proposal_id` - the id of the proposal. /// * `voters` - the list of eligible voters. /// * `deadline_utc_millis` - deadline of the vote in UTC millis. /// /// # Returns /// /// The initial state of the vote. /// #[init] pub fn initialize( ctx: ContractContext, proposal_id: u64, voters: Vec<Address>, deadline_utc_millis: i64, ) -> VoteState { assert_ne!(voters.len(), 0, "Voters are required"); let unique_voters: SortedVecSet<Address> = voters.iter().cloned().collect(); assert_eq!( voters.len(), unique_voters.len(), "All voters must be unique" ); VoteState { owner: ctx.sender, proposal_id, voters: unique_voters, deadline_utc_millis, votes: AvlTreeMap::new(), result: None, version: ContractVersionBase::new(CONTRACT_NAME, CONTRACT_VERSION), } } /// Cast a vote for the proposal. /// The vote is cast by the sender of the action. /// Voters can cast and update their vote until the deadline. #[action(shortname = 0x01)] pub fn vote(ctx: ContractContext, mut state: VoteState, vote: bool) -> VoteState { assert!( state.result.is_none() && ctx.block_production_time < state.deadline_utc_millis, "The deadline has passed" ); assert!(state.voters.contains(&ctx.sender), "Not an eligible voter"); state.votes.insert(ctx.sender, vote); state } /// Count the votes and publish the result. /// Counting will fail if the deadline has not passed. #[action(shortname = 0x02)] pub fn count(ctx: ContractContext, mut state: VoteState) -> VoteState { assert_eq!(state.result, None, "The votes have already been counted"); assert!( ctx.block_production_time >= state.deadline_utc_millis, "The deadline has not yet passed" ); let voters_approving = state.votes.iter().filter(|(_, v)| *v).count(); let vote_passed = voters_approving > state.voters.len() / 2; state.result = Some(vote_passed); state } /// Add voters to the list of eligible voters. /// Voters can be added until the deadline. #[action(shortname = 0x03)] pub fn add_voters(ctx: ContractContext, mut state: VoteState, voters: Vec<Address>) -> VoteState { assert_eq!(ctx.sender, state.owner, "Only the owner can add voters"); assert_eq!(state.result, None, "The votes have already been counted"); let mut unique_voters: SortedVecSet<Address> = voters.iter().cloned().collect(); state.voters.append(&mut unique_voters); state } /// Remove voters from the list of eligible voters. /// Voters can be removed until the deadline. #[action(shortname = 0x04)] pub fn remove_voters( ctx: ContractContext, mut state: VoteState, voters: Vec<Address>, ) -> VoteState { assert_eq!(ctx.sender, state.owner, "Only the owner can add voters"); assert_eq!(state.result, None, "The votes have already been counted"); let voters_to_remove: SortedVecSet<Address> = voters.iter().cloned().collect(); state.voters.retain(|v| !voters_to_remove.contains(v)); for key in voters_to_remove.iter() { state.votes.remove(key); } state }
import { createAppContainer } from 'react-navigation' import { createStackNavigator } from 'react-navigation-stack' import UsersScreen from './screens/Users'; import PostsScreen from './screens/Posts'; import DetailScreen from './screens/Detail'; const AppNavigator = createStackNavigator({ Users: { screen: UsersScreen, navigationOptions: () => ({ title: 'Usuarios' }) }, Posts: { screen: PostsScreen, navigationOptions: () => ({ title: 'Posts' }) }, Detail: { screen: DetailScreen, navigationOptions: () => ({ title: 'Detalle' }) } },{ initialRouteName: 'Users' }) export default createAppContainer(AppNavigator)
import * as algoliasearch from "algoliasearch"; import config from "~/alogolia.config.js"; const client = algoliasearch(config.appId, config.apiKey); const index = client.initIndex("compa"); export const state = () => ({ searchLists: [], qWord: "", }); export const getters = { searchLists: (state) => { return state.searchLists; }, qWord: (state) => { return state.qWord; }, }; export const mutations = { setLists(state, data) { state.searchLists = data; }, setQWord(state, data) { state.qWord = data.searchWord; }, commitQWord(state, data) { state.qWord = data.searchWord; }, }; export const actions = { async getLists({ commit }, payload) { // let searchResult = await index.search(""); let searchResult = await index.search(payload.searchWord); // const userFollows = []; // searchResult.hits.forEach((doc) => { // const data = doc.data(); // userFollows.push(data); // }); for (let i = 0; i < searchResult.hits.length; i++) { const userFollow = searchResult.hits[i]; const userQuerySnapshot = await this.$fire.firestore .collection("user") .where("uid", "==", userFollow.uid) .get(); userQuerySnapshot.forEach((doc) => { const userData = doc.data(); userFollow.name = userData.name; userFollow.photoURL = userData.photoURL; }); } return commit("setLists", searchResult.hits); }, };
import {RouteProp, useNavigation, useRoute} from '@react-navigation/native'; import React, { FC, useCallback, useEffect, useMemo, useLayoutEffect, useState, } from 'react'; import {View, SectionList, SafeAreaView, ActivityIndicator} from 'react-native'; import Api from '../../../Api'; import {PRIMARY} from '../../../constants/colors'; import {px} from '../../../constants/constants'; import {RegionList} from '../../../types/models/address.model'; import {useFetching} from '../../../utils/hooks'; import {navigationRef} from '../../../utils/refs'; import Empty from '../../common/Empty'; import {AddressSearch, SectionListItem} from './AddressComponent'; let subscribe: (params: string) => void; type SelectRegionParams = { title: string; region?: string; }; type NavigationType = { SelectRegion: SelectRegionParams; }; const SelectRegion: FC = () => { const navigation = useNavigation(); const {params} = useRoute<RouteProp<NavigationType, 'SelectRegion'>>(); const [loading, fetchFn, res] = useFetching<RegionList.RootObject>( Api.regionList, ); const [search, setSearch] = useState<string>(''); const data = (res?.data || {list: []}).list; useEffect(() => { fetchFn(params.region || ''); }, [fetchFn, params.region]); // 配置header useLayoutEffect(() => { navigation.setOptions({ headerShown: true, headerTintColor: 'black', headerStyle: {backgroundColor: 'white'}, headerTitleAlign: 'center', title: params.title, }); }, [navigation, params]); // 生成sectionList所需要的数据 const sectionData = useMemo(() => { const map: Record<string, string[]> = {}; data .filter(({name}) => { return name.toUpperCase().includes(search.toUpperCase()); }) .forEach(({name}) => { const category = name[0].toUpperCase(); if (map[category]) { map[category].push(name); return; } map[category] = [name]; }); return Object.keys(map).map((title) => { return { title, data: map[title].sort(), }; }); }, [data, search]); const handleSelect = useCallback((params: string) => { subscribe && subscribe(params); }, []); if (!res && loading) { return <ActivityIndicator color={PRIMARY} style={{flex: 1}} />; } return ( <SafeAreaView style={{flex: 1}}> <AddressSearch value={search} onChange={setSearch} placeholder={'Search'} /> <SectionList stickySectionHeadersEnabled keyboardShouldPersistTaps={'always'} style={{flex: 1}} sections={sectionData} ItemSeparatorComponent={() => ( <View style={{height: 1, backgroundColor: '#D8D8D8'}} /> )} keyExtractor={(item, index) => item + index} renderItem={({item}) => ( <SectionListItem style={{ height: 120 * px, backgroundColor: 'white', paddingLeft: 30 * px, }} textStyle={{fontSize: 40 * px}} title={item} onPress={handleSelect} /> )} renderSectionHeader={({section: {title}}) => ( <SectionListItem style={{ height: 80 * px, backgroundColor: '#D3D3D3', paddingLeft: 30 * px, }} title={title} /> )} ListEmptyComponent={<Empty title="Empty" />} /> </SafeAreaView> ); }; export const selectRegion = (navigationParams: SelectRegionParams) => { navigationRef.current.navigate('SelectRegion', navigationParams); return new Promise<string>((resolve) => { subscribe = (params: string) => { resolve(params); navigationRef.current.goBack(); }; }); }; export default SelectRegion;
import time from pyspark.sql import SparkSession from pyspark.sql.functions import col from pyspark.ml.linalg import DenseVector, SparseVector from pyspark import StorageLevel, RDD, SparkContext from typing import List, Tuple, Dict from .InitialThresholdsFinder import InitialThresholdsFinder from .ManyValuesThresholdFinder import ManyValuesThresholdFinder from .FewValuesThresholdFinder import FewValuesThresholdFinder from .DiscretizerModel import DiscretizerModel class MDLPDiscretizer: """ * Entropy minimization discretizer based on Minimum Description Length Principle (MDLP) proposed by Fayyad and Irani in 1993 [1]. * [1] Fayyad, U., & Irani, K. (1993). "Multi-interval discretization of continuous-valued attributes for classification learning." * Note: Approximate version may generate some non-boundary points when processing limits in partitions. """ DEFAULT_STOPPING_CRITERION = 0 """ The original paper suggested 0 for the stopping criterion, but smaller values like -1e-3 yield more splits """ DEFAULT_MIN_BIN_PERCENTAGE = 0 """ * Don't allow less that this percent of the total number of records in a single bin. * The default is 0, meaning that its OK to have as few as a single record in a bin. * A value of 0.1 means that no fewer than 0.1% of records will be in a single bin. """ DEFAULT_MAX_BY_PART = 100000 """ * Maximum number of elements in a partition. * If this number gets too big, you could run out of memory depending on resources. """ def __init__(self, data, stopping_criterion=DEFAULT_STOPPING_CRITERION, max_by_part=DEFAULT_MAX_BY_PART, min_bin_percentage=DEFAULT_MIN_BIN_PERCENTAGE, approximate=True): """ * @param data Dataset of LabeledPoint * @param stopping_criterion (optional) used to determine when to stop recursive splitting * @param max_by_part (optional) used to determine maximum number of elements in a partition * @param min_bin_percentage (optional) minimum percent of total dataset allowed in a single bin. * @param approximate If true, boundary points are computed faster but in an approximate manner. """ self.data = data self.stopping_criterion = stopping_criterion self.max_by_part = max_by_part self.min_bin_percentage = min_bin_percentage self.approximate = approximate # Dictionary maps labels (classes) to integer indices self.labels2int = self.data.select('label').distinct().rdd.map(lambda x: x[0]).zipWithIndex().collectAsMap() self.n_labels = len(self.labels2int) def process_continuous_attributes(self, cont_indices: List[int], n_features: int): """ * Get information about the attributes before performing discretization. * @param cont_indices Indexes to discretize (if not specified, they are calculated). * @param n_features Total number of input features. * @return Indexes of continuous features. """ if cont_indices is not None: intersect = set(range(n_features)).intersection(cont_indices) if len(intersect) != len(cont_indices): raise ValueError("Invalid continuous feature indices provided") return cont_indices else: return list(range(n_features)) def get_sorted_distinct_values(self, b_class_distrib, feature_values): """ * Group elements by feature and point (get distinct points). * Since values like (0, Float.NaN) are not considered unique when calling reduceByKey, use the serialized version of the tuple. * @return sorted list of unique feature values """ non_zeros = (feature_values .map(lambda x: (f"{x[0][0]},{x[0][1]}", x[1])) .reduceByKey(lambda x, y: [a + b for a, b in zip(x, y)]) .map(lambda x: ((int(x[0].split(",")[0]), float(x[0].split(",")[1])), x[1]))) zeros = (non_zeros .map(lambda x: (x[0][0], x[1])) .reduceByKey(lambda x, y: [a + b for a, b in zip(x, y)]) .map(lambda x: ((x[0], 0.0), [b_class_distrib.value[i] - x[1][i] for i in range(len(x[1]))])) #.map(lambda x: ((x[0], 0.0), x[1])) instead .filter(lambda x: sum(x[1]) > 0) ) distinct_values = non_zeros.union(zeros) start = time.time() result = distinct_values.sortByKey() print("Done sortByKey in", time.time() - start) return result def initial_thresholds(self, points: RDD[Tuple[Tuple[int, float], List[int]]], n_features: int): """ * Computes the initial candidate points by feature. * @param points RDD with distinct points by feature ((feature, point), class values). * @param n_features the number of continuous features to bin * @return RDD of candidate points. """ finder = InitialThresholdsFinder() if self.approximate: return finder.find_fast_initial_thresholds(points, self.n_labels, self.max_by_part) else: return finder.find_initial_thresholds(points, n_features, self.n_labels, self.max_by_part) def find_all_thresholds(self, initial_candidates, sc: SparkContext, max_bins: int): """ * Divide RDD into two categories according to the number of points by feature. * @return find threshold for both sorts of attributes - those with many values, and those with few. """ big_indexes = {k: v for k, v in initial_candidates.countByKey().items() if v > self.max_by_part} print(f"Big indexes: {big_indexes}") b_big_indexes = sc.broadcast(big_indexes) min_bin_weight = int(self.min_bin_percentage * self.data.count() / 100.0) big_thresholds = self.find_big_thresholds(initial_candidates, max_bins, min_bin_weight, big_indexes) small_thresholds = self.find_small_thresholds(initial_candidates, max_bins, min_bin_weight, b_big_indexes) big_thresholds_rdd = sc.parallelize(big_thresholds.items()) all_thresholds = small_thresholds.union(big_thresholds_rdd).collect() return all_thresholds def find_big_thresholds(self, initial_candidates: RDD[Tuple[int, Tuple[float, List[int]]]], max_bins: int, min_bin_weight: int, big_indexes: Dict[int, int]): """ * Features with too many unique points must be processed iteratively (rare condition) * @return the splits for features with more values than will fit in a partition. """ print(f"Find big thresholds") big_thresholds = {} big_thresholds_finder = ManyValuesThresholdFinder(self.n_labels, self.stopping_criterion, max_bins, min_bin_weight, self.max_by_part) for key in big_indexes: cands = initial_candidates.filter(lambda x: x[0] == key).values().sortByKey() big_thresholds[k] = big_thresholds_finder.find_thresholds(cands) return big_thresholds def find_small_thresholds(self, initial_candidates: RDD[Tuple[int, Tuple[float, List[int]]]], max_bins: int, min_bin_weight: int, b_big_indexes): """ * The features with a small number of points can be processed in a parallel way * @return the splits for features with few values """ print("Find small thresholds") small_thresholds_finder = FewValuesThresholdFinder(self.n_labels, self.stopping_criterion, max_bins, min_bin_weight) return initial_candidates \ .filter(lambda x: x[0] not in b_big_indexes.value) \ .groupByKey() \ .mapValues(list) \ .mapValues(lambda x: small_thresholds_finder.find_thresholds(sorted(x, key=lambda x: x[0]))) def build_model_from_thresholds(self, n_features: int, continuous_vars: List[int], all_thresholds: List[Tuple[int, List[float]]]): """ * @return the discretizer model that can be used to bin data """ thresholds = [None] * n_features for idx in continuous_vars: thresholds[idx] = [float('-inf'), float('inf')] for k, vth in all_thresholds: thresholds[k] = vth print("Number of features with thresholds computed: {}".format(len(all_thresholds))) print("Thresholds:\n {}".format(";\n".join([", ".join(map(str, t)) for t in thresholds]))) print("Thresholds raw: {}".format(thresholds)) return DiscretizerModel(thresholds) def train(self, cont_feat=None, max_bins=15): """ * Run the entropy minimization discretizer on input data. (train model) * @param cont_feat Indices to discretize (if not specified, the algorithm tries to figure it out). * @param max_bins Maximum number of thresholds per feature. * @return A discretization model with the thresholds by feature. """ start0 = time.time() if self.data.storageLevel == StorageLevel.NONE: self.data.persist(StorageLevel.MEMORY_ONLY) print("The input data is now cached in memory.") if self.data.filter(col("label").isNull()).count() > 0: raise ValueError("Some NaN values have been found in the label Column. This problem must be fixed before continuing with discretization.") sc = self.data.rdd.context num_partitions_df = self.data.rdd.getNumPartitions() print(f"Number of partitions in DataFrame: {num_partitions_df}") b_labels2int = sc.broadcast(self.labels2int) class_distrib = self.data.rdd.map(lambda x: b_labels2int.value[x.label]).countByValue() b_class_distrib = sc.broadcast(class_distrib) b_n_labels = sc.broadcast(self.n_labels) n_features = len(self.data.first().features) continuous_vars = self.process_continuous_attributes(cont_feat, n_features) print("Number of labels:", self.n_labels) print("Number of continuous attributes:", len(continuous_vars)) print("Total number of attributes:", n_features) if not continuous_vars: print("Discretization aborted. No continuous attributes in the dataset!") sc.broadcast(continuous_vars) def map_to_feature_values(lp): # labeled point c = [0] * b_n_labels.value c[b_labels2int.value[lp.label]] = 1 vector = lp.features if isinstance(vector, DenseVector): return [((i, float(vector[i])), c) for i in range(len(vector))] elif isinstance(vector, SparseVector): return [((int(i), float(vector[int(i)])), c) for i in vector.indices] feature_values = self.data.rdd.flatMap(map_to_feature_values) sorted_values = self.get_sorted_distinct_values(b_class_distrib, feature_values) arr = [False] * n_features for idx in continuous_vars: arr[idx] = True b_arr = sc.broadcast(arr) # Get only boundary points from the whole set of distinct values start1 = time.time() initial_candidates = (self.initial_thresholds(sorted_values, n_features) .map(lambda x: (x[0][0], (x[0][1], x[1]))) .filter(lambda x: b_arr.value[x[0]]) .cache()) print("Done finding initial thresholds in", time.time() - start1) start2 = time.time() all_thresholds = self.find_all_thresholds(initial_candidates, sc, max_bins) print("Done finding MDLP thresholds in", time.time() - start2) print("Total running times", time.time() - start0) print("Now returning model...") return self.build_model_from_thresholds(n_features, continuous_vars, all_thresholds)
/* * Copyright 1999-2018 Alibaba Group Holding Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.csp.sentinel.slots.block.flow.controller; import com.alibaba.csp.sentinel.node.Node; import com.alibaba.csp.sentinel.node.OccupyTimeoutProperty; import com.alibaba.csp.sentinel.slots.block.RuleConstant; import com.alibaba.csp.sentinel.slots.block.flow.PriorityWaitException; import com.alibaba.csp.sentinel.slots.block.flow.TrafficShapingController; import com.alibaba.csp.sentinel.util.TimeUtil; /** * Default throttling controller (immediately reject strategy). * * @author jialiang.linjl * @author Eric Zhao */ public class DefaultController implements TrafficShapingController { private static final int DEFAULT_AVG_USED_TOKENS = 0; // 就是 FlowRule 的 count private double count; // 就是 FlowRule 的 grade private int grade; public DefaultController(double count, int grade) { this.count = count; this.grade = grade; } @Override public boolean canPass(Node node, int acquireCount) { return canPass(node, acquireCount, false); } @Override public boolean canPass(Node node, int acquireCount, boolean prioritized) { // 当前时间窗口内已创建的线程数量(FLOW_GRADE_THREAD) 或 已通过的请求个数(FLOW_GRADE_QPS) int curCount = avgUsedTokens(node); if (curCount + acquireCount > count) { // 如果该请求存在优先级,即 prioritized 设置为 true,并且流控类型为基于QPS进行限流,则进入if,否则直接返回false if (prioritized && grade == RuleConstant.FLOW_GRADE_QPS) { long currentTime; long waitInMs; currentTime = TimeUtil.currentTimeMillis(); // 尝试抢占下一个滑动窗口的令牌,并返回该时间窗口所剩余的时间 // 如果获取失败,则返回 OccupyTimeoutProperty.getOccupyTimeout() 值,该返回值的作用就是当前申请资源的线程将 sleep(阻塞)的时间 waitInMs = node.tryOccupyNext(currentTime, acquireCount, count); // 如果 waitInMs 小于抢占的最大超时时间,则在下一个时间窗口中增加对应令牌数,并且线程将sleep if (waitInMs < OccupyTimeoutProperty.getOccupyTimeout()) { node.addWaitingRequest(currentTime + waitInMs, acquireCount); node.addOccupiedPass(acquireCount); sleep(waitInMs); // PriorityWaitException indicates that the request will pass after waiting for {@link @waitInMs}. // 这里不是很明白为什么等待 waitMs 之后,还需要抛出 PriorityWaitException,那这个prioritized 机制、 // 可抢占下一个时间窗口的令牌有什么意义呢?应该是一个BUG吧 throw new PriorityWaitException(waitInMs); } } // 否则直接返回 false,最终会直接抛出 FlowException,即快速失败 return false; } return true; } private int avgUsedTokens(Node node) { if (node == null) { return DEFAULT_AVG_USED_TOKENS; } return grade == RuleConstant.FLOW_GRADE_THREAD ? node.curThreadNum() : (int) (node.passQps()); } private void sleep(long timeMillis) { try { Thread.sleep(timeMillis); } catch (InterruptedException e) { // Ignore. } } }
package data.api.state import androidx.compose.runtime.Immutable @Immutable sealed class NetworkDataState<out T> { object Loading : NetworkDataState<Nothing>() data class Success<T>(val data: T) : NetworkDataState<T>() data class Error<T>(val error: Throwable? = null) : NetworkDataState<T>() }
<!doctype linuxdoc system> <article> <title>Oracle 8i on Linux RH7.X Installation HOWTO <author>Krastio Atanassov <tt/&lt;[email protected]&gt;/ , and Luca Roversi <tt/&lt;[email protected]&gt;/ <date>v0.1, 2002-07-15 <abstract> Following this HOWTO you should be able to get "Oracle 8i, version 8.1.7, Enterprise Edition for Linux" installed on a RedHat 7.X distribution (and, we hope, on distributions based/derived from it.) You will also have some few hints at how to create a database. We decide to write this notes because we did not manage to get through the installation, simply following the already existing "Oracle 8 for Linux" HOWTOs, and Oracle documentation and we found people on the net experiencing our problems. </abstract> <toc> <sect>Introduction <sect1>What's in here? <p> A sequence of steps that brought us to let Oracle 8i, and Linux RedHat 7.2 working together. <sect1>Who is this HOWTO for? <p> This document is for people who want to install Oracle 8i version 8.1.7 Enterprise edition on Linux RedHat 7.2. At the time Luca Roversi tried to combine the twos, he could only find people on the net who was wandering why previous HOWTOs could not lead them to a successful installation. We have not yet realized the points where this HOWTO substantially differs from previous HOWTOs on the same subject; however, it lists operations that seems to be correct. <sect1>Current versions of this document <p> The web site where this document can be found is: <url name="author's web site" url="http://www.di.unito.it/~rover/LOCAL-HOWTOS/"> <sect1>Disclaimer <p> You get what you pay for. We offer no warranty of any kind, implied or otherwise. May be we shall help you where we can, but, legally, you are on your own. <sect1>Credits and Thanks <p> This HOWTO has been written by Krastio Atanassov and Luca Roversi. The very first version could not have been created without the initial support the second author obtained from various mailing lists. Also, the very first revision was written exploiting Stephen Darlington's <tt/&lt;[email protected]&gt;/ "Oracle for Linux Installation HOWTO" sgml source as a template. We welcome any constructive feedback on this HOWTO and any general Linux or Oracle issues. Email us at <url url="mailto:[email protected]" name="[email protected]"> or/and <url url="mailto:[email protected]" name="[email protected]">. <sect1>License <p> This document is copyright 2002 Krastio Atanassov and Luca Roversi. <p> Permission is granted to copy, distribute and/or modify this document under the terms of the <url url="http://www.gnu.org/copyleft/fdl.html" name="GNU Free Documentation License">, Version 1.1 or any later version published by the Free Software Foundation. <sect>Starting off <sect1>Prerequisites <p> At least 800M free on your hard disk. Type: <verb> bash$ df -h Filesystem Size Used Avail Use% Mounted on /dev/hda2 5.3G 3.6G 1.4G 72% / </verb> and read the field Avail. <sect2>Hardware <p> The steps we are going to describe allow to have Oracle 8i, version 8.1.7 running on: <itemize> <item> a laptop Toshiba Satellite 2800-100 with 128Mb RAM and a 600 Mhz Intel Celeron; <item> others .... </itemize> In any case, never underestimate Oracle's system prerequisites. <sect1>Linux setup <sect2>Distribution <p> We focus on a Linux RedHat 7.2 distribution, since we had problems with it and we wanted to use it. The steps we are going to describe should work on any Red Hat 7.2 based Linux distribution. <sect2>Distribution Setup <p> We assume you have your Linux RedHat 7.2 box installed and working in a reasonable way for you. In any case, 'base' packages, X Windows (the installation routine is a Java GUI) and the development tools regardless of whether you intend doing any coding or not is what you need. <sect2>Setting users and groups <p> Login as root: <tt> $ su - root </tt> and type whatever password you decided root must have. Create groups: <verb> bash# groupadd oinstall bash# groupadd dba bash# groupadd oper </verb> Create oracle user and set its password: <verb> bash# useradd oracle -g oinstall -G dba,oper bash# passwd oracle (to change password) </verb> <sect2>Installing the right Java Virtual Machine <p> The only Java Virtual Machine compatible with Oracle 8i, version 8.1.7, is: <url url="ftp://sunsite.dk/mirrors/java-linux/JDK-1.1.8/i386/v3/jdk118_v3-glibc-2.1.3.tar.bz2">. <newline> Do not think: "newer versions will be less buggy", as the installer probably won't work. And don't think. Once downloaded it, move it: <tt> bash# mv jdk118_v3-glibc-2.1.3.tar.bz2 /usr/local </tt> untar it: <tt> bash# tar xvIf jdk118_v3-glibc-2.1.3.tar.bz2 </tt> and create a symbolic link to the folder the command here above has just created: <tt> bash# ln -s /usr/local/jdk118_v3 /usr/local/java </tt> <sect2>Kernel parameters <p> Oracle documentation suggests that you make changes to the Linux kernel so you can get more shared memory. If you decide to follow that way, keep the instructions in the Oracle documentation and the <url name="Linux Kernel HOWTO" url="http://www.linuxdoc.org/HOWTO/Kernel-HOWTO.html"> at hand to build your new kernel. <p> In fact, the required changes can be made by setting some parameter in a suitable initialization file. Just follow some steps: <itemize> <item> <verb> bash# cd /etc </verb> and create a new file <tt>rc.config</tt>, if it does not exists. Inside <tt>rc.config</tt> copy the following four lines: <verb> cd /proc/sys/kernel echo 250 32000 100 128 > sem echo 4294967295 > shmmax echo 4096 > shmmni </verb> <item> Edit the file <tt>/etc/rc</tt> and add the line: <verb> /etc/rc.config </verb> </itemize> <p> In any case, if you want just to start playing with Oracle 8i, version 8.1.7, Linux RedHat 7.2 default settings can work fine, and you do not need to set any kernel parameter, as just described. <sect2>Setting up some libraries <p> There may be some compatibility problems between Oracle 8i and gcc versions >= 2.1. If you experience them, download these rpms: <url url="http://www.pawprint.net/linux/compat-egcs-6.2-1.1.2.14.i386.rpm" name="compat-egcs-6.2-1.1.2.14.i386.rpm"><newline> <url url="http://www.pawprint.net/linux/compat-glibc-6.2-2.1.3.2.i386.rpm" name="compat-glibc-6.2-2.1.3.2.i386.rpm"><newline> <url url="http://www.pawprint.net/linux/compat-libs-6.2-3.i386.rpm" name="compat-libs-6.2-3.i386.rpm"><newline> install them, as usual, by: <verb> $ rpm -Uvh compat-egcs-6.2-1.1.2.14.i386.rpm compat-glibc-6.2-2.1.3.2.i386.rpm compat-libs-6.2-3.i386.rpm </verb> and, finally set a symbolic link because there is a small installation bug in one of the packages just installed: <verb> bash# ln -s /bin/id /usr/bin/id </verb> <sect2>Final step <p> Reboot your machine and keep reading... <sect>Installing Oracle 8i, version 8.1.7 <sect1>Setting up oracle's shell <p> Login as oracle user, edit the file <tt>.bash_profile</tt> and copy the following lines into it: <verb> # +------------------------------------------------------------+ # | FILE : .bash_profile | # +------------------------------------------------------------+ umask 022 EDITOR=vi; export EDITOR TERM=xterm; export TERM TMPDIR=/tmp; export TMPDIR # +--------------------------+ # | SETUP ORACLE ENVIRONMENT | # +--------------------------+ export ORACLE_SID=O817DB export ORACLE_BASE=/u01/app/oracle export ORACLE_HOME=/u01/app/oracle/product/8.1.7 export LD_LIBRARY_PATH=$ORACLE_HOME/lib:/lib:/usr/lib:/usr/local/lib export TNS_ADMIN=$ORACLE_HOME/network/admin export NLS_LANG=AMERICAN_AMERICA.WE8ISO8859P1 export ORA_NLS33=$ORACLE_HOME/ocommon/nls/admin/data export ORACLE_OWNER=oracle export ORACLE_TERM=xterm # +--------------------------+ # | LINUX STUFF | # +--------------------------+ export LD_ASSUME_KERNEL=2.2.5 source /usr/i386-glibc21-linux/bin/i386-glibc21-linux-env.sh # +--------------------------+ # | SETUP SEARCH PATH | # +--------------------------+ PATH=$ORACLE_HOME/bin:/opt/bin:/bin:/usr/bin:/usr/local/bin:/usr/sbin:/usr/X11R6/bin:/usr/local/java/bin:. export PATH # +--------------------------+ # | SETUP JAVA ENVIRONMENT | # +--------------------------+ export JAVA_HOME=/usr/local/java export CLASSPATH=/u01/app/oracle/product/8.1.7/jdbc/lib/classes12.zip:/u01/app/oracle/product/8.1.7/JRE:/u01/app/oracle/product/8.1.7/jlib:/u01/app/oracle/product/8.1.7/rdbms/jlib:/u01/app/oracle/product/8.1.7/network/jlib:. # +-------------+ # | "GREETINGS" | # +-------------+ echo ".bash_profile executed" </verb> Save the new version of <tt>.bash_profile</tt> and re-read it, by issuing: <verb> bash$ source .bash_profile </verb> Finally, if you have not any window manager running, it is time to let it running. <sect1>Starting the installer <p> We shall work under the hypothesis that you want to install cdrom Oracle distribution. Mount the cdrom with: <verb> bash$ mount /mnt/cdrom </verb> and move to the directory that contains the installer: <verb> bash$ cd /mnt/cdrom/install/linux </verb> Then, launch the installer by: <verb> bash$ ./runInstaller </verb> and follow the steps on the GUI it should appear: <enum> <item> after a first click on <tt>NEXT</tt> verify that the proposed path is: <verb> /u01/app/oracle/product/8.1.7 </verb> and click <tt>NEXT</tt> again; <item> fill in the filed <tt>Unix Group Name</tt> with the value: <verb> oinstall </verb> If, for any reasons, this is not your first attempt to install Oracle, you will not be prompted for the <tt>Unix Group Name</tt>. In this case jump to step 4, below. <item> A pop-up window will ask you to run a script as root user, so, open a terminal emulator and type in: <verb> bash$ su bash# cd $ORACLE_HOME bash# ./orainstRoot.sh </verb> When you're done click <tt>Retry</tt> on the pop-up window. <item> You are now given the option of what to install. Choose <tt>Oracle Enterprise Edition</tt>, and click <tt>Next</tt>. <p> It should now allow you to choose what you install with much finer granularity. Unless you're particularly constrained by disk space or know exactly what you need, choose <tt>Typical</tt> and click <tt>Next</tt>. <item> When it asks you the <tt>Global database name</tt>, if you do not have any particular needs you can type in <tt>oracle.localdomain</tt>. Also, verify that the values of <tt>SID</tt> is set to: <verb> O817DB </verb> Then, click <tt>Next</tt>. <item> The next step is to set the location of the database. Type in: <verb> /u01 </verb> and click <tt>Next</tt>. <item> Finally, you are asked to indicate the location where you put java. If you followed our suggestions the path is already: <verb> /usr/local/java </verb> Since it is fine, click <tt>Next</tt>, and, then <tt>Install</tt>. <item> The installation completes by a pop-up windows that asks you to run a script as root. If you closed the previously opened terminal open one again and type: <verb> bash$ su bash# cd $ORACLE_HOME bash# ./root.sh </verb> After the script completes, click <tt>OK</tt> on the pop-up window. <item> <tt>Oracle Net8 Configuration</tt> starts. Choose <tt>Perform typical configuration</tt> and click <tt>Next</tt>. <item> The configuration tool that starts is the <tt>Database Configuration Assistant</tt>. <p> It may signal errors like: <verb> ORA-03114: not connected to ORACLE </verb> The temporary solution is to just click on <tt>Abort</tt>. These kinds of errors will be recovered in a few!! <p> When the <tt>Database Configuration Assistant</tt> concludes its tasks, just click on <tt>Next</tt> and the installation concludes. <p> If you needed to click on <tt>Abort</tt>, you must: <itemize> <item> Download the patch: <url url="http://www.pawprint.net/linux/glibc-2.1.3-stubs.tar.gz" name="glibc-2.1.3-stubs.tar.gz"> <item> move it into ORACLE_HOME by: <verb> bash$ mv ./glibc-2.1.3-stubs.tar.gz $ORACLE_HOME </verb> and let ORACLE_HOME your working directory: <verb> bash$ cd $ORACLE_HOME </verb> <item> uncompress and untar the patch: <verb> bash$ gunzip glibc-2.1.3-stubs.tar.gz bash$ tar xvf glibc-2.1.3-stubs.tar </verb> <item> run the patch script: <verb> bash$ ./setup_stubs.sh </verb> When it stops you are done! </itemize> </enum> <sect>Creating a database <p> We just typed: <verb> bash$ dbassist </verb> and we played around with the default options. This allowed us to generate an instance of Oracle 8i we could use for teaching purposes, during an undergraduate course on the foundational principles of data bases. If you need more professional-oriented instances, consult other HOWTOs or read Oracle documentation. <p> In any case, at this point, what you should be able to do is to let interactive Oracle sql interpreter SQL*Plus run, by issuing: <verb> bash$ sqlplus </verb> and by choosing one of the following two default account/passwd pairs that Oracle creates by default. The first pair is: <verb> user-name:sys password:change_on_install </verb> while the second is: <verb> user-name:system password:manager </verb> <p> However, if you, just for example, want to connect from/to another machine we address you to other HOWTOs; for example, Stephen Darlington's "Oracle for Linux Installation HOWTO" covers this subjects and gives other useful hints in its final sections. <sect>Final Words <p> Our goal was to write a short list of steps to have Oracle 8i, version 8.1.7, running on RedHat 7.2. We think we have gotten to our goal, so we stop here. <p> We think that it would be nice merge all HOWTOs, related to some Oracle installation on some Linux distribution could be very helpful. This is not in our coming projects. Any volunteer? <sect1>Some Internet Resources <p> To conclude, we have copied here, with some minor changes, the list of Internet resources Stephen Darlington's "Oracle for Linux Installation HOWTO" lists, just for easy of use: <itemize> <item><url name="Oracle Technet" url="http://technet.oracle.com">. This is Oracle's public and free support website. Lot's of very useful information there. <item><url name="Oracle Metalink" url="http://support.oracle.com">. Oracle's private (you need a support contract) support website. Only slightly more useful than Technet! <item><url name="Oracle Fans" url="http://www.orafans.com">. Editorials and support forums. No official connection to Oracle. <item><url name="OraFaq" url="http://www.orafaq.org">. A site full of questions and answers regarding Oracle on all platforms. <item>Oracle Linux mailing list (Send a mail to <url url="mailto:[email protected]" name="[email protected]"> with the words 'SUBSCRIBE ORACLE-LINUX-L' in the body. </itemize> </article>
<!DOCTYPE html> <html lang="ru" xmlns="http://www.w3.org/1999/xhtml" xmlns:th="https://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Страница заказа</title> <link rel="stylesheet" href="../static/css/styles.css"> <script src="https://api-maps.yandex.ru/v3/?apikey=d4c30c84-8597-42a1-b916-fedb4bc275e8&suggest_apikey=6d2ad455-7f44-4302-ba2b-90525671a7b0&lang=ru_RU" type="text/javascript"></script> <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script> <style> #startpoint { margin-bottom: 10px; } .suggested-locations { list-style-type: none; padding: 0; } .suggested-locations li { cursor: pointer; padding: 5px; background-color: #eee; } .suggested-locations li:hover { background-color: #ccc; } .radio { padding: 0; } form { width: 80%; margin: 0 auto; padding: 20px; border: 1px solid #ccc; border-radius: 5px; background-color: #f9f9f9; text-align: center; } </style> </head> <body> <header> <h1>Грузоперевозки - это просто!</h1> </header> <p id="notification"></p> <div id="map" style= "height: 600px"></div> <form method="post" action="/order" th:object="${trip}"> <label for="startpoint">Начальная точка:</label> <input type="text" id="startpoint" placeholder="Введите геолокацию" th:field="*{pickupLocation}"> <ul id="suggested-locations" class="suggested-locations"></ul> <label for="endpoint">Конечная точка:</label> <input type="text" id="endpoint" placeholder="Введите геолокацию" th:field="*{dropoffLocation}"> <ul id="suggested-locations-2" class="suggested-locations"></ul> <button id="confirmOrder">Подтверждение заказа</button> <button type="button" id="orderDetails">Детали заказа</button> <div id="orderDetailsForm" style="display: none;"> <label for="description">Описание:</label> <textarea id="description" th:field="*{comment}"></textarea> <label for="tariff">Выбрать тариф:</label> <select id="tariff" th:field="*{tarif}"> <option th:value="'До 700 кг'">До 700 кг</option> <option th:value="'До 1.5 тонн'">До 1.5 тонн</option> <option th:value="'До 2 тонн'">До 2 тонн</option> <option th:value="'До 3.5 тонн'">До 3.5 тонн</option> <option th:value="'До 5 тонн'">До 5 тонн</option> </select> <label for="price">Цена:</label> <input type="text" id="price" style= "width: 250px" th:field="*{tripCost}"> <label for="pay">Способ оплаты:</label> <select id="pay" th:field="*{paymentType}"> <option th:value="false" value="cash">Наличные</option> <option th:value="true" value="card">SberPay</option> </select> <!-- <label for="payment">Оплата:</label>--> <!-- <input type="text" id="payment" style= "width: 250px">--> <label> <input type="radio" name="dateTime" id="dateTimePicker" value="dateTime" checked> Выбор даты и времени: <input type="datetime-local" id="dateTimeInput" name="dateTimeInput"> </label> <label> <input type="radio" name="dateTime" id="nearestTime" value="nearestTime"> В ближайшее время </label> <button type="submit" onclick="submitDateTime()">Подтвердить</button> <script> function submitDateTime() { const dateTimeType = document.querySelector('input[name="dateTime"]:checked').value; if (dateTimeType === 'dateTime') { const selectedDateTime = document.getElementById('dateTimeInput').value; alert(`Выбранная дата и время: ${selectedDateTime}`); } else { const nearestTime = new Date(); const minutes = nearestTime.getMinutes() + 15 - (nearestTime.getMinutes() % 15); nearestTime.setMinutes(minutes); alert(`Ближайшее время: ${nearestTime.toLocaleString()}`); } } </script> </div> </form> <script src="https://api-maps.yandex.ru/2.1/?apikey=d4c30c84-8597-42a1-b916-fedb4bc275e8&lang=ru_RU" type="text/javascript"></script> <script src="../static/js/script.js"></script> <script> ymaps.ready(function() { $('#startpoint').on('input', function() { var searchText = $(this).val(); if (searchText.length > 0) { ymaps.geocode(searchText, { results: 5 }).then(function (res) { $('#suggested-locations').empty(); res.geoObjects.each(function (obj) { var locationName = obj.properties.get('name'); $('#suggested-locations').append('<li>' + locationName + '</li>'); }); }); } else { $('#suggested-locations').empty(); } }); $('#endpoint').on('input', function() { var searchText = $(this).val(); if (searchText.length > 0) { ymaps.geocode(searchText, { results: 5 }).then(function (res) { $('#suggested-locations-2').empty(); res.geoObjects.each(function (obj) { var locationName = obj.properties.get('name'); $('#suggested-locations-2').append('<li>' + locationName + '</li>'); }); }); } else { $('#suggested-locations-2').empty(); } }); $('#suggested-locations').on('click', 'li', function() { $('#startpoint').val($(this).text()); $('#suggested-locations').empty(); }); $('#suggested-locations-2').on('click', 'li', function() { $('#endpoint').val($(this).text()); $('#suggested-locations-2').empty(); }); }); </script> <script> // Отслеживаем изменения в Local Storage window.addEventListener('storage', function(event) { if (event.key === 'acceptedOrder1') { const acceptedOrder1 = JSON.parse(event.newValue); document.getElementById('notification').innerText = `Заказ принят водителем, ожидайте: \n${acceptedOrder.description}`; } }); </script> </body> </html>
import GlobalContext from "@/Context/AuthProvider"; import NoItemFound from "@/components/NoItemFound"; import React, { useContext, useEffect, useState } from "react"; import { AiOutlineUser } from "react-icons/ai"; import { BsTelephone } from "react-icons/bs"; export default function Vehiclelist() { const { handleGetVehicle, user } = useContext(GlobalContext); const [vehicleData, setVehicleData] = useState(); useEffect(() => { async function Data() { const id = localStorage.getItem("id"); const { data } = await handleGetVehicle(id); setVehicleData(data); } Data(); }, []); return ( <div className="grid lg:grid-cols-4 md:grid-cols-2 grid-cols-1"> {vehicleData?.length > 0 ? ( vehicleData?.map((items, index) => { return ( <div key={index} className="px-4 cursor-pointer md:group py-5 border-transparent radius-2 " > <div className="block max-w-sm p-4 bg-white border border-gray-200 rounded-lg shadow hover:bg-gray-100 dark:bg-gray-800 dark:border-gray-700 dark:hover:bg-gray-700"> <div className="flex justify-between"> <div className="flex items-center"> <AiOutlineUser className="mr-1.5 w-5 h-5" /> <span className="mb-2 text-xl font-medium tracking-tight text-gray-900 dark:text-white"> {items?.firstname} {items?.lastname} </span> </div> <h5 className="mb-2 text-xl font-bold tracking-tight text-gray-900 dark:text-white"> {items?.vehicleno} </h5> </div> <div className="flex items-center"> <BsTelephone className="mr-1.5 w-5 h-5" /> <span className="text-bold font-medium text-[19px]"> {items?.phonenumber} <br /> {items?.phonenumber2} </span> </div> <p className="font-normal text-gray-700 dark:text-gray-400"> {items?.description} </p> </div> </div> ); }) ) : ( <NoItemFound /> )} </div> ); }
package com.projectSPI.bibliotheque.controller; import com.projectSPI.bibliotheque.DTO.BorrowRequestDTO; import com.projectSPI.bibliotheque.entity.Emprunt; import com.projectSPI.bibliotheque.entity.Livre; import com.projectSPI.bibliotheque.entity.User; import com.projectSPI.bibliotheque.repository.EmpruntRepository; import com.projectSPI.bibliotheque.repository.LivreRepository; import com.projectSPI.bibliotheque.repository.UserRepository; import com.projectSPI.bibliotheque.service.LivreEmpruntService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; 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.RequestMapping; import org.springframework.web.bind.annotation.RestController; //import com.github.javafaker.Faker; //import org.springframework.beans.factory.annotation.Autowired; //import org.springframework.http.HttpStatus; //import org.springframework.http.ResponseEntity; //import org.springframework.web.bind.annotation.*; import java.time.ZoneId; import java.time.LocalDate; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; @RestController @RequestMapping("/api") public class EmpruntController { @Autowired private EmpruntRepository empruntRepository; @Autowired private LivreRepository livreRepository; @Autowired private UserRepository userRepository; private final LivreEmpruntService livreEmpruntService; public EmpruntController(LivreEmpruntService livreEmpruntService) { this.livreEmpruntService = livreEmpruntService; } @PostMapping("/Emprunt") public ResponseEntity<?> borrowBook(@RequestBody BorrowRequestDTO borrowRequest) { boolean success = livreEmpruntService.processBorrowRequest(borrowRequest); if (success) { return ResponseEntity.ok().body("Student borrowed book successfully"); } else { return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Student failed to borrow the book"); } } // @GetMapping("/generateRandomData") // public ResponseEntity<String> generateRandomEmpruntData() { // try { // List<Emprunt> randomEmprunts = new ArrayList<>(); // Faker faker = new Faker(); // // // Assuming you have repositories for User and Livre // List<User> users = userRepository.findAll(); // List<Livre> livres = livreRepository.findAll(); // // for (int i = 0; i < 10; i++) { // User randomUser = getRandomElement(users, faker); // Livre randomLivre = getRandomElement(livres, faker); // // LocalDate randomCheckoutDate = faker.date().future(180, TimeUnit.DAYS).toInstant().atZone(ZoneId.systemDefault()).toLocalDate(); // LocalDate randomReturnDate = randomCheckoutDate.plusDays(faker.number().numberBetween(7, 30)); // // Emprunt emprunt = new Emprunt(); // emprunt.setUser(randomUser); // emprunt.setLivre(randomLivre); // emprunt.setCheckoutDate(randomCheckoutDate); // emprunt.setReturnDate(randomReturnDate); // // randomEmprunts.add(emprunt); // } // // // Save the generated Emprunts to the repository // empruntRepository.saveAll(randomEmprunts); // // return new ResponseEntity<>("Random data inserted successfully", HttpStatus.OK); // } catch (Exception e) { // return new ResponseEntity<>("Failed to insert random data", HttpStatus.INTERNAL_SERVER_ERROR); // } // } // // // Helper method to get a random element from a list // private <T> T getRandomElement(List<T> list, Faker faker) { // return list.get(faker.number().numberBetween(0, list.size())); // } }
val input = io.Source.fromResource("2020/day-14.txt").getLines.toList input.size // val mem = collection.mutable.Map().withDefaultValue(0) def masked(n: Long, mask: String): Long = val bin = n.toBinaryString.reverse.padTo(36, '0').reverse val newBin = bin.zip(mask).map { case (b, 'X') => b case (_, '1') => '1' case (_, '0') => '0' } BigInt.apply(newBin.mkString, 2).toLong def maskedAddresses(a: Long, mask: String): List[Long] = val bin = a.toBinaryString.reverse.padTo(36, '0').reverse.toList def newBins(addresses: List[String], pairs: List[(Char, Char)]): List[String] = pairs match case (_, 'X') :: tail => val both = addresses.flatMap { addr => List(addr :+ '0', addr :+ '1') } newBins(both, tail) case (_, '1') :: tail => newBins(addresses.map(_ :+ '1'), tail) case (b, '0') :: tail => newBins(addresses.map(_ :+ b), tail) case Nil => addresses newBins(List(""), bin.zip(mask)) // .tapEach(println(_)) .map(a => BigInt.apply(a.mkString, 2).toLong) maskedAddresses(42L, "000000000000000000000000000000X1001X") maskedAddresses(26L, "00000000000000000000000000000000X0XX") case class State(mask: String, memory: Map[Long, Long]): def interperet(inst: String): State = inst match case s"mask = $m" => copy(mask = m) case s"mem[$a] = $v" => copy(memory = memory.updated(a.toLong, masked(v.toLong, mask))) def interperet2(inst: String): State = inst match case s"mask = $m" => copy(mask = m) case s"mem[$a] = $v" => val addrs = maskedAddresses(a.toLong, mask) addrs.foldLeft(this)((s, addr) => s.copy(memory = s.memory.updated(addr, v.toLong)) ) val start = State(mask = "X" * 36, Map.empty.withDefaultValue(0L)) val finalState: State = input.foldLeft(start)((s, i) => s.interperet(i)) val ans = finalState.memory.values.sum val ans2 = val s = input.foldLeft(start)(_ interperet2 _) s.memory.values.sum input.foldLeft(start)(_ interperet2 _).memory
package project.generate_html; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.Writer; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.List; import java.util.ArrayList; import java.util.Arrays; import java.nio.file.FileSystems; import java.nio.file.Path; import java.nio.file.Paths; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; import freemarker.template.Configuration; import freemarker.template.DefaultObjectWrapper; import freemarker.template.Template; import freemarker.template.TemplateException; public class GenerateHtml { public static void generate(String templateName, String targetFileName, Map<String, Object> params) { Writer out = null; Path currentRelativePath = Paths.get(""); String base_path = currentRelativePath.toAbsolutePath().toString(); // System.out.println(base_path); String output_folder = "target\\output"; //通過匹配路徑格式拼接完整生成路徑 String outFile = base_path + File.separator + output_folder + File.separator + targetFileName; System.out.println("Output file: " + outFile); try { File file = new File(outFile); if (!file.exists()) { // 生成空 HTML文件 file.createNewFile(); } else{ file.delete(); } // 初始化 freemarker 設定 Configuration cfg = new Configuration(Configuration.VERSION_2_3_26); cfg.setObjectWrapper(new DefaultObjectWrapper(Configuration.VERSION_2_3_26)); cfg.setDefaultEncoding("UTF-8"); String template_folder = base_path + File.separator + "src\\main\\resources\\templates"; cfg.setDirectoryForTemplateLoading(new File(template_folder)); // 模板存放處 // 根據模板名稱獲取模板 Template template = cfg.getTemplate(templateName); // 設置輸出流 out = new OutputStreamWriter(new FileOutputStream(file), "UTF-8"); // 模版數據插入參數,通過輸出流插入到HTML中 template.process(params, out); } catch (Exception e) { e.printStackTrace(); } finally { if (null != out) { try { out.flush(); out.close(); } catch (IOException e) { e.printStackTrace(); } } } System.out.println("Done"); } public static String readAll(BufferedReader reader) { StringBuffer buffer = new StringBuffer(); while (true) { String line; try { line = reader.readLine(); } catch (IOException e) { throw new RuntimeException(e); } if (line == null) { break; } else { buffer.append(line); buffer.append("\n"); } } return buffer.toString(); } public static void main(String[] args) throws IOException, TemplateException { Map<String, Object> params = new HashMap<String, Object>(); params.put("title", "Freemarker 模板引擎"); params.put("author", "Stanley"); params.put("publishTime", "2022-07-07"); params.put("seeNum", "6"); params.put("imgPath", "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRABZYhX2FTcVfhbhN2y6QFHITZf1XgSy92eQ&usqp=CAU"); params.put("content", "不秀恩愛,沒有傷害!!!<br>~~單身狗保護協會~~"); Object arr[] = new Object[0]; List<Object> array = new ArrayList<Object>(Arrays.asList(arr)); try { JSONParser parser = new JSONParser(); Path currentRelativePath = Paths.get(""); String base_path = currentRelativePath.toAbsolutePath().toString(); String input_file_path = base_path + File.separator + "src\\main\\resources\\inputs\\comments.json"; FileInputStream input_file = new FileInputStream(input_file_path); BufferedReader reader = new BufferedReader(new InputStreamReader(input_file, "UTF-8")); JSONObject jsonObject = (JSONObject) parser.parse(readAll(reader)); Set<String> keys = jsonObject.keySet(); // System.out.println(keys); for(String time : keys){ Map<String, Object> data = new HashMap<String, Object>(); JSONObject commentObject = (JSONObject) jsonObject.get(time); String comment = (String) commentObject.get("comment"); // System.out.println(time); // System.out.println(comment); data.put("time", time); data.put("detail", comment); array.add(data); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } params.put("commentList", array); GenerateHtml.generate("html_template.html", "html_test.html", params); } }
#!/usr/bin/nsp class testlib2 { function constructor() { } function shared_sql_tests(db) { db.open(); db.query("CREATE TABLE test_table ( id integer, col1 varchar(8), col2 varchar(8) );", false); printf("db.changes = %d;\r\n", db.changes); db.begin(); db.query(sprintf("INSERT INTO test_table (id, col1, col2) VALUES (1, 'a', '%s');", db.escape("abc")), false); printf("db.changes = %d;\r\n", db.changes); db.query(sprintf("INSERT INTO test_table (id, col1, col2) VALUES (2, 'b', '%s');", db.escape("a'b'c")), false); printf("db.changes = %d;\r\n", db.changes); db.query(sprintf("INSERT INTO test_table (id, col1, col2) VALUES (3, 'c', '%s');", db.escape('a"b"c')), false); printf("db.changes = %d;\r\n", db.changes); db.commit(); //db.rollback(); db.query("SELECT * FROM test_table;"); printf("db.last_query = \"%s\";\r\n", db.last_query); while ((row=db.getnext())!=null) { printf("row = %s;\r\n", serialize(row).replace('\r', '').replace('\n', ' ').replace('\t', '')); } db.endquery(); printf("db.changes = %d;\r\n", db.changes); db.close(); } function fbsql() { ci = { host="localhost", port=3050, username="SYSDBA", password="masterkey", database="/tmp/nstest.fdb" }; file.unlink(ci.database); file.writeall("/tmp/nstest.sql", sprintf("SET SQL DIALECT 3;\r\nCREATE DATABASE '%s'\r\nUSER '%s' PASSWORD '%s'\r\nPAGE_SIZE 16384;\r\n", ci.database, ci.username, ci.password)); system("isql-fb -input /tmp/nstest.sql 2> /dev/null"); file.unlink("/tmp/nstest.sql"); try { dl.load("data"); dl.load("fbsql"); db=new data.fbsql.client(ci); this.shared_sql_tests(db); } catch (ex) { printf("Exception: %s\r\n", ex.description); } file.unlink(ci.database); return; } function mysql() { ci = { host="localhost", port=3306, username="root", password="test", database="nstest" }; system(sprintf("mysql -u%s -p%s -e \"DROP DATABASE IF EXISTS nstest\"", ci.username, ci.password)); system(sprintf("mysql -u%s -p%s -e \"CREATE DATABASE nstest\"", ci.username, ci.password)); try { dl.load("data"); dl.load("mysql"); db=new data.mysql.client(ci); this.shared_sql_tests(db); } catch (ex) { printf("Exception: %s\r\n", ex.description); } //system(sprintf("mysql -u%s -p%s -e \"DROP DATABASE IF EXISTS nstest\"", ci.username, ci.password)); return; } function pgsql() { ci = { host="localhost", port=5432, username="postgres", password="test", database="nstest" }; system(sprintf("export PGPASSWORD=%s && dropdb -h localhost -U %s %s", ci.password, ci.username, ci.database)); system(sprintf("export PGPASSWORD=%s && createdb -h localhost -U %s %s", ci.password, ci.username, ci.database)); try { dl.load("data"); dl.load("pgsql"); db=new data.pgsql.client(ci); this.shared_sql_tests(db); } catch (ex) { printf("Exception: %s\r\n", ex.description); } system(sprintf("export PGPASSWORD=%s && dropdb -h localhost -U %s %s", ci.password, ci.username, ci.database)); return; } function sqlite() { ci = { database="/tmp/nstest.db" }; file.unlink(ci.database); try { dl.load("data"); dl.load("sqlite"); db=new data.sqlite.client(ci); this.shared_sql_tests(db); } catch (ex) { printf("Exception: %s\r\n", ex.description); } file.unlink(ci.database); } function mongodb() { function trim(s) { if (s.gettype()=='string') return s; return serialize(s).replace('\t','').replace('\r','').replace('\n',' '); } class mongo { function constructor() { if (!dl.load("mongodb")) throw "mongo library not found"; /* db.adminCommand( { "hostInfo": 1 } ) use admin db.auth( { user: "root", pwd: "test" } ) use nulltest db.dropDatabase() */ conninfo = { url="mongodb://root:test@localhost:27017/", database="nulltest", collection="users" }; this.client = new data.mongodb.client(conninfo); this.client.open(); //q='{ "hostInfo": 1 }'; //r=client.clientcommand(q); //printf("q = %s\r\nr = %s\r\n", trim(q), trim(r)); client.db.use("nulltest2", "users"); printf("[%s][%s]\r\n", client.db.name, client.collection.name); } function destructor() { print("shutting down mongo client\r\n"); if (client) client.close(); } function clientcommand() { printf("--beginning clientcommand tests--\r\n"); q = '{ "ping": 1 }'; r = client.clientcommand(q); printf("\tq = %s\r\n\tr = %s\r\n", trim(q), trim(r)); q = { ping = 1 }; r = client.clientcommand(q); printf("\tq = %s\r\n\tr = %s\r\n", trim(q), trim(r)); } function collectioncommand() { printf("--beginning collectioncommand tests--\r\n"); q = { collStats = "users" }; try { r = this.client.collection.command(q); } catch (ex) { print("client.collection.command(q) failed. this is normal the first time\r\n"); } printf("\tq = %s\r\n\tr = %s\r\n", trim(q), trim(r)); } function collectioninsert() { printf("--beginning collectioninsert tests--\r\n"); this.newoid = client.collection.newoid(); q = sprintf('{ "_id": { "$oid": "%s" }, "name": { "first": "Dan", "last": "Cahill" }, "time": "%s" }', this.newoid, time.sqltime()); r = client.collection.insert(q); printf("\tq = %s\r\n\tr = %s\r\n", trim(q), trim(r)); } function collectionupdate() { printf("--beginning collectionupdate tests--\r\n"); q = '{ "name": "Bob" }'; d = '{ "name": "Bob", "rating": 2 }'; r = client.collection.update(q, d); printf("\tq = %s\r\n\td = %s\r\n\tr = %s\r\n", trim(q), trim(d), trim(r)); //q = '{ "_id": { "$oid": "5d6c615f7c71de67c00c8161" } }'; q = sprintf('{ "_id": { "$in": ["%s", { "$oid": "%s" }] } }', this.newoid, this.newoid); d = sprintf('{ "$set": { "time2": "%s" } }', time.sqltime()); r = client.collection.update(q, d); printf("\tq = %s\r\n\td = %s\r\n\tr = %s\r\n", trim(q), trim(d), trim(r)); } function collectionremove() { printf("--beginning collectionremove tests--\r\n"); // search for _id must match how doc was created // search using $oid is right but _id gets inserted // as a string in the inserted doc is an nsp table o = "5d6ad3197c71de503813daa1"; //q = sprintf('{ "_id": { "$oid": "%s" } }', o); q = sprintf('{ "_id": { "$in": ["%s", { "$oid": "%s" }] } }', o, o); r = client.collection.remove(q); printf("\tq = %s, r = %s\r\n", q, r); } function collectionfind() { printf("--beginning collectionfind tests--\r\n"); //q = '{"_id": {"$oid": "5d6b12367c71de08fb215601"}}'; //q = { ["name.first"] = "Dan"}; //q = "{}"; //q = {}; q = '{ "$query": {}, "$orderby": { "time": 1 } }'; client.collection.find(q); while ((row=client.collection.getnext())!=null) { //q = sprintf('{ "_id": { "$in": ["%s", { "$oid": "%s" }] } }', row._id, row._id); //r = client.collection.remove(q); printf("\t%s\r\n", trim(row)); if (!firstid) firstid = row._id; } //client.collection.endfind(); // <- shouldn't need this if (firstid) { //q = sprintf('{ "_id": { "$oid": "%s" } }', firstid); q = sprintf('{ "_id": { "$in": ["%s", { "$oid": "%s" }] } }', firstid, firstid); r = client.collection.remove(q); printf("\tq = %s, r = %s\r\n", q, r); } var todelete = { "5d6edfca7c71de1f7a2cdcf1" }; foreach (n,v in todelete) { q = sprintf('{ "_id": { "$in": ["%s", { "$oid": "%s" }] } }', v, v); r = client.collection.remove(q); printf("\tfirstid = [%s] - collection.remove(q) = %s, r = %s\r\n", firstid, trim(q), r); } } } try { test = new mongo(); test.clientcommand(); test.collectioninsert(); test.collectionupdate(); test.collectionfind(); test.collectioncommand(); test.collectionremove(); } catch (ex) { printf("Exception: %s\r\n", ex.description); } finally { delete test; } } }; //tests = new testlib2(); //tests.fbsql(); //tests.mysql(); //tests.pgsql(); //tests.sqlite(); //tests.mongodb();
import { View, StyleSheet, TouchableOpacity, Text, Image } from "react-native"; import React, { useEffect, useContext, useState } from "react"; import { LinearGradient } from "expo-linear-gradient"; import MultiSlider from "@ptomasroos/react-native-multi-slider"; import { COLORS, FONT, images } from "../../constants"; import { Menu, SwitchBox, StandardBox, SelectSearch } from "../../components"; import ScrollContext from "../../context/ScrollContext"; function Customize() { const { scrollToTop, setScrollEnable } = useContext(ScrollContext); useEffect(() => { scrollToTop(); }, []); const testArray = [ "ABC", "AMRIGS", "ENARE", "SUS-SP", "UNICAMP", "USP", "UNIFEST", "UFS", "UFRJ", "SANTA CASA DE SÃO PAULO", ]; const themeArray = [ "Asma", "Tuberculose", "Pneumonia", "Epidemias", "Gestão em saúde", "HIV", "Abdome agudo obstrutivo", "Tumores abdominais na infância", ]; const [sliderValue, setSliderValue] = useState([200]); const enableScroll = () => setScrollEnable(true); const disableScroll = () => setScrollEnable(false); const [width, setWidth] = useState(0); const handleLayout = (event) => { const { width } = event.nativeEvent.layout; setWidth(width); }; return ( <LinearGradient style={[styles.view, styles.gradient]} colors={[COLORS.purple, COLORS.pink]} start={{ x: 1, y: 1 }} end={{ x: 1, y: 0 }} > <Menu title="Personalizar" /> <StandardBox text="Definir meta diária de questões"> <View style={styles.sliderContainer} onLayout={handleLayout}> <MultiSlider values={sliderValue} onValuesChange={(value) => setSliderValue(value)} max={200} sliderLength={width - 90} customMarker={() => ( <Image source={images.SliderThumb} style={{ transform: [{ scaleX: 0.3 }, { scaleY: 0.3 }], marginTop: 8 }} /> )} trackStyle={styles.track} selectedStyle={styles.trackSelected} onValuesChangeStart={() => disableScroll()} onValuesChangeFinish={() => enableScroll()} /> <LinearGradient style={styles.sliderTextContainer} colors={[COLORS.green, COLORS.darkGreen]} start={{ x: 1, y: 1 }} end={{ x: 1, y: 0 }} > <Text style={styles.sliderText}>{sliderValue}</Text> </LinearGradient> </View> </StandardBox> <StandardBox text="Questões por Grandes áreas"> <SwitchBox title="Clínica médica" initialState={true} /> <SwitchBox title="Cirurgia geral" initialState={true} /> <SwitchBox title="Pediatria" initialState={false} /> <SwitchBox title="Ginecologia e obstetrícia" initialState={true} /> <SwitchBox title="Medicina preventiva" initialState={false} /> </StandardBox> <StandardBox text="Questões de provas específicas:"> <SelectSearch placeholder="Busque provas" content={testArray} /> </StandardBox> <StandardBox text="Questões de temas específicos:"> <SelectSearch placeholder="Busque temas" content={themeArray} /> </StandardBox> <TouchableOpacity style={styles.startButton}> <Text style={styles.startButtonText}>COMEÇAR</Text> </TouchableOpacity> </LinearGradient> ); } const styles = StyleSheet.create({ gradient: { flex: 1, borderRadius: 12, }, view: { flex: 1, paddingTop: 16, paddingBottom: 2, paddingHorizontal: 16, }, sliderContainer: { flexDirection: "row", justifyContent: "space-between", alignContent: "center", alignItems: "center", }, track: { height: 10, borderRadius: 10, borderStyle: "solid", borderWidth: 1.8, borderColor: COLORS.black, }, trackSelected: { backgroundColor: COLORS.green }, sliderTextContainer: { width: 60, height: 30, backgroundColor: COLORS.green, borderRadius: 6, justifyContent: "center", alignItems: "center", borderStyle: "solid", borderWidth: 1.8, borderColor: COLORS.black, }, sliderText: { fontFamily: FONT.bold, fontSize: 14, color: COLORS.white, lineHeight: 20, }, startButton: { width: 200, backgroundColor: COLORS.white, borderRadius: 100, marginTop: 20, alignSelf: "center", shadowColor: "rgba(0, 0, 0, 0.2)", // iOS shadowOffset: { width: 3, height: 2 }, // iOS shadowRadius: 5, // iOS elevation: 10, // Android marginBottom: 30, }, startButtonText: { fontFamily: FONT.bold, fontSize: 14, color: COLORS.black, textAlign: "center", paddingVertical: 8, lineHeight: 20, }, }); export default Customize;
<?php /** * Titan Framework Tracker Class */ if (!defined('ABSPATH')) exit; // Exit if accessed directly /** * Titan Framework Tracker Class * In charge of the opt-in procedure and performing the actual data sending for tracking Titan * intallation details. * * @author Benjamin Intal * */ class TitanFrameworkTracker { const REMOTE_URL = 'http://www.titanframework.net/wp-admin/admin-ajax.php'; // TODO: This isn't live yet, although will not error out const TRACKER_INTERVAL = 10; // temporarily 10 secs for debugging FIXME: WEEK_IN_SECONDS; const REMOTE_ACTION = 'tracker'; const OPT_AJAX_ACTION = 'tf_tracker_opted'; const NONCE_NAME = 'tracker_nonce'; // Internal variables private $frameworkInstance; private $optInOption; private $transientName; /** * Class constructor * * @param TitanFramework $frameworkInstance an instance of the framework object * @return void * @since 1.6 */ function __construct($frameworkInstance) { $this->frameworkInstance = $frameworkInstance; $this->optInOption = $this->frameworkInstance->optionNamespace . '_tf_tracker'; $this->transientName = $this->optInOption . '_transient'; add_action('admin_notices', array($this, 'includeOptInScript')); add_action('wp_ajax_' . self::OPT_AJAX_ACTION, array($this, 'ajaxTrackerOptedHandler')); add_action('admin_footer', array($this, 'performTracking')); add_action('wp_footer', array($this, 'performTracking')); } /** * Adds a notice in the admin for tracking opt-in * * @return void * @since 1.6 */ public function includeOptInScript() { // Check our settings if (!$this->frameworkInstance->settings['tracking']) { delete_option($this->optInOption); delete_transient($this->transientName, $this->transientName); return; } // Check if opted in/out before, quit if (false !== get_option($this->optInOption)) { return; } // Check if first time, ask to opt-in echo '<div class="updated" style="border-left-color: #3498db"> <p> ' . __('Help us make Titan Framework better by enabling your site to periodically send us tracking data. This is so we can know where and how Titan is being used.', 'thim' ) . ' <button name="opt" value="1" class="' . $this->optInOption . ' button button-primary">' . __('Help us and track', 'thim' ) . '</button> <button name="opt" value="0" class="' . $this->optInOption . ' button button-default">' . __("Don't track", 'thim' ) . '</button> <script> jQuery(document).ready(function($) { $(".' . $this->optInOption . '").click(function() { var data = { "' . self::NONCE_NAME . '": "' . wp_create_nonce(__CLASS__) . '", "action": "' . self::OPT_AJAX_ACTION . '", "opt": $(this).val() }; var $this = $(this); $.post(ajaxurl, data, function(response) { $this.parents(".updated:eq(0)").fadeOut(); }); $(".' . $this->optInOption . '").attr("disabled", "disabled"); }); }); </script> </p> </div>'; } /** * Ajax handler for the opt-in question from the admin notice * * @return void * @since 1.6 */ public function ajaxTrackerOptedHandler() { check_ajax_referer(__CLASS__, self::NONCE_NAME); if ($_POST['opt'] == '1') { update_option($this->optInOption, '1'); // Send out tracking stuff immediately during ajax $this->performTracking(); } else { update_option($this->optInOption, '0'); } die(); } /** * Performs the sending out of data for the tracking, this uses the transient API * to perform data sending only every week. * * @return void * @since 1.6 */ public function performTracking() { // Only do this when settings permit and the user opted-in if (!$this->frameworkInstance->settings['tracking']) { return; } if (get_option($this->optInOption) !== '1') { return; } // Send out our tracking data if it's time already if (false === get_transient($this->transientName)) { $response = wp_remote_post( self::REMOTE_URL, array( 'method' => 'POST', 'timeout' => 45, 'redirection' => 5, 'httpversion' => '1.0', 'blocking' => true, 'headers' => array(), 'body' => $this->formDataToSend(), 'cookies' => array(), ) ); // Periodically repeat set_transient($this->transientName, $this->transientName, self::TRACKER_INTERVAL); } } /** * Gathers all the data that we can get (not sensitive) to send out as tracker * information. * * @return array WP installation data * @since 1.6 */ private function formDataToSend() { $data = array(); // Action of the receiving WP host $data['action'] = self::REMOTE_ACTION; // WordPress installation details $data['wp'] = array( 'name' => is_rtl('name'), 'home_url' => home_url(), 'description' => is_rtl('description'), 'version' => is_rtl('version'), 'text_direction' => is_rtl('text_direction'), 'language' => is_rtl('language'), ); // Titan Framework details $data['titan'] = array(); if (defined('TF_VERSION')) { $data['titan']['version'] = TF_VERSION; } // Get option & container stats if (!empty($this->frameworkInstance->optionsUsed)) { $data['titan']['num_options'] = count($this->frameworkInstance->optionsUsed); $data['titan']['option_count'] = array(); $data['titan']['container_count'] = array(); $data['titan']['container_option_count'] = array(); foreach ($this->frameworkInstance->optionsUsed as $option) { if (!empty($option->settings['type'])) { if (empty($data['titan']['option_count'][$option->settings['type']])) { $data['titan']['option_count'][$option->settings['type']] = 0; } $data['titan']['option_count'][$option->settings['type']] ++; } if (empty($data['titan']['container_count'][get_class($option->owner)])) { $data['titan']['container_count'][get_class($option->owner)] = 0; } $data['titan']['container_count'][get_class($option->owner)] ++; if (empty($data['titan']['container_option_count'][get_class($option->owner)])) { $data['titan']['container_option_count'][get_class($option->owner)] = array(); } $data['titan']['container_option_count'][get_class($option->owner)][] = count($option->owner->options); } } // Average the number of options per container if (!empty($data['titan']['container_option_count'])) { foreach ($data['titan']['container_option_count'] as $key => $countArr) { $runningTotal = 0; foreach ($countArr as $count) { $runningTotal += $count; } $data['titan']['container_option_count'][$key] = $runningTotal / count($countArr); } } // Current theme details $theme = wp_get_theme(); $data['theme'] = array( 'name' => $theme->get('Name'), 'version' => $theme->get('Version'), 'themeuri' => $theme->get('ThemeURI'), 'author' => $theme->get('Author'), 'authoruri' => $theme->get('AuthorURI'), ); // Plugin details $data['plugins'] = array(); if ($plugins = get_plugins()) { foreach ($plugins as $key => $pluginData) { if (is_plugin_active($key)) { $data['plugins'][$key] = $pluginData; } } } // PHP details $data['php'] = array( 'phpversion' => phpversion(), ); // Super basic security remote check $data['hash'] = md5(serialize($data)); return $data; } }
package be.selckin; import guru.nidi.graphviz.attribute.*; import guru.nidi.graphviz.engine.Format; import guru.nidi.graphviz.engine.Graphviz; import guru.nidi.graphviz.model.Graph; import guru.nidi.graphviz.model.Node; import javax.sound.midi.Soundbank; import java.io.File; import java.io.IOException; import java.io.SequenceInputStream; import java.util.*; import static be.selckin.Day20.Pulse.HIGH; import static be.selckin.Day20.Pulse.LOW; import static guru.nidi.graphviz.attribute.Attributes.attr; import static guru.nidi.graphviz.attribute.Rank.RankDir.LEFT_TO_RIGHT; import static guru.nidi.graphviz.attribute.Rank.RankDir.TOP_TO_BOTTOM; import static guru.nidi.graphviz.model.Factory.graph; import static guru.nidi.graphviz.model.Factory.node; import static guru.nidi.graphviz.model.Link.to; public class Day20 { public static final String PART1_EXAMPLE = """ broadcaster -> a, b, c %a -> b %b -> c %c -> inv &inv -> a """; public static final String PART1_EXAMPLE2 = """ broadcaster -> a %a -> inv, con &inv -> b %b -> con &con -> output """; public static void main(String[] args) throws IOException { part1(PART1_EXAMPLE, 32000000); part1(PART1_EXAMPLE2, 11687500); part1(PART1_INPUT, 812721756); part2(PART1_INPUT, 233338595643977L); } public enum Pulse { HIGH, LOW } public static class Module { public char type; public String name; public List<String> outputs; // % private boolean flipFlop = false; // & private Map<String, Pulse> memory = new HashMap<>(); public Module(char type, String name, List<String> outputs) { this.type = type; this.name = name; this.outputs = outputs; } public List<Signal> on(Signal signal) { if (type == '>') return output(LOW); if (type == '#') { return List.of(); } if (type == '%') { if (signal.pulse() == LOW) { flipFlop = !flipFlop; return output(flipFlop ? HIGH : LOW); } else return List.of(); } if (type == '&') { memory.put(signal.source(), signal.pulse()); return output(outputSignal()); } throw new RuntimeException(); } public Pulse outputSignal() { return memory.values().stream().allMatch(pulse -> pulse == HIGH) ? LOW : HIGH; } private List<Signal> output(Pulse pulse) { return outputs.stream().map(output -> new Signal(name, output, pulse)).toList(); } public void connect(String name) { if (type == '&') { memory.put(name, LOW); } } } public record Signal(String source, String target, Pulse pulse) { } private static void part1(String input, long expected) { Map<String, Module> modules = parse(input); long low = 0; long high = 0; Deque<Signal> pending = new ArrayDeque<>(); for (int i = 0; i < 1000; i++) { pending.add(new Signal("button", "broadcaster", LOW)); while (!pending.isEmpty()) { Signal signal = pending.pop(); switch (signal.pulse) { case HIGH -> high++; case LOW -> low++; } if (!"rx".equals(signal.target())) pending.addAll(modules.get(signal.target()).on(signal)); } } long result = high * low; if (expected != result) throw new RuntimeException("Expected " + expected + " but got " + result); } private static void part2(String input, long expected) { Map<String, Module> modules = parse(input); draw(modules); List<List<Module>> numbers = new ArrayList<>(); for (String output : modules.get("broadcaster").outputs) { List<Module> number = new ArrayList<>(); collect(modules, number, output); numbers.add(number); } List<Module> rollOverModule = new ArrayList<>(); for (String output : modules.get("broadcaster").outputs) { for (String next : modules.get(output).outputs) { Module nextMod = modules.get(next); if (nextMod.type == '&') { rollOverModule.add(nextMod); } } } int count = 0; long[] rollOverCount = new long[rollOverModule.size()]; boolean finished = false; Deque<Signal> pending = new ArrayDeque<>(); while (!finished) { count++; pending.add(new Signal("button", "broadcaster", LOW)); while (!pending.isEmpty()) { Signal signal = pending.pop(); if (!"rx".equals(signal.target())) pending.addAll(modules.get(signal.target()).on(signal)); else if (signal.pulse == LOW) { finished = true; } for (int i = 0; i < rollOverModule.size(); i++) { if (rollOverCount[i] == 0) { Module module = rollOverModule.get(i); if (signal.source.equals(module.name) && signal.pulse == LOW) { rollOverCount[i] = count; System.out.println("Roll over " + i + " at " + count); } } } } System.out.print(count + ": "); for (List<Module> digits : numbers) { int num = 0; for (int i = 0; i < digits.size(); i++) { if (digits.get(i).flipFlop) num += 1 << i; } System.out.print(num + " "); } System.out.println(); if (count > 4100) break; } long lcm = 0; for (long i : rollOverCount) { if (lcm == 0) lcm = i; else lcm = Day8.lcm(lcm, i); } System.out.println(lcm); long result = lcm; if (expected != result) throw new RuntimeException("Expected " + expected + " but got " + result); } private static void collect(Map<String, Module> modules, List<Module> result, String output) { Module module = modules.get(output); if (module == null) { return; } if (module.type != '%') return; result.add(module); for (String next : module.outputs) { collect(modules, result, next); } } private static void draw(Map<String, Module> modules) { List<Node> nodes = new ArrayList<>(); for (Module module : modules.values()) { Node node = node(module.name).with(module.type == '&' ? Color.RED : Color.GREEN); for (String output : module.outputs) { node = node.link(output); } nodes.add(node); } Graph g = graph("aoc").directed() .graphAttr().with(Rank.dir(TOP_TO_BOTTOM)) .linkAttr().with("class", "link-class") .with(nodes); try { Graphviz.fromGraph(g).height(2000).render(Format.PNG).toFile(new File("day20.png")); } catch (IOException ex) { throw new RuntimeException(); } } private static Map<String, Module> parse(String input) { Map<String, Module> modules = new HashMap<>(); modules.put("output", new Module('#', "output", List.of())); input.lines().forEach(line -> { String[] split = line.split(" -> "); List<String> targets = List.of(split[1].split(", ")); String name = split[0]; Module module; if ("broadcaster".equals(name)) { module = new Module('>', "broadcaster", targets); } else { module = new Module(split[0].charAt(0), name.substring(1), targets); } modules.put(module.name, module); }); for (Module module : modules.values()) { for (String output : module.outputs) { Optional.ofNullable(modules.get(output)) .ifPresent(m -> m.connect(module.name)); } } return modules; } public static final String PART1_INPUT = """ %np -> vn &lv -> rx %rt -> ns %th -> bc %gt -> rt, db %zf -> db, np %sg -> fs, gr %vn -> db, zj %qh -> ms, lz %rv -> rj, vc %br -> lz, qh %pc -> jq, vc %dk -> xl %qq -> th, gr %ns -> xv &vc -> gl, tv, pc, qd, tn, dg %bd -> lz, vm %ms -> lz, bd %dg -> rv %cf -> vc %kc -> cq, db %ds -> dk, lz %zj -> kc %qm -> db, zf %gl -> qd %hf -> db %hx -> px, gr %fk -> tv, vc %tp -> ld %gg -> rq, gr %xl -> gj, lz %vm -> lz %qf -> lz, vr %px -> qq %fs -> tp %bc -> cd, gr %vr -> xz, lz %xv -> qm, db %rq -> gr %cq -> hf, db &lz -> dt, dk, qf &gr -> tp, fs, px, st, th, sg &st -> lv &tn -> lv %xz -> ds, lz &hh -> lv &db -> np, gt, zj, ns, hh, rt %qd -> dg %jq -> vc, fk %jp -> cf, vc %rj -> jp, vc %tv -> kz %cd -> gg, gr &dt -> lv %ld -> hx, gr %kz -> gl, vc broadcaster -> pc, sg, qf, gt %gj -> lz, br """; }
// 防抖函数 function debounce(fn, delay) { let timer = null; return function (...args) { if (timer) clearTimeout(timer); timer = setTimeout(() => { fn.apply(this, args); }, delay); }; } // 节流函数 // 方式 1:使用定时器 function throttle(fn, delay) { let timer = null; return function (...args) { if (!timer) { timer = setTimeout(() => { fn.apply(this, args); timer = null; }, delay); } }; } // 方式 2:使用时间戳 // function throttle(fn, delay) { // let last = 0; // return function (...args) { // const now = +new Date(); // const now = Date.now(); // if (now - last > delay) { // fn.apply(this, args); // last = now; // } // }; // } // 测试防抖函数 window.onresize = debounce(() => console.log("resize"), 500); // 测试节流函数 window.onscroll = throttle(() => console.log("scroll"), 500);
<?php /* Copyright (C) 2004-2007 Rodolphe Quiedeville <[email protected]> * Copyright (C) 2006-2007 Laurent Destailleur <[email protected]> * * 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. */ /** \defgroup telephonie Module telephonie \brief Module pour gerer la telephonie */ /** \file htdocs/includes/modules/modTelephonie.class.php \ingroup telephonie \brief Fichier de description et activation du module de Telephonie \version $Id: modTelephonie.class.php,v 1.3 2010/08/31 22:40:45 eldy Exp $ */ include_once(DOL_DOCUMENT_ROOT."/includes/modules/DolibarrModules.class.php"); require_once(DOL_DOCUMENT_ROOT."/lib/admin.lib.php"); /** \class modTelephonie \brief Classe de description et activation du module Telephonie */ class modTelephonie extends DolibarrModules { /** * \brief Constructeur. Definit les noms, constantes et boites * \param DB handler d'acces base */ function modTelephonie($DB) { $this->db = $DB ; $this->numero = 56 ; $this->family = "other"; // Module label (no space allowed), used if translation string 'ModuleXXXName' not found (where XXX is value of numeric property 'numero' of module) $this->name = preg_replace('/^mod/i','',get_class($this)); $this->description = "Gestion de la Telephonie"; // Possible values for version are: 'development', 'experimental', 'dolibarr' or version $this->version = 'dolibarr'; $this->const_name = 'MAIN_MODULE_'.strtoupper($this->name); $this->special = 2; $this->picto='phoning'; // Relative path to module style sheet if exists $this->style_sheet = '/telephonie/telephonie.css'; // Data directories to create when module is enabled $this->dirs = array("/telephonie/temp", "/telephonie/graph", "/telephonie/logs", "/telephonie/client", "/telephonie/rapports", "/telephonie/ligne/commande/retour/traite", "/telephonie/cdr/archives", "/telephonie/cdr/atraiter"); // Dependancies $this->depends = array(); $this->requiredby = array(); // Constants $this->const = array(); // Boxes $this->boxes = array(); // Permissions $this->rights = array(); $this->rights_class = 'telephonie'; $this->rights[1][0] = 211; // id de la permission $this->rights[1][1] = 'Consulter la telephonie'; // libelle de la permission $this->rights[1][2] = 'r'; // type de la permission (deprecie a ce jour) $this->rights[1][3] = 1; // La permission est-elle une permission par defaut $this->rights[1][4] = 'lire'; $this->rights[2][0] = 212; // id de la permission $this->rights[2][1] = 'Commander les lignes'; // libelle de la permission $this->rights[2][2] = 'w'; // type de la permission (deprecie a ce jour) $this->rights[2][3] = 0; // La permission est-elle une permission par defaut $this->rights[2][4] = 'ligne_commander'; $this->rights[3][0] = 213; $this->rights[3][1] = 'Activer une ligne'; $this->rights[3][2] = 'w'; $this->rights[3][3] = 0; $this->rights[3][4] = 'ligne_activer'; $this->rights[4][0] = 214; // id de la permission $this->rights[4][1] = 'Configurer la telephonie'; // libelle de la permission $this->rights[4][2] = 'w'; $this->rights[4][3] = 0; $this->rights[4][4] = 'configurer'; $this->rights[5][0] = 215; $this->rights[5][1] = 'Configurer les fournisseurs'; $this->rights[5][2] = 'w'; $this->rights[5][3] = 0; $this->rights[5][4] = 'fournisseur'; $this->rights[5][5] = 'config'; $this->rights[6][0] = 192; $this->rights[6][1] = 'Creer des lignes'; $this->rights[6][2] = 'w'; $this->rights[6][3] = 0; $this->rights[6][4] = 'ligne'; $this->rights[6][5] = 'creer'; $this->rights[7][0] = 202; $this->rights[7][1] = 'Creer des liaisons ADSL'; $this->rights[7][2] = 'w'; $this->rights[7][3] = 0; $this->rights[7][4] = 'adsl'; $this->rights[7][5] = 'creer'; $this->rights[8][0] = 203; $this->rights[8][1] = "Demander la commande des liaisons"; $this->rights[8][2] = 'w'; $this->rights[8][3] = 0; $this->rights[8][4] = 'adsl'; $this->rights[8][5] = 'requete'; $this->rights[9][0] = 204; $this->rights[9][1] = 'Commander les liaisons'; $this->rights[9][2] = 'w'; $this->rights[9][3] = 0; $this->rights[9][4] = 'adsl'; $this->rights[9][5] = 'commander'; $this->rights[10][0] = 205; $this->rights[10][1] = 'Gerer les liaisons'; $this->rights[10][2] = 'w'; $this->rights[10][3] = 0; $this->rights[10][4] = 'adsl'; $this->rights[10][5] = 'gerer'; $r = 10; $r++; $this->rights[$r][0] = 271; $this->rights[$r][1] = 'Consulter le CA'; $this->rights[$r][2] = 'w'; $this->rights[$r][3] = 0; $this->rights[$r][4] = 'ca'; $this->rights[$r][5] = 'lire'; $r++; $this->rights[$r][0] = 272; $this->rights[$r][1] = 'Consulter les factures'; $this->rights[$r][2] = 'r'; $this->rights[$r][3] = 0; $this->rights[$r][4] = 'facture'; $this->rights[$r][5] = 'lire'; $r++; $this->rights[$r][0] = 273; $this->rights[$r][1] = 'Emmettre les factures'; $this->rights[$r][2] = 'r'; $this->rights[$r][3] = 0; $this->rights[$r][4] = 'facture'; $this->rights[$r][5] = 'ecrire'; $r++; $this->rights[$r][0] = 206; $this->rights[$r][1] = 'Consulter les liaisons'; $this->rights[$r][2] = 'w'; $this->rights[$r][3] = 0; $this->rights[$r][4] = 'adsl'; $this->rights[$r][5] = 'lire'; $r++; $this->rights[$r][0] = 231; $this->rights[$r][1] = 'Definir le mode de reglement'; $this->rights[$r][2] = 'w'; $this->rights[$r][3] = 0; $this->rights[$r][4] = 'contrat'; $this->rights[$r][5] = 'paiement'; $r++; $this->rights[$r][0] = 193; $this->rights[$r][1] = 'Resilier des lignes'; $this->rights[$r][2] = 'w'; $this->rights[$r][3] = 0; $this->rights[$r][4] = 'ligne'; $this->rights[$r][5] = 'resilier'; $r++; $this->rights[$r][0] = 194; $this->rights[$r][1] = 'Consulter la marge des lignes'; $this->rights[$r][2] = 'r'; $this->rights[$r][3] = 0; $this->rights[$r][4] = 'ligne'; $this->rights[$r][5] = 'gain'; $r++; $this->rights[$r][0] = 146; $this->rights[$r][1] = 'Consulter les fournisseurs'; $this->rights[$r][2] = 'w'; $this->rights[$r][3] = 0; $this->rights[$r][4] = 'fournisseur'; $this->rights[$r][5] = 'lire'; $r++; $this->rights[$r][0] = 147; $this->rights[$r][1] = 'Consulter les stats'; $this->rights[$r][2] = 'w'; $this->rights[$r][3] = 0; $this->rights[$r][4] = 'stats'; $this->rights[$r][5] = 'lire'; $r++; $this->rights[$r][0] = 311; $this->rights[$r][1] = 'Consulter les services'; $this->rights[$r][2] = 'w'; $this->rights[$r][3] = 0; $this->rights[$r][4] = 'service'; $this->rights[$r][5] = 'lire'; $r++; $this->rights[$r][0] = 312; $this->rights[$r][1] = 'Affecter des services a un contrat'; $this->rights[$r][2] = 'w'; $this->rights[$r][3] = 0; $this->rights[$r][4] = 'service'; $this->rights[$r][5] = 'affecter'; $r++; $this->rights[$r][0] = 291; $this->rights[$r][1] = 'Consulter les tarifs'; $this->rights[$r][2] = 'w'; $this->rights[$r][3] = 0; $this->rights[$r][4] = 'tarifs'; $this->rights[$r][5] = 'lire'; $r++; $this->rights[$r][0] = 292; $this->rights[$r][1] = 'Definir les permissions sur les tarifs'; $this->rights[$r][2] = 'w'; $this->rights[$r][3] = 0; $this->rights[$r][4] = 'tarif'; $this->rights[$r][5] = 'permission'; $r++; $this->rights[$r][0] = 293; $this->rights[$r][1] = 'Modifier les tarifs clients'; $this->rights[$r][2] = 'w'; $this->rights[$r][3] = 0; $this->rights[$r][4] = 'tarif'; $this->rights[$r][5] = 'client_modifier'; $r++; } /** * \brief Fonction appelee lors de l'activation du module. Insere en base les constantes, boites, permissions du module. * Definit egalement les repertoires de donnees a creer pour ce module. */ function init() { global $conf; // Permissions $this->remove(); // $this->load_tables(); // return $this->_init($sql); } /** \brief Fonction appelee lors de la desactivation d'un module. Supprime de la base les constantes, boites et permissions du module. */ function remove() { $sql = array(); return $this->_remove($sql); } /** * \brief Create tables and keys required by module * Files mymodule.sql and mymodule.key.sql with create table and create keys * commands must be stored in directory /mymodule/sql/. * This function is called by this->init. * \return int <=0 if KO, >0 if OK */ function load_tables() { return $this->_load_tables('/telephonie/sql/'); } } ?>
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <title>Registro Empleados</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <!-- DATATABLES --> <!-- <link rel="stylesheet" href="https://cdn.datatables.net/1.10.20/css/jquery.dataTables.min.css"> --> <!-- BOOTSTRAP --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.css"> <link rel="stylesheet" href="https://cdn.datatables.net/1.10.20/css/dataTables.bootstrap4.min.css"> <link href="/css/estilos_tablas.css" rel="stylesheet" type="text/css" /> <!-- MODAL --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.css"> </head> <body> <header th:include="/navbar.html :: header"> </header> <div class="container-fluid"> <div th:if="${employers != null and !employers.empty}"> <table id="myTabla" class="table table-striped flex-fill"> <thead> <tr> <th scope="col">IdEmpleado</th> <th scope="col">Nombre Usuario</th> <th scope="col">Salario</th> <th scope="col">Tipo</th> <th scope="col" th:if="${#authorization.expression('hasRole(''ROLE_ADMIN'')')}">Acción</th> </tr> </thead> <tr th:each="employer: ${employers}"> <td th:text="${employer.Employeid}"></td> <td th:text="${employer.username}"></td> <td th:text="${employer.salary}"></td> <td th:text="${employer.type}"></td> <td th:if="${#authorization.expression('hasRole(''ROLE_ADMIN'')')}"> <a th:href="@{/editaremployer/{Employeid}(Employeid=${employer.Employeid})}"> <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-pencil-fill" viewBox="0 0 16 16"> <path d="M12.854.146a.5.5 0 0 0-.707 0L10.5 1.793 14.207 5.5l1.647-1.646a.5.5 0 0 0 0-.708l-3-3zm.646 6.061L9.793 2.5 3.293 9H3.5a.5.5 0 0 1 .5.5v.5h.5a.5.5 0 0 1 .5.5v.5h.5a.5.5 0 0 1 .5.5v.5h.5a.5.5 0 0 1 .5.5v.207l6.5-6.5zm-7.468 7.468A.5.5 0 0 1 6 13.5V13h-.5a.5.5 0 0 1-.5-.5V12h-.5a.5.5 0 0 1-.5-.5V11h-.5a.5.5 0 0 1-.5-.5V10h-.5a.499.499 0 0 1-.175-.032l-.179.178a.5.5 0 0 0-.11.168l-2 5a.5.5 0 0 0 .65.65l5-2a.5.5 0 0 0 .168-.11l.178-.178z"/> </svg> </a> </td> </tr> </table> </div> </div> <!-- JQUERY --> <script src="https://code.jquery.com/jquery-3.5.1.js"></script> <!-- BOOTSTRAP --> <script src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js"></script> <script src="https://cdn.datatables.net/1.10.20/js/dataTables.bootstrap4.min.js"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script> <!<!-- MODAL --> <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js"></script> <script src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js"></script> <script src="https://cdn.datatables.net/1.10.20/js/dataTables.bootstrap4.min.js"></script> <!-- CUSTOM JS --> <script> class Auth { #authorization; constructor(authorization) { this.#authorization = authorization; } hasRole(role) { return this.#authorization && this.#authorization.expression(`hasRole('${role}')`); } } const auth = new Auth($('#myTabla').data('authorization')); const isAdmin = auth.hasRole('ROLE_ADMIN'); const columnTargets = isAdmin ? [1, 2, 3] : [1, 2]; const dataTableOptions = { columnDefs: [ {orderable: false, targets: columnTargets}, {searchable: false, targets: [1, 2]} ], destroy: true, language: { lengthMenu: "Mostrar _MENU_ registros por página", zeroRecords: "Ningún usuario encontrado", info: "Mostrando de _START_ a _END_ de un total de _TOTAL_ registros", infoEmpty: "Ningún usuario encontrado", infoFiltered: "(filtrados desde _MAX_ registros totales)", search: "Buscar:", loadingRecords: "Cargando...", paginate: { first: "Primero", last: "Último", next: "Siguiente", previous: "Anterior" } } }; const dataTable = $("#myTabla").DataTable(dataTableOptions); </script> </body> </html>
import sqlite3 import geopandas as gpd import matplotlib.pyplot as plt import os import warnings warnings.filterwarnings("ignore", category=FutureWarning) def make_impact_by_year_png(): # Connect and get data for the database conn = sqlite3.connect('meteorite_landings.db') # Get unique years from the database query = """ SELECT DISTINCT year FROM meteorite_landings WHERE year IS NOT NULL """ years = [result[0] for result in conn.execute(query).fetchall()] # Define the geographical bounds of the Americas americas_lat_min = -56.0 americas_lat_max = 83.0 americas_lon_min = -168.0 americas_lon_max = -34.0 # Create a directory to save the PNG files if not os.path.exists('meteorite_impacts_by_year'): os.mkdir('meteorite_impacts_by_year') # Loop through the years and create maps for year in years: # Modify the SQL query to select meteorite impacts for a specific year within the Americas query = f""" SELECT GeoLocation FROM meteorite_landings WHERE GeoLocation IS NOT NULL AND year = {year} AND (reclat >= {americas_lat_min} AND reclat <= {americas_lat_max}) AND (reclong >= {americas_lon_min} AND reclong <= {americas_lon_max}) """ results = conn.execute(query).fetchall() # Extract latitude and longitude from the GeoLocation data coordinates = [result[0].strip('()').split(', ') for result in results] latitude = [float(coord[0]) for coord in coordinates] longitude = [float(coord[1]) for coord in coordinates] # Create a GeoDataFrame with Point geometries gdf = gpd.GeoDataFrame(geometry=gpd.points_from_xy(longitude, latitude)) # Create a map of the Americas using geopandas world = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres')) america = world[(world['continent'] == 'North America') | (world['continent'] == 'South America')] # Plot meteorite landings on the map of the Americas ax = america.plot(figsize=(12, 6), color='white', edgecolor='black') gdf.plot(ax=ax, marker='o', color='red', markersize=5) plt.title(f'Meteorite Impacts in America ({year})') # Save the map as a PNG file filename = f'meteorite_impacts_by_year/{year}_meteorite_impacts.png' plt.savefig(filename, dpi=300) # Close the figure to avoid overlapping plots plt.close() # Close the database connection conn.close() if __name__=="__main__": make_impact_by_year_png()
package Papery::Renderer; use strict; use warnings; sub render { my ($class, $pulp, @options) = @_; $pulp->{meta}{_output} = $pulp->{meta}{_content}; return $pulp; } 1; __END__ =head1 NAME Papery::Renderer - Base class for Papery processors =head1 SYNOPSIS package Papery::Renderer::MyRenderer; use strict; use warnings; use Papery::Renderer; our @ISA = qw( Papery::Renderer ); sub render { my ( $class, $pulp ) = @_; # render $pulp->{meta}{_content} # update $pulp->{meta}{_output} return $pulp; } 1; =head1 DESCRIPTION C<Papery::Renderer> is the base class for Papery renderer classes. Subclasses only need to define an C<render()> method, taking a C<Papery::Pulp> object as the single parameter. The C<render()> method is expected to take the C<_content> key from the C<Papery::Pulp> object and use it to update the C<_output> key, that will be later saved to a file by the C<Papery::Pulp> object itself. =head1 METHODS This class provides a single method: =over 4 =item render( $pulp ) Render the C<_content> metadata, and update the C<$pulp> metadata and C<_output>. =back =head1 AUTHOR Philippe Bruhat (BooK), C<< <book at cpan.org> >> =head1 COPYRIGHT Copyright 2010 Philippe Bruhat (BooK), all rights reserved. =head1 LICENSE This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut
//@HEADER // ************************************************************************ // // HPCCG: Simple Conjugate Gradient Benchmark Code // Copyright (2006) Sandia Corporation // // Under terms of Contract DE-AC04-94AL85000, there is a non-exclusive // license for use of this work by or on behalf of the U.S. Government. // // 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. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 // USA // Questions? Contact Michael A. Heroux ([email protected]) // // changes Copyright 2014-2016 Gdansk University of Technology // Questions regarding changes? Contact Piotr Dorozynski ([email protected]) // // ************************************************************************ //@HEADER // Routine to compute an approximate solution to Ax = b where: // A - known matrix stored as an HPC_Sparse_Matrix struct // b - known right hand side vector // x - On entry is initial guess, on exit new approximate solution // max_iter - Maximum number of iterations to perform, even if // tolerance is not met. // tolerance - Stop and assert convergence if norm of residual is <= // to tolerance. // niters - On output, the number of iterations actually performed. #include <iostream> #include <common/util.h> #include <mpi_one_sided_extension/mpi_win_pmem.h> using std::cout; using std::cerr; using std::endl; #include <cmath> #include "mytimer.hpp" #include "HPCCG.hpp" #define TICK() t0 = mytimer() // Use TICK and TOCK to time a code section #define TOCK(t) t += mytimer() - t0 int HPCCG(HPC_Sparse_Matrix * A, const double * const b, double * const x, const char * const checkpoint_path, bool restart, const int max_iter, const double tolerance, int &niters, double & normr, double * times) { UNUSED(checkpoint_path); UNUSED(restart); MPI_Barrier(MPI_COMM_WORLD); double t_begin = mytimer(); // Start timing right away double t0, t1 = 0.0, t2 = 0.0, t3 = 0.0, t4 = 0.0; #ifdef USING_MPI double t5 = 0.0; #endif int nrow = A->local_nrow; int ncol = A->local_ncol; double * r = new double[nrow]; #ifdef USING_MPI double * p; MPI_Win_pmem p_win; MPI_Win_allocate_pmem(ncol * sizeof(double), sizeof(double), MPI_INFO_NULL, MPI_COMM_WORLD, &p, &p_win); #else double * p = new double[ncol]; // In parallel case, A is rectangular #endif double * Ap = new double[nrow]; normr = 0.0; double rtrans = 0.0; double oldrtrans; #ifdef USING_MPI int rank; // Number of MPI processes, My process ID MPI_Comm_rank(MPI_COMM_WORLD, &rank); #else int rank = 0; // Serial case (not using MPI) #endif int print_freq = max_iter / 10; if (print_freq > 50) print_freq = 50; if (print_freq < 1) print_freq = 1; // p is of length ncols, copy x to p for sparse MV operation TICK(); waxpby(nrow, 1.0, x, 0.0, x, p); TOCK(t2); #ifdef USING_MPI TICK(); exchange_externals(A, p, p_win); TOCK(t5); #endif TICK(); HPC_sparsemv(A, p, Ap); TOCK(t3); TICK(); waxpby(nrow, 1.0, b, -1.0, Ap, r); TOCK(t2); TICK(); ddot(nrow, r, r, &rtrans, t4); TOCK(t1); normr = sqrt(rtrans); if (rank == 0) cout << "Initial Residual = " << normr << endl; MPI_Barrier(MPI_COMM_WORLD); if (rank == 0) { cout << "Start/Restart time is " << mytimer() - t_begin << " seconds." << endl; } for (int k = 1; k<max_iter && normr > tolerance; k++) { if (k == 1) { TICK(); waxpby(nrow, 1.0, r, 0.0, r, p); TOCK(t2); } else { oldrtrans = rtrans; TICK(); ddot(nrow, r, r, &rtrans, t4); TOCK(t1);// 2*nrow ops double beta = rtrans / oldrtrans; TICK(); waxpby(nrow, 1.0, r, beta, p, p); TOCK(t2);// 2*nrow ops } normr = sqrt(rtrans); if (rank == 0 && (k%print_freq == 0 || k + 1 == max_iter)) cout << "Iteration = " << k << " Residual = " << normr << endl; #ifdef USING_MPI TICK(); exchange_externals(A, p, p_win); TOCK(t5); #endif TICK(); HPC_sparsemv(A, p, Ap); TOCK(t3); // 2*nnz ops double alpha = 0.0; TICK(); ddot(nrow, p, Ap, &alpha, t4); TOCK(t1); // 2*nrow ops alpha = rtrans / alpha; TICK(); waxpby(nrow, 1.0, x, alpha, p, x);// 2*nrow ops waxpby(nrow, 1.0, r, -alpha, Ap, r); TOCK(t2);// 2*nrow ops niters = k; if (rank == 0) { cout << "Progress [%]: " << k * 100 / (max_iter - 1) << endl; } } // Store times times[1] = t1; // ddot time times[2] = t2; // waxpby time times[3] = t3; // sparsemv time times[4] = t4; // AllReduce time #ifdef USING_MPI times[5] = t5; // exchange boundary time #endif #ifdef USING_MPI MPI_Win_free_pmem(&p_win); #else delete[] p; #endif delete[] Ap; delete[] r; MPI_Barrier(MPI_COMM_WORLD); times[0] = mytimer() - t_begin; // Total time. All done... return(0); }
{% extends 'base.html.twig' %} {% block body %} <div class="row mt-2 ms-2 me-2"> <div class="col-md-4 col-12 mb-2"> <div class="card"> <div class="card-header"> Issues assigned to you </div> <div class="card-body"> {% if assigned_issues %} <div class="accordion" {{ stimulus_controller('tooltip-initialize') }}> {% for key, issue in assigned_issues %} <div class="accordion-item"> <h2 class="accordion-header" id="heading{{ key }}"> <button class="accordion-button collapsed" data-bs-toggle="collapse" data-bs-target="#collapseAssigned{{ key }}" aria-expanded="false" aria-controls="collapseAssigned{{ key }}"> <span class="badge rounded-pill me-2" {{ stimulus_target('tooltip-initialize', 'tooltip') }} data-bs-placement="top" title="Status" style="background-color: {{ issue.status.color }} !important;"> {{ issue.status.name }} </span> <span class="badge rounded-pill me-2" {{ stimulus_target('tooltip-initialize', 'tooltip') }} data-bs-placement="top" title="Priority" style="background-color: {{ issue.priority.color }} !important;"> {{ issue.priority.name }} </span> {{ issue.title }} </button> </h2> <div id="collapseAssigned{{ key }}" class="accordion-collapse collapse" aria-labelledby="heading{{ key }}"> <div class="accordion-body markdown-body" style="position: relative"> <a href={{ path('app_issue', {id: issue.id}) }} class="stretched-link"></a> {{ issue.description|markdown_to_html }} </div> </div> </div> {% endfor %} </div> {% else %} <h1 class="display-6 text-muted text-center">None</h1> {% endif %} </div> </div> </div> <div class="col-md-4 col-12 mb-2"> <div class="card"> <div class="card-header"> Recent comments </div> <div class="card-body"> {% if recent_comments %} {% for key, comment in recent_comments %} <div class="card mb-4"> <div class="card-header text-muted fw-light"> <span>{{ comment.author.username }} added a comment to <a href={{ path('app_issue', {id: comment.issue.id, _fragment: 'comment-' ~ comment.id}) }} class="link-secondary">issue {{ comment.issue.id }}</a></span> <span class="float-end text-muted fw-light"> {{ comment.createdAt|date }} </span> </div> <div class="card-body markdown-body"> {{ comment.text|markdown_to_html }} </div> </div> {% endfor %} {% else %} <h1 class="display-6 text-muted text-center">None</h1> {% endif %} </div> </div> </div> <div class="col-md-4 col-12"> <div class="card"> <div class="card-header"> Recent issues </div> <div class="card-body"> {% if recent_issues %} <div class="accordion" {{ stimulus_controller('tooltip-initialize') }}> {% for key, issue in recent_issues %} <div class="accordion-item"> <h2 class="accordion-header" id="heading{{ key }}"> <button class="accordion-button collapsed" data-bs-toggle="collapse" data-bs-target="#collapseRecent{{ key }}" aria-expanded="false" aria-controls="collapseRecent{{ key }}"> <span class="badge rounded-pill me-2" {{ stimulus_target('tooltip-initialize', 'tooltip') }} data-bs-placement="top" title="Status" style="background-color: {{ issue.status.color }} !important;"> {{ issue.status.name }} </span> <span class="badge rounded-pill me-2" {{ stimulus_target('tooltip-initialize', 'tooltip') }} data-bs-placement="top" title="Priority" style="background-color: {{ issue.priority.color }} !important;"> {{ issue.priority.name }} </span> {{ issue.title }} </button> </h2> <div id="collapseRecent{{ key }}" class="accordion-collapse collapse" aria-labelledby="heading{{ key }}"> <div class="accordion-body markdown-body" style="position: relative"> <a href={{ path('app_issue', {id: issue.id}) }} class="stretched-link"></a> {{ issue.description|markdown_to_html }} </div> </div> </div> {% endfor %} </div> {% else %} <h1 class="display-6 text-muted text-center">None</h1> {% endif %} </div> </div> </div> </div> {% endblock %}
import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import '../../widgets/my_text_field.dart'; import 'add_user_model.dart'; class AddUserProviderWidget extends StatelessWidget { const AddUserProviderWidget({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return ChangeNotifierProvider(create: (context) => AddUserModel(), child: const AddUser()); } } class AddUser extends StatelessWidget { const AddUser({Key? key}) : super(key: key); @override Widget build(BuildContext context) { final model = context.read <AddUserModel>(); final name = TextEditingController(); return Scaffold( appBar: AppBar( leading: const BackButton( color: Colors.black ), backgroundColor: Colors.white, title: const Text( 'Введите данные', style: TextStyle(color: Colors.black), ), ), body: ListView( scrollDirection: Axis.vertical, children: [ const SizedBox( height: 20, ), MyTextField( hintTextField: 'Фамилия Имя Отчество', controller: name, // onPress: (value) => print(value), // onEditingComplete: () => // model.saveUser(context), ), const SizedBox( height: 10, ), Container( height: 45, margin: const EdgeInsets.only(top:20, left: 30, right: 30), child: ElevatedButton( onPressed: () { model.userName = name.text; model.saveUser(context); }, style: ButtonStyle( backgroundColor: MaterialStateProperty.all(const Color.fromRGBO(169, 167, 167, 100)), shape: MaterialStateProperty.all<RoundedRectangleBorder>( RoundedRectangleBorder( borderRadius: BorderRadius.circular(15.0), side: const BorderSide( color: Colors.black, width: 0.5, ), ), ), ), child: const Text('Сохранить', style: TextStyle(fontSize: 20),), ), ) ]), ); } }
# models Tracking models can be chosen from the ros parameter `~tracking_model`: Each model has its own parameters, which can be set in the ros parameter server. - model name - parameter name for general - override parameter name for each tracking object class ## linear constant acceleration model - prediction $$ \begin{bmatrix} x_{k+1} \\ y_{k+1} \\ v_{x_{k+1}} \\ v_{y_{k+1}} \\ a_{x_{k+1}} \\ a_{y_{k+1}} \end{bmatrix} = \begin{bmatrix} 1 & 0 & dt & 0 & \frac{1}{2}dt^2 & 0 \\ 0 & 1 & 0 & dt & 0 & \frac{1}{2}dt^2 \\ 0 & 0 & 1 & 0 & dt & 0 \\ 0 & 0 & 0 & 1 & 0 & dt \\ 0 & 0 & 0 & 0 & 1 & 0 \\ 0 & 0 & 0 & 0 & 0 & 1 \\ \end{bmatrix} \begin{bmatrix} x_k \\ y_k \\ v_{x_k} \\ v_{y_k} \\ a_{x_k} \\ a_{y_k} \end{bmatrix} + noise $$ - noise model - random walk in acc: 2 parameters(currently disabled) - random state noise: 6 parameters $$ \begin{align} noise &= \begin{bmatrix} \frac{dt^{3}}{6} \\ 0\\ \frac{dt^{2}}{2} \\ 0 \\ dt \\0 \end{bmatrix} \nu_{ax_k} + \begin{bmatrix} 0 \\ \frac{dt^{3}}{6} \\ 0 \\ \frac{dt^{2}}{2} \\ 0 \\ dt \end{bmatrix} \nu_{ay_k} & \text{(random walk in acc)} \\ noise &= \begin{bmatrix} \nu_{x_k} \\ \nu_{y_k} \\ \nu_{v_{x_k}} \\ \nu_{v_{y_k}} \\ \nu_{a_{x_k}} \\ \nu_{a_{y_k}} \end{bmatrix} & \text{(random state noise)} & \end{align} $$ - observation - observation: x,y,vx,vy - observation noise: 4 parameters ## constant turn rate and velocity model Just idea, not implemented yet. $$ \begin{align} x_{k+1} &= x_k + \frac{v_k}{\omega_k} (sin(\theta_k + \omega_k dt) - sin(\theta_k)) \\ y_{k+1} &= y_k + \frac{v_k}{\omega_k} (cos(\theta_k) - cos(\theta_k + \omega_k dt)) \\ v_{k+1} &= v_k \\ \theta_{k+1} &= \theta_k + \omega_k dt \\ \omega_{k+1} &= \omega_k \end{align} $$ ## Noise filtering Radar sensors often have noisy measurement. So we use the following filter to reduce the false positive objects. The figure below shows the current noise filtering process. ![noise_filter](image/noise_filtering.drawio.svg) ### minimum range filter In most cases, Radar sensors are used with other sensors such as LiDAR and Camera, and Radar sensors are used to detect objects far away. So we can filter out objects that are too close to the sensor. `use_distance_based_noise_filtering` parameter is used to enable/disable this filter, and `minimum_range_threshold` parameter is used to set the threshold. ### lanelet based filter With lanelet map information, We can filter out false positive objects that are not likely important obstacles. We filter out objects that satisfy the following conditions: - too large lateral distance from lane - velocity direction is too different from lane direction - too large lateral velocity Each condition can be set by the following parameters: - `max_distance_from_lane` - `max_angle_diff_from_lane` - `max_lateral_velocity`
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="./d3.min.js"></script> <script> //选择 body 标签,添加 svg 元素,设置 svg 元素的宽度和高度为 500 // let body = d3.select('body').append('svg').attr("width", 500).attr('height', 500).style('background-color', 'red'); let body = d3.select("body").style("background-color", "black"); body.append('p').text("this is p line -0"); body.append('p').text("this is p1 line -1"); //设置属性 body.selectAll('p').style('color','yellow'); body.select('p').style("color","pink"); //插入 body.insert('p').text('this is p4 line -4'); body.insert('p', 'p:first-of-type').text("insert-p"); //删除 body.select('p:last-of-type').remove(); </script> </head> <body> <h2>D3对象</h2> <span> D3 对象类似 jQuery 中的 “$”对象,采用了同样的链式语法。每次打点调用 d3 提供的函数方法,都会返回一个 d3 对象,这样可以继续调用 d3 的其他函数方法。 </span> <h2>选择元素</h2> <span> D3 选择元素提供了两个函数:select 和 selectAll。 select 返回css选择器所匹配的第一个元素。 selectAll 返回css选择器匹配的所有元素。 选择元素后可以操作元素,操作元素主要分为增加 ( append )、插入 ( insert )、删除元素 ( remove ) 和设置获取元素属性 ( attr, style )。 </span> <h2>数据绑定</h2> <span> 数据绑定是将数据绑定到 DOM 元素上,这是 D3 最大的特色,也是 D3 的设计哲学。D3 中数据绑定提供了datum()和data()两个函数。 datum(value)选择集中的每一个元素绑定相同的数据value。 这个方法不会进行数据绑定的计算(update、enter、exit),只能在现有的元素上绑定数据。如果value是数组会自动转成字符串。 data([value])选择集中的每一个元素分别绑定数组value中的一项。 </span> </body> </html>
#pragma once #include "QQmlAutoPropertyHelpers.h" #include <sstream> #include <iomanip> #include <QUuid> #include <QThreadPool> #include <functional> static std::string convertIdToStr(const long long& msb,const long long& lsb) { std::stringstream msbStream; msbStream << std::setfill('0') << std::setw(sizeof(unsigned long long) * 2) << std::hex << static_cast<unsigned long long>(msb); std::string msbStr(msbStream.str()); std::stringstream lsbStream; lsbStream << std::setfill('0') << std::setw(sizeof(unsigned long long) * 2) << std::hex << static_cast<unsigned long long>(lsb); std::string lsbStr(lsbStream.str()); std::string idStr("{00000000-0000-0000-0000-000000000000}"); for (unsigned int i = 1; i < 9; i++) { idStr[i] = msbStr[i - 1]; } for (unsigned int i = 10; i < 14; i++) { idStr[i] = msbStr[i - 2]; } for (unsigned int i = 15; i < 19; i++) { idStr[i] = msbStr[i - 3]; } for (unsigned int i = 20; i < 24; i++) { idStr[i] = lsbStr[i - 20]; } for (unsigned int i = 25; i < 37; i++) { idStr[i] = lsbStr[i - 21]; } return idStr; } static bool checkIdStrFormat(const char* idStr) { /* * Id Format = {00000000-0000-0000-0000-000000000000} * The zeros can be replaced by any hex char: <0-9> | <a-f> | <A-F> */ return (std::strlen(idStr) == 38) && (idStr[0] == '{') && (idStr[9] == '-') && (idStr[14] == '-') && (idStr[19] == '-') && (idStr[24] == '-') && (idStr[37] == '}'); } static void convertStrToId(const char* str, long long& msb, long long& lsb) { /* * Removing all occurrences of '-' , '{' , '}' * from a string of the form {00000000-0000-0000-0000-000000000000} * The produced string, idHexStr is a sequential representation of the id * that later would be converted to two std::int_64t numbers */ if(checkIdStrFormat(str) == false) return; char msbStr[17] = {0}; char lsbStr[17] = {0}; for (int i = 1; i < 9; i++) { msbStr[i-1] = str[i]; } for (int i = 10; i < 14; i++) { msbStr[i-2] = str[i]; } for (int i = 15; i < 19; i++) { msbStr[i-3] = str[i]; } for (int i = 20; i < 24; i++) { lsbStr[i-20] = str[i]; } for (int i = 25; i < 37; i++) { lsbStr[i-21] = str[i]; } msb = static_cast<long long>(std::strtoull(msbStr, nullptr, 16)); lsb = static_cast<long long>(std::strtoull(lsbStr, nullptr, 16)); } template<typename T> static QVariantList vectorToList(const QVector<T>& vec) { QVariantList list; list.reserve(vec.size()); for(int i = 0 ; i < vec.size() ; i++) list.append(QVariant::fromValue<T>(vec.at(i))); return list; } template<typename T> static QVector<T> listToVector(const QVariantList& list) { QVector<T> vec; vec.reserve(list.size()); for(int i = 0 ; i < list.size() ; i++) vec.append(list.at(i).value<T>()); return vec; } namespace QUtils { static inline void runAsync(const std::function<void()>& func) { class runner :public QRunnable { private: std::function<void()> m_func; public: runner(const std::function<void()>& func) : m_func(func) { } void run() override { m_func(); } }; QThreadPool::globalInstance()->start(new runner(func)); } static inline void runAsyncWait(const std::function<void()>& func) { class runner :public QRunnable { private: std::function<void()> m_func; public: runner(const std::function<void()>& func) : m_func(func) { } void run() override { m_func(); } }; runner* instance = new runner(func); while (QThreadPool::globalInstance()->tryStart(instance) == false) std::this_thread::yield(); } }
# -*- coding: utf-8 -*- # # PartMgr GUI - Item select widget # # Copyright 2014 Michael Buesch <[email protected]> # # 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., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # from partmgr.gui.entitycombobox import * from partmgr.gui.util import * from partmgr.core.entity import * class ItemSelectWidget(QWidget): "Abstract item selection widget" selectionChanged = Signal(object) def __init__(self, parent=None, actionButtonLabel=None, itemLabel=None, itemSpecificWidget=None): QWidget.__init__(self, parent) self.setLayout(QGridLayout(self)) self.layout().setContentsMargins(QMargins(0, 5, 0, 5)) x = 0 comboLayout = QVBoxLayout() if itemLabel: self.itemLabel = QLabel(itemLabel, self) comboLayout.addWidget(self.itemLabel) self.combo = EntityComboBox(self) comboLayout.addWidget(self.combo) comboLayout.addStretch(1) comboWidth = 4 if itemSpecificWidget else 8 self.layout().addLayout(comboLayout, 0, x, 1, comboWidth) x += comboWidth if itemSpecificWidget: self.layout().addWidget(itemSpecificWidget, 0, x, 1, 4) x += 4 if actionButtonLabel: self.actionButton = QPushButton(actionButtonLabel, self) self.layout().addWidget(self.actionButton, 0, x, 1, 1) x += 1 self.actionButton.released.connect( self.actionButtonPressed) self.descLabel = QLabel(self) self.descLabel.hide() self.layout().addWidget(self.descLabel, 1, 0, 1, x) self.setProtected() self.combo.currentIndexChanged.connect( self.__idxChanged) def setProtected(self, prot=True): self.combo.setProtected(prot) try: self.actionButton.setEnabled(not prot) except AttributeError as e: pass def updateData(self, entities, selected=None): self.combo.updateData(entities, selected) def clear(self): self.combo.clear() def getSelected(self): return self.combo.getSelectedEntity() def setSelected(self, entity): self.combo.setSelectedEntity(entity) def __idxChanged(self, comboIndex): entity = self.combo.itemData(comboIndex) description = entity.getDescription() if entity else None if description: self.descLabel.setText(description) self.descLabel.show() else: self.descLabel.hide() self.selectionChanged.emit(entity) def actionButtonPressed(self): raise NotImplementedError
import { onGetProducts } from './connectionDB.js'; const productsContainer = document.getElementById('products-container'); const messageNotFound = document.getElementById('message-not-found'); window.addEventListener('DOMContentLoaded', async (e) => { if (localStorage.getItem('currentProducts') == null) { localStorage.setItem('currentProducts', JSON.stringify([])); } const querySnapshot = await onGetProducts(); if (querySnapshot.size == 0) { clearLocalStorage(); messageNotFound.innerHTML = 'Actualmente no hay artículos disponibles.'; return; } let html = '<div class="row row-cols-1 row-cols-sm-2 row-cols-md-3 g-3">'; querySnapshot.forEach((doc) => { const product = doc.data(); const medidas = product.medidas; if (product.productInCart == null) { product.productInCart = verifyProductCart(product); } html += ` <div class="col"> <div class="card shadow-sm"> <img src="${product.imageURL}" /> <div class="card-body"> <h5 class="card-title">${product.nombre} - ${product.marca}</h5> <p class="card-text">${product.descripcion}.</p> <p class="card-text">Medidas: ${medidas.alto}cm de alto x ${medidas.ancho}cm de ancho x ${medidas.profundidad}cm de profundidad.</p> <p class="card-text price">$ ${product.precio}</p> <div class="d-flex justify-content-between align-items-center"> <div class="btn-group"> <i class="fas ${product.disponible ? 'fa-check-circle available' : 'fa-exclamation-circle sold-out'}">${product.disponible ? 'Disponible' : 'Agotado'} </i> </div> ${labelInCart(product.productInCart)} <button id="button-product-${product.id}" style="width: 160px" onclick="addToCart(${product.id})" class="btn btn-success" ${!product.disponible || product.productInCart ? 'disabled' : ''}> <i class="fas fa-cart-plus">Agregar al carrito</i> </button> <button id="spinner-cart-product-${product.id}" class="btn spinner-button btn-success hidden d-none"> <span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> </button> </div> </div> </div> </div> `; setProductInLocalStorage(product); }); html += `</div>`; productsContainer.innerHTML = html; }); function verifyProductCart(product) { var productsCart = getCartInLocalStorage(); var productCart = productsCart.find(x => x.id == product.id); if (!productCart || !productCart.productInCart) return false; return true; } function labelInCart(bool) { if (bool) return `<div class="btn-group"> <i class="fas fa-check-circle available"> En el carrito </i> </div> `; return ''; }
import logging as log import numpy as np import pandas as pd import matplotlib.pyplot as plt from typing import Tuple def constrain_plotting_df( full_df: pd.DataFrame, column_list: list ) -> pd.DataFrame: """ Constraining an input-df based on nan-values in cells, as well as only one entry per target and observation type """ # First, drop all entries where the EPA query failed epa_sc = full_df.dropna(subset=["pl_name"]) # Create unique data frame based on target name and observation type specialised_df = epa_sc.drop_duplicates(subset=["Target Name", "Type"], ignore_index=True) # Constrain to available values constrained_df = specialised_df.dropna(subset=column_list) #ignore_index=True) # Check for remaining empty values and log missing targets dropped_df = specialised_df.loc[ pd.isnull(specialised_df[column_list]).any(axis=1) ] log.info(f"Not plotting " f"{np.unique(dropped_df['Target Name'].values)} " f"due to missing values!\n") return constrained_df def plot_parameters( full_df: pd.DataFrame, x_param: str, y_param: str, savename: str ) -> None: """ Wrapper for plotting target parameters with variable x- and y-parameters """ log.info(f"Plotting {x_param} against {y_param}") # SANITY CHECK: x- and y-parameters must be columns in the data frame # TO BE ADDED # Constraining data frame to usable values plotting_df = constrain_plotting_df(full_df, [x_param, y_param]) # Plot the remaining values fig, ax = draw_figure(savename) fill_figure(ax, plotting_df, x_param, y_param) finish_figure(savename) return None def draw_figure(savename: str) -> Tuple[plt.Figure, plt.Axes]: """Instantiate pyplot figure""" fig, ax = plt.subplots(figsize=(6, 6)) ax.set(title=f"{savename}") return fig, ax def fill_figure( ax: plt.Axes, specialised_df: pd.DataFrame, x_param: str, y_param: str ) -> None: """ Fill figure with data points. The data frame drawn from here already needs to be completely prepared for plotting. """ # ax.scatter(specialised_df[x_param], specialised_df[y_param]) transits = specialised_df.loc[specialised_df["Type"] == "Transit"] eclipses = specialised_df.loc[specialised_df["Type"] == "Eclipse"] ax.scatter(transits[x_param], transits[y_param], color="tab:blue", marker="o", edgecolor="black") ax.scatter(eclipses[x_param], eclipses[y_param], color="tab:red", marker=".", edgecolor="black") ax.set(xlabel=f"{x_param}", ylabel=f"{y_param}") # Potential axis scaling if x_param in ["pl_orbper", "pl_orbsmax"]: plt.xscale("log") return None def finish_figure(savename: str) -> None: """Clean up pyplot figure""" plt.tight_layout() plt.savefig(f"plots/target_parameters/{savename}.svg") return None
#include "item.h" #include <iostream> bool itemInit() { if (SDL_Init(SDL_INIT_EVERYTHING) > 0) { std::cout << "HEY.. SDL_Init HAS FAILED. SDL_ERROR: " << SDL_GetError() << std::endl; return false; } if (!(IMG_Init(IMG_INIT_PNG))) { std::cout << "IMG_init has failed. Error: " << SDL_GetError() << std::endl; return false; } return true; } void itemQuit() { SDL_Quit(); IMG_Quit(); } item::item() { pos.x = 30; pos.y = 60; image = NULL; pos.w = 100; pos.h = 100; oldTick = 0; } item::~item() { if (image != NULL) { SDL_DestroyTexture(image); image = NULL; } } bool item::loadImage(std::string filename) { SDL_Surface* temp = IMG_Load(filename.c_str()); if (temp != NULL) { image = SDL_CreateTextureFromSurface(ren, temp); SDL_FreeSurface(temp); if (image != NULL) { return true; } } return false; } void item::freeImage() { if (image != NULL) { SDL_DestroyTexture(image); image = NULL; } } void item::setRenderer(SDL_Renderer* dest) { ren = dest; } void item::setSize(int w, int h) { pos.w = w; pos.h = h; } void item::setPos(int x, int y) { pos.x = x; pos.y = y; } SDL_Rect* item::getPos() { return &pos; } void item::move(int x, int y) { pos.x += x; pos.y += y; } bool item::getCollision(item* other) { int dx, dy, rs; dx = pos.x + center.x - (other->getPos()->x + other->getCenter().x); dy = pos.y + center.y - (other->getPos()->y + other->getCenter().y); rs = center.r + other->getCenter().r; dx *= dx; dy *= dy; rs *= rs; if (dx + dy < rs) { return true; } return false; } bool item::isClicked(int x, int y) { int dx, dy, rs; dx = pos.x + center.x - x; dy = pos.y + center.y - y; rs = center.r; dx *= dx; dy *= dy; rs *= rs; return (dx + dy < rs); } circle item::getCenter() { return center; } void item::setCenter(int x, int y, int r) { center.x = x; center.y = y; center.r = r; } void item::draw(double angle) { if (image != NULL) { SDL_RenderCopyEx(ren, image, NULL, &pos, angle, NULL, SDL_FLIP_NONE); } else { std::cout << "Help, image is NULL at draw()\n"; } } void item::draw() { if (image != NULL) { SDL_RenderCopy(ren, image, NULL, &pos); } else { std::cout << "Help, image is NULL at draw()\n"; } } void item::update(int tick) { oldTick = tick; }
// // BIM IFC library: this library works with Autodesk(R) Revit(R) to export IFC files containing model geometry. // Copyright (C) 2012 Autodesk, Inc. // // 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. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA // using System; using System.Collections.Generic; using System.Text; using Autodesk.Revit; using Autodesk.Revit.DB; using Autodesk.Revit.DB.IFC; using System.Text.RegularExpressions; namespace Revit.IFC.Export.Utility { /// <summary> /// Provides static methods for naming and string related operations. /// </summary> public class NamingUtil { private static IDictionary<string, Tuple<ElementId, int>> m_NameIncrNumberDict = new Dictionary<string, Tuple<ElementId, int>>(); public static void InitNameIncrNumberCache() { m_NameIncrNumberDict.Clear(); } /// <summary> /// Removes spaces in a string. /// </summary> /// <param name="originalString">The original string.</param> /// <returns>The string without spaces.</returns> public static string RemoveSpaces(string originalString) { return originalString.Replace(" ", null); } /// <summary> /// Removes underscores in a string. /// </summary> /// <param name="originalString">The original string.</param> /// <returns>The string without underscores.</returns> public static string RemoveUnderscores(string originalString) { return originalString.Replace("_", null); } /// <summary> /// Removes spaces and underscores in a string. /// </summary> /// <param name="originalString">The original string.</param> /// <returns>The string without spaces or underscores.</returns> public static string RemoveSpacesAndUnderscores(string originalString) { return originalString.Replace(" ", null).Replace("_", null); } /// <summary> /// Checks if two strings are equal ignoring case and spaces. /// </summary> /// <param name="string1">The string to be compared.</param> /// <param name="string2">The other string to be compared.</param> /// <returns>True if they are equal, false otherwise.</returns> public static bool IsEqualIgnoringCaseAndSpaces(string string1, string string2) { if (string1 == null || string2 == null) return (string1 == string2); string nospace1 = RemoveSpaces(string1); string nospace2 = RemoveSpaces(string2); return (string.Compare(nospace1, nospace2, true) == 0); } /// <summary> /// Checks if two strings are equal ignoring case, spaces and underscores. /// </summary> /// <param name="string1">The string to be compared.</param> /// <param name="string2">The other string to be compared.</param> /// <returns>True if they are equal, false otherwise.</returns> public static bool IsEqualIgnoringCaseSpacesAndUnderscores(string string1, string string2) { string nospaceOrUnderscore1 = RemoveSpacesAndUnderscores(string1); string nospaceOrUnderscore2 = RemoveSpacesAndUnderscores(string2); return (string.Compare(nospaceOrUnderscore1, nospaceOrUnderscore2, true) == 0); } /// <summary> /// Checks if a string is equal ignoring case, spaces and underscores to one of two possible strings. /// </summary> /// <param name="string1">The string to be compared.</param> /// <param name="string2a">Option 1 to be compared.</param> /// <param name="string2b">Option 2 to be compared.</param> /// <returns>True if string1 matches string2a or string2b, false otherwise.</returns> public static bool IsEqualIgnoringCaseSpacesAndUnderscores(string string1, string string2a, string string2b) { string nospaceOrUnderscore1 = RemoveSpacesAndUnderscores(string1); string nospaceOrUnderscore2a = RemoveSpacesAndUnderscores(string2a); if (string.Compare(nospaceOrUnderscore1, nospaceOrUnderscore2a, true) == 0) return true; string nospaceOrUnderscore2b = RemoveSpacesAndUnderscores(string2b); return (string.Compare(nospaceOrUnderscore1, nospaceOrUnderscore2b, true) == 0); } /// <summary> /// Gets override string value from element parameter. /// </summary> /// <param name="element">The element.</param> /// <param name="paramName">The parameter name.</param> /// <param name="originalValue">The original value.</param> /// <returns>The string contains the string value.</returns> public static string GetOverrideStringValue(Element element, string paramName, string originalValue) { //string strValue; string paramValue; if (element != null) { if (ParameterUtil.GetStringValueFromElement(element, paramName, out paramValue) != null && !string.IsNullOrEmpty(paramValue)) { string propertyValue = null; object strValue = null; ParamExprResolver.CheckForParameterExpr(paramValue, element, paramName, ParamExprResolver.ExpectedValueEnum.STRINGVALUE, out strValue); if (strValue != null && strValue is string) propertyValue = strValue as string; else propertyValue = paramValue; // return the original paramValue return propertyValue; } } return originalValue; } /// <summary> /// Gets the IFC name for a material layer, taking into account shared parameter overrides. /// </summary> /// <param name="material">The material.</param> /// <returns>The IFC name of the material.</returns> public static string GetMaterialLayerName(Material material) { return GetOverrideStringValue(material, "IfcMaterialLayer.Name", GetMaterialName(material)); } /// <summary> /// Gets the category name for a material, taking into account shared parameter overrides. /// </summary> /// <param name="material">The material.</param> /// <returns>The category name of the material.</returns> /// <remarks>This is a convenience function for Materials only.</remarks> public static string GetMaterialCategoryName(Material material) { if (material == null) return null; return GetOverrideStringValue(material, "IfcCategory", GetOverrideStringValue(material, "Category", material.MaterialCategory)); } /// <summary> /// Gets the IFC name for a material, taking into account shared parameter overrides. /// </summary> /// <param name="material">The material.</param> /// <returns>The IFC name of the material.</returns> /// <remarks>This is a convenience function for Materials only.</remarks> public static string GetMaterialName(Material material) { if (material == null) return null; return GetNameOverride(material, material.Name); } /// <summary> /// Gets the IFC name for a material by id, taking into account shared parameter overrides. /// </summary> /// <param name="doc">The document.</param> /// <param name="materialId">The id of the material.</param> /// <returns>The IFC name of the material.</returns> /// <remarks>This is a convenience function for Materials only.</remarks> public static string GetMaterialName(Document doc, ElementId materialId) { Material material = doc.GetElement(materialId) as Material; return GetMaterialName(material); } /// <summary> /// Gets the IFC name for an element, taking into account shared parameter overrides. /// </summary> /// <param name="element">The element.</param> /// <param name="originalValue">The default IFC name of the element, if not overriden.</param> /// <returns>The IFC name of the element.</returns> public static string GetNameOverride(Element element, string originalValue) { if (element == null) return originalValue; // CQ_TODO: Understand the naming here and possible use GetCleanName - have it as UI option? string overrideValue = GetOverrideStringValue(element, "IfcName", originalValue); // For backward compatibility where the old parameter name may still be use (NameOverride), handle it also if the above returns nothing if (string.IsNullOrEmpty(overrideValue) || (!string.IsNullOrEmpty(overrideValue) && overrideValue.Equals(originalValue))) { overrideValue = GetOverrideStringValue(element, "NameOverride", originalValue); } if (element is ElementType || element is FamilySymbol) { if (string.IsNullOrEmpty(overrideValue) || (!string.IsNullOrEmpty(overrideValue) && overrideValue.Equals(originalValue))) { overrideValue = GetOverrideStringValue(element, "IfcName[Type]", originalValue); } } // CQ_TODO: Understand the naming here and possible use GetCleanName - have it as UI option? //overrideValue = GetCleanName(overrideValue); //GetOverrideStringValue will return the override value from the parameter specified, otherwise it will return the originalValue return overrideValue; } public static string GetNameOverride(IFCAnyHandle handle, Element element, string originalValue) { List<Exporter.PropertySet.AttributeEntry> entries = ExporterCacheManager.AttributeCache.GetEntry(handle, Exporter.PropertySet.PropertyType.Label, "Name"); if (entries != null) { foreach (Exporter.PropertySet.AttributeEntry entry in entries) { string result = entry.AsString(element); if (result != null) return result; } } return GetNameOverride(element, originalValue); } /// <summary> /// Gets override long name from element. /// </summary> /// <param name="element"> /// The element. /// </param> /// <param name="originalValue"> /// The original value. /// </param> /// <returns> /// The string contains the long name string value. /// </returns> public static string GetLongNameOverride(Element element, string originalValue) { string longNameOverride = "IfcLongName"; string overrideValue = GetOverrideStringValue(element, longNameOverride, originalValue); // For backward compatibility where the old parameter name may still be use (LongNameOverride), handle it also if the above returns nothing if (string.IsNullOrEmpty(overrideValue) || (!string.IsNullOrEmpty(overrideValue) && overrideValue.Equals(originalValue))) { longNameOverride = "LongNameOverride"; overrideValue = GetOverrideStringValue(element, longNameOverride, originalValue); } //GetOverrideStringValue will return the override value from the parameter specified, otherwise it will return the originalValue return overrideValue; } public static string GetLongNameOverride(IFCAnyHandle handle, Element element, string originalValue) { List<Exporter.PropertySet.AttributeEntry> entries = ExporterCacheManager.AttributeCache.GetEntry(handle, Exporter.PropertySet.PropertyType.Text, "LongName"); if (entries != null) { foreach (Exporter.PropertySet.AttributeEntry entry in entries) { string result = entry.AsString(element); if (result != null) return result; } } return GetLongNameOverride(element, originalValue); } /// <summary> /// Gets override description from element. /// </summary> /// <param name="element"> /// The element. /// </param> /// <param name="originalValue"> /// The original value. /// </param> /// <returns> /// The string contains the description string value. /// </returns> public static string GetDescriptionOverride(Element element, string originalValue) { string nameOverride = "IfcDescription"; string overrideValue = GetOverrideStringValue(element, nameOverride, originalValue); // For backward compatibility where the old parameter name may still be use (DescriptionOverride), handle it also if the above returns nothing if (string.IsNullOrEmpty(overrideValue) || (!string.IsNullOrEmpty(overrideValue) && overrideValue.Equals(originalValue))) { overrideValue = GetOverrideStringValue(element, "DescriptionOverride", originalValue); } if (element is ElementType || element is FamilySymbol) { if (string.IsNullOrEmpty(overrideValue) || (!string.IsNullOrEmpty(overrideValue) && overrideValue.Equals(originalValue))) { nameOverride = "IfcDescription[Type]"; overrideValue = GetOverrideStringValue(element, nameOverride, originalValue); } } //GetOverrideStringValue will return the override value from the parameter specified, otherwise it will return the originalValue return overrideValue; } public static string GetDescriptionOverride(IFCAnyHandle handle, Element element, string originalValue) { List<Exporter.PropertySet.AttributeEntry> entries = ExporterCacheManager.AttributeCache.GetEntry(handle, Exporter.PropertySet.PropertyType.Text, "Description"); if (entries != null) { foreach (Exporter.PropertySet.AttributeEntry entry in entries) { string result = entry.AsString(element); if (result != null) return result; } } return GetDescriptionOverride(element, originalValue); } /// <summary> /// Gets override object type from element. /// </summary> /// <param name="element"> /// The element. /// </param> /// <param name="originalValue"> /// The original value. /// </param> /// <returns>The string contains the object type string value.</returns> public static string GetObjectTypeOverride(Element element, string originalValue) { string objectTypeOverride = "IfcObjectType"; string overrideValue = GetOverrideStringValue(element, objectTypeOverride, originalValue); // For backward compatibility where the old parameter name may still be use (ObjectTypeOverride), handle it also if the above returns nothing if (string.IsNullOrEmpty(overrideValue) || (!string.IsNullOrEmpty(overrideValue) && overrideValue.Equals(originalValue))) { overrideValue = GetOverrideStringValue(element, "ObjectTypeOverride", originalValue); } // The following is a special treatment for ObjectType. If IfcObjectType is not set, or carrying the original value, // check the existence of IfcObjectType[Type] parameter for the ElementType or the FamilySymbol. If it is set, the // ObjectType attribute will be overridden by that value, allowing ObjectType is set according to the Type setting // such as IfcExportType="USERDEFINED" set in the Type which necessitates ObjectType in the instance to be set to // the appropriate value if (string.IsNullOrEmpty(overrideValue) || (!string.IsNullOrEmpty(overrideValue) && overrideValue.Equals(originalValue))) { Element typeOrSymbol = element.Document.GetElement(element.GetTypeId()) as ElementType; ; if (typeOrSymbol == null) { FamilyInstance famInst = element as FamilyInstance; if (famInst != null) typeOrSymbol = famInst.Symbol; } if (typeOrSymbol != null) { objectTypeOverride = "IfcObjectType[Type]"; overrideValue = GetOverrideStringValue(typeOrSymbol, objectTypeOverride, originalValue); } } //GetOverrideStringValue will return the override value from the parameter specified, otherwise it will return the originalValue return overrideValue; } /// <summary> /// Get ObjectType override /// </summary> /// <param name="handle">the object Handle</param> /// <param name="element">the element</param> /// <param name="originalValue">the original value</param> /// <returns>the override value or the original</returns> public static string GetObjectTypeOverride(IFCAnyHandle handle, Element element, string originalValue) { List<Exporter.PropertySet.AttributeEntry> entries = ExporterCacheManager.AttributeCache.GetEntry(handle, Exporter.PropertySet.PropertyType.Label, "ObjectType"); if (entries != null) { foreach (Exporter.PropertySet.AttributeEntry entry in entries) { string result = entry.AsString(element); if (result != null) return result; } } return GetObjectTypeOverride(element, originalValue); } /// <summary> /// Gets Tag override from element. /// </summary> /// <param name="element"> /// The element. /// </param> /// <returns>The string contains the object type string value.</returns> public static string GetTagOverride(Element element) { string originalValue = NamingUtil.CreateIFCElementId(element); string nameOverride = "IfcTag"; string overrideValue = GetOverrideStringValue(element, nameOverride, originalValue); if (string.IsNullOrEmpty(overrideValue) || (!string.IsNullOrEmpty(overrideValue) && overrideValue.Equals(originalValue))) { overrideValue = GetOverrideStringValue(element, "TagOverride", originalValue); } if (element is ElementType || element is FamilySymbol) { if (string.IsNullOrEmpty(overrideValue) || (!string.IsNullOrEmpty(overrideValue) && overrideValue.Equals(originalValue))) { nameOverride = "IfcTag[Type]"; overrideValue = GetOverrideStringValue(element, nameOverride, originalValue); } } return overrideValue; } /// <summary> /// Get ElementType attribute override /// </summary> /// <param name="element">the element (should be the Type)</param> /// <param name="originalValue">the original value</param> /// <returns>the string that contains the ElementType attribute value</returns> public static string GetElementTypeOverride(Element element, string originalValue) { if (element == null) return null; string nameOverride = "IfcElementType"; string overrideValue = GetOverrideStringValue(element, nameOverride, originalValue); if (element is ElementType || element is FamilySymbol) { if (string.IsNullOrEmpty(overrideValue) || (!string.IsNullOrEmpty(overrideValue) && overrideValue.Equals(originalValue))) { nameOverride = "IfcElementType[Type]"; overrideValue = GetOverrideStringValue(element, nameOverride, originalValue); } } return overrideValue; } /// <summary> /// Generates the IFC name for the current element. /// </summary> /// <param name="element">The element.</param> /// <returns> The string containing the name.</returns> static private string GetIFCBaseName(Element element) { if (element == null) return ""; bool isType = (element is ElementType); string elementName = element.Name; if (elementName == "???") elementName = ""; string familyName = ""; ElementType elementType = (isType ? element : element.Document.GetElement(element.GetTypeId())) as ElementType; if (elementType != null) { familyName = elementType.FamilyName; if (familyName == "???") familyName = ""; } string fullName = familyName; if (elementName != "") { // if it is a type and the name is set and the option is selected, use the name only if (isType && ExporterCacheManager.ExportOptionsCache.NamingOptions.UseTypeNameOnlyForIfcType) fullName = elementName; else { if (fullName != "") fullName = fullName + ":" + elementName; else fullName = elementName; } } if (isType) return fullName; if (fullName != "") return fullName + ":" + CreateIFCElementId(element); return CreateIFCElementId(element); } /// <summary> /// Generates the IFC name based on the Revit display name. /// </summary> /// <param name="element">The element.</param> /// <returns> The string containing the name.</returns> static private string GetRevitDisplayName(Element element) { if (element == null) return string.Empty; string fullName = CategoryUtil.GetCategoryName(element); string typeName = element.Name; string familyName = string.Empty; ElementType elementType = (element is ElementType) ? (element as ElementType) : element.Document.GetElement(element.GetTypeId()) as ElementType; if (elementType != null) familyName = elementType.FamilyName; if (!string.IsNullOrEmpty(familyName)) { if (!string.IsNullOrEmpty(fullName)) fullName = fullName + " : " + familyName; else fullName = familyName; } if (!string.IsNullOrEmpty(typeName)) { if (!string.IsNullOrEmpty(fullName)) fullName = fullName + " : " + typeName; else fullName = typeName; } return fullName; } /// <summary> /// Special name format as required by COBie v2.4 /// </summary> /// <param name="element">the Element</param> /// <returns>the name</returns> static private string GetCOBieDesiredName(Element element) { if (element == null) return ""; Parameter instanceMarkParam = element.get_Parameter(BuiltInParameter.ALL_MODEL_MARK); // if NULL, try DOOR_NUMBER which also has the same parameter name "Mark" if (instanceMarkParam == null) instanceMarkParam = element.get_Parameter(BuiltInParameter.DOOR_NUMBER); ElementType elementType = null; if (element is ElementType) elementType = element as ElementType; else elementType = element.Document.GetElement(element.GetTypeId()) as ElementType; Parameter typeMarkParam = null; if (elementType != null) { typeMarkParam = elementType.get_Parameter(BuiltInParameter.ALL_MODEL_TYPE_MARK); // if NULL, try WINDOW_TYPE_ID which also has the same parameter name "Mark" if (typeMarkParam == null) typeMarkParam = elementType.get_Parameter(BuiltInParameter.WINDOW_TYPE_ID); } string typeMarkValue = typeMarkParam?.AsString(); string instanceMarkValue = instanceMarkParam?.AsString(); string fullName = null; if (string.IsNullOrWhiteSpace(typeMarkValue)) fullName = string.IsNullOrWhiteSpace(instanceMarkValue) ? "" : instanceMarkValue; else if (string.IsNullOrWhiteSpace(instanceMarkValue)) fullName = typeMarkValue; else fullName = typeMarkValue + "-" + instanceMarkValue; Tuple<ElementId, int> tupNameDupl; if (!m_NameIncrNumberDict.TryGetValue(fullName, out tupNameDupl)) m_NameIncrNumberDict.Add(fullName, new Tuple<ElementId, int>(element.Id, 1)); else { // Found the same name used before, if not the same ElementId than the previously processed, add an incremental number to name if (!element.Id.Equals(tupNameDupl.Item1)) { Tuple<ElementId, int> tup = new Tuple<ElementId, int>(element.Id, tupNameDupl.Item2 + 1); m_NameIncrNumberDict[fullName] = tup; fullName = fullName + " (" + tup.Item2.ToString() + ")"; } } return fullName; } /// <summary> /// Get the IFC name of an element. /// </summary> /// <param name="element">The element.</param> /// <returns>The name.</returns> static public string GetIFCName(Element element) { if (element == null) return ""; if (ExporterCacheManager.ExportOptionsCache.ExportAs2x3COBIE24DesignDeliverable) return GetCOBieDesiredName(element); if (ExporterCacheManager.ExportOptionsCache.NamingOptions.UseVisibleRevitNameAsEntityName) return GetRevitDisplayName(element); string baseName = GetIFCBaseName(element); return GetNameOverride(element, baseName); } /// <summary> /// Creates an IFC name for an element, with a suffix. /// </summary> /// <param name="element">The element./// </param> /// <param name="index">/// The index of the name. If it is larger than 0, it is appended to the name./// </param> /// <returns>/// The string contains the name string value./// </returns> public static string GetIFCNamePlusIndex(Element element, int index) { string elementName = GetIFCName(element); if (index >= 0) { elementName += ":"; elementName += index.ToString(); } return elementName; } public static string GetFamilyAndTypeName(Element element) { if (element == null) return null; string familyName = null; string typeName = null; ElementType elementType = element.Document.GetElement(element.GetTypeId()) as ElementType; if (elementType != null) { typeName = elementType.Name; if (typeName == "???") typeName = ""; familyName = elementType.FamilyName; if (familyName == "???") familyName = ""; } // set famSym name. if (!string.IsNullOrEmpty(familyName)) { if (!string.IsNullOrEmpty(typeName)) return familyName + ":" + typeName; return familyName; } return typeName; } /// <summary> /// Creates an IFC object name from export state. /// </summary> /// <remarks>It is combined with family name and element type id.</remarks> /// <param name="exporterIFC">The ExporterIFC object.</param> /// <param name="element">The element.</param> /// <returns>The name string value, or null if there is none.</returns> public static string CreateIFCObjectName(ExporterIFC exporterIFC, Element element) { // This maintains the same behavior as the previous export. if (element is FamilyInstance) { FamilySymbol familySymbol = (element as FamilyInstance).Symbol; if (familySymbol != null) return familySymbol.Name; } ElementId typeId = element != null ? element.GetTypeId() : ElementId.InvalidElementId; string objectName = GetFamilyAndTypeName(element); if (typeId != ElementId.InvalidElementId) { if (objectName == "") return typeId.ToString(); else return (objectName + ":" + typeId.ToString()); } return null; } /// <summary> /// Creates an IFC element id string from element id. /// </summary> /// <param name="element"> /// The element. /// </param> /// <returns> /// The string contains the name string value. /// </returns> public static string CreateIFCElementId(Element element) { if (element == null) return "NULL"; string elemIdString = element.Id.ToString(); return elemIdString; } /// <summary> /// Parses the name string and gets the parts separately. /// </summary> /// <param name="name"> /// The name. /// </param> /// <param name="lastName"> /// The output last name. /// </param> /// <param name="firstName"> /// The output first name. /// </param> /// <param name="middleNames"> /// The output middle names. /// </param> /// <param name="prefixTitles"> /// The output prefix titles. /// </param> /// <param name="suffixTitles"> /// The output suffix titles. /// </param> public static void ParseName(string name, out string lastName, out string firstName, out List<string> middleNames, out List<string> prefixTitles, out List<string> suffixTitles) { lastName = string.Empty; firstName = string.Empty; middleNames = null; prefixTitles = null; suffixTitles = null; if (String.IsNullOrEmpty(name)) return; string currName = name; List<string> names = new List<string>(); int noEndlessLoop = 0; int index = 0; bool foundComma = false; do { int currIndex = index; // index might get reset by comma. currName = currName.TrimStart(' '); if (String.IsNullOrEmpty(currName)) break; int comma = foundComma ? currName.Length : currName.IndexOf(','); if (comma == -1) comma = currName.Length; int space = currName.IndexOf(' '); if (space == -1) space = currName.Length; // treat comma as space, mark found. if (comma < space) { foundComma = true; index = 0; // start inserting at the beginning again. space = comma; } if (space == currName.Length) { names.Add(currName); break; } else if (space == 0) { if (comma == 0) continue; else break; // shouldn't happen } names.Insert(currIndex, currName.Substring(0, space)); index++; currName = currName.Substring(space + 1); noEndlessLoop++; } while (noEndlessLoop < 100); // parse names. // assuming anything ending in a dot is a prefix. int sz = names.Count; for (index = 0; index < sz; index++) { if (names[index].LastIndexOf('.') == names[index].Length - 1) { if (prefixTitles == null) prefixTitles = new List<string>(); prefixTitles.Add(names[index]); } else break; } if (index < sz) { firstName = names[index++]; } // suffixes, if any. Note this misses "III", "IV", etc., but this is not that important! int lastIndex; for (lastIndex = sz - 1; lastIndex >= index; lastIndex--) { if (names[lastIndex].LastIndexOf('.') == names[lastIndex].Length - 1) { if (suffixTitles == null) suffixTitles = new List<string>(); suffixTitles.Insert(0, names[lastIndex]); } else break; } if (lastIndex >= index) { lastName = names[lastIndex--]; } // rest are middle names. for (; index <= lastIndex; index++) { if (middleNames == null) middleNames = new List<string>(); middleNames.Add(names[index]); } } /// <summary> /// Get an IFC Profile Name from the FamilySymbol (the type) name, or from the override parameter of the type "IfcProfileName[Type]" /// </summary> /// <param name="element">the element (Instance/FamilyInstance or Type/FamilySymbol)</param> /// <returns>the profile name</returns> public static string GetProfileName(Element element, string originalName = null) { FamilySymbol fSymb; if (element is FamilyInstance) fSymb = (element as FamilyInstance).Symbol; else fSymb = element as FamilySymbol; if (fSymb == null) return originalName; // Get a profile name. It is by default set to the type (familySymbol) name, but can be overridden by IfcProfileName[Type] shared parameter string profileName = fSymb.Name; string profile; ParameterUtil.GetStringValueFromElement(fSymb, "IfcProfileName[Type]", out profile); if (!string.IsNullOrEmpty(profile)) profileName = profile; if (string.IsNullOrEmpty(profileName)) return originalName; return profileName; } /// <summary> /// Get unique name by incrementing a number as suffix. It is looking for "name + (number)". It works like this: /// - if the entry is "name" without number, it will return "name (2)" /// - if the entry is "name (number)", it will return "name (number + 1)" /// Only the last (number) will be evaluated in the case that there are multiple (number) in the string /// </summary> /// <param name="nameToCheck">the name to check</param> /// <returns>the name with incremented number appended</returns> public static string GetUniqueNameByIncrement(string nameToCheck) { string uniqueName = nameToCheck; string baseName = null; string suffix = null; string prefix = null; int number = 1; // Looking for pattern "... name (number)". If the last part is number in bracket, this number will be incremented Regex rx = new Regex(@"(?<basename>\w+)\s*[(]\s*(?<number>\d+)\s*[)]", RegexOptions.Compiled | RegexOptions.IgnoreCase); MatchCollection matches = rx.Matches(uniqueName); // If found matches, increment the number and return if (matches.Count > 0) { Match lastMatch = matches[matches.Count - 1]; GroupCollection groups = lastMatch.Groups; baseName = groups["basename"].Value; number = int.Parse(groups["number"].Value); int index = lastMatch.Index; int len = lastMatch.Length; if (index > 1) { prefix = uniqueName.Substring(0, index - 1).Trim(); if (!string.IsNullOrEmpty(prefix)) baseName = prefix + " " + baseName; } // It ends with word without number, it will be treated the same for the name without number if (index + len < uniqueName.Length) { suffix = uniqueName.Substring(index + len).Trim(); if (!string.IsNullOrEmpty(suffix)) uniqueName = uniqueName + " (" + (++number).ToString() + ")"; else { number = int.Parse(groups["number"].Value); uniqueName = baseName + " (" + (++number).ToString() + ")"; } } else { number = int.Parse(groups["number"].Value); uniqueName = baseName + " (" + (++number).ToString() + ")"; } } else { // If no match, return the name plus the incremented number (starting from 2) uniqueName = uniqueName + " (" + (++number).ToString() + ")"; } return uniqueName; } /// <summary> /// Check unique name within the given Set. If the name is unique add the name and return it, /// If it is not unique, it will call GetUniqueNameByIncrement() and check the new name for its existence in the Set, until it finds the unique name /// </summary> /// <param name="inputName">the input name</param> /// <param name="theNameSet">the Set where the name should be search</param> /// <returns>the unique name that is also added into the Set</returns> public static string GetUniqueNameWithinSet(string inputName, HashSet<string> theNameSet) { string uniqueName = inputName; if (!theNameSet.Contains(uniqueName)) { theNameSet.Add(uniqueName); return uniqueName; } while (true) { uniqueName = GetUniqueNameByIncrement(uniqueName); if (!theNameSet.Contains(uniqueName)) { theNameSet.Add(uniqueName); break; } } return uniqueName; } } }
// SPDX-License-Identifier: MIT pragma solidity >=0.5.0 <0.9.0; contract DeathOracle { uint256 numCertificates; mapping(address => DeathCertificate) users; struct DeathCertificate { uint256 id; address requester; string url; bool verified; } function isVerifiedOracle(address oracle) public pure returns (bool) { /* Simulated Verification of Oracle Service */ require(oracle != address(0)); return true; } function isDead(address deceased) public view returns (bool) { return users[deceased].verified; } function submit(address deceased, string memory url) public { DeathCertificate storage dc = users[deceased]; dc.id = numCertificates++; dc.requester = msg.sender; dc.url = url; dc.verified = false; } function verify(address deceased) public returns (bool) { require(isVerifiedOracle(msg.sender)); /* Simulated Verification of Death Certificate */ DeathCertificate storage dc = users[deceased]; dc.verified = true; return true; } }
import 'dart:io'; import 'package:android_alarm_manager_plus/android_alarm_manager_plus.dart'; import 'package:flutter/material.dart'; import 'package:flutter_local_notifications/flutter_local_notifications.dart'; import 'package:provider/provider.dart'; import 'package:restaurant_v2/common/navigation.dart'; import 'package:restaurant_v2/common/text_theme.dart'; import 'package:restaurant_v2/data/preferences/preferences_helper.dart'; import 'package:restaurant_v2/data/services/api_services.dart'; import 'package:restaurant_v2/main_page.dart'; import 'package:restaurant_v2/provider/preferences_provider.dart'; import 'package:restaurant_v2/provider/restaurant_provider.dart'; import 'package:restaurant_v2/provider/scheduling_provider.dart'; import 'package:restaurant_v2/provider/search_restaurant_provider.dart'; import 'package:restaurant_v2/ui/detail_screen.dart'; import 'package:restaurant_v2/ui/home_screen.dart'; import 'package:restaurant_v2/ui/restaurant_screen.dart'; import 'package:restaurant_v2/ui/setting_screen.dart'; import 'package:restaurant_v2/ui/splash_screen.dart'; import 'package:restaurant_v2/utils/background_service.dart'; import 'package:restaurant_v2/utils/notification_helper.dart'; import 'package:shared_preferences/shared_preferences.dart'; final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin(); Future<void> main() async { WidgetsFlutterBinding.ensureInitialized(); final NotificationHelper notificationHelper = NotificationHelper(); final BackgroundService service = BackgroundService(); service.initializeIsolate(); if (Platform.isAndroid) { await AndroidAlarmManager.initialize(); } await notificationHelper.initNotifications(flutterLocalNotificationsPlugin); runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return MultiProvider( providers: [ ChangeNotifierProvider<RestaurantProvider>( create: (_) => RestaurantProvider(apiService: ApiService()), child: const HomeScreen(), ), ChangeNotifierProvider<SearchRestaurantProvider>( create: (_) => SearchRestaurantProvider(apiService: ApiService()), child: const RestaurantScreen()), ChangeNotifierProvider<SchedulingProvider>( create: (_) => SchedulingProvider(), child: const SettingScreen()), ChangeNotifierProvider( create: (context) => PreferencesProvider( preferencesHelper: PreferencesHelper( sharedPreferences: SharedPreferences.getInstance())), child: const SettingScreen(), ) ], child: MaterialApp( debugShowCheckedModeBanner: false, title: 'Restauran App', theme: ThemeData( textTheme: myTextTheme, ), navigatorKey: navigatorKey, initialRoute: SplashScreen.routeName, routes: { SplashScreen.routeName: (context) => const SplashScreen(), MainPage.routeName: (context) => const MainPage(), DetailScreen.routeName: (context) => DetailScreen( id: ModalRoute.of(context)?.settings.arguments as String) }, ), ); } }
<!DOCTYPE HTML> <html xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.w3.org/1999/xhtml"> <head> <title th:text="${title}"/> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous"> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-OERcA2EqjJCMA+/3y+gxIOqMEjwtxJY7qPCqsdltbNJuaOe923+mo//f6V8Qbsw3" crossorigin="anonymous"></script> </head> <body> <header class="d-flex justify-content-center py-3"> <ul class="nav nav-pills"> <li class="nav-item"><a href="/" class="nav-link">Главная</a></li> <li class="nav-item"><a href="/about" class="nav-link">О проекте</a></li> <li sec:authorize="isAuthenticated()" class="nav-item"><a href="/trips/my" class="nav-link active" aria-current="page">Мои путешествия</a></li> <li sec:authorize="hasRole('ADMIN')" class="nav-item"><a href="/admin" class="nav-link">Администратор</a></li> </ul> <div class="col-md-3 text-end"> <button sec:authorize="!isAuthenticated()" type="button" class="btn btn-outline-primary me-2" onClick="window.location.href='/login'">Войти</button> <button sec:authorize="!isAuthenticated()" type="button" class="btn btn-primary" onClick="window.location.href='/registration'">Регистрация</button> <button sec:authorize="isAuthenticated()" type="button" class="btn btn-outline-primary me-2" onClick="window.location.href='/logout'">Выйти</button> </div> </header> <div class="col-md-8 " style="margin-left:40px; margin-right:100px;"> <article class="blog-post"> <h2 class="blog-post-title mb-1" th:text ="${trip.place}"></h2> <p class="blog-post-meta">Автор: <a th:text="${authorName}" href="/users/"></a></p> <p class="blog-post-meta">Просмотров: <span th:text ="${trip.views}"></span></p> <p class="blog-post-meta">Дата поездки: <span th:text ="${trip.date}"></span></p> <p class="blog-post-meta">Длительность поездки: <span th:text ="${trip.duration}"></span></p> <p th:text ="${trip.story}"></p> </article> <nav class="blog-pagination" aria-label="Pagination"> <a sec:authorize="isAuthenticated()" class="btn btn-outline-primary rounded-pill" th:href="'/trips/my/'+ ${trip.id} + '/edit'">Редактировать</a> <br><br> <!-- Кнопка-триггер модального окна --> <button type="button" class="btn btn-outline-secondary rounded-pill" data-bs-toggle="modal" data-bs-target="#exampleModal"> Удалить </button> </nav> </div> <!-- Модальное окно --> <div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Подтверждение удаления</h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Закрыть"></button> </div> <div class="modal-body"> Вы действительно хотите безвозвратно удалить выбранную запись? </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Отмена</button> <form sec:authorize="isAuthenticated()" th:action="'/trips/my/' + ${trip.id} + '/remove'" method="post"> <button class="btn btn-primary" type="submit">Удалить</button> </form> </div> </div> </div> </div> <footer th:insert="blocks/footer::footer"></footer> </body> </html>
import { motion } from 'framer-motion' import { useState } from 'react' import { FiAlertCircle } from 'react-icons/fi' const Input = (props: any) => { const [focus, setFocus] = useState<boolean>(false) return ( <div className="flex flex-col"> <motion.label htmlFor={props.label} className="flex items-center gap-x-3 px-4" animate={focus ? 'active' : ''} variants={{active: { translateY: -10 }}} > {props.icon && props.icon} <motion.span animate={focus ? 'active' : ''} variants={{active: { color: '#691DBC', scale: 0.8 }}} > {props.label} </motion.span> </motion.label> <input {...props.register} type={props.type || 'text'} id={props.label} className="px-6 border-b w-full outline-none transition-all duration-500 focus:border-b-primary" onFocus={() => setFocus(true)} onBlur={(e) => { props.register?.onBlur(e) setFocus(false) }} /> <div className="mt-1"> {props.error?.message ? ( <span className="flex items-center gap-x-2 text-red-500 text-sm"> <FiAlertCircle /> <span>{props.error?.message}</span> </span> ) : ( <div className="h-5"></div> )} </div> </div> ) } export default Input
package main import ( "encoding/json" "errors" "fmt" "io/ioutil" "log" "os" "os/exec" "os/user" "strings" "go.i3wm.org/i3/v4" ) var i3Tree i3.Tree var jsonWhitelistPath string type JsonWhitelist struct { Whitelist []string `json:"whitelist"` Blacklist []string `json:"blacklist"` } func (jw *JsonWhitelist) checkWhitelist(mark string) bool { for _, m := range jw.Whitelist { if m == mark { return true } } return false } func readJsonWhitelist(filePath string) JsonWhitelist { file, err := os.Open(filePath) if err != nil { //fmt.Println("Error opening file:", err) //return } defer file.Close() content, err := ioutil.ReadAll(file) if err != nil { //fmt.Println("Error reading file:", err) //return } var jsonWhitelist JsonWhitelist err = json.Unmarshal(content, &jsonWhitelist) if err != nil { //fmt.Println("Error unmarshaling JSON:", err) //return } return jsonWhitelist } func fileExists(filename string) bool { _, err := os.Stat(filename) return !os.IsNotExist(err) } func getI3Tree() i3.Tree { tree, err := i3.GetTree() if err != nil { log.Fatal(err) } return tree } func runi3Input() (string, error) { output, err := exec.Command("bash", "-c", "i3-input -l 1 -P \"Are you sure you want to close this window y/n?: \" | grep -oP \"output = \\K.*\" | tr -d '\n'").Output() if err != nil { return "", err } return string(output), nil } func getFocusedNode() *i3.Node { node := i3Tree.Root.FindFocused(func(n *i3.Node) bool { return n.Focused == true }) if node == nil { log.Fatal(errors.New("Could not find focused node")) } return node } func getNodeMark(node *i3.Node) string { if len(node.Marks) == 0 { return "" } return node.Marks[0] } func resolveJsonAbsolutePath(filename string) string { usr, err := user.Current() if err != nil { log.Fatal(err) } return strings.Replace(fmt.Sprintf("~/%s", filename), "~", usr.HomeDir, 1) } func init() { i3Tree = getI3Tree() jsonWhitelistPath = resolveJsonAbsolutePath(".KillContainerConfig.json") } func main() { var jsonWhitelist JsonWhitelist if fileExists(jsonWhitelistPath) == true { jsonWhitelist = readJsonWhitelist(jsonWhitelistPath) } focusedNode := getFocusedNode() focusedContainerMark := getNodeMark(focusedNode) if focusedContainerMark == "" || jsonWhitelist.checkWhitelist(focusedContainerMark) { i3.RunCommand("kill") os.Exit(0) } userConfirmation, err := runi3Input() if err != nil { log.Fatal(err) } if userConfirmation == "y" { i3.RunCommand("kill") } }
//cryptocurrenciesList import {component} from 'react' import CryptocurrencyItem from '../CryptocurrencyItem' import './index.css' class CryptocurrenciesList extends component { renderCryptoCurrenciesHeader = () => ( <div className="crypto-header"> <p className="para">Coin Type</p> <div className="values-container"> <p className="para">USD</p> <p className="para">EURO</p> </div> </div> ) renderCryptoCurrenciesView = () => { const {cryptoCurrenciesData} = this.props return ( <div className="cryptoCurrenciesView"> {this.renderCryptoCurrenciesHeader()} <ul> {cryptoCurrenciesData.map(eachItem => ( <CryptocurrencyItem key={eachItem.id} cryptoCurrencyDetails={eachItem} /> ))} </ul> </div> ) } render() { return ( <div className="list-container"> <h1 className="heading">Cryptocurrency Traker</h1> <img src="https://assets.ccbp.in/frontend/react-js/cryptocurrency-bg.png" alt="cryptocurrency" className="image" /> {this.renderCryptoCurrenciesView()} </div> ) } } export default CryptocurrenciesList //cryptocurrencyItem import './index.css' const CryptocurrencyItem = props => { const {cryptocurrencyDetails} = props const { currencyName, usdValues, euroValue, currencyLogo, } = cryptocurrencyDetails return ( <li className="cryptoCurrency-item"> <div className="logo-container"> <img src={currencyLogo} alt={currencyName} className="logo" /> <p className="para">{currencyName}</p> </div> <div className="values-container"> <p className="para">{usdValues}</p> <p className="para">{euroValue}</p> </div> </li> ) } export default CryptocurrencyItem //cryptocurrencyTracker import {Component} from 'react' import Loader from 'react-loader-spinner' import 'react-loader-spinner/dist/loader/css/react-spinner-loader.css' import CryptocurrenciesList from '../CryptocurrenciesList' import './index.css' class CryptocurrencyTracker extends Component { state = {cryptoCurrenciesData: [], isLoading: true} componentDidMount() { this.getCryptoData() } getCryptoData = async () => { const response = await fetch( 'https://apis.ccbp.in/crypto-currency-converter', ) const data = await response.json() const updatedData = data.map(eachItem => ({ currencyName: eachItem.currency_name, usdValue: eachItem.usd_value, euroValue: eachItem.euro_value, id: eachItem.id, currencyLogo: eachItem.currency_logo, })) this.setState({cryptoCurrenciesData: updatedData, isLoading: false}) } render() { const {cryptoCurrenciesData, isLoading} = this.state return ( <div className="bg-container" data-testid="loader"> {isLoading ? ( <Loader type="Rings" color="#ffffff" height={80} width={80} /> ) : ( <CryptocurrenciesList cryptoCurrenciesData={cryptoCurrenciesData} /> )} </div> ) } } export default CryptocurrencyTracker //App.js import CryptocurrencyTracker from './components/CryptocurrencyTracker' import './App.css' const App = () => <CryptocurrencyTracker /> export default App
'use strict'; const { Model } = require('sequelize'); module.exports = (sequelize, DataTypes) => { class Restourant extends Model { /** * Helper method for defining associations. * This method is not a part of Sequelize lifecycle. * The `models/index` file will call this method automatically. */ static associate(models) { // define association here Restourant.hasOne(models.Address, { foreignKey :'restourantId', as: 'addresses' }); Restourant.hasMany(models.Review ,{ foreignKey : 'restourantId', as:'reviews' }) } } Restourant.init({ id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true }, name: { type: DataTypes.STRING, unique: true, allowNull: false }, description: { type: DataTypes.STRING, allowNull: false }, rating: { type: DataTypes.DECIMAL, allowNull: false }, telephone: { type: DataTypes.STRING, allowNull: false }, hours: { type: DataTypes.STRING, allowNull: false } }, { sequelize, modelName: 'Restourant', }); return Restourant; };
import React, { PureComponent } from 'react'; import PropTypes from 'prop-types'; import InputDateCalendar from '../Input/InputDateCalendar'; export default class InputDateCalendarExample extends PureComponent { static propTypes = { value: PropTypes.string, }; static defaultProps = { value: null, }; constructor(props) { super(props); const { value } = this.props; this.state = { value }; } onChange = ({ value }) => { this.setState({ value }); }; render() { const { ...rest } = this.props; const { value } = this.state; return <InputDateCalendar {...rest} value={value} onChange={this.onChange} />; } }
import Avatar from '@mui/material/Avatar'; import Button from '@mui/material/Button'; import CssBaseline from '@mui/material/CssBaseline'; import TextField from '@mui/material/TextField'; import Link from '@mui/material/Link'; import Grid from '@mui/material/Grid'; import Box from '@mui/material/Box'; import LockOutlinedIcon from '@mui/icons-material/LockOutlined'; import Typography from '@mui/material/Typography'; import Container from '@mui/material/Container'; import {useLogin} from '@hooks'; import {Copyright} from '@components'; import {useDispatch, useSelector} from 'react-redux'; import {RootState, setUsername} from '@redux'; export default function SelfLogin() { const {password, setPassword, handleSubmit} = useLogin(); const username = useSelector((state: RootState) => state.username.username); const dispatch = useDispatch(); return ( <Container component="main" maxWidth="xs"> <CssBaseline/> <Box sx={{ marginTop: 8, display: 'flex', flexDirection: 'column', alignItems: 'center', }} > <Avatar sx={{m: 1, bgcolor: 'secondary.main'}}> <LockOutlinedIcon/> </Avatar> <Typography component="h1" variant="h5"> 로그인 </Typography> <Box component="form" onSubmit={handleSubmit} noValidate sx={{mt: 1}}> <TextField margin="normal" required fullWidth id="username" label="학번" name="username" autoComplete="학번" autoFocus value={username} onChange={e => dispatch(setUsername(e.target.value))} /> <TextField margin="normal" required fullWidth name="password" label="비밀번호" type="password" id="password" autoComplete="current-password" value={password} onChange={e => setPassword(e.target.value)} /> {/*<FormControlLabel*/} {/* control={<Checkbox value="remember" color="primary" />}*/} {/* label="Remember me"*/} {/*/>*/} <Button type="submit" fullWidth variant="contained" sx={{mt: 3, mb: 2}} > 로그인 </Button> <Grid container> <Grid item xs> <Link href="#" variant="body2"> Forgot password? </Link> </Grid> {/*<Grid item>*/} {/* <Link href="#" variant="body2">*/} {/* {"Don't have an account? Sign Up"}*/} {/* </Link>*/} {/*</Grid>*/} </Grid> </Box> </Box> <Copyright sx={{mt: 8, mb: 4}}/> </Container> ); }
import React from 'react'; import Panel from './panel_container'; import Constants from '../../constants/constants'; import ProfileTweets from './profile_tweets_container'; import Follow from './follow_container'; import Likes from './likes_container'; import Trending from '../trending/trending_container'; class Profile extends React.Component { constructor(props) { super(props); this.props.resetTweets(); const username = this.props.params.username; this.props.getProfileUser(username); } mainDisplay(){ if (this.hasFetchedProfileUser()){ const display = this.props.params.display; switch(this.props.params.display){ case undefined: case Constants.WITH_REPLIES: { return <ProfileTweets params={this.props.params}/> break;} case Constants.FOLLOWING: case Constants.FOLLOWERS:{ return <Follow followType={display}/>; break;} case Constants.LIKES: { return <Likes params={this.props.params} profileUser={this.props.profileUser}/>; break;} default: { <span>Invalid Section</span>} } } } componentDidUpdate(prevProps){ if (prevProps.params.username != this.props.params.username){ this.props.getProfileUser(this.props.params.username); } } hasFetchedProfileUser(){ return (this.props.profileUser.username !== undefined) } username(){ const username = this.props.profileUser.username; return username ? <h6 id="profile-username">{`@${username}`}</h6> : <h6>invalid user</h6>; } fullNameOfUser(user){ let names = [] if (user.firstName) {names.push(user.firstName)}; if (user.lastName) {names.push(user.lastName)}; return names.join(" "); } fullName(){ const fullName = this.fullNameOfUser.call(this, this.props.profileUser); return (<h3 id="profile-fullname">{fullName}</h3>); } tweetToButtonClicked(username, fullNameTo){ if (this.props.currUser){ this.props.openTweetingInterface(`@${username}`, fullNameTo); } else { this.props.openSessionPopup(); } } tweetToButton(){ const username = this.props.profileUser.username; if (!this.props.currUser || this.props.currUser.username !== username){ const fullNameTo = this.fullNameOfUser(this.props.profileUser); return username ? <button id="tweet-to-btn" onClick={this.tweetToButtonClicked.bind(this, username, fullNameTo)}>Tweet to {fullNameTo}</button> : undefined; } } getImageFromUser(type){ let file = document.getElementById(type === Constants.PROFILE_IMG ? "profile-img-upload-btn" : "cover-img-upload-btn").files[0]; let reader = new FileReader(); reader.onloadend = () => { const result = reader.result; if (this.isImage(result)){ if (type === Constants.PROFILE_IMG){ let profileImg = document.getElementsByClassName("user-profile-img")[0]; console.log(`result is ${result}`); this.props.uploadProfileImg(result); } else { console.log(`result is ${result}`); this.props.uploadCoverImg(result); } } else { alert("Must upload image (jpeg or png)"); } } if(file){ reader.readAsDataURL(file); }else{ } } isImage(result){ const colonIndex = result.indexOf(':'); const afterIndex = result.substr(colonIndex + 1, 5); return (afterIndex === "image"); } profileImgUpload(){ const currUser = this.props.currUser; if (currUser && this.props.profileUser.username === currUser.username){ return ( <div id="profile-img-upload-container"> <input id="profile-img-upload-btn" name="profile-img-upload-btn" className="inputfile" type="file" onChange={this.getImageFromUser.bind(this, Constants.PROFILE_IMG)}/> <label className="img-upload-label" htmlFor="profile-img-upload-btn"><i className="fa fa-camera photo-btn"></i></label> </div> ) } } coverImgUpload(){ const currUser = this.props.currUser; if (currUser && this.props.profileUser.username === currUser.username){ return ( <div id="cover-img-upload-container"> <input id="cover-img-upload-btn" name="cover-img-upload-btn" className="inputfile" type="file" onChange={this.getImageFromUser.bind(this, Constants.COVER_IMG)}/> <label className="img-upload-label" htmlFor="cover-img-upload-btn"><i className="fa fa-camera photo-btn"></i></label> </div> ) } } render(){ const user = this.props.profileUser; const profileImg = user.largeProfileImg; const coverImg = user.largeCoverImg; return ( <div> {this.profileImgUpload()} {this.coverImgUpload()} <div className="top"> <div id="cover-img-container"> <img className="cover-img" src={coverImg}/> </div> <Panel params={this.props.params}/> </div> <div id="user-profile-img-container"> <img className="user-profile-img" src={profileImg}/> </div> <div id="user-profile-info"> {this.fullName()} {this.username()} {this.tweetToButton()} <div className="trending-container-on-profile"> <Trending/> </div> </div> {this.mainDisplay()} </div> ) } }; module.exports = Profile;
--- title: EncodedVideoChunk.timestamp slug: Web/API/EncodedVideoChunk/timestamp tags: - API - Property - Reference - timestamp - EncodedVideoChunk browser-compat: api.EncodedVideoChunk.timestamp --- {{DefaultAPISidebar("WebCodecs API")}} The **`timestamp`** read-only property of the {{domxref("EncodedVideoChunk")}} interface returns an integer indicating the timestamp of the video in microseconds. ### Value An integer. ## Examples In the following example the `timestamp` is printed to the console. ```js const init = { type: 'key', data: videoBuffer, timestamp: 23000000, duration: 2000000 }; chunk = EncodedVideoChunk(init); console.log(chunk.timestamp); //23000000 ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
import { PieChart } from "@mui/x-charts"; import "./styles.css"; import BaseText from "../text"; import { useEffect, useState } from "react"; import { classNames } from "../../utils/common"; import BaseCard from "../baseCard"; import { BaseInputSelect } from "../input/BaseInputSelect"; import { useTranslation } from "react-i18next"; import { analyticsApi } from "../../apis/analyticsApi"; type PieChartProps = { className?: string; // for tailwindcss }; export default function BasePieChart(props: PieChartProps) { const { className } = props; const { t } = useTranslation(); const [data, setData] = useState<any[]>([]); const changeStyle = (textElements: any) => { textElements.forEach((textElement: any) => { if (textElement) { const currentTransform = textElement.style.transform; if (!currentTransform.includes("scale")) { textElement.style.cssText = `fill: white !important; transform: ${currentTransform} scale(0.4)`; } } }); }; const getInfoAnalytics = async () => { const params = { property: "properties/244725891", dimensions: [{ name: "deviceCategory" }], metrics: [{ name: "active28DayUsers" }], dateRanges: [{ startDate: "30daysAgo", endDate: "yesterday" }], }; let result = await analyticsApi.getInfo(params); const convertedData = result.data[0].rows.map((item: any) => { const value = parseFloat(item.metricValues[0].value); const totalValue = result.data[0].rows.reduce( (acc: any, curr: any) => acc + parseFloat(curr.metricValues[0].value), 0 ); const percentage = (value / totalValue) * 100; return { name: item.dimensionValues[0].value, value: value, percentage: `${percentage.toFixed(2)}%`, }; }); setData(convertedData); }; useEffect(() => { getInfoAnalytics(); return () => {}; }, []); // useEffect(() => { // setTimeout(() => { // const textElements: any = document.querySelectorAll("#pie-chart text"); // changeStyle(textElements); // }, 400); // }, [data]); function getColorByIndex(index: any) { const colors = [ "bg-rose-900", "bg-purple", "bg-blue-700", "bg-emerald-600", ]; return colors[index]; } return ( <BaseCard className={classNames( "flex flex-col justify-between w-[375px]", className )} > <div className="flex flex-row justify-between"> <BaseText locale size={24} bold> Used by </BaseText> <BaseInputSelect onChange={() => {}} value="Weekly" options={[ { value: "Weekly", label: t("Weekly"), }, { value: "Monthly", label: t("Monthly"), }, { value: "Annually", label: t("Annually"), }, ]} /> </div> <div className="flex flex-col items-center mt-7"> <div id="pie-chart" className="w-[160px] h-[160px] "> <PieChart colors={["#9f1239", "#722ed1", "#1d4ed8", "#059669"]} series={[ { arcLabel: (item) => `${item.percentage}`, data: data, highlightScope: { faded: "global", highlighted: "item" }, faded: { innerRadius: 0, additionalRadius: -2, color: "gray" }, cx: 150, cy: 150, paddingAngle: 0, color: "red", }, ]} /> </div> <div className="flex flex-row mt-10 max-w-[375px]"> <div className="flex flex-row items-start justify-center"> {/* <div className="h-full w-0 border-[0.5px] mx-4"></div> */} {data.map((item, index) => ( <> <div className={classNames( `w-3 h-3 mt-1 rounded-full ${getColorByIndex(index)}` )} /> <div className="flex flex-col pl-2"> <BaseText locale>{item.name}</BaseText> <BaseText size={18} bold> {item.percentage} </BaseText> </div> {/* <div className="h-full w-0 border-[0.5px] mx-4"></div> */} </> ))} </div> </div> </div> </BaseCard> ); }
import {Injectable} from '@angular/core'; import {HttpClient, HttpHeaders} from '@angular/common/http'; import {Client} from '../Models/client'; const URI = 'http://localhost:8080/api/client/'; const httpOptions = { headers: new HttpHeaders({'Content-Type' : 'application/json'}) }; @Injectable({ providedIn: 'root' }) export class ClientService { constructor(private http: HttpClient) { } public readClients() { return this.http.get<Client[]>(URI); } public readClient(id: number) { return this.http.get<Client>(URI + id); } public createClient(client: Client) { const clientDto = { nomClient: client.nomClient, prenomClient: client.prenomClient, telephoneClient: client.telephoneClient, dateNaissanceClient: client.dateNaissanceClient }; return this.http.post(URI, clientDto, httpOptions); } public updateClient(id: number, client: Client) { const clientDto = { nomClient: client.nomClient, prenomClient: client.prenomClient, telephoneClient: client.telephoneClient, dateNaissanceClient: client.dateNaissanceClient }; return this.http.put(URI + id, clientDto, httpOptions); } public deleteClient(id: number) { return this.http.delete(URI + id); } }
// Fill out your copyright notice in the Description page of Project Settings. #include "Entity/Playable/HNSTPlayable.h" #include <ciso646> #include "GameplayEffectTypes.h" #include "Camera/CameraComponent.h" #include "Components/CapsuleComponent.h" #include "Entity/GAS/HNSTAbilitySystemComponent.h" #include "Entity/GAS/HNSTAttributeSet.h" #include "Entity/GAS/HNSTGameplayAbility.h" #include "Game/HNSTPlayerController.h" #include "Game/HNSTPlayerState.h" #include "GameFramework/CharacterMovementComponent.h" #include "GameFramework/SpringArmComponent.h" #include "Kismet/KismetMathLibrary.h" //Camera positioning inputs in case you drastically change the camera void AHNSTPlayable::Turn(float Value) { if(IsAlive()) AddControllerYawInput(Value); } void AHNSTPlayable::LookUp(float Value) { if(IsAlive()) AddControllerPitchInput(Value); } void AHNSTPlayable::LookUpRate(float Value) { if(IsAlive()) AddControllerPitchInput(Value * BaseLookUpRate * GetWorld()->DeltaTimeSeconds); } void AHNSTPlayable::TurnRate(float Value) { if(IsAlive()) AddControllerYawInput(Value * BaseTurnRate * GetWorld()->DeltaTimeSeconds); } //Movement set to be diagonal relative to world for easier perspective application void AHNSTPlayable::MoveForward(float Value) { if(Controller and Value != 0.0f) { //Find out which way is forward const FRotator Rotation = Controller->GetControlRotation(); const FRotator YawRotation(0, Rotation.Yaw, 0); //Get forward vector const FVector& ForwardDirection = FRotationMatrix(YawRotation).GetUnitAxis(EAxis::X); //Get right vector const FVector& RightDirection = FRotationMatrix(YawRotation).GetUnitAxis(EAxis::Y); const FVector Direction = ForwardDirection - RightDirection; //Add input AddMovementInput(Direction, Value); } } void AHNSTPlayable::MoveRight(float Value) { if(Controller and Value != 0.0f) { //Find out which way is right const FRotator Rotation = Controller->GetControlRotation(); const FRotator YawRotation(0, Rotation.Yaw, 0); //Get forward vector const FVector& ForwardDirection = FRotationMatrix(YawRotation).GetUnitAxis(EAxis::X); //Get right vector const FVector& RightDirection = FRotationMatrix(YawRotation).GetUnitAxis(EAxis::Y); const FVector Direction = ForwardDirection + RightDirection; //Add input AddMovementInput(Direction, Value); } } void AHNSTPlayable::BindASCInput() { if(!bASCInputBound and AbilitySystemComponent.IsValid() and IsValid(InputComponent)) { //Additional inputs, like Ability1 or Basic, are automatically bound. AbilitySystemComponent->BindAbilityActivationToInputComponent(InputComponent, FGameplayAbilityInputBinds ( "Confirm","Cancel", "EHNSTAbilityInputID", static_cast<int32>(EHNSTAbilityInputID::Confirm),static_cast<int32>(EHNSTAbilityInputID::Cancel) )); bASCInputBound = true; } } void AHNSTPlayable::InitializeASC(AHNSTPlayerState* TempPlayerState) { //Initialize GAS AbilitySystemComponent = Cast<UHNSTAbilitySystemComponent>(TempPlayerState->GetAbilitySystemComponent()); TempPlayerState->GetAbilitySystemComponent()->InitAbilityActorInfo(TempPlayerState, this); AttributeSet = TempPlayerState->GetAttributeSet(); AbilitySystemComponent->SetTagMapCount(DeadTag, 0); InitializeAttributes(); SetCurrentHealth(GetMaxHealth()); SetCurrentStamina(GetMaxStamina()); } void AHNSTPlayable::BeginPlay() { Super::BeginPlay(); Controller->SetControlRotation(FRotator(180, 0, 0)); //Save starting camera settings //Useful when you make abilities that change the camera position StartingCameraBoomArmLength = CameraBoom->TargetArmLength; StartingCameraBoomLocation = CameraBoom->GetRelativeLocation(); StartingCameraBoomRotation = CameraBoom->GetComponentRotation(); } //Replication void AHNSTPlayable::OnRep_PlayerState() { Super::OnRep_PlayerState(); if(AHNSTPlayerState* TempPlayerState = GetPlayerState<AHNSTPlayerState>()) { InitializeASC(TempPlayerState); BindASCInput(); } } AHNSTPlayable::AHNSTPlayable(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) { PrimaryActorTick.bCanEverTick = true; //Setup camera boom CameraBoom = CreateDefaultSubobject<USpringArmComponent>(FName("CameraBoom")); CameraBoom->SetupAttachment(RootComponent); CameraBoom->SetAbsolute(false, true, false); //Sets rotation to being relative to world CameraBoom->bDoCollisionTest = false; //Makes it so the camera boom does not shorten when the camera hits something CameraBoom->TargetArmLength = 1200.f; CameraBoom->SetRelativeRotation(FRotator(-45.0f,-45.0f,0.0f)); //Sets the camera in isometric view relative to actor //Don't rotate when the controller rotates. bUseControllerRotationPitch = false; bUseControllerRotationYaw = false; bUseControllerRotationRoll = false; //Configure character movement GetCharacterMovement()->bOrientRotationToMovement = false; //Setup camera FollowCamera = CreateDefaultSubobject<UCameraComponent>(FName("FollowCamera")); FollowCamera->SetupAttachment(CameraBoom, USpringArmComponent::SocketName); FollowCamera->FieldOfView = 80.0f; FollowCamera->bUsePawnControlRotation = false; //Setup cursor to world CursorToWorld = CreateDefaultSubobject<UDecalComponent>("CursorToWorld"); CursorToWorld->SetupAttachment(RootComponent); CursorToWorld->DecalSize = FVector(16.0f, 32.0f, 32.0f); CursorToWorld->SetRelativeRotation(FRotator(90.0f, 0.0f, 0.0f).Quaternion()); GetCapsuleComponent()->SetCollisionResponseToChannel(ECollisionChannel::ECC_Camera, ECollisionResponse::ECR_Ignore); GetMesh()->VisibilityBasedAnimTickOption = EVisibilityBasedAnimTickOption::AlwaysTickPoseAndRefreshBones; GetMesh()->SetCollisionEnabled(ECollisionEnabled::NoCollision); GetMesh()->SetCollisionProfileName(FName("NoCollision")); DeadTag = FGameplayTag::RequestGameplayTag(FName("State.Dead")); } void AHNSTPlayable::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent) { Super::SetupPlayerInputComponent(PlayerInputComponent); check(PlayerInputComponent); //Uncomment these when changing camera, e.x. when switching from isometric to third person PlayerInputComponent->BindAxis("MoveForward", this, &AHNSTPlayable::MoveForward); PlayerInputComponent->BindAxis("MoveRight", this, &AHNSTPlayable::MoveRight); //PlayerInputComponent->BindAxis("LookUp", this, &AHNSTPlayable::LookUp); //PlayerInputComponent->BindAxis("LookUpRate", this, &AHNSTPlayable::LookUpRate); //PlayerInputComponent->BindAxis("Turn", this, &AHNSTPlayable::Turn); //PlayerInputComponent->BindAxis("TurnRate", this, &AHNSTPlayable::TurnRate); BindASCInput(); } void AHNSTPlayable::Tick(float DeltaSeconds) { Super::Tick(DeltaSeconds); APlayerController* PlayerController = Cast<APlayerController>(GetController()); if(!IsValid(PlayerController)) return; //Updates the cursor transform each frame if(CursorToWorld) { FHitResult TraceHitResult; PlayerController->GetHitResultUnderCursor(ECC_Visibility, true, TraceHitResult); FVector CursorFV = TraceHitResult.ImpactNormal; FRotator CursorR = CursorFV.Rotation(); CursorToWorld->SetWorldLocation(TraceHitResult.Location); CursorToWorld->SetWorldRotation(CursorR); } FVector MouseLocation; FVector MouseDirection; //Rotates the actor towards the world cursor if(PlayerController->DeprojectMousePositionToWorld(MouseLocation, MouseDirection)) { FRotator MeshRotation = UKismetMathLibrary::FindLookAtRotation(GetActorLocation(), CursorToWorld->GetComponentLocation()); MeshRotation.Pitch = 0; MeshRotation.Roll = 0; GetCharacterMovement()->MoveUpdatedComponent(FVector::ZeroVector, MeshRotation, false); } } void AHNSTPlayable::PossessedBy(AController* NewController) { Super::PossessedBy(NewController); if(AHNSTPlayerState* TempPlayerState = GetPlayerState<AHNSTPlayerState>()) { InitializeASC(TempPlayerState); AddStartupEffects(); GiveAbilities(); } } USpringArmComponent* AHNSTPlayable::GetCameraBoom() const { return CameraBoom; } UCameraComponent* AHNSTPlayable::GetFollowCamera() const { return FollowCamera; } UDecalComponent* AHNSTPlayable::GetCursorToWorld() const { return CursorToWorld; } float AHNSTPlayable::GetStartingCameraBoomArmLength() const { return StartingCameraBoomArmLength; } FVector AHNSTPlayable::GetStartingCameraBoomLocation() const { return StartingCameraBoomLocation; } FRotator AHNSTPlayable::GetStartingCameraBoomRotation() const { return StartingCameraBoomRotation; }
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // https://github.com/WICG/web-codecs // A VideoDecoder processes a queue of configure, decode, and flush requests. // Requests are taken from the queue sequentially but may be processed // concurrently. // // TODO(sandersd): Specify a tune() implementation for changing decoder // parameters (separate from stream parameters). This is more important for // encoders. [ Exposed=Window, RuntimeEnabled=WebCodecs ] interface VideoDecoder { // |init| includes an |output| callback for emitting VideoFrames and an // |error| callback for emitting decode errors. // // When in an closed state, all methods will fail. // // TODO(sandersd): Consider adding a state or last error attribute. [CallWith=ScriptState, RaisesException, MeasureAs=WebCodecsVideoDecoder] constructor(VideoDecoderInit init); // The number of pending decode requests. This does not include requests that // have been sent to the underlying codec. // // Applications can minimize underflow by enqueueing decode requests until // |decodeQueueSize| is greater than a constant. // // TODO(sandersd): Consider adding a predicted output count or other // backpressure mechanism that considers the state of the underlying codec. // TODO(sandersd): Consider emitting an event when this number decreases. readonly attribute long decodeQueueSize; // Set the stream configuration for future decode() requests. // // The next decode request must be for a keyframe. // // TODO(sandersd): Move the keyframe rule into the bytestream registry. [RaisesException] void configure(VideoDecoderConfig config); // Request decoding of an input chunk. // // You must call configure() before calling decode() for the first time. // // TODO(sandersd): Change to a dictionary type. [RaisesException] void decode(EncodedVideoChunk chunk); // Request output from all previous decode requests. // // Resolved after all output for earlier decode requests has been emitted. // // The next decode request must be for a keyframe. // // TODO(sandersd): Consider relaxing the keyframe requirement. // TODO(sandersd): Indicate whether the flush() completed successfully or due // to a reset. [RaisesException] Promise<void> flush(); // Discard all pending decode requests. // // The next decode request must be for a keyframe. // // Note: It may be possible to call reset() after a flush() promise has been // resolved but before it is fulfilled. In that case the flush() promise will // be fulfilled successfully even though reset() was called. [RaisesException] void reset(); // Immediately shut down the decoder and free its resources. All pending // decode requests are aborted. // // Not recoverable: make a new VideoDecoder if needed. [RaisesException] void close(); // Which state the decoder is in, indicating which methods can be called. readonly attribute CodecState state; };
import React from 'react' import { useParams } from 'react-router-dom' import { useState, useEffect } from 'react'; import BackUpImage from '../assets/images/backup.png' export const MovieDetail = () => { const params = useParams(); const [movie, setMovie] = useState({}); const image = movie.poster_path ? `https://image.tmdb.org/t/p/w500/${movie.poster_path}` : BackUpImage; useEffect(() => { async function fetchMovie(){ const response = await fetch(`https://api.themoviedb.org/3/movie/${params.id}?api_key=${process.env.REACT_APP_API_KEY}`); const json = await response.json(); setMovie(json); } fetchMovie(); }, []) return ( <main> <section className='flex justify-around flex-wrap py-5'> <div className='max-w-sm'> <img className='rounded' src={image} alt={movie.title} /> </div> <div className='max-w-2xl text-gray-700 text-lg dark:text-white'> <h1 className='text-4xl font-bold my-3 text-center lg:text-left'>{movie.title}</h1> <p className='my-4'>{movie.overview}</p> {movie.genre ? (<p className='my-7 flex flex-wrap gap-2'> {movie.genres.map((genre) => ( <span key={genre.id} className='mt-2 border border-gray-200 rounded dark: border-gray-600 p-2'>{genre.name}</span> ))} </p>): ""} <div className="flex items-center"> <svg aria-hidden="true" className="w-5 h-5 text-yellow-400" fill="currentColor" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><title>Rating star</title><path d="M9.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-1.175 0l-2.8 2.034c-.784.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.98 8.72c-.783-.57-.38-1.81.588-1.81h3.461a1 1 0 00.951-.69l1.07-3.292z"></path></svg> <p className="ml-2 text-sm text-gray-900 dark:text-white">{movie.vote_average}</p> <span className="w-1 h-1 mx-1.5 bg-gray-500 rounded-full dark:bg-gray-400"></span> <span href="#" className="text-gray-900 text-sm dark:text-white">{movie.vote_count} reviews</span> </div> <p className='my-4'> <span className='text-sm mr-2 font-bold'>Runtime:</span> <span className='text-sm'>{movie.runtime} min.</span> </p> <p className='my-4'> <span className='text-sm mr-2 font-bold'>Budget:</span> <span className='text-sm'>{movie.budget}</span> </p> <p className='my-4'> <span className='text-sm mr-2 font-bold'>Revenue:</span> <span className='text-sm'>{movie.revenue}</span> </p> <p className='my-4'> <span className='text-sm mr-2 font-bold'>Release Date:</span> <span className='text-sm'>{movie.release_date}</span> </p> <p className='my-4'> <span className='text-sm mr-2 font-bold'>IMDB Code:</span> <a href={`https://www.imdb.com/title/${movie.imdb_id}`} target="_" rel='noreferrer' className='text-sm hover:underline'>{movie.imdb_id}</a> </p> </div> </section> </main> ) }
<?php namespace Packages\Modules\ERP\Http\Controllers; use Packages\Foundation\Http\Controllers\BaseController; use Packages\Modules\ERP\DataTables\ProvidersDataTable; use Packages\Modules\ERP\Http\Requests\ProviderRequest; use Packages\Modules\ERP\Models\Provider; use Packages\Modules\ERP\Models\Account; use Packages\Modules\ERP\Models\Financial; class ProvidersController extends BaseController { protected $excludedRequestParams = []; public function __construct() { $this->resource_url = config('erp.models.provider.resource_url'); $this->title = 'ERP::module.provider.title'; $this->title_singular = 'ERP::module.provider.title_singular'; parent::__construct(); } /** * @param ProviderRequest $request * @param ProvidersDataTable $dataTable * @return mixed */ public function index(ProviderRequest $request, ProvidersDataTable $dataTable) { return $dataTable->render('ERP::providers.index'); } /** * @param ProviderRequest $request * @return $this */ public function create(ProviderRequest $request) { $provider = new Provider(); $this->setViewSharedData(['title_singular' => trans('Packages::labels.create_title', ['title' => $this->title_singular])]); return view('ERP::providers.create_edit')->with(compact('provider')); } /** * @param ProviderRequest $request * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector */ public function store(ProviderRequest $request) { try { $provider = \ERP::storeUser($request, 'provider', ['financial_accounts', 'create_financial_account']); //add financials and account if($request->create_financial_account == 'yes'){ if(is_array($request->financial_accounts)){ $accountData = array_merge($request->financial_accounts, [ 'name' => $request->input('financial_accounts.translated_name.ar'), 'name_en' => $request->input('financial_accounts.translated_name.en'), 'user_id' => $provider->id, ]); $account = Account::create($accountData); $opening_balance = $request->input('financial_accounts.opening_balance'); $description_financial = [ 'ar' => 'ايداع مبلغ'. $opening_balance. ' كرصيد افتتاحي لحساب رقم ['.$account->account_code.']', 'en' => 'Deposit of '. $opening_balance.' to account with code ['.$account->account_code.'] as opening balance', ]; if($account->exists && $opening_balance > 0){ $financial = Financial::create([ 'reg_code' => uniqid(), 'type' => 'deposit', 'reg_value' => $request->input('financial_accounts.opening_balance'), 'value_type' => 'amount', 'final_value' => $request->input('financial_accounts.opening_balance'), 'description' => $description_financial, 'status' => 1, 'to_user_id' => $provider->id, 'to_account_id' => $account->id, ]); } } } flash(trans('Packages::messages.success.created', ['item' => $this->title_singular]))->success(); } catch (\Exception $exception) { log_exception($exception, Provider::class, 'store'); } return redirectTo($this->resource_url); } /** * @param ProviderRequest $request * @param Provider $provider * @return Provider */ public function show(ProviderRequest $request, Provider $provider) { $this->setViewSharedData(['title_singular' => trans('Packages::labels.show_title', ['title' => $provider->name])]); $this->setViewSharedData(['edit_url' => $this->resource_url . '/' . $Provider->hashed_id . '/edit']); return view('ERP::providers.show')->with(compact('provider')); } /** * @param ProviderRequest $request * @param Provider $provider * @return $this */ public function edit(ProviderRequest $request, Provider $provider) { $this->setViewSharedData(['title_singular' => trans('Packages::labels.update_title', ['title' => $provider->name])]); return view('ERP::providers.create_edit')->with(compact('provider')); } /** * @param ProviderRequest $request * @param Provider $provider * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector */ public function update(ProviderRequest $request, Provider $provider) { try { \ERP::updateUser($request, $provider, 'provider',['financial_accounts', 'create_financial_account']); flash(trans('Packages::messages.success.updated', ['item' => $this->title_singular]))->success(); } catch (\Exception $exception) { log_exception($exception, Provider::class, 'update'); } return redirectTo($this->resource_url); } /** * @param ProviderRequest $request * @param Provider $provider * @return \Illuminate\Http\JsonResponse */ public function destroy(ProviderRequest $request, Provider $provider) { try { $provider->delete(); $message = ['level' => 'success', 'message' => trans('Packages::messages.success.deleted', ['item' => $this->title_singular])]; } catch (\Exception $exception) { log_exception($exception, Provider::class, 'destroy'); $message = ['level' => 'error', 'message' => $exception->getMessage()]; } return response()->json($message); } }
// SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; import "./IWallet.sol"; import "./IModule.sol"; /** * @title BaseWallet * @notice Simple modular wallet that authorises modules to call its invoke() method. * @author Julien Niset - <[email protected]> */ contract BaseWallet is IWallet { // The implementation of the proxy address public implementation; // The owner address public override owner; // The authorised modules mapping(address => bool) public override authorised; // The enabled static calls mapping(bytes4 => address) public override enabled; // The number of modules uint256 public override modules; event AuthorisedModule(address indexed module, bool value); event EnabledStaticCall(address indexed module, bytes4 indexed method); event Invoked( address indexed module, address indexed target, uint256 indexed value, bytes data ); event Received(uint256 indexed value, address indexed sender, bytes data); event OwnerChanged(address owner); /** * @notice Throws if the sender is not an authorised module. */ modifier moduleOnly { require( authorised[msg.sender], "BW: msg.sender not an authorized module" ); _; } /** * @notice Inits the wallet by setting the owner and authorising a list of modules. * @param _owner The owner. * @param _modules The modules to authorise. */ function init(address _owner, address[] calldata _modules) external { require( owner == address(0) && modules == 0, "BW: wallet already initialised" ); require( _modules.length > 0, "BW: construction requires at least 1 module" ); owner = _owner; modules = _modules.length; for (uint256 i = 0; i < _modules.length; i++) { require( authorised[_modules[i]] == false, "BW: module is already added" ); authorised[_modules[i]] = true; IModule(_modules[i]).init(address(this)); emit AuthorisedModule(_modules[i], true); } if (address(this).balance > 0) { emit Received(address(this).balance, address(0), ""); } } /** * @inheritdoc IWallet */ function authoriseModule(address _module, bool _value) external override moduleOnly { if (authorised[_module] != _value) { emit AuthorisedModule(_module, _value); if (_value == true) { modules += 1; authorised[_module] = true; IModule(_module).init(address(this)); } else { modules -= 1; require( modules > 0, "BW: wallet must have at least one module" ); delete authorised[_module]; } } } /** * @inheritdoc IWallet */ function enableStaticCall(address _module, bytes4 _method) external override moduleOnly { require( authorised[_module], "BW: must be an authorised module for static call" ); enabled[_method] = _module; emit EnabledStaticCall(_module, _method); } /** * @inheritdoc IWallet */ function setOwner(address _newOwner) external override moduleOnly { require(_newOwner != address(0), "BW: address cannot be null"); owner = _newOwner; emit OwnerChanged(_newOwner); } /** * @notice Performs a generic transaction. * @param _target The address for the transaction. * @param _value The value of the transaction. * @param _data The data of the transaction. */ function invoke( address _target, uint256 _value, bytes calldata _data ) external moduleOnly returns (bytes memory _result) { bool success; (success, _result) = _target.call{value: _value}(_data); if (!success) { // solhint-disable-next-line no-inline-assembly assembly { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } } emit Invoked(msg.sender, _target, _value, _data); } /** * @notice This method delegates the static call to a target contract if the data corresponds * to an enabled module, or logs the call otherwise. */ fallback() external payable { address module = enabled[msg.sig]; if (module == address(0)) { emit Received(msg.value, msg.sender, msg.data); } else { require( authorised[module], "BW: must be an authorised module for static call" ); // solhint-disable-next-line no-inline-assembly assembly { calldatacopy(0, 0, calldatasize()) let result := staticcall(gas(), module, 0, calldatasize(), 0, 0) returndatacopy(0, 0, returndatasize()) switch result case 0 { revert(0, returndatasize()) } default { return(0, returndatasize()) } } } } receive() external payable {} }
/* USER CODE BEGIN Header */ /** ****************************************************************************** * @file : main.c * @brief : Main program body ****************************************************************************** * @attention * * Copyright (c) 2023 STMicroelectronics. * All rights reserved. * * This software is licensed under terms that can be found in the LICENSE file * in the root directory of this software component. * If no LICENSE file comes with this software, it is provided AS-IS. * ****************************************************************************** */ /* USER CODE END Header */ /* Includes ------------------------------------------------------------------*/ #include "main.h" /* Private includes ----------------------------------------------------------*/ /* USER CODE BEGIN Includes */ /* USER CODE END Includes */ /* Private typedef -----------------------------------------------------------*/ /* USER CODE BEGIN PTD */ /* USER CODE END PTD */ /* Private define ------------------------------------------------------------*/ /* USER CODE BEGIN PD */ #define BUTTON_PRESSED 0 #define BUTTON_UNPRESSED 1 /* USER CODE END PD */ /* Private macro -------------------------------------------------------------*/ /* USER CODE BEGIN PM */ /* USER CODE END PM */ /* Private variables ---------------------------------------------------------*/ /* USER CODE BEGIN PV */ /* USER CODE END PV */ /* Private function prototypes -----------------------------------------------*/ void SystemClock_Config(void); static void MX_GPIO_Init(void); /* USER CODE BEGIN PFP */ /* USER CODE END PFP */ /* Private user code ---------------------------------------------------------*/ /* USER CODE BEGIN 0 */ uint8_t Segment_Cathode_Code[] = {0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xf8,0x80,0x90}; //********************************* void Clear_Data_Segment1(){ for(uint8_t i = 0; i<8; i++){ HAL_GPIO_WritePin(DATA1_GPIO_Port,DATA1_Pin,(0xff<<i)&0x80); HAL_GPIO_WritePin(CLK_GPIO_Port,CLK_Pin,GPIO_PIN_RESET); HAL_GPIO_WritePin(CLK_GPIO_Port,CLK_Pin,GPIO_PIN_SET); } HAL_GPIO_WritePin(LAT_GPIO_Port,LAT_Pin,GPIO_PIN_RESET); HAL_GPIO_WritePin(LAT_GPIO_Port,LAT_Pin,GPIO_PIN_SET); } void Write_Data_Segment1(uint8_t number){ //write data into 74hc595 then 74hc595 will push data to segment if((number <= 9) && (number >= 0)){ for(uint8_t i = 0; i<8; i++){ HAL_GPIO_WritePin(DATA1_GPIO_Port,DATA1_Pin,(Segment_Cathode_Code[number]<<i)&0x80); HAL_GPIO_WritePin(CLK_GPIO_Port,CLK_Pin,GPIO_PIN_RESET); HAL_GPIO_WritePin(CLK_GPIO_Port,CLK_Pin,GPIO_PIN_SET); } HAL_GPIO_WritePin(LAT_GPIO_Port,LAT_Pin,GPIO_PIN_RESET); HAL_GPIO_WritePin(LAT_GPIO_Port,LAT_Pin,GPIO_PIN_SET); } } void Turn_On_Segment1(uint8_t pos){ if(pos == 1){ // Turn on LED 1 and turn off LED 2 HAL_GPIO_WritePin(B1_GPIO_Port,B1_Pin,GPIO_PIN_SET); HAL_GPIO_WritePin(B2_GPIO_Port,B2_Pin,GPIO_PIN_RESET); } else if(pos == 2){ // Turn on LED 2 and turn off LED 1 HAL_GPIO_WritePin(B1_GPIO_Port,B1_Pin,GPIO_PIN_RESET); HAL_GPIO_WritePin(B2_GPIO_Port,B2_Pin,GPIO_PIN_SET); } } void Display_Number_Segment1(uint8_t number){ if((number >= 0) && (number <= 99)){ Write_Data_Segment1(number / 10); Turn_On_Segment1(1); HAL_Delay(4); Clear_Data_Segment1(); Write_Data_Segment1(number % 10); Turn_On_Segment1(2); HAL_Delay(4); Clear_Data_Segment1(); } } //************************************ void Clear_Data_Segment2(){ for(uint8_t i = 0; i<8; i++){ HAL_GPIO_WritePin(DATA2_GPIO_Port,DATA2_Pin,(0xff<<i)&0x80); HAL_GPIO_WritePin(CLK2_GPIO_Port,CLK2_Pin,GPIO_PIN_RESET); HAL_GPIO_WritePin(CLK2_GPIO_Port,CLK2_Pin,GPIO_PIN_SET); } HAL_GPIO_WritePin(LAT2_GPIO_Port,LAT2_Pin,GPIO_PIN_RESET); HAL_GPIO_WritePin(LAT2_GPIO_Port,LAT2_Pin,GPIO_PIN_SET); } void Write_Data_Segment2(uint8_t number){ //write data into 74hc595 then 74hc595 will push data to segment if((number <= 9) && (number >= 0)){ for(uint8_t i = 0; i<8; i++){ HAL_GPIO_WritePin(DATA2_GPIO_Port,DATA2_Pin,(Segment_Cathode_Code[number]<<i)&0x80); HAL_GPIO_WritePin(CLK2_GPIO_Port,CLK2_Pin,GPIO_PIN_RESET); HAL_GPIO_WritePin(CLK2_GPIO_Port,CLK2_Pin,GPIO_PIN_SET); } HAL_GPIO_WritePin(LAT2_GPIO_Port,LAT2_Pin,GPIO_PIN_RESET); HAL_GPIO_WritePin(LAT2_GPIO_Port,LAT2_Pin,GPIO_PIN_SET); } } void Turn_On_Segment2(uint8_t pos){ if(pos == 1){ // Turn on LED 1 and turn off LED 2 HAL_GPIO_WritePin(B3_GPIO_Port,B3_Pin,GPIO_PIN_SET); HAL_GPIO_WritePin(B4_GPIO_Port,B4_Pin,GPIO_PIN_RESET); } else if(pos == 2){ // Turn on LED 2 and turn off LED 1 HAL_GPIO_WritePin(B3_GPIO_Port,B3_Pin,GPIO_PIN_RESET); HAL_GPIO_WritePin(B4_GPIO_Port,B4_Pin,GPIO_PIN_SET); } } void Display_Number_Segment2(uint8_t number){ if((number >= 0) && (number <= 99)){ Write_Data_Segment2(number / 10); Turn_On_Segment2(1); HAL_Delay(4); Clear_Data_Segment2(); Write_Data_Segment2(number % 10); Turn_On_Segment2(2); HAL_Delay(4); Clear_Data_Segment2(); } } //************************************** uint8_t hour = 00; // loi so 1 va 4 uint8_t min = 55; void Display_Time(uint8_t* hour, uint8_t* min){ Display_Number_Segment1(*hour); Display_Number_Segment2(*min); } //****************************** uint8_t button_value = 0; void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin) { if(GPIO_Pin == CHANGE_MODE_Pin){ if((button_value <2) && (button_value >= 1)) button_value++; else button_value = 1; if(button_value == 1){ HAL_GPIO_WritePin(LED1_GPIO_Port,LED1_Pin,0); HAL_GPIO_WritePin(LED2_GPIO_Port,LED2_Pin,1); } else if(button_value == 2){ HAL_GPIO_WritePin(LED1_GPIO_Port,LED1_Pin,1); HAL_GPIO_WritePin(LED2_GPIO_Port,LED2_Pin,0); } } if(GPIO_Pin == INCREASE_Pin){ if(button_value == 1){ if((min < 59) && (min >= 0)) min++; else if(min == 59) min = 0; } else if(button_value == 2){ if((hour < 24) && (hour >= 0)) hour++; else if(hour == 24) hour = 0; } } else if(GPIO_Pin == DECREASE_Pin){ if(button_value == 1){ if((min <= 59) && (min > 0)) min--; else if(min == 0) min = 59; } else if(button_value == 2){ if((hour <= 24) && (hour > 0)) hour--; else if(hour == 0) hour = 24; } } } //************************************************ /* USER CODE END 0 */ /** * @brief The application entry point. * @retval int */ int main(void) { /* USER CODE BEGIN 1 */ /* USER CODE END 1 */ /* MCU Configuration--------------------------------------------------------*/ /* Reset of all peripherals, Initializes the Flash interface and the Systick. */ HAL_Init(); /* USER CODE BEGIN Init */ /* USER CODE END Init */ /* Configure the system clock */ SystemClock_Config(); /* USER CODE BEGIN SysInit */ /* USER CODE END SysInit */ /* Initialize all configured peripherals */ MX_GPIO_Init(); /* USER CODE BEGIN 2 */ uint8_t sys_state1 = 0; uint8_t sys_state2 = 0; uint8_t sec = 0; /* USER CODE END 2 */ /* Infinite loop */ /* USER CODE BEGIN WHILE */ while (1) { /* USER CODE END WHILE */ /* USER CODE BEGIN 3 */ Display_Time(&hour,&min); if((HAL_GPIO_ReadPin(RUN_GPIO_Port,RUN_Pin) == BUTTON_PRESSED) && sys_state1 == 0) sys_state1 = 1; if(sys_state1 == 1) HAL_GPIO_WritePin(LED4_GPIO_Port,LED4_Pin,1); while(sys_state1 == 1){ for(uint8_t i = 0; i < 36; i++){ Display_Time(&hour,&min); } if(sec < 59) sec++; else if((sec == 59) && (min < 59)){ sec = 0; min++; } else if((sec == 59) && (min == 59) && (hour < 24)){ sec = 0; min = 0; hour++; } else if((sec == 59) && (min == 59) && (hour == 24)){ sec = 0; min = 0; hour = 0; } if((HAL_GPIO_ReadPin(STOP_GPIO_Port,STOP_Pin) == BUTTON_PRESSED) && sys_state2 == 0) sys_state2 = 1; if(sys_state2 == 1) break; } HAL_GPIO_WritePin(LED4_GPIO_Port,LED4_Pin,0); sys_state1 = 0; sys_state2 = 0; // Display_Number_Segment1(00); } /* USER CODE END 3 */ } /** * @brief System Clock Configuration * @retval None */ void SystemClock_Config(void) { RCC_OscInitTypeDef RCC_OscInitStruct = {0}; RCC_ClkInitTypeDef RCC_ClkInitStruct = {0}; /** Initializes the RCC Oscillators according to the specified parameters * in the RCC_OscInitTypeDef structure. */ RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE; RCC_OscInitStruct.HSEState = RCC_HSE_ON; RCC_OscInitStruct.PLL.PLLState = RCC_PLL_NONE; if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) { Error_Handler(); } /** Initializes the CPU, AHB and APB buses clocks */ RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2; RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_HSE; RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1; RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1; RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1; if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_0) != HAL_OK) { Error_Handler(); } } /** * @brief GPIO Initialization Function * @param None * @retval None */ static void MX_GPIO_Init(void) { GPIO_InitTypeDef GPIO_InitStruct = {0}; /* GPIO Ports Clock Enable */ __HAL_RCC_GPIOD_CLK_ENABLE(); __HAL_RCC_GPIOA_CLK_ENABLE(); __HAL_RCC_GPIOB_CLK_ENABLE(); /*Configure GPIO pin Output Level */ HAL_GPIO_WritePin(GPIOA, CLK_Pin|LAT_Pin|DATA1_Pin|B1_Pin |B2_Pin|CLK2_Pin|LAT2_Pin|DATA2_Pin |B3_Pin|B4_Pin, GPIO_PIN_RESET); /*Configure GPIO pin Output Level */ HAL_GPIO_WritePin(GPIOB, LED4_Pin|LED5_Pin|LED1_Pin|LED2_Pin, GPIO_PIN_RESET); /*Configure GPIO pins : CLK_Pin LAT_Pin DATA1_Pin B1_Pin B2_Pin CLK2_Pin LAT2_Pin DATA2_Pin B3_Pin B4_Pin */ GPIO_InitStruct.Pin = CLK_Pin|LAT_Pin|DATA1_Pin|B1_Pin |B2_Pin|CLK2_Pin|LAT2_Pin|DATA2_Pin |B3_Pin|B4_Pin; GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP; GPIO_InitStruct.Pull = GPIO_NOPULL; GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW; HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); /*Configure GPIO pins : STOP_Pin RUN_Pin */ GPIO_InitStruct.Pin = STOP_Pin|RUN_Pin; GPIO_InitStruct.Mode = GPIO_MODE_INPUT; GPIO_InitStruct.Pull = GPIO_PULLUP; HAL_GPIO_Init(GPIOB, &GPIO_InitStruct); /*Configure GPIO pins : LED4_Pin LED5_Pin LED1_Pin LED2_Pin */ GPIO_InitStruct.Pin = LED4_Pin|LED5_Pin|LED1_Pin|LED2_Pin; GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP; GPIO_InitStruct.Pull = GPIO_NOPULL; GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW; HAL_GPIO_Init(GPIOB, &GPIO_InitStruct); /*Configure GPIO pins : INCREASE_Pin DECREASE_Pin CHANGE_MODE_Pin */ GPIO_InitStruct.Pin = INCREASE_Pin|DECREASE_Pin|CHANGE_MODE_Pin; GPIO_InitStruct.Mode = GPIO_MODE_IT_FALLING; GPIO_InitStruct.Pull = GPIO_PULLUP; HAL_GPIO_Init(GPIOB, &GPIO_InitStruct); /* EXTI interrupt init*/ HAL_NVIC_SetPriority(EXTI3_IRQn, 0, 0); HAL_NVIC_EnableIRQ(EXTI3_IRQn); HAL_NVIC_SetPriority(EXTI4_IRQn, 1, 0); HAL_NVIC_EnableIRQ(EXTI4_IRQn); HAL_NVIC_SetPriority(EXTI9_5_IRQn, 2, 0); HAL_NVIC_EnableIRQ(EXTI9_5_IRQn); } /* USER CODE BEGIN 4 */ /* USER CODE END 4 */ /** * @brief This function is executed in case of error occurrence. * @retval None */ void Error_Handler(void) { /* USER CODE BEGIN Error_Handler_Debug */ /* User can add his own implementation to report the HAL error return state */ __disable_irq(); while (1) { } /* USER CODE END Error_Handler_Debug */ } #ifdef USE_FULL_ASSERT /** * @brief Reports the name of the source file and the source line number * where the assert_param error has occurred. * @param file: pointer to the source file name * @param line: assert_param error line source number * @retval None */ void assert_failed(uint8_t *file, uint32_t line) { /* USER CODE BEGIN 6 */ /* User can add his own implementation to report the file name and line number, ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */ /* USER CODE END 6 */ } #endif /* USE_FULL_ASSERT */
import { Component } from '@angular/core'; import { FormBuilder, FormGroup, Validators } from '@angular/forms'; import { Router } from '@angular/router'; import { LibrosI } from 'src/app/models/interfaces'; import { LibrosService } from 'src/app/services/libros/libros.service'; @Component({ selector: 'app-form', templateUrl: './form-libro.component.html', styleUrls: ['./form-libro.component.scss'] }) export class FormLibroComponent { libroForm! : FormGroup; _id! : string; libro! : LibrosI; submitted: boolean = false; genres: Array<any> = [ { name: 'Manga', value: 'Manga' }, { name: 'Narrativa de humor', value: 'Narrativa de humor' }, { name: 'Infantil', value: 'Infantil' }, { name: 'Novela de Terror', value: 'Novela de Terror' }, { name: 'Novela romántica', value: 'Novela romantica' }, { name: 'Narrativa fantástica', value: 'Narrativa fantastica' }, { name: 'Novela negra', value: 'Novela ' }, { name: 'Novela histórica', value: 'Novela historica' } ]; constructor(private service: LibrosService, private form: FormBuilder, private router: Router) { this.libro = this.service.getOneLibro(); this._id = this.service.getId(); } ngOnInit() : void { this.libroForm = this.form.group({ Portada: [this.libro?.Portada, [Validators.required]], Nombre: [this.libro?.Nombre, [Validators.required]], Autor: [this.libro?.Autor, [Validators.required]], Descripcion: [this.libro?.Descripcion, [Validators.required]], Genero: [this.libro.Genero, [Validators.required]], Resena: [this.libro?.Resena], Valoracion: [this.libro?.Valoracion], }); this.libroForm.valueChanges.subscribe((data) => { this.libro = data; }) } onCheckboxChange(event: any) { if (event.target.checked) { this.libro.Genero.push(event.target.value); } else { const index = this.libro.Genero.indexOf(event.target.value); if (index > -1) { this.libro.Genero.splice(index, 1); } } } onClick() { this.submitted = true; if(this.libroForm.valid) { if(this._id === "") { // ADD LIBRO this.service.postLibro(this.libro).subscribe((data) => { this.libroForm.reset(); this.submitted = false; this.router.navigate(['/libros']); }); } else { // EDIT LIBRO this.service.putLibro(this._id,this.libro).subscribe((data) => { this.libroForm.reset(); this.submitted = false; this.router.navigate(['/libros']); }); } } } ngOnDestroy() : void { this.submitted = false; this.service.resetLibroData(); this._id = ""; } }
// Aggrega tutte le dipendenze in una singola Promessa var inizializzazioneApp = Promise.all([ traduzioneCaricata, new Promise(resolve => $(document).ready(resolve)) ]); /** * Funzione di inizializzazione eseguita al caricamento completo del DOM. */ inizializzazioneApp.then(() => { /** * Gestisce l'evento di scorrimento della finestra. */ $(window).scroll(function () { // Controlla se lo scroll supera i 50 pixel dall'alto della pagina if ($(this).scrollTop() > 50) { $('#back-to-top').fadeIn(); // Mostra il pulsante 'back-to-top' } else { $('#back-to-top').fadeOut(); // Nasconde il pulsante } }); /** * Gestisce il click sul pulsante 'back-to-top'. */ $('#back-to-top').click(function () { // Anima lo scroll verso l'alto della pagina $('body,html').animate({ scrollTop: 0 }, 400); // Durata dell'animazione: 400 millisecondi return false; }); /** * Imposta l'effetto fumo su un elemento canvas specificato. */ var fumo = $('#smoke-effect-canvas'); if (fumo.length) fumo.SmokeEffect({ color: fumo.data('color'), // Colore del fumo opacity: fumo.data('opacity'), // Opacità del fumo maximumVelocity: fumo.data('maximumVelocity'), // Velocità massima delle particelle particleRadius: fumo.data('particleRadius'), // Raggio delle particelle di fumo density: fumo.data('density') // Densità del fumo }); /** * Gestisce lo scorrimento orizzontale su elementi con classe 'horizontal-scroll'. */ $('.horizontal-scroll').on('wheel', function (event) { event.preventDefault(); // Previene lo scorrimento verticale predefinito this.scrollLeft += event.originalEvent.deltaY + event.originalEvent.deltaX; }); }); /** * Apre un link codificato. * * @param {string} prefix - Prefisso da aggiungere alla stringa decodificata. * @param {string} encodedStr - Stringa codificata da decodificare e aprire come link. */ function openEncodedLink(prefix, encodedStr) { var decodedString = encodedStr; var url = ""; // Costruisce l'URL completo if (prefix) { url = prefix + decodedString; } else { url = decodedString; } // Reindirizza alla nuova URL window.location.href = url; } /** * Imposta lo sfondo della pagina con il colore medio di un'immagine. * * @param {string} src - Percorso dell'immagine da cui estrarre il colore medio. */ function set_background_with_average_rgb(src) { var canvas = document.createElement('canvas'); var context = canvas.getContext('2d'); var img = new Image(); img.crossOrigin = 'Anonymous'; img.onload = function () { context.drawImage(img, 0, 0, 1, 1); var data = context.getImageData(0, 0, 1, 1).data; var colorStr = 'rgb(' + data[0] + ',' + data[1] + ',' + data[2] + ')'; document.body.style.backgroundColor = colorStr; }; img.onerror = function () { // Gestione dell'errore }; img.src = src; } /** * Copia un testo specificato nella clipboard del sistema. * * Utilizza l'API Clipboard di navigator, se disponibile e il contesto è sicuro (https). * In caso contrario, ricorre a un metodo alternativo creando un'area di testo temporanea. * * @param {string} testoDaCopiare - Testo da copiare nella clipboard. * @param {string} idElemento - ID dell'elemento da cui ottenere il testo (usato nel metodo alternativo). * @returns {Promise} - Ritorna una Promise che risolve se la copia è riuscita, altrimenti la rifiuta. * * Esempio di utilizzo: * copyToClipboard('Testo da copiare').then(() => { * console.log('Testo copiato con successo!'); * }).catch(() => { * console.error('Errore nella copia del testo.'); * }); */ function copyToClipboard(testoDaCopiare) { // Controlla se l'API Clipboard di navigator è disponibile e se il contesto è sicuro (https) if (navigator.clipboard && window.isSecureContext) { // Usa il metodo writeText dell'API Clipboard di navigator per copiare il testo return navigator.clipboard.writeText(testoDaCopiare); } else { // Metodo alternativo creando un elemento input temporaneo let tempInput = document.createElement("input"); tempInput.style.position = "absolute"; tempInput.style.left = "-9999px"; tempInput.value = testoDaCopiare; document.body.appendChild(tempInput); tempInput.select(); // Crea una nuova Promise per gestire la copia return new Promise((resolve, reject) => { // Esegue il comando di copia e risolve o rifiuta la Promise in base al risultato if (document.execCommand('copy')) { resolve(); } else { reject(); } // Rimuove l'elemento temporaneo dal DOM document.body.removeChild(tempInput); }); } } /** * Gestisce l'animazione e lo stato di un oggetto durante un periodo di tempo definito. * * @param {Object} myobj - Selettore jQuery per identificare l'oggetto. * @param {number} durata - Durata dell'animazione in millisecondi. */ function disattivaper(myobj, durata) { // Funzione per aggiungere lo stile di caricamento e disabilitare l'oggetto function iniziaCaricamento() { myobj.prop('disabled', true).addClass('obj-loading'); } // Funzione per aggiornare lo sfondo del oggetto function updateProgress(value) { var percentage = (value / durata) * 100; myobj.css('background-size', percentage + '% 100%'); } // Funzione per terminare il caricamento e riabilitare l'oggetto function terminaCaricamento() { myobj.prop('disabled', false).removeClass('obj-loading'); } // Inizia l'animazione iniziaCaricamento(); // Imposta un timer per riattivare l'oggetto dopo la durata specificata e aggiornare il progresso var startTime = Date.now(); var interval = setInterval(function () { var elapsedTime = Date.now() - startTime; updateProgress(elapsedTime); if (elapsedTime >= durata) { clearInterval(interval); terminaCaricamento(); } }, 100); } /** * Setta ala linga dell'applicativo * @param {string} lang - codice lingua */ function setLanguage(lang) { let searchParams = new URLSearchParams(window.location.search); searchParams.set('lang', lang); // Imposta o aggiorna il parametro 'lang' // Costruisce l'URL con i parametri aggiornati let newUrl = window.location.pathname + '?' + searchParams.toString() + window.location.hash; window.location.href = newUrl; // Reindirizza l'utente all'URL aggiornato }
## Homework 2 - create database on Postgresql => create a few table about pizza restaurants #ลองดึง table เก่าจาก db นึงไปสู่ db นึง library(RSQLite) # 1. connect db con1 <- dbConnect(SQLite(),"source/res.db") # 2. check db dbListTables(con1) # 3. list field (cols) dbListFields(con1,"menus") # 4. get data customers <- dbGetQuery(con1,"select * from customer") employees <- dbGetQuery(con1,"select * from employees") ingredient <- dbGetQuery(con1,"select * from ingredient") menus_ingre <- dbGetQuery(con1,"select * from menus_ingre") # 5. close db dbDisconnect(con1) ### อัปโหลดขึ้น db อันใหม่ # 0.use library library(RPostgreSQL) library(tidyverse) # 1. connect db con <- dbConnect(PostgreSQL(), host = "floppy.db.elephantsql.com", port = 5432, user = "selfweoz", password = "XY2Jy00k-MrnPDzCyDs3LcHTdAPaXoqq", dbname = "selfweoz") # 2. check db dbListTables(con) # 3. dis db dbDisconnect(con) # 4. write table or export table dbWriteTable(con,"customers",customers) dbWriteTable(con,"employees",employees) dbWriteTable(con,"ingredient",ingredient) dbWriteTable(con,"menus_ingre",menus_ingre) # 5. close db dbDisconnect(con)
import React from 'react' import "./style/All.css" import Navbar from './components/Navbar' import Home from './components/home-comp/Home' import Footer from './components/Footer' import {BrowserRouter, Routes,Route} from 'react-router-dom' import Login from './components/Login' import Signup from './components/Signup' import MainReview from './components/review-comp/MainReview' import Contact from './components/contact-comp/Contact' import Error404Page from './components/Error404Page' import MainAlert from './components/alers-comp/MainAlert' import AuthState from './context/auth/authState' import ContactState from './context/contact/contactState' import AlertState from './context/alert/alertState' import ReviewState from './context/review/reviewState' import TopLoadginBar from './components/TopLoadginBar' import ProgressState from './context/progress/progressState' import ScrallingReviewState from './context/review/scrallingReviewState' const App = () => { return ( <> <ProgressState> <AlertState> <ScrallingReviewState> <ReviewState> <ContactState> <AuthState> <BrowserRouter> <TopLoadginBar/> <Navbar/> <MainAlert/> <Routes> <Route exact path='/' element={<Home/>}/> <Route exact path='/home' element={<Home/>}/> <Route exact path='/login' element={<Login/>}/> <Route exact path='/signup' element={<Signup/>}/> <Route exact path='/contact' element={<Contact/>}/> <Route exact path='/mainreview' element={<MainReview/>}/> <Route exact path='/*' element={<Error404Page/>}/> </Routes> <Footer/> </BrowserRouter> </AuthState> </ContactState> </ReviewState> </ScrallingReviewState> </AlertState> </ProgressState> </> ) } export default App
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <link rel="stylesheet" href="style.css"> <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/brands.min.css" integrity="sha512-8RxmFOVaKQe/xtg6lbscU9DU0IRhURWEuiI0tXevv+lXbAHfkpamD4VKFQRto9WgfOJDwOZ74c/s9Yesv3VvIQ==" crossorigin="anonymous" referrerpolicy="no-referrer" /> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css" integrity="sha512-DTOQO9RWCH3ppGqcWaEA1BIZOC6xxalwEsw9c2QQeAIftl+Vegovlnee1c9QX4TctnWMn13TZye+giMm8e2LwA==" crossorigin="anonymous" referrerpolicy="no-referrer" /> </head> <body> <section id="nav-bar"> <nav class="navbar navbar-expand-lg navbar-light "> <!-- <div class="container-fluid"> --> <a class="navbar-brand" href="#"><img src="images/demo-logo.png" alt=""></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> --> <i class="fa fa-bars"></i> </button> <div class="collapse navbar-collapse d-flex justify-content-end" id="navbarNav"> <ul class="navbar-nav "> <li class="nav-item"> <a class="nav-link " aria-current="page" href="#">HOME</a> </li> <li class="nav-item"> <a class="nav-link" href="#">SERVICES</a> </li> <li class="nav-item"> <a class="nav-link" href="#">ABOUT US</a> </li> <li class="nav-item"> <a class="nav-link" href="#">TESTIMONIALS</a> </li> <li class="nav-item"> <a class="nav-link" href="#">CONTACT</a> </li> </ul> </div> </div> </nav> </section> <!-- banner section --> <section id="banner"> <div class="container"> <div class="row"> <div class="col-md-6"> <p class="promo-title">BEST DIGITAL AGENCY</p> <p>Lorem ipsum dolor sit amet consectetur, adipisicing elit. Harum dignissimos sed deleniti ipsam dolor obcaecati molestias laudantium quibusdam recusandae blanditiis fugiat tenetur.</p> <a href="#"> <img src="images/play.png" class="play-btn"></a>Watch Tutorials </div> <div class="col-md-6 text-center"> <img src="images/home2.png" class="img-fluid"> </div> </div> </div> <img src="images/wave1.png" class="bottom-img"> </section> <!-- Services section --> <section id="services"> <div class="container text-center"> <h1 class="title">WHAT WE DO ?</h1> <div class="row text-center"> <div class="col-md-4"> <img src="images/service1.png" class="service-img"> <h4>Growth Marketing</h4> <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Accusamus, nostrum voluptatibus placeat exercitationem corporis asperiores. .</p> </div> <div class="col-md-4"> <img src="images/service2.png" class="service-img"> <h4>Online Branding</h4> <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Accusamus, nostrum voluptatibus placeat exercitationem corporis asperiores. .</p> </div> <div class="col-md-4"> <img src="images/service3.png" class="service-img"> <h4>Animated Ads</h4> <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Accusamus, nostrum voluptatibus placeat exercitationem corporis asperiores. .</p> </div> </div> </div> <button type="button" class="btn btn-primary d-flex justify-content-center">All Service</button> </section> <!-- About us --> <section id="about-us"> <div class="container"> <h1 class="title text-center"> WHY CHOOSE US ?</h1> <div class="row"> <div class="col-md-6"> <ul> <p class="about-title">Why we're different</p> <li>Believe in doing business with honesty</li> <li>Believe in doing business with honesty</li> <li>Believe in doing business with honesty</li> <li>Believe in doing business with honesty</li> <li>Believe in doing business with honesty</li> <li>Believe in doing business with honesty</li> <li>Believe in doing business with honesty</li> </ul> </div> <div class="col-md-6"> <img src="images/network.png" class="img-fluid"> </div> </div> </div> </section> <!-- TESTIMONIALS --> <section id="testimonials"> <div class="container"> <h1 class="title text-center">WHAT CLIENT SAY</h1> <div class="row offset-1"> <div class="col-md-5 testimonials"> <p>Subscribe Easy TutorialsYoutube Channel to Watch more videos on wesite development, DIGITAL Marketing, Wordpress and graphic Designing</p> <img src="images/user1.jpg" class=""> <p class="user-detail"><b>Angelina</b><br> Co-founder at XYZ</p> </div> <div class="col-md-5 testimonials"> <p>Subscribe Easy TutorialsYoutube Channel to Watch more videos on wesite development, DIGITAL Marketing, Wordpress and graphic Designing</p> <img src="images/user2.jpg" class=""> <p class="user-detail"><b>John Doe</b><br> Director at XYZ</p> </div> </div> </div> </section> <!-- Social media section --> <section id="Social-media"> <div class="container text-center"> <p>FIND US ON SOCIAL MEDIA</p> </div> <div class="Social-icons text-center"> <a href="#"> <img src="images/facebook-icon.png" ></a> <a href="#"> <img src="images/instagram-icon.png" ></a> <a href="#"> <img src="images/twitter-icon.png" ></a> <a href="#"> <img src="images/whatsapp-icon.png" ></a> <a href="#"> <img src="images/linkedin-icon.png" ></a> <a href="#"> <img src="images/snapchat-icon.png" ></a> </div> </section> <!--footer section --> <section id="footer"> <img src="images/wave2.png" class="footer-img"> <div class="container"> <div class="row"> <div class="col-md-4 footer-box"> <img src="images/demo-logo.png" alt=""> <p>Subscribe Easy TutorialsYoutube Channel to Watch more videos on wesite development, DIGITAL Marketing, Wordpress and graphic Designing? Press the bell icon to get notifiation</p> </div> <div class="col-md-4 footer-box"> <p><b>CONTACT US</b></p> <p> <i class="fa fa-map-marker"></i>World Trade Center, Bangalore</p> <p> <i class="fa fa-phone"></i> +221 5038657</p> <p> <i class="fa fa-envelope"></i>[email protected]</p> </div> <div class="col-md-4 footer-box"> <p><b>SUBSCRIBE NEWLETTER</b></p> <input type="email" class="form-control" placeholder="Your Email"> <button type="button" class="btn btn-primary">Subscribe</button> </div> </div> <hr> <p class="copy"> Website casted by Easy Tutorials</p> </div> </section> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script> </body> </html>
import * as React from 'react'; import {Button, message, Table} from 'antd'; import {useImmerAtom} from 'jotai/immer'; import {useTranslation} from 'react-i18next'; import EditableDiv from '../../CustomInput/EditableDiv'; import {pieAtomFamily} from '../../../atoms/pieAtomFamily'; import {Param} from '../../../atoms/appAtom'; import {usePie} from '../../../hooks/usePie'; import {DeleteOutlined} from '@ant-design/icons'; export default function PieDataTable({id}: Param) { const [pie, setPie] = useImmerAtom(pieAtomFamily({id})); const {t} = useTranslation(); const {addArc, removeArcById, changeArcValueById} = usePie(id); const columns = [ { dataIndex: 'id', title: t('ID'), render: (value, record) => ( <EditableDiv value={value} onFinishEditing={(value) => { if ((value + '').length <= 0) { message.error('Cannot leave this field empty'); return; } if (pie.data.some((datum) => datum.id === value + '')) { message.error(`${value} exists.`); return; } setPie((pie) => { pie.data.find((i) => i.id === record.id).id = value as string; }); }} /> ), }, { dataIndex: 'label', title: t('Label'), render: (value: string, record) => ( <EditableDiv value={value} onFinishEditing={(value) => { setPie((pie) => { pie.data.find((i) => i.id === record.id).label = value as string; }); }} /> ), }, { dataIndex: 'value', title: t('Value'), render: (value: number, record) => ( <EditableDiv value={value} onFinishEditing={(value) => { changeArcValueById(record.id, value as number); }} /> ), }, { dataIndex: 'id', title: t('Action'), render: (value: string) => ( <Button type={'ghost'} icon={ <DeleteOutlined onClick={() => { removeArcById(value); }} /> } /> ), }, ]; return ( <> <Table rowKey={'id'} dataSource={pie.data} columns={columns} scroll={{y: 140}} footer={() => <Button onClick={addArc}>{t('Add Row')}</Button>} /> </> ); }
<!DOCTYPE html> <!-- Project: Portfolio Author: Jeffrey Sanford Credit: Adapted from template at startbootstrap.com called Grayscale. http://startbootstrap.com/template-overviews/grayscale/ with code from the portfolio section of the bootstrap temple freelancer (http://startbootstrap.com/template-overviews/freelancer/) --> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content="Portfolio of web design, development and programming sites"> <meta name="author" content="Jeffrey Sanford"> <title>Portfolio</title> <!-- Bootstrap Core CSS --> <link href="css/bootstrap.min.css" rel="stylesheet"> <!-- Custom CSS --> <link href="css/grayscale.css" rel="stylesheet"> <!-- Custom Fonts --> <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet" type="text/css"> <link href="http://fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic" rel="stylesheet" type="text/css"> <link href="http://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css"> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script> <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script> <![endif]--> <!-- jQuery Version 1.11.0 --> <script src="js/jquery-1.11.0.js"></script> </head> <body id="page-top" data-spy="scroll" data-target=".navbar-fixed-top"> <!-- Navigation --> <nav class="navbar navbar-custom navbar-fixed-top" role="navigation"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-main-collapse"> <i class="fa fa-bars"></i> </button> </div> <!-- Collect the nav links, forms, and other content for toggling --> <div class="collapse navbar-collapse navbar-right navbar-main-collapse"> <ul class="nav navbar-nav"> <!-- Hidden li included to remove active class from about link when scrolled up past about section --> <li class="hidden"> <a href="#page-top"></a> </li> <li> <a class="page-scroll" href="development" target="_blank">projects</a> </li> <li> <a class="page-scroll" href="#about">about</a> </li> <li> <a class="page-scroll" href="#resume">resume</a> </li> <li> <a class="page-scroll" href="#contact">contact</a> </li> </ul> </div> <!-- /.navbar-collapse --> </div> <!-- /.container --> </nav> <!-- Intro Header --> <header class="intro"> <div class="intro-body"> <div class="container"> <div class="row"> <div class="col-md-8 col-md-offset-2"> <p class="brand-heading">Jeffrey Sanford</p> <p class="intro-text">designer <i class="glyphicon glyphicon-star-empty"></i> developer <i class="glyphicon glyphicon-star-empty"></i> programmer</p> <a href="#about" class="btn btn-circle page-scroll"> <i class="fa fa-angle-double-down animated"></i> </a> </div> </div> </div> </div> </header> </section> <!-- About Section --> <section id="about" class="container content-section text-justify"> <div class="row"> <div class="col-lg-8 col-lg-offset-2"> <h2 class="text-center">About</h2> <div class="aboutStyle"> <p class="text-justify">I love programming; the logic structures, the code. It has given me a lifelong creative outlet and assisted me in many facets with associated work. My first computer was an Atari 400 with 16K of RAM and Atari BASIC that I taught myself with the help of the programming community. I have used that knowledge my entire life.</p> <p>After working on developing radar systems in the Army, then gaining expertise in technical, desktop and network support, I returned to my passion for programming. Most recently, I have been designing websites in <a href="projects/html5css3.html">HTML5</a> and <a href="projects/javascript.html">JavaScript</a> along with content management systems such as WordPress, Drupal and the brilliant framework AngularJS.</p> <p>Passionate about working on complex platforms and multiple programming languages, I have gained experience in PHP and libraries, JavaScript (primarily JQuery and angularJS), Java, Visual Basic, as well as, various content management systems (WordPress, Drupal, PyroCMS), databases (mySQL, MSSQL and Access). My design patterns focus first on the responsive-first design pattern using tools like <a href="projects/bootstrap.html">bootstrap</a>, mobile-friendly and dynamic web development models. I thrive in positions that I can share my knowledge of programming and design techniques in a team environment.</p> </div> </div> </div> </section> <!-- Contact Section --> <section id="contact" class="container content-section text-center"> <!-- Resume Section --> <article id="resume" class="text-center"> <ul class="list-inline banner-social-buttons"> <li> <a href="resume/jeffreysanford.pdf" class="btn btn-default btn-lg"><span class="network-name">Simple Resume</span></a> </li> <li> <a href="resume/DetailedResume.pdf" class="btn btn-default btn-lg"><span class="network-name">Detailed Background</span></a> </li> </ul> <br /><br /><br /> </article> <article> <div class="row"> <div class="col-lg-8 col-lg-offset-2"> <h2>Contact Me</h2> <p><a href="mailto:[email protected]">[email protected]</a></p> <br /><br /><br /><br /> <ul class="list-inline banner-social-buttons"> <li> <a href="https://twitter.com/jeffrey_sanford" class="btn btn-default btn-lg"><i class="fa fa-twitter fa-fw"></i> <span class="network-name">Twitter</span></a> </li> <li> <a href="https://github.com/jeffreysanford" class="btn btn-default btn-lg"><i class="fa fa-github fa-fw"></i> <span class="network-name">Github</span></a> </li> <li> <a href="https://plus.google.com/116252561894619265339/posts/p/pub" class="btn btn-default btn-lg"><i class="fa fa-google-plus fa-fw"></i> <span class="network-name">Google+</span></a> </li> <li> <a href="http://www.linkedin.com/pub/jeffrey-sanford/7/897/79/" class="btn btn-default btn-lg"><i class="fa fa-linkedin"></i> <span class="network-name">LinkedIn</span></a> </li> </ul> </div> </div> </article> </section> <!-- Footer --> <footer> <div class="container text-center"> <br /><br /> <p>Copyright &copy; Jeffrey Sanford 2014</p> </div> </footer> <!-- Bootstrap Core JavaScript --> <script src="js/bootstrap.min.js"></script> <!-- Plugin JavaScript --> <script src="js/jquery.easing.min.js"></script> <!-- Custom Theme JavaScript --> <script src="js/grayscale.js"></script> <script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-53432658-1', 'auto'); ga('send', 'pageview'); </script> </body> </html>
package cl.accenture.android.challenge.presentation.model sealed class FormUiState { object Loading: FormUiState() data class FormError(val errorMessage: String): FormUiState() data class Form( val name: String, val lastName: String, val city: String, val phone: String, val commune: String ): FormUiState() object FormCompleted: FormUiState() }
//! Provider management utilities for use during testing use std::pin::pin; use std::time::Duration; use anyhow::{anyhow, ensure, Context as _, Result}; use nkeys::KeyPair; use serde::Deserialize; use tokio::time::interval; use tokio_stream::wrappers::IntervalStream; use tokio_stream::StreamExt; use tracing::warn; use url::Url; use wasmcloud_control_interface::CtlResponse; use wasmcloud_core::health_subject; /// Helper method for deserializing content, so that we can easily switch out implementations pub fn deserialize<'de, T: Deserialize<'de>>(buf: &'de [u8]) -> Result<T> { serde_json::from_slice(buf).context("failed to deserialize") } /// Arguments to [`assert_start_provider`] pub struct StartProviderArgs<'a> { pub client: &'a wasmcloud_control_interface::Client, pub lattice: &'a str, pub host_key: &'a KeyPair, pub provider_key: &'a KeyPair, pub provider_id: &'a str, pub url: &'a Url, pub config: Vec<String>, } /// Response expected from a successful healthcheck #[derive(Deserialize)] #[serde(deny_unknown_fields)] struct ProviderHealthCheckResponse { #[serde(default)] healthy: bool, #[serde(default)] message: Option<String>, } /// Start a provider, ensuring that the provider starts properly /// /// # Errors /// /// Returns an `Err` if the provider fails to start pub async fn assert_start_provider( StartProviderArgs { client, lattice, host_key, provider_key, provider_id, url, config, }: StartProviderArgs<'_>, ) -> Result<()> { let rpc_client = client.nats_client(); let CtlResponse { success, message, .. } = client .start_provider( &host_key.public_key(), url.as_ref(), provider_id, None, config, ) .await .map_err(|e| anyhow!(e).context("failed to start provider"))?; ensure!(message == ""); ensure!(success); let res = pin!(IntervalStream::new(interval(Duration::from_secs(1))) .take(30) .then(|_| rpc_client.request( health_subject(lattice, &provider_key.public_key()), "".into(), )) .filter_map(|res| { match res { Err(error) => { warn!(?error, "failed to connect to provider"); None } Ok(res) => Some(res), } })) .next() .await .context("failed to perform health check request")?; let ProviderHealthCheckResponse { healthy, message } = deserialize(&res.payload) .map_err(|e| anyhow!(e).context("failed to decode health check response"))?; ensure!(message == None); ensure!(healthy); Ok(()) }
<mat-sidenav-container> <mat-sidenav #leftnav> <cosmic-drawer></cosmic-drawer> </mat-sidenav> <div> <mat-toolbar class="mat-primary"> <button mat-button (click)="leftnav.toggle()"> <mat-icon>menu</mat-icon> </button>&nbsp; <h1>Game Generator</h1> </mat-toolbar> <div id="gen-options"> <cosmic-game-options [games]="settings.games" (change)="onSelectGame($event)"></cosmic-game-options> <alien-level-options [levels]="settings.levels" (change)="onSelectLevel($event)"></alien-level-options> <mat-card> <mat-card-title>Game Setup</mat-card-title> <mat-radio-group [(ngModel)]="settings.setupLevel" (change)="change()"> <mat-radio-button value="" class="mat-primary">Remove none</mat-radio-button> <mat-radio-button value="color" class="mat-primary">Remove those requiring extra color</mat-radio-button> <mat-radio-button value="all" class="mat-primary">Remove all</mat-radio-button> </mat-radio-group> </mat-card> <mat-card> <mat-card-title>Exclude by name</mat-card-title> <mat-form-field> <mat-select multiple [(ngModel)]="settings.namesExcluded" (selectionChange)="change()" placeholder="Select names"> <mat-option *ngFor="let name of namesAll" [value]="name">{{name}}</mat-option> </mat-select> </mat-form-field> </mat-card> <mat-card> <mat-card-title>How to choose</mat-card-title> <mat-form-field> <input matInput type="number" [(ngModel)]="settings.numToChoose" placeholder="Choices per player" step="1" min="1" (change)="restrictNumToChoose()"> </mat-form-field> <div> <mat-checkbox class="mat-primary" (change)="saveSettings()" [(ngModel)]="settings.preventConflicts">Prevent conflicts (like Oracle vs. Magician)</mat-checkbox> </div> </mat-card> </div> <mat-toolbar id="gen-actions"> <span class="space-right alien-0-theme"> <button mat-raised-button class="mat-accent" (click)="draw()" [disabled]="disabled.draw">Draw</button> </span> <span class=""> <button mat-raised-button class="mat-primary" (click)="hide()" [disabled]="disabled.hide"> <mat-icon>visibility_off</mat-icon>&nbsp;Hide</button> </span> <span class="space-right"> <button mat-raised-button class="mat-primary" (click)="show()" [disabled]="disabled.show"> <mat-icon>visibility</mat-icon>&nbsp;Show</button> </span> <span class="space-right alien-1-theme"> <button mat-raised-button class="mat-accent" (click)="redo();" [disabled]="disabled.redo"> <mat-icon>history</mat-icon>&nbsp;Redo</button> </span> <span class="space-right alien-2-theme"> <button mat-raised-button class="mat-accent" (click)="reset()" [disabled]="disabled.reset"> <mat-icon>replay</mat-icon>&nbsp;Reset</button> </span> </mat-toolbar> <p class="mat-body-1" id="gen-status">{{status}} {{state}}</p> <alien-grid [aliens]="aliensToShow"></alien-grid> </div> </mat-sidenav-container>
/* Nombre del programa: ...................Problema: 12. Un triángulo rectángulo tiene un ángulo de 42° 25" y el lado opuesto a este ángulo mide 25.4 cm. Encontrar los otros lados del triángulo. Creado por: .......... Gastelum Nieves Carlos No Control: .................................................14210456 Fecha ......................................................17-02-2017 */ //Librería import Foundation //Declaramos los datos del Triangulo var anguA : Float = 42 + (25/60) //comvertimos de minutos a grados var anguC : Float = 90 //Al ser triángulo rectángulo al menos uno de los ángulos será de 90° var ladA : Float = 25.4 var anguB = 180 - (anguA+anguC) //Se restan los otros ángulos a 180 para obtener el ángulo faltante var ladB = ladA / sin(anguA * Float.pi / 180) //Se divide el Lado A por el seno del ángulo A para obtener la hipotenusa var ladC = sqrt((pow(ladB,2)) - (pow(ladA,2 ))) //Se despeja el teorema de Pitágoras para calcular el último lado //Se guarda en una variable el texto con el problema a resolver let problema = " Problema: " + "\n" + "12. Un triángulo rectángulo tiene un ángulo de 42° 25\" y el lado opuesto a este ángulo mide 25.4 cm. Encontrar los otros lados del triángulo." + "\n \n" //En otra variable diferente se guardan los datos para desplegarse let datos = "Datos: " + "\n" + "Lado A: \(ladA)" + "\n" + "Ángulo A: \(anguA)°" + "\n" + "\n" + "Ángulo C = 90°" + "\n \n" //gardamos la variable el procedimiento let procedimiento = "Procedimiento: " + "\n" + "Ángulo B = 180 - (\(anguA)° + \(anguC)°)" + "\n" + "Lado B = \(ladA)/sen(\(sin(anguA * Float.pi / 180)))" + "\n" + "Lado C = v((\(ladB))^2-(\(ladA))^2)" + "\n \n" //se van guardando los resultados en una variable distinta let resultado = "Resultado: " + "\n" + "Lado A: \(ladA) cm" + "\n" + "Lado B: \(ladB) cm" + "\n" + "Lado C: \(ladC) cm" // desplegamos las variables donde guardamos el texto print(problema,datos,procedimiento,resultado)
from dataclasses import dataclass from pathlib import Path import pytest from unstructured.ingest.connector.fsspec.dropbox import ( DropboxIngestDoc, ) from unstructured.ingest.connector.fsspec.fsspec import ( FsspecIngestDoc, ) from unstructured.ingest.connector.fsspec.sftp import SftpAccessConfig, SimpleSftpConfig from unstructured.ingest.interfaces import ( FsspecConfig, ) @dataclass class FakeConfigDropboxRoot: output_dir = "/fakeuser/fake_output" dir_path = " " download_dir = "/fakeuser/fake_download" path_without_protocol = " " @dataclass class FakeConfigFolder: output_dir = "/fakeuser/fake_output" dir_path = "fake_folder" download_dir = "/fakeuser/fake_download" path_without_protocol = "fake_folder" def test_dropbox_root_succeeds(): """ Test that path joining method works for Dropbox root folder. Note slash in front of remote_file_path. """ dbox = DropboxIngestDoc( connector_config=FakeConfigDropboxRoot, read_config=FakeConfigDropboxRoot, processor_config=FakeConfigDropboxRoot, remote_file_path="/fake_file.txt", ) output_filename = dbox._output_filename download_filename = dbox._tmp_download_file() assert output_filename == Path("/fakeuser/fake_output/fake_file.txt.json") assert download_filename == Path("/fakeuser/fake_download/fake_file.txt") def test_dropbox_root_succeeds2(): """ Test that path joining method works for Dropbox root folder. Note lack of slash in front of remote_file_path. This still works. """ dbox = DropboxIngestDoc( connector_config=FakeConfigDropboxRoot, read_config=FakeConfigDropboxRoot, processor_config=FakeConfigDropboxRoot, remote_file_path="fake_file.txt", ) output_filename = dbox._output_filename download_filename = dbox._tmp_download_file() assert output_filename == Path("/fakeuser/fake_output/fake_file.txt.json") assert download_filename == Path("/fakeuser/fake_download/fake_file.txt") def test_dropbox_folder_succeeds(): """ Test that path joining method works for Dropbox root folder. Note no slash in front of remote_file_path. """ dbox = DropboxIngestDoc( connector_config=FakeConfigFolder, read_config=FakeConfigFolder, processor_config=FakeConfigFolder, remote_file_path="fake_file2.txt", ) output_filename = dbox._output_filename download_filename = dbox._tmp_download_file() assert output_filename == Path("/fakeuser/fake_output/fake_file2.txt.json") assert download_filename == Path("/fakeuser/fake_download/fake_file2.txt") def test_dropbox_folder_fails(): """Test that path joining method gives WRONG path. Note slash in front of remote_file_path. Path joining is sensitive. Note that the path is MISSING the folders.""" dbox = DropboxIngestDoc( connector_config=FakeConfigFolder, read_config=FakeConfigFolder, processor_config=FakeConfigFolder, remote_file_path="/fake_file2.txt", ) output_filename = dbox._output_filename download_filename = dbox._tmp_download_file() assert output_filename == Path("/fake_file2.txt.json") assert download_filename == Path("/fake_file2.txt") def test_fsspec_folder_succeeds(): """ Test that path joining method works for root folder. Note no slash in front of remote_file_path. """ dbox = FsspecIngestDoc( connector_config=FakeConfigFolder, read_config=FakeConfigFolder, processor_config=FakeConfigFolder, remote_file_path="fake_file2.txt", ) output_filename = dbox._output_filename download_filename = dbox._tmp_download_file() assert output_filename == Path("/fakeuser/fake_output/fake_file2.txt.json") assert download_filename == Path("/fakeuser/fake_download/fake_file2.txt") def test_fsspec_folder_fails(): """Test that path joining method gives WRONG path. Note slash in front of remote_file_path. Path joining is sensitive. Note that the path is MISSING the folders.""" fstest = FsspecIngestDoc( connector_config=FakeConfigFolder, read_config=FakeConfigFolder, processor_config=FakeConfigFolder, remote_file_path="/fake_file2.txt", ) output_filename = fstest._output_filename download_filename = fstest._tmp_download_file() assert output_filename == Path("/fake_file2.txt.json") assert download_filename == Path("/fake_file2.txt") def test_post_init_invalid_protocol(): """Validate that an invalid protocol raises a ValueError""" with pytest.raises(ValueError): FsspecConfig(remote_url="ftp://example.com/path/to/file.txt") def test_fsspec_path_extraction_dropbox_root(): """Validate that the path extraction works for dropbox root""" config = FsspecConfig(remote_url="dropbox:// /") assert config.protocol == "dropbox" assert config.path_without_protocol == " /" assert config.dir_path == " " assert config.file_path == "" def test_fsspec_path_extraction_dropbox_subfolder(): """Validate that the path extraction works for dropbox subfolder""" config = FsspecConfig(remote_url="dropbox://path") assert config.protocol == "dropbox" assert config.path_without_protocol == "path" assert config.dir_path == "path" assert config.file_path == "" def test_fsspec_path_extraction_s3_bucket_only(): """Validate that the path extraction works for s3 bucket without filename""" config = FsspecConfig(remote_url="s3://bucket-name") assert config.protocol == "s3" assert config.path_without_protocol == "bucket-name" assert config.dir_path == "bucket-name" assert config.file_path == "" def test_fsspec_path_extraction_s3_valid_path(): """Validate that the path extraction works for s3 bucket with filename""" config = FsspecConfig(remote_url="s3://bucket-name/path/to/file.txt") assert config.protocol == "s3" assert config.path_without_protocol == "bucket-name/path/to/file.txt" assert config.dir_path == "bucket-name" assert config.file_path == "path/to/file.txt" def test_fsspec_path_extraction_s3_invalid_path(): """Validate that an invalid s3 path (that mimics triple slash for dropbox) raises a ValueError""" with pytest.raises(ValueError): FsspecConfig(remote_url="s3:///bucket-name/path/to") def test_sftp_path_extraction_post_init_with_extension(): """Validate that the path extraction works for sftp with file extension""" config = SimpleSftpConfig( remote_url="sftp://example.com/path/to/file.txt", access_config=SftpAccessConfig(username="username", password="password", host="", port=22), ) assert config.file_path == "file.txt" assert config.dir_path == "path/to" assert config.path_without_protocol == "path/to" assert config.access_config.host == "example.com" assert config.access_config.port == 22 def test_sftp_path_extraction_without_extension(): """Validate that the path extraction works for sftp without extension""" config = SimpleSftpConfig( remote_url="sftp://example.com/path/to/directory", access_config=SftpAccessConfig(username="username", password="password", host="", port=22), ) assert config.file_path == "" assert config.dir_path == "path/to/directory" assert config.path_without_protocol == "path/to/directory" assert config.access_config.host == "example.com" assert config.access_config.port == 22 def test_sftp_path_extraction_with_port(): """Validate that the path extraction works for sftp with a non-default port""" config = SimpleSftpConfig( remote_url="sftp://example.com:47474/path/to/file.txt", access_config=SftpAccessConfig(username="username", password="password", host="", port=22), ) assert config.file_path == "file.txt" assert config.dir_path == "path/to" assert config.path_without_protocol == "path/to" assert config.access_config.host == "example.com" assert config.access_config.port == 47474
import { signOut } from "firebase/auth"; import React, { useEffect, useState } from "react"; import { useAuthState } from "react-firebase-hooks/auth"; import { Link, useNavigate } from "react-router-dom"; import auth from "../../firebase.init"; import CancelModal from "./CancelModal"; const MyOrders = () => { const [orders, setOrders] = useState([]); const [user] = useAuthState(auth); const navigate = useNavigate(); const [cancelOrder, setCancelOrder] = useState(null); useEffect(() => { fetch( `https://music-store-server-side.vercel.app/order?customerEmail=${user.email}`, { method: "GET", headers: { authorization: `Bearer ${localStorage.getItem("accessToken")}`, }, } ) .then((res) => { if (res.status === 401 || res.status === 403) { //signOut(auth); //localStorage.removeItem('accessToken'); navigate("/"); } return res.json(); }) .then((data) => setOrders(data)); }, [orders]); return ( <div> <h2 className="text-xl font-semibold text-center py-5 uppercase border-b-2 border-red-100"> My Orders </h2> <div className="overflow-x-auto p-10"> <table className="table table-zebra w-full"> <thead> <tr className="text-center"> <th>SL. No</th> <th>Instrument Name</th> <th>Price</th> <th>Order Quantity</th> <th>Payment</th> <th>Action</th> </tr> </thead> <tbody className="text-center"> {orders.map((order, index) => ( <tr> <th>{index + 1}</th> <td>{order.productName}</td> <td>$ {order.orderPrice}</td> <td>{order.orderQuantity}</td> <td> {!order.paid ? ( <Link to={`/dashboard/myOrders/payment/${order._id}`}> <button className="btn btn-xs bg-black">Pay Now</button> </Link> ) : ( <div className="flex flex-col"> <span className="font-bold">Paid</span> <span> Trans id:{" "} <span className="text-green-500"> {order.transactionId} </span> </span> </div> )} </td> <td> {!order.paid && ( <label htmlFor="cancel-confirm-modal" onClick={() => setCancelOrder(order)} className="btn btn-xs bg-rose-700" > Cancel Order </label> )} </td> </tr> ))} </tbody> </table> </div> {cancelOrder && ( <CancelModal cancelOrder={cancelOrder} setCancelOrder={setCancelOrder} ></CancelModal> )} </div> ); }; export default MyOrders;
<template> <div class="card"> <div class="card-header"> <h3>Users</h3> </div> <div class="card-body"> <div class="table-responsive"> <div v-if="loading" class="">Loading...</div> <table v-if="!loading"> <tr> <th>ID</th> <th>Username</th> <th>Email</th> <th>Active?</th> <th>TokenVersion</th> </tr> <tr v-for="user in users" :key="user.id"> <td>{{ user.id }}</td> <td>{{ user.username }}</td> <td>{{ user.email }}</td> <td>{{ user.isActive }}</td> <td>{{ user.tokenVersion }}</td> </tr> </table> <div class="d-flex justify-content-center"> <Pagination :isLarge="true" :currentPage="currentPage" :totalPages="totalPages" :perPage="perPage" @onpagechanged="onPageChanged" /> </div> </div> </div> </div> </template> <script> export default { data() { return { loading: true, users: [], metaTag: null, currentPage: 1, perPage: 10, totalPages: null, } }, methods: { onPageChanged(pageNumber) { //console.log(pageNumber) this.currentPage = pageNumber this.fetchData() }, fetchData() { this.loading = true //console.log('Fetching...') fetch(process.env.VUE_APP_API_BASE_URL + `/users?page=${this.currentPage}&limit=${this.perPage}`, { method: 'get', credentials: 'include', headers: { Authorization: `bearer ${this.$store.state.accessToken}` }, }) .then((res) => res.json()) .then((data) => { this.users = data.users this.totalPages = data.totalPages this.loading = false //console.log(data) }) .catch((err) => console.log(err.message)) }, }, } </script> <style lang="scss" scoped></style>
import { DataTypes, UUIDV1, Model, Sequelize, STRING } from 'sequelize' interface MangaFavoriteAttributes { id: number; title: string; image: string; score: number; popularity: number; chapters: number; status: string; synopsis: string; genres: string; price: number; } module.exports = (sequelize: any, DataTypes: any) => { class MangaFavorites extends Model implements MangaFavoriteAttributes { id!: number; title!: string; image!: string; score!: number; popularity!: number; chapters!: number; status!: string; synopsis!: string; genres!: string; price!: number; static associate(models: any) { MangaFavorites.belongsToMany(models.Users, { through: 'manga_favorite' }) } } MangaFavorites.init({ id: { type: DataTypes.UUID, defaultValue: DataTypes.UUIDV4, allowNull: false, primaryKey: true, }, title: { type: DataTypes.STRING, allowNull: false, unique: true, }, image: { type: DataTypes.STRING, }, score: { type: DataTypes.FLOAT, defaultValue: 5, }, popularity: { type: DataTypes.FLOAT, }, chapters: { type: DataTypes.INTEGER, }, status: { type: DataTypes.STRING, }, synopsis: { type: DataTypes.TEXT, }, genres: { type: DataTypes.STRING, }, price: { type: DataTypes.FLOAT, allowNull: false, }, }, { sequelize, timestamps: false, modelName: "MangaFavorites" }) return MangaFavorites }
import React, {useState, useEffect} from 'react' import { useNavigate } from 'react-router-dom'; import axios from 'axios'; import GuestNavBar from './GuestNavBar'; import UserNavBar from './UserNavBar'; import generalStyle from '../css/general.module.css' import formStyle from '../css/form.module.css' const ArtistForm = () => { // search variable const [searchItem, setSearchItem] = useState(''); // user variable const [user, setUser] = useState({}); const [loggedIn, setLoggedIn] = useState(false); // redirect const navigate = useNavigate(); // redirects to search results const onSubmitHandler = (e) => { e.preventDefault(); navigate("/search/artists/results/" + searchItem) } useEffect(()=>{ axios.get("http://localhost:8000/api/users/checkUser", {withCredentials:true}) .then(res=>{ console.log("✅", res) if(res.data.results){ //this means the user is logged in and can accees this page setUser(res.data.results) setLoggedIn(true); } }) .catch(err=>{ //this means someone who is not logged in tried to access the dashboard console.log("err when gettign logged in user", err) }) }, []) return ( <div className={generalStyle} style={{"height": "100vh"}}> { loggedIn ? <UserNavBar /> : <GuestNavBar /> } <div className={formStyle.search}> <h1>Search for Artists</h1> <form onSubmit={onSubmitHandler}> <input placeholder="What artist would you like to search for?" type="text" onChange={e => setSearchItem(e.target.value)}/> <button>Search</button> </form> </div> {/* </motion.div> */} </div> ) } export default ArtistForm
// MIT License // // Copyright (c) 2024 Daniel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import Foundation /// Base presenter for UICollectionView or UITableView public protocol CollectionPresentable: Presenter { /// Sections in this collection view. @MainActor var sections: [CollectionSectionPresentable] { get } } open class CollectionPresenter<View, SectionType: CollectionSectionPresentable>: ViewPresenter<View>, CollectionPresentable { @MainActor private var _sections: [SectionType] = [] @MainActor public var sections: [CollectionSectionPresentable] { _sections } @MainActor public var typedSections: [SectionType] { get { _sections } set { setSections(newValue) } } @MainActor public func setSections(_ sections: [SectionType], animated: Bool = false, completion: (()->Void)? = nil) { // If new sections are already in the parent, do not need remove then add, // so just remove children not exist in the new sections. let oldValue = _sections let newSet = Set(sections.map({ ObjectIdentifier($0) })) for old in oldValue { if !newSet.contains(ObjectIdentifier(old)) { remove(child: old) } } _sections = sections for section in sections { add(child: section) } setState(updater: {}, context: { $0.reloadData() $0.animated = animated $0.forceDisableAnimation = !animated }, completion: completion) } }
package com.codingbox.core3.domain.web.basic; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.Map; @Controller public class RequestParamController { /* 반환 타입이 없고, 응답(response) 에값을 집어넣으면, view 조회 x */ @RequestMapping("/request-param-v1") public void requestParamV1(HttpServletRequest request, HttpServletResponse response) throws IOException { String username = request.getParameter("username"); int age = Integer.parseInt(request.getParameter("age")); System.out.println("username : " + username); System.out.println("age : " + age); response.getWriter().write("ok"); } /* @RequestParam -파라미터 이름으로 바인딩 - @RequestParam("username") String memberName=String memberName = request.getParameter("username"); @ResponseBody -view 조회를 무시하고, HTTP message body에 직접 해당 내용을 입력 */ @ResponseBody @RequestMapping("/request-param-v2") public String requestParamV2(@RequestParam("username")String memberName, @RequestParam("age") int memberAge) { System.out.println("username : " + memberName); System.out.println("age : " + memberAge); return "ok"; } /* @RequestParam 사용 - HTTP 파라미터 이름이 변수 이름과 같으면 @RequestParam("xxxx") 생략 가능 */ @ResponseBody @RequestMapping("/request-param-v3") public String requestParamV3(@RequestParam String username, @RequestParam int age) { System.out.println("username : " + username); System.out.println("age : " + age); return "ok"; } /* @RequestParam -String,int 등의 단순 타입이면 @RequestParam 도 생략 가능 -required == false로 적용한다. */ @ResponseBody @RequestMapping("/request-param-v4") public String requestParamV4( String username, int age) { System.out.println("username : " + username); System.out.println("age : " + age); return "ok"; } /* @RequestParam - required = true : 반드시 파라미터 값이 들어와야 한다. int age -> Integer age - null을 int에 입력하는 것은 불가능, 따라서 Integer변경해야함. */ @ResponseBody @RequestMapping("/request-param-required") public String requestParamRequired( @RequestParam(required = true) String username, @RequestParam(required = false) Integer age) { System.out.println("username : " + username); System.out.println("age : " + age); return "ok"; } /* @RequestParam -defaultValue 사용시 기본 값 세팅 -빈 문자의 경우에도 적용 (/request-param-dafault?username= ) */ @ResponseBody @RequestMapping("/request-param-default") public String requestParamDefault( @RequestParam(required = true, defaultValue = "guest") String username, @RequestParam(required = false, defaultValue = "-1") Integer age) { System.out.println("username : " + username); System.out.println("age : " + age); return "ok"; } /* -@RequestParam -Map(key-value) */ @ResponseBody @RequestMapping("/request-param-map") public String requestParamMap(@RequestParam Map<String,Object> paramMap) { System.out.println("username : " + paramMap.get("username")); System.out.println("age : " + paramMap.get("age")); return "ok"; } @ResponseBody @RequestMapping("/model-attribute-v1") public String modelAttributeV1(@RequestParam String username,@RequestParam int age){ HelloData helloData = new HelloData(); helloData.setUsername(username); helloData.setAge(age); System.out.println("username : " + helloData.getUsername()); System.out.println("age : " + helloData.getAge()); return "ok"; } /* @ModelAttribute 사용해서 아래 과정들을 자동화 한다. (@RequestParam String username,@RequestParam int age){ HelloData helloData = new HelloData(); helloData.setUsername(username); helloData.setAge(age); */ @ResponseBody @RequestMapping("/model-attribute-v2") public String modelAttributeV2(@ModelAttribute HelloData helloData){ System.out.println("username : " + helloData.getUsername()); System.out.println("age : " + helloData.getAge()); System.out.println("helloDAt : " + helloData.toString()); return "ok"; } /* @ModelAttribute 생략가능 - String,int 같은 단순 타입 : @RequestParam - 사용자 정의 객체 : @ModelAttribute */ @ResponseBody @RequestMapping("/model-attribute-v3") public String modelAttributeV3(HelloData helloData){ System.out.println("username : " + helloData.getUsername()); System.out.println("age : " + helloData.getAge()); System.out.println("helloDAt : " + helloData.toString()); return "ok"; } }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <script src="https://cdn.ckeditor.com/4.17.0/standard/ckeditor.js"></script> <link href="https://fonts.googleapis.com/css2?family=Libre+Baskerville:ital,wght@0,400;0,700;1,400&family=Open+Sans:ital,wght@0,300;0,400;0,500;0,600;0,700;0,800;1,300;1,400;1,500;1,600;1,700;1,800&display=swap" rel="stylesheet"> <link href="https://cdn.quilljs.com/1.3.6/quill.snow.css" rel="stylesheet"> <link rel="stylesheet" type="text/css" href="https://celionatti.github.io/blog-template/assets/css/admin-style.css"> <title>Admin Create Post | New Blog Template 2023</title> </head> <body> <header> <div class="nav-overlay"></div> <span role="button" class="menu-icon"> <ion-icon name="menu-outline"></ion-icon> </span> <a href="#" class="logo-wrapper td-none"> <div><span>B</span>LOG</div> </a> <nav> <ul class="nav-menu"> <li class="nav-item"> <a href="#"> <ion-icon name="person-circle-outline" class="nav-icon"></ion-icon> Celio Natti <ion-icon name="chevron-down-outline" class="nav-icon"></ion-icon> </a> <ul class="dropdown"> <li><a href="#">Logout</a></li> </ul> </li> </ul> </nav> </header> <div class="page-wrapper"> <div class="sidebar"> <div class="sidebar-author-mobile"> <img class="avatar" src="/assets/images/avatar/user.webp" alt=""> <h3 class="author-name">Celio Natti</h3> <a href="#" class="logout-link">Logout</a> </div> <ul class="list-menu"> <li> <a href="#"> <ion-icon name="speedometer-outline" class="menu-icon"></ion-icon> Dashboard <ion-icon name="chevron-forward-outline" class="chevron-forward"></ion-icon> </a> </li> <li> <a href="#"> <ion-icon name="reader-outline" class="menu-icon"></ion-icon> Post <ion-icon name="chevron-forward-outline" class="chevron-forward"></ion-icon> </a> </li> <li> <a href="#"> <ion-icon name="grid-outline" class="menu-icon"></ion-icon> Topics <ion-icon name="chevron-forward-outline" class="chevron-forward"></ion-icon> </a> </li> <li> <a href="#"> <ion-icon name="people-outline" class="menu-icon"></ion-icon> Users <ion-icon name="chevron-forward-outline" class="chevron-forward"></ion-icon> </a> </li> <li> <a href="#"> <ion-icon name="lock-closed-outline" class="menu-icon"></ion-icon> Roles <ion-icon name="chevron-forward-outline" class="chevron-forward"></ion-icon> </a> </li> <li> <a href="#"> <ion-icon name="key-outline" class="menu-icon"></ion-icon> Permissions <ion-icon name="chevron-forward-outline" class="chevron-forward"></ion-icon> </a> </li> <li> <a href="#"> <ion-icon name="reader-outline" class="menu-icon"></ion-icon> Collections <ion-icon name="chevron-forward-outline" class="chevron-forward"></ion-icon> </a> </li> </ul> </div> <!-- ==== PAGE CONTENT ==== --> <div class="page-content"> <div class="admin-container"> <form action="text.php" method="post" class="admin-form md-box" enctype="multipart/form-data"> <h1 class="center form-title">Create Post</h1> <div class="input-group"> <label for="title">Title</label> <input type="text" name="title" id="title" class="input-control"> </div> <div class="input-group"> <label for="post-editor">Body</label> <textarea name="editor"></textarea> </div> <div class="post-details"> <div class="select-topic-wrapper"> <div class="input-group"> <label for="topic">Topic</label> <select name="topic" id="topic" class="input-control"> <option value=""></option> <option value="business">Business</option> <option value="life-lesson">Life Lesson</option> <option value="journal">Journal</option> </select> </div> </div> <div class="image-wrapper"> <input type="file" name="image" class="hide image-input"> <button type="button" class="image-btn bg-image"> <span class="choose-image-label"> <ion-icon name="image-outline" class="image-outline"></ion-icon> <span>Choose Image</span> </span> </button> </div> </div> <div class="input-group"> <label for="published"> <input type="checkbox" name="published" id="published"> Publish </label> </div> <div class="input-group"> <button type="submit" class="btn primary-btn big-btn">Save</button> </div> </form> </div> </div> </div> <script type="module" src="https://unpkg.com/[email protected]/dist/ionicons/ionicons.esm.js"></script> <script nomodule src="https://unpkg.com/[email protected]/dist/ionicons/ionicons.js"></script> <script src="https://cdn.quilljs.com/1.3.6/quill.js"></script> <script src="https://celionatti.github.io/blog-template/assets/js/admin.js"></script> <!-- <script src="https://celionatti.github.io/blog-template/assets/js/post_quill_editor.js"></script> --> <!-- <script src="../../assets/js/post_quill_editor.js"></script> --> <script> CKEDITOR.replace('editor'); // PREVIEW POST IMAGE const imageBtn = document.querySelector('.image-btn'); const imageInput = document.querySelector('.image-input'); const chooseImageLabel = document.querySelector('.choose-image-label'); imageBtn.addEventListener('click', function () { imageInput.click(); }); imageInput.addEventListener('change', function () { const file = imageInput.files[0]; if (file) { const reader = new FileReader(); reader.onload = function (e) { imageBtn.style.backgroundImage = `url(${e.target.result})`; imageBtn.style.height = '150px'; imageBtn.style.border = 'none'; chooseImageLabel.classList.toggle('hide'); }; reader.readAsDataURL(file); } }); </script> </body> </html>
import Vue from 'vue' import Router from 'vue-router' Vue.use(Router) /* Layout */ import Layout from '@/layout' import layout from '@/layout/index.vue' /** * Note: sub-menu only appear when route children.length >= 1 * Detail see: https://panjiachen.github.io/vue-element-admin-site/guide/essentials/router-and-nav.html * * hidden: true if set true, item will not show in the sidebar(default is false) * alwaysShow: true if set true, will always show the root menu * if not set alwaysShow, when item has more than one children route, * it will becomes nested mode, otherwise not show the root menu * redirect: noRedirect if set noRedirect will no redirect in the breadcrumb * name:'router-name' the name is used by <keep-alive> (must set!!!) * meta : { roles: ['admin','editor'] control the page roles (you can set multiple roles) title: 'title' the name show in sidebar and breadcrumb (recommend set) icon: 'svg-name'/'el-icon-x' the icon show in the sidebar breadcrumb: false if set false, the item will hidden in breadcrumb(default is true) activeMenu: '/example/list' if set path, the sidebar will highlight the path you set } */ /** * constantRoutes * a base page that does not have permission requirements * all roles can be accessed */ export const constantRoutes = [ { path: '/login', component: () => import('@/views/login/index'), //hidden:true————不显示在侧边导航栏里 hidden: true }, { path: '/404', component: () => import('@/views/404'), hidden: true }, { path: '/', component: Layout, meta: { title: '我的主页', icon: 'el-icon-s-home' }, redirect: '/dashboard', children: [ { path: 'dashboard', name: 'Dashboard', component: () => import('@/views/admin/home/index.vue'), meta: { title: '仪表盘', icon: 'dashboard' } }, { path: 'userInfo', name: 'UserInfo', component: () => import('@/views/admin/home/userInfo.vue'), meta: { title: '个人信息', icon: 'el-icon-user-solid' } } ] }, { path: '/verify', component: Layout, redirect: '/overview', name: 'Verify', meta: { title: '内容审核', icon: 'el-icon-s-platform' }, children: [ { path: 'reportReview', name: 'ReportReview', component: () => import('@/views/admin/verify/reportReview.vue'), meta: { title: '举报信息审核', icon: 'el-icon-warning' } }, { path: 'newsReview', name: 'NewsReview', component: () => import('@/views/admin/verify/newsReview.vue'), meta: { title: '公告信息审核', icon: 'el-icon-s-comment' } } ] }, { path: '/manage', component:layout, redirect: '/manage/userManage', name:'Manage', meta: {title: '系统管理',icon: 'el-icon-s-cooperation'}, children: [ { path: 'userManage', name:'UserManage', component: () => import('@/views/admin/manage/user.vue'), meta: {title: '用户管理',icon: 'el-icon-user-solid'} }, { path: 'orderManage', name:'OrderManage', component: () => import('@/views/admin/manage/order.vue'), meta: {title: '订单管理',icon: 'el-icon-s-order'} }, { path: 'questionManage', name:'QuestionManage', component: () => import('@/views/admin/manage/question.vue'), meta: {title: '论坛管理',icon: 'el-icon-s-comment'} } ] }, { path: 'https://www.google.com', component: Layout, meta: {title: 'Github仓库',icon: 'el-icon-coin'}, }, // 404 page must be placed at the end !!! { path: '*', redirect: '/404', hidden: true } ] const createRouter = () => new Router({ // mode: 'history', // require service support scrollBehavior: () => ({ y: 0 }), routes: constantRoutes }) const router = createRouter() // Detail see: https://github.com/vuejs/vue-router/issues/1234#issuecomment-357941465 export function resetRouter() { const newRouter = createRouter() router.matcher = newRouter.matcher // reset router } export default router
import * as React from 'react' import { Typography, Divider } from '@mui/material' import { Link } from 'react-router-dom' import LoadingIcon from '../components/LoadingIcon/LoadingIcon' import MovieCard from '../components/MovieCard/MovieCard' const Home = () => { const api_key = process.env.REACT_APP_API_KEY; const [loading, setLoading] = React.useState(true) const [trendingList, setTrendingList] = React.useState({}) const [popularList, setPopularList] = React.useState({}) const [topRatedList, setTopRatedList] = React.useState({}) const [upcomingList, setUpcomingList] = React.useState({}) React.useEffect(() => { setLoading(true) fetch(`https://api.themoviedb.org/3/movie/upcoming?api_key=${api_key}&language=es&page=1`) .then((response) => response.json()) .then(data => setUpcomingList(data)) .catch((error) => console.error(error)) fetch(`https://api.themoviedb.org/3/trending/movie/day?api_key=${api_key}&language=es`) .then((response) => response.json()) .then(data => setTrendingList(data)) .catch((error) => console.error(error)) fetch(`https://api.themoviedb.org/3/discover/movie?api_key=${api_key}&language=es&sort_by=vote_average.desc&include_adult=false&page=1&vote_count.gte=7500`) .then((response) => response.json()) .then(data => setTopRatedList(data)) .catch((error) => console.error(error)) fetch(`https://api.themoviedb.org/3/movie/popular?api_key=${api_key}&language=es&page=1`) .then((response) => response.json()) .then(data => setPopularList(data)) .catch((error) => console.error(error)) .finally(() => setTimeout(() => { setLoading(false) }, 500)) // eslint-disable-next-line react-hooks/exhaustive-deps }, []) if (loading) { return <LoadingIcon /> } else { return ( <div className='my-container'> <div className='movie-images-list'> <div className='see-more'> <Typography variant="h5" component="h3">TRENDING MOVIES</Typography> <Typography variant="h7" component={Link} sx={{ marginRight: 1 }} to='/trending'>Ver mas</Typography> </div> <Divider sx={{ borderColor: `primary.light`, margin: '0.6rem 0' }} /> <section className="cards-container-home"> {(trendingList.results.slice(0, 4)).map((movie, index) => <MovieCard key={index} id={movie.id} title={movie.original_title} img={movie.poster_path === null ? 'https://images.pngnice.com/download/2007/Movie-PNG-Transparent-Image.png' : `https://image.tmdb.org/t/p/w500${movie.poster_path}`} rating={movie.vote_average} overview={movie.overview !== '' ? movie.overview : 'No hay descripcion disponible para esta película'} />)} </section> </div> <div className='movie-images-list'> <div className='see-more'> <Typography variant="h5" component="h3">POPULAR MOVIES</Typography> <Typography variant="h7" component={Link} sx={{ marginRight: 1 }} to='/popular/page/1'>Ver mas</Typography> </div> <Divider sx={{ borderColor: `primary.light`, margin: '0.6rem 0' }} /> <section className="cards-container-home"> {(popularList.results.slice(0, 4)).map((movie, index) => <MovieCard key={index} id={movie.id} title={movie.original_title} img={movie.poster_path === null ? 'https://images.pngnice.com/download/2007/Movie-PNG-Transparent-Image.png' : `https://image.tmdb.org/t/p/w500${movie.poster_path}`} rating={movie.vote_average} overview={movie.overview !== '' ? movie.overview : 'No hay descripcion disponible para esta película'} />)} </section> </div> <div className='movie-images-list'> <div className='see-more'> <Typography variant="h5" component="h3">TOP RATED MOVIES</Typography> <Typography variant="h7" component={Link} sx={{ marginRight: 1 }} to='/top_rated/page/1'>Ver mas</Typography> </div> <Divider sx={{ borderColor: `primary.light`, margin: '0.6rem 0' }} /> <section className="cards-container-home"> {(topRatedList.results.slice(0, 4)).map((movie, index) => <MovieCard key={index} id={movie.id} title={movie.original_title} img={movie.poster_path === null ? 'https://images.pngnice.com/download/2007/Movie-PNG-Transparent-Image.png' : `https://image.tmdb.org/t/p/w500${movie.poster_path}`} rating={movie.vote_average} overview={movie.overview !== '' ? movie.overview : 'No hay descripcion disponible para esta película'} />)} </section> </div> <div className='movie-images-list'> <div className='see-more'> <Typography variant="h5" component="h3">UPCOMING MOVIES</Typography> <Typography variant="h7" component={Link} sx={{ marginRight: 1 }} to='/upcoming/page/1'>Ver mas</Typography> </div> <Divider sx={{ borderColor: `primary.light`, margin: '0.6rem 0' }} /> <section className="cards-container-home"> {(upcomingList.results.slice(0, 4)).map((movie, index) => <MovieCard key={index} id={movie.id} title={movie.original_title} img={movie.poster_path === null ? 'https://images.pngnice.com/download/2007/Movie-PNG-Transparent-Image.png' : `https://image.tmdb.org/t/p/w500${movie.poster_path}`} rating={movie.vote_average} overview={movie.overview !== '' ? movie.overview : 'No hay descripcion disponible para esta película'} />)} </section> </div> </div> ) } } export default Home
import { useForm, SubmitHandler } from "react-hook-form"; import { useHistory } from "react-router-dom"; import { useState } from "react"; import axios from "axios"; import { useAppSelector, useAppDispatch } from "../../app/hooks"; import { logging, loggedInSuccess, loggedInError, twofasuccess, twofaError, UserLogin, } from "./userSlice"; import MPIN from "./MPIN"; import md5 from "md5"; import { isMobile } from "react-device-detect"; import "./Login.css"; import { ILoginRequest } from "../../types/Request/IloginRequest"; // import "../Home/style1.css"; interface ILoginInput { clientid: string; password: string; brokerId: string; source: string; pin: number; } const Login = () => { const [passwordShown, setPasswordShown] = useState(false); const { register, formState: { errors }, handleSubmit, } = useForm<ILoginInput>(); const history = useHistory(); const user = useAppSelector((state) => state.user); const dispatch = useAppDispatch(); var Source = ""; if (isMobile) { Source = "Mobile"; } else { Source = "Web"; } const onSubmit: SubmitHandler<ILoginInput> = (data) => { dispatch(logging(data.clientid + "-TECXLABS")); //console.log(data); //dispatch(loggedInSuccess("User")); const loginRequest: ILoginRequest = { uid: data.clientid.toLocaleUpperCase() + "-TECXLABS", pwd: md5(data.password), brokerId: "TECXLABS", source: Source, }; //var querystring = JSON.stringify(loginRequest); dispatch(UserLogin(loginRequest)); }; const togglePasswordVisiblity = () => { setPasswordShown(passwordShown ? false : true); }; function onInput(event: any) { event.target.value = event.target.value.toLocaleUpperCase(); } if (user.isAuthenticated) { history.push("/home"); } return ( <div className="retail_login"> <div className="Login container-login-main"> <div className="wrap-login-main"> <div className="wrap-login-in"> <div className="loginform"> {user.isPasswordCheked === false ? ( <form onSubmit={handleSubmit(onSubmit)}> <div className="text-center logo"> <img src="../images/logo.svg" /> <span>MALAMAAL</span> </div> <h3 className="login-main-form-title">Sign in</h3> <div className="form"> <input {...register("clientid", { required: "User Id is required.", })} className="form__input" id="clientid" name="clientid" placeholder=" " type="text" autoFocus onInput={(e) => onInput(e)} /> <label htmlFor="clientid" className="form__label"> User ID </label> <span className="icon-inside"> <img src="../images/user-ico.png" /> </span> </div> <p>{errors.clientid && errors.clientid.message}</p> <div className="form"> <input {...register("password", { required: "Password is required", })} className="form__input" id="password" name="password" placeholder=" " type={passwordShown ? "text" : "password"} /> <label htmlFor="password" className="form__label"> Password </label> <span className="icon-inside"> <img src="../images/pswd-ico.png" /> </span> <span className={ "toggle-password " + (passwordShown ? "pass-eye-slash" : "pass-eye") } onClick={togglePasswordVisiblity} ></span> </div> <p>{errors.password && errors.password.message}</p> <div className="container-login-main-form-btn p-t-25"> <button type="submit" className="btn btn-primary login-main-form-btn" > SIGN IN </button> </div> <div className="text-right w-full"> <a href="/forgotpassword" id="frgt-clk" className="lf"> FORGOT PASSWORD? </a> </div> </form> ) : user.SetPassword ? ( "SetPasword Window Here" ) : user.SetPassword ? ( "SetPasword Window Here" ) : ( <MPIN /> )} </div> </div> </div> </div> </div> ); }; export default Login;
a:5:{s:2:"id";s:8:"18678475";s:4:"info";a:4:{s:6:"Title:";s:19:"An Overview of MODX";s:7:"Author:";s:15:"Shaun McCormick";s:16:"Last Changed by:";s:12:"Mark Hamstra";s:12:"Wiki Markup:";s:34:"[revolution20:An Overview of MODX]";}s:6:"parent";s:8:"18678198";s:6:"source";s:5077:"\\ h2. What is MODX? MODX is a Content Application Platform. What does this mean? Well, that depends on who you are: !avgjoe.png|align=right! h3. End-Users (Average Joe) MODX offers you a system that lets you publish your offline content onto the web in any form, shape or presence you want. It also offers a completely customizable backend interface that you can make as simple (or as complex) as you like. You can setup everything from a simple site, to a blog, to a full-scale web presence with MODX, and keep your admin interface simple and usable. Drag and drop your webpages around to reorder and move them. Get a full WYSIWYG view of your Resources. Leave Resources unpublished before you finish them. Schedule Resources to publish at certain times. MODX helps you organize your content the way you want it, and get stellar built-in SEO results. MODX is fully, 100% Friendly URL compatible, so getting mysite.com/my/own/custom/url.html is incredibly simple, and as easy as structuring your site that way. !coolcarl.png|align=right! h3. Designers (Cool Carl) Ever wanted complete freedom with your HTML and CSS? Tired of hacking existing systems to get your design to work the way you comp&#39;ed it? MODX does not generate one single line of HTML - it leaves the front-end design up to you. You can use MODX as your Content Management System (CMS) of choice, as MODX offers completely flexible templating and no-holds-barred content delivery. Put your CSS and images where you want them. And once you&#39;re done designing, either hand off the development duties to your developer, or point-and-click install Extras straight from within the manager. Simple. !badassbilly.png|align=right! h3. Developers (Badass Billy) You&#39;ve looked at different CMSes, but have found developing in them to be either a mishmash of too many unconnected code pieces, or simply not powerful or elegant enough. You&#39;ve looked at PHP frameworks, and have found they have the power, but don&#39;t do Content Management nor have a good enough UI for your clients. You want the power and flexibility of a framework, with the UI and content management of a CMS. Enter MODX Revolution. A completely flexible, powerful and robust API, built on OOP principles and using a PDO-powered Object Relational Model (ORM) called [xPDO|xPDO20:Home]. Add in a rich, [Sencha|http://sencha.com]\-powered UI for your clients, that&#39;s fully customizable. Custom properties and sets. Internationalization support. Package distribution built-in so you can pack up your code, and distribute it across any Revolution install. Add custom manager pages to run entire applications within MODX. h2. Basic Concepts MODX, in essence, has a ton of moving parts. But the basics parts are: h3. Resources [Resources] are basically a webpage location. It can be actual HTML content, or a file, forwarding link, or a symlink, or anything else. h3. Templates [Templates] are the house a Resource lives in. They usually contain the footer and header for a page. h3. Template Variables [Template Variables] (TVs) are custom fields for a Template that allow the user to assign dynamic values to a Resource. A great example would be a &#39;tags&#39; TV that allows you to specify tags for a Resource. You can have an unlimited number of TVs per page. h3. Chunks [Chunks] are simply small blocks of content, be it whatever you want inside it. They can contain [Snippets], or any other Element type (Snippet, Chunk, TV, etc). h3. Snippets [Snippets] are dynamic bits of PHP code that run when the page is loaded. They can do anything you can code, including building custom menus, grabbing custom data, tagging elements, processing forms, grabbing tweets, etc. h3. Plugins Plugins are event hooks that run whenever an event is fired. They are usually used for extending the Revolution core to do something during a part of the loading process - such as stripping out bad words in content, adding dictionary links to words, managing redirects for old pages, etc. h3. System Settings System Settings give you near infinite configuration options. Most of these are set the best way they should be, but some things (such as [friendly urls|revolution20:Using Friendly URLs]) are disabled by default&amp;nbsp;or could be improved for your specific needs just by changing a setting value. After installation, head over to System &gt; System Settings in the Manager and browse through the available options. Definitely check out the &quot;Site&quot; area (use the dropdown that says &quot;Filter on area...&quot;), there are some interesting things there for you. h2. So What Happens on a Request? MODX loads the requested [Resource|Resources], fetches that Resource&#39;s [Template|Templates], and then places the Resource&#39;s content in that Template. MODX then parses the resulting combined content, including any tags that might be in it, in the order they are reached. From there, it outputs the response to the user&#39;s browser. h2. See Also {pagetree:root=An Overview of MODX} {scrollbar}";s:8:"versions";a:17:{i:0;a:3:{s:2:"id";s:8:"18678475";s:3:"ver";s:1:"1";s:4:"code";s:5077:"\\ h2. What is MODX? MODX is a Content Application Platform. What does this mean? Well, that depends on who you are: !avgjoe.png|align=right! h3. End-Users (Average Joe) MODX offers you a system that lets you publish your offline content onto the web in any form, shape or presence you want. It also offers a completely customizable backend interface that you can make as simple (or as complex) as you like. You can setup everything from a simple site, to a blog, to a full-scale web presence with MODX, and keep your admin interface simple and usable. Drag and drop your webpages around to reorder and move them. Get a full WYSIWYG view of your Resources. Leave Resources unpublished before you finish them. Schedule Resources to publish at certain times. MODX helps you organize your content the way you want it, and get stellar built-in SEO results. MODX is fully, 100% Friendly URL compatible, so getting mysite.com/my/own/custom/url.html is incredibly simple, and as easy as structuring your site that way. !coolcarl.png|align=right! h3. Designers (Cool Carl) Ever wanted complete freedom with your HTML and CSS? Tired of hacking existing systems to get your design to work the way you comp&#39;ed it? MODX does not generate one single line of HTML - it leaves the front-end design up to you. You can use MODX as your Content Management System (CMS) of choice, as MODX offers completely flexible templating and no-holds-barred content delivery. Put your CSS and images where you want them. And once you&#39;re done designing, either hand off the development duties to your developer, or point-and-click install Extras straight from within the manager. Simple. !badassbilly.png|align=right! h3. Developers (Badass Billy) You&#39;ve looked at different CMSes, but have found developing in them to be either a mishmash of too many unconnected code pieces, or simply not powerful or elegant enough. You&#39;ve looked at PHP frameworks, and have found they have the power, but don&#39;t do Content Management nor have a good enough UI for your clients. You want the power and flexibility of a framework, with the UI and content management of a CMS. Enter MODX Revolution. A completely flexible, powerful and robust API, built on OOP principles and using a PDO-powered Object Relational Model (ORM) called [xPDO|xPDO20:Home]. Add in a rich, [Sencha|http://sencha.com]\-powered UI for your clients, that&#39;s fully customizable. Custom properties and sets. Internationalization support. Package distribution built-in so you can pack up your code, and distribute it across any Revolution install. Add custom manager pages to run entire applications within MODX. h2. Basic Concepts MODX, in essence, has a ton of moving parts. But the basics parts are: h3. Resources [Resources] are basically a webpage location. It can be actual HTML content, or a file, forwarding link, or a symlink, or anything else. h3. Templates [Templates] are the house a Resource lives in. They usually contain the footer and header for a page. h3. Template Variables [Template Variables] (TVs) are custom fields for a Template that allow the user to assign dynamic values to a Resource. A great example would be a &#39;tags&#39; TV that allows you to specify tags for a Resource. You can have an unlimited number of TVs per page. h3. Chunks [Chunks] are simply small blocks of content, be it whatever you want inside it. They can contain [Snippets], or any other Element type (Snippet, Chunk, TV, etc). h3. Snippets [Snippets] are dynamic bits of PHP code that run when the page is loaded. They can do anything you can code, including building custom menus, grabbing custom data, tagging elements, processing forms, grabbing tweets, etc. h3. Plugins Plugins are event hooks that run whenever an event is fired. They are usually used for extending the Revolution core to do something during a part of the loading process - such as stripping out bad words in content, adding dictionary links to words, managing redirects for old pages, etc. h3. System Settings System Settings give you near infinite configuration options. Most of these are set the best way they should be, but some things (such as [friendly urls|revolution20:Using Friendly URLs]) are disabled by default&amp;nbsp;or could be improved for your specific needs just by changing a setting value. After installation, head over to System &gt; System Settings in the Manager and browse through the available options. Definitely check out the &quot;Site&quot; area (use the dropdown that says &quot;Filter on area...&quot;), there are some interesting things there for you. h2. So What Happens on a Request? MODX loads the requested [Resource|Resources], fetches that Resource&#39;s [Template|Templates], and then places the Resource&#39;s content in that Template. MODX then parses the resulting combined content, including any tags that might be in it, in the order they are reached. From there, it outputs the response to the user&#39;s browser. h2. See Also {pagetree:root=An Overview of MODX} {scrollbar}";}i:1;a:3:{s:2:"id";s:8:"41484358";s:3:"ver";s:1:"1";s:4:"code";s:4481:"\\ h2. What is MODX? MODX is a Content Application Platform. What does this mean? Well, that depends on who you are: !avgjoe.png|align=right! h3. End-Users (Average Joe) MODX offers you a system that lets you publish your offline content onto the web in any form, shape or presence you want. It also offers a completely customizable backend interface that you can make as simple (or as complex) as you like. You can setup everything from a simple site, to a blog, to a full-scale web presence with MODX, and keep your admin interface simple and usable. Drag and drop your webpages around to reorder and move them. Get a full WYSIWYG view of your Resources. Leave Resources unpublished before you finish them. Schedule Resources to publish at certain times. MODX helps you organize your content the way you want it, and get stellar built-in SEO results. MODX is fully, 100% Friendly URL compatible, so getting mysite.com/my/own/custom/url.html is incredibly simple, and as easy as structuring your site that way. !coolcarl.png|align=right! h3. Designers (Cool Carl) Ever wanted complete freedom with your HTML and CSS? Tired of hacking existing systems to get your design to work the way you comp&#39;ed it? MODX does not generate one single line of HTML - it leaves the front-end design up to you. You can use MODX as your Content Management System (CMS) of choice, as MODX offers completely flexible templating and no-holds-barred content delivery. Put your CSS and images where you want them. And once you&#39;re done designing, either hand off the development duties to your developer, or point-and-click install Extras straight from within the manager. Simple. !badassbilly.png|align=right! h3. Developers (Badass Billy) You&#39;ve looked at different CMSes, but have found developing in them to be either a mishmash of too many unconnected code pieces, or simply not powerful or elegant enough. You&#39;ve looked at PHP frameworks, and have found they have the power, but don&#39;t do Content Management nor have a good enough UI for your clients. You want the power and flexibility of a framework, with the UI and content management of a CMS. Enter MODX Revolution. A completely flexible, powerful and robust API, built on OOP principles and using a PDO-powered Object Relational Model (ORM) called [xPDO|xPDO20:Home]. Add in a rich, [Sencha|http://sencha.com]\-powered UI for your clients, that&#39;s fully customizable. Custom properties and sets. Internationalization support. Package distribution built-in so you can pack up your code, and distribute it across any Revolution install. Add custom manager pages to run entire applications within MODX. h2. Basic Concepts MODX, in essence, has a ton of moving parts. But the basics parts are: h3. Resources [Resources] are basically a webpage location. It can be actual HTML content, or a file, forwarding link, or a symlink, or anything else. h3. Templates [Templates] are the house a Resource lives in. They usually contain the footer and header for a page. h3. Template Variables [Template Variables] (TVs) are custom fields for a Template that allow the user to assign dynamic values to a Resource. A great example would be a &#39;tags&#39; TV that allows you to specify tags for a Resource. You can have an unlimited number of TVs per page. h3. Chunks [Chunks] are simply small blocks of content, be it whatever you want inside it. They can contain [Snippets], or any other Element type (Snippet, Chunk, TV, etc). h3. Snippets [Snippets] are dynamic bits of PHP code that run when the page is loaded. They can do anything you can code, including building custom menus, grabbing custom data, tagging elements, processing forms, grabbing tweets, etc. h3. Plugins Plugins are event hooks that run whenever an event is fired. They are usually used for extending the Revolution core to do something during a part of the loading process - such as stripping out bad words in content, adding dictionary links to words, managing redirects for old pages, etc. h2. So What Happens on a Request? MODX loads the requested [Resource|Resources], fetches that Resource&#39;s [Template|Templates], and then places the Resource&#39;s content in that Template. MODX then parses the resulting combined content, including any tags that might be in it, in the order they are reached. From there, it outputs the response to the user&#39;s browser. h2. See Also {pagetree:root=An Overview of MODX} {scrollbar}";}i:2;a:3:{s:2:"id";s:8:"39354459";s:3:"ver";s:1:"1";s:4:"code";s:4477:"\\ h2. What is MODx? MODx is a Content Application Platform. What does this mean? Well, that depends on who you are: !avgjoe.png|align=right! h3. End-Users (Average Joe) MODx offers you a system that lets you publish your offline content onto the web in any form, shape or presence you want. It also offers a completely customizable backend interface that you can make as simple (or as complex) as you like. You can setup everything from a simple site, to a blog, to a full-scale web presence with MODx, and keep your admin interface simple and usable. Drag and drop your webpages around to reorder and move them. Get a full WYSIWYG view of your Resources. Leave Resources unpublished before you finish them. Schedule Resources to publish at certain times. MODx helps you organize your content the way you want it, and get stellar built-in SEO results. MODx is fully, 100% Friendly URL compatible, so getting mysite.com/my/own/custom/url.html is incredibly simple, and as easy as structuring your site that way. !coolcarl.png|align=right! h3. Designers (Cool Carl) Ever wanted complete freedom with your HTML and CSS? Tired of hacking existing systems to get your design to work the way you comp&#39;ed it? MODx does not generate one single line of HTML - it leaves the front-end design up to you. You can use MODx as your Content Management System (CMS) of choice, as MODx offers completely flexible templating and no-holds-barred content delivery. Put your CSS and images where you want them. And once you&#39;re done designing, either hand off the development duties to your developer, or point-and-click install Extras straight from within the manager. Simple. !badassbilly.png|align=right! h3. Developers (Badass Billy) You&#39;ve looked at different CMSes, but have found developing in them to be either a mishmash of too many unconnected code pieces, or simply not powerful or elegant enough. You&#39;ve looked at PHP frameworks, and have found they have the power, but don&#39;t do Content Management nor have a good enough UI for your clients. You want the power and flexibility of a framework, with the UI and content management of a CMS. Enter MODx Revolution. A completely flexible, powerful and robust API, built on OOP principles and using a PDO-powered Object Relational Model (ORM) called [xPDO|xPDO20:Home]. Add in a rich, [Sencha|http://sencha.com]-powered UI for your clients, that&#39;s fully customizable. Custom properties and sets. Internationalization support. Package distribution built-in so you can pack up your code, and distribute it across any Revolution install. Add custom manager pages to run entire applications within MODx. h2. Basic Concepts MODx, in essence, has a ton of moving parts. But the basics parts are: h3. Resources [Resources] are basically a webpage location. It can be actual HTML content, or a file, forwarding link, or a symlink, or anything else. h3. Templates [Templates] are the house a Resource lives in. They usually contain the footer and header for a page. h3. Template Variables [Template Variables] (TVs) are custom fields for a Template that allow the user to assign dynamic values to a Resource. A great example would be a &#39;tags&#39; TV that allows you to specify tags for a Resource. You can have an unlimited number of TVs per page. h3. Chunks [Chunks] are simply small blocks of content, be it whatever you want inside it. They can contain [Snippets], or any other Element type (Snippet, Chunk, TV, etc). h3. Snippets [Snippets] are dynamic bits of PHP code that run when the page is loaded. They can do anything you can code, including building custom menus, grabbing custom data, tagging elements, processing forms, grabbing tweets, etc. h3. Plugins Plugins are event hooks that run whenever an event is fired. They are usually used for extending the Revolution core to do something during a part of the loading process - such as stripping out bad words in content, adding dictionary links to words, managing redirects for old pages, etc. h2. So What Happens on a Request? MODx loads the requested [Resource|Resources], fetches that Resource&#39;s [Template|Templates], and then places the Resource&#39;s content in that Template. MODx then parses the resulting combined content, including any tags that might be in it, in the order they are reached. From there, it outputs the response to the user&#39;s browser. h2. See Also {pagetree:root=An Overview of MODx} {scrollbar}";}i:3;a:3:{s:2:"id";s:8:"18678623";s:3:"ver";s:1:"1";s:4:"code";s:4426:"\\ h2. What is MODx? MODx is a Content Application Platform. What does this mean? Well, that depends on who you are: !avgjoe.png|align=right! h3. End-Users (Average Joe) MODx offers you a system that lets you publish your offline content onto the web in any form, shape or presence you want. It also offers a completely customizable backend interface that you can make as simple (or as complex) as you like. You can setup everything from a simple site, to a blog, to a full-scale web presence with MODx, and keep your admin interface simple and usable. Drag and drop your webpages around to reorder and move them. Get a full WYSIWYG view of your Resources. Leave Resources unpublished before you finish them. Schedule Resources to publish at certain times. MODx helps you organize your content the way you want it, and get stellar built-in SEO results. MODx is fully, 100% Friendly URL compatible, so getting mysite.com/my/own/custom/url.html is incredibly simple, and as easy as structuring your site that way. !coolcarl.png|align=right! h3. Designers (Cool Carl) Ever wanted complete freedom with your HTML and CSS? Tired of hacking existing systems to get your design to work the way you comp&#39;ed it? MODx does not generate one single line of HTML - it leaves the front-end design up to you. You can use MODx as your Content Management System (CMS) of choice, as MODx offers completely flexible templating and no-holds-barred content delivery. Put your CSS and images where you want them. And once you&#39;re done designing, either hand off the development duties to your developer, or point-and-click install Extras straight from within the manager. Simple. !badassbilly.png|align=right! h3. Developers (Badass Billy) You&#39;ve looked at different CMSes, but have found developing in them to be either a mishmash of too many unconnected code pieces, or simply not powerful or elegant enough. You&#39;ve looked at PHP frameworks, and have found they have the power, but don&#39;t do Content Management nor have a good enough UI for your clients. You want the power and flexibility of a framework, with the UI and content management of a CMS. Enter MODx Revolution. A completely flexible, powerful and robust API, built on OOP principles and using a PDO-powered Object Relational Model (ORM) called [xPDO|xPDO20:Home]. Add in a rich, [Sencha|http://sencha.com]-powered UI for your clients, that&#39;s fully customizable. Custom properties and sets. Internationalization support. Package distribution built-in so you can pack up your code, and distribute it across any Revolution install. Add custom manager pages to run entire applications within MODx. h2. Basic Concepts MODx, in essence, has a ton of moving parts. But the basics parts are: h3. Resources [Resources] are basically a webpage location. It can be actual HTML content, or a file, forwarding link, or a symlink, or anything else. h3. Templates [Templates] are the house a Resource lives in. They usually contain the footer and header for a page. h3. Template Variables [Template Variables] (TVs) are custom fields for a Template that allow the user to assign dynamic values to a Resource. A great example would be a &#39;tags&#39; TV that allows you to specify tags for a Resource. You can have an unlimited number of TVs per page. h3. Chunks [Chunks] are simply small blocks of content, be it whatever you want inside it. They can contain [Snippets], or any other Element type (Snippet, Chunk, TV, etc). h3. Snippets [Snippets] are dynamic bits of PHP code that run when the page is loaded. They can do anything you can code, including building custom menus, grabbing custom data, tagging elements, processing forms, grabbing tweets, etc. h3. Plugins Plugins are event hooks that run whenever an event is fired. They are usually used for extending the Revolution core to do something during a part of the loading process - such as stripping out bad words in content, adding dictionary links to words, managing redirects for old pages, etc. h2. So What Happens on a Request? MODx loads the requested [Resource|Resources], fetches that Resource&#39;s [Template|Templates], and then places the Resource&#39;s content in that Template. MODx then parses the resulting combined content, including any tags that might be in it, in the order they are reached. From there, it outputs the response to the user&#39;s browser. {scrollbar}";}i:4;a:3:{s:2:"id";s:8:"18678622";s:3:"ver";s:1:"1";s:4:"code";s:4426:"\\ h2. What is MODx? MODx is a Content Application Platform. What does this mean? Well, that depends on who you are: !avgjoe.png|align=right! h3. End-Users (Average Joe) MODx offers you a system that lets you publish your offline content onto the web in any form, shape or presence you want. It also offers a completely customizable backend interface that you can make as simple (or as complex) as you like. You can setup everything from a simple site, to a blog, to a full-scale web presence with MODx, and keep your admin interface simple and usable. Drag and drop your webpages around to reorder and move them. Get a full WYSIWYG view of your Resources. Leave Resources unpublished before you finish them. Schedule Resources to publish at certain times. MODx helps you organize your content the way you want it, and get stellar built-in SEO results. MODx is fully, 100% Friendly URL compatible, so getting mysite.com/my/own/custom/url.html is incredibly simple, and as easy as structuring your site that way. !coolcarl.png|align=right! h3. Designers (Cool Carl) Ever wanted complete freedom with your HTML and CSS? Tired of hacking existing systems to get your design to work the way you comp&#39;ed it? MODx does not generate one single line of HTML - it leaves the front-end design up to you. You can use MODx as your Content Management System (CMS) of choice, as MODx offers completely flexible templating and no-holds-barred content delivery. Put your CSS and images where you want them. And once you&#39;re done designing, either hand off the development duties to your developer, or point-and-click install Extras straight from within the manager. Simple. !badassbilly.png|align=right! h3. Developers (Badass Billy) You&#39;ve looked at different CMSes, but have found developing in them to be either a mishmash of too many unconnected code pieces, or simply not powerful or elegant enough. You&#39;ve looked at PHP frameworks, and have found they have the power, but don&#39;t do Content Management nor have a good enough UI for your clients. You want the power and flexibility of a framework, with the UI and content management of a CMS. Enter MODx Revolution. A completely flexible, powerful and robust API, built on OOP principles and using a PDO-powered Object Relational Model (ORM) called [xPDO|xPDO20:Home]. Add in a rich, [Sencha|http://sencha.com]-powered UI for your clients, that&#39;s fully customizable. Custom properties and sets. Internationalization support. Package distribution built-in so you can pack up your code, and distribute it across any Revolution install. Add custom manager pages to run entire applications within MODx. h2. Basic Overview MODx, in essence, has a ton of moving parts. But the basics parts are: h3. Resources [Resources] are basically a webpage location. It can be actual HTML content, or a file, forwarding link, or a symlink, or anything else. h3. Templates [Templates] are the house a Resource lives in. They usually contain the footer and header for a page. h3. Template Variables [Template Variables] (TVs) are custom fields for a Template that allow the user to assign dynamic values to a Resource. A great example would be a &#39;tags&#39; TV that allows you to specify tags for a Resource. You can have an unlimited number of TVs per page. h3. Chunks [Chunks] are simply small blocks of content, be it whatever you want inside it. They can contain [Snippets], or any other Element type (Snippet, Chunk, TV, etc). h3. Snippets [Snippets] are dynamic bits of PHP code that run when the page is loaded. They can do anything you can code, including building custom menus, grabbing custom data, tagging elements, processing forms, grabbing tweets, etc. h3. Plugins Plugins are event hooks that run whenever an event is fired. They are usually used for extending the Revolution core to do something during a part of the loading process - such as stripping out bad words in content, adding dictionary links to words, managing redirects for old pages, etc. h2. So What Happens on a Request? MODx loads the requested [Resource|Resources], fetches that Resource&#39;s [Template|Templates], and then places the Resource&#39;s content in that Template. MODx then parses the resulting combined content, including any tags that might be in it, in the order they are reached. From there, it outputs the response to the user&#39;s browser. {scrollbar}";}i:5;a:3:{s:2:"id";s:8:"18678620";s:3:"ver";s:1:"1";s:4:"code";s:2776:"\\ h2. What is MODx? MODx is a Content Application Platform. What does this mean? Well, that depends on who you are: !avgjoe.png|align=right! h3. End-Users (Average Joe) MODx offers you a system that lets you publish your offline content onto the web in any form, shape or presence you want. It also offers a completely customizable backend interface that you can make as simple (or as complex) as you like. You can setup everything from a simple site, to a blog, to a full-scale web presence with MODx, and keep your admin interface simple and usable. Drag and drop your webpages around to reorder and move them. Get a full WYSIWYG view of your Resources. Leave Resources unpublished before you finish them. Schedule Resources to publish at certain times. MODx helps you organize your content the way you want it, and get stellar built-in SEO results. MODx is fully, 100% Friendly URL compatible, so getting mysite.com/my/own/custom/url.html is incredibly simple, and as easy as structuring your site that way. !coolcarl.png|align=right! h3. Designers (Cool Carl) Ever wanted complete freedom with your HTML and CSS? Tired of hacking existing systems to get your design to work the way you comp&#39;ed it? MODx does not generate one single line of HTML - it leaves the front-end design up to you. You can use MODx as your Content Management System (CMS) of choice, as MODx offers completely flexible templating and no-holds-barred content delivery. Put your CSS and images where you want them. And once you&#39;re done designing, either hand off the development duties to your developer, or point-and-click install Extras straight from within the manager. Simple. !badassbilly.png|align=right! h3. Developers (Badass Billy) You&#39;ve looked at different CMSes, but have found developing in them to be either a mishmash of too many unconnected code pieces, or simply not powerful or elegant enough. You&#39;ve looked at PHP frameworks, and have found they have the power, but don&#39;t do Content Management nor have a good enough UI for your clients. You want the power and flexibility of a framework, with the UI and content management of a CMS. Enter MODx Revolution. A completely flexible, powerful and robust API, built on OOP principles and using a PDO-powered Object Relational Model (ORM) called [xPDO|xPDO20:Home]. Add in a rich, [Sencha|http://sencha.com]-powered UI for your clients, that&#39;s fully customizable. Custom properties and sets. Internationalization support. Package distribution built-in so you can pack up your code, and distribute it across any Revolution install. Add custom manager pages to run entire applications within MODx. h2. Basic Overview MODx, in essence, has a ton of moving parts. But the basics are this: {scrollbar}";}i:6;a:3:{s:2:"id";s:8:"18678618";s:3:"ver";s:1:"1";s:4:"code";s:2784:"\\ h2. What is MODx? MODx is a Content Application Platform. What does this mean? Well, that depends on who you are: !avgjoe.png|align=left,border=0! h3. End-Users (Average Joe) MODx offers you a system that lets you publish your offline content onto the web in any form, shape or presence you want. It also offers a completely customizable backend interface that you can make as simple (or as complex) as you like. You can setup everything from a simple site, to a blog, to a full-scale web presence with MODx, and keep your admin interface simple and usable. Drag and drop your webpages around to reorder and move them. Get a full WYSIWYG view of your Resources. Leave Resources unpublished before you finish them. Schedule Resources to publish at certain times. MODx helps you organize your content the way you want it, and get stellar built-in SEO results. MODx is fully, 100% Friendly URL compatible, so getting mysite.com/my/own/custom/url.html is incredibly simple, and as easy as structuring your site that way. !coolcarl.png|align=right! h3. Designers (Cool Carl) Ever wanted complete freedom with your HTML and CSS? Tired of hacking existing systems to get your design to work the way you comp&#39;ed it? MODx does not generate one single line of HTML - it leaves the front-end design up to you. You can use MODx as your Content Management System (CMS) of choice, as MODx offers completely flexible templating and no-holds-barred content delivery. Put your CSS and images where you want them. And once you&#39;re done designing, either hand off the development duties to your developer, or point-and-click install Extras straight from within the manager. Simple. !badassbilly.png|align=right! h3. Developers (Badass Billy) You&#39;ve looked at different CMSes, but have found developing in them to be either a mishmash of too many unconnected code pieces, or simply not powerful or elegant enough. You&#39;ve looked at PHP frameworks, and have found they have the power, but don&#39;t do Content Management nor have a good enough UI for your clients. You want the power and flexibility of a framework, with the UI and content management of a CMS. Enter MODx Revolution. A completely flexible, powerful and robust API, built on OOP principles and using a PDO-powered Object Relational Model (ORM) called [xPDO|xPDO20:Home]. Add in a rich, [Sencha|http://sencha.com]-powered UI for your clients, that&#39;s fully customizable. Custom properties and sets. Internationalization support. Package distribution built-in so you can pack up your code, and distribute it across any Revolution install. Add custom manager pages to run entire applications within MODx. h2. Basic Overview MODx, in essence, has a ton of moving parts. But the basics are this: {scrollbar}";}i:7;a:3:{s:2:"id";s:8:"18678617";s:3:"ver";s:1:"1";s:4:"code";s:2807:"\\ h2. What is MODx? MODx is a Content Application Platform. What does this mean? Well, that depends on who you are: !avgjoe.png|align=left,style=&quot;padding: 10px&quot;! h3. End-Users (Average Joe) MODx offers you a system that lets you publish your offline content onto the web in any form, shape or presence you want. It also offers a completely customizable backend interface that you can make as simple (or as complex) as you like. You can setup everything from a simple site, to a blog, to a full-scale web presence with MODx, and keep your admin interface simple and usable. Drag and drop your webpages around to reorder and move them. Get a full WYSIWYG view of your Resources. Leave Resources unpublished before you finish them. Schedule Resources to publish at certain times. MODx helps you organize your content the way you want it, and get stellar built-in SEO results. MODx is fully, 100% Friendly URL compatible, so getting mysite.com/my/own/custom/url.html is incredibly simple, and as easy as structuring your site that way. !coolcarl.png|align=right! h3. Designers (Cool Carl) Ever wanted complete freedom with your HTML and CSS? Tired of hacking existing systems to get your design to work the way you comp&#39;ed it? MODx does not generate one single line of HTML - it leaves the front-end design up to you. You can use MODx as your Content Management System (CMS) of choice, as MODx offers completely flexible templating and no-holds-barred content delivery. Put your CSS and images where you want them. And once you&#39;re done designing, either hand off the development duties to your developer, or point-and-click install Extras straight from within the manager. Simple. !badassbilly.png|align=right! h3. Developers (Badass Billy) You&#39;ve looked at different CMSes, but have found developing in them to be either a mishmash of too many unconnected code pieces, or simply not powerful or elegant enough. You&#39;ve looked at PHP frameworks, and have found they have the power, but don&#39;t do Content Management nor have a good enough UI for your clients. You want the power and flexibility of a framework, with the UI and content management of a CMS. Enter MODx Revolution. A completely flexible, powerful and robust API, built on OOP principles and using a PDO-powered Object Relational Model (ORM) called [xPDO|xPDO20:Home]. Add in a rich, [Sencha|http://sencha.com]-powered UI for your clients, that&#39;s fully customizable. Custom properties and sets. Internationalization support. Package distribution built-in so you can pack up your code, and distribute it across any Revolution install. Add custom manager pages to run entire applications within MODx. h2. Basic Overview MODx, in essence, has a ton of moving parts. But the basics are this: {scrollbar}";}i:8;a:3:{s:2:"id";s:8:"18678616";s:3:"ver";s:1:"9";s:4:"code";s:2784:"\\ h2. What is MODx? MODx is a Content Application Platform. What does this mean? Well, that depends on who you are: !avgjoe.png|align=left,vspace=4! h3. End-Users (Average Joe) MODx offers you a system that lets you publish your offline content onto the web in any form, shape or presence you want. It also offers a completely customizable backend interface that you can make as simple (or as complex) as you like. You can setup everything from a simple site, to a blog, to a full-scale web presence with MODx, and keep your admin interface simple and usable. Drag and drop your webpages around to reorder and move them. Get a full WYSIWYG view of your Resources. Leave Resources unpublished before you finish them. Schedule Resources to publish at certain times. MODx helps you organize your content the way you want it, and get stellar built-in SEO results. MODx is fully, 100% Friendly URL compatible, so getting mysite.com/my/own/custom/url.html is incredibly simple, and as easy as structuring your site that way. !coolcarl.png|align=right! h3. Designers (Cool Carl) Ever wanted complete freedom with your HTML and CSS? Tired of hacking existing systems to get your design to work the way you comp&#39;ed it? MODx does not generate one single line of HTML - it leaves the front-end design up to you. You can use MODx as your Content Management System (CMS) of choice, as MODx offers completely flexible templating and no-holds-barred content delivery. Put your CSS and images where you want them. And once you&#39;re done designing, either hand off the development duties to your developer, or point-and-click install Extras straight from within the manager. Simple. !badassbilly.png|align=right! h3. Developers (Badass Billy) You&#39;ve looked at different CMSes, but have found developing in them to be either a mishmash of too many unconnected code pieces, or simply not powerful or elegant enough. You&#39;ve looked at PHP frameworks, and have found they have the power, but don&#39;t do Content Management nor have a good enough UI for your clients. You want the power and flexibility of a framework, with the UI and content management of a CMS. Enter MODx Revolution. A completely flexible, powerful and robust API, built on OOP principles and using a PDO-powered Object Relational Model (ORM) called [xPDO|xPDO20:Home]. Add in a rich, [Sencha|http://sencha.com]-powered UI for your clients, that&#39;s fully customizable. Custom properties and sets. Internationalization support. Package distribution built-in so you can pack up your code, and distribute it across any Revolution install. Add custom manager pages to run entire applications within MODx. h2. Basic Overview MODx, in essence, has a ton of moving parts. But the basics are this: {scrollbar}";}i:9;a:3:{s:2:"id";s:8:"18678615";s:3:"ver";s:1:"8";s:4:"code";s:2787:"\\ h2. What is MODx? MODx is a Content Application Platform. What does this mean? Well, that depends on who you are: !avgjoe.png|align=left,margin=10px! h3. End-Users (Average Joe) MODx offers you a system that lets you publish your offline content onto the web in any form, shape or presence you want. It also offers a completely customizable backend interface that you can make as simple (or as complex) as you like. You can setup everything from a simple site, to a blog, to a full-scale web presence with MODx, and keep your admin interface simple and usable. Drag and drop your webpages around to reorder and move them. Get a full WYSIWYG view of your Resources. Leave Resources unpublished before you finish them. Schedule Resources to publish at certain times. MODx helps you organize your content the way you want it, and get stellar built-in SEO results. MODx is fully, 100% Friendly URL compatible, so getting mysite.com/my/own/custom/url.html is incredibly simple, and as easy as structuring your site that way. !coolcarl.png|align=right! h3. Designers (Cool Carl) Ever wanted complete freedom with your HTML and CSS? Tired of hacking existing systems to get your design to work the way you comp&#39;ed it? MODx does not generate one single line of HTML - it leaves the front-end design up to you. You can use MODx as your Content Management System (CMS) of choice, as MODx offers completely flexible templating and no-holds-barred content delivery. Put your CSS and images where you want them. And once you&#39;re done designing, either hand off the development duties to your developer, or point-and-click install Extras straight from within the manager. Simple. !badassbilly.png|align=right! h3. Developers (Badass Billy) You&#39;ve looked at different CMSes, but have found developing in them to be either a mishmash of too many unconnected code pieces, or simply not powerful or elegant enough. You&#39;ve looked at PHP frameworks, and have found they have the power, but don&#39;t do Content Management nor have a good enough UI for your clients. You want the power and flexibility of a framework, with the UI and content management of a CMS. Enter MODx Revolution. A completely flexible, powerful and robust API, built on OOP principles and using a PDO-powered Object Relational Model (ORM) called [xPDO|xPDO20:Home]. Add in a rich, [Sencha|http://sencha.com]-powered UI for your clients, that&#39;s fully customizable. Custom properties and sets. Internationalization support. Package distribution built-in so you can pack up your code, and distribute it across any Revolution install. Add custom manager pages to run entire applications within MODx. h2. Basic Overview MODx, in essence, has a ton of moving parts. But the basics are this: {scrollbar}";}i:10;a:3:{s:2:"id";s:8:"18678614";s:3:"ver";s:1:"7";s:4:"code";s:2775:"\\ h2. What is MODx? MODx is a Content Application Platform. What does this mean? Well, that depends on who you are: !avgjoe.png|align=left! h3. End-Users (Average Joe) MODx offers you a system that lets you publish your offline content onto the web in any form, shape or presence you want. It also offers a completely customizable backend interface that you can make as simple (or as complex) as you like. You can setup everything from a simple site, to a blog, to a full-scale web presence with MODx, and keep your admin interface simple and usable. Drag and drop your webpages around to reorder and move them. Get a full WYSIWYG view of your Resources. Leave Resources unpublished before you finish them. Schedule Resources to publish at certain times. MODx helps you organize your content the way you want it, and get stellar built-in SEO results. MODx is fully, 100% Friendly URL compatible, so getting mysite.com/my/own/custom/url.html is incredibly simple, and as easy as structuring your site that way. !coolcarl.png|align=right! h3. Designers (Cool Carl) Ever wanted complete freedom with your HTML and CSS? Tired of hacking existing systems to get your design to work the way you comp&#39;ed it? MODx does not generate one single line of HTML - it leaves the front-end design up to you. You can use MODx as your Content Management System (CMS) of choice, as MODx offers completely flexible templating and no-holds-barred content delivery. Put your CSS and images where you want them. And once you&#39;re done designing, either hand off the development duties to your developer, or point-and-click install Extras straight from within the manager. Simple. !badassbilly.png|align=right! h3. Developers (Badass Billy) You&#39;ve looked at different CMSes, but have found developing in them to be either a mishmash of too many unconnected code pieces, or simply not powerful or elegant enough. You&#39;ve looked at PHP frameworks, and have found they have the power, but don&#39;t do Content Management nor have a good enough UI for your clients. You want the power and flexibility of a framework, with the UI and content management of a CMS. Enter MODx Revolution. A completely flexible, powerful and robust API, built on OOP principles and using a PDO-powered Object Relational Model (ORM) called [xPDO|xPDO20:Home]. Add in a rich, [Sencha|http://sencha.com]-powered UI for your clients, that&#39;s fully customizable. Custom properties and sets. Internationalization support. Package distribution built-in so you can pack up your code, and distribute it across any Revolution install. Add custom manager pages to run entire applications within MODx. h2. Basic Overview MODx, in essence, has a ton of moving parts. But the basics are this: {scrollbar}";}i:11;a:3:{s:2:"id";s:8:"18678613";s:3:"ver";s:1:"6";s:4:"code";s:2776:"\\ h2. What is MODx? MODx is a Content Application Platform. What does this mean? Well, that depends on who you are: !avgjoe.png|align=right! h3. End-Users (Average Joe) MODx offers you a system that lets you publish your offline content onto the web in any form, shape or presence you want. It also offers a completely customizable backend interface that you can make as simple (or as complex) as you like. You can setup everything from a simple site, to a blog, to a full-scale web presence with MODx, and keep your admin interface simple and usable. Drag and drop your webpages around to reorder and move them. Get a full WYSIWYG view of your Resources. Leave Resources unpublished before you finish them. Schedule Resources to publish at certain times. MODx helps you organize your content the way you want it, and get stellar built-in SEO results. MODx is fully, 100% Friendly URL compatible, so getting mysite.com/my/own/custom/url.html is incredibly simple, and as easy as structuring your site that way. !coolcarl.png|align=right! h3. Designers (Cool Carl) Ever wanted complete freedom with your HTML and CSS? Tired of hacking existing systems to get your design to work the way you comp&#39;ed it? MODx does not generate one single line of HTML - it leaves the front-end design up to you. You can use MODx as your Content Management System (CMS) of choice, as MODx offers completely flexible templating and no-holds-barred content delivery. Put your CSS and images where you want them. And once you&#39;re done designing, either hand off the development duties to your developer, or point-and-click install Extras straight from within the manager. Simple. !badassbilly.png|align=right! h3. Developers (Badass Billy) You&#39;ve looked at different CMSes, but have found developing in them to be either a mishmash of too many unconnected code pieces, or simply not powerful or elegant enough. You&#39;ve looked at PHP frameworks, and have found they have the power, but don&#39;t do Content Management nor have a good enough UI for your clients. You want the power and flexibility of a framework, with the UI and content management of a CMS. Enter MODx Revolution. A completely flexible, powerful and robust API, built on OOP principles and using a PDO-powered Object Relational Model (ORM) called [xPDO|xPDO20:Home]. Add in a rich, [Sencha|http://sencha.com]-powered UI for your clients, that&#39;s fully customizable. Custom properties and sets. Internationalization support. Package distribution built-in so you can pack up your code, and distribute it across any Revolution install. Add custom manager pages to run entire applications within MODx. h2. Basic Overview MODx, in essence, has a ton of moving parts. But the basics are this: {scrollbar}";}i:12;a:3:{s:2:"id";s:8:"18678612";s:3:"ver";s:1:"5";s:4:"code";s:1542:"\\ h2. What is MODx? MODx is a Content Application Platform. What does this mean? Well, that depends on who you are: !avgjoe.png|align=right! h3. End-Users (Average Joe) MODx offers you a system that lets you publish your offline content onto the web in any form, shape or presence you want. It also offers a completely customizable backend interface that you can make as simple (or as complex) as you like. You can setup everything from a simple site, to a blog, to a full-scale web presence with MODx, and keep your admin interface simple and usable. Drag and drop your webpages around to reorder and move them. Get a full WYSIWYG view of your Resources. Leave Resources unpublished before you finish them. Schedule Resources to publish at certain times. !coolcarl.png|align=right! h3. Designers (Cool Carl) Ever wanted complete freedom with your HTML and CSS? Tired of hacking existing systems to get your design to work the way you comp&#39;ed it? MODx does not generate one single line of HTML - it leaves the front-end design up to you. You can use MODx as your Content Management System (CMS) of choice, as MODx offers completely flexible templating and no-holds-barred content delivery. Put your CSS and images where you want them. And once you&#39;re done designing, either hand off the development duties to your developer, or point-and-click install Extras straight from within the manager. Simple. !badassbilly.png|align=right! h3. Developers (Badass Billy) A completely flexible, powerful and robust API. {scrollbar}";}i:13;a:3:{s:2:"id";s:8:"18678610";s:3:"ver";s:1:"4";s:4:"code";s:930:"\\ h2. What is MODx? MODx is a Content Application Platform. What does this mean? Well, that depends on who you are: !avgjoe.png|align=right! h3. End-Users (Average Joe) MODx offers you a system that lets you publish your offline content onto the web in any form, shape or presence you want. It also offers a completely customizable backend interface that you can make as simple (or as complex) as you like. You can setup everything from a simple site, to a blog, to a full-scale web presence with MODx. !coolcarl.png|align=right|border=0! h3. Designers (Cool Carl) Ever wanted complete freedom with your HTML and CSS? Tired of hacking existing systems to get your design to work the way you comp&#39;ed it? MODx does not generate one single line of HTML - it leaves the front-end design up to you. !badassbilly.png|align=right! h3. Developers (Badass Billy) A completely flexible, powerful and robust API. {scrollbar}";}i:14;a:3:{s:2:"id";s:8:"18678608";s:3:"ver";s:1:"3";s:4:"code";s:934:"\\ h2. What is MODx? MODx is a Content Application Platform. What does this mean? Well, that depends on who you are: !avgjoe.png|align=right! h3. End-Users (Average Joe) MODx offers you a system that lets you publish your offline content onto the web in any form, shape or presence you want. It also offers a completely customizable backend interface that you can make as simple (or as complex) as you like. You can setup everything from a simple site, to a blog, to a full-scale web presence with MODx. !coolcarl.png|align=right|border=false! h3. Designers (Cool Carl) Ever wanted complete freedom with your HTML and CSS? Tired of hacking existing systems to get your design to work the way you comp&#39;ed it? MODx does not generate one single line of HTML - it leaves the front-end design up to you. !badassbilly.png|align=right! h3. Developers (Badass Billy) A completely flexible, powerful and robust API. {scrollbar}";}i:15;a:3:{s:2:"id";s:8:"18678607";s:3:"ver";s:1:"2";s:4:"code";s:921:"\\ h2. What is MODx? MODx is a Content Application Platform. What does this mean? Well, that depends on who you are: !avgjoe.png|align=right! h3. End-Users (Average Joe) MODx offers you a system that lets you publish your offline content onto the web in any form, shape or presence you want. It also offers a completely customizable backend interface that you can make as simple (or as complex) as you like. You can setup everything from a simple site, to a blog, to a full-scale web presence with MODx. !coolcarl.png|align=right! h3. Designers (Cool Carl) Ever wanted complete freedom with your HTML and CSS? Tired of hacking existing systems to get your design to work the way you comp&#39;ed it? MODx does not generate one single line of HTML - it leaves the front-end design up to you. !badassbilly.png|align=right! h3. Developers (Badass Billy) A completely flexible, powerful and robust API. {scrollbar}";}i:16;a:3:{s:2:"id";s:8:"18678606";s:3:"ver";s:1:"1";s:4:"code";s:15:"\\ {scrollbar}";}}}
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab /* * Ceph - scalable distributed file system * * Copyright (C) 2004-2006 Sage Weil <[email protected]> * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. * */ #ifndef CEPH_MBACKFILL_H #define CEPH_MBACKFILL_H #include "msg/Message.h" #include "messages/MOSDPeeringOp.h" #include "osd/PGPeeringEvent.h" class MBackfillReserve : public MOSDPeeringOp { private: static constexpr int HEAD_VERSION = 5; static constexpr int COMPAT_VERSION = 4; public: spg_t pgid; epoch_t query_epoch; enum { REQUEST = 0, // primary->replica: please reserve a slot GRANT = 1, // replica->primary: ok, i reserved it REJECT_TOOFULL = 2, // replica->primary: too full, sorry, try again later (*) RELEASE = 3, // primary->replcia: release the slot i reserved before REVOKE_TOOFULL = 4, // replica->primary: too full, stop backfilling REVOKE = 5, // replica->primary: i'm taking back the slot i gave you // (*) NOTE: prior to luminous, REJECT was overloaded to also mean release }; uint32_t type; uint32_t priority; int64_t primary_num_bytes; int64_t shard_num_bytes; spg_t get_spg() const { return pgid; } epoch_t get_map_epoch() const { return query_epoch; } epoch_t get_min_epoch() const { return query_epoch; } PGPeeringEvent *get_event() override { switch (type) { case REQUEST: return new PGPeeringEvent( query_epoch, query_epoch, RequestBackfillPrio(priority, primary_num_bytes, shard_num_bytes)); case GRANT: return new PGPeeringEvent( query_epoch, query_epoch, RemoteBackfillReserved()); case REJECT_TOOFULL: // NOTE: this is replica -> primary "i reject your request" // and also primary -> replica "cancel my previously-granted request" // (for older peers) // and also replica -> primary "i revoke your reservation" // (for older peers) return new PGPeeringEvent( query_epoch, query_epoch, RemoteReservationRejectedTooFull()); case RELEASE: return new PGPeeringEvent( query_epoch, query_epoch, RemoteReservationCanceled()); case REVOKE_TOOFULL: return new PGPeeringEvent( query_epoch, query_epoch, RemoteReservationRevokedTooFull()); case REVOKE: return new PGPeeringEvent( query_epoch, query_epoch, RemoteReservationRevoked()); default: ceph_abort(); } } MBackfillReserve() : MOSDPeeringOp{MSG_OSD_BACKFILL_RESERVE, HEAD_VERSION, COMPAT_VERSION}, query_epoch(0), type(-1), priority(-1), primary_num_bytes(0), shard_num_bytes(0) {} MBackfillReserve(int type, spg_t pgid, epoch_t query_epoch, unsigned prio = -1, int64_t primary_num_bytes = 0, int64_t shard_num_bytes = 0) : MOSDPeeringOp{MSG_OSD_BACKFILL_RESERVE, HEAD_VERSION, COMPAT_VERSION}, pgid(pgid), query_epoch(query_epoch), type(type), priority(prio), primary_num_bytes(primary_num_bytes), shard_num_bytes(shard_num_bytes) {} std::string_view get_type_name() const override { return "MBackfillReserve"; } void inner_print(std::ostream& out) const override { switch (type) { case REQUEST: out << "REQUEST"; break; case GRANT: out << "GRANT"; break; case REJECT_TOOFULL: out << "REJECT_TOOFULL"; break; case RELEASE: out << "RELEASE"; break; case REVOKE_TOOFULL: out << "REVOKE_TOOFULL"; break; case REVOKE: out << "REVOKE"; break; } if (type == REQUEST) out << " prio: " << priority; return; } void decode_payload() override { auto p = payload.cbegin(); using ceph::decode; decode(pgid.pgid, p); decode(query_epoch, p); decode(type, p); decode(priority, p); decode(pgid.shard, p); if (header.version >= 5) { decode(primary_num_bytes, p); decode(shard_num_bytes, p); } else { primary_num_bytes = 0; shard_num_bytes = 0; } } void encode_payload(uint64_t features) override { using ceph::encode; if (!HAVE_FEATURE(features, RECOVERY_RESERVATION_2)) { header.version = 3; header.compat_version = 3; encode(pgid.pgid, payload); encode(query_epoch, payload); encode((type == RELEASE || type == REVOKE_TOOFULL || type == REVOKE) ? REJECT_TOOFULL : type, payload); encode(priority, payload); encode(pgid.shard, payload); return; } header.version = HEAD_VERSION; header.compat_version = COMPAT_VERSION; encode(pgid.pgid, payload); encode(query_epoch, payload); encode(type, payload); encode(priority, payload); encode(pgid.shard, payload); encode(primary_num_bytes, payload); encode(shard_num_bytes, payload); } }; #endif
class Solution: def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: answer = ListNode() #ListNode로 초기화 - 더미 노드가 된다 s = answer #ListNode를 가리키는 포인터 carry = 0 #올림수 초기화 #l1나 l2의 자릿수가 남았거나 (이들이 가리키는 값이 null이 아님) #처리해줘야 할 올림수가 있거나 while l1 or l2 or carry: sum = 0 # 각 자릿수의 합 if l1: sum += l1.val # 현재 l1 자릿수를 더해주고 l1 = l1.next # l1의 다음 자릿수를 가리켜준다 if l2: sum += l2.val # 현재 l2 자릿수를 더해주고 l2 = l2.next # l2의 다음 자릿수를 가리켜준다 sum += carry # 올림수가 있다면 더해줌 carry = sum // 10 # 각 자릿수의 합 + 올림수가 두자리가 되면, 올림수 구해줌 sum = sum % 10 s.next = ListNode(sum) # 현재 가리키는 노드에 새로운 노드를 연결시켜준다 s = s.next return answer.next # 더미노드 이후의 노드부터 리턴해준다
import Button from '@mui/material/Button'; import { useCallback, useEffect, useState } from 'react'; import { useNavigate } from 'react-router-dom'; import Web3 from 'web3'; import contractAbi from '@shared/assets/bscContract.json'; import { useConfiguration } from '@shared/hooks/useConfiguration'; import { useNotifications } from '@shared/hooks/useNotifications'; import { invalidateOrders } from '@shared/redux/slices/ordersSlice'; import { getCurrentContract, getEthereum } from '@dashboard/components/PayWithAGS/utils'; import { useAppDispatch, useAppSelector } from '@dashboard/redux/hooks'; import { clearSubmissionState, getTotalInAGS, verifyOrderStatus } from '@dashboard/redux/slices/newSubmissionSlice'; // @ts-ignore const web3: any = new Web3(window?.ethereum); export function PayWithCollectorCoinButton() { const paymentMethodId = useAppSelector((state) => state.newSubmission.step04Data.paymentMethodId); const orderID = useAppSelector((state) => state.newSubmission.orderID); const [isLoading, setIsLoading] = useState(false); const configs = useConfiguration(); const dispatch = useAppDispatch(); const discountedValue = useAppSelector( (state) => state.newSubmission.couponState.appliedCouponData.discountedAmount, ); const isCouponApplied = useAppSelector((state) => state.newSubmission.couponState.isCouponApplied); const couponCode = useAppSelector((state) => state.newSubmission.couponState.couponCode); const originalPaymentPlanId = useAppSelector((state) => state.newSubmission?.step01Data?.originalServiceLevel.id); const isCouponValid = useAppSelector((state) => state.newSubmission?.couponState.isCouponValid); const wallets = { // Prod eth mainnet wallet ethWallet: configs?.web3EthWallet, // Prod binance smart chain wallet bscWallet: configs?.web3BscWallet, // Staging wallet testWallet: configs?.web3TestWallet, }; const notifications = useNotifications(); const navigate = useNavigate(); const supportedNetworks = configs?.web3SupportedNetworks?.split(',') ?? []; const appliedCredit = useAppSelector((state) => state.newSubmission.appliedCredit); function getRecipientWalletFromNetwork(networkID: number) { switch (networkID) { case 1: return wallets.ethWallet; case 4: return wallets.testWallet; case 56: return wallets.bscWallet; case 97: return wallets.testWallet; default: return wallets.ethWallet; } } async function initiateTransaction(totalInAGS: number) { setIsLoading(true); // @ts-ignore const currentChainId = await web3.eth.net.getId(); const currentAccounts = await getEthereum().request({ method: 'eth_requestAccounts' }); const contract = new web3.eth.Contract(contractAbi, getCurrentContract(currentChainId, supportedNetworks)); const balanceResult = await contract.methods.balanceOf(currentAccounts[0]).call(); const balance = await web3.utils.fromWei(balanceResult, 'ether'); if (balance <= totalInAGS) { notifications.error("You don't have enough AGS to finish the payment"); setIsLoading(false); return; } try { const tx = { from: currentAccounts[0], data: contract.methods .transfer(getRecipientWalletFromNetwork(currentChainId), web3.utils.toWei(String(totalInAGS))) .encodeABI(), to: getCurrentContract(currentChainId, supportedNetworks), }; web3.eth.sendTransaction(tx, async (err: any, txHash: string) => { if (err) { setIsLoading(false); return; } setIsLoading(true); setTimeout(async () => { try { await dispatch( verifyOrderStatus({ orderID, txHash: txHash, paymentByWallet: appliedCredit, paymentBlockchainNetwork: currentChainId, paymentMethod: { id: paymentMethodId, }, ...(couponCode && { coupon: couponCode, paymentPlan: originalPaymentPlanId, }), }), ).unwrap(); dispatch(clearSubmissionState()); dispatch(invalidateOrders()); setIsLoading(false); navigate(`/submissions/${orderID}/collector-coin/confirmation`); } catch (error: any) { setIsLoading(false); notifications.error('Order payment information is incorrect'); } }, 8000); }); } catch (error: any) { setIsLoading(false); } } const fetchTotalInAGS = useCallback(async () => { const currentChainId = await web3.eth.net.getId(); if (currentChainId) { return dispatch( getTotalInAGS({ orderID, chainID: currentChainId, paymentByWallet: appliedCredit, ...(couponCode && { coupon: couponCode, paymentPlan: originalPaymentPlanId, }), discountedAmount: isCouponApplied ? discountedValue : 0, }), ); } return dispatch( getTotalInAGS({ orderID, chainID: 1, paymentByWallet: appliedCredit, discountedAmount: isCouponApplied ? discountedValue : 0, }), ); }, [appliedCredit, discountedValue, dispatch, isCouponApplied, orderID, couponCode, originalPaymentPlanId]); const handleClick = () => { fetchTotalInAGS().then((result: any) => initiateTransaction(result.payload)); }; useEffect(() => { fetchTotalInAGS(); }, [dispatch, orderID, appliedCredit, discountedValue, isCouponApplied, fetchTotalInAGS]); return ( <Button variant={'contained'} disabled={isLoading || !isCouponValid} onClick={handleClick} sx={{ height: 48 }}> {isLoading ? 'Processing Payment...' : 'Pay With Collector Coin'} </Button> ); }
<?php namespace App\Http\Livewire\User; use App\Models\User; use Illuminate\Support\Facades\Hash; use Livewire\Component; use Illuminate\Support\Facades\Auth; class UserChangePasswordComponent extends Component { public $current_password; public $password; public $password_confirmation; public function updated($field){ $this->validateOnly($field,[ 'current_password' => 'required', 'password' => 'required|min:8|confirmed|different:current_password', ]); } public function changePassword(){ $this->validate([ 'current_password' => 'required', 'password' => 'required|min:8|confirmed|different:current_password', ]); if(Hash::check($this->current_password,Auth::user()->password)){ $user = User::findOrFail(Auth::user()->id); $user->password = Hash::make($this->password); $user->save(); session()->flash('message_success','Password has been updated successfuly!'); } else{ session()->flash('message_error','Password does not update!'); } } public function render() { return view('livewire.user.user-change-password-component')->layout('layouts.base'); } }
#include <stdlib.h> #include <string.h> #include "exception.h" #include "mark.h" #include "util.h" #include "gputil.h" #define NUM_POS_TESTS 4 #define NUM_NEG_TESTS 0 void GpFile_compareWaypt(GpFile *a, GpFile *b) { int exception; try { if ( a->nwaypts != b->nwaypts ) { LOG( "nwaypts %d did not match %d\n" , a->nwaypts, b->nwaypts ); FAIL_POS_TEST } for ( int i = 0; i < a->nwaypts; ++i ) { GpWaypt_equalsCheck( &a->waypt[i] , &b->waypt[i] ); } } catch ( exception ) { LOG( "%s\n", Exception_Names[exception] ); FAIL_POS_TEST } } void GpFile_compareTrkpt(GpFile *a, GpFile *b) { int exception; try { if ( a->ntrkpts != b->ntrkpts ) { LOG( "ntrkpts %d did not match %d\n" , a->ntrkpts, b->ntrkpts ); FAIL_POS_TEST } for ( int i = 0; i < a->ntrkpts; ++i ) { GpTrkpt_equalsCheck( &a->trkpt[i] , &b->trkpt[i] ); } } catch ( exception ) { LOG( "%s\n", Exception_Names[exception] ); FAIL_POS_TEST } } void GpFile_compareRoute(GpFile *a, GpFile *b) { int exception; try { if ( a->nroutes != b->nroutes ) { LOG( "nroutes %d did not match %d\n" , a->nroutes, b->nroutes ); FAIL_POS_TEST } for ( int i = 0; i < a->nroutes; ++i ) { GpRoute_equalsCheck( a->route[i] , b->route[i] ); } } catch ( exception ) { LOG( "%s\n", Exception_Names[exception] ); FAIL_POS_TEST } } void GpFile_compareHeader(GpFile *a, GpFile *b) { int exception; try { if ( strcmp( a->dateFormat, b->dateFormat ) != 0 ) { LOG( "dateFormat '%s' did not match '%s'\n" , a->dateFormat, b->dateFormat ); FAIL_POS_TEST } if ( a->timeZone != b->timeZone ) { LOG( "timeZone %d did not match %d\n" , a->timeZone, b->timeZone ); FAIL_POS_TEST } if ( a->unitHorz != b->unitHorz ) { LOG( "unitHorz %c did not match %c\n" , a->unitHorz, b->unitHorz ); FAIL_POS_TEST } if ( a->unitTime != b->unitTime ) { LOG( "unitTime %c did not match %c\n" , a->unitTime, b->unitTime ); FAIL_POS_TEST } } catch ( exception ) { LOG( "%s\n", Exception_Names[exception] ); FAIL_POS_TEST } } int s2( int suite, int weight, int argc, char *argv[] ) { int exception; START_SUITE( suite, "writeGpFile", weight, NUM_POS_TESTS, NUM_NEG_TESTS ); START_POS_TEST( 1, "Write a Gpfile -- Header information valid" ); GpFile orig_gpf; UTIL_LOAD_GOLD_FILE( "a2-suite2-postest1.gps", orig_gpf, FAIL_POS_TEST ); FILE * ofp = fopen( "a2-suite2-postest1out.gps", "w+" ); if ( ofp == NULL ) { LOG( "open output file failed\n" ); abort(); } try { int ret = writeGpFile( ofp, &orig_gpf ); //They should not have closed the file rewind( ofp ); fseek( ofp, 0, SEEK_END ); if ( ret == 0 ) { LOG( "writeGpFile failed\n" ); FAIL_POS_TEST } GpFile after_gpf; UTIL_LOAD_GOLD_FILE( "a2-suite2-postest1out.gps", after_gpf, FAIL_POS_TEST ); GpFile_compareHeader( &orig_gpf , &after_gpf ); } catch ( exception ) { LOG( "%s\n", Exception_Names[exception] ); FAIL_POS_TEST } PASS_POS_TEST START_POS_TEST( 2, "Write a GpFile -- Waypt information valid" ); GpFile orig_gpf2; UTIL_LOAD_GOLD_FILE( "a2-suite2-postest1.gps", orig_gpf2, FAIL_POS_TEST ); FILE * ofp2 = fopen( "a2-suite2-postest1out.gps", "w+" ); if ( ofp2 == NULL ) { LOG( "open output file failed\n" ); abort(); } try { int ret2 = writeGpFile( ofp2, &orig_gpf2 ); //They should not have closed the file rewind( ofp2 ); fseek( ofp2, 0, SEEK_END ); if ( ret2 == 0 ) { LOG( "writeGpFile failed\n" ); FAIL_POS_TEST } GpFile after_gpf2; UTIL_LOAD_GOLD_FILE( "a2-suite2-postest1out.gps", after_gpf2, FAIL_POS_TEST ); GpFile_compareWaypt( &orig_gpf2 , &after_gpf2 ); } catch ( exception ) { LOG( "%s\n", Exception_Names[exception] ); FAIL_POS_TEST } PASS_POS_TEST START_POS_TEST( 3, "Write a GpFile -- route information valid" ); GpFile orig_gpf3; UTIL_LOAD_GOLD_FILE( "a2-suite2-postest1.gps", orig_gpf3, FAIL_POS_TEST ); FILE * ofp3 = fopen( "a2-suite2-postest1out.gps", "w+" ); if ( ofp3 == NULL ) { LOG( "open output file failed\n" ); abort(); } try { int ret3 = writeGpFile( ofp3, &orig_gpf3 ); //They should not have closed the file rewind( ofp3 ); fseek( ofp3, 0, SEEK_END ); if ( ret3 == 0 ) { LOG( "writeGpFile failed\n" ); FAIL_POS_TEST } GpFile after_gpf3; UTIL_LOAD_GOLD_FILE( "a2-suite2-postest1out.gps", after_gpf3, FAIL_POS_TEST ); GpFile_compareRoute( &orig_gpf3 , &after_gpf3 ); } catch ( exception ) { LOG( "%s\n", Exception_Names[exception] ); FAIL_POS_TEST } PASS_POS_TEST START_POS_TEST( 4, "Write a GpFile -- trackpoint information valid" ); GpFile orig_gpf4; UTIL_LOAD_GOLD_FILE( "a2-suite2-postest1.gps", orig_gpf4, FAIL_POS_TEST ); FILE * ofp4 = fopen( "a2-suite2-postest1out.gps", "w+" ); if ( ofp4 == NULL ) { LOG( "open output file failed\n" ); abort(); } try { int ret4 = writeGpFile( ofp4, &orig_gpf4 ); //They should not have closed the file rewind( ofp4 ); fseek( ofp4, 0, SEEK_END ); if ( ret4 == 0 ) { LOG( "writeGpFile failed\n" ); FAIL_POS_TEST } GpFile after_gpf4; UTIL_LOAD_GOLD_FILE( "a2-suite2-postest1out.gps", after_gpf4, FAIL_POS_TEST ); GpFile_compareTrkpt( &orig_gpf4 , &after_gpf4 ); } catch ( exception ) { LOG( "%s\n", Exception_Names[exception] ); FAIL_POS_TEST } PASS_POS_TEST END_SUITE }
// Copyright 2022-2023 Sophos Limited. All rights reserved. /* * This test binary runs against the test server HttpTestServer during TAP test. * The tests can also be run locally by running HttpTestServer.py (right click run), and then running the tests here * as normal. * The first lot of tests are parameterised into HTTP and HTTPS tests so that the same tests did not need to be * duplicated for both HTTP and HTTPS. The test server runs both an HTTP and HTTPS server. */ #include "Common/CurlWrapper/CurlWrapper.h" #include "Common/FileSystem/IFileSystem.h" #include "Common/HttpRequestsImpl/HttpRequesterImpl.h" #include "tests/Common/Helpers/LogInitializedTests.h" #include <gtest/gtest.h> namespace { struct HttpTestParam { std::string url; std::string urlAndPort; int port = 0; std::string certToUse; std::string proxyToUse; std::string proxyUsernameToUse; std::string proxyPasswordToUse; }; // Test helper function to make creating the different requests for each parameterised run easier Common::HttpRequests::RequestConfig getTestRequest(const HttpTestParam& testParams) { Common::HttpRequests::RequestConfig request = { .url = testParams.url }; if (!testParams.certToUse.empty()) { request.certPath = testParams.certToUse; } if (!testParams.proxyToUse.empty()) { request.proxy = testParams.proxyToUse; } if (!testParams.proxyUsernameToUse.empty()) { request.proxyUsername = testParams.proxyUsernameToUse; } if (!testParams.proxyPasswordToUse.empty()) { request.proxyPassword = testParams.proxyPasswordToUse; } return request; } // Helper function to allow us to use the certs both in TAP and when run locally std::string getCertLocation() { static std::string certPath; if (certPath.empty()) { std::string certName = "localhost-selfsigned.crt"; std::string srcDirCertPath = Common::FileSystem::join(Common::FileSystem::dirName(std::string(__FILE__)), certName); if (Common::FileSystem::fileSystem()->isFile(srcDirCertPath)) { certPath = srcDirCertPath; } else { std::optional<std::string> exe = Common::FileSystem::fileSystem()->readlink("/proc/self/exe"); std::string exeDirCertPath = Common::FileSystem::join(Common::FileSystem::dirName(exe.value()), certName); if (Common::FileSystem::fileSystem()->isFile(exeDirCertPath)) { certPath = exeDirCertPath; } else { std::stringstream ss; ss << "Live network tests cannot find the test cert here: " << srcDirCertPath << ", or here: " << exeDirCertPath; throw std::runtime_error(ss.str()); } } } return certPath; } } // namespace class HttpRequesterLiveNetworkTestsParam : public ::testing::TestWithParam<HttpTestParam> { Common::Logging::ConsoleLoggingSetup m_loggingSetup; public: std::vector<std::string> m_filesToRemove; protected: virtual void SetUp() { // Give the server a chance to keep up usleep(200000); } virtual void TearDown() { auto fs = Common::FileSystem::fileSystem(); for (const auto& file : m_filesToRemove) { std::cout << "Cleaning up test file: " << file << std::endl; try { fs->removeFile(file); } catch (const std::exception& ex) { // don't care } } } }; INSTANTIATE_TEST_SUITE_P( LiveNetworkTestRuns, HttpRequesterLiveNetworkTestsParam, ::testing::Values( HttpTestParam{ .url = "http://localhost", .urlAndPort = "http://localhost:7780", .port = 7780 }, HttpTestParam{ .url = "https://localhost", .urlAndPort = "https://localhost:7743", .port = 7743, .certToUse = getCertLocation() }, HttpTestParam{ .url = "http://localhost", .urlAndPort = "http://localhost:7780", .port = 7780, .proxyToUse = "localhost:7750" }, HttpTestParam{ .url = "http://localhost", .urlAndPort = "http://localhost:7780", .port = 7780, .proxyToUse = "localhost:7751", .proxyUsernameToUse="user", .proxyPasswordToUse="password"} ) ); TEST_P(HttpRequesterLiveNetworkTestsParam, getWithPort) { std::shared_ptr<Common::CurlWrapper::ICurlWrapper> curlWrapper = std::make_shared<Common::CurlWrapper::CurlWrapper>(); Common::HttpRequestsImpl::HttpRequesterImpl client = Common::HttpRequestsImpl::HttpRequesterImpl(curlWrapper); HttpTestParam param = GetParam(); Common::HttpRequests::RequestConfig request = getTestRequest(param); std::string testUrlResource = "getWithPort"; request.url = param.urlAndPort + "/" + testUrlResource;; Common::HttpRequests::Response response = client.get(request); ASSERT_EQ(response.status, 200); std::string expected_response = "/" + testUrlResource + " response body"; ASSERT_EQ(response.body, expected_response); ASSERT_EQ(response.headers.count("test_header"), 1); ASSERT_EQ(response.headers.at("test_header"), "test_header_value"); } TEST_P(HttpRequesterLiveNetworkTestsParam, getWithPortAndHeaders) { HttpTestParam param = GetParam(); Common::HttpRequests::RequestConfig request = getTestRequest(param); std::string testUrlResource = "getWithPortAndHeaders"; std::shared_ptr<Common::CurlWrapper::ICurlWrapper> curlWrapper = std::make_shared<Common::CurlWrapper::CurlWrapper>(); Common::HttpRequestsImpl::HttpRequesterImpl client = Common::HttpRequestsImpl::HttpRequesterImpl(curlWrapper); request.url = param.urlAndPort + "/" + testUrlResource; request.headers = Common::HttpRequests::Headers{ { "req_header", "a value" } }; Common::HttpRequests::Response response = client.get(request); ASSERT_EQ(response.status, 200); std::string expected_response = "/" + testUrlResource + " response body"; ASSERT_EQ(response.body, expected_response); } TEST_P(HttpRequesterLiveNetworkTestsParam, getWithPortAndParameters) { HttpTestParam param = GetParam(); Common::HttpRequests::RequestConfig request = getTestRequest(param); std::string testUrlResource = "getWithPortAndParameters"; std::shared_ptr<Common::CurlWrapper::ICurlWrapper> curlWrapper = std::make_shared<Common::CurlWrapper::CurlWrapper>(); Common::HttpRequestsImpl::HttpRequesterImpl client = Common::HttpRequestsImpl::HttpRequesterImpl(curlWrapper); request.url = param.urlAndPort + "/" + testUrlResource; request.parameters = Common::HttpRequests::Parameters{ { "param1", "value1" } }; Common::HttpRequests::Response response = client.get(request); ASSERT_EQ(response.status, 200); std::string expected_response = "/" + testUrlResource + " response body"; ASSERT_EQ(response.body, expected_response); } TEST_P(HttpRequesterLiveNetworkTestsParam, getWithFileDownloadAndExplicitFileName) { HttpTestParam param = GetParam(); Common::HttpRequests::RequestConfig request = getTestRequest(param); std::string testUrlResource = "getWithFileDownloadAndExplicitFileName"; std::shared_ptr<Common::CurlWrapper::ICurlWrapper> curlWrapper = std::make_shared<Common::CurlWrapper::CurlWrapper>(); Common::HttpRequestsImpl::HttpRequesterImpl client = Common::HttpRequestsImpl::HttpRequesterImpl(curlWrapper); std::string fileDownloadLocation = "/tmp/" + testUrlResource + ".txt"; m_filesToRemove.push_back(fileDownloadLocation); std::string fileExpectedContent = "Sample text file to use in HTTP tests."; request.url = param.urlAndPort + "/" + testUrlResource; request.fileDownloadLocation = fileDownloadLocation; Common::HttpRequests::Response response = client.get(request); auto fs = Common::FileSystem::fileSystem(); ASSERT_TRUE(fs->exists(fileDownloadLocation)); ASSERT_EQ(fs->readFile(fileDownloadLocation), fileExpectedContent); ASSERT_EQ(response.status, 200); // Downloaded to file so body will be empty ASSERT_EQ(response.body, ""); } TEST_P(HttpRequesterLiveNetworkTestsParam, getWithFileDownloadToDirectory) { HttpTestParam param = GetParam(); Common::HttpRequests::RequestConfig request = getTestRequest(param); std::string testUrlResource = "getWithFileDownloadToDirectory"; std::shared_ptr<Common::CurlWrapper::ICurlWrapper> curlWrapper = std::make_shared<Common::CurlWrapper::CurlWrapper>(); Common::HttpRequestsImpl::HttpRequesterImpl client = Common::HttpRequestsImpl::HttpRequesterImpl(curlWrapper); std::string fileDownloadLocationDir = "/tmp"; std::string fileDownloadLocationFullPath = fileDownloadLocationDir + "/sample.txt"; m_filesToRemove.push_back(fileDownloadLocationFullPath); std::string fileExpectedContent = "Sample text file to use in HTTP tests."; request.url = param.urlAndPort + "/" + testUrlResource + "/sample.txt"; request.fileDownloadLocation = fileDownloadLocationDir; Common::HttpRequests::Response response = client.get(request); auto fs = Common::FileSystem::fileSystem(); ASSERT_TRUE(fs->exists(fileDownloadLocationFullPath)); ASSERT_EQ(fs->readFile(fileDownloadLocationFullPath), fileExpectedContent); ASSERT_EQ(response.status, 200); // Downloaded to file, body will be empty ASSERT_EQ(response.body, ""); } TEST_P(HttpRequesterLiveNetworkTestsParam, getWithFileDownloadToDirectoryAndContentDispositionHeader) { HttpTestParam param = GetParam(); Common::HttpRequests::RequestConfig request = getTestRequest(param); std::string testUrlResource = "getWithFileDownloadToDirectoryAndContentDispositionHeader"; std::shared_ptr<Common::CurlWrapper::ICurlWrapper> curlWrapper = std::make_shared<Common::CurlWrapper::CurlWrapper>(); Common::HttpRequestsImpl::HttpRequesterImpl client = Common::HttpRequestsImpl::HttpRequesterImpl(curlWrapper); std::string fileDownloadLocationDir = "/tmp"; std::string fileDownloadLocationFullPath = fileDownloadLocationDir + "/differentName.txt"; m_filesToRemove.push_back(fileDownloadLocationFullPath); std::string fileExpectedContent = "Sample text file to use in HTTP tests."; request.url = param.urlAndPort + "/" + testUrlResource + "/sample.txt"; request.fileDownloadLocation = fileDownloadLocationDir; Common::HttpRequests::Response response = client.get(request); auto fs = Common::FileSystem::fileSystem(); ASSERT_TRUE(fs->exists(fileDownloadLocationFullPath)); ASSERT_EQ(fs->readFile(fileDownloadLocationFullPath), fileExpectedContent); ASSERT_EQ(response.status, 200); // Downloaded to file so body will be empty ASSERT_EQ(response.body, ""); } TEST_P(HttpRequesterLiveNetworkTestsParam, getWithPortAndTimeout) { HttpTestParam param = GetParam(); Common::HttpRequests::RequestConfig request = getTestRequest(param); std::string testUrlResource = "getWithPortAndTimeout"; std::shared_ptr<Common::CurlWrapper::ICurlWrapper> curlWrapper = std::make_shared<Common::CurlWrapper::CurlWrapper>(); Common::HttpRequestsImpl::HttpRequesterImpl client = Common::HttpRequestsImpl::HttpRequesterImpl(curlWrapper); request.url = param.urlAndPort + "/" + testUrlResource; request.timeout = 3; Common::HttpRequests::Response response = client.get(request); ASSERT_EQ(response.status, Common::HttpRequests::HTTP_STATUS_NOT_SET); ASSERT_EQ(response.body, ""); ASSERT_EQ(response.errorCode, Common::HttpRequests::ResponseErrorCode::TIMEOUT); ASSERT_EQ(response.error, "Timeout was reached"); } // Due to changes in Curl 7.87.0, rate limiting is more about the long-term average, so short bursts can go over the // set limit. // So to be able to test it we would need to send more data, at least 1-10MB. // This will fill up the Robot logs and requires adapting the test server to use HTTP/1.1 (> frame of data over proxy). // Since we don't use bandwidth limiting in any code, I decided to disable this test. TEST_P(HttpRequesterLiveNetworkTestsParam, DISABLED_getWithPortAndBandwidthLimit) { HttpTestParam param = GetParam(); Common::HttpRequests::RequestConfig request = getTestRequest(param); std::string testUrlResource = "getWithPortAndBandwidthLimit"; std::shared_ptr<Common::CurlWrapper::ICurlWrapper> curlWrapper = std::make_shared<Common::CurlWrapper::CurlWrapper>(); Common::HttpRequestsImpl::HttpRequesterImpl client = Common::HttpRequestsImpl::HttpRequesterImpl(curlWrapper); request.url = param.urlAndPort + "/" + testUrlResource; request.bandwidthLimit = 100; auto start = std::chrono::high_resolution_clock::now(); // Download a 1000B file at ~100B/s per second Common::HttpRequests::Response response = client.get(request); auto stop = std::chrono::high_resolution_clock::now(); auto duration = std::chrono::duration_cast<std::chrono::seconds>(stop - start); // Bandwidth limiting is not perfect so even though in theory this should take 20 seconds, // if it took more than a few seconds (compared to 10 milliseconds that it normally takes) then // it's close enough and we don't want this to be a flaky test ASSERT_GE(duration.count(), 3); ASSERT_EQ(response.status, 200); std::string expected_response = std::string(1000, 'a'); ASSERT_EQ(response.body, expected_response); } // PUT Tests TEST_P(HttpRequesterLiveNetworkTestsParam, putWithPort) { HttpTestParam param = GetParam(); Common::HttpRequests::RequestConfig request = getTestRequest(param); std::string testUrlResource = "putWithPort"; std::shared_ptr<Common::CurlWrapper::ICurlWrapper> curlWrapper = std::make_shared<Common::CurlWrapper::CurlWrapper>(); Common::HttpRequestsImpl::HttpRequesterImpl client = Common::HttpRequestsImpl::HttpRequesterImpl(curlWrapper); request.url = param.urlAndPort + "/" + testUrlResource; Common::HttpRequests::Response response = client.put(request); ASSERT_EQ(response.status, 200); std::string expected_response = "/" + testUrlResource + " response body"; ASSERT_EQ(response.body, expected_response); ASSERT_EQ(response.headers.count("test_header"), 1); ASSERT_EQ(response.headers.at("test_header"), "test_header_value"); } TEST_P(HttpRequesterLiveNetworkTestsParam, putWithFileUpload) { HttpTestParam param = GetParam(); Common::HttpRequests::RequestConfig request = getTestRequest(param); std::string testUrlResource = "putWithFileUpload"; m_filesToRemove.emplace_back("/tmp/testPutFile"); std::ignore = system("bash -c 'echo test > /tmp/testPutFile'"); std::shared_ptr<Common::CurlWrapper::ICurlWrapper> curlWrapper = std::make_shared<Common::CurlWrapper::CurlWrapper>(); Common::HttpRequestsImpl::HttpRequesterImpl client = Common::HttpRequestsImpl::HttpRequesterImpl(curlWrapper); request.url = param.urlAndPort + "/" + testUrlResource; // "test" is 4 bytes. request.headers = Common::HttpRequests::Headers{ { "Content-Length", "4" } }; request.fileToUpload = "/tmp/testPutFile"; Common::HttpRequests::Response response = client.put(request); ASSERT_EQ(response.status, 200); std::string expected_response = "/" + testUrlResource + " response body, you PUT 4 bytes"; ASSERT_EQ(response.body, expected_response); ASSERT_EQ(response.headers.count("test_header"), 1); ASSERT_EQ(response.headers.at("test_header"), "test_header_value"); } // POST Tests TEST_P(HttpRequesterLiveNetworkTestsParam, postWithPort) { HttpTestParam param = GetParam(); Common::HttpRequests::RequestConfig request = getTestRequest(param); std::string testUrlResource = "postWithPort"; std::shared_ptr<Common::CurlWrapper::ICurlWrapper> curlWrapper = std::make_shared<Common::CurlWrapper::CurlWrapper>(); Common::HttpRequestsImpl::HttpRequesterImpl client = Common::HttpRequestsImpl::HttpRequesterImpl(curlWrapper); request.url = param.urlAndPort + "/" + testUrlResource; Common::HttpRequests::Response response = client.post(request); ASSERT_EQ(response.status, 200); std::string expected_response = "/" + testUrlResource + " response body"; ASSERT_EQ(response.body, expected_response); } TEST_P(HttpRequesterLiveNetworkTestsParam, postWithData) { HttpTestParam param = GetParam(); Common::HttpRequests::RequestConfig request = getTestRequest(param); std::string testUrlResource = "postWithData"; std::shared_ptr<Common::CurlWrapper::ICurlWrapper> curlWrapper = std::make_shared<Common::CurlWrapper::CurlWrapper>(); Common::HttpRequestsImpl::HttpRequesterImpl client = Common::HttpRequestsImpl::HttpRequesterImpl(curlWrapper); request.url = param.urlAndPort + "/" + testUrlResource; request.data = "SamplePostData"; Common::HttpRequests::Response response = client.post(request); ASSERT_EQ(response.status, 200); std::string expected_response = "/" + testUrlResource + " response body"; ASSERT_EQ(response.body, expected_response); } // DELETE tests TEST_P(HttpRequesterLiveNetworkTestsParam, deleteWithPort) { std::shared_ptr<Common::CurlWrapper::ICurlWrapper> curlWrapper = std::make_shared<Common::CurlWrapper::CurlWrapper>(); Common::HttpRequestsImpl::HttpRequesterImpl client = Common::HttpRequestsImpl::HttpRequesterImpl(curlWrapper); HttpTestParam param = GetParam(); Common::HttpRequests::RequestConfig request = getTestRequest(param); std::string testUrlResource = "deleteWithPort"; request.url = param.urlAndPort + "/" + testUrlResource;; Common::HttpRequests::Response response = client.del(request); ASSERT_EQ(response.status, 200); std::string expected_response = "/" + testUrlResource + " response body"; ASSERT_EQ(response.body, expected_response); ASSERT_EQ(response.headers.count("test_header"), 1); ASSERT_EQ(response.headers.at("test_header"), "test_header_value"); } // OPTIONS tests TEST_P(HttpRequesterLiveNetworkTestsParam, optionsWithPort) { std::shared_ptr<Common::CurlWrapper::ICurlWrapper> curlWrapper = std::make_shared<Common::CurlWrapper::CurlWrapper>(); Common::HttpRequestsImpl::HttpRequesterImpl client = Common::HttpRequestsImpl::HttpRequesterImpl(curlWrapper); HttpTestParam param = GetParam(); Common::HttpRequests::RequestConfig request = getTestRequest(param); std::string testUrlResource = "optionsWithPort"; request.url = param.urlAndPort + "/" + testUrlResource;; Common::HttpRequests::Response response = client.options(request); ASSERT_EQ(response.status, 200); std::string expected_response = "/" + testUrlResource + " response body"; ASSERT_EQ(response.body, expected_response); ASSERT_EQ(response.headers.count("test_header"), 1); ASSERT_EQ(response.headers.at("test_header"), "test_header_value"); } // Some live network tests that do not need to be parameterised into HTTP/HTTPS tests. class HttpRequesterLiveNetworkTests : public LogInitializedTests { }; const int HTTP_PORT = 7780; const std::string HTTP_URL_WITH_PORT = "http://localhost:" + std::to_string(HTTP_PORT); const int HTTPS_PORT = 7743; const std::string HTTPS_URL_WITH_PORT = "https://localhost:" + std::to_string(HTTPS_PORT); TEST_F(HttpRequesterLiveNetworkTests, httpsFailsWithMissingCert) { std::string testName = ::testing::UnitTest::GetInstance()->current_test_info()->name(); std::shared_ptr<Common::CurlWrapper::ICurlWrapper> curlWrapper = std::make_shared<Common::CurlWrapper::CurlWrapper>(); Common::HttpRequestsImpl::HttpRequesterImpl client = Common::HttpRequestsImpl::HttpRequesterImpl(curlWrapper); std::string url = HTTPS_URL_WITH_PORT + "/" + testName; Common::HttpRequests::Response response = client.get(Common::HttpRequests::RequestConfig{ .url = url, .certPath = "/missing/file.crt" }); ASSERT_EQ(response.status, Common::HttpRequests::HTTP_STATUS_NOT_SET); ASSERT_EQ(response.body, ""); ASSERT_EQ(response.errorCode, Common::HttpRequests::ResponseErrorCode::CERTIFICATE_ERROR); } TEST_F(HttpRequesterLiveNetworkTests, httpFailsWith404) { std::string testName = ::testing::UnitTest::GetInstance()->current_test_info()->name(); std::shared_ptr<Common::CurlWrapper::ICurlWrapper> curlWrapper = std::make_shared<Common::CurlWrapper::CurlWrapper>(); Common::HttpRequestsImpl::HttpRequesterImpl client = Common::HttpRequestsImpl::HttpRequesterImpl(curlWrapper); std::string url = HTTP_URL_WITH_PORT + "/somethingthatdoesnotexist"; Common::HttpRequests::Response response = client.get(Common::HttpRequests::RequestConfig{ .url = url }); ASSERT_EQ(response.status, 404); ASSERT_EQ(response.body, "Not a valid test case!"); ASSERT_EQ(response.errorCode, Common::HttpRequests::ResponseErrorCode::OK); }